Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid exposing configs that are not configurable #682

Merged
merged 17 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions packages/waku/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import * as dotenv from 'dotenv';

import type { Config } from './config.js';
import { runner } from './lib/hono/runner.js';
import { build } from './lib/builder/build.js';
import { DIST_ENTRIES_JS, build } from './lib/builder/build.js';

const require = createRequire(new URL('.', import.meta.url));

Expand Down Expand Up @@ -120,13 +120,9 @@ async function runBuild() {
});
}

async function runStart({
distDir = 'dist',
entriesJs = 'entries.js',
publicDir = 'public',
}) {
async function runStart({ distDir = 'dist', publicDir = 'public' }) {
const loadEntries = () =>
import(pathToFileURL(path.resolve(distDir, entriesJs)).toString());
import(pathToFileURL(path.resolve(distDir, DIST_ENTRIES_JS)).toString());
const app = new Hono();
app.use('*', serveStatic({ root: path.join(distDir, publicDir) }));
app.use('*', runner({ cmd: 'start', loadEntries, env: process.env as any }));
Expand Down
20 changes: 0 additions & 20 deletions packages/waku/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export interface Config {
basePath?: string;
/**
* The source directory relative to root.
* This will be the actual root in the development mode.
* Defaults to "src".
*/
srcDir?: string;
Expand All @@ -37,19 +36,6 @@ export interface Config {
*/
ssrDir?: string;
/**
* The client main file relative to srcDir.
* The extension should be `.js`,
* but resolved with other extensions in the development mode.
* Defaults to "main.js".
*/
mainJs?: string;
/**
* The entries.js file relative to srcDir or distDir.
* The extension should be `.js`,
* but resolved with other extensions in the development mode.
* Defaults to "entries.js".
*/
entriesJs?: string;
/**
* The list of directries to preserve server module structure.
* Relative to srcDir.
Expand All @@ -62,12 +48,6 @@ export interface Config {
* Defaults to "private".
*/
privateDir?: 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
76 changes: 24 additions & 52 deletions packages/waku/src/lib/builder/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,12 @@ const onwarn = (warning: RollupLog, defaultHandler: LoggingFunction) => {
defaultHandler(warning);
};

const analyzeEntries = async (
rootDir: string,
config: ResolvedConfig,
entriesFile: string,
) => {
// Some file and dir names for dist
// We may change this in the future
export const DIST_ENTRIES_JS = 'entries.js';
export const DIST_SERVE_JS = 'serve.js';

const analyzeEntries = async (rootDir: string, config: ResolvedConfig) => {
const wakuClientDist = decodeFilePathFromAbsolute(
joinPath(fileURLToFilePath(import.meta.url), '../../../client.js'),
);
Expand All @@ -106,7 +107,7 @@ const analyzeEntries = async (
await buildVite({
plugins: [
rscAnalyzePlugin(clientFileSet, serverFileSet, fileHashMap),
rscManagedPlugin(config),
rscManagedPlugin({ ...config, addEntriesToInput: true }),
],
ssr: {
target: 'webworker',
Expand All @@ -122,10 +123,7 @@ const analyzeEntries = async (
target: 'node18',
rollupOptions: {
onwarn,
input: {
...Object.fromEntries(moduleFileMap),
entries: entriesFile,
},
input: Object.fromEntries(moduleFileMap),
},
},
});
Expand Down Expand Up @@ -153,7 +151,6 @@ const analyzeEntries = async (
const buildServerBundle = async (
rootDir: string,
config: ResolvedConfig,
entriesFile: string,
clientEntryFiles: Record<string, string>,
serverEntryFiles: Record<string, string>,
serverModuleFiles: Record<string, string>,
Expand All @@ -177,9 +174,12 @@ const buildServerBundle = async (
}),
rscEnvPlugin({ config }),
rscPrivatePlugin(config),
rscManagedPlugin(config),
rscManagedPlugin({
...config,
addEntriesToInput: true,
}),
rscEntriesPlugin({
entriesFile,
srcDir: config.srcDir,
moduleMap: {
...Object.fromEntries(
Object.keys(SERVER_MODULE_MAP).map((key) => [key, `./${key}.js`]),
Expand Down Expand Up @@ -208,7 +208,7 @@ const buildServerBundle = async (
? [
rscServePlugin({
...config,
entriesFile,
distServeJs: DIST_SERVE_JS,
srcServeFile: decodeFilePathFromAbsolute(
joinPath(
fileURLToFilePath(import.meta.url),
Expand Down Expand Up @@ -251,7 +251,6 @@ const buildServerBundle = async (
rollupOptions: {
onwarn,
input: {
entries: entriesFile,
...SERVER_MODULE_MAP,
...serverModuleFiles,
...clientEntryFiles,
Expand All @@ -270,7 +269,6 @@ const buildServerBundle = async (
const buildSsrBundle = async (
rootDir: string,
config: ResolvedConfig,
mainJsFile: string,
clientEntryFiles: Record<string, string>,
serverBuildOutput: Awaited<ReturnType<typeof buildServerBundle>>,
isNodeCompatible: boolean,
Expand All @@ -284,11 +282,10 @@ const buildSsrBundle = async (
rscIndexPlugin({
...config,
cssAssets,
mainJs: mainJsFile.split('/').pop()!,
}),
rscEnvPlugin({ config }),
rscPrivatePlugin(config),
rscManagedPlugin(config),
rscManagedPlugin({ ...config, addMainToInput: true }),
],
ssr: isNodeCompatible
? {
Expand Down Expand Up @@ -316,7 +313,6 @@ const buildSsrBundle = async (
rollupOptions: {
onwarn,
input: {
main: mainJsFile,
...clientEntryFiles,
...CLIENT_MODULE_MAP,
},
Expand All @@ -342,7 +338,6 @@ const buildSsrBundle = async (
const buildClientBundle = async (
rootDir: string,
config: ResolvedConfig,
mainJsFile: string,
clientEntryFiles: Record<string, string>,
serverBuildOutput: Awaited<ReturnType<typeof buildServerBundle>>,
) => {
Expand All @@ -357,21 +352,17 @@ const buildClientBundle = async (
rscIndexPlugin({
...config,
cssAssets,
mainJs: mainJsFile.split('/').pop()!,
}),
rscEnvPlugin({ config }),
rscPrivatePlugin(config),
rscManagedPlugin(config),
rscManagedPlugin({ ...config, addMainToInput: true }),
],
build: {
outDir: joinPath(rootDir, config.distDir, config.publicDir),
rollupOptions: {
onwarn,
input: {
main: mainJsFile,
// rollup will ouput the style files related to clientEntryFiles, but since it does not find any link to them in the index.html file, it will not inject them. They are only mentioned by the standalone `clientEntryFiles`
...clientEntryFiles,
},
// rollup will ouput the style files related to clientEntryFiles, but since it does not find any link to them in the index.html file, it will not inject them. They are only mentioned by the standalone `clientEntryFiles`
input: clientEntryFiles,
preserveEntrySignatures: 'exports-only',
output: {
entryFileNames: (chunkInfo) => {
Expand Down Expand Up @@ -609,16 +600,6 @@ export const publicIndexHtml = ${JSON.stringify(publicIndexHtml)};
await appendFile(distEntriesFile, code);
};

const resolveFileName = (fname: string) => {
for (const ext of EXTENSIONS) {
const resolvedName = fname.slice(0, -extname(fname).length) + ext;
if (existsSync(resolvedName)) {
return resolvedName;
}
}
return fname; // returning the default one
};

export async function build(options: {
config: Config;
env?: Record<string, string>;
Expand All @@ -638,26 +619,17 @@ export async function build(options: {
const rootDir = (
await resolveViteConfig({}, 'build', 'production', 'production')
).root;
const entriesFile = resolveFileName(
joinPath(rootDir, config.srcDir, config.entriesJs),
);
const distEntriesFile = resolveFileName(
joinPath(rootDir, config.distDir, config.entriesJs),
);
const mainJsFile = resolveFileName(
joinPath(rootDir, config.srcDir, config.mainJs),
);
const distEntriesFile = joinPath(rootDir, config.distDir, DIST_ENTRIES_JS);
const isNodeCompatible =
options.deploy !== 'cloudflare' &&
options.deploy !== 'partykit' &&
options.deploy !== 'deno';

const { clientEntryFiles, serverEntryFiles, serverModuleFiles } =
await analyzeEntries(rootDir, config, entriesFile);
await analyzeEntries(rootDir, config);
const serverBuildOutput = await buildServerBundle(
rootDir,
config,
entriesFile,
clientEntryFiles,
serverEntryFiles,
serverModuleFiles,
Expand All @@ -672,15 +644,13 @@ export async function build(options: {
await buildSsrBundle(
rootDir,
config,
mainJsFile,
clientEntryFiles,
serverBuildOutput,
isNodeCompatible,
);
const clientBuildOutput = await buildClientBundle(
rootDir,
config,
mainJsFile,
clientEntryFiles,
serverBuildOutput,
);
Expand Down Expand Up @@ -711,18 +681,20 @@ export async function build(options: {
await emitVercelOutput(
rootDir,
config,
DIST_SERVE_JS,
options.deploy.slice('vercel-'.length) as 'static' | 'serverless',
);
} else if (options.deploy?.startsWith('netlify-')) {
await emitNetlifyOutput(
rootDir,
config,
DIST_SERVE_JS,
options.deploy.slice('netlify-'.length) as 'static' | 'functions',
);
} else if (options.deploy === 'cloudflare') {
await emitCloudflareOutput(rootDir, config);
await emitCloudflareOutput(rootDir, config, DIST_SERVE_JS);
} else if (options.deploy === 'partykit') {
await emitPartyKitOutput(rootDir, config);
await emitPartyKitOutput(rootDir, config, DIST_SERVE_JS);
} else if (options.deploy === 'aws-lambda') {
await emitAwsLambdaOutput(config);
}
Expand Down
3 changes: 2 additions & 1 deletion packages/waku/src/lib/builder/output-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import type { ResolvedConfig } from '../config.js';
export const emitCloudflareOutput = async (
rootDir: string,
config: ResolvedConfig,
serveJs: string,
) => {
const wranglerTomlFile = path.join(rootDir, 'wrangler.toml');
if (!existsSync(wranglerTomlFile)) {
writeFileSync(
wranglerTomlFile,
`
name = "waku-project"
main = "${config.distDir}/${config.serveJs}"
main = "${config.distDir}/${serveJs}"
compatibility_date = "2023-12-06"
compatibility_flags = [ "nodejs_als" ]

Expand Down
3 changes: 2 additions & 1 deletion packages/waku/src/lib/builder/output-netlify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { ResolvedConfig } from '../config.js';
export const emitNetlifyOutput = async (
rootDir: string,
config: ResolvedConfig,
serveJs: string,
type: 'static' | 'functions',
) => {
if (type === 'functions') {
Expand All @@ -26,7 +27,7 @@ export const emitNetlifyOutput = async (
path.join(functionsDir, 'serve.js'),
`
globalThis.__WAKU_NOT_FOUND_HTML__ = ${JSON.stringify(notFoundHtml)};
export { default } from '../../${config.distDir}/${config.serveJs}';
export { default } from '../../${config.distDir}/${serveJs}';
export const config = {
preferStatic: true,
path: ['/', '/*'],
Expand Down
3 changes: 2 additions & 1 deletion packages/waku/src/lib/builder/output-partykit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { ResolvedConfig } from '../config.js';
export const emitPartyKitOutput = async (
rootDir: string,
config: ResolvedConfig,
serveJs: string,
) => {
const partykitJsonFile = path.join(rootDir, 'partykit.json');
if (!existsSync(partykitJsonFile)) {
Expand All @@ -15,7 +16,7 @@ export const emitPartyKitOutput = async (
JSON.stringify(
{
name: 'waku-project',
main: `${config.distDir}/${config.serveJs}`,
main: `${config.distDir}/${serveJs}`,
compatibilityDate: '2023-02-16',
serve: `./${config.distDir}/${config.publicDir}`,
},
Expand Down
3 changes: 2 additions & 1 deletion packages/waku/src/lib/builder/output-vercel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { ResolvedConfig } from '../config.js';
export const emitVercelOutput = async (
rootDir: string,
config: ResolvedConfig,
serveJs: string,
type: 'static' | 'serverless',
) => {
const publicDir = path.join(rootDir, config.distDir, config.publicDir);
Expand Down Expand Up @@ -37,7 +38,7 @@ export const emitVercelOutput = async (
}
const vcConfigJson = {
runtime: 'nodejs20.x',
handler: `${config.distDir}/${config.serveJs}`,
handler: `${config.distDir}/${serveJs}`,
launcherType: 'Nodejs',
};
writeFileSync(
Expand Down
3 changes: 0 additions & 3 deletions packages/waku/src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,8 @@ export async function resolveConfig(config: Config) {
publicDir: 'public',
assetsDir: 'assets',
ssrDir: 'ssr',
mainJs: 'main.js',
entriesJs: 'entries.js',
preserveModuleDirs: ['pages', 'templates', 'routes', 'components'],
privateDir: 'private',
serveJs: 'serve.js',
rscPath: 'RSC',
htmlAttrs: '',
htmlHead: DEFAULT_HTML_HEAD,
Expand Down
Loading
Loading