@ecopages/react 0.2.1 → 0.3.1

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 (167) hide show
  1. package/README.md +179 -35
  2. package/package.json +78 -33
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  6. package/src/bundling/bootstrap-package-paths.js +5 -0
  7. package/src/bundling/bundle.d.ts +78 -0
  8. package/src/bundling/bundle.js +130 -0
  9. package/src/bundling/runtime-alias-map.d.ts +12 -0
  10. package/src/bundling/runtime-alias-map.js +110 -0
  11. package/src/bundling/runtime-bundle.d.ts +70 -0
  12. package/src/bundling/runtime-bundle.js +233 -0
  13. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  14. package/src/bundling/runtime-interop-plugin.js +32 -0
  15. package/src/bundling/runtime-mode.d.ts +1 -0
  16. package/src/bundling/runtime-mode.js +10 -0
  17. package/src/bundling/runtime-modules.d.ts +21 -0
  18. package/src/bundling/runtime-modules.js +28 -0
  19. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  20. package/src/client-graph/ast-transform-eco-page.js +71 -0
  21. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  22. package/src/client-graph/ast-transform-import-edits.js +75 -0
  23. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  24. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  25. package/src/client-graph/ast-transform.d.ts +12 -0
  26. package/src/client-graph/ast-transform.js +91 -0
  27. package/src/client-graph/ast-walk.d.ts +10 -0
  28. package/src/client-graph/ast-walk.js +26 -0
  29. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  31. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  32. package/src/client-graph/boundary-plugin-transform.js +31 -0
  33. package/src/client-graph/boundary-plugin.d.ts +23 -0
  34. package/src/client-graph/boundary-plugin.js +177 -0
  35. package/src/client-graph/component-config-traversal.d.ts +36 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/{utils → client-graph}/declared-modules.d.ts +1 -1
  38. package/src/client-graph/declared-modules.js +69 -0
  39. package/src/client-graph/module-classification.d.ts +3 -0
  40. package/src/client-graph/module-classification.js +43 -0
  41. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  42. package/src/client-graph/reachability-analyzer.js +55 -0
  43. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  44. package/src/client-graph/reachability-client-roots.js +59 -0
  45. package/src/client-graph/reachability-export-names.d.ts +5 -0
  46. package/src/client-graph/reachability-export-names.js +34 -0
  47. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  48. package/src/client-graph/reachability-fallback-roots.js +71 -0
  49. package/src/client-graph/reachability-preload.d.ts +10 -0
  50. package/src/client-graph/reachability-preload.js +30 -0
  51. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  52. package/src/client-graph/reachability-top-level-index.js +93 -0
  53. package/src/client-graph/reachability-traverse.d.ts +7 -0
  54. package/src/client-graph/reachability-traverse.js +201 -0
  55. package/src/client-graph/specifier-classification.d.ts +74 -0
  56. package/src/client-graph/specifier-classification.js +191 -0
  57. package/src/content/collection-component-cache.d.ts +25 -0
  58. package/src/content/collection-component-cache.js +62 -0
  59. package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +7 -14
  60. package/src/contracts/router-adapter.js +6 -0
  61. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  62. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  63. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  64. package/src/hmr/hmr-strategy-process.js +83 -0
  65. package/src/hmr/hmr-strategy.d.ts +67 -0
  66. package/src/hmr/hmr-strategy.js +306 -0
  67. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +6 -2
  68. package/src/hmr/page-metadata-cache.js +44 -0
  69. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  70. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -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 +81 -0
  74. package/src/hydration/browser/island-hydration.js +247 -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/compiled-page-hydration-options.js +1 -0
  83. package/src/hydration/hydration-asset.d.ts +128 -0
  84. package/src/hydration/hydration-asset.js +388 -0
  85. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  86. package/src/hydration/hydration-page-entry-source.js +87 -0
  87. package/src/hydration/hydration-script-compiler.d.ts +47 -0
  88. package/src/hydration/hydration-script-compiler.js +213 -0
  89. package/src/hydration/page-data-manifest.d.ts +58 -0
  90. package/src/hydration/page-data-manifest.js +97 -0
  91. package/src/hydration/page-data-reader.d.ts +17 -0
  92. package/src/hydration/page-data-reader.js +31 -0
  93. package/src/hydration/page-payload.d.ts +68 -0
  94. package/src/hydration/page-payload.js +106 -0
  95. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  96. package/src/hydration/serialize-page-data-script.js +30 -0
  97. package/src/mdx/mdx-config-dependency.d.ts +37 -0
  98. package/src/mdx/mdx-config-dependency.js +107 -0
  99. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  100. package/src/mdx/mdx-loader-plugin.js +11 -0
  101. package/src/page/page-module.d.ts +46 -0
  102. package/src/page/page-module.js +74 -0
  103. package/src/plugin/react.constants.d.ts +1 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/plugin/react.plugin.d.ts +71 -0
  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.d.ts +11 -0
  114. package/src/render/eco-embed.js +9 -0
  115. package/src/render/errors.d.ts +16 -0
  116. package/src/render/errors.js +23 -0
  117. package/src/render/html-boundary.js +59 -0
  118. package/src/render/layout-compose.d.ts +66 -0
  119. package/src/render/layout-compose.js +134 -0
  120. package/src/render/react-renderer.d.ts +114 -0
  121. package/src/render/react-renderer.js +490 -0
  122. package/src/render/react-runtime.d.ts +13 -0
  123. package/src/render/react-runtime.js +26 -0
  124. package/src/render/unified-layout-composition.d.ts +22 -0
  125. package/src/render/unified-layout-composition.js +31 -0
  126. package/src/runtime/use-sync-external-store-with-selector.d.ts +3 -0
  127. package/src/runtime/use-sync-external-store-with-selector.js +54 -0
  128. package/CHANGELOG.md +0 -29
  129. package/src/react-hmr-strategy.d.ts +0 -148
  130. package/src/react-hmr-strategy.js +0 -313
  131. package/src/react-renderer.d.ts +0 -213
  132. package/src/react-renderer.js +0 -654
  133. package/src/react.plugin.d.ts +0 -147
  134. package/src/react.plugin.js +0 -146
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/react-bundle.service.d.ts +0 -47
  137. package/src/services/react-bundle.service.js +0 -93
  138. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  139. package/src/services/react-hydration-asset.service.d.ts +0 -76
  140. package/src/services/react-hydration-asset.service.js +0 -210
  141. package/src/services/react-page-module.service.d.ts +0 -83
  142. package/src/services/react-page-module.service.js +0 -162
  143. package/src/services/react-runtime-bundle.service.d.ts +0 -40
  144. package/src/services/react-runtime-bundle.service.js +0 -130
  145. package/src/utils/client-graph-boundary-plugin.d.ts +0 -43
  146. package/src/utils/client-graph-boundary-plugin.js +0 -494
  147. package/src/utils/client-only.js +0 -19
  148. package/src/utils/declared-modules.js +0 -59
  149. package/src/utils/dynamic.js +0 -12
  150. package/src/utils/hmr-scripts.d.ts +0 -18
  151. package/src/utils/hmr-scripts.js +0 -31
  152. package/src/utils/html-boundary.js +0 -55
  153. package/src/utils/hydration-scripts.d.ts +0 -86
  154. package/src/utils/hydration-scripts.js +0 -285
  155. package/src/utils/reachability-analyzer.d.ts +0 -66
  156. package/src/utils/reachability-analyzer.js +0 -339
  157. package/src/utils/react-dom-runtime-interop-plugin.js +0 -29
  158. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  159. package/src/utils/react-mdx-loader-plugin.js +0 -45
  160. package/src/utils/react-runtime-specifier-map.d.ts +0 -6
  161. package/src/utils/react-runtime-specifier-map.js +0 -37
  162. package/src/utils/use-sync-external-store-shim-plugin.d.ts +0 -5
  163. package/src/utils/use-sync-external-store-shim-plugin.js +0 -41
  164. /package/src/{utils → app}/client-only.d.ts +0 -0
  165. /package/src/{utils → app}/dynamic.d.ts +0 -0
  166. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  167. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -1,654 +0,0 @@
1
- import { IntegrationRenderer } from "@ecopages/core/route-renderer/integration-renderer";
2
- import { LocalsAccessError } from "@ecopages/core/errors/locals-access-error";
3
- import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
4
- import { getAppBuildExecutor } from "@ecopages/core/build/build-adapter";
5
- import { rapidhash } from "@ecopages/core/hash";
6
- import { AssetFactory } from "@ecopages/core/services/asset-processing-service";
7
- import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from "@ecopages/core/router/navigation-coordinator";
8
- import path from "node:path";
9
- import { createElement, Fragment } from "react";
10
- import { renderToReadableStream, renderToString } from "react-dom/server";
11
- import { PLUGIN_NAME } from "./react.plugin.js";
12
- import { hasSingleRootElement } from "./utils/html-boundary.js";
13
- import { ReactBundleService } from "./services/react-bundle.service.js";
14
- import { ReactHmrPageMetadataCache } from "./services/react-hmr-page-metadata-cache.js";
15
- import { ReactPageModuleService } from "./services/react-page-module.service.js";
16
- import { getReactIslandComponentKey, ReactHydrationAssetService } from "./services/react-hydration-asset.service.js";
17
- class ReactRenderError extends Error {
18
- constructor(message) {
19
- super(message);
20
- this.name = "ReactRenderError";
21
- }
22
- }
23
- class BundleError extends Error {
24
- logs;
25
- constructor(message, logs) {
26
- super(message);
27
- this.name = "BundleError";
28
- this.logs = logs;
29
- }
30
- }
31
- class ReactRenderer extends IntegrationRenderer {
32
- name = PLUGIN_NAME;
33
- componentDirectory = RESOLVED_ASSETS_DIR;
34
- static routerAdapter;
35
- static mdxCompilerOptions;
36
- static mdxExtensions = [".mdx"];
37
- static hmrPageMetadataCache;
38
- /**
39
- * Enables explicit graph behavior for React page-entry bundling.
40
- *
41
- * When true, page-entry bundles disable AST server-only stripping and rely
42
- * on explicit dependency declarations for browser graph composition.
43
- */
44
- static explicitGraphEnabled = false;
45
- /** @internal */
46
- bundleService;
47
- /** @internal */
48
- pageModuleService;
49
- /** @internal */
50
- hydrationAssetService;
51
- constructor(options) {
52
- super(options);
53
- this.bundleService = new ReactBundleService({
54
- rootDir: this.appConfig.rootDir,
55
- routerAdapter: ReactRenderer.routerAdapter,
56
- mdxCompilerOptions: ReactRenderer.mdxCompilerOptions,
57
- jsxImportSource: (this.appConfig.integrations ?? []).find((integration) => integration.name === this.name)?.jsxImportSource,
58
- nonReactExtensions: (this.appConfig.integrations ?? []).filter((integration) => integration.name !== this.name).flatMap((integration) => integration.extensions)
59
- });
60
- this.pageModuleService = new ReactPageModuleService({
61
- rootDir: this.appConfig.rootDir,
62
- distDir: this.appConfig.absolutePaths.distDir,
63
- workDir: this.appConfig.absolutePaths.workDir,
64
- buildExecutor: getAppBuildExecutor(this.appConfig),
65
- layoutsDir: this.appConfig.absolutePaths.layoutsDir,
66
- componentsDir: this.appConfig.absolutePaths.componentsDir,
67
- mdxCompilerOptions: ReactRenderer.mdxCompilerOptions,
68
- mdxExtensions: ReactRenderer.mdxExtensions,
69
- integrationName: this.name,
70
- hasRouterAdapter: Boolean(ReactRenderer.routerAdapter)
71
- });
72
- this.hydrationAssetService = new ReactHydrationAssetService({
73
- srcDir: this.appConfig.srcDir,
74
- routerAdapter: ReactRenderer.routerAdapter,
75
- assetProcessingService: this.assetProcessingService,
76
- bundleService: this.bundleService,
77
- hmrPageMetadataCache: ReactRenderer.hmrPageMetadataCache
78
- });
79
- }
80
- shouldRenderPageComponent() {
81
- return false;
82
- }
83
- /**
84
- * Reads the declared integration name for a component or layout.
85
- *
86
- * We honor both the explicit `config.integration` override and injected
87
- * `config.__eco.integration` metadata because pages can arrive here through
88
- * authored config as well as build-time component metadata.
89
- */
90
- getComponentIntegration(component) {
91
- return component?.config?.integration ?? component?.config?.__eco?.integration;
92
- }
93
- /**
94
- * Returns whether a component should stay inside the React render lane.
95
- *
96
- * Components without explicit integration metadata are treated as React-owned
97
- * here because this renderer only receives them after the route pipeline has
98
- * already selected the React integration.
99
- */
100
- isReactManagedComponent(component) {
101
- const integration = this.getComponentIntegration(component);
102
- return integration === void 0 || integration === this.name;
103
- }
104
- /**
105
- * Creates the canonical page-props payload used by router hydration.
106
- *
107
- * React pages embedded in a non-React HTML shell still need to expose the same
108
- * page-data contract as fully React-owned documents so navigation and hydration
109
- * can read one shared document payload consistently.
110
- */
111
- buildRouterPageDataScript(pageProps) {
112
- const safeJson = JSON.stringify(pageProps || {}).replace(/</g, "\\u003c");
113
- return `<script id="__ECO_PAGE_DATA__" type="application/json">${safeJson}<\/script>`;
114
- }
115
- getRouterDocumentAttributes() {
116
- if (!ReactRenderer.routerAdapter) {
117
- return void 0;
118
- }
119
- return {
120
- [ECO_DOCUMENT_OWNER_ATTRIBUTE]: "react-router"
121
- };
122
- }
123
- /**
124
- * Commits a framework-agnostic component to React semantics.
125
- *
126
- * This is one of the two real cast boundaries in this file. Core keeps
127
- * `EcoComponent` broad so integrations can share the same public surface; once
128
- * the React renderer is executing, `createElement()` needs a concrete React
129
- * component signature.
130
- */
131
- asReactComponent(component) {
132
- return component;
133
- }
134
- /**
135
- * Commits a mixed-shell component to the string-returning contract required by
136
- * non-React layouts and HTML templates.
137
- *
138
- * This is the second real cast boundary: once we decide a shell is not managed
139
- * by React, we call it directly and require serialized HTML back.
140
- */
141
- asNonReactShellComponent(component) {
142
- return component;
143
- }
144
- /**
145
- * Builds the serialized page-props payload embedded into the final HTML.
146
- *
147
- * The document payload is intentionally narrower than the full server render
148
- * input: only routing data, public page props, and explicitly allowed locals are
149
- * exposed to the browser.
150
- */
151
- buildSerializedPageProps(options) {
152
- return {
153
- ...options.pageProps,
154
- params: options.params,
155
- query: options.query,
156
- ...options.safeLocals && { locals: options.safeLocals }
157
- };
158
- }
159
- /**
160
- * Appends route hydration assets for a concrete page/view file to the current
161
- * HTML transformer state.
162
- */
163
- async appendHydrationAssetsForFile(filePath) {
164
- if (!filePath) {
165
- return;
166
- }
167
- const hydrationAssets = await this.buildRouteRenderAssets(filePath);
168
- this.appendProcessedDependencies(hydrationAssets);
169
- }
170
- /**
171
- * Renders a non-React layout or HTML template and enforces that mixed shells
172
- * return serialized HTML.
173
- *
174
- * The React renderer can compose through another integration's shell, but only
175
- * if that shell yields a string that can be inserted into the final document.
176
- */
177
- async renderNonReactShellComponent(Component, props, label) {
178
- const output = await Component(props);
179
- if (typeof output === "string") {
180
- return output;
181
- }
182
- throw new ReactRenderError(`${label} must return a string when used as a mixed shell for React pages.`);
183
- }
184
- /**
185
- * Renders one React component boundary while preserving already-resolved child HTML.
186
- *
187
- * When nested boundary resolution has already produced child HTML for this
188
- * boundary, the child payload must remain raw SSR output rather than a React
189
- * string child, otherwise React would escape it. This helper renders a unique
190
- * token through React and swaps that token back to the resolved HTML
191
- * afterward.
192
- *
193
- * @param input Component render input for the current boundary.
194
- * @param context React-specific render context for stable token generation.
195
- * @returns Serialized component HTML with resolved child markup preserved.
196
- */
197
- renderComponentHtml(input, context, runtimeContext) {
198
- if (input.children === void 0) {
199
- return this.normalizeBoundaryArtifactHtml(
200
- renderToString(createElement(this.asReactComponent(input.component), input.props))
201
- );
202
- }
203
- const resolvedChildHtml = typeof input.children === "string" ? input.children : String(input.children ?? "");
204
- const rawChildrenToken = `__ECO_RAW_HTML_CHILD_${context.componentInstanceId ?? "component"}__`;
205
- if (runtimeContext) {
206
- runtimeContext.rawChildrenToken = rawChildrenToken;
207
- runtimeContext.rawChildrenHtml = resolvedChildHtml;
208
- }
209
- const html = renderToString(
210
- createElement(this.asReactComponent(input.component), input.props, rawChildrenToken)
211
- );
212
- return this.normalizeBoundaryArtifactHtml(html.split(rawChildrenToken).join(resolvedChildHtml));
213
- }
214
- restoreRuntimeChildHtml(html, runtimeContext) {
215
- if (!runtimeContext?.rawChildrenToken || runtimeContext.rawChildrenHtml === void 0) {
216
- return html;
217
- }
218
- return html.split(runtimeContext.rawChildrenToken).join(runtimeContext.rawChildrenHtml);
219
- }
220
- async renderQueuedChildrenToHtml(children, runtimeContext, queuedResolutionsByToken, resolveToken) {
221
- if (children === void 0) {
222
- return void 0;
223
- }
224
- let html = this.normalizeBoundaryArtifactHtml(
225
- renderToString(createElement(Fragment, null, children))
226
- );
227
- html = this.restoreRuntimeChildHtml(html, runtimeContext);
228
- html = await this.resolveQueuedBoundaryTokens(html, queuedResolutionsByToken, resolveToken);
229
- return html;
230
- }
231
- async resolveQueuedBoundaryHtml(html, runtimeContext) {
232
- return this.resolveRendererOwnedQueuedBoundaryHtml({
233
- html,
234
- runtimeContext,
235
- queueLabel: "React",
236
- renderQueuedChildren: async (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => {
237
- const renderedHtml = await this.renderQueuedChildrenToHtml(
238
- children,
239
- currentRuntimeContext,
240
- queuedResolutionsByToken,
241
- resolveToken
242
- );
243
- return {
244
- assets: [],
245
- html: renderedHtml
246
- };
247
- }
248
- });
249
- }
250
- buildHydrationProps(props) {
251
- if (!props || !Object.prototype.hasOwnProperty.call(props, "locals")) {
252
- return props ?? {};
253
- }
254
- const { locals: _locals, ...hydrationProps } = props;
255
- return hydrationProps;
256
- }
257
- /**
258
- * Renders a React component for component-level orchestration.
259
- *
260
- * Behavior:
261
- * - SSR always returns the component's own root HTML (no synthetic wrapper).
262
- * - When an explicit component instance id is provided, a stable
263
- * `data-eco-component-id` attribute is attached so island hydration can target it.
264
- * - Without an explicit instance id, component renders remain plain SSR output.
265
- * - When resolved child HTML is provided, that boundary is treated as a pure SSR
266
- * composition step and does not emit hydration assets for the parent wrapper.
267
- *
268
- * This preserves DOM shape for global CSS/layout selectors while keeping a
269
- * deterministic mount target per component instance.
270
- */
271
- async renderComponent(input) {
272
- const runtimeContext = this.getQueuedBoundaryRuntime(input);
273
- if (!this.isReactManagedComponent(input.component)) {
274
- let props = input.props;
275
- if (input.children !== void 0) {
276
- props = {
277
- ...input.props,
278
- children: typeof input.children === "string" ? input.children : String(input.children ?? "")
279
- };
280
- }
281
- const html2 = await this.renderNonReactShellComponent(
282
- this.asNonReactShellComponent(input.component),
283
- props,
284
- "Component"
285
- );
286
- const hasDependencies = Boolean(input.component.config?.dependencies);
287
- const canResolveAssets = typeof this.assetProcessingService?.processDependencies === "function";
288
- const assets2 = hasDependencies && canResolveAssets ? await this.processComponentDependencies([input.component]) : void 0;
289
- const queuedBoundaryResolution2 = await this.resolveQueuedBoundaryHtml(html2, runtimeContext);
290
- const mergedAssets2 = this.htmlTransformer.dedupeProcessedAssets([
291
- ...assets2 ?? [],
292
- ...queuedBoundaryResolution2.assets
293
- ]);
294
- return {
295
- html: queuedBoundaryResolution2.html,
296
- canAttachAttributes: true,
297
- rootTag: this.getRootTagName(queuedBoundaryResolution2.html),
298
- integrationName: this.name,
299
- assets: mergedAssets2.length > 0 ? mergedAssets2 : void 0
300
- };
301
- }
302
- const componentConfig = input.component.config;
303
- const context = input.integrationContext ?? {};
304
- const hasResolvedChildHtml = input.children !== void 0;
305
- let html = this.renderComponentHtml(input, context, runtimeContext);
306
- const queuedBoundaryResolution = await this.resolveQueuedBoundaryHtml(html, runtimeContext);
307
- html = queuedBoundaryResolution.html;
308
- let canAttachAttributes = hasSingleRootElement(html);
309
- let rootTag = this.getRootTagName(html);
310
- const componentFile = componentConfig?.__eco?.file;
311
- let rootAttributes;
312
- let assets;
313
- if (canAttachAttributes && componentFile && context.componentInstanceId && this.assetProcessingService && !hasResolvedChildHtml) {
314
- const componentInstanceId = context.componentInstanceId;
315
- assets = await this.hydrationAssetService.buildComponentRenderAssets(componentFile, componentConfig);
316
- rootAttributes = {
317
- "data-eco-component-id": componentInstanceId,
318
- "data-eco-component-key": getReactIslandComponentKey(componentFile, componentConfig),
319
- "data-eco-props": btoa(JSON.stringify(this.buildHydrationProps(input.props)))
320
- };
321
- }
322
- const mergedAssets = this.htmlTransformer.dedupeProcessedAssets([
323
- ...assets ?? [],
324
- ...queuedBoundaryResolution.assets
325
- ]);
326
- return {
327
- html,
328
- canAttachAttributes,
329
- rootTag,
330
- integrationName: this.name,
331
- rootAttributes,
332
- assets: mergedAssets.length > 0 ? mergedAssets : void 0
333
- };
334
- }
335
- createComponentBoundaryRuntime(options) {
336
- return this.createQueuedBoundaryRuntime({
337
- boundaryInput: options.boundaryInput,
338
- rendererCache: options.rendererCache,
339
- createRuntimeContext: (integrationContext, rendererCache) => ({
340
- rendererCache,
341
- componentInstanceScope: integrationContext.componentInstanceId,
342
- nextBoundaryId: 0,
343
- queuedResolutions: [],
344
- rawChildrenToken: void 0,
345
- rawChildrenHtml: void 0
346
- })
347
- });
348
- }
349
- /**
350
- * Checks if the given file path corresponds to an MDX file based on configured extensions.
351
- * @param filePath - The file path to check
352
- * @returns True if the file is an MDX file
353
- */
354
- isMdxFile(filePath) {
355
- return this.pageModuleService.isMdxFile(filePath);
356
- }
357
- usesIntegrationPageImporter(file) {
358
- return this.pageModuleService.isMdxFile(file);
359
- }
360
- async importIntegrationPageFile(file) {
361
- return await this.pageModuleService.importMdxPageFile(file);
362
- }
363
- normalizeImportedPageFile(file, pageModule) {
364
- const reactModule = pageModule;
365
- const { default: Page, getMetadata, config } = reactModule;
366
- if (this.pageModuleService.isMdxFile(file) && config) {
367
- Page.config = config;
368
- }
369
- return {
370
- ...pageModule,
371
- default: Page,
372
- getMetadata,
373
- config
374
- };
375
- }
376
- /**
377
- * Processes MDX-specific configuration dependencies including layout dependencies.
378
- * @param pagePath - Absolute path to the MDX page file
379
- * @returns Processed assets for MDX configuration dependencies
380
- */
381
- async processMdxConfigDependencies(pagePath) {
382
- const pageModule = await this.importPageFile(pagePath);
383
- const config = pageModule.config;
384
- const resolvedLayout = config?.layout;
385
- const components = [];
386
- if (resolvedLayout?.config?.dependencies) {
387
- const layoutConfig = this.pageModuleService.ensureConfigFileMetadata(resolvedLayout.config, pagePath);
388
- components.push({ config: layoutConfig });
389
- }
390
- if (config?.dependencies) {
391
- const configWithMeta = {
392
- ...config,
393
- __eco: { id: rapidhash(pagePath).toString(36), file: pagePath, integration: "react" }
394
- };
395
- components.push({ config: configWithMeta });
396
- }
397
- const processedDependencies = await this.processComponentDependencies(components);
398
- const eagerSsrLazyDependencies = await this.processDeclaredMdxSsrLazyDependencies(components, pagePath);
399
- return [...processedDependencies, ...eagerSsrLazyDependencies];
400
- }
401
- async processDeclaredMdxSsrLazyDependencies(components, pagePath) {
402
- if (!this.assetProcessingService?.processDependencies) {
403
- return [];
404
- }
405
- const dependencies = this.collectDeclaredMdxSsrLazyDependencies(components);
406
- if (dependencies.length === 0) {
407
- return [];
408
- }
409
- return this.assetProcessingService.processDependencies(dependencies, `react-mdx-ssr-lazy:${pagePath}`);
410
- }
411
- collectDeclaredMdxSsrLazyDependencies(components) {
412
- const dependencies = [];
413
- const visitedConfigs = /* @__PURE__ */ new Set();
414
- const seenKeys = /* @__PURE__ */ new Set();
415
- const normalizeAttributes = (attributes) => ({
416
- type: "module",
417
- defer: "",
418
- ...attributes ?? {}
419
- });
420
- const collect = (config) => {
421
- if (!config || visitedConfigs.has(config)) {
422
- return;
423
- }
424
- visitedConfigs.add(config);
425
- const componentFile = config.__eco?.file;
426
- if (componentFile) {
427
- const componentDir = path.dirname(componentFile);
428
- for (const script of config.dependencies?.scripts ?? []) {
429
- if (typeof script === "string" || !script.lazy || script.ssr !== true) {
430
- continue;
431
- }
432
- const attributes = normalizeAttributes(script.attributes);
433
- if (script.content) {
434
- const key2 = `content:${script.content}:${JSON.stringify(attributes)}`;
435
- if (seenKeys.has(key2)) {
436
- continue;
437
- }
438
- seenKeys.add(key2);
439
- dependencies.push(
440
- AssetFactory.createContentScript({
441
- position: "head",
442
- content: script.content,
443
- attributes
444
- })
445
- );
446
- continue;
447
- }
448
- if (!script.src) {
449
- continue;
450
- }
451
- const resolvedPath = path.resolve(componentDir, script.src);
452
- const key = `file:${resolvedPath}:${JSON.stringify(attributes)}`;
453
- if (seenKeys.has(key)) {
454
- continue;
455
- }
456
- seenKeys.add(key);
457
- dependencies.push(
458
- AssetFactory.createFileScript({
459
- filepath: resolvedPath,
460
- position: "head",
461
- attributes
462
- })
463
- );
464
- }
465
- }
466
- if (config.layout?.config) {
467
- collect(config.layout.config);
468
- }
469
- for (const nestedComponent of config.dependencies?.components ?? []) {
470
- collect(nestedComponent?.config);
471
- }
472
- };
473
- for (const component of components) {
474
- collect(component.config);
475
- }
476
- return dependencies;
477
- }
478
- async buildRouteRenderAssets(pagePath) {
479
- try {
480
- const pageModule = await this.importPageFile(pagePath);
481
- const shouldHydrate = ReactRenderer.explicitGraphEnabled ? true : this.pageModuleService.shouldHydratePage(pageModule);
482
- if (!shouldHydrate) {
483
- return [];
484
- }
485
- const isMdx = this.pageModuleService.isMdxFile(pagePath);
486
- const declaredModules = this.pageModuleService.collectPageDeclaredModules(pageModule);
487
- const processedAssets = await this.hydrationAssetService.buildRouteRenderAssets(
488
- pagePath,
489
- isMdx,
490
- declaredModules
491
- );
492
- if (isMdx) {
493
- const mdxConfigAssets = await this.processMdxConfigDependencies(pagePath);
494
- return [...processedAssets, ...mdxConfigAssets];
495
- }
496
- return processedAssets;
497
- } catch (error) {
498
- if (error instanceof BundleError) {
499
- console.error("[ecopages] Bundle errors:", error.logs);
500
- }
501
- throw new ReactRenderError(
502
- `Failed to generate hydration script: ${error instanceof Error ? error.message : String(error)}`
503
- );
504
- }
505
- }
506
- /**
507
- * Renders a full route response for the filesystem page pipeline.
508
- *
509
- * This path receives already-resolved route metadata, layout, locals, and HTML
510
- * template instances from the shared renderer orchestration. Its main job is to
511
- * serialize only the browser-safe page payload, compose the mixed React/non-
512
- * React shell tree, and hand the result back as a document body.
513
- */
514
- async render({
515
- params,
516
- query,
517
- props,
518
- locals,
519
- pageLocals,
520
- metadata,
521
- Page,
522
- Layout,
523
- HtmlTemplate,
524
- pageProps
525
- }) {
526
- try {
527
- const safeLocals = this.getSerializableLocals(locals, Page.requires);
528
- const allPageProps = this.buildSerializedPageProps({
529
- pageProps,
530
- params,
531
- query,
532
- safeLocals
533
- });
534
- return await this.renderPageWithDocumentShell({
535
- page: {
536
- component: Page,
537
- props: { params, query, ...props, locals: pageLocals }
538
- },
539
- layout: Layout ? {
540
- component: Layout,
541
- props: locals ? { locals } : {}
542
- } : void 0,
543
- htmlTemplate: HtmlTemplate,
544
- metadata,
545
- pageProps: allPageProps,
546
- documentProps: !this.isReactManagedComponent(HtmlTemplate) && ReactRenderer.routerAdapter ? { headContent: this.buildRouterPageDataScript(allPageProps) } : void 0
547
- });
548
- } catch (error) {
549
- throw this.createRenderError("Failed to render component", error);
550
- }
551
- }
552
- getDocumentAttributes() {
553
- return this.getRouterDocumentAttributes();
554
- }
555
- /**
556
- * Safely extracts the declared subset of locals for client-side hydration.
557
- *
558
- * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
559
- * request-scoped data (e.g., session). Only keys explicitly declared via
560
- * `Page.requires` are serialized to the client so sensitive request-only data
561
- * is not leaked into hydration payloads by default.
562
- *
563
- * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
564
- * to prevent accidental use. This method safely detects that case and returns
565
- * `undefined` instead of throwing.
566
- *
567
- * @param locals - The locals object from the render context
568
- * @param requiredLocals - Keys explicitly requested for client hydration
569
- * @returns The filtered locals object if serializable, undefined otherwise
570
- */
571
- getSerializableLocals(locals, requiredLocals) {
572
- try {
573
- if (!locals) {
574
- return void 0;
575
- }
576
- const requiredKeys = requiredLocals ? Array.isArray(requiredLocals) ? requiredLocals : [requiredLocals] : [];
577
- if (requiredKeys.length === 0) {
578
- return void 0;
579
- }
580
- const serializedLocals = Object.fromEntries(
581
- requiredKeys.filter((key) => Object.prototype.hasOwnProperty.call(locals, key)).map((key) => [key, locals[key]])
582
- );
583
- if (Object.keys(serializedLocals).length > 0) {
584
- return serializedLocals;
585
- }
586
- return void 0;
587
- } catch (e) {
588
- if (e instanceof LocalsAccessError) {
589
- return void 0;
590
- }
591
- throw e;
592
- }
593
- }
594
- /**
595
- * Renders an arbitrary React view through the application's HTML shell.
596
- *
597
- * Unlike route rendering, this path starts from a single component rather than a
598
- * page module discovered by the router. It still needs to resolve metadata,
599
- * layout dependencies, and hydration assets so direct `ctx.render()` calls match
600
- * normal page responses.
601
- */
602
- async renderToResponse(view, props, ctx) {
603
- try {
604
- const viewConfig = view.config;
605
- const Layout = viewConfig?.layout;
606
- const ViewComponent = this.asReactComponent(view);
607
- const normalizedProps = props ?? {};
608
- if (ctx.partial) {
609
- return this.renderPartialViewResponse({
610
- view,
611
- props,
612
- ctx,
613
- renderInline: async () => await renderToReadableStream(createElement(ViewComponent, normalizedProps))
614
- });
615
- }
616
- const HtmlTemplate = await this.getHtmlTemplate();
617
- const metadata = await this.resolveViewMetadata(view, props);
618
- await this.prepareViewDependencies(view, Layout);
619
- await this.appendHydrationAssetsForFile(viewConfig?.__eco?.file);
620
- const viewRender = await this.renderComponentBoundary({
621
- component: view,
622
- props: normalizedProps
623
- });
624
- const layoutRender = Layout ? await this.renderComponentBoundary({
625
- component: Layout,
626
- props: {},
627
- children: viewRender.html
628
- }) : void 0;
629
- const documentRender = await this.renderComponentBoundary({
630
- component: HtmlTemplate,
631
- props: {
632
- metadata,
633
- pageProps: normalizedProps,
634
- ...!this.isReactManagedComponent(HtmlTemplate) && ReactRenderer.routerAdapter ? { headContent: this.buildRouterPageDataScript(normalizedProps) } : {}
635
- },
636
- children: layoutRender?.html ?? viewRender.html
637
- });
638
- this.appendProcessedDependencies(viewRender.assets, layoutRender?.assets, documentRender.assets);
639
- const transformedHtml = await this.finalizeResolvedHtml({
640
- html: `${this.DOC_TYPE}${documentRender.html}`,
641
- partial: false,
642
- documentAttributes: this.getRouterDocumentAttributes()
643
- });
644
- return this.createHtmlResponse(transformedHtml, ctx);
645
- } catch (error) {
646
- throw this.createRenderError("Failed to render view", error);
647
- }
648
- }
649
- }
650
- export {
651
- BundleError,
652
- ReactRenderError,
653
- ReactRenderer
654
- };