@ecopages/react 0.2.0-beta.9 → 0.2.0-rc.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 (142) hide show
  1. package/README.md +179 -7
  2. package/package.json +53 -28
  3. package/src/app/client-only.js +15 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +31 -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} +23 -8
  9. package/src/bundling/bundle.js +120 -0
  10. package/src/bundling/discover-layout-runtime-modules.d.ts +32 -0
  11. package/src/bundling/discover-layout-runtime-modules.js +185 -0
  12. package/src/bundling/runtime-alias-map.d.ts +13 -0
  13. package/src/bundling/runtime-alias-map.js +113 -0
  14. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +25 -4
  15. package/src/bundling/runtime-bundle.js +258 -0
  16. package/src/bundling/runtime-interop-plugin.js +34 -0
  17. package/src/bundling/runtime-mode.d.ts +9 -0
  18. package/src/bundling/runtime-mode.js +11 -0
  19. package/src/bundling/runtime-modules.d.ts +29 -0
  20. package/src/bundling/runtime-modules.js +49 -0
  21. package/src/client-graph/ast-transform.d.ts +18 -0
  22. package/src/client-graph/ast-transform.js +426 -0
  23. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +23 -13
  24. package/src/client-graph/boundary-cache.js +182 -0
  25. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +4 -13
  26. package/src/client-graph/boundary-plugin.js +149 -0
  27. package/src/client-graph/component-config-traversal.js +77 -0
  28. package/src/client-graph/declared-modules.js +69 -0
  29. package/src/client-graph/module-classification.d.ts +3 -0
  30. package/src/client-graph/module-classification.js +43 -0
  31. package/src/{utils → client-graph}/reachability-analyzer.d.ts +4 -12
  32. package/src/client-graph/reachability-analyzer.js +515 -0
  33. package/src/client-graph/specifier-classification.d.ts +75 -0
  34. package/src/client-graph/specifier-classification.js +214 -0
  35. package/src/contracts/router-adapter.js +6 -0
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  37. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  38. package/src/hmr/hmr-scripts.js +44 -0
  39. package/src/hmr/hmr-strategy.d.ts +74 -0
  40. package/src/hmr/hmr-strategy.js +351 -0
  41. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  42. package/src/hmr/page-metadata-cache.js +44 -0
  43. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  44. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  45. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  46. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  47. package/src/hydration/bootstrap-imports.d.ts +25 -0
  48. package/src/hydration/bootstrap-imports.js +33 -0
  49. package/src/hydration/hydration-asset.d.ts +84 -0
  50. package/src/hydration/hydration-asset.js +227 -0
  51. package/src/hydration/hydration-scripts.d.ts +104 -0
  52. package/src/hydration/hydration-scripts.js +483 -0
  53. package/src/hydration/hydration-scripts.test.browser.js +199 -0
  54. package/src/hydration/page-data-manifest.d.ts +58 -0
  55. package/src/hydration/page-data-manifest.js +97 -0
  56. package/src/hydration/page-data-reader.d.ts +31 -0
  57. package/src/hydration/page-data-reader.js +77 -0
  58. package/src/hydration/page-payload.d.ts +67 -0
  59. package/src/hydration/page-payload.js +106 -0
  60. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  61. package/src/hydration/serialize-page-data-script.js +30 -0
  62. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +6 -6
  63. package/src/mdx/mdx-config-dependency.js +110 -0
  64. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  65. package/src/mdx/mdx-loader-plugin.js +8 -0
  66. package/src/page/page-module.d.ts +46 -0
  67. package/src/page/page-module.js +74 -0
  68. package/src/plugin/react.constants.js +1 -0
  69. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +9 -3
  70. package/src/plugin/react.plugin.js +241 -0
  71. package/src/plugin/react.types.d.ts +156 -0
  72. package/src/plugin/react.types.js +1 -0
  73. package/src/render/component-ownership.d.ts +49 -0
  74. package/src/render/component-ownership.js +46 -0
  75. package/src/render/component-ssr.d.ts +113 -0
  76. package/src/render/component-ssr.js +180 -0
  77. package/src/render/eco-embed.js +9 -0
  78. package/src/render/errors.d.ts +16 -0
  79. package/src/render/errors.js +23 -0
  80. package/src/render/html-boundary.js +59 -0
  81. package/src/render/layout-compose.d.ts +66 -0
  82. package/src/render/layout-compose.js +134 -0
  83. package/src/render/react-renderer.d.ts +139 -0
  84. package/src/render/react-renderer.js +450 -0
  85. package/src/render/react-runtime.d.ts +13 -0
  86. package/src/render/react-runtime.js +26 -0
  87. package/src/render/unified-layout-composition.d.ts +53 -0
  88. package/src/render/unified-layout-composition.js +78 -0
  89. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  90. package/src/eco-embed.js +0 -11
  91. package/src/react-hmr-strategy.d.ts +0 -230
  92. package/src/react-hmr-strategy.js +0 -657
  93. package/src/react-renderer.d.ts +0 -233
  94. package/src/react-renderer.js +0 -622
  95. package/src/react.constants.js +0 -4
  96. package/src/react.plugin.js +0 -209
  97. package/src/react.types.d.ts +0 -88
  98. package/src/react.types.js +0 -0
  99. package/src/router-adapter.js +0 -0
  100. package/src/services/pages-index.d.ts +0 -64
  101. package/src/services/pages-index.js +0 -73
  102. package/src/services/react-bundle.service.js +0 -86
  103. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  104. package/src/services/react-hydration-asset.service.d.ts +0 -84
  105. package/src/services/react-hydration-asset.service.js +0 -217
  106. package/src/services/react-mdx-config-dependency.service.js +0 -122
  107. package/src/services/react-page-module.service.d.ts +0 -88
  108. package/src/services/react-page-module.service.js +0 -166
  109. package/src/services/react-page-payload.service.d.ts +0 -46
  110. package/src/services/react-page-payload.service.js +0 -67
  111. package/src/services/react-runtime-bundle.service.js +0 -192
  112. package/src/utils/client-graph-boundary-cache.js +0 -116
  113. package/src/utils/client-graph-boundary-plugin.js +0 -552
  114. package/src/utils/client-only.js +0 -19
  115. package/src/utils/component-config-traversal.js +0 -54
  116. package/src/utils/declared-modules.js +0 -47
  117. package/src/utils/dynamic.js +0 -12
  118. package/src/utils/dynamic.test.browser.js +0 -33
  119. package/src/utils/hmr-scripts.js +0 -31
  120. package/src/utils/html-boundary.js +0 -55
  121. package/src/utils/hydration-scripts.d.ts +0 -92
  122. package/src/utils/hydration-scripts.js +0 -358
  123. package/src/utils/hydration-scripts.test.browser.js +0 -198
  124. package/src/utils/reachability-analyzer.js +0 -339
  125. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  126. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  127. package/src/utils/react-mdx-loader-plugin.js +0 -45
  128. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  129. package/src/utils/react-runtime-alias-map.js +0 -90
  130. /package/src/{utils → app}/client-only.d.ts +0 -0
  131. /package/src/{utils → app}/dynamic.d.ts +0 -0
  132. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  133. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  134. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  135. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  136. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  137. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  138. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  139. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  140. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  141. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  142. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,483 @@
1
+ /**
2
+ * Hydration script generators for React pages.
3
+ * These functions create the page entry modules that hydrate React routes.
4
+ * @module
5
+ */
6
+ import { getDevPageDataReaderBootstrapSource } from './page-data-reader.js';
7
+ function getPageDataReaderSource(options) {
8
+ if (options.pageDataReaderImportPath) {
9
+ return `import { readPageDataDocument, getPageDataFromDocument as getPageData } from "${options.pageDataReaderImportPath}";`;
10
+ }
11
+ return getDevPageDataReaderBootstrapSource();
12
+ }
13
+ /**
14
+ * Generates the page component import for the hydration entry.
15
+ *
16
+ * @remarks
17
+ * MDX pages need a namespace import so `config` can be copied onto the default
18
+ * export before layout normalization runs.
19
+ */
20
+ function getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath) {
21
+ return isMdx
22
+ ? `import * as MDXModule from "${importPath}";
23
+ import { ensurePageConfigLayouts } from "${pageLayoutNormalizationImportPath}";
24
+ const Page = MDXModule.default;
25
+ if (MDXModule.config) {
26
+ Page.config = MDXModule.config;
27
+ ensurePageConfigLayouts(Page.config);
28
+ }`
29
+ : `import Page from "${importPath}";`;
30
+ }
31
+ /**
32
+ * Assigns `NewPage` from a hot-reloaded module, including MDX `config` reattach.
33
+ */
34
+ function getHmrImportStatement(isMdx) {
35
+ return isMdx
36
+ ? `const NewPage = newModule.default;
37
+ if (newModule.config) {
38
+ NewPage.config = newModule.config;
39
+ ensurePageConfigLayouts(NewPage.config);
40
+ }`
41
+ : 'const NewPage = newModule.default;';
42
+ }
43
+ function getComponentType(isMdx) {
44
+ return isMdx ? 'MDX' : 'React';
45
+ }
46
+ /**
47
+ * Browser hook that unmounts the page React root and releases navigation ownership.
48
+ *
49
+ * @remarks
50
+ * Emitted into the page bootstrap so browser-router / react-router handoff can
51
+ * tear down React without knowing React root internals.
52
+ */
53
+ function getPageRootCleanupScript() {
54
+ return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
55
+ window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
56
+ window.__ECO_PAGES__.react.cleanupPageRoot = () => {
57
+ const activeRoot = window.__ECO_PAGES__.react?.pageRoot || root;
58
+ if (!activeRoot) {
59
+ window.__ECO_PAGES__.react.pageRoot = null;
60
+ window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
61
+ delete window.__ECO_PAGES__.page;
62
+ return;
63
+ }
64
+ window.__ECO_PAGES__.react.pageRoot = null;
65
+ window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
66
+ delete window.__ECO_PAGES__.page;
67
+ root = null;
68
+ activeRoot.unmount();
69
+ };`;
70
+ }
71
+ /**
72
+ * Registers react-router with the shared navigation coordinator when it does
73
+ * not already own SPA navigation.
74
+ */
75
+ function getRouterBootstrapRegistrationScript() {
76
+ return `const currentOwnerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
77
+ if (!(currentOwnerState?.owner === "react-router" && currentOwnerState.canHandleSpaNavigation)) {
78
+ window.__ECO_PAGES__?.navigation?.register({
79
+ owner: "react-router",
80
+ cleanupBeforeHandoff: async () => {
81
+ window.__ECO_PAGES__?.react?.cleanupPageRoot?.();
82
+ }
83
+ });
84
+ window.__ECO_PAGES__?.navigation?.claimOwnership?.("react-router");
85
+ }`;
86
+ }
87
+ /**
88
+ * Predicate used by router bootstraps to keep a long-lived hydrateRoot across
89
+ * client navigations when react-router already owns the document.
90
+ */
91
+ function getReuseExistingRouterRootScript() {
92
+ return `const shouldReuseExistingRouterRoot = () => {
93
+ const ownerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
94
+ return Boolean(
95
+ window.__ECO_PAGES__.react?.pageRoot &&
96
+ ownerState?.owner === "react-router" &&
97
+ ownerState.canHandleSpaNavigation
98
+ );
99
+ };`;
100
+ }
101
+ /**
102
+ * Registers `mount` under `window.__ECO_PAGES__.rerunScripts` for after-swap re-execution.
103
+ */
104
+ function getRerunRegistrationScript(scriptId) {
105
+ return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
106
+ window.__ECO_PAGES__.rerunScripts = window.__ECO_PAGES__.rerunScripts || {};
107
+ window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}] = mount;`;
108
+ }
109
+ function getHydrationTimingScript() {
110
+ return `const __ecoRecordHydrationReady = () => {
111
+ if (window.__ECO_DEV_HYDRATION_STARTED__ == null) return;
112
+ window.__ECO_DEV_HYDRATION_MS__ = Math.round(performance.now() - window.__ECO_DEV_HYDRATION_STARTED__);
113
+ };`;
114
+ }
115
+ /**
116
+ * HMR handler for router pages: prefers coordinator reload when layouts change,
117
+ * otherwise re-renders the existing root.
118
+ */
119
+ function getRouterHmrHandlerScript(options) {
120
+ const { importPath, isMdx } = options;
121
+ return ` window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
122
+ try {
123
+ const newModule = await import(newUrl);
124
+ const nextProps = getPageData();
125
+ ${getHmrImportStatement(isMdx)}
126
+ const currentPageLayoutStack = (Component) =>
127
+ (Component.config?.layouts ?? []).map((layout) => layout?.config?.identity?.file ?? '').join('|');
128
+ const currentPageLayoutStackKey = currentPageLayoutStack(Page);
129
+ const nextPageLayoutStackKey = currentPageLayoutStack(NewPage);
130
+
131
+ if (window.__ECO_PAGES__?.navigation?.getOwnerState().owner === "react-router") {
132
+ await window.__ECO_PAGES__?.navigation?.reloadCurrentPage?.({
133
+ clearCache: currentPageLayoutStackKey !== nextPageLayoutStackKey,
134
+ moduleUrl: newUrl,
135
+ source: "react-router"
136
+ });
137
+ console.log("[ecopages] ${getComponentType(isMdx)} component updated via router");
138
+ return;
139
+ }
140
+
141
+ const nextPageData = readPageDataDocument();
142
+ window.__ECO_PAGES__.page = {
143
+ module: nextPageData.moduleUrl || pageModuleUrl,
144
+ props: nextProps
145
+ };
146
+ root.render(createTree(NewPage, nextProps));
147
+ console.log("[ecopages] ${getComponentType(isMdx)} component updated");
148
+ } catch (e) {
149
+ console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
150
+ }
151
+ };`;
152
+ }
153
+ /**
154
+ * HMR handler for non-router pages: hot-imports the module and re-renders the layout tree.
155
+ */
156
+ function getNonRouterHmrHandlerScript(options) {
157
+ const { importPath, isMdx } = options;
158
+ return ` window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
159
+ try {
160
+ const newModule = await import(newUrl);
161
+ ${getHmrImportStatement(isMdx)}
162
+ root.render(createTree(NewPage, props));
163
+ console.log("[ecopages] ${getComponentType(isMdx)} component updated");
164
+ } catch (e) {
165
+ console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
166
+ }
167
+ };`;
168
+ }
169
+ /**
170
+ * Creates a readable hydration script with router support.
171
+ *
172
+ * @remarks
173
+ * Router-managed pages keep a long-lived root across client navigations.
174
+ * When `hmrEnabled` is true, HMR handlers are included. Otherwise the same
175
+ * semantic source is emitted without HMR hooks; the asset layer bundles it and
176
+ * production builds minify it.
177
+ */
178
+ function createScriptWithRouter(options) {
179
+ const { importPath, isMdx, router, reactImportPath, reactDomClientImportPath, routerImportPath, scriptId, hmrEnabled, } = options;
180
+ const pageModuleUrlExpression = options.pageModuleUrlExpression ?? 'import.meta.url';
181
+ const { components, getRouterProps } = router;
182
+ if (!routerImportPath) {
183
+ throw new Error('routerImportPath is required when router adapter is configured');
184
+ }
185
+ const pageLayoutNormalizationImportPath = options.pageLayoutNormalizationImportPath;
186
+ const hmrInit = hmrEnabled
187
+ ? `window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
188
+ `
189
+ : '';
190
+ const hmrHandler = hmrEnabled ? getRouterHmrHandlerScript({ importPath, isMdx }) : '';
191
+ return `
192
+ import { hydrateRoot } from "${reactDomClientImportPath}";
193
+ import { createElement } from "${reactImportPath}";
194
+ import { ${components.router}, ${components.pageContent} } from "${routerImportPath}";
195
+ ${getPageDataReaderSource(options)}
196
+ ${getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath)}
197
+ const pageModuleUrl = ${pageModuleUrlExpression};
198
+ export default Page;
199
+ export const config = Page.config;
200
+ const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
201
+
202
+ if (isActivePageEntry) {
203
+
204
+ window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
205
+ ${hmrInit}window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
206
+ window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
207
+ let root = window.__ECO_PAGES__.react.pageRoot;
208
+ ${getPageRootCleanupScript()}
209
+ ${getRouterBootstrapRegistrationScript()}
210
+ ${getReuseExistingRouterRootScript()}
211
+ ${getHydrationTimingScript()}
212
+
213
+ const initialPageData = readPageDataDocument();
214
+ const props = initialPageData.props;
215
+
216
+ window.__ECO_PAGES__.page = {
217
+ module: initialPageData.moduleUrl || pageModuleUrl,
218
+ props
219
+ };
220
+
221
+ const createTree = (Component, props) => {
222
+ const pageContent = createElement(${components.pageContent});
223
+ return createElement(${components.router}, ${getRouterProps('Component', 'props')}, pageContent);
224
+ };
225
+
226
+ const mount = () => {
227
+ const pageData = readPageDataDocument();
228
+ const props = pageData.props;
229
+ window.__ECO_PAGES__.page = {
230
+ module: pageData.moduleUrl || pageModuleUrl,
231
+ props
232
+ };
233
+
234
+ if (shouldReuseExistingRouterRoot()) {
235
+ root = window.__ECO_PAGES__.react.pageRoot;
236
+ return;
237
+ }
238
+
239
+ if (window.__ECO_PAGES__.react?.pageRoot) {
240
+ root = window.__ECO_PAGES__.react.pageRoot;
241
+ return;
242
+ }
243
+
244
+ window.__ECO_DEV_HYDRATION_STARTED__ = performance.now();
245
+ root = hydrateRoot(document.body, createTree(Page, props), {
246
+ onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
247
+ });
248
+ window.__ECO_PAGES__.react.pageRoot = root;
249
+ __ecoRecordHydrationReady();
250
+ ${hmrHandler}
251
+ };
252
+
253
+ ${getRerunRegistrationScript(scriptId)}
254
+
255
+ if (document.readyState === "loading") {
256
+ document.addEventListener("DOMContentLoaded", mount);
257
+ } else {
258
+ mount();
259
+ }
260
+ }
261
+ `.trim();
262
+ }
263
+ /**
264
+ * Creates a readable hydration script without router.
265
+ *
266
+ * @remarks
267
+ * Reconstructs the page and layout tree via `composeLayoutPageTree` so hydration
268
+ * matches SSR. HMR handlers are included only when `hmrEnabled` is true.
269
+ */
270
+ function createScriptWithoutRouter(options) {
271
+ const { importPath, isMdx, reactImportPath, reactDomClientImportPath, scriptId, hmrEnabled } = options;
272
+ const pageModuleUrlExpression = options.pageModuleUrlExpression ?? 'import.meta.url';
273
+ const layoutComposeImportPath = options.layoutComposeImportPath;
274
+ const pageLayoutNormalizationImportPath = options.pageLayoutNormalizationImportPath;
275
+ const hmrInit = hmrEnabled
276
+ ? `window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
277
+ `
278
+ : '';
279
+ const hmrHandler = hmrEnabled ? getNonRouterHmrHandlerScript({ importPath, isMdx }) : '';
280
+ return `
281
+ import { hydrateRoot } from "${reactDomClientImportPath}";
282
+ import { createElement } from "${reactImportPath}";
283
+ import { composeLayoutPageTree } from "${layoutComposeImportPath}";
284
+ ${getPageDataReaderSource(options)}
285
+ ${getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath)}
286
+ const pageModuleUrl = ${pageModuleUrlExpression};
287
+ export default Page;
288
+ export const config = Page.config;
289
+ const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
290
+
291
+ if (isActivePageEntry) {
292
+
293
+ window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
294
+ ${hmrInit}window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
295
+ window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
296
+ let root = window.__ECO_PAGES__.react.pageRoot;
297
+ ${getPageRootCleanupScript()}
298
+ ${getHydrationTimingScript()}
299
+
300
+ const initialPageData = readPageDataDocument();
301
+ const props = initialPageData.props;
302
+
303
+ window.__ECO_PAGES__.page = {
304
+ module: initialPageData.moduleUrl || pageModuleUrl,
305
+ props
306
+ };
307
+
308
+ const createTree = (Component, props) => composeLayoutPageTree(Component, props);
309
+
310
+ const mount = () => {
311
+ const pageData = readPageDataDocument();
312
+ const props = pageData.props;
313
+ window.__ECO_PAGES__.page = {
314
+ module: pageData.moduleUrl || pageModuleUrl,
315
+ props
316
+ };
317
+
318
+ if (window.__ECO_PAGES__.react?.pageRoot) {
319
+ root = window.__ECO_PAGES__.react.pageRoot;
320
+ root.render(createTree(Page, props));
321
+ } else {
322
+ window.__ECO_DEV_HYDRATION_STARTED__ = performance.now();
323
+ root = hydrateRoot(document.body, createTree(Page, props), {
324
+ onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
325
+ });
326
+ window.__ECO_PAGES__.react.pageRoot = root;
327
+ __ecoRecordHydrationReady();
328
+ }
329
+ ${hmrHandler}
330
+ };
331
+
332
+ ${getRerunRegistrationScript(scriptId)}
333
+
334
+ if (document.readyState === "loading") {
335
+ document.addEventListener("DOMContentLoaded", mount);
336
+ } else {
337
+ mount();
338
+ }
339
+ }
340
+ `.trim();
341
+ }
342
+ /**
343
+ * Creates a page hydration entry module.
344
+ *
345
+ * @remarks
346
+ * Always emits readable source. Production page assets set `bundle: true` so
347
+ * core's content-script processor minifies the result. Do not hand-minify here.
348
+ */
349
+ export function createHydrationScript(options) {
350
+ return options.router ? createScriptWithRouter(options) : createScriptWithoutRouter(options);
351
+ }
352
+ /**
353
+ * Registers an HMR handler that hot-imports an island module and re-renders mounted roots.
354
+ */
355
+ function getIslandHmrHandlerScript(options) {
356
+ const { importPath, targetSelector } = options;
357
+ return ` window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
358
+ window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
359
+ window.__ECO_PAGES__.islandRoots = window.__ECO_PAGES__.islandRoots || {};
360
+ window.__ECO_PAGES__.hmrHandlers[${JSON.stringify(importPath)}] = async (newUrl) => {
361
+ try {
362
+ const nextModule = await import(newUrl);
363
+ const Component = resolveComponent(nextModule);
364
+ if (!Component) {
365
+ return;
366
+ }
367
+
368
+ document.querySelectorAll(${JSON.stringify(targetSelector)}).forEach((target) => {
369
+ if (!(target instanceof HTMLElement)) {
370
+ return;
371
+ }
372
+
373
+ const componentKey = target.getAttribute("data-eco-component-key") ?? "";
374
+ const props = JSON.parse(atob(target.getAttribute("data-eco-props") || "e30="));
375
+ let container = target;
376
+
377
+ if (target.tagName.toLowerCase() !== "eco-island") {
378
+ container = document.createElement("eco-island");
379
+ container.style.display = "block";
380
+ container.setAttribute("data-eco-component-key", componentKey);
381
+ container.setAttribute("data-eco-props", target.getAttribute("data-eco-props") || "e30=");
382
+ target.replaceWith(container);
383
+ }
384
+
385
+ let root = window.__ECO_PAGES__.islandRoots[componentKey];
386
+ if (!root) {
387
+ root = createRoot(container);
388
+ window.__ECO_PAGES__.islandRoots[componentKey] = root;
389
+ }
390
+
391
+ root.render(createElement(Component, props));
392
+ });
393
+ console.log("[ecopages] Island component updated");
394
+ } catch (error) {
395
+ console.error("[ecopages] Failed to hot-reload island component:", error);
396
+ }
397
+ };`;
398
+ }
399
+ /**
400
+ * Creates the client bootstrap for component-level React islands.
401
+ *
402
+ * @remarks
403
+ * Island scripts use `bundle: false`, so compact output still needs a
404
+ * handwritten string.
405
+ */
406
+ export function createIslandHydrationScript(options) {
407
+ const targetSelector = JSON.stringify(options.targetSelector);
408
+ const componentRef = JSON.stringify(options.componentRef ?? '');
409
+ const componentFile = JSON.stringify(options.componentFile ?? '');
410
+ const scriptId = options.scriptId;
411
+ const hmrHandler = options.hmrEnabled
412
+ ? getIslandHmrHandlerScript({ importPath: options.importPath, targetSelector: options.targetSelector })
413
+ : '';
414
+ if (options.minify) {
415
+ return `import{createRoot as cr}from"${options.reactDomClientImportPath}";import{createElement as ce}from"${options.reactImportPath}";import*as M from"${options.importPath}";const r=${componentRef};const f=${componentFile};const mv=Object.values(M);const c=mv.find((e)=>{if(typeof e!=="function")return false;const ec=e.config?.identity;if(!ec)return false;if(r&&ec.id===r)return true;if(f&&ec.file===f)return true;return false;})??(typeof M.default==="function"?M.default:mv.find((e)=>typeof e==="function")??null);const m=()=>{const ts=document.querySelectorAll(${targetSelector});if(!c||ts.length===0)return;ts.forEach((t)=>{if(!(t instanceof HTMLElement))return;const p=JSON.parse(atob(t.getAttribute("data-eco-props")||"e30="));const ct=document.createElement("eco-island");ct.style.display="block";t.replaceWith(ct);cr(ct).render(ce(c,p))})};window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.rerunScripts=window.__ECO_PAGES__.rerunScripts||{};window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}]=m;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",m,{once:true}):m()`;
416
+ }
417
+ return `
418
+ import { createRoot } from "${options.reactDomClientImportPath}";
419
+ import { createElement } from "${options.reactImportPath}";
420
+ import * as ComponentModule from "${options.importPath}";
421
+
422
+ const resolveComponent = (module = ComponentModule) => {
423
+ const id = ${componentRef};
424
+ const file = ${componentFile};
425
+ const moduleValues = Object.values(module);
426
+
427
+ const matchByMetadata = moduleValues.find((entry) => {
428
+ if (typeof entry !== "function") return false;
429
+ const config = entry.config;
430
+ const eco = config?.identity;
431
+ if (!eco) return false;
432
+ if (id && eco.id === id) return true;
433
+ if (file && eco.file === file) return true;
434
+ return false;
435
+ });
436
+
437
+ if (matchByMetadata && typeof matchByMetadata === "function") {
438
+ return matchByMetadata;
439
+ }
440
+
441
+ const defaultExport = module.default;
442
+ if (typeof defaultExport === "function") {
443
+ return defaultExport;
444
+ }
445
+
446
+ const firstFunction = moduleValues.find((entry) => typeof entry === "function");
447
+ return typeof firstFunction === "function" ? firstFunction : null;
448
+ };
449
+
450
+ const mount = () => {
451
+ const targets = document.querySelectorAll(${targetSelector});
452
+ const Component = resolveComponent();
453
+ if (!Component || targets.length === 0) {
454
+ return;
455
+ }
456
+ targets.forEach((target) => {
457
+ if (!(target instanceof HTMLElement)) {
458
+ return;
459
+ }
460
+ const props = JSON.parse(atob(target.getAttribute("data-eco-props") || "e30="));
461
+ const container = document.createElement("eco-island");
462
+ container.style.display = "block";
463
+ container.setAttribute("data-eco-component-key", target.getAttribute("data-eco-component-key") ?? "");
464
+ container.setAttribute("data-eco-props", target.getAttribute("data-eco-props") || "e30=");
465
+ target.replaceWith(container);
466
+ const root = createRoot(container);
467
+ const componentKey = container.getAttribute("data-eco-component-key") ?? "";
468
+ window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
469
+ window.__ECO_PAGES__.islandRoots = window.__ECO_PAGES__.islandRoots || {};
470
+ window.__ECO_PAGES__.islandRoots[componentKey] = root;
471
+ root.render(createElement(Component, props));
472
+ });
473
+ };
474
+
475
+ ${getRerunRegistrationScript(scriptId)}
476
+ ${hmrHandler ? `${hmrHandler}\n` : ''}
477
+ if (document.readyState === "loading") {
478
+ document.addEventListener("DOMContentLoaded", mount, { once: true });
479
+ } else {
480
+ mount();
481
+ }
482
+ `.trim();
483
+ }
@@ -0,0 +1,199 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { createHydrationScript } from './hydration-scripts.js';
3
+ const routerAdapter = {
4
+ name: 'eco-router',
5
+ bundle: {
6
+ importPath: '/assets/router.js',
7
+ outputName: 'router',
8
+ externals: [],
9
+ },
10
+ components: {
11
+ router: 'EcoRouter',
12
+ pageContent: 'PageContent',
13
+ },
14
+ getRouterProps: (page, props) => `{ page: ${page}, pageProps: ${props} }`,
15
+ };
16
+ function createModuleUrl(source) {
17
+ return `data:text/javascript;base64,${btoa(source)}`;
18
+ }
19
+ async function importModule(moduleUrl, scriptId) {
20
+ let marker;
21
+ if (scriptId) {
22
+ marker = document.createElement('script');
23
+ marker.setAttribute('data-eco-script-id', scriptId);
24
+ document.head.appendChild(marker);
25
+ }
26
+ await import(/* @vite-ignore */ moduleUrl);
27
+ marker?.remove();
28
+ }
29
+ function createRuntimeModules() {
30
+ const reactImportPath = createModuleUrl('export const createElement = (...args) => ({ args });');
31
+ const reactDomClientImportPath = createModuleUrl(`
32
+ export const hydrateRoot = (container, tree, options) => {
33
+ const runtime = window.__ECO_REACT_HYDRATION_TEST__;
34
+ runtime.hydrateCalls.push({
35
+ containerTag: container.tagName,
36
+ hasRecoverableErrorHandler: typeof options?.onRecoverableError === "function",
37
+ tree,
38
+ });
39
+
40
+ return {
41
+ render() {},
42
+ unmount() {
43
+ runtime.unmountCount += 1;
44
+ },
45
+ };
46
+ };
47
+ `);
48
+ const importPath = createModuleUrl('export default function Page() { return null; }');
49
+ const routerImportPath = createModuleUrl(`
50
+ export function EcoRouter(props) {
51
+ return props;
52
+ }
53
+
54
+ export function PageContent() {
55
+ return null;
56
+ }
57
+ `);
58
+ return {
59
+ importPath,
60
+ reactImportPath,
61
+ reactDomClientImportPath,
62
+ routerImportPath,
63
+ layoutComposeImportPath: createModuleUrl('export function composeLayoutPageTree() { return null; }'),
64
+ pageLayoutNormalizationImportPath: createModuleUrl('export function ensurePageConfigLayouts(config) { return config; }'),
65
+ };
66
+ }
67
+ describe('createHydrationScript browser execution', () => {
68
+ afterEach(() => {
69
+ document.body.innerHTML = '';
70
+ const testWindow = window;
71
+ delete testWindow.__ECO_PAGES__;
72
+ delete testWindow.__ECO_REACT_HYDRATION_TEST__;
73
+ });
74
+ it('registers router ownership and cleanup when the browser hydration bootstrap runs', async () => {
75
+ const runtimeModules = createRuntimeModules();
76
+ const testWindow = window;
77
+ testWindow.__ECO_REACT_HYDRATION_TEST__ = {
78
+ hydrateCalls: [],
79
+ renderCalls: [],
80
+ claimedOwners: [],
81
+ releasedOwners: [],
82
+ registrations: [],
83
+ unmountCount: 0,
84
+ };
85
+ testWindow.__ECO_PAGES__ = {
86
+ navigation: {
87
+ getOwnerState: () => ({
88
+ owner: 'html',
89
+ canHandleSpaNavigation: false,
90
+ }),
91
+ register: (registration) => {
92
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
93
+ },
94
+ claimOwnership: (owner) => {
95
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
96
+ },
97
+ releaseOwnership: (owner) => {
98
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
99
+ },
100
+ },
101
+ };
102
+ document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
103
+ title: 'Hello React',
104
+ locals: { theme: 'dark' },
105
+ })}</script>`;
106
+ const script = createHydrationScript({
107
+ ...runtimeModules,
108
+ scriptId: 'ecopages-react-page',
109
+ hmrEnabled: true,
110
+ isMdx: false,
111
+ router: routerAdapter,
112
+ pageDataReaderImportPath: new URL('./page-data-reader.js', import.meta.url).href,
113
+ });
114
+ const moduleUrl = createModuleUrl(script);
115
+ await importModule(moduleUrl, 'ecopages-react-page');
116
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1);
117
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.containerTag).toBe('BODY');
118
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.hasRecoverableErrorHandler).toBe(true);
119
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toEqual(['react-router']);
120
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(1);
121
+ expect(typeof testWindow.__ECO_PAGES__?.react?.cleanupPageRoot).toBe('function');
122
+ expect(testWindow.__ECO_PAGES__?.page).toEqual({
123
+ module: moduleUrl,
124
+ props: {
125
+ title: 'Hello React',
126
+ locals: { theme: 'dark' },
127
+ },
128
+ });
129
+ await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
130
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
131
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners).toEqual(['react-router']);
132
+ expect(testWindow.__ECO_PAGES__?.page).toBeUndefined();
133
+ expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBeNull();
134
+ });
135
+ it('reuses an existing router-owned page root during rerun bootstrap execution', async () => {
136
+ const runtimeModules = createRuntimeModules();
137
+ const testWindow = window;
138
+ testWindow.__ECO_REACT_HYDRATION_TEST__ = {
139
+ hydrateCalls: [],
140
+ renderCalls: [],
141
+ claimedOwners: [],
142
+ releasedOwners: [],
143
+ registrations: [],
144
+ unmountCount: 0,
145
+ };
146
+ const existingRoot = {
147
+ render: (tree) => {
148
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree);
149
+ },
150
+ unmount: () => {
151
+ testWindow.__ECO_REACT_HYDRATION_TEST__.unmountCount += 1;
152
+ },
153
+ };
154
+ testWindow.__ECO_PAGES__ = {
155
+ navigation: {
156
+ getOwnerState: () => ({
157
+ owner: 'react-router',
158
+ canHandleSpaNavigation: true,
159
+ }),
160
+ register: (registration) => {
161
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
162
+ },
163
+ claimOwnership: (owner) => {
164
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
165
+ },
166
+ releaseOwnership: (owner) => {
167
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
168
+ },
169
+ },
170
+ react: {
171
+ pageRoot: existingRoot,
172
+ },
173
+ };
174
+ document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
175
+ title: 'Rerun',
176
+ })}</script>`;
177
+ const script = createHydrationScript({
178
+ ...runtimeModules,
179
+ scriptId: 'ecopages-react-page-rerun',
180
+ hmrEnabled: true,
181
+ isMdx: false,
182
+ router: routerAdapter,
183
+ pageDataReaderImportPath: new URL('./page-data-reader.js', import.meta.url).href,
184
+ });
185
+ const moduleUrl = createModuleUrl(script);
186
+ await importModule(moduleUrl, 'ecopages-react-page-rerun');
187
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
188
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
189
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toHaveLength(0);
190
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(0);
191
+ expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBe(existingRoot);
192
+ expect(testWindow.__ECO_PAGES__?.page).toEqual({
193
+ module: moduleUrl,
194
+ props: {
195
+ title: 'Rerun',
196
+ },
197
+ });
198
+ });
199
+ });