Skip to content

Commit

Permalink
Merge branch 'main' into issue-391
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi authored Jan 19, 2024
2 parents 81c15c4 + 2614470 commit f849c04
Show file tree
Hide file tree
Showing 18 changed files with 189 additions and 201 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ npx wrangler dev # or deploy

```
npm run build -- --with-deno
DENO_DEPLOY_TOKEN=... deployctl deploy --project=... --prod serve.ts --exclude node_modules
DENO_DEPLOY_TOKEN=... deployctl deploy --project=... --prod dist/serve.js --exclude node_modules
```

## Community
Expand Down
2 changes: 1 addition & 1 deletion examples/08_cookies/dev.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express from 'express';
import cookieParser from 'cookie-parser';
import { connectMiddleware } from 'waku/dev';
import { unstable_connectMiddleware as connectMiddleware } from 'waku/dev';

const withSsr = process.argv[2] === '--with-ssr';

Expand Down
7 changes: 3 additions & 4 deletions examples/08_cookies/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import express from 'express';
import cookieParser from 'cookie-parser';
import { connectMiddleware } from 'waku/prd';
import { unstable_connectMiddleware as connectMiddleware } from 'waku/prd';

const withSsr = process.argv[2] === '--with-ssr';

Expand All @@ -12,9 +12,8 @@ const app = express();
app.use(cookieParser());
app.use(
connectMiddleware({
entries: import(
pathToFileURL(path.join(root, 'dist', 'entries.js')).toString()
),
loadEntries: () =>
import(pathToFileURL(path.join(root, 'dist', 'entries.js')).toString()),
unstable_prehook: (req) => {
return { count: Number(req.orig.cookies.count) || 0 };
},
Expand Down
28 changes: 16 additions & 12 deletions packages/waku/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,26 +97,30 @@ async function runBuild(options: { ssr: boolean }) {
...options,
config,
env: process.env as any,
vercel:
values['with-vercel'] ?? !!process.env.VERCEL
? {
type: values['with-vercel-static'] ? 'static' : 'serverless',
}
: undefined,
cloudflare: !!values['with-cloudflare'],
deno: !!values['with-deno'],
deploy:
(values['with-vercel'] ?? !!process.env.VERCEL
? values['with-vercel-static']
? 'vercel-static'
: 'vercel-serverless'
: undefined) ||
(values['with-cloudflare'] ? 'cloudflare' : undefined) ||
(values['with-deno'] ? 'deno' : undefined),
});
}

async function runStart(options: { ssr: boolean }) {
const { distDir, publicDir, entriesJs } = await resolveConfig(config);
const entries = import(
pathToFileURL(path.resolve(distDir, entriesJs)).toString()
);
const loadEntries = () =>
import(pathToFileURL(path.resolve(distDir, entriesJs)).toString());
const app = new Hono();
app.use(
'*',
honoPrdMiddleware({ ...options, config, entries, env: process.env as any }),
honoPrdMiddleware({
...options,
config,
loadEntries,
env: process.env as any,
}),
);
app.use('*', serveStatic({ root: path.join(distDir, publicDir) }));
const port = parseInt(process.env.PORT || '8080', 10);
Expand Down
6 changes: 6 additions & 0 deletions packages/waku/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ export interface Config {
* Defaults to "entries.js".
*/
entriesJs?: string;
/**
* The serve.js file relative distDir.
* This file is used for deployment.
* Defaults to "serve.js".
*/
serveJs?: string;
/**
* Prefix for HTTP requests to indicate RSC requests.
* Defaults to "RSC".
Expand Down
4 changes: 2 additions & 2 deletions packages/waku/src/dev.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { honoMiddleware } from './lib/middleware/hono-dev.js';
export { connectMiddleware } from './lib/middleware/connect-dev.js';
export { honoMiddleware as unstable_honoMiddleware } from './lib/middleware/hono-dev.js';
export { connectMiddleware as unstable_connectMiddleware } from './lib/middleware/connect-dev.js';

export { createHandler as unstable_createHandler } from './lib/handlers/handler-dev.js';
export { build } from './lib/builder/build.js';
57 changes: 33 additions & 24 deletions packages/waku/src/lib/builder/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,10 @@ import { rscIndexPlugin } from '../plugins/vite-plugin-rsc-index.js';
import { rscAnalyzePlugin } from '../plugins/vite-plugin-rsc-analyze.js';
import { nonjsResolvePlugin } from '../plugins/vite-plugin-nonjs-resolve.js';
import { rscTransformPlugin } from '../plugins/vite-plugin-rsc-transform.js';
import { rscEntriesPlugin } from '../plugins/vite-plugin-rsc-entries.js';
import { rscServePlugin } from '../plugins/vite-plugin-rsc-serve.js';
import { rscEnvPlugin } from '../plugins/vite-plugin-rsc-env.js';
import { emitVercelOutput } from './output-vercel.js';
import { emitCloudflareOutput } from './output-cloudflare.js';
import { emitDenoOutput } from './output-deno.js';

// TODO this file and functions in it are too long. will fix.

Expand Down Expand Up @@ -139,8 +138,8 @@ const buildServerBundle = async (
commonEntryFiles: Record<string, string>,
clientEntryFiles: Record<string, string>,
serverEntryFiles: Record<string, string>,
reExportHonoMiddleware: boolean,
reExportConnectMiddleware: boolean,
ssr: boolean,
serve: 'vercel' | 'cloudflare' | 'deno' | false,
) => {
const serverBuildOutput = await buildVite({
plugins: [
Expand All @@ -157,18 +156,29 @@ const buildServerBundle = async (
},
serverEntryFiles,
}),
rscEntriesPlugin({
entriesFile,
reExportHonoMiddleware,
reExportConnectMiddleware,
}),
rscEnvPlugin({ config }),
...(serve
? [
rscServePlugin({
...config,
entriesFile,
srcServeFile: decodeFilePathFromAbsolute(
joinPath(
fileURLToFilePath(import.meta.url),
`../serve-${serve}.js`,
),
),
ssr,
}),
]
: []),
],
ssr: {
resolve: {
conditions: ['react-server', 'workerd'],
externalConditions: ['react-server', 'workerd'],
},
external: ['hono', 'hono/cloudflare-workers'],
noExternal: /^(?!node:)/,
},
define: {
Expand Down Expand Up @@ -506,9 +516,12 @@ export async function build(options: {
config?: Config;
ssr?: boolean;
env?: Record<string, string>;
vercel?: { type: 'static' | 'serverless' } | undefined;
cloudflare?: boolean;
deno?: boolean;
deploy?:
| 'vercel-static'
| 'vercel-serverless'
| 'cloudflare'
| 'deno'
| undefined;
}) {
(globalThis as any).__WAKU_PRIVATE_ENV__ = options.env || {};
const config = await resolveConfig(options.config || {});
Expand All @@ -532,8 +545,10 @@ export async function build(options: {
commonEntryFiles,
clientEntryFiles,
serverEntryFiles,
!!options.cloudflare || !!options.deno,
!!options.vercel,
!!options.ssr,
(options.deploy === 'vercel-serverless' ? 'vercel' : false) ||
(options.deploy === 'cloudflare' ? 'cloudflare' : false) ||
(options.deploy === 'deno' ? 'deno' : false),
);
await buildClientBundle(
rootDir,
Expand All @@ -558,22 +573,16 @@ export async function build(options: {
!!options.ssr,
);

if (options.vercel) {
if (options.deploy?.startsWith('vercel-')) {
await emitVercelOutput(
rootDir,
config,
rscFiles,
htmlFiles,
!!options.ssr,
options.vercel.type,
options.deploy.slice('vercel-'.length) as 'static' | 'serverless',
);
}

if (options.cloudflare) {
await emitCloudflareOutput(rootDir, config, !!options.ssr);
}

if (options.deno) {
await emitDenoOutput(rootDir, config, !!options.ssr);
} else if (options.deploy === 'cloudflare') {
await emitCloudflareOutput(rootDir, config);
}
}
46 changes: 4 additions & 42 deletions packages/waku/src/lib/builder/output-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,55 +7,17 @@ import type { ResolvedConfig } from '../config.js';
export const emitCloudflareOutput = async (
rootDir: string,
config: ResolvedConfig,
ssr: boolean,
) => {
const outputDir = path.resolve('.');
const relativeRootDir = path.relative(outputDir, rootDir);
const entriesFile = path.join(
relativeRootDir,
config.distDir,
config.entriesJs,
);
const publicDir = path.join(
relativeRootDir,
config.distDir,
config.publicDir,
);
if (!existsSync(path.join(outputDir, 'serve.js'))) {
if (!existsSync(path.join(rootDir, 'wrangler.toml'))) {
writeFileSync(
path.join(outputDir, 'serve.js'),
`
import { Hono } from 'hono';
import { serveStatic } from 'hono/cloudflare-workers';
const entries = import('./${entriesFile}');
const { honoMiddleware } = await entries;
let serveWaku;
const app = new Hono();
app.use('*', (c, next) => serveWaku(c, next));
app.use('*', serveStatic({ root: './' }));
export default {
async fetch(request, env, ctx) {
if (!serveWaku) {
serveWaku = honoMiddleware({ entries, ssr: ${ssr}, env });
}
return app.fetch(request, env, ctx);
}
}
`,
);
}
if (!existsSync(path.join(outputDir, 'wrangler.toml'))) {
writeFileSync(
path.join(outputDir, 'wrangler.toml'),
path.join(rootDir, 'wrangler.toml'),
`
name = "waku-project"
main = "serve.js"
main = "${config.distDir}/${config.serveJs}"
compatibility_date = "2023-12-06"
[site]
bucket = "./${publicDir}"
bucket = "./${config.distDir}/${config.publicDir}"
`,
);
}
Expand Down
43 changes: 0 additions & 43 deletions packages/waku/src/lib/builder/output-deno.ts

This file was deleted.

42 changes: 2 additions & 40 deletions packages/waku/src/lib/builder/output-vercel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@ export const emitVercelOutput = async (
) => {
const publicDir = path.join(rootDir, config.distDir, config.publicDir);
const outputDir = path.resolve('.vercel', 'output');
cpSync(
path.join(rootDir, config.distDir, config.publicDir),
path.join(outputDir, 'static'),
{ recursive: true },
);
cpSync(publicDir, path.join(outputDir, 'static'), { recursive: true });

if (type === 'serverless') {
// for serverless function
Expand All @@ -37,7 +33,7 @@ export const emitVercelOutput = async (
);
const vcConfigJson = {
runtime: 'nodejs18.x',
handler: 'serve.js',
handler: `${config.distDir}/${config.serveJs}`,
launcherType: 'Nodejs',
};
writeFileSync(
Expand All @@ -48,40 +44,6 @@ export const emitVercelOutput = async (
path.join(serverlessDir, 'package.json'),
JSON.stringify({ type: 'module' }, null, 2),
);
writeFileSync(
path.join(serverlessDir, 'serve.js'),
`
import path from 'node:path';
import fs from 'node:fs';
const entries = import(path.resolve('${config.distDir}', '${config.entriesJs}'));
const { connectMiddleware } = await entries;
const env = process.env;
export default function handler(req, res) {
connectMiddleware({ entries, ssr: ${ssr}, env })(req, res, () => {
const { pathname } = new URL(req.url, 'http://localhost');
const fname = path.join(
'${config.distDir}',
'${config.publicDir}',
pathname,
path.extname(pathname) ? '' : '${config.indexHtml}',
);
if (fs.existsSync(fname)) {
if (fname.endsWith('.html')) {
res.setHeader('content-type', 'text/html; charset=utf-8');
} else if (fname.endsWith('.txt')) {
res.setHeader('content-type', 'text/plain');
}
fs.createReadStream(fname).pipe(res);
return;
}
res.statusCode = 404;
res.end();
});
}
`,
);
}

const overrides = Object.fromEntries(
Expand Down
Loading

0 comments on commit f849c04

Please sign in to comment.