@ecopages/react 0.2.0-beta.4 → 0.2.0-beta.41

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 +175 -7
  2. package/package.json +54 -29
  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 +191 -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} +30 -5
  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 +223 -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 +152 -0
  72. package/src/plugin/react.types.js +1 -0
  73. package/src/render/component-ownership.d.ts +49 -0
  74. package/src/render/component-ownership.js +46 -0
  75. package/src/render/component-ssr.d.ts +113 -0
  76. package/src/render/component-ssr.js +180 -0
  77. package/src/render/eco-embed.js +9 -0
  78. package/src/render/errors.d.ts +16 -0
  79. package/src/render/errors.js +23 -0
  80. package/src/render/html-boundary.js +59 -0
  81. package/src/render/layout-compose.d.ts +66 -0
  82. package/src/render/layout-compose.js +134 -0
  83. package/src/render/react-renderer.d.ts +138 -0
  84. package/src/render/react-renderer.js +448 -0
  85. package/src/render/react-runtime.d.ts +13 -0
  86. package/src/render/react-runtime.js +26 -0
  87. package/src/render/unified-layout-composition.d.ts +53 -0
  88. package/src/render/unified-layout-composition.js +78 -0
  89. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  90. package/src/eco-embed.js +0 -11
  91. package/src/react-hmr-strategy.d.ts +0 -230
  92. package/src/react-hmr-strategy.js +0 -657
  93. package/src/react-renderer.d.ts +0 -233
  94. package/src/react-renderer.js +0 -622
  95. package/src/react.constants.js +0 -4
  96. package/src/react.plugin.js +0 -205
  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 -186
  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,191 @@
1
+ /**
2
+ * Discovers npm packages reachable from persisted `eco.layout()` client graphs.
3
+ *
4
+ * @module
5
+ */
6
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { isBarePackageImportSpecifier, resolveProjectModulePath, } from '@ecopages/core/plugins/tsconfig-import-resolver';
9
+ import { analyzeReachability } from '../client-graph/reachability-analyzer.js';
10
+ import { REACT_RUNTIME_SPECIFIERS } from './runtime-alias-map.js';
11
+ const MODULE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mts', '.mjs'];
12
+ const AUTO_RUNTIME_EXCLUDED_SPECIFIERS = new Set([
13
+ ...REACT_RUNTIME_SPECIFIERS,
14
+ 'react-dom/client',
15
+ 'use-sync-external-store/shim',
16
+ 'use-sync-external-store/shim/index.js',
17
+ 'use-sync-external-store/shim/with-selector',
18
+ 'use-sync-external-store/shim/with-selector.js',
19
+ ]);
20
+ const AUTO_RUNTIME_EXCLUDED_PACKAGE_PREFIXES = ['@ecopages/', '@techn.es/'];
21
+ const PROVIDER_MODULE_PATH_PATTERN = /(?:^|[/\\])(?:[^/\\]*provider[^/\\]*|[^/\\]*context[^/\\]*)\.(?:tsx?|jsx?|mts?|mjs)$/i;
22
+ const PROVIDER_MODULE_SOURCE_PATTERN = /\b(?:QueryClientProvider|(?:\w+Provider)|createContext|Context\.Provider)\b/;
23
+ function isServerModulePath(filePath) {
24
+ return /\.server\.(?:tsx?|jsx?|mts?|mjs|cjs)$/.test(filePath);
25
+ }
26
+ function isEcoLayoutSource(source) {
27
+ return /\beco\.layout(?:<[^>]*>)?\s*\(/.test(source);
28
+ }
29
+ /**
30
+ * Returns true when a layout opts into runtime-provider auto-vendoring discovery.
31
+ */
32
+ export function isRuntimeProviderLayoutSource(source) {
33
+ return isEcoLayoutSource(source) && /\bruntimeProvider\s*:\s*true\b/.test(source);
34
+ }
35
+ /**
36
+ * Returns true when a module looks like it mounts shared client runtime state
37
+ * (React context providers, query clients, etc.).
38
+ */
39
+ export function isProviderRuntimeModulePath(filePath, source) {
40
+ if (PROVIDER_MODULE_PATH_PATTERN.test(filePath)) {
41
+ return true;
42
+ }
43
+ return PROVIDER_MODULE_SOURCE_PATTERN.test(source);
44
+ }
45
+ /**
46
+ * Normalizes import specifiers to the package entry used for browser vendors.
47
+ */
48
+ export function normalizeRuntimePackageSpecifier(specifier) {
49
+ if (specifier.startsWith('@')) {
50
+ const parts = specifier.split('/');
51
+ if (parts.length >= 2) {
52
+ return `${parts[0]}/${parts[1]}`;
53
+ }
54
+ return specifier;
55
+ }
56
+ return specifier.split('/')[0] ?? specifier;
57
+ }
58
+ function isAutoRuntimeExcludedPackage(packageRoot) {
59
+ if (AUTO_RUNTIME_EXCLUDED_PACKAGE_PREFIXES.some((prefix) => packageRoot.startsWith(prefix))) {
60
+ return true;
61
+ }
62
+ return packageRoot.endsWith('-devtools');
63
+ }
64
+ function shouldExcludeAutoRuntimeSpecifier(specifier, options) {
65
+ if (AUTO_RUNTIME_EXCLUDED_SPECIFIERS.has(specifier)) {
66
+ return true;
67
+ }
68
+ if (options.routerImportPath && specifier === options.routerImportPath) {
69
+ return true;
70
+ }
71
+ return isAutoRuntimeExcludedPackage(normalizeRuntimePackageSpecifier(specifier));
72
+ }
73
+ function collectLayoutEntryFiles(searchDir, extensions, files) {
74
+ if (!existsSync(searchDir)) {
75
+ return;
76
+ }
77
+ for (const entry of readdirSync(searchDir, { withFileTypes: true })) {
78
+ const entryPath = path.join(searchDir, entry.name);
79
+ if (entry.isDirectory()) {
80
+ collectLayoutEntryFiles(entryPath, extensions, files);
81
+ continue;
82
+ }
83
+ if (!entry.isFile()) {
84
+ continue;
85
+ }
86
+ if (!extensions.some((extension) => entry.name.endsWith(extension))) {
87
+ continue;
88
+ }
89
+ try {
90
+ const source = readFileSync(entryPath, 'utf8');
91
+ if (!isEcoLayoutSource(source)) {
92
+ continue;
93
+ }
94
+ files.all.push(entryPath);
95
+ if (isRuntimeProviderLayoutSource(source)) {
96
+ files.runtimeProvider.push(entryPath);
97
+ }
98
+ }
99
+ catch {
100
+ continue;
101
+ }
102
+ }
103
+ }
104
+ function resolveLayoutDiscoveryPlan(layoutEntries) {
105
+ if (layoutEntries.runtimeProvider.length > 0) {
106
+ return {
107
+ entryFiles: layoutEntries.runtimeProvider,
108
+ mode: 'runtime-provider-layouts',
109
+ collectAllReachableNpm: true,
110
+ };
111
+ }
112
+ return {
113
+ entryFiles: layoutEntries.all,
114
+ mode: 'provider-scoped-fallback',
115
+ collectAllReachableNpm: false,
116
+ };
117
+ }
118
+ function collectReachableNpmSpecifiersFromFile(filePath, options) {
119
+ if (isServerModulePath(filePath)) {
120
+ return;
121
+ }
122
+ if (options.visitedFiles.has(filePath)) {
123
+ return;
124
+ }
125
+ options.visitedFiles.add(filePath);
126
+ let source;
127
+ try {
128
+ source = readFileSync(filePath, 'utf8');
129
+ }
130
+ catch {
131
+ return;
132
+ }
133
+ const reachability = analyzeReachability(source, filePath);
134
+ if (!reachability.analyzed) {
135
+ return;
136
+ }
137
+ const collectNpmFromModule = options.collectAllReachableNpm || isProviderRuntimeModulePath(filePath, source);
138
+ for (const specifier of reachability.reachableImports.keys()) {
139
+ if (options.projectRoot) {
140
+ const resolvedLocalModule = resolveProjectModulePath(options.projectRoot, filePath, specifier);
141
+ if (resolvedLocalModule) {
142
+ options.queue.push(resolvedLocalModule);
143
+ continue;
144
+ }
145
+ }
146
+ if (!collectNpmFromModule) {
147
+ continue;
148
+ }
149
+ if (!isBarePackageImportSpecifier(specifier, options.projectRoot)) {
150
+ continue;
151
+ }
152
+ if (shouldExcludeAutoRuntimeSpecifier(specifier, options)) {
153
+ continue;
154
+ }
155
+ options.discovered.add(normalizeRuntimePackageSpecifier(specifier));
156
+ }
157
+ }
158
+ /**
159
+ * Finds npm packages imported from persisted layout client graphs under the given directories.
160
+ */
161
+ export function discoverLayoutRuntimeModuleSpecifiers(options) {
162
+ const extensions = options.extensions ?? MODULE_EXTENSIONS;
163
+ const layoutEntries = { all: [], runtimeProvider: [] };
164
+ for (const searchDir of options.searchDirs) {
165
+ collectLayoutEntryFiles(searchDir, extensions, layoutEntries);
166
+ }
167
+ const plan = resolveLayoutDiscoveryPlan(layoutEntries);
168
+ const discovered = new Set();
169
+ for (const entryFile of plan.entryFiles) {
170
+ const visitedFiles = new Set();
171
+ const queue = [entryFile];
172
+ while (queue.length > 0) {
173
+ const filePath = queue.shift();
174
+ if (!filePath) {
175
+ continue;
176
+ }
177
+ collectReachableNpmSpecifiersFromFile(filePath, {
178
+ projectRoot: options.projectRoot,
179
+ routerImportPath: options.routerImportPath,
180
+ collectAllReachableNpm: plan.collectAllReachableNpm,
181
+ visitedFiles,
182
+ queue,
183
+ discovered,
184
+ });
185
+ }
186
+ }
187
+ return {
188
+ specifiers: [...discovered].sort(),
189
+ mode: plan.mode,
190
+ };
191
+ }
@@ -0,0 +1,13 @@
1
+ import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
2
+ import type { ReactRuntimeImports } from './runtime-bundle.js';
3
+ import type { ResolvedReactPluginRuntimeModule } from './runtime-modules.js';
4
+ import { type BrowserRuntimeAssetDeclaration, type BrowserRuntimeManifest } from '@ecopages/core/build/browser-runtime-manifest';
5
+ export type BuildReactRuntimeManifestOptions = {
6
+ routerImportPath?: string;
7
+ };
8
+ export declare const REACT_RUNTIME_SPECIFIERS: readonly ["react", "react-dom", "react/jsx-runtime", "react/jsx-dev-runtime", "react-dom/client"];
9
+ export declare function buildReactRuntimeAliasMap(runtimeImports: ReactRuntimeImports): Record<string, string>;
10
+ export declare function buildConfiguredRuntimeModuleManifestEntries(modules: readonly ResolvedReactPluginRuntimeModule[], getPublicPath: (outputName: string) => string): BrowserRuntimeAssetDeclaration[];
11
+ export declare function buildReactRuntimeManifest(runtimeImports: ReactRuntimeImports, configuredRuntimeModules?: readonly ResolvedReactPluginRuntimeModule[], getConfiguredRuntimeModulePublicPath?: (outputName: string) => string, options?: BuildReactRuntimeManifestOptions): BrowserRuntimeManifest;
12
+ export declare function getReactRuntimeExternalSpecifiers(): string[];
13
+ export declare function getReactClientGraphAllowSpecifiers(runtimeSpecifiers: Iterable<string>, routerAdapter?: ReactRouterAdapter): string[];
@@ -0,0 +1,113 @@
1
+ import { createBrowserRuntimeManifest, getBrowserRuntimeSpecifierMap, } from '@ecopages/core/build/browser-runtime-manifest';
2
+ import { LAYOUT_COMPOSE_PACKAGE } from './bootstrap-package-paths.js';
3
+ export const REACT_RUNTIME_SPECIFIERS = [
4
+ 'react',
5
+ 'react-dom',
6
+ 'react/jsx-runtime',
7
+ 'react/jsx-dev-runtime',
8
+ 'react-dom/client',
9
+ ];
10
+ export function buildReactRuntimeAliasMap(runtimeImports) {
11
+ return Object.fromEntries(getBrowserRuntimeSpecifierMap(buildReactRuntimeManifest(runtimeImports)));
12
+ }
13
+ export function buildConfiguredRuntimeModuleManifestEntries(modules, getPublicPath) {
14
+ return modules.map((module) => ({
15
+ specifier: module.specifier,
16
+ owner: '@ecopages/react',
17
+ importPath: module.specifier,
18
+ publicPath: getPublicPath(module.outputName),
19
+ externals: [...getReactRuntimeExternalSpecifiers(), ...module.externals],
20
+ }));
21
+ }
22
+ export function buildReactRuntimeManifest(runtimeImports, configuredRuntimeModules = [], getConfiguredRuntimeModulePublicPath = () => '', options) {
23
+ const frameworkDeclarations = [
24
+ {
25
+ specifier: LAYOUT_COMPOSE_PACKAGE,
26
+ owner: '@ecopages/react',
27
+ importPath: LAYOUT_COMPOSE_PACKAGE,
28
+ publicPath: runtimeImports.layoutCompose,
29
+ },
30
+ ];
31
+ if (options?.routerImportPath && runtimeImports.router) {
32
+ frameworkDeclarations.push({
33
+ specifier: options.routerImportPath,
34
+ owner: '@ecopages/react-router',
35
+ importPath: options.routerImportPath,
36
+ publicPath: runtimeImports.router,
37
+ }, {
38
+ specifier: '@ecopages/react-router',
39
+ owner: '@ecopages/react-router',
40
+ importPath: options.routerImportPath,
41
+ publicPath: runtimeImports.router,
42
+ });
43
+ }
44
+ return createBrowserRuntimeManifest([
45
+ {
46
+ specifier: 'react',
47
+ owner: '@ecopages/react',
48
+ importPath: 'react',
49
+ publicPath: runtimeImports.react,
50
+ },
51
+ {
52
+ specifier: 'react/jsx-runtime',
53
+ owner: '@ecopages/react',
54
+ importPath: 'react/jsx-runtime',
55
+ publicPath: runtimeImports.reactJsxRuntime,
56
+ },
57
+ {
58
+ specifier: 'react/jsx-dev-runtime',
59
+ owner: '@ecopages/react',
60
+ importPath: 'react/jsx-dev-runtime',
61
+ publicPath: runtimeImports.reactJsxDevRuntime,
62
+ },
63
+ {
64
+ specifier: 'react-dom',
65
+ owner: '@ecopages/react',
66
+ importPath: 'react-dom',
67
+ publicPath: runtimeImports.reactDom,
68
+ },
69
+ {
70
+ specifier: 'react-dom/client',
71
+ owner: '@ecopages/react',
72
+ importPath: 'react-dom/client',
73
+ publicPath: runtimeImports.reactDomClient,
74
+ },
75
+ {
76
+ specifier: 'use-sync-external-store/shim',
77
+ owner: '@ecopages/react',
78
+ importPath: 'use-sync-external-store/shim',
79
+ publicPath: runtimeImports.react,
80
+ },
81
+ {
82
+ specifier: 'use-sync-external-store/shim/index.js',
83
+ owner: '@ecopages/react',
84
+ importPath: 'use-sync-external-store/shim/index.js',
85
+ publicPath: runtimeImports.react,
86
+ },
87
+ {
88
+ specifier: 'use-sync-external-store/shim/with-selector',
89
+ owner: '@ecopages/react',
90
+ importPath: 'use-sync-external-store/shim/with-selector',
91
+ publicPath: runtimeImports.useSyncExternalStoreWithSelector,
92
+ },
93
+ {
94
+ specifier: 'use-sync-external-store/shim/with-selector.js',
95
+ owner: '@ecopages/react',
96
+ importPath: 'use-sync-external-store/shim/with-selector.js',
97
+ publicPath: runtimeImports.useSyncExternalStoreWithSelector,
98
+ },
99
+ ...frameworkDeclarations,
100
+ ...buildConfiguredRuntimeModuleManifestEntries(configuredRuntimeModules, getConfiguredRuntimeModulePublicPath),
101
+ ]);
102
+ }
103
+ export function getReactRuntimeExternalSpecifiers() {
104
+ return [...REACT_RUNTIME_SPECIFIERS];
105
+ }
106
+ export function getReactClientGraphAllowSpecifiers(runtimeSpecifiers, routerAdapter) {
107
+ return [
108
+ '@ecopages/core',
109
+ ...REACT_RUNTIME_SPECIFIERS,
110
+ ...(routerAdapter ? [routerAdapter.bundle.importPath] : []),
111
+ ...Array.from(runtimeSpecifiers),
112
+ ];
113
+ }
@@ -8,7 +8,8 @@
8
8
  */
9
9
  import type { EcoBuildPlugin } from '@ecopages/core/plugins/integration-plugin';
10
10
  import { type AssetDefinition } from '@ecopages/core/services/asset-processing-service';
11
- import type { ReactRouterAdapter } from '../router-adapter.js';
11
+ import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
12
+ import type { ResolvedReactPluginRuntimeModule } from './runtime-modules.js';
12
13
  import { type BrowserRuntimeManifest } from '@ecopages/core/build/browser-runtime-manifest';
13
14
  export type ReactRuntimeImports = {
14
15
  react: string;
@@ -17,29 +18,53 @@ export type ReactRuntimeImports = {
17
18
  reactJsxDevRuntime: string;
18
19
  reactDom: string;
19
20
  useSyncExternalStoreWithSelector: string;
21
+ pageLayoutNormalization: string;
22
+ layoutCompose: string;
20
23
  router?: string;
21
24
  };
22
- export interface ReactRuntimeBundleServiceConfig {
25
+ export interface RuntimeBundleServiceConfig {
23
26
  routerAdapter?: ReactRouterAdapter;
27
+ runtimeModules?: ResolvedReactPluginRuntimeModule[];
24
28
  rootDir?: string;
29
+ workDir?: string;
25
30
  }
26
31
  type RuntimeMode = 'development' | 'production';
27
- export declare class ReactRuntimeBundleService {
32
+ export declare class RuntimeBundleService {
28
33
  private readonly config;
29
- constructor(config: ReactRuntimeBundleServiceConfig);
34
+ constructor(config: RuntimeBundleServiceConfig);
30
35
  setRootDir(rootDir: string | undefined): void;
36
+ setWorkDir(workDir: string | undefined): void;
37
+ setRuntimeModules(runtimeModules: ResolvedReactPluginRuntimeModule[]): void;
31
38
  private get isDevelopment();
32
39
  private getCurrentRuntimeMode;
33
40
  private createRuntimeDefines;
34
41
  private getReactVendorFileName;
35
42
  private getReactDomVendorFileName;
36
43
  private getRouterVendorFileName;
44
+ private getConfiguredRuntimeModuleFileName;
45
+ private getConfiguredRuntimeModules;
46
+ getConfiguredRuntimeModuleSpecifiers(): string[];
47
+ private getRuntimeModuleBundleExternals;
37
48
  private getUseSyncExternalStoreWithSelectorVendorFileName;
49
+ private getPageLayoutNormalizationVendorFileName;
50
+ private getLayoutComposeVendorFileName;
38
51
  private createReactVendorImportRewritePlugin;
39
52
  getRuntimeImports(mode?: RuntimeMode): ReactRuntimeImports;
40
53
  getRuntimeAliasMap(mode?: RuntimeMode): Record<string, string>;
41
54
  getRuntimeManifest(mode?: RuntimeMode): BrowserRuntimeManifest;
42
- getDependencies(): AssetDefinition[];
55
+ getDependencies(options?: {
56
+ modes?: RuntimeMode[];
57
+ }): AssetDefinition[];
58
+ /**
59
+ * Declares the MDX-only page-layout-normalization vendor for the current runtime mode.
60
+ *
61
+ * @remarks
62
+ * Kept out of {@link getDependencies} so non-MDX pages do not pay for this vendor during
63
+ * integration setup. Callers process these assets once when an MDX page graph is prepared.
64
+ */
65
+ getPageLayoutNormalizationDependencies(options?: {
66
+ modes?: RuntimeMode[];
67
+ }): AssetDefinition[];
43
68
  createRuntimeAliasPlugin(mode?: RuntimeMode): EcoBuildPlugin;
44
69
  }
45
70
  export {};
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Runtime bundle service for React integration.
3
+ *
4
+ * Owns creation of the browser runtime assets for React and React DOM,
5
+ * including shared runtime entry generation and specifier mapping.
6
+ *
7
+ * @module
8
+ */
9
+ import { createBrowserRuntimePlugin } from '@ecopages/core/build/browser-runtime-plugin';
10
+ import { DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME } from '@ecopages/core/build/browser-runtime-plugin';
11
+ import { buildBrowserRuntimeAssetUrl, createBrowserRuntimeModuleAsset, createBrowserRuntimeScriptAsset, } from '@ecopages/core/services/asset-processing-service';
12
+ import { createReactDomRuntimeInteropPlugin } from './runtime-interop-plugin.js';
13
+ import { buildReactRuntimeAliasMap, buildReactRuntimeManifest, getReactRuntimeExternalSpecifiers, } from './runtime-alias-map.js';
14
+ import { createBrowserRuntimeManifest, } from '@ecopages/core/build/browser-runtime-manifest';
15
+ import { LAYOUT_COMPOSE_PACKAGE, PAGE_LAYOUT_NORMALIZATION_PACKAGE } from './bootstrap-package-paths.js';
16
+ export class RuntimeBundleService {
17
+ config;
18
+ constructor(config) {
19
+ this.config = config;
20
+ }
21
+ setRootDir(rootDir) {
22
+ this.config.rootDir = rootDir;
23
+ }
24
+ setWorkDir(workDir) {
25
+ this.config.workDir = workDir;
26
+ }
27
+ setRuntimeModules(runtimeModules) {
28
+ this.config.runtimeModules = runtimeModules;
29
+ }
30
+ get isDevelopment() {
31
+ return process.env.NODE_ENV === 'development';
32
+ }
33
+ getCurrentRuntimeMode() {
34
+ return this.isDevelopment ? 'development' : 'production';
35
+ }
36
+ createRuntimeDefines(mode) {
37
+ const nodeEnv = JSON.stringify(mode);
38
+ return {
39
+ 'process.env.NODE_ENV': nodeEnv,
40
+ 'import.meta.env.NODE_ENV': nodeEnv,
41
+ };
42
+ }
43
+ getReactVendorFileName(mode) {
44
+ return mode === 'development' ? 'react.development.js' : 'react.js';
45
+ }
46
+ getReactDomVendorFileName(mode) {
47
+ return mode === 'development' ? 'react-dom.development.js' : 'react-dom.js';
48
+ }
49
+ getRouterVendorFileName(mode) {
50
+ if (!this.config.routerAdapter) {
51
+ return '';
52
+ }
53
+ return mode === 'development'
54
+ ? `${this.config.routerAdapter.bundle.outputName}.development.js`
55
+ : `${this.config.routerAdapter.bundle.outputName}.js`;
56
+ }
57
+ getConfiguredRuntimeModuleFileName(outputName, mode) {
58
+ return mode === 'development' ? `${outputName}.development.js` : `${outputName}.js`;
59
+ }
60
+ getConfiguredRuntimeModules() {
61
+ return this.config.runtimeModules ?? [];
62
+ }
63
+ getConfiguredRuntimeModuleSpecifiers() {
64
+ return this.getConfiguredRuntimeModules().map((module) => module.specifier);
65
+ }
66
+ getRuntimeModuleBundleExternals(module, mappedSpecifiers) {
67
+ return [
68
+ ...getReactRuntimeExternalSpecifiers(),
69
+ ...(this.config.routerAdapter?.bundle.externals ?? []),
70
+ ...(this.config.routerAdapter ? [this.config.routerAdapter.bundle.importPath] : []),
71
+ ...module.externals,
72
+ ].filter((external) => !mappedSpecifiers.has(external));
73
+ }
74
+ getUseSyncExternalStoreWithSelectorVendorFileName(mode) {
75
+ return mode === 'development'
76
+ ? 'use-sync-external-store-with-selector.development.js'
77
+ : 'use-sync-external-store-with-selector.js';
78
+ }
79
+ getPageLayoutNormalizationVendorFileName(mode) {
80
+ return mode === 'development' ? 'page-layout-normalization.development.js' : 'page-layout-normalization.js';
81
+ }
82
+ getLayoutComposeVendorFileName(mode) {
83
+ return mode === 'development' ? 'layout-compose.development.js' : 'layout-compose.js';
84
+ }
85
+ createReactVendorImportRewritePlugin(mode) {
86
+ return createBrowserRuntimePlugin({
87
+ name: `react-plugin-vendor-runtime-import-rewrite-${mode}`,
88
+ manifest: createBrowserRuntimeManifest([
89
+ {
90
+ specifier: 'react',
91
+ owner: '@ecopages/react',
92
+ importPath: 'react',
93
+ publicPath: buildBrowserRuntimeAssetUrl(this.getReactVendorFileName(mode)),
94
+ },
95
+ ]),
96
+ });
97
+ }
98
+ getRuntimeImports(mode = this.getCurrentRuntimeMode()) {
99
+ const reactVendorFileName = this.getReactVendorFileName(mode);
100
+ const reactDomVendorFileName = this.getReactDomVendorFileName(mode);
101
+ const runtimeImports = {
102
+ react: buildBrowserRuntimeAssetUrl(reactVendorFileName),
103
+ reactDomClient: buildBrowserRuntimeAssetUrl(reactDomVendorFileName),
104
+ reactJsxRuntime: buildBrowserRuntimeAssetUrl(reactVendorFileName),
105
+ reactJsxDevRuntime: buildBrowserRuntimeAssetUrl(reactVendorFileName),
106
+ reactDom: buildBrowserRuntimeAssetUrl(reactDomVendorFileName),
107
+ useSyncExternalStoreWithSelector: buildBrowserRuntimeAssetUrl(this.getUseSyncExternalStoreWithSelectorVendorFileName(mode)),
108
+ pageLayoutNormalization: buildBrowserRuntimeAssetUrl(this.getPageLayoutNormalizationVendorFileName(mode)),
109
+ layoutCompose: buildBrowserRuntimeAssetUrl(this.getLayoutComposeVendorFileName(mode)),
110
+ };
111
+ if (this.config.routerAdapter) {
112
+ runtimeImports.router = buildBrowserRuntimeAssetUrl(this.getRouterVendorFileName(mode));
113
+ }
114
+ return runtimeImports;
115
+ }
116
+ getRuntimeAliasMap(mode = this.getCurrentRuntimeMode()) {
117
+ return buildReactRuntimeAliasMap(this.getRuntimeImports(mode));
118
+ }
119
+ getRuntimeManifest(mode = this.getCurrentRuntimeMode()) {
120
+ return buildReactRuntimeManifest(this.getRuntimeImports(mode), this.getConfiguredRuntimeModules(), (outputName) => buildBrowserRuntimeAssetUrl(this.getConfiguredRuntimeModuleFileName(outputName, mode)), { routerImportPath: this.config.routerAdapter?.bundle.importPath });
121
+ }
122
+ getDependencies(options) {
123
+ const dependencies = [];
124
+ const modes = options?.modes ?? [this.getCurrentRuntimeMode()];
125
+ for (const mode of modes) {
126
+ const reactVendorImportRewritePlugin = this.createReactVendorImportRewritePlugin(mode);
127
+ const reactDomRuntimeInteropPlugin = createReactDomRuntimeInteropPlugin({
128
+ reactSpecifier: buildBrowserRuntimeAssetUrl(this.getReactVendorFileName(mode)),
129
+ });
130
+ const reactRuntimeAliasPlugin = createBrowserRuntimePlugin({
131
+ name: `react-plugin-runtime-specifier-alias-${mode}`,
132
+ manifest: createBrowserRuntimeManifest([
133
+ {
134
+ specifier: 'react',
135
+ owner: '',
136
+ importPath: 'react',
137
+ publicPath: buildBrowserRuntimeAssetUrl(this.getReactVendorFileName(mode)),
138
+ },
139
+ ]),
140
+ });
141
+ const reactDomBundlePlugins = [reactRuntimeAliasPlugin, reactDomRuntimeInteropPlugin].filter((plugin) => plugin !== null);
142
+ const runtimeAliasPlugin = this.createRuntimeAliasPlugin(mode);
143
+ const mappedSpecifiers = new Set(Object.keys(this.getRuntimeAliasMap(mode)));
144
+ dependencies.push(createBrowserRuntimeModuleAsset({
145
+ modules: [
146
+ { specifier: 'react', defaultExport: true },
147
+ { specifier: 'react/jsx-runtime' },
148
+ { specifier: 'react/jsx-dev-runtime' },
149
+ ],
150
+ name: 'react',
151
+ fileName: this.getReactVendorFileName(mode),
152
+ cacheDirName: `ecopages-react-runtime-${mode}`,
153
+ rootDir: this.config.rootDir,
154
+ workDir: this.config.workDir,
155
+ bundleOptions: {
156
+ define: this.createRuntimeDefines(mode),
157
+ excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
158
+ },
159
+ }), createBrowserRuntimeModuleAsset({
160
+ modules: [{ specifier: 'react-dom', defaultExport: true }, { specifier: 'react-dom/client' }],
161
+ name: 'react-dom',
162
+ fileName: this.getReactDomVendorFileName(mode),
163
+ cacheDirName: `ecopages-react-runtime-${mode}`,
164
+ rootDir: this.config.rootDir,
165
+ workDir: this.config.workDir,
166
+ bundleOptions: {
167
+ define: this.createRuntimeDefines(mode),
168
+ excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
169
+ plugins: reactDomBundlePlugins,
170
+ },
171
+ }), createBrowserRuntimeScriptAsset({
172
+ importPath: '@ecopages/react/runtime/use-sync-external-store-with-selector',
173
+ name: 'use-sync-external-store-with-selector',
174
+ fileName: this.getUseSyncExternalStoreWithSelectorVendorFileName(mode),
175
+ bundleOptions: {
176
+ define: this.createRuntimeDefines(mode),
177
+ excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
178
+ plugins: [reactVendorImportRewritePlugin],
179
+ },
180
+ }), createBrowserRuntimeScriptAsset({
181
+ importPath: LAYOUT_COMPOSE_PACKAGE,
182
+ name: 'layout-compose',
183
+ fileName: this.getLayoutComposeVendorFileName(mode),
184
+ bundleOptions: {
185
+ define: this.createRuntimeDefines(mode),
186
+ excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
187
+ plugins: [reactVendorImportRewritePlugin],
188
+ },
189
+ }));
190
+ if (this.config.routerAdapter) {
191
+ const unresolvedExternals = this.config.routerAdapter.bundle.externals.filter((external) => !mappedSpecifiers.has(external));
192
+ dependencies.push(createBrowserRuntimeScriptAsset({
193
+ importPath: this.config.routerAdapter.bundle.importPath,
194
+ name: this.config.routerAdapter.bundle.outputName,
195
+ fileName: this.getRouterVendorFileName(mode),
196
+ bundleOptions: {
197
+ define: this.createRuntimeDefines(mode),
198
+ external: unresolvedExternals,
199
+ plugins: [runtimeAliasPlugin],
200
+ },
201
+ }));
202
+ }
203
+ for (const runtimeModule of this.getConfiguredRuntimeModules()) {
204
+ dependencies.push(createBrowserRuntimeModuleAsset({
205
+ modules: [{ specifier: runtimeModule.specifier, defaultExport: true }],
206
+ name: runtimeModule.outputName,
207
+ fileName: this.getConfiguredRuntimeModuleFileName(runtimeModule.outputName, mode),
208
+ cacheDirName: `ecopages-react-runtime-module-${runtimeModule.outputName}-${mode}`,
209
+ rootDir: this.config.rootDir,
210
+ workDir: this.config.workDir,
211
+ bundleOptions: {
212
+ define: this.createRuntimeDefines(mode),
213
+ external: this.getRuntimeModuleBundleExternals(runtimeModule, mappedSpecifiers),
214
+ excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
215
+ plugins: [runtimeAliasPlugin],
216
+ },
217
+ }));
218
+ }
219
+ }
220
+ return dependencies;
221
+ }
222
+ /**
223
+ * Declares the MDX-only page-layout-normalization vendor for the current runtime mode.
224
+ *
225
+ * @remarks
226
+ * Kept out of {@link getDependencies} so non-MDX pages do not pay for this vendor during
227
+ * integration setup. Callers process these assets once when an MDX page graph is prepared.
228
+ */
229
+ getPageLayoutNormalizationDependencies(options) {
230
+ const dependencies = [];
231
+ const modes = options?.modes ?? [this.getCurrentRuntimeMode()];
232
+ for (const mode of modes) {
233
+ dependencies.push(createBrowserRuntimeScriptAsset({
234
+ importPath: PAGE_LAYOUT_NORMALIZATION_PACKAGE,
235
+ name: 'page-layout-normalization',
236
+ fileName: this.getPageLayoutNormalizationVendorFileName(mode),
237
+ bundleOptions: {
238
+ define: this.createRuntimeDefines(mode),
239
+ excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
240
+ },
241
+ }));
242
+ }
243
+ return dependencies;
244
+ }
245
+ createRuntimeAliasPlugin(mode = this.getCurrentRuntimeMode()) {
246
+ const aliasMap = this.getRuntimeAliasMap(mode);
247
+ const manifest = createBrowserRuntimeManifest(Object.entries(aliasMap).map(([specifier, publicPath]) => ({
248
+ specifier,
249
+ owner: '',
250
+ importPath: specifier,
251
+ publicPath,
252
+ })));
253
+ return createBrowserRuntimePlugin({
254
+ name: `react-plugin-runtime-alias-${mode}`,
255
+ manifest,
256
+ });
257
+ }
258
+ }
@@ -0,0 +1,34 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ function escapeRegExp(value) {
4
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5
+ }
6
+ export function createReactDomRuntimeInteropPlugin(options) {
7
+ const reactDomFileFilter = /[\\/]react-dom[\\/].*\.js$/;
8
+ const reactRequirePattern = /\brequire\((['"])react\1\)/g;
9
+ const reactSpecifier = options?.reactSpecifier ?? 'react';
10
+ return {
11
+ name: options?.name ?? 'react-dom-runtime-interop',
12
+ setup(build) {
13
+ if (reactSpecifier.startsWith('/')) {
14
+ build.onResolve({ filter: new RegExp(`^${escapeRegExp(reactSpecifier)}$`) }, (args) => ({
15
+ path: args.path,
16
+ external: true,
17
+ }));
18
+ }
19
+ build.onLoad({ filter: reactDomFileFilter }, (args) => {
20
+ const content = fs.readFileSync(args.path, 'utf-8');
21
+ if (!reactRequirePattern.test(content)) {
22
+ return undefined;
23
+ }
24
+ reactRequirePattern.lastIndex = 0;
25
+ const rewritten = content.replace(reactRequirePattern, '__ecopages_react_runtime');
26
+ return {
27
+ contents: `import * as __ecopages_react_runtime from '${reactSpecifier}';\n${rewritten}`,
28
+ loader: 'js',
29
+ resolveDir: path.dirname(args.path),
30
+ };
31
+ });
32
+ },
33
+ };
34
+ }