@ecopages/react 0.2.1-beta.0 → 0.3.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.
Files changed (181) hide show
  1. package/README.md +164 -28
  2. package/package.json +67 -30
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +38 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +29 -11
  9. package/src/bundling/bundle.js +130 -0
  10. package/src/bundling/runtime-alias-map.d.ts +12 -0
  11. package/src/bundling/runtime-alias-map.js +110 -0
  12. package/src/bundling/runtime-bundle.d.ts +70 -0
  13. package/src/bundling/runtime-bundle.js +233 -0
  14. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  15. package/src/bundling/runtime-interop-plugin.js +32 -0
  16. package/src/bundling/runtime-mode.d.ts +1 -0
  17. package/src/bundling/runtime-mode.js +10 -0
  18. package/src/bundling/runtime-modules.d.ts +21 -0
  19. package/src/bundling/runtime-modules.js +28 -0
  20. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  21. package/src/client-graph/ast-transform-eco-page.js +71 -0
  22. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  23. package/src/client-graph/ast-transform-import-edits.js +75 -0
  24. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  25. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  26. package/src/client-graph/ast-transform.d.ts +12 -0
  27. package/src/client-graph/ast-transform.js +91 -0
  28. package/src/client-graph/ast-walk.d.ts +10 -0
  29. package/src/client-graph/ast-walk.js +26 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  32. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  33. package/src/client-graph/boundary-plugin-transform.js +31 -0
  34. package/src/client-graph/boundary-plugin.d.ts +23 -0
  35. package/src/client-graph/boundary-plugin.js +177 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/client-graph/declared-modules.js +69 -0
  38. package/src/client-graph/module-classification.d.ts +3 -0
  39. package/src/client-graph/module-classification.js +43 -0
  40. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  41. package/src/client-graph/reachability-analyzer.js +55 -0
  42. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  43. package/src/client-graph/reachability-client-roots.js +59 -0
  44. package/src/client-graph/reachability-export-names.d.ts +5 -0
  45. package/src/client-graph/reachability-export-names.js +34 -0
  46. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  47. package/src/client-graph/reachability-fallback-roots.js +71 -0
  48. package/src/client-graph/reachability-preload.d.ts +10 -0
  49. package/src/client-graph/reachability-preload.js +30 -0
  50. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  51. package/src/client-graph/reachability-top-level-index.js +93 -0
  52. package/src/client-graph/reachability-traverse.d.ts +7 -0
  53. package/src/client-graph/reachability-traverse.js +201 -0
  54. package/src/client-graph/specifier-classification.d.ts +74 -0
  55. package/src/client-graph/specifier-classification.js +191 -0
  56. package/src/content/collection-component-cache.d.ts +25 -0
  57. package/src/content/collection-component-cache.js +62 -0
  58. package/src/contracts/router-adapter.js +6 -0
  59. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  60. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  61. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  62. package/src/hmr/hmr-strategy-process.js +83 -0
  63. package/src/hmr/hmr-strategy.d.ts +67 -0
  64. package/src/hmr/hmr-strategy.js +306 -0
  65. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  66. package/src/hmr/page-metadata-cache.js +44 -0
  67. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  68. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  69. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  70. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  71. package/src/hydration/bootstrap-imports.d.ts +25 -0
  72. package/src/hydration/bootstrap-imports.js +33 -0
  73. package/src/hydration/browser/island-hydration.d.ts +82 -0
  74. package/src/hydration/browser/island-hydration.js +251 -0
  75. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  76. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  77. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  78. package/src/hydration/browser/page-hydration-module.js +17 -0
  79. package/src/hydration/browser/page-hydration.d.ts +54 -0
  80. package/src/hydration/browser/page-hydration.js +177 -0
  81. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  82. package/src/hydration/hydration-asset.d.ts +127 -0
  83. package/src/hydration/hydration-asset.js +379 -0
  84. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  85. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  86. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  87. package/src/hydration/hydration-page-entry-source.js +87 -0
  88. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  89. package/src/hydration/hydration-script-compiler.js +213 -0
  90. package/src/hydration/page-data-manifest.d.ts +58 -0
  91. package/src/hydration/page-data-manifest.js +97 -0
  92. package/src/hydration/page-data-reader.d.ts +17 -0
  93. package/src/hydration/page-data-reader.js +31 -0
  94. package/src/hydration/page-payload.d.ts +68 -0
  95. package/src/hydration/page-payload.js +106 -0
  96. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  97. package/src/hydration/serialize-page-data-script.js +30 -0
  98. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +9 -8
  99. package/src/mdx/mdx-config-dependency.js +107 -0
  100. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  101. package/src/mdx/mdx-loader-plugin.js +11 -0
  102. package/src/page/page-module.d.ts +46 -0
  103. package/src/page/page-module.js +74 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +21 -27
  106. package/src/plugin/react.plugin.js +210 -0
  107. package/src/plugin/react.types.d.ts +106 -0
  108. package/src/plugin/react.types.js +1 -0
  109. package/src/render/component-ownership.d.ts +49 -0
  110. package/src/render/component-ownership.js +47 -0
  111. package/src/render/component-ssr.d.ts +59 -0
  112. package/src/render/component-ssr.js +76 -0
  113. package/src/render/eco-embed.js +9 -0
  114. package/src/render/errors.d.ts +16 -0
  115. package/src/render/errors.js +23 -0
  116. package/src/render/html-boundary.js +59 -0
  117. package/src/render/layout-compose.d.ts +66 -0
  118. package/src/render/layout-compose.js +134 -0
  119. package/src/render/react-renderer.d.ts +114 -0
  120. package/src/render/react-renderer.js +490 -0
  121. package/src/render/react-runtime.d.ts +13 -0
  122. package/src/render/react-runtime.js +26 -0
  123. package/src/render/unified-layout-composition.d.ts +22 -0
  124. package/src/render/unified-layout-composition.js +31 -0
  125. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  126. package/src/eco-embed.js +0 -11
  127. package/src/react-hmr-strategy.d.ts +0 -230
  128. package/src/react-hmr-strategy.js +0 -657
  129. package/src/react-renderer.d.ts +0 -233
  130. package/src/react-renderer.js +0 -622
  131. package/src/react.constants.js +0 -4
  132. package/src/react.plugin.js +0 -205
  133. package/src/react.types.d.ts +0 -88
  134. package/src/react.types.js +0 -0
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/pages-index.d.ts +0 -64
  137. package/src/services/pages-index.js +0 -73
  138. package/src/services/react-bundle.service.js +0 -86
  139. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  140. package/src/services/react-hydration-asset.service.d.ts +0 -84
  141. package/src/services/react-hydration-asset.service.js +0 -217
  142. package/src/services/react-mdx-config-dependency.service.js +0 -122
  143. package/src/services/react-page-module.service.d.ts +0 -88
  144. package/src/services/react-page-module.service.js +0 -166
  145. package/src/services/react-page-payload.service.d.ts +0 -46
  146. package/src/services/react-page-payload.service.js +0 -67
  147. package/src/services/react-runtime-bundle.service.d.ts +0 -45
  148. package/src/services/react-runtime-bundle.service.js +0 -186
  149. package/src/utils/client-graph-boundary-cache.d.ts +0 -108
  150. package/src/utils/client-graph-boundary-cache.js +0 -116
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -51
  152. package/src/utils/client-graph-boundary-plugin.js +0 -552
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/component-config-traversal.js +0 -54
  155. package/src/utils/declared-modules.js +0 -47
  156. package/src/utils/dynamic.js +0 -12
  157. package/src/utils/dynamic.test.browser.js +0 -33
  158. package/src/utils/hmr-scripts.d.ts +0 -18
  159. package/src/utils/hmr-scripts.js +0 -31
  160. package/src/utils/html-boundary.js +0 -55
  161. package/src/utils/hydration-scripts.d.ts +0 -92
  162. package/src/utils/hydration-scripts.js +0 -358
  163. package/src/utils/hydration-scripts.test.browser.js +0 -198
  164. package/src/utils/reachability-analyzer.d.ts +0 -66
  165. package/src/utils/reachability-analyzer.js +0 -339
  166. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  167. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  168. package/src/utils/react-mdx-loader-plugin.js +0 -45
  169. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  170. package/src/utils/react-runtime-alias-map.js +0 -90
  171. /package/src/{utils → app}/client-only.d.ts +0 -0
  172. /package/src/{utils → app}/dynamic.d.ts +0 -0
  173. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  174. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  175. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  176. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  177. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  178. /package/src/{utils/hydration-scripts.test.browser.d.ts → hydration/compiled-page-hydration-options.js} +0 -0
  179. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  180. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  181. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,114 @@
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
+ /**
12
+ * React IntegrationRenderer orchestrator.
13
+ *
14
+ * @remarks
15
+ * Wires services and delegates SSR / layout composition / ownership details to
16
+ * focused modules under `render/`. Prefer changing those modules for
17
+ * implementation work; keep this file as the IntegrationRenderer seam.
18
+ *
19
+ * @module
20
+ */
21
+ import type { EcoComponent } from '@ecopages/core';
22
+ import { type IntegrationRendererOptions } from '@ecopages/core/integration';
23
+ import type { ReactNode } from 'react';
24
+ import type { ReactRendererConfig } from '../plugin/react.types.js';
25
+ import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
26
+ import { BundleService } from '../bundling/bundle.js';
27
+ import { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
28
+ import { MdxConfigDependencyService } from '../mdx/mdx-config-dependency.js';
29
+ import { PageModuleService } from '../page/page-module.js';
30
+ import { PagePayloadService } from '../hydration/page-payload.js';
31
+ import { HydrationAssetService } from '../hydration/hydration-asset.js';
32
+ import { type DocumentShellComposeChildrenContext, type DocumentShellComposeChildrenResult, type DocumentShellLayoutInput } from '@ecopages/core/integration';
33
+ import { type ReactRuntimeModules } from './react-runtime.js';
34
+ export type { ReactRendererConfig } from '../plugin/react.types.js';
35
+ export { BundleError, ReactRenderError } from './errors.js';
36
+ export type ReactRendererOptions = IntegrationRendererOptions & {
37
+ reactConfig?: ReactRendererConfig;
38
+ };
39
+ declare const ReactIntegrationRenderer: new (options: IntegrationRendererOptions) => import("@ecopages/core/integration").IntegrationRenderer<ReactNode> & {
40
+ name: string;
41
+ };
42
+ /** Renderer adapter that contributes React-specific behavior through core hooks. */
43
+ export declare class ReactRenderer extends ReactIntegrationRenderer {
44
+ private reactRuntimeModules?;
45
+ private readonly runtimeStateRef;
46
+ private readonly hookTargets;
47
+ constructor(options: ReactRendererOptions);
48
+ get routerAdapter(): ReactRouterAdapter | undefined;
49
+ get mdxExtensions(): string[];
50
+ get hmrPageMetadataCache(): HmrPageMetadataCache | undefined;
51
+ get forceBrowserGraph(): boolean;
52
+ get bundleService(): BundleService;
53
+ get pageModuleService(): PageModuleService;
54
+ get hydrationAssetService(): HydrationAssetService;
55
+ get pagePayloadService(): PagePayloadService;
56
+ get mdxConfigDependencyService(): MdxConfigDependencyService;
57
+ private getRuntimeState;
58
+ /**
59
+ * Builds React island and lazy-entry modules in one grouped browser build.
60
+ */
61
+ private buildPageClientBrowserAssetsHook;
62
+ private collectAppBrowserClientBuildEntriesHook;
63
+ private getRouterDocumentAttributes;
64
+ protected resolveReactRuntimeModules(): ReactRuntimeModules;
65
+ private getReactRuntimeModules;
66
+ private resolveReactQueuedForeignSubtreeHtml;
67
+ private renderQueuedChildrenToHtml;
68
+ private buildPagePayload;
69
+ /**
70
+ * Renders a React component for component-level orchestration.
71
+ *
72
+ * Behavior:
73
+ * - SSR always returns the component's own root HTML (no synthetic wrapper).
74
+ * - When an explicit component instance id is provided, a stable
75
+ * `data-eco-component-id` attribute is attached so island hydration can target it.
76
+ * - Without an explicit instance id, component renders remain plain SSR output.
77
+ * - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
78
+ * composition step and does not emit hydration assets for the parent wrapper.
79
+ *
80
+ * This preserves DOM shape for global CSS/layout selectors while keeping a
81
+ * deterministic mount target per component instance.
82
+ */
83
+ private renderComponentHook;
84
+ private renderForeignComponentWithSerializedHtml;
85
+ /**
86
+ * Emits a server island host only for eligible, single-root component renders.
87
+ *
88
+ * @remarks
89
+ * Renderer-owned services stay on this class so SSR helpers do not receive
90
+ * wrappers around the renderer's own methods.
91
+ */
92
+ private renderReactManagedComponent;
93
+ private renderQueuedChildrenHook;
94
+ /**
95
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
96
+ * @param filePath - The file path to check
97
+ * @returns True if the file is an MDX file
98
+ */
99
+ isMdxFile(filePath: string): boolean;
100
+ private normalizeImportedPageFileHook;
101
+ private collectPageBrowserGraphContributionHook;
102
+ private composeReactLayoutPageChildrenForShell;
103
+ protected resolveComposeChildren(options: {
104
+ page: {
105
+ component: EcoComponent;
106
+ props: Record<string, unknown>;
107
+ };
108
+ shellLayouts: DocumentShellLayoutInput[];
109
+ foreignChildRoots?: ReadonlyArray<EcoComponent | Partial<EcoComponent>>;
110
+ }): ((context: DocumentShellComposeChildrenContext) => Promise<DocumentShellComposeChildrenResult>) | undefined;
111
+ private buildDocumentShellProps;
112
+ private getHtmlDocumentContributionsHook;
113
+ private getDocumentAttributesHook;
114
+ }
@@ -0,0 +1,490 @@
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
+ import { buildIslandHostAttributes, getComponentIdentity } from '@ecopages/core';
13
+ import { createIntegrationRenderer, selectHydrationIslandEntries, } from '@ecopages/core/integration';
14
+ import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from '@ecopages/core/client';
15
+ import { resolveQueuedTokens } from '@ecopages/core/integration';
16
+ import { ensurePageConfigLayouts } from '@ecopages/core/integration';
17
+ import { hasSingleRootElement } from './html-boundary.js';
18
+ import { getIslandComponentKey } from '../hydration/hydration-asset.js';
19
+ import { REACT_PLUGIN_NAME } from '../plugin/react.constants.js';
20
+ import { BundleService } from '../bundling/bundle.js';
21
+ import { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
22
+ import { MdxConfigDependencyService } from '../mdx/mdx-config-dependency.js';
23
+ import { PageModuleService } from '../page/page-module.js';
24
+ import { PagePayloadService } from '../hydration/page-payload.js';
25
+ import { HydrationAssetService } from '../hydration/hydration-asset.js';
26
+ import {} from '@ecopages/core/integration';
27
+ import { asNonReactShellComponent, getComponentRequires, isReactManagedComponent } from './component-ownership.js';
28
+ import { buildHydrationProps, renderComponentHtml, renderNonReactShellComponent, restoreRuntimeChildHtml, toReactNode, } from './component-ssr.js';
29
+ import { BundleError, ReactRenderError } from './errors.js';
30
+ import { resolveReactRuntimeModules } from './react-runtime.js';
31
+ import { composeReactLayoutPageTree, shouldUseUnifiedReactLayoutComposition } from './unified-layout-composition.js';
32
+ import { assertComposablePage, resolveLayoutContextFromShell } from './layout-compose.js';
33
+ export { BundleError, ReactRenderError } from './errors.js';
34
+ const ReactIntegrationRenderer = createIntegrationRenderer(REACT_PLUGIN_NAME);
35
+ /** Renderer adapter that contributes React-specific behavior through core hooks. */
36
+ export class ReactRenderer extends ReactIntegrationRenderer {
37
+ reactRuntimeModules;
38
+ runtimeStateRef;
39
+ hookTargets;
40
+ constructor(options) {
41
+ const { reactConfig, ...rendererOptions } = options;
42
+ const runtimeStateRef = {};
43
+ const hookTargets = {};
44
+ const configuredHooks = createReactRendererHookFactory(reactConfig, runtimeStateRef, hookTargets);
45
+ const additionalHooks = rendererOptions.hooks;
46
+ const hooks = (factoryOptions) => {
47
+ const reactHooks = configuredHooks(factoryOptions);
48
+ const customHooks = typeof additionalHooks === 'function'
49
+ ? additionalHooks({ ...factoryOptions, hooks: reactHooks })
50
+ : additionalHooks;
51
+ return { ...reactHooks, ...customHooks };
52
+ };
53
+ super({ ...rendererOptions, hooks });
54
+ this.runtimeStateRef = runtimeStateRef;
55
+ this.hookTargets = hookTargets;
56
+ this.hookTargets.buildIslandClientAssets = (plan) => this.buildPageClientBrowserAssetsHook(plan);
57
+ this.hookTargets.collectAppBrowserClientBuildEntries = (plan) => this.collectAppBrowserClientBuildEntriesHook(plan);
58
+ this.hookTargets.renderComponent = (input) => this.renderComponentHook(input);
59
+ this.hookTargets.renderQueuedChildren = (children, runtimeContext, queuedResolutionsByToken, resolveToken) => this.renderQueuedChildrenHook(children, runtimeContext, queuedResolutionsByToken, resolveToken);
60
+ this.hookTargets.normalizePageModule = (file, module) => this.normalizeImportedPageFileHook(file, module);
61
+ this.hookTargets.collectPageBrowserGraphContribution = (context) => this.collectPageBrowserGraphContributionHook(context);
62
+ this.hookTargets.composeChildren = ({ page, layouts, foreignChildRoots }) => this.resolveComposeChildren({ page, shellLayouts: layouts, foreignChildRoots });
63
+ this.hookTargets.documentShellProps = (renderOptions) => this.buildDocumentShellProps(renderOptions);
64
+ this.hookTargets.documentContributions = (context) => this.getHtmlDocumentContributionsHook(context);
65
+ this.hookTargets.documentAttributes = (renderOptions) => this.getDocumentAttributesHook(renderOptions);
66
+ }
67
+ get routerAdapter() {
68
+ return this.getRuntimeState().routerAdapter;
69
+ }
70
+ get mdxExtensions() {
71
+ return this.getRuntimeState().mdxExtensions;
72
+ }
73
+ get hmrPageMetadataCache() {
74
+ return this.getRuntimeState().hmrPageMetadataCache;
75
+ }
76
+ get forceBrowserGraph() {
77
+ return this.getRuntimeState().forceBrowserGraph;
78
+ }
79
+ get bundleService() {
80
+ return this.getRuntimeState().bundleService;
81
+ }
82
+ get pageModuleService() {
83
+ return this.getRuntimeState().pageModuleService;
84
+ }
85
+ get hydrationAssetService() {
86
+ return this.getRuntimeState().hydrationAssetService;
87
+ }
88
+ get pagePayloadService() {
89
+ return this.getRuntimeState().pagePayloadService;
90
+ }
91
+ get mdxConfigDependencyService() {
92
+ return this.getRuntimeState().mdxConfigDependencyService;
93
+ }
94
+ getRuntimeState() {
95
+ if (!this.runtimeStateRef.current) {
96
+ throw new Error('React renderer services were used before hook initialization.');
97
+ }
98
+ return this.runtimeStateRef.current;
99
+ }
100
+ /**
101
+ * Builds React island and lazy-entry modules in one grouped browser build.
102
+ */
103
+ async buildPageClientBrowserAssetsHook(plan) {
104
+ const result = await this.hydrationAssetService.buildPageClientRenderAssets({
105
+ islands: selectHydrationIslandEntries(plan, this.name).map((entry) => ({
106
+ file: entry.file,
107
+ config: entry.component.config,
108
+ })),
109
+ lazyEntries: plan.lazyClientEntries,
110
+ });
111
+ const lazyTriggers = this.getRuntimeState().applyPendingLazyTriggers(result.processedAssets, plan.lazyConfigs ?? []);
112
+ return {
113
+ processedAssets: result.processedAssets,
114
+ islandRenderAssetsByFile: result.assetsByFile,
115
+ lazyTriggers,
116
+ };
117
+ }
118
+ async collectAppBrowserClientBuildEntriesHook(plan) {
119
+ return this.hydrationAssetService.collectAppBrowserClientBuildEntries(selectHydrationIslandEntries(plan, this.name).map((entry) => ({
120
+ file: entry.file,
121
+ config: entry.component.config,
122
+ })));
123
+ }
124
+ getRouterDocumentAttributes() {
125
+ if (!this.routerAdapter) {
126
+ return undefined;
127
+ }
128
+ return {
129
+ [ECO_DOCUMENT_OWNER_ATTRIBUTE]: 'react-router',
130
+ };
131
+ }
132
+ resolveReactRuntimeModules() {
133
+ return resolveReactRuntimeModules(this.appConfig.rootDir);
134
+ }
135
+ getReactRuntimeModules() {
136
+ this.reactRuntimeModules ??= this.resolveReactRuntimeModules();
137
+ return this.reactRuntimeModules;
138
+ }
139
+ resolveReactQueuedForeignSubtreeHtml(html, runtimeContext) {
140
+ return this.resolveQueuedForeignSubtrees(html, runtimeContext, async (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => ({
141
+ html: await this.renderQueuedChildrenToHtml({
142
+ children,
143
+ runtimeContext: currentRuntimeContext,
144
+ queuedResolutionsByToken,
145
+ resolveToken,
146
+ }),
147
+ }));
148
+ }
149
+ async renderQueuedChildrenToHtml(options) {
150
+ const { children, runtimeContext, queuedResolutionsByToken, resolveToken } = options;
151
+ if (children === undefined) {
152
+ return undefined;
153
+ }
154
+ const { react, reactDomServer } = this.getReactRuntimeModules();
155
+ let html = this.normalizeUnresolvedMarkerArtifactHtml(reactDomServer.renderToString(react.createElement(react.Fragment, null, toReactNode(children, this.name))));
156
+ html = restoreRuntimeChildHtml(html, runtimeContext);
157
+ return await resolveQueuedTokens(html, queuedResolutionsByToken, resolveToken);
158
+ }
159
+ buildPagePayload(options) {
160
+ const safeLocals = this.pagePayloadService.getSerializableLocals(options.locals, getComponentRequires(options.Page));
161
+ return {
162
+ pageModuleUrl: this.pagePayloadService.resolvePageModuleUrl(options.pagePackage, {
163
+ routerEnabled: Boolean(this.routerAdapter),
164
+ }),
165
+ pageProps: this.pagePayloadService.buildSerializedPageProps({
166
+ pageProps: options.pageProps,
167
+ params: options.params,
168
+ query: options.query,
169
+ safeLocals,
170
+ }),
171
+ };
172
+ }
173
+ /**
174
+ * Renders a React component for component-level orchestration.
175
+ *
176
+ * Behavior:
177
+ * - SSR always returns the component's own root HTML (no synthetic wrapper).
178
+ * - When an explicit component instance id is provided, a stable
179
+ * `data-eco-component-id` attribute is attached so island hydration can target it.
180
+ * - Without an explicit instance id, component renders remain plain SSR output.
181
+ * - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
182
+ * composition step and does not emit hydration assets for the parent wrapper.
183
+ *
184
+ * This preserves DOM shape for global CSS/layout selectors while keeping a
185
+ * deterministic mount target per component instance.
186
+ */
187
+ async renderComponentHook(input) {
188
+ if (!isReactManagedComponent(input.component, this.name)) {
189
+ return await this.renderForeignComponentWithSerializedHtml(input);
190
+ }
191
+ const runtimeContext = this.getQueuedForeignSubtreeContext(input);
192
+ return await this.renderReactManagedComponent(input, runtimeContext);
193
+ }
194
+ async renderForeignComponentWithSerializedHtml(input) {
195
+ let props = input.props;
196
+ if (input.children !== undefined) {
197
+ props = {
198
+ ...input.props,
199
+ children: typeof input.children === 'string' ? input.children : String(input.children ?? ''),
200
+ };
201
+ }
202
+ 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
+ return {
207
+ html,
208
+ canAttachAttributes: true,
209
+ integrationName: this.name,
210
+ assets,
211
+ };
212
+ }
213
+ /**
214
+ * Emits a server island host only for eligible, single-root component renders.
215
+ *
216
+ * @remarks
217
+ * Renderer-owned services stay on this class so SSR helpers do not receive
218
+ * wrappers around the renderer's own methods.
219
+ */
220
+ async renderReactManagedComponent(input, runtimeContext) {
221
+ const componentConfig = input.component.config;
222
+ const context = {
223
+ componentInstanceId: input.integrationContext?.componentInstanceId,
224
+ };
225
+ const hasResolvedChildHtml = input.children !== undefined;
226
+ let html = this.normalizeUnresolvedMarkerArtifactHtml(renderComponentHtml({ input, context, runtimeContext, runtime: this.getReactRuntimeModules() }));
227
+ const queuedResolution = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
228
+ html = queuedResolution.html;
229
+ const canAttachAttributes = hasSingleRootElement(html);
230
+ const componentFile = getComponentIdentity(componentConfig)?.file;
231
+ let rootAttributes;
232
+ let assets;
233
+ if (canAttachAttributes && componentFile && context.componentInstanceId && !hasResolvedChildHtml) {
234
+ rootAttributes = buildIslandHostAttributes({
235
+ integrationName: this.name,
236
+ componentInstanceId: context.componentInstanceId,
237
+ componentKey: getIslandComponentKey(componentFile, componentConfig),
238
+ props: buildHydrationProps(input.props),
239
+ });
240
+ assets = this.getActiveIslandRenderAssets().get(componentFile);
241
+ html = `<eco-island style="display:contents">${html}</eco-island>`;
242
+ }
243
+ const mergedAssets = this.htmlTransformer.dedupeProcessedAssets([
244
+ ...(assets ?? []),
245
+ ...queuedResolution.assets,
246
+ ]);
247
+ return {
248
+ html,
249
+ canAttachAttributes,
250
+ integrationName: this.name,
251
+ rootAttributes,
252
+ assets: mergedAssets.length > 0 ? mergedAssets : undefined,
253
+ };
254
+ }
255
+ async renderQueuedChildrenHook(children, runtimeContext, queuedResolutionsByToken, resolveToken) {
256
+ if (children === undefined) {
257
+ return {};
258
+ }
259
+ const html = await this.renderQueuedChildrenToHtml({
260
+ children,
261
+ runtimeContext: runtimeContext,
262
+ queuedResolutionsByToken,
263
+ resolveToken,
264
+ });
265
+ return html === undefined ? {} : { html };
266
+ }
267
+ /**
268
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
269
+ * @param filePath - The file path to check
270
+ * @returns True if the file is an MDX file
271
+ */
272
+ isMdxFile(filePath) {
273
+ return this.pageModuleService.isMdxFile(filePath);
274
+ }
275
+ normalizeImportedPageFileHook(file, pageModule) {
276
+ const reactModule = pageModule;
277
+ const { default: Page, getMetadata, config } = reactModule;
278
+ if (this.pageModuleService.isMdxFile(file) && config) {
279
+ ensurePageConfigLayouts(config);
280
+ Page.config = config;
281
+ }
282
+ return {
283
+ ...pageModule,
284
+ default: Page,
285
+ getMetadata,
286
+ config,
287
+ };
288
+ }
289
+ async collectPageBrowserGraphContributionHook(context) {
290
+ try {
291
+ const { file: pagePath, pageModule } = context;
292
+ const shouldHydrate = this.forceBrowserGraph ? true : this.pageModuleService.shouldHydratePage(pageModule);
293
+ if (!shouldHydrate) {
294
+ return { assets: [] };
295
+ }
296
+ const isMdx = this.pageModuleService.isMdxFile(pagePath);
297
+ const declaredModules = this.pageModuleService.collectPageDeclaredModules(pageModule);
298
+ if (isMdx) {
299
+ await this.bundleService.ensurePageLayoutNormalizationVendorProcessed(this.assetProcessingService);
300
+ }
301
+ const dependencies = await this.hydrationAssetService.createPageBrowserGraphDependencies(pagePath, isMdx, declaredModules);
302
+ const assets = isMdx
303
+ ? await this.mdxConfigDependencyService.processMdxConfigDependencies({
304
+ pagePath,
305
+ config: pageModule.config,
306
+ processComponentDependencies: async (components) => await this.processComponentDependencies(components),
307
+ })
308
+ : [];
309
+ return { dependencies, assets };
310
+ }
311
+ catch (error) {
312
+ if (error instanceof BundleError) {
313
+ console.error('[ecopages] Bundle errors:', error.logs);
314
+ }
315
+ throw new ReactRenderError(`Failed to generate hydration script: ${error instanceof Error ? error.message : String(error)}`);
316
+ }
317
+ }
318
+ async composeReactLayoutPageChildrenForShell(page, context) {
319
+ const pageComponent = assertComposablePage(page.component);
320
+ const shellEntries = context.layouts.map((layout) => ({
321
+ component: layout.component,
322
+ props: layout.props,
323
+ }));
324
+ const { react, reactDomServer } = this.getReactRuntimeModules();
325
+ const tree = composeReactLayoutPageTree(pageComponent, page.props, shellEntries, {
326
+ context: resolveLayoutContextFromShell(page.props, shellEntries),
327
+ react,
328
+ });
329
+ const runtimeInput = {
330
+ component: page.component,
331
+ props: page.props,
332
+ integrationContext: {
333
+ rendererCache: context.rendererCache,
334
+ },
335
+ };
336
+ const runtimeContext = this.getQueuedForeignSubtreeContext(runtimeInput);
337
+ const html = this.normalizeUnresolvedMarkerArtifactHtml(reactDomServer.renderToString(tree));
338
+ const resolved = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
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
+ };
350
+ }
351
+ resolveComposeChildren(options) {
352
+ const { page, shellLayouts, foreignChildRoots } = options;
353
+ if (!shouldUseUnifiedReactLayoutComposition({
354
+ page: page.component,
355
+ shellLayouts,
356
+ reactIntegrationName: this.name,
357
+ })) {
358
+ return undefined;
359
+ }
360
+ if (this.hasForeignChildDescendants(page.component, foreignChildRoots) ||
361
+ shellLayouts.some((layout) => this.hasForeignChildDescendants(layout.component))) {
362
+ return undefined;
363
+ }
364
+ return (context) => this.composeReactLayoutPageChildrenForShell(page, context);
365
+ }
366
+ buildDocumentShellProps(options) {
367
+ const pagePayload = this.buildPagePayload({
368
+ Page: options.Page,
369
+ pageProps: options.pageProps,
370
+ params: options.params,
371
+ query: options.query,
372
+ locals: options.locals,
373
+ pagePackage: options.pagePackage,
374
+ });
375
+ return {
376
+ pageProps: pagePayload.pageProps,
377
+ documentProps: pagePayload.pageModuleUrl ? { pageModuleUrl: pagePayload.pageModuleUrl } : undefined,
378
+ };
379
+ }
380
+ getHtmlDocumentContributionsHook(options) {
381
+ const renderOptions = options.renderOptions;
382
+ if (options.partial ||
383
+ !renderOptions ||
384
+ !this.routerAdapter ||
385
+ isReactManagedComponent(renderOptions.HtmlTemplate, this.name)) {
386
+ return undefined;
387
+ }
388
+ const pagePayload = this.buildPagePayload({
389
+ Page: renderOptions.Page,
390
+ pageProps: renderOptions.pageProps,
391
+ params: renderOptions.params,
392
+ query: renderOptions.query,
393
+ locals: renderOptions.locals,
394
+ pagePackage: renderOptions.pagePackage,
395
+ });
396
+ return this.pagePayloadService.buildNonReactDocumentContributions({
397
+ htmlTemplate: renderOptions.HtmlTemplate,
398
+ pageProps: pagePayload.pageProps,
399
+ pageModuleUrl: pagePayload.pageModuleUrl,
400
+ reactIntegrationName: this.name,
401
+ routerEnabled: true,
402
+ });
403
+ }
404
+ getDocumentAttributesHook(_renderOptions) {
405
+ return this.getRouterDocumentAttributes();
406
+ }
407
+ }
408
+ function createReactRendererHookFactory(reactConfig, runtimeStateRef, hookTargets) {
409
+ return ({ appConfig, assetProcessingIntegration, assetProcessingService, applyPendingLazyTriggers, }) => {
410
+ const routerAdapter = reactConfig?.routerAdapter;
411
+ const mdxExtensions = reactConfig?.mdxExtensions ?? ['.mdx'];
412
+ const hmrPageMetadataCache = reactConfig?.hmrPageMetadataCache;
413
+ const forceBrowserGraph = reactConfig?.forceBrowserGraph ?? false;
414
+ const bundleService = new BundleService({
415
+ rootDir: appConfig.rootDir,
416
+ appConfig,
417
+ assetProcessingIntegration,
418
+ hostIntegrationName: REACT_PLUGIN_NAME,
419
+ routerAdapter,
420
+ runtimeModules: reactConfig?.runtimeModules,
421
+ getMdxLoaderPlugin: reactConfig?.getMdxLoaderPlugin,
422
+ });
423
+ const pageModuleService = new PageModuleService({
424
+ layoutsDir: appConfig.absolutePaths.layoutsDir,
425
+ componentsDir: appConfig.absolutePaths.componentsDir,
426
+ mdxExtensions,
427
+ integrationName: REACT_PLUGIN_NAME,
428
+ hasRouterAdapter: Boolean(routerAdapter),
429
+ });
430
+ const hydrationAssetService = new HydrationAssetService({
431
+ srcDir: appConfig.srcDir,
432
+ routerAdapter,
433
+ assetProcessingService,
434
+ assetProcessingIntegration,
435
+ bundleService,
436
+ hmrPageMetadataCache,
437
+ });
438
+ runtimeStateRef.current = {
439
+ routerAdapter,
440
+ mdxExtensions,
441
+ hmrPageMetadataCache,
442
+ forceBrowserGraph,
443
+ bundleService,
444
+ pageModuleService,
445
+ hydrationAssetService,
446
+ pagePayloadService: new PagePayloadService(),
447
+ mdxConfigDependencyService: new MdxConfigDependencyService({
448
+ integrationName: REACT_PLUGIN_NAME,
449
+ pageModuleService,
450
+ assetProcessingService,
451
+ assetProcessingIntegration,
452
+ }),
453
+ applyPendingLazyTriggers,
454
+ };
455
+ return {
456
+ buildIslandClientAssets: (plan) => requireReactRendererHookTarget(hookTargets, 'buildIslandClientAssets')(plan),
457
+ collectAppBrowserClientBuildEntries: (plan) => requireReactRendererHookTarget(hookTargets, 'collectAppBrowserClientBuildEntries')(plan),
458
+ renderComponent: (input) => requireReactRendererHookTarget(hookTargets, 'renderComponent')(input),
459
+ renderQueuedChildren: (children, runtimeContext, queuedResolutionsByToken, resolveToken) => requireReactRendererHookTarget(hookTargets, 'renderQueuedChildren')(children, runtimeContext, queuedResolutionsByToken, resolveToken),
460
+ normalizePageModule: (file, module) => requireReactRendererHookTarget(hookTargets, 'normalizePageModule')(file, module),
461
+ collectPageBrowserGraphContribution: (context) => requireReactRendererHookTarget(hookTargets, 'collectPageBrowserGraphContribution')(context),
462
+ composeChildren: (input) => requireReactRendererHookTarget(hookTargets, 'composeChildren')(input),
463
+ documentShellProps: (options) => requireReactRendererHookTarget(hookTargets, 'documentShellProps')(options),
464
+ documentContributions: (context) => requireReactRendererHookTarget(hookTargets, 'documentContributions')(context),
465
+ documentAttributes: (options) => requireReactRendererHookTarget(hookTargets, 'documentAttributes')(options),
466
+ renderRoute: async (_options, render) => {
467
+ try {
468
+ return await render();
469
+ }
470
+ catch (error) {
471
+ throw createReactRenderError('Failed to render component', error);
472
+ }
473
+ },
474
+ };
475
+ };
476
+ }
477
+ function requireReactRendererHookTarget(hookTargets, name) {
478
+ const hookTarget = hookTargets[name];
479
+ if (!hookTarget) {
480
+ throw new Error(`React renderer hook "${name}" was called before the renderer was initialized.`);
481
+ }
482
+ return hookTarget;
483
+ }
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
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Resolves the React and react-dom/server modules used for SSR.
3
+ *
4
+ * @remarks
5
+ * Prefers the app's own React install so SSR identity matches the app bundle.
6
+ * Falls back to the integration's React when the app package cannot resolve them.
7
+ */
8
+ import type { ReactRuntime } from './layout-compose.js';
9
+ export type ReactRuntimeModules = {
10
+ react: ReactRuntime;
11
+ reactDomServer: typeof import('react-dom/server');
12
+ };
13
+ export declare function resolveReactRuntimeModules(rootDir: string | undefined): ReactRuntimeModules;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Resolves the React and react-dom/server modules used for SSR.
3
+ *
4
+ * @remarks
5
+ * Prefers the app's own React install so SSR identity matches the app bundle.
6
+ * Falls back to the integration's React when the app package cannot resolve them.
7
+ */
8
+ import { createRequire } from 'node:module';
9
+ import path from 'node:path';
10
+ export function resolveReactRuntimeModules(rootDir) {
11
+ const appPackageJsonPath = path.resolve(rootDir || process.cwd(), 'package.json');
12
+ try {
13
+ const requireFromApp = createRequire(appPackageJsonPath);
14
+ return {
15
+ react: requireFromApp('react'),
16
+ reactDomServer: requireFromApp('react-dom/server'),
17
+ };
18
+ }
19
+ catch {
20
+ const requireFromIntegration = createRequire(import.meta.url);
21
+ return {
22
+ react: requireFromIntegration('react'),
23
+ reactDomServer: requireFromIntegration('react-dom/server'),
24
+ };
25
+ }
26
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Unified React layout + page composition for SSR document shells.
3
+ *
4
+ * @remarks
5
+ * When every shell layout is React-managed, compose one element tree via
6
+ * {@link composeLayoutPageTree} / {@link composeLayoutPageTreeFromShell} instead of
7
+ * rendering each tier separately. This keeps SSR DOM shape aligned with client
8
+ * hydration through `@ecopages/react/layout-compose`.
9
+ */
10
+ import type { EcoComponent } from '@ecopages/core';
11
+ import type { DocumentShellLayoutInput } from '@ecopages/core/integration';
12
+ import type { ReactElement } from 'react';
13
+ import { type ComposablePage, type LayoutComposeOptions } from './layout-compose.js';
14
+ export declare function composeReactLayoutPageTree(Page: ComposablePage, pageProps: Record<string, unknown>, shellEntries: Array<{
15
+ component: EcoComponent;
16
+ props?: Record<string, unknown>;
17
+ }>, options: LayoutComposeOptions): ReactElement;
18
+ export declare function shouldUseUnifiedReactLayoutComposition(options: {
19
+ page: EcoComponent;
20
+ shellLayouts: DocumentShellLayoutInput[];
21
+ reactIntegrationName: string;
22
+ }): boolean;