@ecopages/react 0.2.0-rc.1 → 0.2.0-rc.11

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 (86) hide show
  1. package/README.md +68 -14
  2. package/package.json +17 -5
  3. package/src/app/client-only.js +3 -8
  4. package/src/bundling/bundle.js +4 -1
  5. package/src/bundling/runtime-alias-map.d.ts +0 -1
  6. package/src/bundling/runtime-alias-map.js +1 -4
  7. package/src/bundling/runtime-bundle.d.ts +9 -2
  8. package/src/bundling/runtime-bundle.js +27 -16
  9. package/src/bundling/runtime-modules.d.ts +21 -0
  10. package/src/bundling/runtime-modules.js +25 -0
  11. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  12. package/src/client-graph/ast-transform-eco-page.js +71 -0
  13. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  14. package/src/client-graph/ast-transform-import-edits.js +75 -0
  15. package/src/client-graph/ast-transform-walk-imports.d.ts +19 -0
  16. package/src/client-graph/ast-transform-walk-imports.js +103 -0
  17. package/src/client-graph/ast-transform.d.ts +1 -7
  18. package/src/client-graph/ast-transform.js +42 -378
  19. package/src/client-graph/ast-walk.d.ts +10 -0
  20. package/src/client-graph/ast-walk.js +26 -0
  21. package/src/client-graph/boundary-cache.js +1 -1
  22. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +8 -0
  23. package/src/client-graph/boundary-plugin-read-file-inline.js +45 -0
  24. package/src/client-graph/boundary-plugin-transform.d.ts +18 -0
  25. package/src/client-graph/boundary-plugin-transform.js +61 -0
  26. package/src/client-graph/boundary-plugin.d.ts +0 -20
  27. package/src/client-graph/boundary-plugin.js +16 -98
  28. package/src/client-graph/reachability-analyzer.d.ts +4 -36
  29. package/src/client-graph/reachability-analyzer.js +23 -483
  30. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  31. package/src/client-graph/reachability-client-roots.js +59 -0
  32. package/src/client-graph/reachability-export-names.d.ts +5 -0
  33. package/src/client-graph/reachability-export-names.js +34 -0
  34. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  35. package/src/client-graph/reachability-fallback-roots.js +71 -0
  36. package/src/client-graph/reachability-preload.d.ts +10 -0
  37. package/src/client-graph/reachability-preload.js +30 -0
  38. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  39. package/src/client-graph/reachability-top-level-index.js +93 -0
  40. package/src/client-graph/reachability-traverse.d.ts +7 -0
  41. package/src/client-graph/reachability-traverse.js +201 -0
  42. package/src/client-graph/specifier-classification.d.ts +3 -2
  43. package/src/client-graph/specifier-classification.js +6 -2
  44. package/src/content/collection-component-cache.d.ts +25 -0
  45. package/src/content/collection-component-cache.js +62 -0
  46. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  47. package/src/hmr/hmr-strategy-process.js +83 -0
  48. package/src/hmr/hmr-strategy.d.ts +3 -0
  49. package/src/hmr/hmr-strategy.js +47 -86
  50. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +1 -0
  51. package/src/hmr/react-hmr-dev-transform-plugins.js +4 -1
  52. package/src/hydration/browser/island-hydration.d.ts +82 -0
  53. package/src/hydration/browser/island-hydration.js +247 -0
  54. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  55. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  56. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  57. package/src/hydration/browser/page-hydration-module.js +17 -0
  58. package/src/hydration/browser/page-hydration.d.ts +54 -0
  59. package/src/hydration/browser/page-hydration.js +177 -0
  60. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  61. package/src/hydration/hydration-asset.d.ts +21 -1
  62. package/src/hydration/hydration-asset.js +54 -24
  63. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  64. package/src/hydration/hydration-lifecycle.test.browser.js +409 -0
  65. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  66. package/src/hydration/hydration-page-entry-source.js +87 -0
  67. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  68. package/src/hydration/hydration-script-compiler.js +213 -0
  69. package/src/hydration/page-data-reader.d.ts +0 -14
  70. package/src/hydration/page-data-reader.js +1 -47
  71. package/src/mdx/mdx-loader-plugin.d.ts +5 -1
  72. package/src/mdx/mdx-loader-plugin.js +4 -2
  73. package/src/plugin/react.plugin.js +8 -1
  74. package/src/plugin/react.types.d.ts +11 -2
  75. package/src/render/component-ssr.d.ts +17 -0
  76. package/src/render/component-ssr.js +19 -1
  77. package/src/render/react-renderer.d.ts +2 -1
  78. package/src/render/react-renderer.js +5 -1
  79. package/src/render/unified-layout-composition.d.ts +2 -0
  80. package/src/render/unified-layout-composition.js +5 -1
  81. package/src/hmr/hmr-scripts.d.ts +0 -18
  82. package/src/hmr/hmr-scripts.js +0 -44
  83. package/src/hydration/hydration-scripts.d.ts +0 -104
  84. package/src/hydration/hydration-scripts.js +0 -483
  85. package/src/hydration/hydration-scripts.test.browser.js +0 -199
  86. /package/src/hydration/{hydration-scripts.test.browser.d.ts → compiled-page-hydration-options.js} +0 -0
@@ -1,104 +0,0 @@
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 type { ReactRouterAdapter } from '../contracts/router-adapter.js';
7
- /**
8
- * Options for generating a hydration script.
9
- */
10
- export type HydrationScriptOptions = {
11
- /** The module path imported by the page entry module. */
12
- importPath: string;
13
- /** Browser expression that resolves to the page module URL the router should import. */
14
- pageModuleUrlExpression?: string;
15
- /** Stable id of the page entry script tag in the document. */
16
- scriptId: string;
17
- /** Direct import path for React runtime module */
18
- reactImportPath: string;
19
- /** Direct import path for react-dom/client runtime module */
20
- reactDomClientImportPath: string;
21
- /** Direct import path for router runtime module */
22
- routerImportPath?: string;
23
- /**
24
- * When true, emit HMR registration and hot-reload handlers.
25
- *
26
- * @remarks
27
- * HMR page bootstraps stay unbundled and evaluate as native browser ESM.
28
- * Callers must supply browser-resolvable import paths (shared vendor URLs)
29
- * so generated source does not emit bare `@ecopages/*` imports. When false,
30
- * this generator emits the same readable bootstrap without HMR hooks.
31
- */
32
- hmrEnabled: boolean;
33
- /** Whether the source file is an MDX file */
34
- isMdx: boolean;
35
- /** Optional router adapter for SPA navigation */
36
- router?: ReactRouterAdapter;
37
- /**
38
- * Import path for shared layout composition helper.
39
- *
40
- * @remarks
41
- * Required so callers (not this generator) decide vendor URL vs bare package.
42
- */
43
- layoutComposeImportPath: string;
44
- /**
45
- * Import path for MDX page layout normalization helper.
46
- *
47
- * @remarks
48
- * Required so callers (not this generator) decide vendor URL vs bare package.
49
- */
50
- pageLayoutNormalizationImportPath: string;
51
- /**
52
- * Optional import path for the page-data reader.
53
- *
54
- * @remarks
55
- * When omitted, hydration scripts inline the reader so native browser ESM /
56
- * HMR entry evaluation does not depend on bare `@ecopages/react/*` imports.
57
- * Browser unit tests that execute `data:` scripts may still pass a resolvable URL.
58
- */
59
- pageDataReaderImportPath?: string;
60
- };
61
- export type IslandHydrationScriptOptions = {
62
- /** Bundled browser module path for the island component. */
63
- importPath: string;
64
- /** Stable id of the island bootstrap script tag in the document. */
65
- scriptId: string;
66
- /** Browser import path for React runtime. */
67
- reactImportPath: string;
68
- /** Browser import path for react-dom/client runtime. */
69
- reactDomClientImportPath: string;
70
- /** Selector that resolves to all SSR root elements for this island component. */
71
- targetSelector: string;
72
- /** Optional stable component id used to resolve named exports reliably. */
73
- componentRef?: string;
74
- /** Optional source file hint used as fallback for component resolution. */
75
- componentFile?: string;
76
- /**
77
- * When true, emit a compact source string.
78
- *
79
- * @remarks
80
- * Island bootstraps use `bundle: false`, so compact output must be generated
81
- * here rather than delegated to the bundler.
82
- */
83
- minify: boolean;
84
- /**
85
- * When true, register an HMR handler that hot-imports the dev transform module.
86
- */
87
- hmrEnabled?: boolean;
88
- };
89
- /**
90
- * Creates a page hydration entry module.
91
- *
92
- * @remarks
93
- * Always emits readable source. Production page assets set `bundle: true` so
94
- * core's content-script processor minifies the result. Do not hand-minify here.
95
- */
96
- export declare function createHydrationScript(options: HydrationScriptOptions): string;
97
- /**
98
- * Creates the client bootstrap for component-level React islands.
99
- *
100
- * @remarks
101
- * Island scripts use `bundle: false`, so compact output still needs a
102
- * handwritten string.
103
- */
104
- export declare function createIslandHydrationScript(options: IslandHydrationScriptOptions): string;
@@ -1,483 +0,0 @@
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
- }