@ecopages/react 0.2.0-beta.26 → 0.2.0-beta.27

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 (98) hide show
  1. package/README.md +17 -9
  2. package/package.json +42 -34
  3. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +7 -7
  4. package/src/{services/react-bundle.service.js → bundling/bundle.js} +9 -11
  5. package/src/{utils → bundling}/discover-layout-runtime-modules.js +2 -2
  6. package/src/{utils/react-runtime-alias-map.d.ts → bundling/runtime-alias-map.d.ts} +3 -3
  7. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +5 -5
  8. package/src/{services/react-runtime-bundle.service.js → bundling/runtime-bundle.js} +4 -4
  9. package/src/bundling/runtime-mode.d.ts +9 -0
  10. package/src/bundling/runtime-mode.js +6 -0
  11. package/src/{utils/client-graph-ast-transform.d.ts → client-graph/ast-transform.d.ts} +1 -1
  12. package/src/{utils/client-graph-ast-transform.js → client-graph/ast-transform.js} +1 -1
  13. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +0 -5
  14. package/src/{utils/client-graph-boundary-cache.js → client-graph/boundary-cache.js} +1 -3
  15. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +1 -1
  16. package/src/{utils/client-graph-boundary-plugin.js → client-graph/boundary-plugin.js} +3 -3
  17. package/src/{utils/client-graph-reachability.d.ts → client-graph/specifier-classification.d.ts} +1 -1
  18. package/src/{react-hmr-strategy.d.ts → hmr/hmr-strategy.d.ts} +3 -6
  19. package/src/{react-hmr-strategy.js → hmr/hmr-strategy.js} +11 -20
  20. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  21. package/src/{services/react-hmr-page-metadata-cache.js → hmr/page-metadata-cache.js} +8 -2
  22. package/src/{services/react-hydration-asset.service.d.ts → hydration/hydration-asset.d.ts} +33 -33
  23. package/src/{services/react-hydration-asset.service.js → hydration/hydration-asset.js} +45 -52
  24. package/src/{utils → hydration}/hydration-scripts.d.ts +33 -41
  25. package/src/hydration/hydration-scripts.js +353 -0
  26. package/src/{utils → hydration}/hydration-scripts.test.browser.js +6 -4
  27. package/src/hydration/page-data-manifest.d.ts +58 -0
  28. package/src/hydration/page-data-manifest.js +53 -0
  29. package/src/hydration/page-data-reader.d.ts +31 -0
  30. package/src/hydration/page-data-reader.js +64 -0
  31. package/src/hydration/page-payload.d.ts +67 -0
  32. package/src/hydration/page-payload.js +104 -0
  33. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  34. package/src/hydration/serialize-page-data-script.js +31 -0
  35. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +5 -5
  36. package/src/{services/react-mdx-config-dependency.service.js → mdx/mdx-config-dependency.js} +3 -3
  37. package/src/{services/react-page-module.service.d.ts → page/page-module.d.ts} +4 -7
  38. package/src/{services/react-page-module.service.js → page/page-module.js} +5 -9
  39. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +7 -3
  40. package/src/{react.plugin.js → plugin/react.plugin.js} +32 -30
  41. package/src/{react.types.d.ts → plugin/react.types.d.ts} +23 -8
  42. package/src/render/component-ownership.d.ts +50 -0
  43. package/src/render/component-ownership.js +23 -0
  44. package/src/render/component-ssr.d.ts +113 -0
  45. package/src/render/component-ssr.js +202 -0
  46. package/src/render/errors.d.ts +16 -0
  47. package/src/render/errors.js +18 -0
  48. package/src/{layout-compose.d.ts → render/layout-compose.d.ts} +8 -0
  49. package/src/{layout-compose.js → render/layout-compose.js} +14 -6
  50. package/src/render/react-renderer.d.ts +137 -0
  51. package/src/render/react-renderer.js +444 -0
  52. package/src/render/react-runtime.d.ts +13 -0
  53. package/src/render/react-runtime.js +21 -0
  54. package/src/render/unified-layout-composition.d.ts +53 -0
  55. package/src/render/unified-layout-composition.js +89 -0
  56. package/src/react-renderer.d.ts +0 -254
  57. package/src/react-renderer.js +0 -726
  58. package/src/serialize-page-data-script.d.ts +0 -8
  59. package/src/serialize-page-data-script.js +0 -10
  60. package/src/services/pages-index.d.ts +0 -64
  61. package/src/services/pages-index.js +0 -73
  62. package/src/services/react-page-payload.service.d.ts +0 -46
  63. package/src/services/react-page-payload.service.js +0 -67
  64. package/src/utils/hydration-scripts.js +0 -371
  65. /package/src/{utils → app}/client-only.d.ts +0 -0
  66. /package/src/{utils → app}/client-only.js +0 -0
  67. /package/src/{utils → app}/dynamic.d.ts +0 -0
  68. /package/src/{utils → app}/dynamic.js +0 -0
  69. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  70. /package/src/{utils → app}/dynamic.test.browser.js +0 -0
  71. /package/src/{utils → bundling}/discover-layout-runtime-modules.d.ts +0 -0
  72. /package/src/{utils/react-runtime-alias-map.js → bundling/runtime-alias-map.js} +0 -0
  73. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  74. /package/src/{utils/react-dom-runtime-interop-plugin.js → bundling/runtime-interop-plugin.js} +0 -0
  75. /package/src/{utils/react-plugin-runtime-modules.d.ts → bundling/runtime-modules.d.ts} +0 -0
  76. /package/src/{utils/react-plugin-runtime-modules.js → bundling/runtime-modules.js} +0 -0
  77. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  78. /package/src/{utils → client-graph}/component-config-traversal.js +0 -0
  79. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  80. /package/src/{utils → client-graph}/declared-modules.js +0 -0
  81. /package/src/{utils → client-graph}/reachability-analyzer.d.ts +0 -0
  82. /package/src/{utils → client-graph}/reachability-analyzer.js +0 -0
  83. /package/src/{utils/client-graph-reachability.js → client-graph/specifier-classification.js} +0 -0
  84. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  85. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  86. /package/src/{router-adapter.js → contracts/router-adapter.js} +0 -0
  87. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  88. /package/src/{utils → hmr}/hmr-scripts.js +0 -0
  89. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  90. /package/src/{utils/react-mdx-loader-plugin.d.ts → mdx/mdx-loader-plugin.d.ts} +0 -0
  91. /package/src/{utils/react-mdx-loader-plugin.js → mdx/mdx-loader-plugin.js} +0 -0
  92. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  93. /package/src/{react.constants.js → plugin/react.constants.js} +0 -0
  94. /package/src/{react.types.js → plugin/react.types.js} +0 -0
  95. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  96. /package/src/{eco-embed.js → render/eco-embed.js} +0 -0
  97. /package/src/{utils → render}/html-boundary.d.ts +0 -0
  98. /package/src/{utils → render}/html-boundary.js +0 -0
@@ -1,8 +0,0 @@
1
- /**
2
- * Escapes page data JSON for safe embedding in HTML script bodies.
3
- */
4
- export declare function escapePageDataJson(pageProps: Record<string, unknown> | undefined): string;
5
- /**
6
- * Emits the canonical `__ECO_PAGE_DATA__` bootstrap script tag.
7
- */
8
- export declare function serializePageDataScript(pageProps: Record<string, unknown> | undefined): string;
@@ -1,10 +0,0 @@
1
- function escapePageDataJson(pageProps) {
2
- return JSON.stringify(pageProps ?? {}).replace(/</g, "\\u003c");
3
- }
4
- function serializePageDataScript(pageProps) {
5
- return `<script id="__ECO_PAGE_DATA__" type="application/json">${escapePageDataJson(pageProps)}<\/script>`;
6
- }
7
- export {
8
- escapePageDataJson,
9
- serializePageDataScript
10
- };
@@ -1,64 +0,0 @@
1
- /**
2
- * Per-app index of React-owned page entrypoints.
3
- *
4
- * @remarks
5
- * The HMR strategy previously called `fileSystem.glob` on every
6
- * layout change. For apps with many pages this is wasteful: O(pages)
7
- * on every HMR event, and the result rarely changes between HMR
8
- * rebuilds.
9
- *
10
- * `PagesIndex` maintains a `Set` of owned page entrypoint paths. The
11
- * initial population is a single glob; subsequent mutations go through
12
- * `add` / `remove` (called by the HMR strategy when it observes a
13
- * file create/delete under `pagesDir`). The strategy reads via
14
- * `list()` for an O(1) snapshot of the current set.
15
- *
16
- * Phase 1 ships the class and the `list()` consumer. Watcher-driven
17
- * `add` / `remove` integration lands in a follow-up — for now the
18
- * strategy calls `refresh()` lazily, which is equivalent to the old
19
- * glob behavior but with a stable API for the future incremental
20
- * path.
21
- */
22
- export type PagesIndexOptions = {
23
- pagesDir: string;
24
- extensions?: string[];
25
- /**
26
- * Optional predicate to filter out non-page entrypoints (e.g.
27
- * test fixtures, generated files). Defaults to including every
28
- * file matching an extension.
29
- */
30
- isPageEntrypoint?: (absolutePath: string) => boolean;
31
- };
32
- export declare class PagesIndex {
33
- private readonly pagesDir;
34
- private readonly extensions;
35
- private readonly isPageEntrypoint;
36
- private readonly pages;
37
- private lastRefreshAt;
38
- constructor(options: PagesIndexOptions);
39
- /**
40
- * Rescan the pages directory and rebuild the index.
41
- *
42
- * Cheap to call multiple times in sequence (just a glob). The
43
- * real value of `PagesIndex` is the `add` / `remove` path that
44
- * callers can wire to the file watcher; for now this is the
45
- * fallback used on layout changes.
46
- */
47
- refresh(): Promise<void>;
48
- /**
49
- * Add a single entrypoint. Idempotent.
50
- */
51
- add(absolutePath: string): void;
52
- /**
53
- * Remove a single entrypoint. Idempotent.
54
- */
55
- remove(absolutePath: string): void;
56
- /** True if the index contains `absolutePath`. */
57
- has(absolutePath: string): boolean;
58
- /** Snapshot of the current set, sorted by absolute path. */
59
- list(): string[];
60
- /** Number of indexed entrypoints. */
61
- get size(): number;
62
- /** Last refresh timestamp (ms since epoch). */
63
- get refreshedAt(): number;
64
- }
@@ -1,73 +0,0 @@
1
- import path from "node:path";
2
- import { fileSystem } from "@ecopages/file-system";
3
- const DEFAULT_EXTENSIONS = [".tsx", ".kita.tsx", ".lit.tsx", ".eco.tsx", ".mdx", ".react.tsx"];
4
- class PagesIndex {
5
- pagesDir;
6
- extensions;
7
- isPageEntrypoint;
8
- pages = /* @__PURE__ */ new Set();
9
- lastRefreshAt = 0;
10
- constructor(options) {
11
- this.pagesDir = options.pagesDir;
12
- this.extensions = options.extensions ?? DEFAULT_EXTENSIONS;
13
- this.isPageEntrypoint = options.isPageEntrypoint ?? (() => true);
14
- }
15
- /**
16
- * Rescan the pages directory and rebuild the index.
17
- *
18
- * Cheap to call multiple times in sequence (just a glob). The
19
- * real value of `PagesIndex` is the `add` / `remove` path that
20
- * callers can wire to the file watcher; for now this is the
21
- * fallback used on layout changes.
22
- */
23
- async refresh() {
24
- const files = await fileSystem.glob(
25
- this.extensions.map((ext) => `**/*${ext}`),
26
- {
27
- cwd: this.pagesDir
28
- }
29
- );
30
- const next = /* @__PURE__ */ new Set();
31
- for (const file of files) {
32
- const absolutePath = path.join(this.pagesDir, file);
33
- if (!this.isPageEntrypoint(absolutePath)) continue;
34
- if (file.includes(".ecopages-node.")) continue;
35
- next.add(absolutePath);
36
- }
37
- this.pages.clear();
38
- for (const p of next) this.pages.add(p);
39
- this.lastRefreshAt = Date.now();
40
- }
41
- /**
42
- * Add a single entrypoint. Idempotent.
43
- */
44
- add(absolutePath) {
45
- if (!this.isPageEntrypoint(absolutePath)) return;
46
- this.pages.add(absolutePath);
47
- }
48
- /**
49
- * Remove a single entrypoint. Idempotent.
50
- */
51
- remove(absolutePath) {
52
- this.pages.delete(absolutePath);
53
- }
54
- /** True if the index contains `absolutePath`. */
55
- has(absolutePath) {
56
- return this.pages.has(absolutePath);
57
- }
58
- /** Snapshot of the current set, sorted by absolute path. */
59
- list() {
60
- return Array.from(this.pages).sort();
61
- }
62
- /** Number of indexed entrypoints. */
63
- get size() {
64
- return this.pages.size;
65
- }
66
- /** Last refresh timestamp (ms since epoch). */
67
- get refreshedAt() {
68
- return this.lastRefreshAt;
69
- }
70
- }
71
- export {
72
- PagesIndex
73
- };
@@ -1,46 +0,0 @@
1
- import type { HtmlTemplateProps, IntegrationRendererRenderOptions, RequestLocals } from '@ecopages/core';
2
- import type { ReactNode } from 'react';
3
- type PagePayloadOptions = {
4
- pageProps?: HtmlTemplateProps['pageProps'];
5
- params: IntegrationRendererRenderOptions<ReactNode>['params'];
6
- query: IntegrationRendererRenderOptions<ReactNode>['query'];
7
- safeLocals?: RequestLocals;
8
- };
9
- /**
10
- * Builds the serialized page payload React exposes to document shells and the browser.
11
- *
12
- * This keeps hydration payload shaping away from the renderer so the renderer can
13
- * stay focused on component orchestration instead of data serialization rules.
14
- */
15
- export declare class ReactPagePayloadService {
16
- /**
17
- * Creates the canonical page-props payload used by router hydration.
18
- *
19
- * React pages embedded in a non-React HTML shell still need to expose the same
20
- * page-data contract as fully React-owned documents so navigation and hydration
21
- * can read one shared document payload consistently.
22
- */
23
- buildRouterPageDataScript(pageProps: HtmlTemplateProps['pageProps'] | undefined): string;
24
- /**
25
- * Builds the serialized page-props payload embedded into the final HTML.
26
- *
27
- * The document payload is intentionally narrower than the full server render
28
- * input: only routing data, public page props, and explicitly allowed locals are
29
- * exposed to the browser.
30
- */
31
- buildSerializedPageProps(options: PagePayloadOptions): HtmlTemplateProps['pageProps'];
32
- /**
33
- * Safely extracts the declared subset of locals for client-side hydration.
34
- *
35
- * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
36
- * request-scoped data (e.g., session). Only keys explicitly declared via
37
- * `Page.requires` are serialized to the client so sensitive request-only data
38
- * is not leaked into hydration payloads by default.
39
- *
40
- * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
41
- * to prevent accidental use. This method safely detects that case and returns
42
- * `undefined` instead of throwing.
43
- */
44
- getSerializableLocals(locals: RequestLocals | undefined, requiredLocals?: string | readonly string[]): RequestLocals | undefined;
45
- }
46
- export {};
@@ -1,67 +0,0 @@
1
- import { LocalsAccessError } from "@ecopages/core/errors";
2
- import { serializePageDataScript } from "../serialize-page-data-script.js";
3
- class ReactPagePayloadService {
4
- /**
5
- * Creates the canonical page-props payload used by router hydration.
6
- *
7
- * React pages embedded in a non-React HTML shell still need to expose the same
8
- * page-data contract as fully React-owned documents so navigation and hydration
9
- * can read one shared document payload consistently.
10
- */
11
- buildRouterPageDataScript(pageProps) {
12
- return serializePageDataScript(pageProps);
13
- }
14
- /**
15
- * Builds the serialized page-props payload embedded into the final HTML.
16
- *
17
- * The document payload is intentionally narrower than the full server render
18
- * input: only routing data, public page props, and explicitly allowed locals are
19
- * exposed to the browser.
20
- */
21
- buildSerializedPageProps(options) {
22
- return {
23
- ...options.pageProps,
24
- params: options.params,
25
- query: options.query,
26
- ...options.safeLocals && { locals: options.safeLocals }
27
- };
28
- }
29
- /**
30
- * Safely extracts the declared subset of locals for client-side hydration.
31
- *
32
- * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
33
- * request-scoped data (e.g., session). Only keys explicitly declared via
34
- * `Page.requires` are serialized to the client so sensitive request-only data
35
- * is not leaked into hydration payloads by default.
36
- *
37
- * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
38
- * to prevent accidental use. This method safely detects that case and returns
39
- * `undefined` instead of throwing.
40
- */
41
- getSerializableLocals(locals, requiredLocals) {
42
- try {
43
- if (!locals) {
44
- return void 0;
45
- }
46
- const requiredKeys = requiredLocals ? Array.isArray(requiredLocals) ? requiredLocals : [requiredLocals] : [];
47
- if (requiredKeys.length === 0) {
48
- return void 0;
49
- }
50
- const serializedLocals = Object.fromEntries(
51
- requiredKeys.filter((key) => Object.prototype.hasOwnProperty.call(locals, key)).map((key) => [key, locals[key]])
52
- );
53
- if (Object.keys(serializedLocals).length > 0) {
54
- return serializedLocals;
55
- }
56
- return void 0;
57
- } catch (error) {
58
- if (error instanceof LocalsAccessError) {
59
- return void 0;
60
- }
61
- throw error;
62
- }
63
- }
64
- }
65
- export {
66
- ReactPagePayloadService
67
- };
@@ -1,371 +0,0 @@
1
- const DEFAULT_LAYOUT_COMPOSE_IMPORT_PATH = "@ecopages/react/layout-compose";
2
- const PAGE_LAYOUT_NORMALIZATION_IMPORT = "@ecopages/core/eco/page-layout-normalization";
3
- function resolveLayoutComposeImportPath(options) {
4
- return options.layoutComposeImportPath ?? DEFAULT_LAYOUT_COMPOSE_IMPORT_PATH;
5
- }
6
- function getImportStatement(importPath, isMdx) {
7
- return isMdx ? `import * as MDXModule from "${importPath}";
8
- import { ensurePageConfigLayouts } from "${PAGE_LAYOUT_NORMALIZATION_IMPORT}";
9
- const Page = MDXModule.default;
10
- if (MDXModule.config) {
11
- Page.config = MDXModule.config;
12
- ensurePageConfigLayouts(Page.config);
13
- }` : `import Page from "${importPath}";`;
14
- }
15
- function getHmrImportStatement(isMdx) {
16
- return isMdx ? `const NewPage = newModule.default;
17
- if (newModule.config) {
18
- NewPage.config = newModule.config;
19
- ensurePageConfigLayouts(NewPage.config);
20
- }` : "const NewPage = newModule.default;";
21
- }
22
- function getComponentType(isMdx) {
23
- return isMdx ? "MDX" : "React";
24
- }
25
- function getDevPageRootCleanupScript() {
26
- return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
27
- window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
28
- window.__ECO_PAGES__.react.cleanupPageRoot = () => {
29
- const activeRoot = window.__ECO_PAGES__.react?.pageRoot || root;
30
- if (!activeRoot) {
31
- window.__ECO_PAGES__.react.pageRoot = null;
32
- window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
33
- delete window.__ECO_PAGES__.page;
34
- return;
35
- }
36
- window.__ECO_PAGES__.react.pageRoot = null;
37
- window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
38
- delete window.__ECO_PAGES__.page;
39
- root = null;
40
- activeRoot.unmount();
41
- };`;
42
- }
43
- function getProdPageRootCleanupScript() {
44
- 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()};';
45
- }
46
- function getDevRouterBootstrapRegistrationScript() {
47
- return `const currentOwnerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
48
- if (!(currentOwnerState?.owner === "react-router" && currentOwnerState.canHandleSpaNavigation)) {
49
- window.__ECO_PAGES__?.navigation?.register({
50
- owner: "react-router",
51
- cleanupBeforeHandoff: async () => {
52
- window.__ECO_PAGES__?.react?.cleanupPageRoot?.();
53
- }
54
- });
55
- window.__ECO_PAGES__?.navigation?.claimOwnership?.("react-router");
56
- }`;
57
- }
58
- function getProdRouterBootstrapRegistrationScript() {
59
- 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")}';
60
- }
61
- function getDevReuseExistingRouterRootScript() {
62
- return `const shouldReuseExistingRouterRoot = () => {
63
- const ownerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
64
- return Boolean(
65
- window.__ECO_PAGES__.react?.pageRoot &&
66
- ownerState?.owner === "react-router" &&
67
- ownerState.canHandleSpaNavigation
68
- );
69
- };`;
70
- }
71
- function getProdReuseExistingRouterRootScript() {
72
- return 'const sr=()=>{const o=window.__ECO_PAGES__?.navigation?.getOwnerState?.();return!!(window.__ECO_PAGES__.react?.pageRoot&&o?.owner==="react-router"&&o.canHandleSpaNavigation)};';
73
- }
74
- function getDevRerunRegistrationScript(scriptId) {
75
- return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
76
- window.__ECO_PAGES__.rerunScripts = window.__ECO_PAGES__.rerunScripts || {};
77
- window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}] = mount;`;
78
- }
79
- function getProdRerunRegistrationScript(scriptId) {
80
- return `window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.rerunScripts=window.__ECO_PAGES__.rerunScripts||{};window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}]=m;`;
81
- }
82
- function createDevScriptWithRouter(options) {
83
- const { importPath, isMdx, router, reactImportPath, reactDomClientImportPath, routerImportPath, scriptId } = options;
84
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
85
- const { components, getRouterProps } = router;
86
- if (!routerImportPath) {
87
- throw new Error("routerImportPath is required when router adapter is configured");
88
- }
89
- return `
90
- import { hydrateRoot } from "${reactDomClientImportPath}";
91
- import { createElement } from "${reactImportPath}";
92
- import { ${components.router}, ${components.pageContent} } from "${routerImportPath}";
93
- ${getImportStatement(importPath, isMdx)}
94
- const pageModuleUrl = ${pageModuleUrlExpression};
95
- export default Page;
96
- export const config = Page.config;
97
- const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
98
-
99
- if (isActivePageEntry) {
100
-
101
- window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
102
- window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
103
- window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
104
- window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
105
- let root = window.__ECO_PAGES__.react.pageRoot;
106
- ${getDevPageRootCleanupScript()}
107
- ${getDevRouterBootstrapRegistrationScript()}
108
- ${getDevReuseExistingRouterRootScript()}
109
-
110
- const getPageData = () => {
111
- const el = document.getElementById("__ECO_PAGE_DATA__");
112
- if (el?.textContent) {
113
- try { return JSON.parse(el.textContent); } catch {}
114
- }
115
- return {};
116
- };
117
-
118
- const props = getPageData();
119
-
120
- window.__ECO_PAGES__.page = {
121
- module: pageModuleUrl,
122
- props
123
- };
124
-
125
- const createTree = (Component, props) => {
126
- const pageContent = createElement(${components.pageContent});
127
- return createElement(${components.router}, ${getRouterProps("Component", "props")}, pageContent);
128
- };
129
-
130
- const mount = () => {
131
- const props = getPageData();
132
- window.__ECO_PAGES__.page = {
133
- module: pageModuleUrl,
134
- props
135
- };
136
-
137
- if (shouldReuseExistingRouterRoot()) {
138
- root = window.__ECO_PAGES__.react.pageRoot;
139
- return;
140
- }
141
-
142
- if (window.__ECO_PAGES__.react?.pageRoot) {
143
- root = window.__ECO_PAGES__.react.pageRoot;
144
- return;
145
- }
146
-
147
- root = hydrateRoot(document.body, createTree(Page, props), {
148
- onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
149
- });
150
- window.__ECO_PAGES__.react.pageRoot = root;
151
- window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
152
- try {
153
- const newModule = await import(newUrl);
154
- const nextProps = getPageData();
155
- ${getHmrImportStatement(isMdx)}
156
- const currentPageLayoutStack = (Component) =>
157
- (Component.config?.layouts ?? []).map((layout) => layout?.config?.__eco?.file ?? '').join('|');
158
- const currentPageLayoutStackKey = currentPageLayoutStack(Page);
159
- const nextPageLayoutStackKey = currentPageLayoutStack(NewPage);
160
-
161
- if (window.__ECO_PAGES__?.navigation?.getOwnerState().owner === "react-router") {
162
- await window.__ECO_PAGES__?.navigation?.reloadCurrentPage?.({
163
- clearCache: currentPageLayoutStackKey !== nextPageLayoutStackKey,
164
- moduleUrl: "${importPath}",
165
- source: "react-router"
166
- });
167
- console.log("[ecopages] ${getComponentType(isMdx)} component updated via router");
168
- return;
169
- }
170
-
171
- window.__ECO_PAGES__.page = {
172
- module: pageModuleUrl,
173
- props: nextProps
174
- };
175
- root.render(createTree(NewPage, nextProps));
176
- console.log("[ecopages] ${getComponentType(isMdx)} component updated");
177
- } catch (e) {
178
- console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
179
- }
180
- };
181
- };
182
-
183
- ${getDevRerunRegistrationScript(scriptId)}
184
-
185
- if (document.readyState === "loading") {
186
- document.addEventListener("DOMContentLoaded", mount);
187
- } else {
188
- mount();
189
- }
190
- }
191
- `.trim();
192
- }
193
- function createDevScriptWithoutRouter(options) {
194
- const { importPath, isMdx, reactImportPath, reactDomClientImportPath, scriptId } = options;
195
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
196
- const layoutComposeImportPath = resolveLayoutComposeImportPath(options);
197
- return `
198
- import { hydrateRoot } from "${reactDomClientImportPath}";
199
- import { createElement } from "${reactImportPath}";
200
- import { composeLayoutPageTree } from "${layoutComposeImportPath}";
201
- ${getImportStatement(importPath, isMdx)}
202
- const pageModuleUrl = ${pageModuleUrlExpression};
203
- export default Page;
204
- export const config = Page.config;
205
- const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
206
-
207
- if (isActivePageEntry) {
208
-
209
- window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
210
- window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
211
- window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
212
- window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
213
- let root = window.__ECO_PAGES__.react.pageRoot;
214
- ${getDevPageRootCleanupScript()}
215
-
216
- const getPageData = () => {
217
- const el = document.getElementById("__ECO_PAGE_DATA__");
218
- if (el?.textContent) {
219
- try { return JSON.parse(el.textContent); } catch {}
220
- }
221
- return {};
222
- };
223
-
224
- const props = getPageData();
225
-
226
- window.__ECO_PAGES__.page = {
227
- module: pageModuleUrl,
228
- props
229
- };
230
-
231
- const createTree = (Component, props) => composeLayoutPageTree(Component, props);
232
-
233
- const mount = () => {
234
- const props = getPageData();
235
- window.__ECO_PAGES__.page = {
236
- module: pageModuleUrl,
237
- props
238
- };
239
-
240
- if (window.__ECO_PAGES__.react?.pageRoot) {
241
- root = window.__ECO_PAGES__.react.pageRoot;
242
- root.render(createTree(Page, props));
243
- } else {
244
- root = hydrateRoot(document.body, createTree(Page, props), {
245
- onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
246
- });
247
- window.__ECO_PAGES__.react.pageRoot = root;
248
- }
249
- window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
250
- try {
251
- const newModule = await import(newUrl);
252
- ${getHmrImportStatement(isMdx)}
253
- root.render(createTree(NewPage, props));
254
- console.log("[ecopages] ${getComponentType(isMdx)} component updated");
255
- } catch (e) {
256
- console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
257
- }
258
- };
259
- };
260
-
261
- ${getDevRerunRegistrationScript(scriptId)}
262
-
263
- if (document.readyState === "loading") {
264
- document.addEventListener("DOMContentLoaded", mount);
265
- } else {
266
- mount();
267
- }
268
- }
269
- `.trim();
270
- }
271
- function createProdScriptWithRouter(options) {
272
- const { importPath, isMdx, router, reactImportPath, reactDomClientImportPath, routerImportPath, scriptId } = options;
273
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
274
- const { components, getRouterProps } = router;
275
- if (!routerImportPath) {
276
- throw new Error("routerImportPath is required when router adapter is configured");
277
- }
278
- if (isMdx) {
279
- 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{ensurePageConfigLayouts as epl}from"${PAGE_LAYOUT_NORMALIZATION_IMPORT}";import*as M from"${importPath}";const P=M.default;if(M.config){P.config=M.config;epl(P.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()}`;
280
- }
281
- 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()}`;
282
- }
283
- function createProdScriptWithoutRouter(options) {
284
- const { importPath, isMdx, reactImportPath, reactDomClientImportPath, scriptId } = options;
285
- const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
286
- const layoutComposeImportPath = resolveLayoutComposeImportPath(options);
287
- if (isMdx) {
288
- return `import{hydrateRoot as hr}from"${reactDomClientImportPath}";import{createElement as ce}from"${reactImportPath}";import{composeLayoutPageTree as clp}from"${layoutComposeImportPath}";import{ensurePageConfigLayouts as epl}from"${PAGE_LAYOUT_NORMALIZATION_IMPORT}";import*as M from"${importPath}";const P=M.default;if(M.config){P.config=M.config;epl(P.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)=>clp(C,p);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()}`;
289
- }
290
- return `import{hydrateRoot as hr}from"${reactDomClientImportPath}";import{createElement as ce}from"${reactImportPath}";import{composeLayoutPageTree as clp}from"${layoutComposeImportPath}";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)=>clp(C,p);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()}`;
291
- }
292
- function createHydrationScript(options) {
293
- const { isDevelopment, router } = options;
294
- if (isDevelopment) {
295
- return router ? createDevScriptWithRouter(options) : createDevScriptWithoutRouter(options);
296
- }
297
- return router ? createProdScriptWithRouter(options) : createProdScriptWithoutRouter(options);
298
- }
299
- function createIslandHydrationScript(options) {
300
- const targetSelector = JSON.stringify(options.targetSelector);
301
- const componentRef = JSON.stringify(options.componentRef ?? "");
302
- const componentFile = JSON.stringify(options.componentFile ?? "");
303
- const scriptId = options.scriptId;
304
- if (options.isDevelopment) {
305
- return `
306
- import { createRoot } from "${options.reactDomClientImportPath}";
307
- import { createElement } from "${options.reactImportPath}";
308
- import * as ComponentModule from "${options.importPath}";
309
-
310
- const resolveComponent = () => {
311
- const id = ${componentRef};
312
- const file = ${componentFile};
313
- const moduleValues = Object.values(ComponentModule);
314
-
315
- const matchByMetadata = moduleValues.find((entry) => {
316
- if (typeof entry !== "function") return false;
317
- const config = entry.config;
318
- const eco = config?.__eco;
319
- if (!eco) return false;
320
- if (id && eco.id === id) return true;
321
- if (file && eco.file === file) return true;
322
- return false;
323
- });
324
-
325
- if (matchByMetadata && typeof matchByMetadata === "function") {
326
- return matchByMetadata;
327
- }
328
-
329
- const defaultExport = ComponentModule.default;
330
- if (typeof defaultExport === "function") {
331
- return defaultExport;
332
- }
333
-
334
- const firstFunction = moduleValues.find((entry) => typeof entry === "function");
335
- return typeof firstFunction === "function" ? firstFunction : null;
336
- };
337
-
338
- const mount = () => {
339
- const targets = document.querySelectorAll(${targetSelector});
340
- const Component = resolveComponent();
341
- if (!Component || targets.length === 0) {
342
- return;
343
- }
344
- targets.forEach((target) => {
345
- if (!(target instanceof HTMLElement)) {
346
- return;
347
- }
348
- const props = JSON.parse(atob(target.getAttribute("data-eco-props") || "e30="));
349
- const container = document.createElement("eco-island");
350
- container.style.display = "block";
351
- target.replaceWith(container);
352
- const root = createRoot(container);
353
- root.render(createElement(Component, props));
354
- });
355
- };
356
-
357
- ${getDevRerunRegistrationScript(scriptId)}
358
-
359
- if (document.readyState === "loading") {
360
- document.addEventListener("DOMContentLoaded", mount, { once: true });
361
- } else {
362
- mount();
363
- }
364
- `.trim();
365
- }
366
- 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()`;
367
- }
368
- export {
369
- createHydrationScript,
370
- createIslandHydrationScript
371
- };
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes