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

feat(build): introduce buildData in platformObject #860

Merged
merged 5 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 10 additions & 4 deletions packages/waku/src/lib/builder/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import viteReact from '@vitejs/plugin-react';
import type { LoggingFunction, RollupLog } from 'rollup';

import type { Config } from '../../config.js';
import { unstable_getPlatformObject } from '../../server.js';
import type { BuildConfig, EntriesPrd } from '../../server.js';
import type { ResolvedConfig } from '../config.js';
import { resolveConfig, EXTENSIONS } from '../config.js';
Expand Down Expand Up @@ -695,6 +696,10 @@ export async function build(options: {
options.deploy !== 'partykit' &&
options.deploy !== 'deno';

const platformObject = unstable_getPlatformObject();
platformObject.buildOptions ||= {};
platformObject.buildOptions.deploy = options.deploy;

const { clientEntryFiles, serverEntryFiles, serverModuleFiles } =
await analyzeEntries(rootDir, config);
const serverBuildOutput = await buildServerBundle(
Expand Down Expand Up @@ -740,10 +745,6 @@ export async function build(options: {
{ env, config },
{ entries: distEntries },
);
await appendFile(
distEntriesFile,
`export const buildConfig = ${JSON.stringify(buildConfig)};`,
);
const { getClientModules } = await emitRscFiles(
rootDir,
env,
Expand Down Expand Up @@ -783,4 +784,9 @@ export async function build(options: {
} else if (options.deploy === 'aws-lambda') {
await emitAwsLambdaOutput(config);
}

await appendFile(
distEntriesFile,
`export const buildData = ${JSON.stringify(platformObject.buildData)};`,
);
}
27 changes: 14 additions & 13 deletions packages/waku/src/lib/renderers/rsc-renderer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ReactNode } from 'react';
import type { default as RSDWServerType } from 'react-server-dom-webpack/server.edge';

import { unstable_getPlatformObject } from '../../server.js';
import type {
EntriesDev,
EntriesPrd,
Expand Down Expand Up @@ -70,9 +71,9 @@ export async function renderRsc(
const {
default: { renderEntries },
loadModule,
buildConfig,
buildData,
} = entries as
| (EntriesDev & { loadModule: never; buildConfig: never })
| (EntriesDev & { loadModule: never; buildData: never })
| EntriesPrd;

const loadServerModule = <T>(key: keyof typeof SERVER_MODULE_MAP) =>
Expand All @@ -94,6 +95,9 @@ export async function renderRsc(
]);

setAllEnvInternal(env);
if (buildData) {
unstable_getPlatformObject().buildData = buildData;
}

const clientBundlerConfig = new Proxy(
{},
Expand Down Expand Up @@ -132,10 +136,7 @@ export async function renderRsc(
},
};
return runWithRenderStoreInternal(renderStore, async () => {
const elements = await renderEntries(input, {
params,
buildConfig,
});
const elements = await renderEntries(input, { params });
if (elements === null) {
const err = new Error('No function component found');
(err as any).statusCode = 404; // HACK our convention for NotFound
Expand Down Expand Up @@ -167,7 +168,7 @@ export async function renderRsc(
}
elementsPromise = Promise.all([
elementsPromise,
renderEntries(input, { params, buildConfig }),
renderEntries(input, { params }),
]).then(([oldElements, newElements]) => ({
...oldElements,
// FIXME we should actually check if newElements is null and send an error
Expand Down Expand Up @@ -327,9 +328,9 @@ export async function getSsrConfig(
const {
default: { getSsrConfig },
loadModule,
buildConfig,
buildData,
} = entries as
| (EntriesDev & { loadModule: never; buildConfig: never })
| (EntriesDev & { loadModule: never; buildData: never })
| EntriesPrd;

const loadServerModule = <T>(key: keyof typeof SERVER_MODULE_MAP) =>
Expand All @@ -351,11 +352,11 @@ export async function getSsrConfig(
]);

setAllEnvInternal(env);
if (buildData) {
unstable_getPlatformObject().buildData = buildData;
}

const ssrConfig = await getSsrConfig?.(pathname, {
searchParams,
buildConfig,
});
const ssrConfig = await getSsrConfig?.(pathname, { searchParams });
if (!ssrConfig) {
return null;
}
Expand Down
35 changes: 8 additions & 27 deletions packages/waku/src/router/create-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
getPathMapping,
path2regexp,
} from '../lib/utils/path.js';
import type { BuildConfig } from '../server.js';
import type { PathSpec } from '../lib/utils/path.js';

const hasPathSpecPrefix = (prefix: PathSpec, path: PathSpec) => {
Expand Down Expand Up @@ -182,16 +181,10 @@ export type CreateLayout = <T extends string>(layout: {
}) => void;

export function createPages(
fn: (
fns: {
createPage: CreatePage;
createLayout: CreateLayout;
unstable_setBuildData: (path: string, data: unknown) => void;
},
opts: {
unstable_buildConfig: BuildConfig | undefined;
},
) => Promise<void>,
fn: (fns: {
createPage: CreatePage;
createLayout: CreateLayout;
}) => Promise<void>,
) {
let configured = false;

Expand All @@ -211,7 +204,6 @@ export function createPages(
>();
const staticComponentMap = new Map<string, FunctionComponent<any>>();
const noSsrSet = new WeakSet<PathSpec>();
const buildDataMap = new Map<string, unknown>();

const registerStaticComponent = (
id: string,
Expand Down Expand Up @@ -325,17 +317,10 @@ export function createPages(
}
};

const unstable_setBuildData = (path: string, data: unknown) => {
buildDataMap.set(path, data);
};

let ready: Promise<void> | undefined;
const configure = async (buildConfig?: BuildConfig) => {
const configure = async () => {
if (!configured && !ready) {
ready = fn(
{ createPage, createLayout, unstable_setBuildData },
{ unstable_buildConfig: buildConfig },
);
ready = fn({ createPage, createLayout });
await ready;
configured = true;
}
Expand All @@ -350,7 +335,6 @@ export function createPages(
path: PathSpec;
isStatic: boolean;
noSsr: boolean;
data: unknown;
}[] = [];
for (const [path, pathSpec] of staticPathSet) {
const noSsr = noSsrSet.has(pathSpec);
Expand All @@ -368,7 +352,6 @@ export function createPages(
path: pathSpec,
isStatic,
noSsr,
data: buildDataMap.get(path),
});
}
for (const [path, [pathSpec]] of dynamicPagePathMap) {
Expand All @@ -378,7 +361,6 @@ export function createPages(
path: pathSpec,
isStatic: false,
noSsr,
data: buildDataMap.get(path),
});
}
for (const [path, [pathSpec]] of wildcardPagePathMap) {
Expand All @@ -388,13 +370,12 @@ export function createPages(
path: pathSpec,
isStatic: false,
noSsr,
data: buildDataMap.get(path),
});
}
return paths;
},
async (id, { unstable_setShouldSkip, unstable_buildConfig }) => {
await configure(unstable_buildConfig);
async (id, { unstable_setShouldSkip }) => {
await configure();
const staticComponent = staticComponentMap.get(id);
if (staticComponent) {
unstable_setShouldSkip([]);
Expand Down
51 changes: 23 additions & 28 deletions packages/waku/src/router/define-router.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { createElement } from 'react';
import type { ComponentProps, FunctionComponent, ReactNode } from 'react';

import { defineEntries, rerender } from '../server.js';
import {
defineEntries,
rerender,
unstable_getPlatformObject,
} from '../server.js';
import type {
BuildConfig,
RenderEntries,
Expand Down Expand Up @@ -48,34 +52,32 @@ export function unstable_defineRouter(
path: PathSpec;
isStatic?: boolean;
noSsr?: boolean;
data?: unknown; // For build: put in customData
}>
>,
getComponent: (
componentId: string, // "**/layout" or "**/page"
options: {
// TODO setShouldSkip API is too hard to understand
unstable_setShouldSkip: (val?: ShouldSkipValue) => void;
unstable_buildConfig: BuildConfig | undefined;
},
) => Promise<
| FunctionComponent<RouteProps>
| FunctionComponent<RoutePropsForLayout>
| null
>,
): ReturnType<typeof defineEntries> {
const platformObject = unstable_getPlatformObject();
type MyPathConfig = {
pattern: string;
pathname: PathSpec;
isStatic?: boolean | undefined;
customData: { noSsr?: boolean; is404: boolean; data: unknown };
specs: { noSsr?: boolean; is404: boolean };
}[];
let cachedPathConfig: MyPathConfig | undefined;
const getMyPathConfig = async (
buildConfig?: BuildConfig,
): Promise<MyPathConfig> => {
if (buildConfig) {
return buildConfig as MyPathConfig;
const getMyPathConfig = async (): Promise<MyPathConfig> => {
const pathConfig = platformObject.buildData?.defineRouterPathConfigs;
if (pathConfig) {
return pathConfig as MyPathConfig;
}
if (!cachedPathConfig) {
cachedPathConfig = Array.from(await getPathConfig()).map((item) => {
Expand All @@ -87,34 +89,30 @@ export function unstable_defineRouter(
pattern: item.pattern,
pathname: item.path,
isStatic: item.isStatic,
customData: { is404, noSsr: !!item.noSsr, data: item.data },
specs: { is404, noSsr: !!item.noSsr },
};
});
}
return cachedPathConfig;
};
const existsPath = async (
pathname: string,
buildConfig: BuildConfig | undefined,
): Promise<['FOUND', 'NO_SSR'?] | ['NOT_FOUND', 'HAS_404'?]> => {
const pathConfig = await getMyPathConfig(buildConfig);
const pathConfig = await getMyPathConfig();
const found = pathConfig.find(({ pathname: pathSpec }) =>
getPathMapping(pathSpec, pathname),
);
return found
? found.customData.noSsr
? found.specs.noSsr
? ['FOUND', 'NO_SSR']
: ['FOUND']
: pathConfig.some(({ customData: { is404 } }) => is404) // FIXMEs should avoid re-computation
: pathConfig.some(({ specs: { is404 } }) => is404) // FIXMEs should avoid re-computation
? ['NOT_FOUND', 'HAS_404']
: ['NOT_FOUND'];
};
const renderEntries: RenderEntries = async (
input,
{ params, buildConfig },
) => {
const renderEntries: RenderEntries = async (input, { params }) => {
const pathname = parseInputString(input);
if ((await existsPath(pathname, buildConfig))[0] === 'NOT_FOUND') {
if ((await existsPath(pathname))[0] === 'NOT_FOUND') {
return null;
}
const shouldSkipObj: {
Expand Down Expand Up @@ -144,7 +142,6 @@ export function unstable_defineRouter(
};
const component = await getComponent(id, {
unstable_setShouldSkip: setShoudSkip,
unstable_buildConfig: buildConfig,
});
if (!component) {
return [];
Expand Down Expand Up @@ -196,7 +193,7 @@ globalThis.__WAKU_ROUTER_PREFETCH__ = (path) => {
}
};`;
const buildConfig: BuildConfig = [];
for (const { pathname: pathSpec, isStatic, customData } of pathConfig) {
for (const { pathname: pathSpec, isStatic, specs } of pathConfig) {
const entries: BuildConfig[number]['entries'] = [];
if (pathSpec.every(({ type }) => type === 'literal')) {
const pathname = '/' + pathSpec.map(({ name }) => name).join('/');
Expand All @@ -209,18 +206,16 @@ globalThis.__WAKU_ROUTER_PREFETCH__ = (path) => {
entries,
customCode:
customCode +
(customData.is404 ? 'globalThis.__WAKU_ROUTER_404__ = true;' : ''),
customData,
(specs.is404 ? 'globalThis.__WAKU_ROUTER_404__ = true;' : ''),
});
}
platformObject.buildData ||= {};
platformObject.buildData.defineRouterPathConfigs = pathConfig;
return buildConfig;
};

const getSsrConfig: GetSsrConfig = async (
pathname,
{ searchParams, buildConfig },
) => {
const pathStatus = await existsPath(pathname, buildConfig);
const getSsrConfig: GetSsrConfig = async (pathname, { searchParams }) => {
const pathStatus = await existsPath(pathname);
if (pathStatus[1] === 'NO_SSR') {
return null;
}
Expand Down
Loading
Loading