@ecopages/react 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -6
- package/package.json +10 -10
- package/src/client-graph/reachability-analyzer.d.ts +1 -2
- package/src/client-graph/reachability-analyzer.js +2 -4
- package/src/client-graph/reachability-client-roots.d.ts +1 -8
- package/src/client-graph/reachability-client-roots.js +8 -25
- package/src/client-graph/reachability-top-level-index.d.ts +1 -2
- package/src/client-graph/reachability-top-level-index.js +7 -11
- package/src/content/lazy-collection-components.d.ts +38 -0
- package/src/content/lazy-collection-components.js +104 -0
- package/src/hydration/browser/page-hydration-hmr.js +8 -13
- package/src/hydration/browser/page-hydration-module.d.ts +2 -6
- package/src/hydration/browser/page-hydration-module.js +3 -9
- package/src/hydration/browser/page-hydration.d.ts +8 -6
- package/src/hydration/browser/page-hydration.js +120 -50
- package/src/hydration/compiled-page-hydration-options.d.ts +0 -1
- package/src/hydration/hydration-asset.d.ts +5 -10
- package/src/hydration/hydration-asset.js +11 -54
- package/src/hydration/hydration-page-entry-source.js +8 -10
- package/src/plugin/react.constants.d.ts +4 -0
- package/src/plugin/react.constants.js +4 -0
- package/src/plugin/react.plugin.js +11 -2
- package/src/plugin/react.types.d.ts +23 -0
- package/src/render/component-ssr.d.ts +5 -6
- package/src/render/component-ssr.js +8 -9
- package/src/render/errors.d.ts +1 -1
- package/src/render/errors.js +2 -2
- package/src/render/layout-compose.d.ts +1 -1
- package/src/render/react-renderer.d.ts +2 -11
- package/src/render/react-renderer.js +30 -65
- package/src/render/react-runtime.d.ts +50 -2
- package/src/render/react-runtime.js +131 -1
- package/src/client-graph/reachability-preload.d.ts +0 -10
- package/src/client-graph/reachability-preload.js +0 -30
- package/src/content/collection-component-cache.d.ts +0 -25
- package/src/content/collection-component-cache.js +0 -62
package/src/render/errors.js
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
* Error thrown when an error occurs while rendering a React component.
|
|
6
6
|
*/
|
|
7
7
|
export class ReactRenderError extends Error {
|
|
8
|
-
constructor(message) {
|
|
9
|
-
super(message);
|
|
8
|
+
constructor(message, options) {
|
|
9
|
+
super(message, options);
|
|
10
10
|
this.name = 'ReactRenderError';
|
|
11
11
|
}
|
|
12
12
|
}
|
|
@@ -6,7 +6,7 @@ export type LayoutComposeContext = LayoutPropsContext;
|
|
|
6
6
|
export type ReactRuntime = typeof bundledReact;
|
|
7
7
|
export type LayoutComposeOptions = {
|
|
8
8
|
context?: LayoutComposeContext;
|
|
9
|
-
/** @remarks Pass the app-resolved React runtime during SSR so composition
|
|
9
|
+
/** @remarks Pass the app-resolved React runtime during SSR so composition uses the same React instance as server rendering. */
|
|
10
10
|
react?: ReactRuntime;
|
|
11
11
|
/**
|
|
12
12
|
* Optional resolver that substitutes cached layout instances and React keys
|
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* React IntegrationRenderer orchestrator.
|
|
3
|
-
*
|
|
4
|
-
* @remarks
|
|
5
|
-
* Wires services and delegates SSR / layout composition / ownership details to
|
|
6
|
-
* focused modules under `render/`. Prefer changing those modules for
|
|
7
|
-
* implementation work; keep this file as the IntegrationRenderer seam.
|
|
8
|
-
*
|
|
9
|
-
* @module
|
|
10
|
-
*/
|
|
11
1
|
/**
|
|
12
2
|
* React IntegrationRenderer orchestrator.
|
|
13
3
|
*
|
|
@@ -63,6 +53,7 @@ export declare class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
63
53
|
private getRouterDocumentAttributes;
|
|
64
54
|
protected resolveReactRuntimeModules(): ReactRuntimeModules;
|
|
65
55
|
private getReactRuntimeModules;
|
|
56
|
+
private renderReactTree;
|
|
66
57
|
private resolveReactQueuedForeignSubtreeHtml;
|
|
67
58
|
private renderQueuedChildrenToHtml;
|
|
68
59
|
private buildPagePayload;
|
|
@@ -75,7 +66,7 @@ export declare class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
75
66
|
* `data-eco-component-id` attribute is attached so island hydration can target it.
|
|
76
67
|
* - Without an explicit instance id, component renders remain plain SSR output.
|
|
77
68
|
* - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
|
|
78
|
-
* composition step and
|
|
69
|
+
* composition step and the parent wrapper is not an island host.
|
|
79
70
|
*
|
|
80
71
|
* This preserves DOM shape for global CSS/layout selectors while keeping a
|
|
81
72
|
* deterministic mount target per component instance.
|
|
@@ -1,14 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* React IntegrationRenderer orchestrator.
|
|
3
|
-
*
|
|
4
|
-
* @remarks
|
|
5
|
-
* Wires services and delegates SSR / layout composition / ownership details to
|
|
6
|
-
* focused modules under `render/`. Prefer changing those modules for
|
|
7
|
-
* implementation work; keep this file as the IntegrationRenderer seam.
|
|
8
|
-
*
|
|
9
|
-
* @module
|
|
10
|
-
*/
|
|
11
|
-
import { HttpError } from '@ecopages/core/errors';
|
|
12
1
|
import { buildIslandHostAttributes, getComponentIdentity } from '@ecopages/core';
|
|
13
2
|
import { createIntegrationRenderer, selectHydrationIslandEntries, } from '@ecopages/core/integration';
|
|
14
3
|
import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from '@ecopages/core/client';
|
|
@@ -16,7 +5,7 @@ import { resolveQueuedTokens } from '@ecopages/core/integration';
|
|
|
16
5
|
import { ensurePageConfigLayouts } from '@ecopages/core/integration';
|
|
17
6
|
import { hasSingleRootElement } from './html-boundary.js';
|
|
18
7
|
import { getIslandComponentKey } from '../hydration/hydration-asset.js';
|
|
19
|
-
import { REACT_PLUGIN_NAME } from '../plugin/react.constants.js';
|
|
8
|
+
import { REACT_PLUGIN_NAME, REACT_SSR_RENDER_TIMEOUT_MS } from '../plugin/react.constants.js';
|
|
20
9
|
import { BundleService } from '../bundling/bundle.js';
|
|
21
10
|
import { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
|
|
22
11
|
import { MdxConfigDependencyService } from '../mdx/mdx-config-dependency.js';
|
|
@@ -27,7 +16,7 @@ import {} from '@ecopages/core/integration';
|
|
|
27
16
|
import { asNonReactShellComponent, getComponentRequires, isReactManagedComponent } from './component-ownership.js';
|
|
28
17
|
import { buildHydrationProps, renderComponentHtml, renderNonReactShellComponent, restoreRuntimeChildHtml, toReactNode, } from './component-ssr.js';
|
|
29
18
|
import { BundleError, ReactRenderError } from './errors.js';
|
|
30
|
-
import { resolveReactRuntimeModules } from './react-runtime.js';
|
|
19
|
+
import { renderReactHtml, resolveReactRuntimeModules, runWithRenderBudget, } from './react-runtime.js';
|
|
31
20
|
import { composeReactLayoutPageTree, shouldUseUnifiedReactLayoutComposition } from './unified-layout-composition.js';
|
|
32
21
|
import { assertComposablePage, resolveLayoutContextFromShell } from './layout-compose.js';
|
|
33
22
|
export { BundleError, ReactRenderError } from './errors.js';
|
|
@@ -101,18 +90,16 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
101
90
|
* Builds React island and lazy-entry modules in one grouped browser build.
|
|
102
91
|
*/
|
|
103
92
|
async buildPageClientBrowserAssetsHook(plan) {
|
|
104
|
-
const
|
|
93
|
+
const processedAssets = await this.hydrationAssetService.buildPageClientAssets({
|
|
105
94
|
islands: selectHydrationIslandEntries(plan, this.name).map((entry) => ({
|
|
106
95
|
file: entry.file,
|
|
107
96
|
config: entry.component.config,
|
|
108
97
|
})),
|
|
109
98
|
lazyEntries: plan.lazyClientEntries,
|
|
110
99
|
});
|
|
111
|
-
const lazyTriggers = this.getRuntimeState().applyPendingLazyTriggers(result.processedAssets, plan.lazyConfigs ?? []);
|
|
112
100
|
return {
|
|
113
|
-
processedAssets
|
|
114
|
-
|
|
115
|
-
lazyTriggers,
|
|
101
|
+
processedAssets,
|
|
102
|
+
lazyTriggers: this.getRuntimeState().applyPendingLazyTriggers(processedAssets, plan.lazyConfigs ?? []),
|
|
116
103
|
};
|
|
117
104
|
}
|
|
118
105
|
async collectAppBrowserClientBuildEntriesHook(plan) {
|
|
@@ -136,6 +123,12 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
136
123
|
this.reactRuntimeModules ??= this.resolveReactRuntimeModules();
|
|
137
124
|
return this.reactRuntimeModules;
|
|
138
125
|
}
|
|
126
|
+
renderReactTree(element, label) {
|
|
127
|
+
return renderReactHtml(this.getReactRuntimeModules(), element, {
|
|
128
|
+
timeoutMs: this.getRuntimeState().renderTimeoutMs,
|
|
129
|
+
label,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
139
132
|
resolveReactQueuedForeignSubtreeHtml(html, runtimeContext) {
|
|
140
133
|
return this.resolveQueuedForeignSubtrees(html, runtimeContext, async (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => ({
|
|
141
134
|
html: await this.renderQueuedChildrenToHtml({
|
|
@@ -151,8 +144,8 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
151
144
|
if (children === undefined) {
|
|
152
145
|
return undefined;
|
|
153
146
|
}
|
|
154
|
-
const
|
|
155
|
-
let html = this.normalizeUnresolvedMarkerArtifactHtml(
|
|
147
|
+
const runtime = this.getReactRuntimeModules();
|
|
148
|
+
let html = this.normalizeUnresolvedMarkerArtifactHtml(await this.renderReactTree(runtime.react.createElement(runtime.react.Fragment, null, toReactNode(children, this.name)), 'queued children'));
|
|
156
149
|
html = restoreRuntimeChildHtml(html, runtimeContext);
|
|
157
150
|
return await resolveQueuedTokens(html, queuedResolutionsByToken, resolveToken);
|
|
158
151
|
}
|
|
@@ -179,7 +172,7 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
179
172
|
* `data-eco-component-id` attribute is attached so island hydration can target it.
|
|
180
173
|
* - Without an explicit instance id, component renders remain plain SSR output.
|
|
181
174
|
* - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
|
|
182
|
-
* composition step and
|
|
175
|
+
* composition step and the parent wrapper is not an island host.
|
|
183
176
|
*
|
|
184
177
|
* This preserves DOM shape for global CSS/layout selectors while keeping a
|
|
185
178
|
* deterministic mount target per component instance.
|
|
@@ -200,14 +193,10 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
200
193
|
};
|
|
201
194
|
}
|
|
202
195
|
const html = await renderNonReactShellComponent(asNonReactShellComponent(input.component), props, 'Component');
|
|
203
|
-
const assets = input.component.config?.dependencies
|
|
204
|
-
? await this.processComponentDependencies([input.component])
|
|
205
|
-
: undefined;
|
|
206
196
|
return {
|
|
207
197
|
html,
|
|
208
198
|
canAttachAttributes: true,
|
|
209
199
|
integrationName: this.name,
|
|
210
|
-
assets,
|
|
211
200
|
};
|
|
212
201
|
}
|
|
213
202
|
/**
|
|
@@ -223,13 +212,18 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
223
212
|
componentInstanceId: input.integrationContext?.componentInstanceId,
|
|
224
213
|
};
|
|
225
214
|
const hasResolvedChildHtml = input.children !== undefined;
|
|
226
|
-
let html = this.normalizeUnresolvedMarkerArtifactHtml(renderComponentHtml({
|
|
227
|
-
|
|
228
|
-
|
|
215
|
+
let html = this.normalizeUnresolvedMarkerArtifactHtml(await renderComponentHtml({
|
|
216
|
+
input,
|
|
217
|
+
context,
|
|
218
|
+
runtimeContext,
|
|
219
|
+
runtime: this.getReactRuntimeModules(),
|
|
220
|
+
timeoutMs: this.getRuntimeState().renderTimeoutMs,
|
|
221
|
+
label: getComponentIdentity(input.component)?.file ?? 'component',
|
|
222
|
+
}));
|
|
223
|
+
html = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
|
|
229
224
|
const canAttachAttributes = hasSingleRootElement(html);
|
|
230
225
|
const componentFile = getComponentIdentity(componentConfig)?.file;
|
|
231
226
|
let rootAttributes;
|
|
232
|
-
let assets;
|
|
233
227
|
if (canAttachAttributes && componentFile && context.componentInstanceId && !hasResolvedChildHtml) {
|
|
234
228
|
rootAttributes = buildIslandHostAttributes({
|
|
235
229
|
integrationName: this.name,
|
|
@@ -237,19 +231,13 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
237
231
|
componentKey: getIslandComponentKey(componentFile, componentConfig),
|
|
238
232
|
props: buildHydrationProps(input.props),
|
|
239
233
|
});
|
|
240
|
-
assets = this.getActiveIslandRenderAssets().get(componentFile);
|
|
241
234
|
html = `<eco-island style="display:contents">${html}</eco-island>`;
|
|
242
235
|
}
|
|
243
|
-
const mergedAssets = this.htmlTransformer.dedupeProcessedAssets([
|
|
244
|
-
...(assets ?? []),
|
|
245
|
-
...queuedResolution.assets,
|
|
246
|
-
]);
|
|
247
236
|
return {
|
|
248
237
|
html,
|
|
249
238
|
canAttachAttributes,
|
|
250
239
|
integrationName: this.name,
|
|
251
240
|
rootAttributes,
|
|
252
|
-
assets: mergedAssets.length > 0 ? mergedAssets : undefined,
|
|
253
241
|
};
|
|
254
242
|
}
|
|
255
243
|
async renderQueuedChildrenHook(children, runtimeContext, queuedResolutionsByToken, resolveToken) {
|
|
@@ -321,10 +309,10 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
321
309
|
component: layout.component,
|
|
322
310
|
props: layout.props,
|
|
323
311
|
}));
|
|
324
|
-
const
|
|
312
|
+
const runtime = this.getReactRuntimeModules();
|
|
325
313
|
const tree = composeReactLayoutPageTree(pageComponent, page.props, shellEntries, {
|
|
326
314
|
context: resolveLayoutContextFromShell(page.props, shellEntries),
|
|
327
|
-
react,
|
|
315
|
+
react: runtime.react,
|
|
328
316
|
});
|
|
329
317
|
const runtimeInput = {
|
|
330
318
|
component: page.component,
|
|
@@ -334,19 +322,8 @@ export class ReactRenderer extends ReactIntegrationRenderer {
|
|
|
334
322
|
},
|
|
335
323
|
};
|
|
336
324
|
const runtimeContext = this.getQueuedForeignSubtreeContext(runtimeInput);
|
|
337
|
-
const html = this.normalizeUnresolvedMarkerArtifactHtml(
|
|
338
|
-
|
|
339
|
-
const primaryRender = {
|
|
340
|
-
html: resolved.html,
|
|
341
|
-
canAttachAttributes: hasSingleRootElement(resolved.html),
|
|
342
|
-
integrationName: this.name,
|
|
343
|
-
assets: resolved.assets.length > 0 ? resolved.assets : undefined,
|
|
344
|
-
};
|
|
345
|
-
return {
|
|
346
|
-
children: resolved.html,
|
|
347
|
-
layoutRenders: [],
|
|
348
|
-
primaryRender,
|
|
349
|
-
};
|
|
325
|
+
const html = this.normalizeUnresolvedMarkerArtifactHtml(await this.renderReactTree(tree, getComponentIdentity(page.component)?.file ?? 'page'));
|
|
326
|
+
return { children: await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext) };
|
|
350
327
|
}
|
|
351
328
|
resolveComposeChildren(options) {
|
|
352
329
|
const { page, shellLayouts, foreignChildRoots } = options;
|
|
@@ -411,6 +388,7 @@ function createReactRendererHookFactory(reactConfig, runtimeStateRef, hookTarget
|
|
|
411
388
|
const mdxExtensions = reactConfig?.mdxExtensions ?? ['.mdx'];
|
|
412
389
|
const hmrPageMetadataCache = reactConfig?.hmrPageMetadataCache;
|
|
413
390
|
const forceBrowserGraph = reactConfig?.forceBrowserGraph ?? false;
|
|
391
|
+
const renderTimeoutMs = reactConfig?.renderTimeoutMs ?? REACT_SSR_RENDER_TIMEOUT_MS;
|
|
414
392
|
const bundleService = new BundleService({
|
|
415
393
|
rootDir: appConfig.rootDir,
|
|
416
394
|
appConfig,
|
|
@@ -440,6 +418,7 @@ function createReactRendererHookFactory(reactConfig, runtimeStateRef, hookTarget
|
|
|
440
418
|
mdxExtensions,
|
|
441
419
|
hmrPageMetadataCache,
|
|
442
420
|
forceBrowserGraph,
|
|
421
|
+
renderTimeoutMs,
|
|
443
422
|
bundleService,
|
|
444
423
|
pageModuleService,
|
|
445
424
|
hydrationAssetService,
|
|
@@ -463,14 +442,7 @@ function createReactRendererHookFactory(reactConfig, runtimeStateRef, hookTarget
|
|
|
463
442
|
documentShellProps: (options) => requireReactRendererHookTarget(hookTargets, 'documentShellProps')(options),
|
|
464
443
|
documentContributions: (context) => requireReactRendererHookTarget(hookTargets, 'documentContributions')(context),
|
|
465
444
|
documentAttributes: (options) => requireReactRendererHookTarget(hookTargets, 'documentAttributes')(options),
|
|
466
|
-
renderRoute:
|
|
467
|
-
try {
|
|
468
|
-
return await render();
|
|
469
|
-
}
|
|
470
|
-
catch (error) {
|
|
471
|
-
throw createReactRenderError('Failed to render component', error);
|
|
472
|
-
}
|
|
473
|
-
},
|
|
445
|
+
renderRoute: (options, render) => runWithRenderBudget({ timeoutMs: renderTimeoutMs, label: options.file }, render),
|
|
474
446
|
};
|
|
475
447
|
};
|
|
476
448
|
}
|
|
@@ -481,10 +453,3 @@ function requireReactRendererHookTarget(hookTargets, name) {
|
|
|
481
453
|
}
|
|
482
454
|
return hookTarget;
|
|
483
455
|
}
|
|
484
|
-
function createReactRenderError(message, cause) {
|
|
485
|
-
if (HttpError.isHttpError(cause)) {
|
|
486
|
-
return cause;
|
|
487
|
-
}
|
|
488
|
-
const errorMessage = cause instanceof Error ? `${message}: ${cause.message}` : message;
|
|
489
|
-
return HttpError.InternalServerError(errorMessage);
|
|
490
|
-
}
|
|
@@ -1,13 +1,61 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Resolves the React and react-dom/server modules used for SSR.
|
|
2
|
+
* Resolves the React, react-dom/static and react-dom/server modules used for SSR, and renders React trees to HTML with them.
|
|
3
3
|
*
|
|
4
4
|
* @remarks
|
|
5
5
|
* Prefers the app's own React install so SSR identity matches the app bundle.
|
|
6
6
|
* Falls back to the integration's React when the app package cannot resolve them.
|
|
7
7
|
*/
|
|
8
|
+
import type { ReactNode } from 'react';
|
|
8
9
|
import type { ReactRuntime } from './layout-compose.js';
|
|
10
|
+
export type RenderReactHtmlOptions = {
|
|
11
|
+
/** Milliseconds to wait for Suspense when no route render budget is active. */
|
|
12
|
+
timeoutMs: number;
|
|
13
|
+
/** Identity of the tree being rendered, used in timeout messages. */
|
|
14
|
+
label: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Runs `render` with one Suspense deadline shared by every {@link renderReactHtml} call inside it.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* A route render makes several sequential React renders (the Page tree, queued children, each
|
|
21
|
+
* component). Without a shared deadline each would wait the full limit, so a route could wait a
|
|
22
|
+
* multiple of it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function runWithRenderBudget<T>(options: RenderReactHtmlOptions, render: () => Promise<T>): Promise<T>;
|
|
9
25
|
export type ReactRuntimeModules = {
|
|
10
26
|
react: ReactRuntime;
|
|
11
|
-
|
|
27
|
+
reactDomStatic: typeof import('react-dom/static');
|
|
28
|
+
reactDomServer: Pick<typeof import('react-dom/server'), 'renderToString'>;
|
|
12
29
|
};
|
|
13
30
|
export declare function resolveReactRuntimeModules(rootDir: string | undefined): ReactRuntimeModules;
|
|
31
|
+
/**
|
|
32
|
+
* Renders a React tree to complete HTML, waiting for every Suspense boundary to resolve.
|
|
33
|
+
*
|
|
34
|
+
* @remarks
|
|
35
|
+
* - `onError` logs real render errors with `console.error`. An AbortError is ignored only after
|
|
36
|
+
* this render's timeout has fired, so an aborted fetch still logs. An error inside a Suspense
|
|
37
|
+
* boundary then serves that boundary's fallback for the browser to retry, as `renderToString`
|
|
38
|
+
* did, but now logged. An error outside every boundary is logged too and rejects the render, so
|
|
39
|
+
* the caller's own log of that failure repeats it. Abort from the render timeout is the warning
|
|
40
|
+
* below, not a logged error.
|
|
41
|
+
* - An unbounded `progressiveChunkSize` keeps resolved boundaries inline. With the default,
|
|
42
|
+
* React moves a large boundary after its fallback and reveals it with an inline script.
|
|
43
|
+
* A boundary that renders a `precedence` stylesheet is still moved; that HTML fails the
|
|
44
|
+
* render so the stylesheet is declared as a Dependency instead.
|
|
45
|
+
* - React prefixes an `<html>` root with a doctype; the document shell writes its own, so
|
|
46
|
+
* the prefix is dropped.
|
|
47
|
+
* - Waiting is bounded by the active {@link runWithRenderBudget} deadline, or by `timeoutMs` from
|
|
48
|
+
* now outside one. Past the deadline the tree still renders what needs no waiting. When the
|
|
49
|
+
* signal fires, unfinished boundaries stay in their fallback and the rest of the tree is served,
|
|
50
|
+
* the same outcome as a boundary that throws.
|
|
51
|
+
* - `prerender` returns no HTML when the abort lands while the tree has no finished host element
|
|
52
|
+
* around its pending work: a shell still waiting outside every boundary, or a boundary at the
|
|
53
|
+
* root of the tree. The tree is then rendered once more with `renderToString`, which serves such
|
|
54
|
+
* a boundary's fallback, marked for the browser to render, and throws for a waiting shell. That
|
|
55
|
+
* throw fails the render. In development React writes into the marked boundary that
|
|
56
|
+
* `renderToString` does not support Suspense; the browser reports it as a recovered hydration
|
|
57
|
+
* error.
|
|
58
|
+
* - The Node stream variant is used because the web-stream `prerender` is only in the Node
|
|
59
|
+
* build from react-dom 19.2, while the peer range allows any React 19.
|
|
60
|
+
*/
|
|
61
|
+
export declare function renderReactHtml(runtime: ReactRuntimeModules, element: ReactNode, options: RenderReactHtmlOptions): Promise<string>;
|
|
@@ -1,18 +1,36 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Resolves the React and react-dom/server modules used for SSR.
|
|
2
|
+
* Resolves the React, react-dom/static and react-dom/server modules used for SSR, and renders React trees to HTML with them.
|
|
3
3
|
*
|
|
4
4
|
* @remarks
|
|
5
5
|
* Prefers the app's own React install so SSR identity matches the app bundle.
|
|
6
6
|
* Falls back to the integration's React when the app package cannot resolve them.
|
|
7
7
|
*/
|
|
8
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
9
|
import { createRequire } from 'node:module';
|
|
9
10
|
import path from 'node:path';
|
|
11
|
+
import { text } from 'node:stream/consumers';
|
|
12
|
+
import { Logger } from '@ecopages/logger';
|
|
13
|
+
import { ReactRenderError } from './errors.js';
|
|
14
|
+
const appLogger = new Logger('[ReactSSR]');
|
|
15
|
+
const renderBudgetStorage = new AsyncLocalStorage();
|
|
16
|
+
/**
|
|
17
|
+
* Runs `render` with one Suspense deadline shared by every {@link renderReactHtml} call inside it.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* A route render makes several sequential React renders (the Page tree, queued children, each
|
|
21
|
+
* component). Without a shared deadline each would wait the full limit, so a route could wait a
|
|
22
|
+
* multiple of it.
|
|
23
|
+
*/
|
|
24
|
+
export function runWithRenderBudget(options, render) {
|
|
25
|
+
return renderBudgetStorage.run({ deadline: Date.now() + options.timeoutMs, timeoutMs: options.timeoutMs, label: options.label, warned: false }, render);
|
|
26
|
+
}
|
|
10
27
|
export function resolveReactRuntimeModules(rootDir) {
|
|
11
28
|
const appPackageJsonPath = path.resolve(rootDir || process.cwd(), 'package.json');
|
|
12
29
|
try {
|
|
13
30
|
const requireFromApp = createRequire(appPackageJsonPath);
|
|
14
31
|
return {
|
|
15
32
|
react: requireFromApp('react'),
|
|
33
|
+
reactDomStatic: requireFromApp('react-dom/static'),
|
|
16
34
|
reactDomServer: requireFromApp('react-dom/server'),
|
|
17
35
|
};
|
|
18
36
|
}
|
|
@@ -20,7 +38,119 @@ export function resolveReactRuntimeModules(rootDir) {
|
|
|
20
38
|
const requireFromIntegration = createRequire(import.meta.url);
|
|
21
39
|
return {
|
|
22
40
|
react: requireFromIntegration('react'),
|
|
41
|
+
reactDomStatic: requireFromIntegration('react-dom/static'),
|
|
23
42
|
reactDomServer: requireFromIntegration('react-dom/server'),
|
|
24
43
|
};
|
|
25
44
|
}
|
|
26
45
|
}
|
|
46
|
+
const DOCTYPE = '<!DOCTYPE html>';
|
|
47
|
+
/**
|
|
48
|
+
* React's inline timing script, written after the root element (inside `<body>` for an `<html>`
|
|
49
|
+
* root) when a boundary is still pending or moved out of line.
|
|
50
|
+
*
|
|
51
|
+
* @remarks
|
|
52
|
+
* It only feeds React's client reveal timing for streamed boundaries, which a complete document
|
|
53
|
+
* never uses. Left in, it makes the output two root nodes, so an Island Host loses its host
|
|
54
|
+
* attributes and never hydrates, and it is an inline script a strict CSP blocks. The pattern is
|
|
55
|
+
* React's exact output, so user markup is never matched.
|
|
56
|
+
*/
|
|
57
|
+
const REVEAL_TIMING_SCRIPT = /<script(?: id="_R_")?>requestAnimationFrame\(function\(\)\{\$RT=performance\.now\(\)\}\);<\/script>/;
|
|
58
|
+
/**
|
|
59
|
+
* Renders a React tree to complete HTML, waiting for every Suspense boundary to resolve.
|
|
60
|
+
*
|
|
61
|
+
* @remarks
|
|
62
|
+
* - `onError` logs real render errors with `console.error`. An AbortError is ignored only after
|
|
63
|
+
* this render's timeout has fired, so an aborted fetch still logs. An error inside a Suspense
|
|
64
|
+
* boundary then serves that boundary's fallback for the browser to retry, as `renderToString`
|
|
65
|
+
* did, but now logged. An error outside every boundary is logged too and rejects the render, so
|
|
66
|
+
* the caller's own log of that failure repeats it. Abort from the render timeout is the warning
|
|
67
|
+
* below, not a logged error.
|
|
68
|
+
* - An unbounded `progressiveChunkSize` keeps resolved boundaries inline. With the default,
|
|
69
|
+
* React moves a large boundary after its fallback and reveals it with an inline script.
|
|
70
|
+
* A boundary that renders a `precedence` stylesheet is still moved; that HTML fails the
|
|
71
|
+
* render so the stylesheet is declared as a Dependency instead.
|
|
72
|
+
* - React prefixes an `<html>` root with a doctype; the document shell writes its own, so
|
|
73
|
+
* the prefix is dropped.
|
|
74
|
+
* - Waiting is bounded by the active {@link runWithRenderBudget} deadline, or by `timeoutMs` from
|
|
75
|
+
* now outside one. Past the deadline the tree still renders what needs no waiting. When the
|
|
76
|
+
* signal fires, unfinished boundaries stay in their fallback and the rest of the tree is served,
|
|
77
|
+
* the same outcome as a boundary that throws.
|
|
78
|
+
* - `prerender` returns no HTML when the abort lands while the tree has no finished host element
|
|
79
|
+
* around its pending work: a shell still waiting outside every boundary, or a boundary at the
|
|
80
|
+
* root of the tree. The tree is then rendered once more with `renderToString`, which serves such
|
|
81
|
+
* a boundary's fallback, marked for the browser to render, and throws for a waiting shell. That
|
|
82
|
+
* throw fails the render. In development React writes into the marked boundary that
|
|
83
|
+
* `renderToString` does not support Suspense; the browser reports it as a recovered hydration
|
|
84
|
+
* error.
|
|
85
|
+
* - The Node stream variant is used because the web-stream `prerender` is only in the Node
|
|
86
|
+
* build from react-dom 19.2, while the peer range allows any React 19.
|
|
87
|
+
*/
|
|
88
|
+
export async function renderReactHtml(runtime, element, options) {
|
|
89
|
+
const budget = renderBudgetStorage.getStore() ?? {
|
|
90
|
+
deadline: Date.now() + options.timeoutMs,
|
|
91
|
+
timeoutMs: options.timeoutMs,
|
|
92
|
+
label: options.label,
|
|
93
|
+
warned: false,
|
|
94
|
+
};
|
|
95
|
+
const controller = new AbortController();
|
|
96
|
+
const timer = setTimeout(() => controller.abort(), Math.max(0, budget.deadline - Date.now()));
|
|
97
|
+
try {
|
|
98
|
+
const { prelude } = await runtime.reactDomStatic.prerenderToNodeStream(element, {
|
|
99
|
+
progressiveChunkSize: Number.POSITIVE_INFINITY,
|
|
100
|
+
signal: controller.signal,
|
|
101
|
+
onError(error) {
|
|
102
|
+
if (controller.signal.aborted && isAbortError(error)) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
console.error(error);
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
const timedOut = controller.signal.aborted;
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
const prerendered = await text(prelude);
|
|
111
|
+
const html = timedOut && prerendered === '' ? renderFallbackHtml(runtime, element, options.label, budget) : prerendered;
|
|
112
|
+
if (timedOut && !budget.warned) {
|
|
113
|
+
budget.warned = true;
|
|
114
|
+
appLogger.warn(`React server rendering of ${budget.label} stopped after ${budget.timeoutMs}ms: a Suspense boundary did not settle in time.`);
|
|
115
|
+
}
|
|
116
|
+
const markup = html.startsWith(DOCTYPE) ? html.slice(DOCTYPE.length) : html;
|
|
117
|
+
assertNoOutlinedSuspenseBoundary(markup, options.label);
|
|
118
|
+
return markup.replace(REVEAL_TIMING_SCRIPT, '');
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function renderFallbackHtml(runtime, element, label, budget) {
|
|
125
|
+
try {
|
|
126
|
+
return runtime.reactDomServer.renderToString(element);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
throw new ReactRenderError(`React server rendering of ${label} produced no HTML: its shell did not finish within the ${budget.timeoutMs}ms render time limit.`, { cause: error });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* React's call that swaps an outlined boundary's hidden segment in, closing its inline script.
|
|
134
|
+
*
|
|
135
|
+
* @remarks
|
|
136
|
+
* React writes boundary and segment ids as hex counters. The hidden segment's wrapper depends on
|
|
137
|
+
* where the boundary sits (`<div hidden>`, `<table hidden>`, `<svg>`), so the reveal call is the
|
|
138
|
+
* one marker every outlined boundary shares.
|
|
139
|
+
*/
|
|
140
|
+
const OUTLINED_BOUNDARY_REVEAL = /\$RC\("B:[0-9a-f]+","S:[0-9a-f]+"\)<\/script>/;
|
|
141
|
+
/**
|
|
142
|
+
* @remarks
|
|
143
|
+
* React still outlines a boundary that renders a `precedence` stylesheet, even
|
|
144
|
+
* with an unbounded `progressiveChunkSize`. `<template id="B:` also marks
|
|
145
|
+
* pending, errored and aborted boundaries that must keep serving their fallback,
|
|
146
|
+
* so this looks for the reveal of a completed segment. Matching React's exact
|
|
147
|
+
* call keeps user markup that mentions `id="S:` or `$RC(` from failing the render.
|
|
148
|
+
*/
|
|
149
|
+
function assertNoOutlinedSuspenseBoundary(html, label) {
|
|
150
|
+
if (OUTLINED_BOUNDARY_REVEAL.test(html)) {
|
|
151
|
+
throw new ReactRenderError(`React server rendering of ${label} moved a Suspense boundary out of line. Declare the stylesheet as a Dependency instead of rendering a link with rel="stylesheet" and a precedence inside the boundary.`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function isAbortError(error) {
|
|
155
|
+
return error instanceof Error && error.name === 'AbortError';
|
|
156
|
+
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { ExportNamedDeclaration } from 'oxc-parser';
|
|
2
|
-
export declare function isPreloadExportStatement(statement: ExportNamedDeclaration): boolean;
|
|
3
|
-
/**
|
|
4
|
-
* Returns whether a module exports a named `preload` binding.
|
|
5
|
-
*
|
|
6
|
-
* @remarks
|
|
7
|
-
* Hydration entries only wire `preload` when this is true, so Pages without
|
|
8
|
-
* that export do not produce a missing-named-import warning.
|
|
9
|
-
*/
|
|
10
|
-
export declare function hasPagePreloadExport(source: string, filename: string): boolean;
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { parseModuleSource } from '@ecopages/core/build';
|
|
2
|
-
export function isPreloadExportStatement(statement) {
|
|
3
|
-
const declaration = statement.declaration;
|
|
4
|
-
if (declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') {
|
|
5
|
-
return declaration.id?.type === 'Identifier' && declaration.id.name === 'preload';
|
|
6
|
-
}
|
|
7
|
-
if (declaration?.type === 'VariableDeclaration') {
|
|
8
|
-
return (declaration.declarations?.some((declarator) => declarator.id.type === 'Identifier' && declarator.id.name === 'preload') ?? false);
|
|
9
|
-
}
|
|
10
|
-
return statement.specifiers.some((specifier) => {
|
|
11
|
-
const exported = specifier.exported;
|
|
12
|
-
return exported.type === 'Identifier' ? exported.name === 'preload' : exported.value === 'preload';
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Returns whether a module exports a named `preload` binding.
|
|
17
|
-
*
|
|
18
|
-
* @remarks
|
|
19
|
-
* Hydration entries only wire `preload` when this is true, so Pages without
|
|
20
|
-
* that export do not produce a missing-named-import warning.
|
|
21
|
-
*/
|
|
22
|
-
export function hasPagePreloadExport(source, filename) {
|
|
23
|
-
try {
|
|
24
|
-
const { program } = parseModuleSource(filename, source);
|
|
25
|
-
return program.body.some((statement) => statement.type === 'ExportNamedDeclaration' && isPreloadExportStatement(statement));
|
|
26
|
-
}
|
|
27
|
-
catch {
|
|
28
|
-
return false;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import type { EcoComponent } from '@ecopages/core';
|
|
2
|
-
export type CollectionComponentCache = {
|
|
3
|
-
preload(slug: string): Promise<void>;
|
|
4
|
-
prime(slug: string, component: Promise<EcoComponent<Record<string, unknown>>>): Promise<void>;
|
|
5
|
-
get(slug: string): EcoComponent<Record<string, unknown>>;
|
|
6
|
-
};
|
|
7
|
-
/**
|
|
8
|
-
* Creates the synchronous component lookup required by a Page that preloads
|
|
9
|
-
* collection MDX before SSR, hydration, and client navigation.
|
|
10
|
-
*
|
|
11
|
-
* @remarks
|
|
12
|
-
* `preload()` loads the browser-compiled component and must not run in
|
|
13
|
-
* `staticProps`. A hydratable collection Page primes the cache in `staticProps`
|
|
14
|
-
* with its server component, then exposes a named `preload` export for
|
|
15
|
-
* hydration and client navigation to load the browser component.
|
|
16
|
-
*
|
|
17
|
-
* Completed loads are deliberately refreshed by the next preload. Native
|
|
18
|
-
* module caching keeps that inexpensive while allowing HMR to replace a
|
|
19
|
-
* component before the Page re-renders.
|
|
20
|
-
*
|
|
21
|
-
* `prime()` always stores the provided server component, even when a
|
|
22
|
-
* `preload()` is already in flight. Completions from a superseded load are
|
|
23
|
-
* ignored so they cannot replace the primed entry.
|
|
24
|
-
*/
|
|
25
|
-
export declare function createCollectionComponentCache(loadComponent: (slug: string) => Promise<EcoComponent<Record<string, unknown>>>): CollectionComponentCache;
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Creates the synchronous component lookup required by a Page that preloads
|
|
3
|
-
* collection MDX before SSR, hydration, and client navigation.
|
|
4
|
-
*
|
|
5
|
-
* @remarks
|
|
6
|
-
* `preload()` loads the browser-compiled component and must not run in
|
|
7
|
-
* `staticProps`. A hydratable collection Page primes the cache in `staticProps`
|
|
8
|
-
* with its server component, then exposes a named `preload` export for
|
|
9
|
-
* hydration and client navigation to load the browser component.
|
|
10
|
-
*
|
|
11
|
-
* Completed loads are deliberately refreshed by the next preload. Native
|
|
12
|
-
* module caching keeps that inexpensive while allowing HMR to replace a
|
|
13
|
-
* component before the Page re-renders.
|
|
14
|
-
*
|
|
15
|
-
* `prime()` always stores the provided server component, even when a
|
|
16
|
-
* `preload()` is already in flight. Completions from a superseded load are
|
|
17
|
-
* ignored so they cannot replace the primed entry.
|
|
18
|
-
*/
|
|
19
|
-
export function createCollectionComponentCache(loadComponent) {
|
|
20
|
-
const records = new Map();
|
|
21
|
-
const store = async (slug, component) => {
|
|
22
|
-
const pending = {};
|
|
23
|
-
const promise = component.then((resolvedComponent) => {
|
|
24
|
-
if (records.get(slug) === pending.record) {
|
|
25
|
-
records.set(slug, { status: 'success', component: resolvedComponent });
|
|
26
|
-
}
|
|
27
|
-
}, (error) => {
|
|
28
|
-
if (records.get(slug) === pending.record) {
|
|
29
|
-
records.set(slug, { status: 'error', error });
|
|
30
|
-
}
|
|
31
|
-
throw error;
|
|
32
|
-
});
|
|
33
|
-
pending.record = { status: 'pending', promise };
|
|
34
|
-
records.set(slug, pending.record);
|
|
35
|
-
return await promise;
|
|
36
|
-
};
|
|
37
|
-
return {
|
|
38
|
-
async preload(slug) {
|
|
39
|
-
const existing = records.get(slug);
|
|
40
|
-
if (existing?.status === 'pending') {
|
|
41
|
-
return await existing.promise;
|
|
42
|
-
}
|
|
43
|
-
return await store(slug, loadComponent(slug));
|
|
44
|
-
},
|
|
45
|
-
async prime(slug, component) {
|
|
46
|
-
return await store(slug, component);
|
|
47
|
-
},
|
|
48
|
-
get(slug) {
|
|
49
|
-
const record = records.get(slug);
|
|
50
|
-
if (!record) {
|
|
51
|
-
throw new Error(`[ecopages] Collection content '${slug}' was rendered before it was preloaded.`);
|
|
52
|
-
}
|
|
53
|
-
if (record.status === 'success') {
|
|
54
|
-
return record.component;
|
|
55
|
-
}
|
|
56
|
-
if (record.status === 'error') {
|
|
57
|
-
throw record.error;
|
|
58
|
-
}
|
|
59
|
-
throw new Error(`[ecopages] Collection content '${slug}' is still loading during render.`);
|
|
60
|
-
},
|
|
61
|
-
};
|
|
62
|
-
}
|