@ecopages/react 0.2.0-beta.9 → 0.2.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +138 -0
  84. package/src/render/react-renderer.js +448 -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
@@ -1,33 +0,0 @@
1
- import { jsx } from "react/jsx-runtime";
2
- import { Suspense } from "react";
3
- import { afterEach, describe, expect, it } from "vitest";
4
- import { cleanup, render, screen } from "@testing-library/react";
5
- import { dynamic } from "./dynamic.js";
6
- function createDeferredImport() {
7
- let resolve;
8
- const promise = new Promise((innerResolve) => {
9
- resolve = innerResolve;
10
- });
11
- return {
12
- promise,
13
- resolve
14
- };
15
- }
16
- describe("dynamic", () => {
17
- afterEach(() => {
18
- cleanup();
19
- });
20
- it("returns a browser lazy component that resolves through Suspense", async () => {
21
- const deferredImport = createDeferredImport();
22
- const DynamicComponent = dynamic(() => deferredImport.promise);
23
- render(
24
- /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx("span", { children: "Loading dynamic component" }), children: /* @__PURE__ */ jsx(DynamicComponent, {}) })
25
- );
26
- expect(screen.getByText("Loading dynamic component")).toBeTruthy();
27
- deferredImport.resolve({
28
- default: () => /* @__PURE__ */ jsx("span", { children: "Dynamic content" })
29
- });
30
- expect(await screen.findByText("Dynamic content")).toBeTruthy();
31
- expect(screen.queryByText("Loading dynamic component")).toBeNull();
32
- });
33
- });
@@ -1,31 +0,0 @@
1
- const HMR_MARKER = "/* [ecopages] react-hmr */";
2
- function hasHmrMarker(code) {
3
- return code.includes(HMR_MARKER);
4
- }
5
- function injectHmrHandler(code) {
6
- return `${HMR_MARKER}
7
- ${code}
8
- if (import.meta.hot) {
9
- import.meta.hot.accept((newModule) => {
10
- if (newModule) {
11
- const exports = Object.keys(newModule);
12
- const hasReactExport = exports.some(key => {
13
- const value = newModule[key];
14
- return value && (
15
- typeof value === 'function' ||
16
- (typeof value === 'object' && value.$$typeof)
17
- );
18
- });
19
-
20
- if (hasReactExport) {
21
- import.meta.hot.invalidate();
22
- }
23
- }
24
- });
25
- }
26
- `;
27
- }
28
- export {
29
- hasHmrMarker,
30
- injectHmrHandler
31
- };
@@ -1,55 +0,0 @@
1
- const VOID_TAGS = /* @__PURE__ */ new Set([
2
- "area",
3
- "base",
4
- "br",
5
- "col",
6
- "embed",
7
- "hr",
8
- "img",
9
- "input",
10
- "link",
11
- "meta",
12
- "param",
13
- "source",
14
- "track",
15
- "wbr"
16
- ]);
17
- function hasSingleRootElement(html) {
18
- const firstTagMatch = html.match(/^\s*<([a-zA-Z][a-zA-Z0-9:-]*)\b[^>]*>/);
19
- if (!firstTagMatch) {
20
- return false;
21
- }
22
- const firstTag = firstTagMatch[1].toLowerCase();
23
- const firstTagText = firstTagMatch[0];
24
- const firstTagStart = firstTagMatch.index ?? 0;
25
- const firstTagEnd = firstTagStart + firstTagText.length;
26
- const isSelfClosing = /\/\s*>$/.test(firstTagText);
27
- if (isSelfClosing || VOID_TAGS.has(firstTag)) {
28
- return html.slice(firstTagEnd).trim().length === 0;
29
- }
30
- const tokenRegex = /<\/?([a-zA-Z][a-zA-Z0-9:-]*)\b[^>]*>/g;
31
- tokenRegex.lastIndex = firstTagEnd;
32
- let depth = 1;
33
- for (let token = tokenRegex.exec(html); token; token = tokenRegex.exec(html)) {
34
- const tagText = token[0];
35
- const tagName = token[1].toLowerCase();
36
- const isClosing = tagText.startsWith("</");
37
- const tokenSelfClosing = /\/\s*>$/.test(tagText);
38
- if (VOID_TAGS.has(tagName) || tokenSelfClosing) {
39
- continue;
40
- }
41
- if (isClosing) {
42
- depth--;
43
- if (depth === 0) {
44
- const afterRoot = html.slice(token.index + token[0].length).trim();
45
- return afterRoot.length === 0;
46
- }
47
- } else {
48
- depth++;
49
- }
50
- }
51
- return false;
52
- }
53
- export {
54
- hasSingleRootElement
55
- };
@@ -1,92 +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 '../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
- /** Whether running in development mode with HMR support */
24
- isDevelopment: boolean;
25
- /** Whether the source file is an MDX file */
26
- isMdx: boolean;
27
- /** Optional router adapter for SPA navigation */
28
- router?: ReactRouterAdapter;
29
- };
30
- export type IslandHydrationScriptOptions = {
31
- /** Bundled browser module path for the island component. */
32
- importPath: string;
33
- /** Stable id of the island bootstrap script tag in the document. */
34
- scriptId: string;
35
- /** Browser import path for React runtime. */
36
- reactImportPath: string;
37
- /** Browser import path for react-dom/client runtime. */
38
- reactDomClientImportPath: string;
39
- /** Selector that resolves to all SSR root elements for this island component. */
40
- targetSelector: string;
41
- /** Optional stable component id used to resolve named exports reliably. */
42
- componentRef?: string;
43
- /** Optional source file hint used as fallback for component resolution. */
44
- componentFile?: string;
45
- /** Enables development-oriented non-minified output. */
46
- isDevelopment: boolean;
47
- };
48
- /**
49
- * Creates a hydration script for client-side React hydration.
50
- *
51
- * Why this dispatcher exists:
52
- * the runtime matrix is small but behaviorally different across development vs
53
- * production and router vs non-router pages. Keeping that branch here preserves
54
- * a compact public API while allowing each emitted script to stay focused.
55
- *
56
- * Selection rules:
57
- * - development uses readable scripts with HMR hooks
58
- * - production uses minified equivalents
59
- * - router presence decides whether page updates flow through the router runtime
60
- * or rebuild directly from the page module
61
- *
62
- * @param options - Configuration options for script generation
63
- * @returns The generated hydration script as a string
64
- */
65
- export declare function createHydrationScript(options: HydrationScriptOptions): string;
66
- /**
67
- * Creates the client bootstrap for component-level React islands.
68
- *
69
- * The island runtime intentionally uses `createRoot()` (not `hydrateRoot()`) and
70
- * mounts into the SSR element identified by `targetSelector`.
71
- *
72
- * Rationale:
73
- * - No synthetic wrapper element is introduced in SSR output.
74
- * - DOM structure remains identical to authored component markup.
75
- * - Runtime ownership is isolated per island instance.
76
- *
77
- * Generated script behavior:
78
- * - resolves the component export by metadata (`componentRef`, `componentFile`)
79
- * before falling back to default/first function export
80
- * - selects island root using `targetSelector`
81
- * - replaces the SSR host with a dedicated client-owned container
82
- * - creates a fresh React root and renders with serialized `props`
83
- *
84
- * Why it remounts instead of hydrating:
85
- * island SSR intentionally avoids synthetic wrapper elements. The runtime swaps
86
- * the authored SSR node for a dedicated client-owned container before mounting
87
- * so the server markup stays clean while the client still gets a stable root.
88
- *
89
- * @param options Island script generation options.
90
- * @returns Browser-executable JavaScript module source.
91
- */
92
- export declare function createIslandHydrationScript(options: IslandHydrationScriptOptions): string;
@@ -1,358 +0,0 @@
1
- function getImportStatement(importPath, isMdx) {
2
- return isMdx ? `import * as MDXModule from "${importPath}";
3
- const Page = MDXModule.default;
4
- if (MDXModule.config) Page.config = MDXModule.config;` : `import Page from "${importPath}";`;
5
- }
6
- function getHmrImportStatement(isMdx) {
7
- return isMdx ? "const NewPage = newModule.default; if (newModule.config) NewPage.config = newModule.config;" : "const NewPage = newModule.default;";
8
- }
9
- function getComponentType(isMdx) {
10
- return isMdx ? "MDX" : "React";
11
- }
12
- function getDevPageRootCleanupScript() {
13
- return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
14
- window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
15
- window.__ECO_PAGES__.react.cleanupPageRoot = () => {
16
- const activeRoot = window.__ECO_PAGES__.react?.pageRoot || root;
17
- if (!activeRoot) {
18
- window.__ECO_PAGES__.react.pageRoot = null;
19
- window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
20
- delete window.__ECO_PAGES__.page;
21
- return;
22
- }
23
- window.__ECO_PAGES__.react.pageRoot = null;
24
- window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
25
- delete window.__ECO_PAGES__.page;
26
- root = null;
27
- activeRoot.unmount();
28
- };`;
29
- }
30
- function getProdPageRootCleanupScript() {
31
- return 'window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.react=window.__ECO_PAGES__.react||{};window.__ECO_PAGES__.react.cleanupPageRoot=()=>{const a=window.__ECO_PAGES__.react?.pageRoot||root;if(!a){window.__ECO_PAGES__.react.pageRoot=null;window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");delete window.__ECO_PAGES__.page;return}window.__ECO_PAGES__.react.pageRoot=null;window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");delete window.__ECO_PAGES__.page;root=null;a.unmount()};';
32
- }
33
- function getDevRouterBootstrapRegistrationScript() {
34
- return `const currentOwnerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
35
- if (!(currentOwnerState?.owner === "react-router" && currentOwnerState.canHandleSpaNavigation)) {
36
- window.__ECO_PAGES__?.navigation?.register({
37
- owner: "react-router",
38
- cleanupBeforeHandoff: async () => {
39
- window.__ECO_PAGES__?.react?.cleanupPageRoot?.();
40
- }
41
- });
42
- window.__ECO_PAGES__?.navigation?.claimOwnership?.("react-router");
43
- }`;
44
- }
45
- function getProdRouterBootstrapRegistrationScript() {
46
- return 'const o=window.__ECO_PAGES__?.navigation?.getOwnerState?.();if(!(o?.owner==="react-router"&&o.canHandleSpaNavigation)){window.__ECO_PAGES__?.navigation?.register({owner:"react-router",cleanupBeforeHandoff:async()=>{window.__ECO_PAGES__?.react?.cleanupPageRoot?.()}});window.__ECO_PAGES__?.navigation?.claimOwnership?.("react-router")}';
47
- }
48
- function getDevReuseExistingRouterRootScript() {
49
- return `const shouldReuseExistingRouterRoot = () => {
50
- const ownerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
51
- return Boolean(
52
- window.__ECO_PAGES__.react?.pageRoot &&
53
- ownerState?.owner === "react-router" &&
54
- ownerState.canHandleSpaNavigation
55
- );
56
- };`;
57
- }
58
- function getProdReuseExistingRouterRootScript() {
59
- return 'const sr=()=>{const o=window.__ECO_PAGES__?.navigation?.getOwnerState?.();return!!(window.__ECO_PAGES__.react?.pageRoot&&o?.owner==="react-router"&&o.canHandleSpaNavigation)};';
60
- }
61
- function getDevRerunRegistrationScript(scriptId) {
62
- return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
63
- window.__ECO_PAGES__.rerunScripts = window.__ECO_PAGES__.rerunScripts || {};
64
- window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}] = mount;`;
65
- }
66
- function getProdRerunRegistrationScript(scriptId) {
67
- return `window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.rerunScripts=window.__ECO_PAGES__.rerunScripts||{};window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}]=m;`;
68
- }
69
- function createDevScriptWithRouter(options) {
70
- const { importPath, isMdx, router, reactImportPath, reactDomClientImportPath, routerImportPath, scriptId } = options;
71
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
72
- const { components, getRouterProps } = router;
73
- if (!routerImportPath) {
74
- throw new Error("routerImportPath is required when router adapter is configured");
75
- }
76
- return `
77
- import { hydrateRoot } from "${reactDomClientImportPath}";
78
- import { createElement } from "${reactImportPath}";
79
- import { ${components.router}, ${components.pageContent} } from "${routerImportPath}";
80
- ${getImportStatement(importPath, isMdx)}
81
- const pageModuleUrl = ${pageModuleUrlExpression};
82
- export default Page;
83
- export const config = Page.config;
84
- const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
85
-
86
- if (isActivePageEntry) {
87
-
88
- window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
89
- window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
90
- window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
91
- window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
92
- let root = window.__ECO_PAGES__.react.pageRoot;
93
- ${getDevPageRootCleanupScript()}
94
- ${getDevRouterBootstrapRegistrationScript()}
95
- ${getDevReuseExistingRouterRootScript()}
96
-
97
- const getPageData = () => {
98
- const el = document.getElementById("__ECO_PAGE_DATA__");
99
- if (el?.textContent) {
100
- try { return JSON.parse(el.textContent); } catch {}
101
- }
102
- return {};
103
- };
104
-
105
- const props = getPageData();
106
-
107
- window.__ECO_PAGES__.page = {
108
- module: pageModuleUrl,
109
- props
110
- };
111
-
112
- const createTree = (Component, props) => {
113
- const pageContent = createElement(${components.pageContent});
114
- return createElement(${components.router}, ${getRouterProps("Component", "props")}, pageContent);
115
- };
116
-
117
- const mount = () => {
118
- const props = getPageData();
119
- window.__ECO_PAGES__.page = {
120
- module: pageModuleUrl,
121
- props
122
- };
123
-
124
- if (shouldReuseExistingRouterRoot()) {
125
- root = window.__ECO_PAGES__.react.pageRoot;
126
- return;
127
- }
128
-
129
- if (window.__ECO_PAGES__.react?.pageRoot) {
130
- root = window.__ECO_PAGES__.react.pageRoot;
131
- return;
132
- }
133
-
134
- root = hydrateRoot(document.body, createTree(Page, props), {
135
- onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
136
- });
137
- window.__ECO_PAGES__.react.pageRoot = root;
138
- window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
139
- try {
140
- const newModule = await import(newUrl);
141
- const nextProps = getPageData();
142
- ${getHmrImportStatement(isMdx)}
143
- const currentPageLayout = Page.config?.layout;
144
- const nextPageLayout = NewPage.config?.layout;
145
-
146
- if (window.__ECO_PAGES__?.navigation?.getOwnerState().owner === "react-router") {
147
- await window.__ECO_PAGES__?.navigation?.reloadCurrentPage?.({
148
- clearCache: currentPageLayout !== nextPageLayout,
149
- moduleUrl: "${importPath}",
150
- source: "react-router"
151
- });
152
- console.log("[ecopages] ${getComponentType(isMdx)} component updated via router");
153
- return;
154
- }
155
-
156
- window.__ECO_PAGES__.page = {
157
- module: pageModuleUrl,
158
- props: nextProps
159
- };
160
- root.render(createTree(NewPage, nextProps));
161
- console.log("[ecopages] ${getComponentType(isMdx)} component updated");
162
- } catch (e) {
163
- console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
164
- }
165
- };
166
- };
167
-
168
- ${getDevRerunRegistrationScript(scriptId)}
169
-
170
- if (document.readyState === "loading") {
171
- document.addEventListener("DOMContentLoaded", mount);
172
- } else {
173
- mount();
174
- }
175
- }
176
- `.trim();
177
- }
178
- function createDevScriptWithoutRouter(options) {
179
- const { importPath, isMdx, reactImportPath, reactDomClientImportPath, scriptId } = options;
180
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
181
- return `
182
- import { hydrateRoot } from "${reactDomClientImportPath}";
183
- import { createElement } from "${reactImportPath}";
184
- ${getImportStatement(importPath, isMdx)}
185
- const pageModuleUrl = ${pageModuleUrlExpression};
186
- export default Page;
187
- export const config = Page.config;
188
- const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
189
-
190
- if (isActivePageEntry) {
191
-
192
- window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
193
- window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
194
- window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
195
- window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
196
- let root = window.__ECO_PAGES__.react.pageRoot;
197
- ${getDevPageRootCleanupScript()}
198
-
199
- const getPageData = () => {
200
- const el = document.getElementById("__ECO_PAGE_DATA__");
201
- if (el?.textContent) {
202
- try { return JSON.parse(el.textContent); } catch {}
203
- }
204
- return {};
205
- };
206
-
207
- const props = getPageData();
208
-
209
- window.__ECO_PAGES__.page = {
210
- module: pageModuleUrl,
211
- props
212
- };
213
-
214
- const createTree = (Component, props) => {
215
- const Layout = Component.config?.layout;
216
- const pageElement = createElement(Component, props);
217
- const layoutProps = props?.locals ? { locals: props.locals } : null;
218
- return Layout ? createElement(Layout, layoutProps, pageElement) : pageElement;
219
- };
220
-
221
- const mount = () => {
222
- const props = getPageData();
223
- window.__ECO_PAGES__.page = {
224
- module: pageModuleUrl,
225
- props
226
- };
227
-
228
- if (window.__ECO_PAGES__.react?.pageRoot) {
229
- root = window.__ECO_PAGES__.react.pageRoot;
230
- root.render(createTree(Page, props));
231
- } else {
232
- root = hydrateRoot(document.body, createTree(Page, props), {
233
- onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
234
- });
235
- window.__ECO_PAGES__.react.pageRoot = root;
236
- }
237
- window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
238
- try {
239
- const newModule = await import(newUrl);
240
- ${getHmrImportStatement(isMdx)}
241
- root.render(createTree(NewPage, props));
242
- console.log("[ecopages] ${getComponentType(isMdx)} component updated");
243
- } catch (e) {
244
- console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
245
- }
246
- };
247
- };
248
-
249
- ${getDevRerunRegistrationScript(scriptId)}
250
-
251
- if (document.readyState === "loading") {
252
- document.addEventListener("DOMContentLoaded", mount);
253
- } else {
254
- mount();
255
- }
256
- }
257
- `.trim();
258
- }
259
- function createProdScriptWithRouter(options) {
260
- const { importPath, isMdx, router, reactImportPath, reactDomClientImportPath, routerImportPath, scriptId } = options;
261
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
262
- const { components, getRouterProps } = router;
263
- if (!routerImportPath) {
264
- throw new Error("routerImportPath is required when router adapter is configured");
265
- }
266
- if (isMdx) {
267
- return `import{hydrateRoot as hr}from"${reactDomClientImportPath}";import{createElement as ce}from"${reactImportPath}";import{${components.router} as R,${components.pageContent} as PC}from"${routerImportPath}";import*as M from"${importPath}";const P=M.default;if(M.config)P.config=M.config;const u=${pageModuleUrlExpression};export default P;export const config=P.config;const a=!!document.querySelector('script[data-eco-script-id="${scriptId}"]');if(a){window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.react=window.__ECO_PAGES__.react||{};window.__ECO_PAGES__.react.pageRoot=window.__ECO_PAGES__.react.pageRoot||null;let root=window.__ECO_PAGES__.react.pageRoot;${getProdPageRootCleanupScript()}${getProdRouterBootstrapRegistrationScript()}${getProdReuseExistingRouterRootScript()}const gd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(e?.textContent){try{return JSON.parse(e.textContent)}catch{}}return{}};const ct=(C,p)=>ce(R,${getRouterProps("C", "p")},ce(PC));const m=()=>{const pr=gd();window.__ECO_PAGES__.page={module:u,props:pr};if(sr()){root=window.__ECO_PAGES__.react.pageRoot;return}if(window.__ECO_PAGES__.react?.pageRoot){root=window.__ECO_PAGES__.react.pageRoot;return}root=hr(document.body,ct(P,pr),{onRecoverableError:(e)=>console.warn("[ecopages] Hydration error:",e)});window.__ECO_PAGES__.react.pageRoot=root};${getProdRerunRegistrationScript(scriptId)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",m):m()}`;
268
- }
269
- return `import{hydrateRoot as hr}from"${reactDomClientImportPath}";import{createElement as ce}from"${reactImportPath}";import{${components.router} as R,${components.pageContent} as PC}from"${routerImportPath}";import P from"${importPath}";const u=${pageModuleUrlExpression};export default P;export const config=P.config;const a=!!document.querySelector('script[data-eco-script-id="${scriptId}"]');if(a){window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.react=window.__ECO_PAGES__.react||{};window.__ECO_PAGES__.react.pageRoot=window.__ECO_PAGES__.react.pageRoot||null;let root=window.__ECO_PAGES__.react.pageRoot;${getProdPageRootCleanupScript()}${getProdRouterBootstrapRegistrationScript()}${getProdReuseExistingRouterRootScript()}const gd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(e?.textContent){try{return JSON.parse(e.textContent)}catch{}}return{}};const ct=(C,p)=>ce(R,${getRouterProps("C", "p")},ce(PC));const m=()=>{const pr=gd();window.__ECO_PAGES__.page={module:u,props:pr};if(sr()){root=window.__ECO_PAGES__.react.pageRoot;return}if(window.__ECO_PAGES__.react?.pageRoot){root=window.__ECO_PAGES__.react.pageRoot;return}root=hr(document.body,ct(P,pr),{onRecoverableError:(e)=>console.warn("[ecopages] Hydration error:",e)});window.__ECO_PAGES__.react.pageRoot=root};${getProdRerunRegistrationScript(scriptId)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",m):m()}`;
270
- }
271
- function createProdScriptWithoutRouter(options) {
272
- const { importPath, isMdx, reactImportPath, reactDomClientImportPath, scriptId } = options;
273
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
274
- if (isMdx) {
275
- return `import{hydrateRoot as hr}from"${reactDomClientImportPath}";import{createElement as ce}from"${reactImportPath}";import*as M from"${importPath}";const P=M.default;if(M.config)P.config=M.config;const u=${pageModuleUrlExpression};export default P;export const config=P.config;const a=!!document.querySelector('script[data-eco-script-id="${scriptId}"]');if(a){window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.react=window.__ECO_PAGES__.react||{};window.__ECO_PAGES__.react.pageRoot=window.__ECO_PAGES__.react.pageRoot||null;let root=window.__ECO_PAGES__.react.pageRoot;${getProdPageRootCleanupScript()}const gd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(e?.textContent){try{return JSON.parse(e.textContent)}catch{}}return{}};const ct=(C,p)=>{const L=C.config?.layout;const pe=ce(C,p);const lp=p?.locals?{locals:p.locals}:null;return L?ce(L,lp,pe):pe};const m=()=>{const pr=gd();window.__ECO_PAGES__.page={module:u,props:pr};if(window.__ECO_PAGES__.react?.pageRoot){root=window.__ECO_PAGES__.react.pageRoot;root.render(ct(P,pr));return}root=hr(document.body,ct(P,pr),{onRecoverableError:(e)=>console.warn("[ecopages] Hydration error:",e)});window.__ECO_PAGES__.react.pageRoot=root};${getProdRerunRegistrationScript(scriptId)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",m):m()}`;
276
- }
277
- return `import{hydrateRoot as hr}from"${reactDomClientImportPath}";import{createElement as ce}from"${reactImportPath}";import P from"${importPath}";const u=${pageModuleUrlExpression};export default P;export const config=P.config;const a=!!document.querySelector('script[data-eco-script-id="${scriptId}"]');if(a){window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.react=window.__ECO_PAGES__.react||{};window.__ECO_PAGES__.react.pageRoot=window.__ECO_PAGES__.react.pageRoot||null;let root=window.__ECO_PAGES__.react.pageRoot;${getProdPageRootCleanupScript()}const gd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(e?.textContent){try{return JSON.parse(e.textContent)}catch{}}return{}};const ct=(C,p)=>{const L=C.config?.layout;const pe=ce(C,p);const lp=p?.locals?{locals:p.locals}:null;return L?ce(L,lp,pe):pe};const m=()=>{const pr=gd();window.__ECO_PAGES__.page={module:u,props:pr};if(window.__ECO_PAGES__.react?.pageRoot){root=window.__ECO_PAGES__.react.pageRoot;root.render(ct(P,pr));return}root=hr(document.body,ct(P,pr),{onRecoverableError:(e)=>console.warn("[ecopages] Hydration error:",e)});window.__ECO_PAGES__.react.pageRoot=root};${getProdRerunRegistrationScript(scriptId)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",m):m()}`;
278
- }
279
- function createHydrationScript(options) {
280
- const { isDevelopment, router } = options;
281
- if (isDevelopment) {
282
- return router ? createDevScriptWithRouter(options) : createDevScriptWithoutRouter(options);
283
- }
284
- return router ? createProdScriptWithRouter(options) : createProdScriptWithoutRouter(options);
285
- }
286
- function createIslandHydrationScript(options) {
287
- const targetSelector = JSON.stringify(options.targetSelector);
288
- const componentRef = JSON.stringify(options.componentRef ?? "");
289
- const componentFile = JSON.stringify(options.componentFile ?? "");
290
- const scriptId = options.scriptId;
291
- if (options.isDevelopment) {
292
- return `
293
- import { createRoot } from "${options.reactDomClientImportPath}";
294
- import { createElement } from "${options.reactImportPath}";
295
- import * as ComponentModule from "${options.importPath}";
296
-
297
- const resolveComponent = () => {
298
- const id = ${componentRef};
299
- const file = ${componentFile};
300
- const moduleValues = Object.values(ComponentModule);
301
-
302
- const matchByMetadata = moduleValues.find((entry) => {
303
- if (typeof entry !== "function") return false;
304
- const config = entry.config;
305
- const eco = config?.__eco;
306
- if (!eco) return false;
307
- if (id && eco.id === id) return true;
308
- if (file && eco.file === file) return true;
309
- return false;
310
- });
311
-
312
- if (matchByMetadata && typeof matchByMetadata === "function") {
313
- return matchByMetadata;
314
- }
315
-
316
- const defaultExport = ComponentModule.default;
317
- if (typeof defaultExport === "function") {
318
- return defaultExport;
319
- }
320
-
321
- const firstFunction = moduleValues.find((entry) => typeof entry === "function");
322
- return typeof firstFunction === "function" ? firstFunction : null;
323
- };
324
-
325
- const mount = () => {
326
- const targets = document.querySelectorAll(${targetSelector});
327
- const Component = resolveComponent();
328
- if (!Component || targets.length === 0) {
329
- return;
330
- }
331
- targets.forEach((target) => {
332
- if (!(target instanceof HTMLElement)) {
333
- return;
334
- }
335
- const props = JSON.parse(atob(target.getAttribute("data-eco-props") || "e30="));
336
- const container = document.createElement("eco-island");
337
- container.style.display = "block";
338
- target.replaceWith(container);
339
- const root = createRoot(container);
340
- root.render(createElement(Component, props));
341
- });
342
- };
343
-
344
- ${getDevRerunRegistrationScript(scriptId)}
345
-
346
- if (document.readyState === "loading") {
347
- document.addEventListener("DOMContentLoaded", mount, { once: true });
348
- } else {
349
- mount();
350
- }
351
- `.trim();
352
- }
353
- 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?.__eco;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))})};${getProdRerunRegistrationScript(scriptId)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",m,{once:true}):m()`;
354
- }
355
- export {
356
- createHydrationScript,
357
- createIslandHydrationScript
358
- };