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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +179 -7
  2. package/package.json +53 -28
  3. package/src/app/client-only.js +15 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +31 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +23 -8
  9. package/src/bundling/bundle.js +120 -0
  10. package/src/bundling/discover-layout-runtime-modules.d.ts +32 -0
  11. package/src/bundling/discover-layout-runtime-modules.js +185 -0
  12. package/src/bundling/runtime-alias-map.d.ts +13 -0
  13. package/src/bundling/runtime-alias-map.js +113 -0
  14. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +25 -4
  15. package/src/bundling/runtime-bundle.js +258 -0
  16. package/src/bundling/runtime-interop-plugin.js +34 -0
  17. package/src/bundling/runtime-mode.d.ts +9 -0
  18. package/src/bundling/runtime-mode.js +11 -0
  19. package/src/bundling/runtime-modules.d.ts +29 -0
  20. package/src/bundling/runtime-modules.js +49 -0
  21. package/src/client-graph/ast-transform.d.ts +18 -0
  22. package/src/client-graph/ast-transform.js +426 -0
  23. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +23 -13
  24. package/src/client-graph/boundary-cache.js +182 -0
  25. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +4 -13
  26. package/src/client-graph/boundary-plugin.js +149 -0
  27. package/src/client-graph/component-config-traversal.js +77 -0
  28. package/src/client-graph/declared-modules.js +69 -0
  29. package/src/client-graph/module-classification.d.ts +3 -0
  30. package/src/client-graph/module-classification.js +43 -0
  31. package/src/{utils → client-graph}/reachability-analyzer.d.ts +4 -12
  32. package/src/client-graph/reachability-analyzer.js +515 -0
  33. package/src/client-graph/specifier-classification.d.ts +75 -0
  34. package/src/client-graph/specifier-classification.js +214 -0
  35. package/src/contracts/router-adapter.js +6 -0
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  37. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  38. package/src/hmr/hmr-scripts.js +44 -0
  39. package/src/hmr/hmr-strategy.d.ts +74 -0
  40. package/src/hmr/hmr-strategy.js +351 -0
  41. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  42. package/src/hmr/page-metadata-cache.js +44 -0
  43. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  44. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  45. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  46. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  47. package/src/hydration/bootstrap-imports.d.ts +25 -0
  48. package/src/hydration/bootstrap-imports.js +33 -0
  49. package/src/hydration/hydration-asset.d.ts +84 -0
  50. package/src/hydration/hydration-asset.js +227 -0
  51. package/src/hydration/hydration-scripts.d.ts +104 -0
  52. package/src/hydration/hydration-scripts.js +483 -0
  53. package/src/hydration/hydration-scripts.test.browser.js +199 -0
  54. package/src/hydration/page-data-manifest.d.ts +58 -0
  55. package/src/hydration/page-data-manifest.js +97 -0
  56. package/src/hydration/page-data-reader.d.ts +31 -0
  57. package/src/hydration/page-data-reader.js +77 -0
  58. package/src/hydration/page-payload.d.ts +67 -0
  59. package/src/hydration/page-payload.js +106 -0
  60. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  61. package/src/hydration/serialize-page-data-script.js +30 -0
  62. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +6 -6
  63. package/src/mdx/mdx-config-dependency.js +110 -0
  64. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  65. package/src/mdx/mdx-loader-plugin.js +8 -0
  66. package/src/page/page-module.d.ts +46 -0
  67. package/src/page/page-module.js +74 -0
  68. package/src/plugin/react.constants.js +1 -0
  69. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +9 -3
  70. package/src/plugin/react.plugin.js +241 -0
  71. package/src/plugin/react.types.d.ts +156 -0
  72. package/src/plugin/react.types.js +1 -0
  73. package/src/render/component-ownership.d.ts +49 -0
  74. package/src/render/component-ownership.js +46 -0
  75. package/src/render/component-ssr.d.ts +113 -0
  76. package/src/render/component-ssr.js +180 -0
  77. package/src/render/eco-embed.js +9 -0
  78. package/src/render/errors.d.ts +16 -0
  79. package/src/render/errors.js +23 -0
  80. package/src/render/html-boundary.js +59 -0
  81. package/src/render/layout-compose.d.ts +66 -0
  82. package/src/render/layout-compose.js +134 -0
  83. package/src/render/react-renderer.d.ts +139 -0
  84. package/src/render/react-renderer.js +450 -0
  85. package/src/render/react-runtime.d.ts +13 -0
  86. package/src/render/react-runtime.js +26 -0
  87. package/src/render/unified-layout-composition.d.ts +53 -0
  88. package/src/render/unified-layout-composition.js +78 -0
  89. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  90. package/src/eco-embed.js +0 -11
  91. package/src/react-hmr-strategy.d.ts +0 -230
  92. package/src/react-hmr-strategy.js +0 -657
  93. package/src/react-renderer.d.ts +0 -233
  94. package/src/react-renderer.js +0 -622
  95. package/src/react.constants.js +0 -4
  96. package/src/react.plugin.js +0 -209
  97. package/src/react.types.d.ts +0 -88
  98. package/src/react.types.js +0 -0
  99. package/src/router-adapter.js +0 -0
  100. package/src/services/pages-index.d.ts +0 -64
  101. package/src/services/pages-index.js +0 -73
  102. package/src/services/react-bundle.service.js +0 -86
  103. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  104. package/src/services/react-hydration-asset.service.d.ts +0 -84
  105. package/src/services/react-hydration-asset.service.js +0 -217
  106. package/src/services/react-mdx-config-dependency.service.js +0 -122
  107. package/src/services/react-page-module.service.d.ts +0 -88
  108. package/src/services/react-page-module.service.js +0 -166
  109. package/src/services/react-page-payload.service.d.ts +0 -46
  110. package/src/services/react-page-payload.service.js +0 -67
  111. package/src/services/react-runtime-bundle.service.js +0 -192
  112. package/src/utils/client-graph-boundary-cache.js +0 -116
  113. package/src/utils/client-graph-boundary-plugin.js +0 -552
  114. package/src/utils/client-only.js +0 -19
  115. package/src/utils/component-config-traversal.js +0 -54
  116. package/src/utils/declared-modules.js +0 -47
  117. package/src/utils/dynamic.js +0 -12
  118. package/src/utils/dynamic.test.browser.js +0 -33
  119. package/src/utils/hmr-scripts.js +0 -31
  120. package/src/utils/html-boundary.js +0 -55
  121. package/src/utils/hydration-scripts.d.ts +0 -92
  122. package/src/utils/hydration-scripts.js +0 -358
  123. package/src/utils/hydration-scripts.test.browser.js +0 -198
  124. package/src/utils/reachability-analyzer.js +0 -339
  125. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  126. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  127. package/src/utils/react-mdx-loader-plugin.js +0 -45
  128. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  129. package/src/utils/react-runtime-alias-map.js +0 -90
  130. /package/src/{utils → app}/client-only.d.ts +0 -0
  131. /package/src/{utils → app}/dynamic.d.ts +0 -0
  132. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  133. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  134. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  135. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  136. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  137. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  138. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  139. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  140. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  141. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  142. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,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,31 @@
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;
18
+ /**
19
+ * Inlined browser bootstrap for generated hydration scripts.
20
+ *
21
+ * @remarks
22
+ * Hydration and HMR entry modules are evaluated as native browser ESM. Bare
23
+ * package imports such as `@ecopages/react/page-data-reader` are not resolvable
24
+ * there, so the reader algorithm is embedded. Keep this string aligned with
25
+ * {@link readPageDataDocument} / {@link getPageDataFromDocument}.
26
+ */
27
+ export declare function getDevPageDataReaderBootstrapSource(): string;
28
+ /**
29
+ * Minified equivalent of {@link getDevPageDataReaderBootstrapSource}.
30
+ */
31
+ export declare function getProdPageDataReaderBootstrapSource(): string;
@@ -0,0 +1,77 @@
1
+ import { ECO_PAGE_DATA_SCHEMA_VERSION, 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
+ }
32
+ /**
33
+ * Inlined browser bootstrap for generated hydration scripts.
34
+ *
35
+ * @remarks
36
+ * Hydration and HMR entry modules are evaluated as native browser ESM. Bare
37
+ * package imports such as `@ecopages/react/page-data-reader` are not resolvable
38
+ * there, so the reader algorithm is embedded. Keep this string aligned with
39
+ * {@link readPageDataDocument} / {@link getPageDataFromDocument}.
40
+ */
41
+ export function getDevPageDataReaderBootstrapSource() {
42
+ return `const readPageDataDocument = () => {
43
+ const el = document.getElementById("__ECO_PAGE_DATA__");
44
+ if (!el?.textContent) {
45
+ return { props: {} };
46
+ }
47
+ try {
48
+ const parsed = JSON.parse(el.textContent);
49
+ if (
50
+ parsed &&
51
+ parsed.schemaVersion === ${ECO_PAGE_DATA_SCHEMA_VERSION} &&
52
+ parsed.navigationOwner === "react-router" &&
53
+ typeof parsed.moduleUrl === "string" &&
54
+ parsed.props &&
55
+ typeof parsed.props === "object" &&
56
+ !Array.isArray(parsed.props)
57
+ ) {
58
+ return { moduleUrl: parsed.moduleUrl, props: parsed.props };
59
+ }
60
+ if (parsed && typeof parsed === "object" && typeof parsed.schemaVersion === "number") {
61
+ return { props: {} };
62
+ }
63
+ return {
64
+ props: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {},
65
+ };
66
+ } catch {
67
+ return { props: {} };
68
+ }
69
+ };
70
+ const getPageData = () => readPageDataDocument().props;`;
71
+ }
72
+ /**
73
+ * Minified equivalent of {@link getDevPageDataReaderBootstrapSource}.
74
+ */
75
+ export function getProdPageDataReaderBootstrapSource() {
76
+ return `const rd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(!e?.textContent)return{props:{}};try{const p=JSON.parse(e.textContent);if(p&&p.schemaVersion===${ECO_PAGE_DATA_SCHEMA_VERSION}&&p.navigationOwner==="react-router"&&typeof p.moduleUrl==="string"&&p.props&&typeof p.props==="object"&&!Array.isArray(p.props))return{moduleUrl:p.moduleUrl,props:p.props};if(p&&typeof p==="object"&&typeof p.schemaVersion==="number")return{props:{}};return{props:p&&typeof p==="object"&&!Array.isArray(p)?p:{}}}catch{return{props:{}}}};const gd=()=>rd().props;`;
77
+ }
@@ -0,0 +1,67 @@
1
+ import type { EcoComponentConfig, HtmlTemplateProps, IntegrationRendererRenderOptions, RequestLocals } from '@ecopages/core';
2
+ import type { HtmlDocumentContribution } from '@ecopages/core/route-renderer/orchestration/integration-renderer';
3
+ import type { ReactNode } from 'react';
4
+ type PagePayloadOptions = {
5
+ pageProps?: HtmlTemplateProps['pageProps'];
6
+ params: IntegrationRendererRenderOptions<ReactNode>['params'];
7
+ query: IntegrationRendererRenderOptions<ReactNode>['query'];
8
+ safeLocals?: RequestLocals;
9
+ };
10
+ type PagePackage = IntegrationRendererRenderOptions<ReactNode>['pagePackage'];
11
+ /**
12
+ * Builds the serialized page payload React exposes to document shells and the browser.
13
+ *
14
+ * @remarks
15
+ * Keeps hydration payload shaping away from the renderer so orchestration stays
16
+ * focused on component composition instead of document serialization rules.
17
+ */
18
+ export declare class PagePayloadService {
19
+ /**
20
+ * Resolves the browser-importable page module URL from processed page entry assets.
21
+ */
22
+ resolvePageModuleUrl(pagePackage: PagePackage | undefined, options: {
23
+ routerEnabled: boolean;
24
+ }): string | undefined;
25
+ /**
26
+ * Creates the `__ECO_PAGE_DATA__` script for router hydration.
27
+ *
28
+ * @remarks
29
+ * When `moduleUrl` is present, emits the v1 envelope via
30
+ * {@link serializePageDataManifestScript}. Otherwise emits legacy flat props
31
+ * for non-router shells.
32
+ */
33
+ buildRouterPageDataScript(pageProps: HtmlTemplateProps['pageProps'] | undefined, moduleUrl?: string): string;
34
+ /**
35
+ * Builds shared document html contributions for router-backed React pages rendered
36
+ * through a non-React HTML shell.
37
+ */
38
+ buildNonReactDocumentContributions(options: {
39
+ htmlTemplate: {
40
+ config?: EcoComponentConfig;
41
+ } | null | undefined;
42
+ pageProps: Record<string, unknown>;
43
+ pageModuleUrl?: string;
44
+ reactIntegrationName: string;
45
+ routerEnabled: boolean;
46
+ }): HtmlDocumentContribution[] | undefined;
47
+ /**
48
+ * Builds the browser-safe page-props object embedded into the final HTML.
49
+ *
50
+ * @remarks
51
+ * Narrower than the full server render input: only routing data, public page
52
+ * props, and explicitly allowed locals. Page module identity is threaded via
53
+ * `HtmlTemplateProps.pageModuleUrl`, not serialized page props.
54
+ */
55
+ buildSerializedPageProps(options: PagePayloadOptions): HtmlTemplateProps['pageProps'];
56
+ /**
57
+ * Extracts the declared subset of locals for client-side hydration.
58
+ *
59
+ * @remarks
60
+ * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
61
+ * request-scoped data. Only keys declared via `Page.requires` are serialized.
62
+ * On static pages, `locals` is a Proxy that throws `LocalsAccessError`; this
63
+ * method returns `undefined` instead of throwing.
64
+ */
65
+ getSerializableLocals(locals: RequestLocals | undefined, requiredLocals?: string | readonly string[]): RequestLocals | undefined;
66
+ }
67
+ 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
+ }
@@ -1,10 +1,10 @@
1
- import type { EcoComponent, EcoComponentConfig } from '@ecopages/core';
1
+ import { type EcoComponent, type EcoComponentConfig } from '@ecopages/core';
2
2
  import { type AssetProcessingService, type ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
3
- import type { ReactPageModuleService } from './react-page-module.service.js';
3
+ import type { PageModuleService } from '../page/page-module.js';
4
4
  type MdxConfigDependencyProcessor = (components: Partial<EcoComponent>[]) => Promise<ProcessedAsset[]>;
5
- export interface ReactMdxConfigDependencyServiceConfig {
5
+ export interface MdxConfigDependencyServiceConfig {
6
6
  integrationName: string;
7
- pageModuleService: Pick<ReactPageModuleService, 'ensureConfigFileMetadata'>;
7
+ pageModuleService: Pick<PageModuleService, 'ensureConfigFileMetadata'>;
8
8
  assetProcessingService?: Pick<AssetProcessingService, 'processDependencies'>;
9
9
  }
10
10
  /**
@@ -15,9 +15,9 @@ export interface ReactMdxConfigDependencyServiceConfig {
15
15
  * component configs so the shared dependency pipeline can process them without
16
16
  * growing more MDX-specific logic inside the renderer.
17
17
  */
18
- export declare class ReactMdxConfigDependencyService {
18
+ export declare class MdxConfigDependencyService {
19
19
  private readonly config;
20
- constructor(config: ReactMdxConfigDependencyServiceConfig);
20
+ constructor(config: MdxConfigDependencyServiceConfig);
21
21
  /**
22
22
  * Processes MDX-owned config dependencies and eagerly emits any SSR-marked lazy scripts.
23
23
  */
@@ -0,0 +1,110 @@
1
+ import path from 'node:path';
2
+ import { getComponentIdentity, } from '@ecopages/core';
3
+ import { attachEcoFileMetadataToConfig } from '@ecopages/core/route-renderer/page-loading/file-scoped-dependency-components';
4
+ import { AssetFactory, } from '@ecopages/core/services/asset-processing-service';
5
+ import { collectFromConfigForest, getComponentConfigs } from '../client-graph/component-config-traversal.js';
6
+ /**
7
+ * Resolves MDX-owned config dependencies that live outside the normal React component tree.
8
+ *
9
+ * React MDX pages can declare dependencies on the page config itself or on a
10
+ * resolved layout config. Those roots need to be materialized as synthetic
11
+ * component configs so the shared dependency pipeline can process them without
12
+ * growing more MDX-specific logic inside the renderer.
13
+ */
14
+ export class MdxConfigDependencyService {
15
+ config;
16
+ constructor(config) {
17
+ this.config = config;
18
+ }
19
+ /**
20
+ * Processes MDX-owned config dependencies and eagerly emits any SSR-marked lazy scripts.
21
+ */
22
+ async processMdxConfigDependencies(options) {
23
+ const components = this.createOwnedConfigComponents(options.pagePath, options.config);
24
+ if (components.length === 0) {
25
+ return [];
26
+ }
27
+ const processedDependencies = await options.processComponentDependencies(components);
28
+ const eagerSsrLazyDependencies = await this.processDeclaredSsrLazyDependencies(components, options.pagePath);
29
+ return [...processedDependencies, ...eagerSsrLazyDependencies];
30
+ }
31
+ createOwnedConfigComponents(pagePath, config) {
32
+ const components = [];
33
+ for (const layout of config?.layouts ?? []) {
34
+ if (layout?.config?.dependencies) {
35
+ const layoutConfig = this.config.pageModuleService.ensureConfigFileMetadata(layout.config, pagePath);
36
+ components.push({ config: layoutConfig });
37
+ }
38
+ }
39
+ if (config?.dependencies) {
40
+ components.push({
41
+ config: attachEcoFileMetadataToConfig(config, pagePath, this.config.integrationName),
42
+ });
43
+ }
44
+ return components;
45
+ }
46
+ async processDeclaredSsrLazyDependencies(components, pagePath) {
47
+ if (!this.config.assetProcessingService?.processDependencies) {
48
+ return [];
49
+ }
50
+ const dependencies = this.collectDeclaredSsrLazyDependencies(components);
51
+ if (dependencies.length === 0) {
52
+ return [];
53
+ }
54
+ return this.config.assetProcessingService.processDependencies(dependencies, `${this.config.integrationName}-mdx-ssr-lazy:${pagePath}`);
55
+ }
56
+ /**
57
+ * Collects `lazy` script dependencies that also opt into SSR from an MDX config graph.
58
+ */
59
+ collectDeclaredSsrLazyDependencies(components) {
60
+ const dependencies = [];
61
+ const seenKeys = new Set();
62
+ const normalizeAttributes = (attributes) => ({
63
+ type: 'module',
64
+ defer: '',
65
+ ...(attributes ?? {}),
66
+ });
67
+ collectFromConfigForest(getComponentConfigs(components), (config) => {
68
+ const componentFile = getComponentIdentity(config)?.file;
69
+ if (!componentFile) {
70
+ return [];
71
+ }
72
+ const componentDir = path.dirname(componentFile);
73
+ for (const script of config.dependencies?.scripts ?? []) {
74
+ if (typeof script === 'string' || !script.lazy || script.ssr !== true) {
75
+ continue;
76
+ }
77
+ const attributes = normalizeAttributes(script.attributes);
78
+ if (script.content) {
79
+ const key = `content:${script.content}:${JSON.stringify(attributes)}`;
80
+ if (seenKeys.has(key)) {
81
+ continue;
82
+ }
83
+ seenKeys.add(key);
84
+ dependencies.push(AssetFactory.createContentScript({
85
+ position: 'head',
86
+ content: script.content,
87
+ attributes,
88
+ }));
89
+ continue;
90
+ }
91
+ if (!script.src) {
92
+ continue;
93
+ }
94
+ const resolvedPath = path.resolve(componentDir, script.src);
95
+ const key = `file:${resolvedPath}:${JSON.stringify(attributes)}`;
96
+ if (seenKeys.has(key)) {
97
+ continue;
98
+ }
99
+ seenKeys.add(key);
100
+ dependencies.push(AssetFactory.createFileScript({
101
+ filepath: resolvedPath,
102
+ position: 'head',
103
+ attributes,
104
+ }));
105
+ }
106
+ return [];
107
+ });
108
+ return dependencies;
109
+ }
110
+ }
@@ -0,0 +1,2 @@
1
+ import type { CompileOptions } from '@mdx-js/mdx';
2
+ export declare function createReactMdxLoaderPlugin(compilerOptions?: CompileOptions): import("@ecopages/core/build/build-types").EcoBuildPlugin;
@@ -0,0 +1,8 @@
1
+ import { createMdxLoaderPlugin as createMdxLoaderPluginCore } from '@ecopages/mdx/core';
2
+ export function createReactMdxLoaderPlugin(compilerOptions) {
3
+ return createMdxLoaderPluginCore({
4
+ name: 'react-mdx-loader',
5
+ compilerOptions,
6
+ defaultMdExtensions: [],
7
+ });
8
+ }