@ecopages/react 0.2.1-beta.0 → 0.3.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 (181) hide show
  1. package/README.md +164 -28
  2. package/package.json +67 -30
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +38 -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} +29 -11
  9. package/src/bundling/bundle.js +130 -0
  10. package/src/bundling/runtime-alias-map.d.ts +12 -0
  11. package/src/bundling/runtime-alias-map.js +110 -0
  12. package/src/bundling/runtime-bundle.d.ts +70 -0
  13. package/src/bundling/runtime-bundle.js +233 -0
  14. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  15. package/src/bundling/runtime-interop-plugin.js +32 -0
  16. package/src/bundling/runtime-mode.d.ts +1 -0
  17. package/src/bundling/runtime-mode.js +10 -0
  18. package/src/bundling/runtime-modules.d.ts +21 -0
  19. package/src/bundling/runtime-modules.js +28 -0
  20. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  21. package/src/client-graph/ast-transform-eco-page.js +71 -0
  22. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  23. package/src/client-graph/ast-transform-import-edits.js +75 -0
  24. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  25. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  26. package/src/client-graph/ast-transform.d.ts +12 -0
  27. package/src/client-graph/ast-transform.js +91 -0
  28. package/src/client-graph/ast-walk.d.ts +10 -0
  29. package/src/client-graph/ast-walk.js +26 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  32. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  33. package/src/client-graph/boundary-plugin-transform.js +31 -0
  34. package/src/client-graph/boundary-plugin.d.ts +23 -0
  35. package/src/client-graph/boundary-plugin.js +177 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/client-graph/declared-modules.js +69 -0
  38. package/src/client-graph/module-classification.d.ts +3 -0
  39. package/src/client-graph/module-classification.js +43 -0
  40. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  41. package/src/client-graph/reachability-analyzer.js +55 -0
  42. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  43. package/src/client-graph/reachability-client-roots.js +59 -0
  44. package/src/client-graph/reachability-export-names.d.ts +5 -0
  45. package/src/client-graph/reachability-export-names.js +34 -0
  46. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  47. package/src/client-graph/reachability-fallback-roots.js +71 -0
  48. package/src/client-graph/reachability-preload.d.ts +10 -0
  49. package/src/client-graph/reachability-preload.js +30 -0
  50. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  51. package/src/client-graph/reachability-top-level-index.js +93 -0
  52. package/src/client-graph/reachability-traverse.d.ts +7 -0
  53. package/src/client-graph/reachability-traverse.js +201 -0
  54. package/src/client-graph/specifier-classification.d.ts +74 -0
  55. package/src/client-graph/specifier-classification.js +191 -0
  56. package/src/content/collection-component-cache.d.ts +25 -0
  57. package/src/content/collection-component-cache.js +62 -0
  58. package/src/contracts/router-adapter.js +6 -0
  59. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  60. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  61. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  62. package/src/hmr/hmr-strategy-process.js +83 -0
  63. package/src/hmr/hmr-strategy.d.ts +67 -0
  64. package/src/hmr/hmr-strategy.js +306 -0
  65. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  66. package/src/hmr/page-metadata-cache.js +44 -0
  67. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  68. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  69. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  70. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  71. package/src/hydration/bootstrap-imports.d.ts +25 -0
  72. package/src/hydration/bootstrap-imports.js +33 -0
  73. package/src/hydration/browser/island-hydration.d.ts +82 -0
  74. package/src/hydration/browser/island-hydration.js +251 -0
  75. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  76. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  77. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  78. package/src/hydration/browser/page-hydration-module.js +17 -0
  79. package/src/hydration/browser/page-hydration.d.ts +54 -0
  80. package/src/hydration/browser/page-hydration.js +177 -0
  81. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  82. package/src/hydration/hydration-asset.d.ts +127 -0
  83. package/src/hydration/hydration-asset.js +379 -0
  84. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  85. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  86. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  87. package/src/hydration/hydration-page-entry-source.js +87 -0
  88. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  89. package/src/hydration/hydration-script-compiler.js +213 -0
  90. package/src/hydration/page-data-manifest.d.ts +58 -0
  91. package/src/hydration/page-data-manifest.js +97 -0
  92. package/src/hydration/page-data-reader.d.ts +17 -0
  93. package/src/hydration/page-data-reader.js +31 -0
  94. package/src/hydration/page-payload.d.ts +68 -0
  95. package/src/hydration/page-payload.js +106 -0
  96. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  97. package/src/hydration/serialize-page-data-script.js +30 -0
  98. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +9 -8
  99. package/src/mdx/mdx-config-dependency.js +107 -0
  100. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  101. package/src/mdx/mdx-loader-plugin.js +11 -0
  102. package/src/page/page-module.d.ts +46 -0
  103. package/src/page/page-module.js +74 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +21 -27
  106. package/src/plugin/react.plugin.js +210 -0
  107. package/src/plugin/react.types.d.ts +106 -0
  108. package/src/plugin/react.types.js +1 -0
  109. package/src/render/component-ownership.d.ts +49 -0
  110. package/src/render/component-ownership.js +47 -0
  111. package/src/render/component-ssr.d.ts +59 -0
  112. package/src/render/component-ssr.js +76 -0
  113. package/src/render/eco-embed.js +9 -0
  114. package/src/render/errors.d.ts +16 -0
  115. package/src/render/errors.js +23 -0
  116. package/src/render/html-boundary.js +59 -0
  117. package/src/render/layout-compose.d.ts +66 -0
  118. package/src/render/layout-compose.js +134 -0
  119. package/src/render/react-renderer.d.ts +114 -0
  120. package/src/render/react-renderer.js +490 -0
  121. package/src/render/react-runtime.d.ts +13 -0
  122. package/src/render/react-runtime.js +26 -0
  123. package/src/render/unified-layout-composition.d.ts +22 -0
  124. package/src/render/unified-layout-composition.js +31 -0
  125. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  126. package/src/eco-embed.js +0 -11
  127. package/src/react-hmr-strategy.d.ts +0 -230
  128. package/src/react-hmr-strategy.js +0 -657
  129. package/src/react-renderer.d.ts +0 -233
  130. package/src/react-renderer.js +0 -622
  131. package/src/react.constants.js +0 -4
  132. package/src/react.plugin.js +0 -205
  133. package/src/react.types.d.ts +0 -88
  134. package/src/react.types.js +0 -0
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/pages-index.d.ts +0 -64
  137. package/src/services/pages-index.js +0 -73
  138. package/src/services/react-bundle.service.js +0 -86
  139. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  140. package/src/services/react-hydration-asset.service.d.ts +0 -84
  141. package/src/services/react-hydration-asset.service.js +0 -217
  142. package/src/services/react-mdx-config-dependency.service.js +0 -122
  143. package/src/services/react-page-module.service.d.ts +0 -88
  144. package/src/services/react-page-module.service.js +0 -166
  145. package/src/services/react-page-payload.service.d.ts +0 -46
  146. package/src/services/react-page-payload.service.js +0 -67
  147. package/src/services/react-runtime-bundle.service.d.ts +0 -45
  148. package/src/services/react-runtime-bundle.service.js +0 -186
  149. package/src/utils/client-graph-boundary-cache.d.ts +0 -108
  150. package/src/utils/client-graph-boundary-cache.js +0 -116
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -51
  152. package/src/utils/client-graph-boundary-plugin.js +0 -552
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/component-config-traversal.js +0 -54
  155. package/src/utils/declared-modules.js +0 -47
  156. package/src/utils/dynamic.js +0 -12
  157. package/src/utils/dynamic.test.browser.js +0 -33
  158. package/src/utils/hmr-scripts.d.ts +0 -18
  159. package/src/utils/hmr-scripts.js +0 -31
  160. package/src/utils/html-boundary.js +0 -55
  161. package/src/utils/hydration-scripts.d.ts +0 -92
  162. package/src/utils/hydration-scripts.js +0 -358
  163. package/src/utils/hydration-scripts.test.browser.js +0 -198
  164. package/src/utils/reachability-analyzer.d.ts +0 -66
  165. package/src/utils/reachability-analyzer.js +0 -339
  166. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  167. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  168. package/src/utils/react-mdx-loader-plugin.js +0 -45
  169. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  170. package/src/utils/react-runtime-alias-map.js +0 -90
  171. /package/src/{utils → app}/client-only.d.ts +0 -0
  172. /package/src/{utils → app}/dynamic.d.ts +0 -0
  173. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  174. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  175. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  176. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  177. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  178. /package/src/{utils/hydration-scripts.test.browser.d.ts → hydration/compiled-page-hydration-options.js} +0 -0
  179. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  180. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  181. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,213 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { rolldown } from 'rolldown';
3
+ const ISLAND_BOOTSTRAP_ID = '\0ecopages-react-island-bootstrap';
4
+ const PAGE_BOOTSTRAP_ID = '\0ecopages-react-page-bootstrap';
5
+ const PAGE_HYDRATION_MODULE_ID = '\0ecopages-react-page-hydration-module';
6
+ const PAGE_HYDRATION_HMR_ID = '\0ecopages-react-page-hydration-hmr';
7
+ const PAGE_DATA_READER_ID = '\0ecopages-react-page-data-reader';
8
+ const PAGE_DATA_MANIFEST_ID = '\0ecopages-react-page-data-manifest';
9
+ import { createPageEntrySource } from './hydration-page-entry-source.js';
10
+ /** Serializes every compilation input so source/config changes cannot reuse stale output. */
11
+ function getCacheKey(options) {
12
+ return JSON.stringify(options);
13
+ }
14
+ /**
15
+ * Creates the small Island Host entry that imports application modules and
16
+ * delegates lifecycle behavior to the typed browser bootstrap.
17
+ */
18
+ function createEntrySource(options) {
19
+ const hmrSource = options.hmrEnabled
20
+ ? `registerIslandHmr(configuration, (url) => import(url), ${JSON.stringify(options.importPath)});`
21
+ : '';
22
+ return `
23
+ import { hydrateRoot } from ${JSON.stringify(options.reactDomClientImportPath)};
24
+ import { createElement, useEffect } from ${JSON.stringify(options.reactImportPath)};
25
+ import * as ComponentModule from ${JSON.stringify(options.importPath)};
26
+ import { getIslandHydrationRuntime, mountIslands, registerIslandHmr } from ${JSON.stringify(ISLAND_BOOTSTRAP_ID)};
27
+
28
+ const configuration = {
29
+ targetSelector: ${JSON.stringify(options.targetSelector)},
30
+ componentModule: ComponentModule,
31
+ componentRef: ${JSON.stringify(options.componentRef ?? '')},
32
+ componentFile: ${JSON.stringify(options.componentFile ?? '')},
33
+ scriptId: ${JSON.stringify(options.scriptId)},
34
+ runtime: { hydrateRoot, createElement, useEffect },
35
+ runtimeState: getIslandHydrationRuntime()
36
+ };
37
+ const mount = () => mountIslands(configuration);
38
+ ${hmrSource}
39
+ document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", mount, { once: true }) : mount();
40
+ `;
41
+ }
42
+ /**
43
+ * Resolves framework browser sources from repository TypeScript or published
44
+ * JavaScript files while keeping application and vendor modules external.
45
+ */
46
+ function createBootstrapPlugin() {
47
+ const sourcePaths = new Map([
48
+ [ISLAND_BOOTSTRAP_ID, ['island-hydration.ts', 'island-hydration.js']],
49
+ [PAGE_BOOTSTRAP_ID, ['page-hydration.ts', 'page-hydration.js']],
50
+ [PAGE_HYDRATION_MODULE_ID, ['page-hydration-module.ts', 'page-hydration-module.js']],
51
+ [PAGE_HYDRATION_HMR_ID, ['page-hydration-hmr.ts', 'page-hydration-hmr.js']],
52
+ [PAGE_DATA_READER_ID, ['../page-data-reader.js', '../page-data-reader.js']],
53
+ ]);
54
+ const readBootstrapSource = (id) => {
55
+ const candidates = sourcePaths.get(id);
56
+ if (!candidates)
57
+ throw new Error(`Unknown hydration bootstrap module: ${id}`);
58
+ for (const relativePath of candidates) {
59
+ try {
60
+ return readFileSync(new URL(`./browser/${relativePath}`, import.meta.url), 'utf8');
61
+ }
62
+ catch {
63
+ continue;
64
+ }
65
+ }
66
+ throw new Error(`Unable to locate hydration bootstrap source for ${id}`);
67
+ };
68
+ const pageBootstrapRelativeImports = new Map([
69
+ ['./page-hydration-module.js', PAGE_HYDRATION_MODULE_ID],
70
+ ['./page-hydration-hmr.js', PAGE_HYDRATION_HMR_ID],
71
+ ]);
72
+ return {
73
+ name: 'ecopages-react-hydration-bootstrap',
74
+ resolveId(source, importer) {
75
+ if (sourcePaths.has(source))
76
+ return source;
77
+ if (importer === PAGE_DATA_READER_ID && source === './page-data-manifest.js') {
78
+ return PAGE_DATA_MANIFEST_ID;
79
+ }
80
+ if (importer && pageBootstrapRelativeImports.has(source)) {
81
+ if (importer === PAGE_BOOTSTRAP_ID || importer === PAGE_HYDRATION_HMR_ID) {
82
+ return pageBootstrapRelativeImports.get(source);
83
+ }
84
+ }
85
+ return undefined;
86
+ },
87
+ load(id) {
88
+ if (id === PAGE_DATA_MANIFEST_ID) {
89
+ return {
90
+ code: readFileSync(new URL('./page-data-manifest.js', import.meta.url), 'utf8'),
91
+ moduleType: 'ts',
92
+ };
93
+ }
94
+ if (!sourcePaths.has(id))
95
+ return undefined;
96
+ return { code: readBootstrapSource(id), moduleType: 'ts' };
97
+ },
98
+ };
99
+ }
100
+ /** Bundles one virtual entry and closes the Rolldown bundle after generation. */
101
+ async function compileEntry(options) {
102
+ const bundle = await rolldown({
103
+ input: options.entryId,
104
+ plugins: [
105
+ {
106
+ name: 'ecopages-react-entry',
107
+ resolveId(source) {
108
+ return source === options.entryId ? source : undefined;
109
+ },
110
+ load(id) {
111
+ return id === options.entryId ? { code: options.entrySource, moduleType: 'js' } : undefined;
112
+ },
113
+ },
114
+ createBootstrapPlugin(),
115
+ ],
116
+ external: options.external,
117
+ transform: { target: 'es2021' },
118
+ });
119
+ try {
120
+ const generated = await bundle.generate({ format: 'esm', minify: options.minify });
121
+ const chunk = generated.output.find((output) => output.type === 'chunk');
122
+ if (!chunk || !('code' in chunk))
123
+ throw new Error(options.errorMessage);
124
+ return chunk.code ?? '';
125
+ }
126
+ finally {
127
+ await bundle.close();
128
+ }
129
+ }
130
+ /** Compiles an Island Host entry using the shared virtual-entry pipeline. */
131
+ function compileIsland(options) {
132
+ return compileEntry({
133
+ entryId: 'virtual:ecopages-react-island-entry',
134
+ entrySource: createEntrySource(options),
135
+ external: [options.importPath, options.reactImportPath, options.reactDomClientImportPath],
136
+ minify: options.minify,
137
+ errorMessage: 'React hydration compiler emitted no JavaScript chunk',
138
+ });
139
+ }
140
+ /** Compiles a Page entry using the shared virtual-entry pipeline. */
141
+ function compilePage(options) {
142
+ return compileEntry({
143
+ entryId: 'virtual:ecopages-react-page-entry',
144
+ entrySource: createPageEntrySource(options),
145
+ external: [
146
+ options.importPath,
147
+ options.reactImportPath,
148
+ options.reactDomClientImportPath,
149
+ options.routerImportPath,
150
+ options.layoutComposeImportPath,
151
+ options.pageLayoutNormalizationImportPath,
152
+ ].filter((value) => Boolean(value)),
153
+ minify: options.minify,
154
+ errorMessage: 'React page hydration compiler emitted no JavaScript chunk',
155
+ });
156
+ }
157
+ /** Caches in-flight and completed compilations while evicting rejected work. */
158
+ class CompilationCache {
159
+ entries = new Map();
160
+ /** Returns a cached compilation or starts exactly one compilation for the key. */
161
+ getOrCompile(key, factory) {
162
+ const cached = this.entries.get(key);
163
+ if (cached)
164
+ return cached;
165
+ const pending = factory();
166
+ this.entries.set(key, pending);
167
+ pending.then(() => undefined, () => {
168
+ if (this.entries.get(key) === pending)
169
+ this.entries.delete(key);
170
+ });
171
+ return pending;
172
+ }
173
+ }
174
+ /**
175
+ * Compiles the editable React Island Host lifecycle into a browser ESM string.
176
+ *
177
+ * @remarks
178
+ * Compilation is cached by the complete entry configuration. Rejected promises
179
+ * are removed so a transient filesystem or bundler error can recover.
180
+ */
181
+ export class IslandHydrationScriptCompiler {
182
+ compilationCache = new CompilationCache();
183
+ /**
184
+ * Compiles and caches one readable or minified Island Host entry.
185
+ *
186
+ * @param options - Complete entry imports, selector, identity, and output mode.
187
+ * @returns A browser ESM source string.
188
+ */
189
+ compile(options) {
190
+ const key = getCacheKey(options);
191
+ return this.compilationCache.getOrCompile(key, () => compileIsland(options));
192
+ }
193
+ }
194
+ /**
195
+ * Compiles editable Page lifecycle modules into browser ESM strings.
196
+ *
197
+ * @remarks
198
+ * The cache belongs to the service instance, allowing development restarts to
199
+ * discard framework-source changes without sharing stale output globally.
200
+ */
201
+ export class PageHydrationScriptCompiler {
202
+ compilationCache = new CompilationCache();
203
+ /**
204
+ * Compiles and caches one readable or minified Page entry.
205
+ *
206
+ * @param options - Complete page imports, router contract, and output mode.
207
+ * @returns A browser ESM source string.
208
+ */
209
+ compile(options) {
210
+ const key = getCacheKey(options);
211
+ return this.compilationCache.getOrCompile(key, () => compilePage(options));
212
+ }
213
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Versioned React page-data document payload.
3
+ *
4
+ * @remarks
5
+ * The `__ECO_PAGE_DATA__` script emits this envelope so client navigation can
6
+ * read module identity without parsing generated hydration JavaScript. Older
7
+ * documents may still contain a flat props object; consumers must detect both.
8
+ *
9
+ * Compatibility matrix:
10
+ * - new client / new document: prefer `schemaVersion:1` envelope (`moduleUrl` + `props`)
11
+ * - new client / old document: accept legacy flat props; module discovery uses
12
+ * `window.__ECO_PAGES__.page.module` or `script[data-eco-page-bootstrap="react-router"]`
13
+ * - old client / new document: old clients that only read flat props should be
14
+ * upgraded; envelope consumers must unwrap `props` before hydration
15
+ * - malformed / unknown schema (numeric `schemaVersion` present but envelope invalid):
16
+ * empty props and no module URL from the manifest
17
+ * - HMR: `moduleUrlOverride` still bypasses document discovery
18
+ * - legacy flat props may include a string `schemaVersion` field without being treated as an envelope
19
+ */
20
+ export declare const ECO_PAGE_DATA_SCHEMA_VERSION: 1;
21
+ export type EcoPageDataProps = Record<string, unknown>;
22
+ export type EcoPageDataManifestV1 = {
23
+ schemaVersion: typeof ECO_PAGE_DATA_SCHEMA_VERSION;
24
+ navigationOwner: 'react-router';
25
+ moduleUrl: string;
26
+ props: EcoPageDataProps;
27
+ };
28
+ export type EcoPageDataDocumentPayload = EcoPageDataManifestV1 | EcoPageDataProps;
29
+ /**
30
+ * Returns whether a parsed JSON value is a versioned page-data envelope.
31
+ */
32
+ export declare function isEcoPageDataManifestV1(value: unknown): value is EcoPageDataManifestV1;
33
+ /**
34
+ * Extracts browser page props from either a v1 envelope or a legacy flat payload.
35
+ */
36
+ export declare function resolveEcoPageDataProps(payload: unknown): EcoPageDataProps;
37
+ /**
38
+ * Extracts the page module URL from a v1 envelope when present.
39
+ */
40
+ export declare function resolveEcoPageDataModuleUrl(payload: unknown): string | null;
41
+ /**
42
+ * Builds the canonical v1 page-data envelope for React documents.
43
+ */
44
+ export declare function createEcoPageDataManifestV1(input: {
45
+ moduleUrl: string;
46
+ props: EcoPageDataProps;
47
+ }): EcoPageDataManifestV1;
48
+ /**
49
+ * Normalizes flat page props or an existing envelope into the document payload shape.
50
+ *
51
+ * @remarks
52
+ * Shared by server serializers and `EcoPropsScript` so envelope rules stay in one place.
53
+ * A valid v1 envelope is returned as-is; `options.moduleUrl` is ignored in that case.
54
+ * Flat props wrap into a v1 envelope only when `options.moduleUrl` is provided.
55
+ */
56
+ export declare function resolvePageDataDocumentPayload(data: EcoPageDataDocumentPayload, options?: {
57
+ moduleUrl?: string;
58
+ }): EcoPageDataDocumentPayload;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Versioned React page-data document payload.
3
+ *
4
+ * @remarks
5
+ * The `__ECO_PAGE_DATA__` script emits this envelope so client navigation can
6
+ * read module identity without parsing generated hydration JavaScript. Older
7
+ * documents may still contain a flat props object; consumers must detect both.
8
+ *
9
+ * Compatibility matrix:
10
+ * - new client / new document: prefer `schemaVersion:1` envelope (`moduleUrl` + `props`)
11
+ * - new client / old document: accept legacy flat props; module discovery uses
12
+ * `window.__ECO_PAGES__.page.module` or `script[data-eco-page-bootstrap="react-router"]`
13
+ * - old client / new document: old clients that only read flat props should be
14
+ * upgraded; envelope consumers must unwrap `props` before hydration
15
+ * - malformed / unknown schema (numeric `schemaVersion` present but envelope invalid):
16
+ * empty props and no module URL from the manifest
17
+ * - HMR: `moduleUrlOverride` still bypasses document discovery
18
+ * - legacy flat props may include a string `schemaVersion` field without being treated as an envelope
19
+ */
20
+ export const ECO_PAGE_DATA_SCHEMA_VERSION = 1;
21
+ /**
22
+ * Returns whether a parsed JSON value is a versioned page-data envelope.
23
+ */
24
+ export function isEcoPageDataManifestV1(value) {
25
+ if (typeof value !== 'object' || value === null) {
26
+ return false;
27
+ }
28
+ const candidate = value;
29
+ return (candidate.schemaVersion === ECO_PAGE_DATA_SCHEMA_VERSION &&
30
+ candidate.navigationOwner === 'react-router' &&
31
+ typeof candidate.moduleUrl === 'string' &&
32
+ typeof candidate.props === 'object' &&
33
+ candidate.props !== null &&
34
+ !Array.isArray(candidate.props));
35
+ }
36
+ /**
37
+ * Returns whether a payload claims a numeric schema version without being a valid v1 envelope.
38
+ *
39
+ * @remarks
40
+ * Only numeric `schemaVersion` values are treated as envelope attempts. Legacy flat props may
41
+ * legitimately include a string `schemaVersion` field (e.g. a version string) and must not be
42
+ * wiped. Near-miss numeric envelopes must not fall through to the flat-props path.
43
+ */
44
+ function isMalformedPageDataEnvelope(payload) {
45
+ return 'schemaVersion' in payload && typeof payload.schemaVersion === 'number';
46
+ }
47
+ /**
48
+ * Extracts browser page props from either a v1 envelope or a legacy flat payload.
49
+ */
50
+ export function resolveEcoPageDataProps(payload) {
51
+ if (isEcoPageDataManifestV1(payload)) {
52
+ return payload.props;
53
+ }
54
+ if (typeof payload === 'object' && payload !== null && !Array.isArray(payload)) {
55
+ if (isMalformedPageDataEnvelope(payload)) {
56
+ return {};
57
+ }
58
+ return payload;
59
+ }
60
+ return {};
61
+ }
62
+ /**
63
+ * Extracts the page module URL from a v1 envelope when present.
64
+ */
65
+ export function resolveEcoPageDataModuleUrl(payload) {
66
+ return isEcoPageDataManifestV1(payload) ? payload.moduleUrl : null;
67
+ }
68
+ /**
69
+ * Builds the canonical v1 page-data envelope for React documents.
70
+ */
71
+ export function createEcoPageDataManifestV1(input) {
72
+ return {
73
+ schemaVersion: ECO_PAGE_DATA_SCHEMA_VERSION,
74
+ navigationOwner: 'react-router',
75
+ moduleUrl: input.moduleUrl,
76
+ props: input.props,
77
+ };
78
+ }
79
+ /**
80
+ * Normalizes flat page props or an existing envelope into the document payload shape.
81
+ *
82
+ * @remarks
83
+ * Shared by server serializers and `EcoPropsScript` so envelope rules stay in one place.
84
+ * A valid v1 envelope is returned as-is; `options.moduleUrl` is ignored in that case.
85
+ * Flat props wrap into a v1 envelope only when `options.moduleUrl` is provided.
86
+ */
87
+ export function resolvePageDataDocumentPayload(data, options) {
88
+ if (isEcoPageDataManifestV1(data)) {
89
+ return data;
90
+ }
91
+ const props = { ...data };
92
+ const moduleUrl = options?.moduleUrl;
93
+ if (!moduleUrl) {
94
+ return props;
95
+ }
96
+ return createEcoPageDataManifestV1({ moduleUrl, props });
97
+ }
@@ -0,0 +1,17 @@
1
+ import { type EcoPageDataProps } from './page-data-manifest.js';
2
+ export type ReadPageDataDocumentResult = {
3
+ moduleUrl?: string;
4
+ props: EcoPageDataProps;
5
+ };
6
+ /**
7
+ * Reads `__ECO_PAGE_DATA__`, supporting both v1 envelopes and legacy flat props.
8
+ *
9
+ * @remarks
10
+ * Always returns unwrapped `props`. `moduleUrl` is set only when the document
11
+ * carries a valid v1 envelope.
12
+ */
13
+ export declare function readPageDataDocument(): ReadPageDataDocumentResult;
14
+ /**
15
+ * Returns page props from `__ECO_PAGE_DATA__` for hydration and HMR handlers.
16
+ */
17
+ export declare function getPageDataFromDocument(): EcoPageDataProps;
@@ -0,0 +1,31 @@
1
+ import { resolveEcoPageDataModuleUrl, resolveEcoPageDataProps } from './page-data-manifest.js';
2
+ /**
3
+ * Reads `__ECO_PAGE_DATA__`, supporting both v1 envelopes and legacy flat props.
4
+ *
5
+ * @remarks
6
+ * Always returns unwrapped `props`. `moduleUrl` is set only when the document
7
+ * carries a valid v1 envelope.
8
+ */
9
+ export function readPageDataDocument() {
10
+ const element = document.getElementById('__ECO_PAGE_DATA__');
11
+ if (!element?.textContent) {
12
+ return { props: {} };
13
+ }
14
+ try {
15
+ const parsed = JSON.parse(element.textContent);
16
+ const moduleUrl = resolveEcoPageDataModuleUrl(parsed) ?? undefined;
17
+ return {
18
+ ...(moduleUrl && { moduleUrl }),
19
+ props: resolveEcoPageDataProps(parsed),
20
+ };
21
+ }
22
+ catch {
23
+ return { props: {} };
24
+ }
25
+ }
26
+ /**
27
+ * Returns page props from `__ECO_PAGE_DATA__` for hydration and HMR handlers.
28
+ */
29
+ export function getPageDataFromDocument() {
30
+ return readPageDataDocument().props;
31
+ }
@@ -0,0 +1,68 @@
1
+ import type { EcoComponentConfig, HtmlTemplateProps, RequestLocals } from '@ecopages/core';
2
+ import type { IntegrationRendererRenderOptions } from '@ecopages/core/integration';
3
+ import type { HtmlDocumentContribution } from '@ecopages/core/integration';
4
+ import type { ReactNode } from 'react';
5
+ type PagePayloadOptions = {
6
+ pageProps?: HtmlTemplateProps['pageProps'];
7
+ params: IntegrationRendererRenderOptions<ReactNode>['params'];
8
+ query: IntegrationRendererRenderOptions<ReactNode>['query'];
9
+ safeLocals?: RequestLocals;
10
+ };
11
+ type PagePackage = IntegrationRendererRenderOptions<ReactNode>['pagePackage'];
12
+ /**
13
+ * Builds the serialized page payload React exposes to document shells and the browser.
14
+ *
15
+ * @remarks
16
+ * Keeps hydration payload shaping away from the renderer so orchestration stays
17
+ * focused on component composition instead of document serialization rules.
18
+ */
19
+ export declare class PagePayloadService {
20
+ /**
21
+ * Resolves the browser-importable page module URL from processed page entry assets.
22
+ */
23
+ resolvePageModuleUrl(pagePackage: PagePackage | undefined, options: {
24
+ routerEnabled: boolean;
25
+ }): string | undefined;
26
+ /**
27
+ * Creates the `__ECO_PAGE_DATA__` script for router hydration.
28
+ *
29
+ * @remarks
30
+ * When `moduleUrl` is present, emits the v1 envelope via
31
+ * {@link serializePageDataManifestScript}. Otherwise emits legacy flat props
32
+ * for non-router shells.
33
+ */
34
+ buildRouterPageDataScript(pageProps: HtmlTemplateProps['pageProps'] | undefined, moduleUrl?: string): string;
35
+ /**
36
+ * Builds shared document html contributions for router-backed React pages rendered
37
+ * through a non-React HTML shell.
38
+ */
39
+ buildNonReactDocumentContributions(options: {
40
+ htmlTemplate: {
41
+ config?: EcoComponentConfig;
42
+ } | null | undefined;
43
+ pageProps: Record<string, unknown>;
44
+ pageModuleUrl?: string;
45
+ reactIntegrationName: string;
46
+ routerEnabled: boolean;
47
+ }): HtmlDocumentContribution[] | undefined;
48
+ /**
49
+ * Builds the browser-safe page-props object embedded into the final HTML.
50
+ *
51
+ * @remarks
52
+ * Narrower than the full server render input: only routing data, public page
53
+ * props, and explicitly allowed locals. Page module identity is threaded via
54
+ * `HtmlTemplateProps.pageModuleUrl`, not serialized page props.
55
+ */
56
+ buildSerializedPageProps(options: PagePayloadOptions): HtmlTemplateProps['pageProps'];
57
+ /**
58
+ * Extracts the declared subset of locals for client-side hydration.
59
+ *
60
+ * @remarks
61
+ * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
62
+ * request-scoped data. Only keys declared via `Page.requires` are serialized.
63
+ * On static pages, `locals` is a Proxy that throws `LocalsAccessError`; this
64
+ * method returns `undefined` instead of throwing.
65
+ */
66
+ getSerializableLocals(locals: RequestLocals | undefined, requiredLocals?: string | readonly string[]): RequestLocals | undefined;
67
+ }
68
+ export {};
@@ -0,0 +1,106 @@
1
+ import { LocalsAccessError } from '@ecopages/core/errors';
2
+ import { serializePageDataManifestScript, serializePageDataScript, } from './serialize-page-data-script.js';
3
+ import { isReactManagedComponent } from '../render/component-ownership.js';
4
+ /**
5
+ * Builds the serialized page payload React exposes to document shells and the browser.
6
+ *
7
+ * @remarks
8
+ * Keeps hydration payload shaping away from the renderer so orchestration stays
9
+ * focused on component composition instead of document serialization rules.
10
+ */
11
+ export class PagePayloadService {
12
+ /**
13
+ * Resolves the browser-importable page module URL from processed page entry assets.
14
+ */
15
+ resolvePageModuleUrl(pagePackage, options) {
16
+ if (!options.routerEnabled) {
17
+ return undefined;
18
+ }
19
+ const entryScripts = pagePackage?.pageBrowserGraph?.entryAssets.filter((asset) => asset.kind === 'script' && typeof asset.srcUrl === 'string') ?? [];
20
+ const bootstrapScript = entryScripts.find((asset) => asset.attributes?.['data-eco-page-bootstrap'] === 'react-router');
21
+ return bootstrapScript?.srcUrl ?? entryScripts[0]?.srcUrl;
22
+ }
23
+ /**
24
+ * Creates the `__ECO_PAGE_DATA__` script for router hydration.
25
+ *
26
+ * @remarks
27
+ * When `moduleUrl` is present, emits the v1 envelope via
28
+ * {@link serializePageDataManifestScript}. Otherwise emits legacy flat props
29
+ * for non-router shells.
30
+ */
31
+ buildRouterPageDataScript(pageProps, moduleUrl) {
32
+ const props = { ...(pageProps ?? {}) };
33
+ if (moduleUrl) {
34
+ return serializePageDataManifestScript({ moduleUrl, props });
35
+ }
36
+ return serializePageDataScript(props);
37
+ }
38
+ /**
39
+ * Builds shared document html contributions for router-backed React pages rendered
40
+ * through a non-React HTML shell.
41
+ */
42
+ buildNonReactDocumentContributions(options) {
43
+ if (isReactManagedComponent(options.htmlTemplate, options.reactIntegrationName) || !options.routerEnabled) {
44
+ return undefined;
45
+ }
46
+ return [
47
+ {
48
+ placement: 'head-append',
49
+ html: this.buildRouterPageDataScript(options.pageProps, options.pageModuleUrl),
50
+ },
51
+ ];
52
+ }
53
+ /**
54
+ * Builds the browser-safe page-props object embedded into the final HTML.
55
+ *
56
+ * @remarks
57
+ * Narrower than the full server render input: only routing data, public page
58
+ * props, and explicitly allowed locals. Page module identity is threaded via
59
+ * `HtmlTemplateProps.pageModuleUrl`, not serialized page props.
60
+ */
61
+ buildSerializedPageProps(options) {
62
+ return {
63
+ ...options.pageProps,
64
+ params: options.params,
65
+ query: options.query,
66
+ ...(options.safeLocals && { locals: options.safeLocals }),
67
+ };
68
+ }
69
+ /**
70
+ * Extracts the declared subset of locals for client-side hydration.
71
+ *
72
+ * @remarks
73
+ * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
74
+ * request-scoped data. Only keys declared via `Page.requires` are serialized.
75
+ * On static pages, `locals` is a Proxy that throws `LocalsAccessError`; this
76
+ * method returns `undefined` instead of throwing.
77
+ */
78
+ getSerializableLocals(locals, requiredLocals) {
79
+ try {
80
+ if (!locals) {
81
+ return undefined;
82
+ }
83
+ const requiredKeys = requiredLocals
84
+ ? Array.isArray(requiredLocals)
85
+ ? requiredLocals
86
+ : [requiredLocals]
87
+ : [];
88
+ if (requiredKeys.length === 0) {
89
+ return undefined;
90
+ }
91
+ const serializedLocals = Object.fromEntries(requiredKeys
92
+ .filter((key) => Object.prototype.hasOwnProperty.call(locals, key))
93
+ .map((key) => [key, locals[key]]));
94
+ if (Object.keys(serializedLocals).length > 0) {
95
+ return serializedLocals;
96
+ }
97
+ return undefined;
98
+ }
99
+ catch (error) {
100
+ if (error instanceof LocalsAccessError) {
101
+ return undefined;
102
+ }
103
+ throw error;
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,27 @@
1
+ import { type EcoPageDataDocumentPayload, type EcoPageDataProps } from './page-data-manifest.js';
2
+ export { ECO_PAGE_DATA_SCHEMA_VERSION, createEcoPageDataManifestV1, isEcoPageDataManifestV1, resolveEcoPageDataModuleUrl, resolveEcoPageDataProps, resolvePageDataDocumentPayload, type EcoPageDataDocumentPayload, type EcoPageDataManifestV1, type EcoPageDataProps, } from './page-data-manifest.js';
3
+ /**
4
+ * Escapes page data JSON for safe embedding in HTML script bodies.
5
+ */
6
+ export declare function escapePageDataJson(pageProps: EcoPageDataDocumentPayload | undefined): string;
7
+ /**
8
+ * Emits the canonical `__ECO_PAGE_DATA__` bootstrap script tag.
9
+ *
10
+ * @remarks
11
+ * Accepts a v1 envelope or legacy flat props. Router-enabled documents should
12
+ * use {@link serializePageDataManifestScript} so clients can discover the page
13
+ * module without parsing hydration JavaScript.
14
+ */
15
+ export declare function serializePageDataScript(pageProps: EcoPageDataDocumentPayload | undefined): string;
16
+ /**
17
+ * Emits a versioned page-data envelope for React router documents.
18
+ *
19
+ * @remarks
20
+ * Canonical HTML serializer for router-enabled pages. SPA commit paths that
21
+ * build a React element instead of an HTML string use
22
+ * {@link resolvePageDataDocumentPayload} with the same envelope shape.
23
+ */
24
+ export declare function serializePageDataManifestScript(input: {
25
+ moduleUrl: string;
26
+ props: EcoPageDataProps;
27
+ }): string;
@@ -0,0 +1,30 @@
1
+ import { createEcoPageDataManifestV1, } from './page-data-manifest.js';
2
+ export { ECO_PAGE_DATA_SCHEMA_VERSION, createEcoPageDataManifestV1, isEcoPageDataManifestV1, resolveEcoPageDataModuleUrl, resolveEcoPageDataProps, resolvePageDataDocumentPayload, } from './page-data-manifest.js';
3
+ /**
4
+ * Escapes page data JSON for safe embedding in HTML script bodies.
5
+ */
6
+ export function escapePageDataJson(pageProps) {
7
+ return JSON.stringify(pageProps ?? {}).replace(/</g, '\\u003c');
8
+ }
9
+ /**
10
+ * Emits the canonical `__ECO_PAGE_DATA__` bootstrap script tag.
11
+ *
12
+ * @remarks
13
+ * Accepts a v1 envelope or legacy flat props. Router-enabled documents should
14
+ * use {@link serializePageDataManifestScript} so clients can discover the page
15
+ * module without parsing hydration JavaScript.
16
+ */
17
+ export function serializePageDataScript(pageProps) {
18
+ return `<script id="__ECO_PAGE_DATA__" type="application/json">${escapePageDataJson(pageProps)}</script>`;
19
+ }
20
+ /**
21
+ * Emits a versioned page-data envelope for React router documents.
22
+ *
23
+ * @remarks
24
+ * Canonical HTML serializer for router-enabled pages. SPA commit paths that
25
+ * build a React element instead of an HTML string use
26
+ * {@link resolvePageDataDocumentPayload} with the same envelope shape.
27
+ */
28
+ export function serializePageDataManifestScript(input) {
29
+ return serializePageDataScript(createEcoPageDataManifestV1(input));
30
+ }