@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
@@ -1,657 +0,0 @@
1
- import path from "node:path";
2
- import { HmrStrategy, HmrStrategyType } from "@ecopages/core/hmr/hmr-strategy";
3
- import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
4
- import { createBrowserRuntimePlugin } from "@ecopages/core/build/browser-runtime-plugin";
5
- import { FileNotFoundError, fileSystem } from "@ecopages/file-system";
6
- import { Logger } from "@ecopages/logger";
7
- import { injectHmrHandler } from "./utils/hmr-scripts.js";
8
- import { createClientGraphBoundaryPlugin } from "./utils/client-graph-boundary-plugin.js";
9
- import { ClientGraphBoundaryCache } from "./utils/client-graph-boundary-cache.js";
10
- import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from "./utils/declared-modules.js";
11
- import { someInConfigTree } from "./utils/component-config-traversal.js";
12
- import { createReactMdxLoaderPlugin } from "./utils/react-mdx-loader-plugin.js";
13
- import { getReactClientGraphAllowSpecifiers } from "./utils/react-runtime-alias-map.js";
14
- import { PagesIndex } from "./services/pages-index.js";
15
- const appLogger = new Logger("[ReactHmrStrategy]");
16
- class ReactHmrStrategy extends HmrStrategy {
17
- type = HmrStrategyType.INTEGRATION;
18
- mdxCompilerOptions;
19
- ownedTemplateExtensions;
20
- allTemplateExtensions;
21
- async importNodePageModule(entrypointPath) {
22
- return await this.context.importServerModule(entrypointPath);
23
- }
24
- /**
25
- * Creates a new React HMR strategy instance.
26
- *
27
- * @param options - React HMR runtime services and behavior flags.
28
- */
29
- context;
30
- pageMetadataCache;
31
- explicitGraphEnabled;
32
- runtimeManifest;
33
- clientGraphBoundaryCache;
34
- pagesIndex;
35
- constructor(options) {
36
- super();
37
- this.context = options.context;
38
- this.pageMetadataCache = options.pageMetadataCache;
39
- this.runtimeManifest = options.runtimeManifest;
40
- this.explicitGraphEnabled = options.explicitGraphEnabled ?? false;
41
- this.clientGraphBoundaryCache = options.clientGraphBoundaryCache ?? new ClientGraphBoundaryCache();
42
- this.pagesIndex = new PagesIndex({
43
- pagesDir: this.context.getPagesDir(),
44
- extensions: options.allTemplateExtensions,
45
- isPageEntrypoint: (file) => this.isPageEntrypoint(file)
46
- });
47
- this.mdxCompilerOptions = options.mdxCompilerOptions;
48
- this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? [".tsx"]);
49
- this.allTemplateExtensions = [...options.allTemplateExtensions ?? [".tsx"]].sort(
50
- (a, b) => b.length - a.length
51
- );
52
- }
53
- /**
54
- * Returns build plugins for React HMR bundling.
55
- *
56
- * Includes the client graph boundary plugin to prevent undeclared imports
57
- * (including `node:*`) from breaking the browser bundle.
58
- *
59
- * @remarks
60
- * HMR builds receive the React runtime manifest and rewrite manifest-owned
61
- * runtime imports to concrete asset URLs before module resolution.
62
- */
63
- getBuildPlugins(declaredModules) {
64
- const allowSpecifiers = getReactClientGraphAllowSpecifiers(
65
- this.runtimeManifest.assets.map((asset) => asset.specifier)
66
- );
67
- const runtimeRewritePlugin = createBrowserRuntimePlugin({
68
- name: "react-hmr-runtime-import-rewrite",
69
- manifest: this.runtimeManifest
70
- });
71
- return [
72
- createClientGraphBoundaryPlugin({
73
- absWorkingDir: path.dirname(this.context.getSrcDir()),
74
- alwaysAllowSpecifiers: allowSpecifiers,
75
- declaredModules,
76
- cache: this.clientGraphBoundaryCache
77
- }),
78
- ...runtimeRewritePlugin ? [runtimeRewritePlugin] : [],
79
- ...this.context.getPlugins()
80
- ];
81
- }
82
- isReactEntrypoint(filePath) {
83
- if (filePath.endsWith(".mdx")) {
84
- return this.mdxCompilerOptions !== void 0;
85
- }
86
- if (!filePath.endsWith(".tsx")) {
87
- return false;
88
- }
89
- const templateExtension = this.resolveTemplateExtension(filePath);
90
- if (templateExtension && templateExtension !== ".tsx") {
91
- return this.ownedTemplateExtensions.has(templateExtension);
92
- }
93
- if (!this.isRouteTemplate(filePath)) {
94
- return true;
95
- }
96
- if (!templateExtension) {
97
- return false;
98
- }
99
- return this.ownedTemplateExtensions.has(templateExtension);
100
- }
101
- /**
102
- * Returns true when a route file uses a compound extension like `page.foo.tsx`.
103
- *
104
- * @remarks
105
- * React integration owns plain `.tsx` route templates. Compound extensions in
106
- * pages/layouts are integration-specific route templates and should not be
107
- * claimed by React HMR strategy.
108
- */
109
- isRouteTemplate(filePath) {
110
- return filePath.startsWith(this.context.getPagesDir()) || filePath.startsWith(this.context.getLayoutsDir());
111
- }
112
- resolveTemplateExtension(filePath) {
113
- return this.allTemplateExtensions.find((extension) => filePath.endsWith(extension));
114
- }
115
- ownsWatchedEntrypoint(filePath) {
116
- return this.pageMetadataCache.ownsEntrypoint(filePath);
117
- }
118
- configContainsFile(config, filePath) {
119
- const resolvedFilePath = path.resolve(filePath);
120
- return someInConfigTree(config, (node) => {
121
- if (!node.__eco?.file) {
122
- return false;
123
- }
124
- return path.resolve(node.__eco.file) === resolvedFilePath;
125
- });
126
- }
127
- pageModuleRequiresLayoutRefresh(pageModule, filePath) {
128
- return [pageModule.default?.config, pageModule.config].some((config) => {
129
- return this.configContainsFile(config?.layout?.config, filePath);
130
- });
131
- }
132
- async hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets) {
133
- for (const target of requestedTargets) {
134
- if (!this.isPageEntrypoint(target.entrypointPath)) {
135
- continue;
136
- }
137
- const pageModule = await this.importNodePageModule(target.entrypointPath);
138
- if (this.pageModuleRequiresLayoutRefresh(pageModule, changedFilePath)) {
139
- return true;
140
- }
141
- }
142
- return false;
143
- }
144
- /**
145
- * Determines if the file is a React/MDX entrypoint that's registered for HMR.
146
- *
147
- * Uses a three-way decision strategy for selective invalidation:
148
- * 1. If the file is a watched entrypoint, check if React owns it
149
- * 2. If the file is a dependency of watched entrypoints (via dependency graph),
150
- * check if any affected entrypoints are React-owned. Returns false if hits
151
- * exist but none are owned (prevents unnecessary rebuilds).
152
- * 3. Otherwise, check if the file itself is a React entrypoint template
153
- *
154
- * @param filePath - Absolute path to the changed file
155
- * @returns True if this file should trigger React HMR rebuilds
156
- */
157
- matches(filePath) {
158
- const watchedFiles = this.context.getWatchedFiles();
159
- appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
160
- if (watchedFiles.size === 0) {
161
- return false;
162
- }
163
- if (watchedFiles.has(filePath)) {
164
- return this.ownsWatchedEntrypoint(filePath);
165
- }
166
- const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(filePath);
167
- if (dependencyHits.size > 0) {
168
- for (const entrypoint of dependencyHits) {
169
- if (this.ownsWatchedEntrypoint(entrypoint)) {
170
- return true;
171
- }
172
- }
173
- return false;
174
- }
175
- return this.isReactEntrypoint(filePath);
176
- }
177
- /**
178
- * Checks if a file is a layout file.
179
- *
180
- * Layout files require special HMR handling because they wrap multiple pages and affect
181
- * the entire page structure. When a layout changes, we trigger a 'layout-update' event
182
- * instead of a regular 'update' event, which instructs the browser to perform a full
183
- * page reload (or clear cache and re-render) rather than attempting module-level HMR.
184
- *
185
- * @param filePath - Absolute path to the file
186
- * @returns True if the file is in the layouts directory
187
- */
188
- isLayoutFile(filePath) {
189
- return filePath.startsWith(this.context.getLayoutsDir());
190
- }
191
- isPageEntrypoint(filePath) {
192
- return filePath.startsWith(this.context.getPagesDir()) && this.isReactEntrypoint(filePath);
193
- }
194
- getEntrypointOutput(entrypointPath) {
195
- const srcDir = this.context.getSrcDir();
196
- const relativePath = path.relative(srcDir, entrypointPath);
197
- const relativePathJs = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, ".js");
198
- const encodedPathJs = this.encodeDynamicSegments(relativePathJs);
199
- const outputPath = path.join(this.context.getDistDir(), encodedPathJs);
200
- const outputUrl = `/${path.join(RESOLVED_ASSETS_DIR, "_hmr", encodedPathJs).split(path.sep).join("/")}`;
201
- return { outputPath, outputUrl };
202
- }
203
- getRolldownEntryKey(entrypointPath) {
204
- const srcDir = this.context.getSrcDir();
205
- const relativePath = path.relative(srcDir, entrypointPath);
206
- const relativePathNoExt = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, "");
207
- return relativePathNoExt;
208
- }
209
- getTempFileBasename(entrypointPath) {
210
- const srcDir = this.context.getSrcDir();
211
- const relativePath = path.relative(srcDir, entrypointPath);
212
- const relativePathNoExt = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, "");
213
- const encodedPath = this.encodeDynamicSegments(relativePathNoExt);
214
- return path.basename(encodedPath);
215
- }
216
- async collectReactPageBuildTargets() {
217
- await this.pagesIndex.refresh();
218
- const indexed = this.pagesIndex.list();
219
- const targets = /* @__PURE__ */ new Map();
220
- for (const entrypointPath of indexed) {
221
- this.pageMetadataCache.markOwnedEntrypoint(entrypointPath);
222
- targets.set(entrypointPath, {
223
- entrypointPath,
224
- outputUrl: this.getEntrypointOutput(entrypointPath).outputUrl
225
- });
226
- }
227
- return Array.from(targets.values()).sort(
228
- (left, right) => left.entrypointPath.localeCompare(right.entrypointPath)
229
- );
230
- }
231
- /**
232
- * Expands one HMR request into the full React page build cohort when needed.
233
- *
234
- * @remarks
235
- * Page and layout changes need one shared rebuild pass so sibling routes keep
236
- * a consistent client module graph. Non-page changes that do not touch a page
237
- * cohort can stay scoped to the originally requested targets.
238
- */
239
- async resolveBuildTargets(requestedTargets, changedFilePath) {
240
- const requestedPageTargets = requestedTargets.filter((target) => this.isPageEntrypoint(target.entrypointPath));
241
- const shouldGroupPageBuilds = this.isLayoutFile(changedFilePath) || requestedPageTargets.length > 0;
242
- if (!shouldGroupPageBuilds) {
243
- return [];
244
- }
245
- const groupedTargets = new Map(requestedPageTargets.map((target) => [target.entrypointPath, target]));
246
- for (const target of await this.collectReactPageBuildTargets()) {
247
- groupedTargets.set(target.entrypointPath, target);
248
- }
249
- return Array.from(groupedTargets.values()).sort(
250
- (left, right) => left.entrypointPath.localeCompare(right.entrypointPath)
251
- );
252
- }
253
- partitionBuildTargets(requestedTargets, groupedPageTargets) {
254
- if (groupedPageTargets.length === 0) {
255
- return {
256
- pageTargets: [],
257
- nonPageTargets: requestedTargets
258
- };
259
- }
260
- const groupedPageEntrypoints = new Set(groupedPageTargets.map((target) => target.entrypointPath));
261
- return {
262
- pageTargets: groupedPageTargets,
263
- nonPageTargets: requestedTargets.filter(
264
- (target) => !groupedPageEntrypoints.has(target.entrypointPath) && !this.isPageEntrypoint(target.entrypointPath)
265
- )
266
- };
267
- }
268
- /**
269
- * Processes a React file change by rebuilding affected React entrypoints.
270
- *
271
- * Uses a three-way decision strategy for selective invalidation:
272
- * 1. Changed file is a watched entrypoint: rebuild only that entrypoint
273
- * 2. Dependency graph has hits: rebuild only affected React-owned entrypoints.
274
- * If hits exist but none map to React-owned entrypoints, return 'none' to
275
- * prevent unnecessary rebuilds.
276
- * 3. Dependency graph miss: fall back to rebuilding all watched entrypoints
277
- *
278
- * For layout files, broadcasts a 'layout-update' event to trigger full page reload.
279
- * For regular components/pages, broadcasts 'update' events for module-level HMR.
280
- *
281
- * @param _filePath - Absolute path to the changed file
282
- * @returns Action to broadcast update events (layout-update for layouts, update for components)
283
- */
284
- async process(_filePath) {
285
- appLogger.debug(`Processing ${_filePath}`);
286
- const watchedFiles = this.context.getWatchedFiles();
287
- if (watchedFiles.size === 0) {
288
- appLogger.debug(`No watched files`);
289
- return { type: "none" };
290
- }
291
- const isLayout = this.isLayoutFile(_filePath);
292
- const isChangedPageEntrypoint = this.isPageEntrypoint(_filePath);
293
- if (isLayout) {
294
- appLogger.debug(`Detected layout file change: ${_filePath}`);
295
- }
296
- const changedEntrypointOutput = watchedFiles.get(_filePath);
297
- if (changedEntrypointOutput && !this.ownsWatchedEntrypoint(_filePath)) {
298
- if (this.isReactEntrypoint(_filePath)) {
299
- this.pageMetadataCache.markOwnedEntrypoint(_filePath);
300
- } else {
301
- appLogger.debug(`Skipping non-React watched entrypoint: ${_filePath}`);
302
- return { type: "none" };
303
- }
304
- }
305
- const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(_filePath);
306
- const hasDependencyHits = dependencyHits.size > 0;
307
- const affectedEntrypoints = /* @__PURE__ */ new Map();
308
- let hasOwnedLayoutDependencyHit = false;
309
- let layoutOwnedPageTargets = [];
310
- let hasLayoutOwnedRequestedTarget = false;
311
- if (hasDependencyHits && !changedEntrypointOutput) {
312
- for (const entrypoint of dependencyHits) {
313
- const outputUrl = watchedFiles.get(entrypoint);
314
- if (outputUrl && this.ownsWatchedEntrypoint(entrypoint)) {
315
- affectedEntrypoints.set(entrypoint, outputUrl);
316
- continue;
317
- }
318
- if (this.isLayoutFile(entrypoint) && this.ownsWatchedEntrypoint(entrypoint)) {
319
- hasOwnedLayoutDependencyHit = true;
320
- }
321
- }
322
- if (affectedEntrypoints.size === 0 && !hasOwnedLayoutDependencyHit) {
323
- appLogger.debug(`Dependency hits found but none map to React-owned watched entrypoints`);
324
- return { type: "none" };
325
- }
326
- }
327
- if (changedEntrypointOutput && !isLayout && !isChangedPageEntrypoint) {
328
- layoutOwnedPageTargets = await this.collectReactPageBuildTargets();
329
- hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(
330
- _filePath,
331
- layoutOwnedPageTargets
332
- );
333
- }
334
- const requestedTargets = changedEntrypointOutput ? hasLayoutOwnedRequestedTarget ? [{ entrypointPath: _filePath, outputUrl: changedEntrypointOutput }, ...layoutOwnedPageTargets] : [{ entrypointPath: _filePath, outputUrl: changedEntrypointOutput }] : hasOwnedLayoutDependencyHit ? await this.collectReactPageBuildTargets() : hasDependencyHits ? Array.from(affectedEntrypoints, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl })) : Array.from(watchedFiles, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }));
335
- const groupedPageTargets = await this.resolveBuildTargets(requestedTargets, _filePath);
336
- const { pageTargets, nonPageTargets } = this.partitionBuildTargets(requestedTargets, groupedPageTargets);
337
- if (!changedEntrypointOutput) {
338
- hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(_filePath, requestedTargets);
339
- }
340
- const requiresLayoutRefresh = isLayout || hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
341
- const updates = [];
342
- const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
343
- if (pageTargets.length > 1) {
344
- appLogger.debug(`Bundling ${pageTargets.length} React page entrypoints together`);
345
- const rebuiltOutputs = await this.bundleReactEntrypoints(pageTargets);
346
- for (const outputUrl of rebuiltOutputs) {
347
- if (requestedOutputUrls.has(outputUrl)) {
348
- updates.push(outputUrl);
349
- }
350
- }
351
- } else {
352
- for (const { entrypointPath, outputUrl } of pageTargets) {
353
- appLogger.debug(`Bundling ${entrypointPath}`);
354
- const success = await this.bundleReactEntrypoint(entrypointPath, outputUrl);
355
- if (success && requestedOutputUrls.has(outputUrl)) {
356
- updates.push(outputUrl);
357
- }
358
- }
359
- }
360
- for (const { entrypointPath, outputUrl } of nonPageTargets) {
361
- if (!this.isReactEntrypoint(entrypointPath)) {
362
- continue;
363
- }
364
- appLogger.debug(`Bundling ${entrypointPath}`);
365
- const success = await this.bundleReactEntrypoint(entrypointPath, outputUrl);
366
- if (success && requestedOutputUrls.has(outputUrl)) {
367
- updates.push(outputUrl);
368
- }
369
- }
370
- if (updates.length > 0) {
371
- if (requiresLayoutRefresh) {
372
- appLogger.debug(`Layout update detected, sending layout-update event`);
373
- return {
374
- type: "broadcast",
375
- events: [
376
- {
377
- type: "layout-update"
378
- }
379
- ]
380
- };
381
- }
382
- appLogger.debug(`Broadcasting ${updates.length} updates`);
383
- return {
384
- type: "broadcast",
385
- events: updates.map((path2) => ({
386
- type: "update",
387
- path: path2,
388
- timestamp: Date.now()
389
- }))
390
- };
391
- }
392
- appLogger.debug(`No updates generated`);
393
- return { type: "none" };
394
- }
395
- /**
396
- * Bundles a single React/MDX entrypoint with HMR support.
397
- *
398
- * After successful bundling, populates the entrypoint dependency graph with
399
- * the build's dependency metadata. This enables selective invalidation on
400
- * subsequent file changes, so only entrypoints affected by a changed
401
- * dependency are rebuilt.
402
- *
403
- * @param entrypointPath - Absolute path to the source file
404
- * @param outputUrl - URL path for the bundled file
405
- * @returns True if bundling was successful
406
- */
407
- async bundleReactEntrypoint(entrypointPath, outputUrl) {
408
- try {
409
- const isMdx = entrypointPath.endsWith(".mdx");
410
- const { outputPath } = this.getEntrypointOutput(entrypointPath);
411
- const tempDir = path.dirname(outputPath);
412
- const cachedDeclared = this.pageMetadataCache.getDeclaredModules(entrypointPath);
413
- let entrypointDeclaredModules;
414
- let declaredModules;
415
- if (cachedDeclared) {
416
- entrypointDeclaredModules = cachedDeclared;
417
- declaredModules = cachedDeclared;
418
- } else {
419
- entrypointDeclaredModules = isMdx ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
420
- this.pageMetadataCache.setDeclaredModules(entrypointPath, entrypointDeclaredModules);
421
- declaredModules = entrypointDeclaredModules;
422
- }
423
- const plugins = this.getBuildPlugins(declaredModules);
424
- if (isMdx && this.mdxCompilerOptions) {
425
- const mdxPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
426
- plugins.unshift(mdxPlugin);
427
- }
428
- await this.clearHmrOutdir(tempDir);
429
- const result = await this.context.getBrowserBundleService().bundle({
430
- profile: "hmr-entrypoint",
431
- entrypoints: [entrypointPath],
432
- outdir: tempDir,
433
- naming: `[name].[hash].tmp`,
434
- plugins,
435
- minify: false
436
- });
437
- if (!result.success) {
438
- appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
439
- return false;
440
- }
441
- if (result.dependencyGraph?.entrypoints) {
442
- const dependencyGraph = this.context.getEntrypointDependencyGraph();
443
- for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
444
- dependencyGraph.setEntrypointDependencies(entrypoint, deps);
445
- }
446
- }
447
- const tempFile = result.outputs[0]?.path;
448
- if (!tempFile) {
449
- appLogger.error(`No output file generated for ${entrypointPath}`);
450
- return false;
451
- }
452
- const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
453
- if (!resolvedTempFile) {
454
- appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
455
- return false;
456
- }
457
- const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
458
- return processed;
459
- } catch (error) {
460
- appLogger.error(`Error bundling ${entrypointPath}:`, error);
461
- return false;
462
- }
463
- }
464
- /**
465
- * Bundles multiple React/MDX entrypoints in a single build pass.
466
- *
467
- * Uses code splitting to share common dependencies across entrypoints.
468
- * After successful bundling, populates the entrypoint dependency graph with
469
- * the build's dependency metadata for selective invalidation.
470
- *
471
- * @param entrypoints - Array of entrypoint paths and their output URLs
472
- * @returns Array of output URLs that were successfully built
473
- */
474
- async bundleReactEntrypoints(entrypoints) {
475
- try {
476
- const declaredModules = /* @__PURE__ */ new Set();
477
- let shouldEnableMdx = false;
478
- for (const { entrypointPath } of entrypoints) {
479
- const entrypointDeclaredModules = this.pageMetadataCache.getDeclaredModules(entrypointPath) ? this.pageMetadataCache.getDeclaredModules(entrypointPath) : entrypointPath.endsWith(".mdx") ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
480
- this.pageMetadataCache.setDeclaredModules(entrypointPath, entrypointDeclaredModules);
481
- for (const declaredModule of entrypointDeclaredModules) {
482
- declaredModules.add(declaredModule);
483
- }
484
- if (entrypointPath.endsWith(".mdx")) {
485
- shouldEnableMdx = true;
486
- }
487
- }
488
- const plugins = this.getBuildPlugins([...declaredModules]);
489
- if (shouldEnableMdx && this.mdxCompilerOptions) {
490
- plugins.unshift(createReactMdxLoaderPlugin(this.mdxCompilerOptions));
491
- }
492
- await this.clearHmrOutdir(this.context.getDistDir());
493
- const entryNameByPath = /* @__PURE__ */ new Map();
494
- for (const { entrypointPath } of entrypoints) {
495
- entryNameByPath.set(entrypointPath, {
496
- key: this.getRolldownEntryKey(entrypointPath),
497
- basename: this.getTempFileBasename(entrypointPath)
498
- });
499
- }
500
- const result = await this.context.getBrowserBundleService().bundle({
501
- profile: "hmr-entrypoint",
502
- entrypoints: Object.fromEntries(
503
- entrypoints.map(({ entrypointPath }) => [entryNameByPath.get(entrypointPath).key, entrypointPath])
504
- ),
505
- outdir: this.context.getDistDir(),
506
- naming: "[name].[hash].tmp",
507
- splitting: true,
508
- plugins,
509
- minify: false
510
- });
511
- if (!result.success) {
512
- appLogger.error(`Failed to build grouped React entrypoints:`, result.logs);
513
- return [];
514
- }
515
- if (result.dependencyGraph?.entrypoints) {
516
- const dependencyGraph = this.context.getEntrypointDependencyGraph();
517
- for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
518
- dependencyGraph.setEntrypointDependencies(entrypoint, deps);
519
- }
520
- }
521
- const updatedOutputs = [];
522
- for (const { entrypointPath, outputUrl } of entrypoints) {
523
- const { outputPath } = this.getEntrypointOutput(entrypointPath);
524
- const { basename: tempBasename, key: entryKey } = entryNameByPath.get(entrypointPath);
525
- const expectedSubdir = path.join(this.context.getDistDir(), path.dirname(entryKey));
526
- const tempOutput = result.outputs.find((output) => {
527
- return path.dirname(output.path) === expectedSubdir && path.basename(output.path).startsWith(`${tempBasename}.`) && path.basename(output.path).includes(".tmp");
528
- })?.path;
529
- const resolvedTempOutput = tempOutput ? await this.resolveTempOutputPath(tempOutput) : await this.resolveTempOutputPath(path.join(expectedSubdir, `${tempBasename}.[hash].tmp.js`));
530
- if (!resolvedTempOutput) {
531
- appLogger.debug(`Missing grouped temp output for ${outputUrl}`);
532
- continue;
533
- }
534
- const processed = await this.processOutput(resolvedTempOutput, outputPath, outputUrl);
535
- if (processed) {
536
- updatedOutputs.push(outputUrl);
537
- }
538
- }
539
- return updatedOutputs;
540
- } catch (error) {
541
- appLogger.error(`Error bundling grouped React entrypoints:`, error);
542
- return [];
543
- }
544
- }
545
- async resolveTempOutputPath(tempPath) {
546
- if (fileSystem.exists(tempPath)) {
547
- return tempPath;
548
- }
549
- if (!tempPath.includes("[hash]")) {
550
- return null;
551
- }
552
- const directory = path.dirname(tempPath);
553
- const pattern = path.basename(tempPath).replaceAll("[hash]", "*");
554
- const matches = await fileSystem.glob([pattern], { cwd: directory });
555
- if (matches.length === 0) {
556
- return null;
557
- }
558
- return path.isAbsolute(matches[0]) ? matches[0] : path.join(directory, matches[0]);
559
- }
560
- /**
561
- * Clears stale HMR output from a directory before a rebuild.
562
- *
563
- * Only removes:
564
- * - `*.tmp.js` files (the per-build bundler output the strategy owns)
565
- * - the `chunks/` subdirectory (the bundler's splitting target)
566
- *
567
- * The HMR runtime script (`_hmr_runtime.js`) and any user-authored
568
- * assets in the outdir are preserved. This is the minimal set of
569
- * files that, if left from a previous build, can cause the bundler
570
- * to emit `ENOENT` for chunk references that point to entrypoints
571
- * whose hash has since changed.
572
- */
573
- async clearHmrOutdir(outdir) {
574
- if (!fileSystem.exists(outdir)) {
575
- return;
576
- }
577
- const tempFiles = await fileSystem.glob(["**/*.tmp.js"], { cwd: outdir });
578
- await Promise.all(
579
- tempFiles.map((relativePath) => {
580
- const absolutePath = path.isAbsolute(relativePath) ? relativePath : path.join(outdir, relativePath);
581
- return fileSystem.removeAsync(absolutePath).catch(() => void 0);
582
- })
583
- );
584
- const chunksDir = path.join(outdir, "chunks");
585
- if (fileSystem.exists(chunksDir)) {
586
- await fileSystem.removeAsync(chunksDir).catch(() => void 0);
587
- }
588
- }
589
- /**
590
- * Encodes dynamic route segments (brackets) in file paths.
591
- * Converts `[slug]` to `_slug_` to avoid filesystem issues.
592
- */
593
- encodeDynamicSegments(filepath) {
594
- return filepath.replace(/\[([^\]]+)\]/g, "_$1_");
595
- }
596
- rewriteChunkImportUrls(code) {
597
- const hmrChunkBaseUrl = `/${path.join(RESOLVED_ASSETS_DIR, "_hmr").split(path.sep).join("/")}`;
598
- return code.replace(/(['"])(?:\.\.\/)+(chunk-[^'"]+\.js)\1/g, (_match, quote, chunkFile) => {
599
- return `${quote}${hmrChunkBaseUrl}/${chunkFile}${quote}`;
600
- });
601
- }
602
- isMissingTempOutputError(error) {
603
- if (error instanceof FileNotFoundError) {
604
- return true;
605
- }
606
- if (!(error instanceof Error)) {
607
- return false;
608
- }
609
- if (error.message.includes("not found") || error.message.includes("ENOENT")) {
610
- return true;
611
- }
612
- const errorCause = error.cause;
613
- if (errorCause instanceof FileNotFoundError) {
614
- return true;
615
- }
616
- return typeof errorCause === "object" && errorCause !== null && "code" in errorCause && errorCause.code === "ENOENT";
617
- }
618
- /**
619
- * Processes bundled output and injects the React HMR handler.
620
- * Writes to temp file first, then renames atomically to avoid conflicts.
621
- *
622
- * @param tempPath - Path to the temporary bundled file
623
- * @param finalPath - Final destination path
624
- * @param url - URL path for logging
625
- * @returns True if processing was successful
626
- */
627
- async processOutput(tempPath, finalPath, url) {
628
- if (!fileSystem.exists(tempPath)) {
629
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
630
- return false;
631
- }
632
- try {
633
- let code = await fileSystem.readFile(tempPath);
634
- code = this.rewriteChunkImportUrls(code);
635
- code = injectHmrHandler(code);
636
- await fileSystem.writeAsync(finalPath, code);
637
- await fileSystem.removeAsync(tempPath).catch(() => {
638
- });
639
- appLogger.debug(`Processed ${url} with HMR handler`);
640
- return true;
641
- } catch (error) {
642
- if (this.isMissingTempOutputError(error)) {
643
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
644
- await fileSystem.removeAsync(tempPath).catch(() => {
645
- });
646
- return false;
647
- }
648
- appLogger.error(`Error processing output for ${url}:`, error);
649
- await fileSystem.removeAsync(tempPath).catch(() => {
650
- });
651
- return false;
652
- }
653
- }
654
- }
655
- export {
656
- ReactHmrStrategy
657
- };