@ecopages/react 0.2.0-beta.2 → 0.2.0-beta.20

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.
Files changed (30) hide show
  1. package/README.md +12 -0
  2. package/package.json +21 -4
  3. package/src/layout-compose.d.ts +58 -0
  4. package/src/layout-compose.js +98 -0
  5. package/src/react-hmr-strategy.d.ts +14 -0
  6. package/src/react-hmr-strategy.js +134 -108
  7. package/src/react-renderer.d.ts +34 -13
  8. package/src/react-renderer.js +187 -84
  9. package/src/react.plugin.js +6 -27
  10. package/src/serialize-page-data-script.d.ts +8 -0
  11. package/src/serialize-page-data-script.js +10 -0
  12. package/src/services/react-bundle.service.d.ts +3 -2
  13. package/src/services/react-bundle.service.js +17 -8
  14. package/src/services/react-mdx-config-dependency.service.js +5 -7
  15. package/src/services/react-page-module.service.d.ts +4 -43
  16. package/src/services/react-page-module.service.js +0 -90
  17. package/src/services/react-page-payload.service.js +2 -2
  18. package/src/services/react-runtime-bundle.service.d.ts +5 -1
  19. package/src/services/react-runtime-bundle.service.js +8 -2
  20. package/src/utils/client-graph-ast-transform.d.ts +18 -0
  21. package/src/utils/client-graph-ast-transform.js +335 -0
  22. package/src/utils/client-graph-boundary-plugin.d.ts +1 -12
  23. package/src/utils/client-graph-boundary-plugin.js +8 -454
  24. package/src/utils/client-graph-reachability.d.ts +75 -0
  25. package/src/utils/client-graph-reachability.js +148 -0
  26. package/src/utils/component-config-traversal.js +4 -2
  27. package/src/utils/hydration-scripts.d.ts +2 -0
  28. package/src/utils/hydration-scripts.js +27 -14
  29. package/src/utils/react-mdx-loader-plugin.d.ts +2 -3
  30. package/src/utils/react-mdx-loader-plugin.js +5 -39
package/README.md CHANGED
@@ -206,3 +206,15 @@ The main regression coverage lives in:
206
206
  - [../../react-router/test/hmr-reload.test.browser.ts](../../react-router/test/hmr-reload.test.browser.ts): verifies router-backed layout hydration receives `locals` with `persistLayouts` both enabled and disabled.
207
207
 
208
208
  If you change the AST transform or hydration flow, update the corresponding tests in the same change.
209
+
210
+ ### Nested layouts and unified SSR
211
+
212
+ Pages may declare `layout` as a single component or an **outer → inner** array on `eco.page()`. On the server, React-managed layout stacks compose through `composeDocumentShell` + `composeLayoutPageTree` so provider context reaches nested pages during SSR. On the client, `@ecopages/react-router` `PageContent` uses the same `composeLayoutPageTree` helper unless `persistLayouts` is enabled (then each tier is cached independently).
213
+
214
+ During SSR, `ReactRenderer` passes the app-resolved React runtime into `composeLayoutPageTree` via `options.react` so layout trees are built with the same module instance as `renderToString`. App code should import hooks and context from `react` normally; keep a single React version in the app dependency graph (avoid duplicate `react` copies in monorepos).
215
+
216
+ Layout prop factories receive `LayoutPropsContext` (`params`, `query`, `locals`). Route-scoped `locals` are passed to layout tiers via document-shell props during SSR; serialized `pageProps.locals` follow `Page.requires` and are intended for the page component.
217
+
218
+ - [src/layout-compose.ts](src/layout-compose.ts): shared client/SSR tree builder.
219
+ - [src/test/react-ssr-hydration-parity.test.tsx](src/test/react-ssr-hydration-parity.test.tsx): nested tier order parity between SSR and `composeLayoutPageTree`.
220
+ - [src/test/react-ssr-unified.test.tsx](src/test/react-ssr-unified.test.tsx): provider context through nested SSR layouts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/react",
3
- "version": "0.2.0-beta.2",
3
+ "version": "0.2.0-beta.20",
4
4
  "description": "React integration for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -39,6 +39,14 @@
39
39
  "types": "./src/router-adapter.d.ts",
40
40
  "default": "./src/router-adapter.js"
41
41
  },
42
+ "./layout-compose": {
43
+ "types": "./src/layout-compose.d.ts",
44
+ "default": "./src/layout-compose.js"
45
+ },
46
+ "./serialize-page-data-script": {
47
+ "types": "./src/serialize-page-data-script.d.ts",
48
+ "default": "./src/serialize-page-data-script.js"
49
+ },
42
50
  "./eco-embed.ts": {
43
51
  "default": "./src/eco-embed.js",
44
52
  "types": "./src/eco-embed.d.ts"
@@ -61,23 +69,32 @@
61
69
  "./router-adapter.ts": {
62
70
  "types": "./src/router-adapter.d.ts",
63
71
  "default": "./src/router-adapter.js"
72
+ },
73
+ "./layout-compose.ts": {
74
+ "types": "./src/layout-compose.d.ts",
75
+ "default": "./src/layout-compose.js"
76
+ },
77
+ "./serialize-page-data-script.ts": {
78
+ "types": "./src/serialize-page-data-script.d.ts",
79
+ "default": "./src/serialize-page-data-script.js"
64
80
  }
65
81
  },
66
82
  "repository": {
67
83
  "type": "git",
68
- "url": "https://github.com/ecopages/ecopages.git",
84
+ "url": "git+https://github.com/ecopages/ecopages.git",
69
85
  "directory": "packages/integrations/react"
70
86
  },
71
87
  "peerDependencies": {
72
- "@ecopages/core": "0.2.0-beta.2",
88
+ "@ecopages/core": "0.2.0-beta.20",
73
89
  "@types/react": "^19",
74
90
  "@types/react-dom": "^19",
75
91
  "react": "^19",
76
92
  "react-dom": "^19"
77
93
  },
78
94
  "dependencies": {
79
- "@ecopages/file-system": "0.2.0-beta.2",
95
+ "@ecopages/file-system": "0.2.0-beta.20",
80
96
  "@ecopages/logger": "^0.2.3",
97
+ "@ecopages/mdx": "0.2.0-beta.20",
81
98
  "@mdx-js/mdx": "^3.1.1",
82
99
  "oxc-parser": "^0.124.0",
83
100
  "oxc-transform": "^0.124.0",
@@ -0,0 +1,58 @@
1
+ import * as bundledReact from 'react';
2
+ import type { FunctionComponent, ReactElement } from 'react';
3
+ import type { EcoComponent, EcoDeclaredComponent, EcoPageLayoutEntry, LayoutPropsContext } from '@ecopages/core';
4
+ import type { EcoComponentConfig } from '@ecopages/core';
5
+ export type LayoutComposeContext = LayoutPropsContext;
6
+ export type ReactRuntime = typeof bundledReact;
7
+ export type LayoutComposeOptions = {
8
+ context?: LayoutComposeContext;
9
+ /** @remarks Pass the app-resolved React runtime during SSR so composition matches `renderToString`. */
10
+ react?: ReactRuntime;
11
+ };
12
+ export type LayoutShellEntry = {
13
+ component: EcoComponent;
14
+ props?: Record<string, unknown>;
15
+ };
16
+ export type ComposablePage<P extends Record<string, unknown> = Record<string, unknown>> = FunctionComponent<P> & {
17
+ config?: Pick<EcoComponentConfig, 'layouts' | 'layoutEntries'>;
18
+ };
19
+ /**
20
+ * Reads request-scoped layout context from serialized page props.
21
+ */
22
+ export declare function resolveLayoutContext(pageProps: Record<string, unknown>): LayoutComposeContext;
23
+ /**
24
+ * Builds layout prop factory context from document-shell layout entries.
25
+ *
26
+ * @remarks
27
+ * Route-scoped `locals` come from shell layout props, not `pageProps.locals` (pageLocals).
28
+ */
29
+ export declare function resolveLayoutContextFromShell(pageProps: Record<string, unknown>, shellLayouts: LayoutShellEntry[]): LayoutComposeContext;
30
+ /**
31
+ * Resolves props for one layout entry, merging shell locals with an optional factory.
32
+ */
33
+ export declare function resolveLayoutEntryProps(entry: EcoPageLayoutEntry, context: LayoutComposeContext): Record<string, unknown>;
34
+ /**
35
+ * @remarks
36
+ * Eco page components are wider than React layout composition input; runtime checks narrow callables.
37
+ */
38
+ export declare function assertComposablePage(Page: unknown): ComposablePage;
39
+ /**
40
+ * Builds the client or SSR React tree for a page and its outer→inner layout stack.
41
+ *
42
+ * @remarks
43
+ * Layout prop factories receive `LayoutPropsContext`. For SSR, pass `options.react` from the
44
+ * app-resolved runtime. Client code can omit it and use the bundled React import.
45
+ */
46
+ export declare function composeLayoutPageTree<P extends Record<string, unknown>>(Page: ComposablePage<P>, pageProps: P, options?: LayoutComposeOptions): ReactElement;
47
+ /**
48
+ * Builds a layout tree from explicit document-shell layout entries.
49
+ *
50
+ * @remarks
51
+ * Use when the route renderer passes per-tier props (e.g. route `locals` on the layout tier).
52
+ * Shell `entry.props` are authoritative; page config normalization is not required.
53
+ */
54
+ export declare function composeLayoutPageTreeFromShell<P extends Record<string, unknown>>(Page: ComposablePage<P>, pageProps: P, shellLayouts: LayoutShellEntry[], options?: LayoutComposeOptions): ReactElement;
55
+ /**
56
+ * Normalizes page config layout metadata to an outer→inner component list.
57
+ */
58
+ export declare function normalizePageLayoutComponents(layouts?: EcoDeclaredComponent[]): EcoDeclaredComponent[];
@@ -0,0 +1,98 @@
1
+ import * as bundledReact from "react";
2
+ function resolveReact(options) {
3
+ return options?.react ?? bundledReact;
4
+ }
5
+ function toReactComponent(component) {
6
+ if (typeof component !== "function") {
7
+ throw new TypeError("[ecopages] Expected a function component for layout composition.");
8
+ }
9
+ return component;
10
+ }
11
+ function resolveLayoutContext(pageProps) {
12
+ const context = {};
13
+ if (pageProps.params !== void 0) {
14
+ context.params = pageProps.params;
15
+ }
16
+ if (pageProps.query !== void 0) {
17
+ context.query = pageProps.query;
18
+ }
19
+ if (pageProps.locals !== void 0) {
20
+ context.locals = pageProps.locals;
21
+ }
22
+ return context;
23
+ }
24
+ function resolveLayoutContextFromShell(pageProps, shellLayouts) {
25
+ const context = {};
26
+ if (pageProps.params !== void 0) {
27
+ context.params = pageProps.params;
28
+ }
29
+ if (pageProps.query !== void 0) {
30
+ context.query = pageProps.query;
31
+ }
32
+ for (const entry of shellLayouts) {
33
+ if (entry.props !== void 0 && Object.prototype.hasOwnProperty.call(entry.props, "locals")) {
34
+ context.locals = entry.props.locals;
35
+ break;
36
+ }
37
+ }
38
+ return context;
39
+ }
40
+ function resolveLayoutEntryProps(entry, context) {
41
+ const shellProps = context.locals ? { locals: context.locals } : {};
42
+ if (!entry.props) {
43
+ return shellProps;
44
+ }
45
+ return {
46
+ ...shellProps,
47
+ ...entry.props(context)
48
+ };
49
+ }
50
+ function assertComposablePage(Page) {
51
+ if (typeof Page !== "function") {
52
+ throw new TypeError("[ecopages] Expected a function page component for layout composition.");
53
+ }
54
+ return Page;
55
+ }
56
+ function composeLayoutPageTree(Page, pageProps, options) {
57
+ const { createElement } = resolveReact(options);
58
+ const context = options?.context ?? resolveLayoutContext(pageProps);
59
+ const pageElement = createElement(Page, pageProps);
60
+ const layoutEntries = Page.config?.layoutEntries;
61
+ if (layoutEntries && layoutEntries.length > 0) {
62
+ return [...layoutEntries].reverse().reduce((children, entry) => {
63
+ const layoutProps = resolveLayoutEntryProps(entry, context);
64
+ return createElement(toReactComponent(entry.component), layoutProps, children);
65
+ }, pageElement);
66
+ }
67
+ const layouts = Page.config?.layouts;
68
+ if (layouts && layouts.length > 0) {
69
+ const layoutProps = context.locals ? { locals: context.locals } : {};
70
+ return [...layouts].reverse().reduce(
71
+ (children, Layout) => createElement(toReactComponent(Layout), layoutProps, children),
72
+ pageElement
73
+ );
74
+ }
75
+ return pageElement;
76
+ }
77
+ function composeLayoutPageTreeFromShell(Page, pageProps, shellLayouts, options) {
78
+ const { createElement } = resolveReact(options);
79
+ if (shellLayouts.length === 0) {
80
+ return composeLayoutPageTree(Page, pageProps, options);
81
+ }
82
+ const pageElement = createElement(Page, pageProps);
83
+ return [...shellLayouts].reverse().reduce((children, entry) => {
84
+ return createElement(toReactComponent(entry.component), entry.props ?? {}, children);
85
+ }, pageElement);
86
+ }
87
+ function normalizePageLayoutComponents(layouts) {
88
+ return layouts && layouts.length > 0 ? layouts : [];
89
+ }
90
+ export {
91
+ assertComposablePage,
92
+ composeLayoutPageTree,
93
+ composeLayoutPageTreeFromShell,
94
+ normalizePageLayoutComponents,
95
+ resolveLayoutContext,
96
+ resolveLayoutContextFromShell,
97
+ resolveLayoutEntryProps
98
+ };
@@ -171,6 +171,19 @@ export declare class ReactHmrStrategy extends HmrStrategy {
171
171
  * @returns Action to broadcast update events (layout-update for layouts, update for components)
172
172
  */
173
173
  process(_filePath: string): Promise<HmrAction>;
174
+ /**
175
+ * Clears stale HMR output once per outdir before any rebuild pass in `process()`.
176
+ *
177
+ * @remarks
178
+ * Grouped page builds share `getDistDir()`; single page and non-page targets use
179
+ * per-entrypoint temp directories. Clearing here avoids redundant work when both
180
+ * page and non-page targets land in the same outdir.
181
+ */
182
+ private clearOutdirsForTargets;
183
+ private resolveDeclaredModulesForEntrypoint;
184
+ private collectDeclaredModulesForTargets;
185
+ private buildPluginsForDeclaredModules;
186
+ private recordBuildDependencyGraph;
174
187
  /**
175
188
  * Bundles a single React/MDX entrypoint with HMR support.
176
189
  *
@@ -195,6 +208,7 @@ export declare class ReactHmrStrategy extends HmrStrategy {
195
208
  * @returns Array of output URLs that were successfully built
196
209
  */
197
210
  private bundleReactEntrypoints;
211
+ private bundleReactBuildTargets;
198
212
  private resolveTempOutputPath;
199
213
  /**
200
214
  * Clears stale HMR output from a directory before a rebuild.
@@ -126,7 +126,7 @@ class ReactHmrStrategy extends HmrStrategy {
126
126
  }
127
127
  pageModuleRequiresLayoutRefresh(pageModule, filePath) {
128
128
  return [pageModule.default?.config, pageModule.config].some((config) => {
129
- return this.configContainsFile(config?.layout?.config, filePath);
129
+ return (config?.layouts ?? []).some((layout) => this.configContainsFile(layout?.config, filePath));
130
130
  });
131
131
  }
132
132
  async hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets) {
@@ -338,6 +338,7 @@ class ReactHmrStrategy extends HmrStrategy {
338
338
  hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(_filePath, requestedTargets);
339
339
  }
340
340
  const requiresLayoutRefresh = isLayout || hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
341
+ await this.clearOutdirsForTargets(pageTargets, nonPageTargets);
341
342
  const updates = [];
342
343
  const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
343
344
  if (pageTargets.length > 1) {
@@ -392,6 +393,67 @@ class ReactHmrStrategy extends HmrStrategy {
392
393
  appLogger.debug(`No updates generated`);
393
394
  return { type: "none" };
394
395
  }
396
+ /**
397
+ * Clears stale HMR output once per outdir before any rebuild pass in `process()`.
398
+ *
399
+ * @remarks
400
+ * Grouped page builds share `getDistDir()`; single page and non-page targets use
401
+ * per-entrypoint temp directories. Clearing here avoids redundant work when both
402
+ * page and non-page targets land in the same outdir.
403
+ */
404
+ async clearOutdirsForTargets(pageTargets, nonPageTargets) {
405
+ const outdirs = /* @__PURE__ */ new Set();
406
+ if (pageTargets.length > 1) {
407
+ outdirs.add(this.context.getDistDir());
408
+ } else {
409
+ for (const { entrypointPath } of pageTargets) {
410
+ outdirs.add(path.dirname(this.getEntrypointOutput(entrypointPath).outputPath));
411
+ }
412
+ }
413
+ for (const { entrypointPath } of nonPageTargets) {
414
+ outdirs.add(path.dirname(this.getEntrypointOutput(entrypointPath).outputPath));
415
+ }
416
+ await Promise.all([...outdirs].map((outdir) => this.clearHmrOutdir(outdir)));
417
+ }
418
+ async resolveDeclaredModulesForEntrypoint(entrypointPath) {
419
+ const cached = this.pageMetadataCache.getDeclaredModules(entrypointPath);
420
+ if (cached) {
421
+ return cached;
422
+ }
423
+ const declaredModules = entrypointPath.endsWith(".mdx") ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
424
+ this.pageMetadataCache.setDeclaredModules(entrypointPath, declaredModules);
425
+ return declaredModules;
426
+ }
427
+ async collectDeclaredModulesForTargets(targets) {
428
+ const declaredModules = /* @__PURE__ */ new Set();
429
+ let shouldEnableMdx = false;
430
+ for (const { entrypointPath } of targets) {
431
+ const entrypointDeclaredModules = await this.resolveDeclaredModulesForEntrypoint(entrypointPath);
432
+ for (const declaredModule of entrypointDeclaredModules) {
433
+ declaredModules.add(declaredModule);
434
+ }
435
+ if (entrypointPath.endsWith(".mdx")) {
436
+ shouldEnableMdx = true;
437
+ }
438
+ }
439
+ return { declaredModules: [...declaredModules], shouldEnableMdx };
440
+ }
441
+ buildPluginsForDeclaredModules(declaredModules, shouldEnableMdx) {
442
+ const plugins = this.getBuildPlugins(declaredModules);
443
+ if (shouldEnableMdx && this.mdxCompilerOptions) {
444
+ plugins.unshift(createReactMdxLoaderPlugin(this.mdxCompilerOptions));
445
+ }
446
+ return plugins;
447
+ }
448
+ recordBuildDependencyGraph(result) {
449
+ if (!result.dependencyGraph?.entrypoints) {
450
+ return;
451
+ }
452
+ const dependencyGraph = this.context.getEntrypointDependencyGraph();
453
+ for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
454
+ dependencyGraph.setEntrypointDependencies(entrypoint, deps);
455
+ }
456
+ }
395
457
  /**
396
458
  * Bundles a single React/MDX entrypoint with HMR support.
397
459
  *
@@ -405,61 +467,8 @@ class ReactHmrStrategy extends HmrStrategy {
405
467
  * @returns True if bundling was successful
406
468
  */
407
469
  async bundleReactEntrypoint(entrypointPath, outputUrl) {
408
- try {
409
- const isMdx = entrypointPath.endsWith(".mdx");
410
- const { outputPath } = this.getEntrypointOutput(entrypointPath);
411
- const tempDir = path.dirname(outputPath);
412
- const cachedDeclared = this.pageMetadataCache.getDeclaredModules(entrypointPath);
413
- let entrypointDeclaredModules;
414
- let declaredModules;
415
- if (cachedDeclared) {
416
- entrypointDeclaredModules = cachedDeclared;
417
- declaredModules = cachedDeclared;
418
- } else {
419
- entrypointDeclaredModules = isMdx ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
420
- this.pageMetadataCache.setDeclaredModules(entrypointPath, entrypointDeclaredModules);
421
- declaredModules = entrypointDeclaredModules;
422
- }
423
- const plugins = this.getBuildPlugins(declaredModules);
424
- if (isMdx && this.mdxCompilerOptions) {
425
- const mdxPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
426
- plugins.unshift(mdxPlugin);
427
- }
428
- await this.clearHmrOutdir(tempDir);
429
- const result = await this.context.getBrowserBundleService().bundle({
430
- profile: "hmr-entrypoint",
431
- entrypoints: [entrypointPath],
432
- outdir: tempDir,
433
- naming: `[name].[hash].tmp`,
434
- plugins,
435
- minify: false
436
- });
437
- if (!result.success) {
438
- appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
439
- return false;
440
- }
441
- if (result.dependencyGraph?.entrypoints) {
442
- const dependencyGraph = this.context.getEntrypointDependencyGraph();
443
- for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
444
- dependencyGraph.setEntrypointDependencies(entrypoint, deps);
445
- }
446
- }
447
- const tempFile = result.outputs[0]?.path;
448
- if (!tempFile) {
449
- appLogger.error(`No output file generated for ${entrypointPath}`);
450
- return false;
451
- }
452
- const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
453
- if (!resolvedTempFile) {
454
- appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
455
- return false;
456
- }
457
- const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
458
- return processed;
459
- } catch (error) {
460
- appLogger.error(`Error bundling ${entrypointPath}:`, error);
461
- return false;
462
- }
470
+ const rebuiltOutputs = await this.bundleReactBuildTargets([{ entrypointPath, outputUrl }], { grouped: false });
471
+ return rebuiltOutputs.length > 0;
463
472
  }
464
473
  /**
465
474
  * Bundles multiple React/MDX entrypoints in a single build pass.
@@ -472,73 +481,90 @@ class ReactHmrStrategy extends HmrStrategy {
472
481
  * @returns Array of output URLs that were successfully built
473
482
  */
474
483
  async bundleReactEntrypoints(entrypoints) {
484
+ return this.bundleReactBuildTargets(entrypoints, { grouped: true });
485
+ }
486
+ async bundleReactBuildTargets(targets, options) {
487
+ if (targets.length === 0) {
488
+ return [];
489
+ }
475
490
  try {
476
- const declaredModules = /* @__PURE__ */ new Set();
477
- let shouldEnableMdx = false;
478
- for (const { entrypointPath } of entrypoints) {
479
- const entrypointDeclaredModules = this.pageMetadataCache.getDeclaredModules(entrypointPath) ? this.pageMetadataCache.getDeclaredModules(entrypointPath) : entrypointPath.endsWith(".mdx") ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
480
- this.pageMetadataCache.setDeclaredModules(entrypointPath, entrypointDeclaredModules);
481
- for (const declaredModule of entrypointDeclaredModules) {
482
- declaredModules.add(declaredModule);
483
- }
484
- if (entrypointPath.endsWith(".mdx")) {
485
- shouldEnableMdx = true;
491
+ const { declaredModules, shouldEnableMdx } = await this.collectDeclaredModulesForTargets(targets);
492
+ const plugins = this.buildPluginsForDeclaredModules(declaredModules, shouldEnableMdx);
493
+ if (options.grouped) {
494
+ const entryNameByPath = /* @__PURE__ */ new Map();
495
+ for (const { entrypointPath: entrypointPath2 } of targets) {
496
+ entryNameByPath.set(entrypointPath2, {
497
+ key: this.getRolldownEntryKey(entrypointPath2),
498
+ basename: this.getTempFileBasename(entrypointPath2)
499
+ });
486
500
  }
487
- }
488
- const plugins = this.getBuildPlugins([...declaredModules]);
489
- if (shouldEnableMdx && this.mdxCompilerOptions) {
490
- plugins.unshift(createReactMdxLoaderPlugin(this.mdxCompilerOptions));
491
- }
492
- await this.clearHmrOutdir(this.context.getDistDir());
493
- const entryNameByPath = /* @__PURE__ */ new Map();
494
- for (const { entrypointPath } of entrypoints) {
495
- entryNameByPath.set(entrypointPath, {
496
- key: this.getRolldownEntryKey(entrypointPath),
497
- basename: this.getTempFileBasename(entrypointPath)
501
+ const result2 = await this.context.getBrowserBundleService().bundle({
502
+ profile: "hmr-entrypoint",
503
+ entrypoints: Object.fromEntries(
504
+ targets.map(({ entrypointPath: entrypointPath2 }) => [entryNameByPath.get(entrypointPath2).key, entrypointPath2])
505
+ ),
506
+ outdir: this.context.getDistDir(),
507
+ naming: "[name].[hash].tmp",
508
+ splitting: true,
509
+ plugins,
510
+ minify: false
498
511
  });
512
+ if (!result2.success) {
513
+ appLogger.error(`Failed to build grouped React entrypoints:`, result2.logs);
514
+ return [];
515
+ }
516
+ this.recordBuildDependencyGraph(result2);
517
+ const updatedOutputs = [];
518
+ for (const { entrypointPath: entrypointPath2, outputUrl: outputUrl2 } of targets) {
519
+ const { outputPath: outputPath2 } = this.getEntrypointOutput(entrypointPath2);
520
+ const { basename: tempBasename, key: entryKey } = entryNameByPath.get(entrypointPath2);
521
+ const expectedSubdir = path.join(this.context.getDistDir(), path.dirname(entryKey));
522
+ const tempOutput = result2.outputs.find((output) => {
523
+ return path.dirname(output.path) === expectedSubdir && path.basename(output.path).startsWith(`${tempBasename}.`) && path.basename(output.path).includes(".tmp");
524
+ })?.path;
525
+ const resolvedTempOutput = tempOutput ? await this.resolveTempOutputPath(tempOutput) : await this.resolveTempOutputPath(path.join(expectedSubdir, `${tempBasename}.[hash].tmp.js`));
526
+ if (!resolvedTempOutput) {
527
+ appLogger.debug(`Missing grouped temp output for ${outputUrl2}`);
528
+ continue;
529
+ }
530
+ const processed2 = await this.processOutput(resolvedTempOutput, outputPath2, outputUrl2);
531
+ if (processed2) {
532
+ updatedOutputs.push(outputUrl2);
533
+ }
534
+ }
535
+ return updatedOutputs;
499
536
  }
537
+ const { entrypointPath, outputUrl } = targets[0];
538
+ const { outputPath } = this.getEntrypointOutput(entrypointPath);
539
+ const tempDir = path.dirname(outputPath);
500
540
  const result = await this.context.getBrowserBundleService().bundle({
501
541
  profile: "hmr-entrypoint",
502
- entrypoints: Object.fromEntries(
503
- entrypoints.map(({ entrypointPath }) => [entryNameByPath.get(entrypointPath).key, entrypointPath])
504
- ),
505
- outdir: this.context.getDistDir(),
506
- naming: "[name].[hash].tmp",
507
- splitting: true,
542
+ entrypoints: [entrypointPath],
543
+ outdir: tempDir,
544
+ naming: `[name].[hash].tmp`,
508
545
  plugins,
509
546
  minify: false
510
547
  });
511
548
  if (!result.success) {
512
- appLogger.error(`Failed to build grouped React entrypoints:`, result.logs);
549
+ appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
513
550
  return [];
514
551
  }
515
- if (result.dependencyGraph?.entrypoints) {
516
- const dependencyGraph = this.context.getEntrypointDependencyGraph();
517
- for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
518
- dependencyGraph.setEntrypointDependencies(entrypoint, deps);
519
- }
552
+ this.recordBuildDependencyGraph(result);
553
+ const tempFile = result.outputs[0]?.path;
554
+ if (!tempFile) {
555
+ appLogger.error(`No output file generated for ${entrypointPath}`);
556
+ return [];
520
557
  }
521
- const updatedOutputs = [];
522
- for (const { entrypointPath, outputUrl } of entrypoints) {
523
- const { outputPath } = this.getEntrypointOutput(entrypointPath);
524
- const { basename: tempBasename, key: entryKey } = entryNameByPath.get(entrypointPath);
525
- const expectedSubdir = path.join(this.context.getDistDir(), path.dirname(entryKey));
526
- const tempOutput = result.outputs.find((output) => {
527
- return path.dirname(output.path) === expectedSubdir && path.basename(output.path).startsWith(`${tempBasename}.`) && path.basename(output.path).includes(".tmp");
528
- })?.path;
529
- const resolvedTempOutput = tempOutput ? await this.resolveTempOutputPath(tempOutput) : await this.resolveTempOutputPath(path.join(expectedSubdir, `${tempBasename}.[hash].tmp.js`));
530
- if (!resolvedTempOutput) {
531
- appLogger.debug(`Missing grouped temp output for ${outputUrl}`);
532
- continue;
533
- }
534
- const processed = await this.processOutput(resolvedTempOutput, outputPath, outputUrl);
535
- if (processed) {
536
- updatedOutputs.push(outputUrl);
537
- }
558
+ const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
559
+ if (!resolvedTempFile) {
560
+ appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
561
+ return [];
538
562
  }
539
- return updatedOutputs;
563
+ const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
564
+ return processed ? [outputUrl] : [];
540
565
  } catch (error) {
541
- appLogger.error(`Error bundling grouped React entrypoints:`, error);
566
+ const label = options.grouped ? "grouped React entrypoints" : targets[0]?.entrypointPath ?? "React entrypoint";
567
+ appLogger.error(`Error bundling ${label}:`, error);
542
568
  return [];
543
569
  }
544
570
  }
@@ -2,8 +2,8 @@
2
2
  * This module contains the React renderer
3
3
  * @module
4
4
  */
5
- import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, IntegrationRendererRenderOptions, RouteRendererBody } from '@ecopages/core';
6
- import { IntegrationRenderer, type HtmlDocumentContribution, type HtmlDocumentContributionContext, type PageBrowserGraphContributionContext, type RenderToResponseContext, type RouteModuleLoadOptions } from '@ecopages/core/route-renderer/integration-renderer';
5
+ import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, IntegrationRendererRenderOptions, PageMetadataProps, RouteRendererBody } from '@ecopages/core';
6
+ import { IntegrationRenderer, type HtmlDocumentContribution, type HtmlDocumentContributionContext, type PageBrowserGraphContributionContext, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
7
7
  import type { AssetDefinition, ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
8
8
  import type { ReactNode } from 'react';
9
9
  import type { ReactRendererConfig } from './react.types.js';
@@ -12,10 +12,12 @@ import { ReactMdxConfigDependencyService } from './services/react-mdx-config-dep
12
12
  import { ReactPageModuleService } from './services/react-page-module.service.js';
13
13
  import { ReactPagePayloadService } from './services/react-page-payload.service.js';
14
14
  import { ReactHydrationAssetService } from './services/react-hydration-asset.service.js';
15
+ import { type DocumentShellLayoutInput } from '@ecopages/core/route-renderer/orchestration/document-shell-render.service';
16
+ import { type ReactRuntime } from './layout-compose.js';
15
17
  export type { ReactRendererConfig } from './react.types.js';
16
18
  type ReactRuntimeModules = {
17
- react: Pick<typeof import('react'), 'createElement' | 'Fragment'>;
18
- reactDomServer: Pick<typeof import('react-dom/server'), 'renderToReadableStream' | 'renderToString'>;
19
+ react: ReactRuntime;
20
+ reactDomServer: typeof import('react-dom/server');
19
21
  };
20
22
  export type ReactRendererOptions = ConstructorParameters<typeof IntegrationRenderer>[0] & {
21
23
  reactConfig?: ReactRendererConfig;
@@ -128,8 +130,8 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
128
130
  * @returns Serialized component HTML with resolved child markup preserved.
129
131
  */
130
132
  private renderComponentHtml;
133
+ private toReactNode;
131
134
  /**
132
- * Restores raw child HTML that was temporarily replaced by a token during React SSR.
133
135
  *
134
136
  * Queued foreign-subtree resolution may render children through a fragment path before all
135
137
  * nested integration tokens are resolved. When that happens, React must never see
@@ -149,13 +151,9 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
149
151
  private renderQueuedChildrenToHtml;
150
152
  /**
151
153
  * Resolves queued renderer-owned foreign-subtree tokens produced during React component rendering.
152
- *
153
- * React components can enqueue nested foreign subtrees while the parent HTML is being
154
- * rendered. This delegates to the shared renderer-owned queue resolver but keeps
155
- * the React-specific child rendering behavior local so raw child HTML and React's
156
- * fragment rendering semantics stay coordinated.
157
154
  */
158
- private resolveQueuedForeignSubtreeHtml;
155
+ private renderReactQueuedForeignSubtreeChildren;
156
+ private resolveReactQueuedForeignSubtreeHtml;
159
157
  private buildHydrationProps;
160
158
  /**
161
159
  * Builds shared document html contributions for router-backed React pages rendered
@@ -203,13 +201,30 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
203
201
  * @returns True if the file is an MDX file
204
202
  */
205
203
  isMdxFile(filePath: string): boolean;
206
- protected usesIntegrationPageImporter(file: string): boolean;
207
- protected importIntegrationPageFile(file: string, options?: RouteModuleLoadOptions): Promise<EcoPageFile>;
208
204
  protected normalizeImportedPageFile<TPageModule extends EcoPageFile>(file: string, pageModule: TPageModule): TPageModule;
209
205
  protected collectPageBrowserGraphContribution(context: PageBrowserGraphContributionContext): Promise<{
210
206
  dependencies?: AssetDefinition[];
211
207
  assets?: ProcessedAsset[];
212
208
  }>;
209
+ /**
210
+ * Composes page and layout tiers as one React element tree for SSR.
211
+ */
212
+ private composeReactLayoutPageChildren;
213
+ private composeReactLayoutPageTree;
214
+ private shouldUseUnifiedReactLayoutComposition;
215
+ protected renderPageWithDocumentShell(input: {
216
+ page: {
217
+ component: EcoComponent;
218
+ props: Record<string, unknown>;
219
+ };
220
+ layout?: DocumentShellLayoutInput;
221
+ layouts?: DocumentShellLayoutInput[];
222
+ htmlTemplate: EcoComponent;
223
+ metadata: PageMetadataProps;
224
+ pageProps: Record<string, unknown>;
225
+ documentProps?: Record<string, unknown>;
226
+ transformDocumentHtml?: (html: string) => string;
227
+ }): Promise<string>;
213
228
  /**
214
229
  * Renders a full route response for the filesystem page pipeline.
215
230
  *
@@ -221,6 +236,12 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
221
236
  render({ params, query, props, locals, pageLocals, metadata, Page, Layout, HtmlTemplate, pageProps, }: IntegrationRendererRenderOptions<ReactNode>): Promise<RouteRendererBody>;
222
237
  protected getHtmlDocumentContributions(options: HtmlDocumentContributionContext<ReactNode>): HtmlDocumentContribution[] | undefined;
223
238
  protected getDocumentAttributes(): Record<string, string> | undefined;
239
+ protected renderViewWithDocumentShell<P>(input: {
240
+ view: EcoComponent<P>;
241
+ props: P;
242
+ ctx: RenderToResponseContext;
243
+ layout?: EcoComponent;
244
+ }): Promise<Response>;
224
245
  /**
225
246
  * Renders an arbitrary React view through the application's HTML shell.
226
247
  *