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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +179 -7
  2. package/package.json +53 -28
  3. package/src/app/client-only.js +15 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +31 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +23 -8
  9. package/src/bundling/bundle.js +120 -0
  10. package/src/bundling/discover-layout-runtime-modules.d.ts +32 -0
  11. package/src/bundling/discover-layout-runtime-modules.js +185 -0
  12. package/src/bundling/runtime-alias-map.d.ts +13 -0
  13. package/src/bundling/runtime-alias-map.js +113 -0
  14. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +25 -4
  15. package/src/bundling/runtime-bundle.js +258 -0
  16. package/src/bundling/runtime-interop-plugin.js +34 -0
  17. package/src/bundling/runtime-mode.d.ts +9 -0
  18. package/src/bundling/runtime-mode.js +11 -0
  19. package/src/bundling/runtime-modules.d.ts +29 -0
  20. package/src/bundling/runtime-modules.js +49 -0
  21. package/src/client-graph/ast-transform.d.ts +18 -0
  22. package/src/client-graph/ast-transform.js +426 -0
  23. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +23 -13
  24. package/src/client-graph/boundary-cache.js +182 -0
  25. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +4 -13
  26. package/src/client-graph/boundary-plugin.js +149 -0
  27. package/src/client-graph/component-config-traversal.js +77 -0
  28. package/src/client-graph/declared-modules.js +69 -0
  29. package/src/client-graph/module-classification.d.ts +3 -0
  30. package/src/client-graph/module-classification.js +43 -0
  31. package/src/{utils → client-graph}/reachability-analyzer.d.ts +4 -12
  32. package/src/client-graph/reachability-analyzer.js +515 -0
  33. package/src/client-graph/specifier-classification.d.ts +75 -0
  34. package/src/client-graph/specifier-classification.js +214 -0
  35. package/src/contracts/router-adapter.js +6 -0
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  37. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  38. package/src/hmr/hmr-scripts.js +44 -0
  39. package/src/hmr/hmr-strategy.d.ts +74 -0
  40. package/src/hmr/hmr-strategy.js +351 -0
  41. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  42. package/src/hmr/page-metadata-cache.js +44 -0
  43. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  44. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  45. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  46. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  47. package/src/hydration/bootstrap-imports.d.ts +25 -0
  48. package/src/hydration/bootstrap-imports.js +33 -0
  49. package/src/hydration/hydration-asset.d.ts +84 -0
  50. package/src/hydration/hydration-asset.js +227 -0
  51. package/src/hydration/hydration-scripts.d.ts +104 -0
  52. package/src/hydration/hydration-scripts.js +483 -0
  53. package/src/hydration/hydration-scripts.test.browser.js +199 -0
  54. package/src/hydration/page-data-manifest.d.ts +58 -0
  55. package/src/hydration/page-data-manifest.js +97 -0
  56. package/src/hydration/page-data-reader.d.ts +31 -0
  57. package/src/hydration/page-data-reader.js +77 -0
  58. package/src/hydration/page-payload.d.ts +67 -0
  59. package/src/hydration/page-payload.js +106 -0
  60. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  61. package/src/hydration/serialize-page-data-script.js +30 -0
  62. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +6 -6
  63. package/src/mdx/mdx-config-dependency.js +110 -0
  64. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  65. package/src/mdx/mdx-loader-plugin.js +8 -0
  66. package/src/page/page-module.d.ts +46 -0
  67. package/src/page/page-module.js +74 -0
  68. package/src/plugin/react.constants.js +1 -0
  69. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +9 -3
  70. package/src/plugin/react.plugin.js +241 -0
  71. package/src/plugin/react.types.d.ts +156 -0
  72. package/src/plugin/react.types.js +1 -0
  73. package/src/render/component-ownership.d.ts +49 -0
  74. package/src/render/component-ownership.js +46 -0
  75. package/src/render/component-ssr.d.ts +113 -0
  76. package/src/render/component-ssr.js +180 -0
  77. package/src/render/eco-embed.js +9 -0
  78. package/src/render/errors.d.ts +16 -0
  79. package/src/render/errors.js +23 -0
  80. package/src/render/html-boundary.js +59 -0
  81. package/src/render/layout-compose.d.ts +66 -0
  82. package/src/render/layout-compose.js +134 -0
  83. package/src/render/react-renderer.d.ts +138 -0
  84. package/src/render/react-renderer.js +448 -0
  85. package/src/render/react-runtime.d.ts +13 -0
  86. package/src/render/react-runtime.js +26 -0
  87. package/src/render/unified-layout-composition.d.ts +53 -0
  88. package/src/render/unified-layout-composition.js +78 -0
  89. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  90. package/src/eco-embed.js +0 -11
  91. package/src/react-hmr-strategy.d.ts +0 -230
  92. package/src/react-hmr-strategy.js +0 -657
  93. package/src/react-renderer.d.ts +0 -233
  94. package/src/react-renderer.js +0 -622
  95. package/src/react.constants.js +0 -4
  96. package/src/react.plugin.js +0 -209
  97. package/src/react.types.d.ts +0 -88
  98. package/src/react.types.js +0 -0
  99. package/src/router-adapter.js +0 -0
  100. package/src/services/pages-index.d.ts +0 -64
  101. package/src/services/pages-index.js +0 -73
  102. package/src/services/react-bundle.service.js +0 -86
  103. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  104. package/src/services/react-hydration-asset.service.d.ts +0 -84
  105. package/src/services/react-hydration-asset.service.js +0 -217
  106. package/src/services/react-mdx-config-dependency.service.js +0 -122
  107. package/src/services/react-page-module.service.d.ts +0 -88
  108. package/src/services/react-page-module.service.js +0 -166
  109. package/src/services/react-page-payload.service.d.ts +0 -46
  110. package/src/services/react-page-payload.service.js +0 -67
  111. package/src/services/react-runtime-bundle.service.js +0 -192
  112. package/src/utils/client-graph-boundary-cache.js +0 -116
  113. package/src/utils/client-graph-boundary-plugin.js +0 -552
  114. package/src/utils/client-only.js +0 -19
  115. package/src/utils/component-config-traversal.js +0 -54
  116. package/src/utils/declared-modules.js +0 -47
  117. package/src/utils/dynamic.js +0 -12
  118. package/src/utils/dynamic.test.browser.js +0 -33
  119. package/src/utils/hmr-scripts.js +0 -31
  120. package/src/utils/html-boundary.js +0 -55
  121. package/src/utils/hydration-scripts.d.ts +0 -92
  122. package/src/utils/hydration-scripts.js +0 -358
  123. package/src/utils/hydration-scripts.test.browser.js +0 -198
  124. package/src/utils/reachability-analyzer.js +0 -339
  125. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  126. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  127. package/src/utils/react-mdx-loader-plugin.js +0 -45
  128. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  129. package/src/utils/react-runtime-alias-map.js +0 -90
  130. /package/src/{utils → app}/client-only.d.ts +0 -0
  131. /package/src/{utils → app}/dynamic.d.ts +0 -0
  132. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  133. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  134. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  135. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  136. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  137. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  138. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  139. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  140. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  141. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  142. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,351 @@
1
+ /**
2
+ * React HMR Strategy
3
+ *
4
+ * Handles hot module replacement for React components.
5
+ * Triggers module invalidation on changes to ensure fresh component re-renders.
6
+ *
7
+ * @module
8
+ */
9
+ import path from 'node:path';
10
+ import { HmrStrategy, HmrStrategyType } from '@ecopages/core/hmr/hmr-strategy';
11
+ import { isRegisteredScriptEntrypoint } from '@ecopages/core/hmr/hmr-entrypoint-output';
12
+ import { DEV_TRANSFORM_URL_PREFIX } from '@ecopages/core/dev/transform-server';
13
+ import { createBrowserRuntimePlugin } from '@ecopages/core/build/browser-runtime-plugin';
14
+ import { Logger } from '@ecopages/logger';
15
+ import { createClientGraphBoundaryPlugin } from '../client-graph/boundary-plugin.js';
16
+ import { ClientGraphBoundaryCache } from '../client-graph/boundary-cache.js';
17
+ import { someInConfigTree } from '../client-graph/component-config-traversal.js';
18
+ import { getReactClientGraphAllowSpecifiers } from '../bundling/runtime-alias-map.js';
19
+ import { getComponentIdentity } from '@ecopages/core';
20
+ import { buildReactDevTransformPlugins, resolveReactDeclaredModulesForEntrypoint, } from './react-hmr-dev-transform-plugins.js';
21
+ const appLogger = new Logger('[ReactHmrStrategy]');
22
+ /**
23
+ * Strategy for handling React component HMR updates.
24
+ */
25
+ export class ReactHmrStrategy extends HmrStrategy {
26
+ type = HmrStrategyType.INTEGRATION;
27
+ mdxCompilerOptions;
28
+ ownedTemplateExtensions;
29
+ allTemplateExtensions;
30
+ context;
31
+ pageMetadataCache;
32
+ runtimeManifest;
33
+ clientGraphBoundaryCache;
34
+ async importNodePageModule(entrypointPath) {
35
+ return await this.context.importServerModule(entrypointPath);
36
+ }
37
+ getDevTransformPluginOptions() {
38
+ return {
39
+ pageMetadataCache: this.pageMetadataCache,
40
+ mdxCompilerOptions: this.mdxCompilerOptions,
41
+ getBuildPlugins: (declaredModules) => this.getBuildPlugins(declaredModules),
42
+ importNodePageModule: (entrypointPath) => this.importNodePageModule(entrypointPath),
43
+ };
44
+ }
45
+ constructor(options) {
46
+ super();
47
+ this.context = options.context;
48
+ this.pageMetadataCache = options.pageMetadataCache;
49
+ this.runtimeManifest = options.runtimeManifest;
50
+ this.clientGraphBoundaryCache = options.clientGraphBoundaryCache ?? new ClientGraphBoundaryCache();
51
+ this.mdxCompilerOptions = options.mdxCompilerOptions;
52
+ this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? ['.tsx']);
53
+ this.allTemplateExtensions = [...(options.allTemplateExtensions ?? ['.tsx'])].sort((a, b) => b.length - a.length);
54
+ }
55
+ getBuildPlugins(declaredModules) {
56
+ const allowSpecifiers = getReactClientGraphAllowSpecifiers(this.runtimeManifest.assets.map((asset) => asset.specifier));
57
+ const runtimeRewritePlugin = createBrowserRuntimePlugin({
58
+ name: 'react-hmr-runtime-import-rewrite',
59
+ manifest: this.runtimeManifest,
60
+ });
61
+ return [
62
+ createClientGraphBoundaryPlugin({
63
+ projectRoot: path.dirname(this.context.getSrcDir()),
64
+ absWorkingDir: path.dirname(this.context.getSrcDir()),
65
+ alwaysAllowSpecifiers: allowSpecifiers,
66
+ declaredModules,
67
+ cache: this.clientGraphBoundaryCache,
68
+ }),
69
+ ...(runtimeRewritePlugin ? [runtimeRewritePlugin] : []),
70
+ ];
71
+ }
72
+ isReactEntrypoint(filePath) {
73
+ if (filePath.endsWith('.mdx')) {
74
+ return this.mdxCompilerOptions !== undefined;
75
+ }
76
+ if (!filePath.endsWith('.tsx')) {
77
+ return false;
78
+ }
79
+ const templateExtension = this.resolveTemplateExtension(filePath);
80
+ if (templateExtension && templateExtension !== '.tsx') {
81
+ return this.ownedTemplateExtensions.has(templateExtension);
82
+ }
83
+ if (!this.isRouteTemplate(filePath)) {
84
+ return true;
85
+ }
86
+ if (!templateExtension) {
87
+ return false;
88
+ }
89
+ return this.ownedTemplateExtensions.has(templateExtension);
90
+ }
91
+ /**
92
+ * @remarks
93
+ * React integration owns plain `.tsx` route templates. Compound extensions in
94
+ * pages/layouts are integration-specific route templates and should not be
95
+ * claimed by React HMR strategy.
96
+ */
97
+ isRouteTemplate(filePath) {
98
+ return filePath.startsWith(this.context.getPagesDir()) || filePath.startsWith(this.context.getLayoutsDir());
99
+ }
100
+ resolveTemplateExtension(filePath) {
101
+ return this.allTemplateExtensions.find((extension) => filePath.endsWith(extension));
102
+ }
103
+ isDevTransformOutputUrl(outputUrl) {
104
+ return outputUrl.startsWith(`${DEV_TRANSFORM_URL_PREFIX}/`);
105
+ }
106
+ queueDevTransformOutputUpdates(targets, requestedOutputUrls, updates) {
107
+ for (const { outputUrl } of targets) {
108
+ if (requestedOutputUrls.has(outputUrl)) {
109
+ updates.push(outputUrl);
110
+ }
111
+ }
112
+ }
113
+ ownsWatchedEntrypoint(filePath) {
114
+ return this.pageMetadataCache.ownsEntrypoint(filePath);
115
+ }
116
+ configContainsFile(config, filePath) {
117
+ const resolvedFilePath = path.resolve(filePath);
118
+ return someInConfigTree(config, (node) => {
119
+ const identity = getComponentIdentity(node);
120
+ if (!identity?.file) {
121
+ return false;
122
+ }
123
+ return path.resolve(identity.file) === resolvedFilePath;
124
+ });
125
+ }
126
+ pageModuleRequiresLayoutRefresh(pageModule, filePath) {
127
+ return [pageModule.default?.config, pageModule.config].some((config) => {
128
+ return (config?.layouts ?? []).some((layout) => this.configContainsFile(layout?.config, filePath));
129
+ });
130
+ }
131
+ async hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets) {
132
+ for (const target of requestedTargets) {
133
+ if (!this.isPageEntrypoint(target.entrypointPath)) {
134
+ continue;
135
+ }
136
+ const pageModule = await this.importNodePageModule(target.entrypointPath);
137
+ if (this.pageModuleRequiresLayoutRefresh(pageModule, changedFilePath)) {
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ matches(filePath) {
144
+ const watchedFiles = this.context.getWatchedFiles();
145
+ const resolvedFilePath = path.resolve(filePath);
146
+ appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
147
+ if (isRegisteredScriptEntrypoint(this.context.getRegisteredEntrypoints(), resolvedFilePath)) {
148
+ return false;
149
+ }
150
+ if (watchedFiles.has(resolvedFilePath)) {
151
+ if (this.ownsWatchedEntrypoint(resolvedFilePath)) {
152
+ return true;
153
+ }
154
+ const outputUrl = watchedFiles.get(resolvedFilePath);
155
+ if (outputUrl && this.isDevTransformOutputUrl(outputUrl) && this.isReactEntrypoint(resolvedFilePath)) {
156
+ return true;
157
+ }
158
+ return false;
159
+ }
160
+ const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(resolvedFilePath);
161
+ if (dependencyHits.size > 0) {
162
+ for (const entrypoint of dependencyHits) {
163
+ if (this.ownsWatchedEntrypoint(entrypoint)) {
164
+ return true;
165
+ }
166
+ }
167
+ return false;
168
+ }
169
+ return this.isReactEntrypoint(filePath);
170
+ }
171
+ ownsDevTransformEntrypoint(sourcePath) {
172
+ if (!this.isReactEntrypoint(sourcePath)) {
173
+ return false;
174
+ }
175
+ const normalized = path.resolve(sourcePath);
176
+ const srcDir = path.resolve(this.context.getSrcDir());
177
+ return normalized === srcDir || normalized.startsWith(`${srcDir}${path.sep}`);
178
+ }
179
+ getRuntimeManifest() {
180
+ return this.runtimeManifest;
181
+ }
182
+ async getVendorBundlePlugins() {
183
+ return this.getBuildPlugins();
184
+ }
185
+ async createDevTransformPlugins(sourcePath) {
186
+ const shouldResolveDeclaredModules = this.isPageEntrypoint(sourcePath) || sourcePath.endsWith('.mdx');
187
+ const declaredModules = shouldResolveDeclaredModules
188
+ ? await resolveReactDeclaredModulesForEntrypoint(this.getDevTransformPluginOptions(), sourcePath)
189
+ : [];
190
+ return buildReactDevTransformPlugins(this.getDevTransformPluginOptions(), declaredModules, sourcePath.endsWith('.mdx'));
191
+ }
192
+ isLayoutFile(filePath) {
193
+ return filePath.startsWith(this.context.getLayoutsDir());
194
+ }
195
+ isPageEntrypoint(filePath) {
196
+ return filePath.startsWith(this.context.getPagesDir()) && this.isReactEntrypoint(filePath);
197
+ }
198
+ resolveEntrypointOutputUrl(entrypointPath) {
199
+ return this.context.getWatchedFiles().get(path.resolve(entrypointPath));
200
+ }
201
+ async collectReactPageBuildTargets() {
202
+ const targets = new Map();
203
+ for (const entrypointPath of this.pageMetadataCache.getOwnedEntrypoints()) {
204
+ if (!this.isPageEntrypoint(entrypointPath)) {
205
+ continue;
206
+ }
207
+ const outputUrl = this.resolveEntrypointOutputUrl(entrypointPath);
208
+ if (!outputUrl) {
209
+ continue;
210
+ }
211
+ targets.set(entrypointPath, {
212
+ entrypointPath,
213
+ outputUrl,
214
+ });
215
+ }
216
+ return Array.from(targets.values()).sort((left, right) => left.entrypointPath.localeCompare(right.entrypointPath));
217
+ }
218
+ async resolveBuildTargets(requestedTargets, changedFilePath) {
219
+ const requestedPageTargets = requestedTargets.filter((target) => this.isPageEntrypoint(target.entrypointPath));
220
+ const shouldGroupPageBuilds = this.isLayoutFile(changedFilePath) || requestedPageTargets.length > 0;
221
+ if (!shouldGroupPageBuilds) {
222
+ return [];
223
+ }
224
+ const groupedTargets = new Map(requestedPageTargets.map((target) => [target.entrypointPath, target]));
225
+ for (const target of await this.collectReactPageBuildTargets()) {
226
+ if (!groupedTargets.has(target.entrypointPath)) {
227
+ groupedTargets.set(target.entrypointPath, target);
228
+ }
229
+ }
230
+ return Array.from(groupedTargets.values()).sort((left, right) => left.entrypointPath.localeCompare(right.entrypointPath));
231
+ }
232
+ partitionBuildTargets(requestedTargets, groupedPageTargets) {
233
+ if (groupedPageTargets.length === 0) {
234
+ return {
235
+ pageTargets: [],
236
+ nonPageTargets: requestedTargets,
237
+ };
238
+ }
239
+ const groupedPageEntrypoints = new Set(groupedPageTargets.map((target) => target.entrypointPath));
240
+ return {
241
+ pageTargets: groupedPageTargets,
242
+ nonPageTargets: requestedTargets.filter((target) => !groupedPageEntrypoints.has(target.entrypointPath) && !this.isPageEntrypoint(target.entrypointPath)),
243
+ };
244
+ }
245
+ async process(_filePath) {
246
+ appLogger.debug(`Processing ${_filePath}`);
247
+ const resolvedFilePath = path.resolve(_filePath);
248
+ const watchedFiles = this.context.getWatchedFiles();
249
+ if (watchedFiles.size === 0) {
250
+ appLogger.debug(`No watched files`);
251
+ return { type: 'none' };
252
+ }
253
+ const isLayout = this.isLayoutFile(resolvedFilePath);
254
+ const isChangedPageEntrypoint = this.isPageEntrypoint(resolvedFilePath);
255
+ if (isLayout) {
256
+ appLogger.debug(`Detected layout file change: ${resolvedFilePath}`);
257
+ }
258
+ const changedEntrypointOutput = watchedFiles.get(resolvedFilePath);
259
+ if (changedEntrypointOutput && !this.ownsWatchedEntrypoint(resolvedFilePath)) {
260
+ if (this.isReactEntrypoint(resolvedFilePath)) {
261
+ this.pageMetadataCache.markOwnedEntrypoint(resolvedFilePath);
262
+ }
263
+ else {
264
+ appLogger.debug(`Skipping non-React watched entrypoint: ${resolvedFilePath}`);
265
+ return { type: 'none' };
266
+ }
267
+ }
268
+ const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(resolvedFilePath);
269
+ const hasDependencyHits = dependencyHits.size > 0;
270
+ const affectedEntrypoints = new Map();
271
+ let hasOwnedLayoutDependencyHit = false;
272
+ let layoutOwnedPageTargets = [];
273
+ let hasLayoutOwnedRequestedTarget = false;
274
+ if (hasDependencyHits && !changedEntrypointOutput) {
275
+ for (const entrypoint of dependencyHits) {
276
+ const resolvedEntrypoint = path.resolve(entrypoint);
277
+ const outputUrl = watchedFiles.get(resolvedEntrypoint);
278
+ if (outputUrl &&
279
+ (this.ownsWatchedEntrypoint(resolvedEntrypoint) || this.isDevTransformOutputUrl(outputUrl))) {
280
+ affectedEntrypoints.set(resolvedEntrypoint, outputUrl);
281
+ continue;
282
+ }
283
+ if (this.isLayoutFile(resolvedEntrypoint) && this.ownsWatchedEntrypoint(resolvedEntrypoint)) {
284
+ hasOwnedLayoutDependencyHit = true;
285
+ }
286
+ }
287
+ if (affectedEntrypoints.size === 0 && !hasOwnedLayoutDependencyHit) {
288
+ if (!isLayout) {
289
+ appLogger.debug(`Dependency hits found but none map to React-owned watched entrypoints`);
290
+ return { type: 'none' };
291
+ }
292
+ }
293
+ }
294
+ if (changedEntrypointOutput && !isLayout && !isChangedPageEntrypoint) {
295
+ layoutOwnedPageTargets = await this.collectReactPageBuildTargets();
296
+ hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(resolvedFilePath, layoutOwnedPageTargets);
297
+ }
298
+ const requestedTargets = changedEntrypointOutput
299
+ ? hasLayoutOwnedRequestedTarget
300
+ ? [{ entrypointPath: resolvedFilePath, outputUrl: changedEntrypointOutput }, ...layoutOwnedPageTargets]
301
+ : [{ entrypointPath: resolvedFilePath, outputUrl: changedEntrypointOutput }]
302
+ : hasOwnedLayoutDependencyHit
303
+ ? await this.collectReactPageBuildTargets()
304
+ : hasDependencyHits
305
+ ? Array.from(affectedEntrypoints, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }))
306
+ : Array.from(watchedFiles, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }));
307
+ const groupedPageTargets = await this.resolveBuildTargets(requestedTargets, resolvedFilePath);
308
+ const { pageTargets, nonPageTargets } = this.partitionBuildTargets(requestedTargets, groupedPageTargets);
309
+ if (!changedEntrypointOutput) {
310
+ hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(resolvedFilePath, requestedTargets);
311
+ }
312
+ const requiresLayoutRefresh = isLayout || hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
313
+ const updates = [];
314
+ const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
315
+ this.queueDevTransformOutputUpdates(pageTargets, requestedOutputUrls, updates);
316
+ for (const { outputUrl } of nonPageTargets) {
317
+ if (!requestedOutputUrls.has(outputUrl)) {
318
+ continue;
319
+ }
320
+ if (this.isDevTransformOutputUrl(outputUrl)) {
321
+ updates.push(outputUrl);
322
+ continue;
323
+ }
324
+ appLogger.debug(`Skipping non-dev-transform HMR output: ${outputUrl}`);
325
+ }
326
+ if (requiresLayoutRefresh) {
327
+ appLogger.debug(`Layout update detected, sending layout-update event`);
328
+ return {
329
+ type: 'broadcast',
330
+ events: [
331
+ {
332
+ type: 'layout-update',
333
+ },
334
+ ],
335
+ };
336
+ }
337
+ if (updates.length > 0) {
338
+ appLogger.debug(`Broadcasting ${updates.length} updates`);
339
+ return {
340
+ type: 'broadcast',
341
+ events: updates.map((path) => ({
342
+ type: 'update',
343
+ path,
344
+ timestamp: Date.now(),
345
+ })),
346
+ };
347
+ }
348
+ appLogger.debug(`No updates generated`);
349
+ return { type: 'none' };
350
+ }
351
+ }
@@ -4,7 +4,7 @@
4
4
  * This keeps React Fast Refresh optimizations local to the React integration so
5
5
  * core HMR interfaces do not need React-specific metadata hooks.
6
6
  */
7
- export declare class ReactHmrPageMetadataCache {
7
+ export declare class HmrPageMetadataCache {
8
8
  private readonly declaredModulesByEntrypoint;
9
9
  private readonly ownedEntrypoints;
10
10
  /**
@@ -19,6 +19,10 @@ export declare class ReactHmrPageMetadataCache {
19
19
  * Returns the last known declared browser modules for a page entrypoint.
20
20
  */
21
21
  getDeclaredModules(entrypointPath: string): string[] | undefined;
22
+ /**
23
+ * Returns React-owned page entrypoints discovered during development renders.
24
+ */
25
+ getOwnedEntrypoints(): string[];
22
26
  /**
23
27
  * Returns true when the watched entrypoint is owned by the React integration.
24
28
  */
@@ -0,0 +1,44 @@
1
+ import path from 'node:path';
2
+ /**
3
+ * React-only cache for page metadata that HMR rebuilds need during development.
4
+ *
5
+ * This keeps React Fast Refresh optimizations local to the React integration so
6
+ * core HMR interfaces do not need React-specific metadata hooks.
7
+ */
8
+ export class HmrPageMetadataCache {
9
+ declaredModulesByEntrypoint = new Map();
10
+ ownedEntrypoints = new Set();
11
+ /**
12
+ * Marks an HMR entrypoint as React-owned.
13
+ */
14
+ markOwnedEntrypoint(entrypointPath) {
15
+ this.ownedEntrypoints.add(path.resolve(entrypointPath));
16
+ }
17
+ /**
18
+ * Stores the declared browser modules for a page entrypoint.
19
+ */
20
+ setDeclaredModules(entrypointPath, declaredModules) {
21
+ const resolvedEntrypointPath = path.resolve(entrypointPath);
22
+ this.markOwnedEntrypoint(resolvedEntrypointPath);
23
+ this.declaredModulesByEntrypoint.set(resolvedEntrypointPath, [...declaredModules]);
24
+ }
25
+ /**
26
+ * Returns the last known declared browser modules for a page entrypoint.
27
+ */
28
+ getDeclaredModules(entrypointPath) {
29
+ const declaredModules = this.declaredModulesByEntrypoint.get(path.resolve(entrypointPath));
30
+ return declaredModules ? [...declaredModules] : undefined;
31
+ }
32
+ /**
33
+ * Returns React-owned page entrypoints discovered during development renders.
34
+ */
35
+ getOwnedEntrypoints() {
36
+ return [...this.ownedEntrypoints].sort((left, right) => left.localeCompare(right));
37
+ }
38
+ /**
39
+ * Returns true when the watched entrypoint is owned by the React integration.
40
+ */
41
+ ownsEntrypoint(entrypointPath) {
42
+ return this.ownedEntrypoints.has(path.resolve(entrypointPath));
43
+ }
44
+ }
@@ -0,0 +1,23 @@
1
+ import type { EcoBuildPlugin } from '@ecopages/core/plugins/integration-plugin';
2
+ import type { EcoComponentConfig } from '@ecopages/core';
3
+ import type { CompileOptions } from '@mdx-js/mdx';
4
+ import type { HmrPageMetadataCache } from './page-metadata-cache.js';
5
+ export type ReactHmrBuildTarget = {
6
+ entrypointPath: string;
7
+ outputUrl: string;
8
+ };
9
+ type ImportedReactPageModule = {
10
+ default?: {
11
+ config?: EcoComponentConfig;
12
+ };
13
+ config?: EcoComponentConfig;
14
+ };
15
+ export type ReactHmrDevTransformPluginOptions = {
16
+ pageMetadataCache: HmrPageMetadataCache;
17
+ mdxCompilerOptions?: CompileOptions;
18
+ getBuildPlugins: (declaredModules?: readonly string[]) => EcoBuildPlugin[];
19
+ importNodePageModule: (entrypointPath: string) => Promise<ImportedReactPageModule>;
20
+ };
21
+ export declare function resolveReactDeclaredModulesForEntrypoint(options: ReactHmrDevTransformPluginOptions, entrypointPath: string): Promise<readonly string[]>;
22
+ export declare function buildReactDevTransformPlugins(options: ReactHmrDevTransformPluginOptions, declaredModules: readonly string[], shouldEnableMdx: boolean): EcoBuildPlugin[];
23
+ export {};
@@ -0,0 +1,20 @@
1
+ import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from '../client-graph/declared-modules.js';
2
+ import { createReactMdxLoaderPlugin } from '../mdx/mdx-loader-plugin.js';
3
+ export async function resolveReactDeclaredModulesForEntrypoint(options, entrypointPath) {
4
+ const cached = options.pageMetadataCache.getDeclaredModules(entrypointPath);
5
+ if (cached) {
6
+ return cached;
7
+ }
8
+ const declaredModules = entrypointPath.endsWith('.mdx')
9
+ ? await collectPageDeclaredModules(entrypointPath)
10
+ : collectPageDeclaredModulesFromModule(await options.importNodePageModule(entrypointPath));
11
+ options.pageMetadataCache.setDeclaredModules(entrypointPath, declaredModules);
12
+ return declaredModules;
13
+ }
14
+ export function buildReactDevTransformPlugins(options, declaredModules, shouldEnableMdx) {
15
+ const plugins = options.getBuildPlugins(declaredModules);
16
+ if (shouldEnableMdx && options.mdxCompilerOptions) {
17
+ plugins.unshift(createReactMdxLoaderPlugin(options.mdxCompilerOptions));
18
+ }
19
+ return plugins;
20
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Test helper: assert generated hydration bootstrap source has no bare `@ecopages/*` imports.
3
+ */
4
+ export declare function assertNoBareEcopagesImports(source: string): void;
@@ -0,0 +1,7 @@
1
+ import { expect } from 'vitest';
2
+ /**
3
+ * Test helper: assert generated hydration bootstrap source has no bare `@ecopages/*` imports.
4
+ */
5
+ export function assertNoBareEcopagesImports(source) {
6
+ expect(source).not.toMatch(/from\s+["']@ecopages\//);
7
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Resolves browser import paths for React page hydration bootstraps.
3
+ *
4
+ * @remarks
5
+ * When `useBrowserRuntimeImports` is true, helpers and runtimes resolve to shared
6
+ * `/assets/vendors/*.js` URLs so unbundled HMR bootstraps evaluate as native ESM.
7
+ * When false, bare package names are emitted for the production page bundler.
8
+ */
9
+ import type { ReactRuntimeImports } from '../bundling/runtime-bundle.js';
10
+ export type HydrationBootstrapImportPaths = {
11
+ reactImportPath: string;
12
+ reactDomClientImportPath: string;
13
+ routerImportPath?: string;
14
+ layoutComposeImportPath: string;
15
+ pageLayoutNormalizationImportPath: string;
16
+ };
17
+ export type ResolveHydrationBootstrapImportsOptions = {
18
+ useBrowserRuntimeImports: boolean;
19
+ runtimeImports: ReactRuntimeImports;
20
+ routerAdapterImportPath?: string;
21
+ };
22
+ /**
23
+ * Returns import paths for React page hydration scripts.
24
+ */
25
+ export declare function resolveHydrationBootstrapImports(options: ResolveHydrationBootstrapImportsOptions): HydrationBootstrapImportPaths;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Resolves browser import paths for React page hydration bootstraps.
3
+ *
4
+ * @remarks
5
+ * When `useBrowserRuntimeImports` is true, helpers and runtimes resolve to shared
6
+ * `/assets/vendors/*.js` URLs so unbundled HMR bootstraps evaluate as native ESM.
7
+ * When false, bare package names are emitted for the production page bundler.
8
+ */
9
+ import { LAYOUT_COMPOSE_PACKAGE, PAGE_LAYOUT_NORMALIZATION_PACKAGE } from '../bundling/bootstrap-package-paths.js';
10
+ /**
11
+ * Returns import paths for React page hydration scripts.
12
+ */
13
+ export function resolveHydrationBootstrapImports(options) {
14
+ const { useBrowserRuntimeImports, runtimeImports, routerAdapterImportPath } = options;
15
+ if (useBrowserRuntimeImports) {
16
+ return {
17
+ reactImportPath: runtimeImports.react,
18
+ reactDomClientImportPath: runtimeImports.reactDomClient,
19
+ ...(runtimeImports.router || routerAdapterImportPath
20
+ ? { routerImportPath: runtimeImports.router ?? routerAdapterImportPath }
21
+ : {}),
22
+ layoutComposeImportPath: runtimeImports.layoutCompose,
23
+ pageLayoutNormalizationImportPath: runtimeImports.pageLayoutNormalization,
24
+ };
25
+ }
26
+ return {
27
+ reactImportPath: 'react',
28
+ reactDomClientImportPath: 'react-dom/client',
29
+ ...(routerAdapterImportPath ? { routerImportPath: routerAdapterImportPath } : {}),
30
+ layoutComposeImportPath: LAYOUT_COMPOSE_PACKAGE,
31
+ pageLayoutNormalizationImportPath: PAGE_LAYOUT_NORMALIZATION_PACKAGE,
32
+ };
33
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Hydration asset creation service for React integration.
3
+ *
4
+ * Builds the asset definitions required for client-side React rendering — both at
5
+ * the page level and the component island level.
6
+ *
7
+ * @module
8
+ */
9
+ import type { EcoComponentConfig } from '@ecopages/core';
10
+ import { type AssetDefinition, type ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
11
+ import type { AssetProcessingService } from '@ecopages/core/services/asset-processing-service';
12
+ import type { BundleService } from '../bundling/bundle.js';
13
+ import type { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
14
+ import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
15
+ /**
16
+ * Configuration for the HydrationAssetService.
17
+ */
18
+ export interface HydrationAssetServiceConfig {
19
+ srcDir: string;
20
+ routerAdapter?: ReactRouterAdapter;
21
+ assetProcessingService: AssetProcessingService;
22
+ bundleService: BundleService;
23
+ hmrPageMetadataCache?: HmrPageMetadataCache;
24
+ }
25
+ type PageDependencyOptions = {
26
+ pagePath: string;
27
+ componentName: string;
28
+ importPath: string;
29
+ pageModuleUrlExpression: string;
30
+ bundleOptions: Record<string, unknown>;
31
+ hmrEnabled: boolean;
32
+ useBrowserRuntimeImports: boolean;
33
+ isMdx: boolean;
34
+ };
35
+ export declare function getIslandComponentKey(componentFile: string, config?: EcoComponentConfig): string;
36
+ /**
37
+ * Manages the creation of client-side hydration assets for React pages and component islands.
38
+ */
39
+ export declare class HydrationAssetService {
40
+ private readonly config;
41
+ private static readonly ROUTER_PAGE_GROUPED_BUNDLE_ID;
42
+ constructor(config: HydrationAssetServiceConfig);
43
+ private getIslandBundleName;
44
+ private getIslandHydrationName;
45
+ private getRouterPageGroupedEntryName;
46
+ /**
47
+ * Resolves the browser import path used for a React-owned page or island module.
48
+ *
49
+ * @remarks
50
+ * When HMR is enabled, registers the source file as an HMR entrypoint and returns
51
+ * that URL. Otherwise returns the static resolved-assets path for the generated
52
+ * asset name.
53
+ */
54
+ resolveAssetImportPath(pagePath: string, assetName: string): Promise<string>;
55
+ /**
56
+ * Creates the page-owned route entry asset for hydration and client navigation.
57
+ */
58
+ createPageDependencies(options: PageDependencyOptions): AssetDefinition[];
59
+ /**
60
+ * Builds client-side assets for a React component island.
61
+ *
62
+ * Includes the bundled component entry and a shared hydration bootstrap script.
63
+ *
64
+ * @param componentFile - Absolute path to the component source file
65
+ * @param config - Optional component config with identity attribution
66
+ * @returns Processed assets ready for injection
67
+ */
68
+ buildComponentRenderAssets(componentFile: string, config?: EcoComponentConfig): Promise<ProcessedAsset[]>;
69
+ /**
70
+ * Creates the page browser graph dependency declarations for a React page.
71
+ *
72
+ * @remarks
73
+ * Chooses shared vendor import URLs when HMR is on, when running a non-production
74
+ * hosted runtime with HMR off, or when a router adapter is configured (router
75
+ * pages always externalize to shared runtimes). Production non-router pages
76
+ * may inline React into the page bundle instead.
77
+ *
78
+ * @param pagePath - Absolute file path of the page
79
+ * @param isMdx - Whether the page is an MDX file
80
+ * @param declaredModules - Explicitly declared browser module specifiers
81
+ */
82
+ createPageBrowserGraphDependencies(pagePath: string, isMdx: boolean, declaredModules: string[]): Promise<AssetDefinition[]>;
83
+ }
84
+ export {};