@ecopages/react 0.2.0-rc.1 → 0.2.0-rc.10

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 (83) hide show
  1. package/README.md +68 -14
  2. package/package.json +17 -5
  3. package/src/app/client-only.js +3 -8
  4. package/src/bundling/bundle.js +4 -1
  5. package/src/bundling/runtime-alias-map.d.ts +0 -1
  6. package/src/bundling/runtime-alias-map.js +1 -4
  7. package/src/bundling/runtime-bundle.d.ts +9 -2
  8. package/src/bundling/runtime-bundle.js +27 -16
  9. package/src/bundling/runtime-modules.d.ts +21 -0
  10. package/src/bundling/runtime-modules.js +25 -0
  11. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  12. package/src/client-graph/ast-transform-eco-page.js +71 -0
  13. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  14. package/src/client-graph/ast-transform-import-edits.js +75 -0
  15. package/src/client-graph/ast-transform-walk-imports.d.ts +19 -0
  16. package/src/client-graph/ast-transform-walk-imports.js +103 -0
  17. package/src/client-graph/ast-transform.d.ts +1 -7
  18. package/src/client-graph/ast-transform.js +42 -378
  19. package/src/client-graph/ast-walk.d.ts +10 -0
  20. package/src/client-graph/ast-walk.js +26 -0
  21. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +8 -0
  22. package/src/client-graph/boundary-plugin-read-file-inline.js +45 -0
  23. package/src/client-graph/boundary-plugin-transform.d.ts +18 -0
  24. package/src/client-graph/boundary-plugin-transform.js +61 -0
  25. package/src/client-graph/boundary-plugin.d.ts +0 -20
  26. package/src/client-graph/boundary-plugin.js +16 -98
  27. package/src/client-graph/reachability-analyzer.d.ts +4 -36
  28. package/src/client-graph/reachability-analyzer.js +23 -483
  29. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  30. package/src/client-graph/reachability-client-roots.js +59 -0
  31. package/src/client-graph/reachability-export-names.d.ts +5 -0
  32. package/src/client-graph/reachability-export-names.js +34 -0
  33. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  34. package/src/client-graph/reachability-fallback-roots.js +71 -0
  35. package/src/client-graph/reachability-preload.d.ts +10 -0
  36. package/src/client-graph/reachability-preload.js +30 -0
  37. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  38. package/src/client-graph/reachability-top-level-index.js +93 -0
  39. package/src/client-graph/reachability-traverse.d.ts +7 -0
  40. package/src/client-graph/reachability-traverse.js +201 -0
  41. package/src/client-graph/specifier-classification.d.ts +3 -2
  42. package/src/client-graph/specifier-classification.js +6 -2
  43. package/src/content/collection-component-cache.d.ts +25 -0
  44. package/src/content/collection-component-cache.js +62 -0
  45. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  46. package/src/hmr/hmr-strategy-process.js +83 -0
  47. package/src/hmr/hmr-strategy.d.ts +3 -0
  48. package/src/hmr/hmr-strategy.js +47 -86
  49. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +1 -0
  50. package/src/hmr/react-hmr-dev-transform-plugins.js +4 -1
  51. package/src/hydration/browser/island-hydration.d.ts +82 -0
  52. package/src/hydration/browser/island-hydration.js +247 -0
  53. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  54. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  55. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  56. package/src/hydration/browser/page-hydration-module.js +17 -0
  57. package/src/hydration/browser/page-hydration.d.ts +54 -0
  58. package/src/hydration/browser/page-hydration.js +177 -0
  59. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  60. package/src/hydration/hydration-asset.d.ts +21 -1
  61. package/src/hydration/hydration-asset.js +54 -24
  62. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  63. package/src/hydration/hydration-lifecycle.test.browser.js +409 -0
  64. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  65. package/src/hydration/hydration-page-entry-source.js +87 -0
  66. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  67. package/src/hydration/hydration-script-compiler.js +213 -0
  68. package/src/hydration/page-data-reader.d.ts +0 -14
  69. package/src/hydration/page-data-reader.js +1 -47
  70. package/src/mdx/mdx-loader-plugin.d.ts +5 -1
  71. package/src/mdx/mdx-loader-plugin.js +4 -2
  72. package/src/plugin/react.plugin.js +8 -1
  73. package/src/plugin/react.types.d.ts +11 -2
  74. package/src/render/component-ssr.d.ts +17 -0
  75. package/src/render/component-ssr.js +19 -1
  76. package/src/render/react-renderer.d.ts +2 -1
  77. package/src/render/react-renderer.js +5 -1
  78. package/src/render/unified-layout-composition.d.ts +2 -0
  79. package/src/render/unified-layout-composition.js +5 -1
  80. package/src/hydration/hydration-scripts.d.ts +0 -104
  81. package/src/hydration/hydration-scripts.js +0 -483
  82. package/src/hydration/hydration-scripts.test.browser.js +0 -199
  83. /package/src/hydration/{hydration-scripts.test.browser.d.ts → compiled-page-hydration-options.js} +0 -0
@@ -0,0 +1,83 @@
1
+ import path from 'node:path';
2
+ export function scanDependencyHits(ctx, changedEntrypointOutput) {
3
+ const dependencyHits = ctx.getDependencyEntrypoints(ctx.resolvedFilePath);
4
+ const affectedEntrypoints = new Map();
5
+ let hasOwnedLayoutDependencyHit = false;
6
+ if (dependencyHits.size === 0 || changedEntrypointOutput) {
7
+ return { affectedEntrypoints, hasOwnedLayoutDependencyHit, shouldAbort: false };
8
+ }
9
+ for (const entrypoint of dependencyHits) {
10
+ const resolvedEntrypoint = path.resolve(entrypoint);
11
+ const outputUrl = ctx.watchedFiles.get(resolvedEntrypoint);
12
+ if (outputUrl && (ctx.ownsWatchedEntrypoint(resolvedEntrypoint) || ctx.isDevTransformOutputUrl(outputUrl))) {
13
+ affectedEntrypoints.set(resolvedEntrypoint, outputUrl);
14
+ continue;
15
+ }
16
+ if (ctx.isLayoutFile(resolvedEntrypoint) && ctx.ownsWatchedEntrypoint(resolvedEntrypoint)) {
17
+ hasOwnedLayoutDependencyHit = true;
18
+ }
19
+ }
20
+ const shouldAbort = affectedEntrypoints.size === 0 && !hasOwnedLayoutDependencyHit && !ctx.isLayoutFile(ctx.resolvedFilePath);
21
+ return { affectedEntrypoints, hasOwnedLayoutDependencyHit, shouldAbort };
22
+ }
23
+ export async function resolveRequestedTargets(ctx, changedEntrypointOutput, isLayout, isChangedPageEntrypoint, hasOwnedLayoutDependencyHit, affectedEntrypoints, hasDependencyHits) {
24
+ let layoutOwnedPageTargets = [];
25
+ let hasLayoutOwnedRequestedTarget = false;
26
+ if (changedEntrypointOutput && !isLayout && !isChangedPageEntrypoint) {
27
+ layoutOwnedPageTargets = await ctx.collectReactPageBuildTargets();
28
+ hasLayoutOwnedRequestedTarget = await ctx.hasLayoutOwnedDependencyTarget(ctx.resolvedFilePath, layoutOwnedPageTargets);
29
+ }
30
+ const requestedTargets = changedEntrypointOutput
31
+ ? hasLayoutOwnedRequestedTarget
32
+ ? [{ entrypointPath: ctx.resolvedFilePath, outputUrl: changedEntrypointOutput }, ...layoutOwnedPageTargets]
33
+ : [{ entrypointPath: ctx.resolvedFilePath, outputUrl: changedEntrypointOutput }]
34
+ : hasOwnedLayoutDependencyHit
35
+ ? await ctx.collectReactPageBuildTargets()
36
+ : hasDependencyHits
37
+ ? Array.from(affectedEntrypoints, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }))
38
+ : Array.from(ctx.watchedFiles, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }));
39
+ return { requestedTargets, hasLayoutOwnedRequestedTarget };
40
+ }
41
+ export function collectHmrUpdateUrls(ctx, requestedTargets, pageTargets, nonPageTargets) {
42
+ const updates = [];
43
+ const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
44
+ ctx.queueDevTransformOutputUpdates(pageTargets, requestedOutputUrls, updates);
45
+ for (const { outputUrl } of nonPageTargets) {
46
+ if (!requestedOutputUrls.has(outputUrl)) {
47
+ continue;
48
+ }
49
+ if (ctx.isDevTransformOutputUrl(outputUrl)) {
50
+ updates.push(outputUrl);
51
+ }
52
+ }
53
+ return updates;
54
+ }
55
+ export function buildHmrAction(requiresLayoutRefresh, updates) {
56
+ if (requiresLayoutRefresh) {
57
+ return {
58
+ type: 'broadcast',
59
+ events: [{ type: 'layout-update' }],
60
+ };
61
+ }
62
+ if (updates.length > 0) {
63
+ return {
64
+ type: 'broadcast',
65
+ events: updates.map((path) => ({
66
+ type: 'update',
67
+ path,
68
+ timestamp: Date.now(),
69
+ })),
70
+ };
71
+ }
72
+ return { type: 'none' };
73
+ }
74
+ export function ensureWatchedEntrypointOwnership(ctx, changedEntrypointOutput) {
75
+ if (!changedEntrypointOutput || ctx.ownsWatchedEntrypoint(ctx.resolvedFilePath)) {
76
+ return 'continue';
77
+ }
78
+ if (ctx.isReactEntrypoint(ctx.resolvedFilePath)) {
79
+ ctx.markOwnedEntrypoint(ctx.resolvedFilePath);
80
+ return 'continue';
81
+ }
82
+ return 'abort';
83
+ }
@@ -15,6 +15,7 @@ import { ClientGraphBoundaryCache } from '../client-graph/boundary-cache.js';
15
15
  import type { HmrPageMetadataCache } from './page-metadata-cache.js';
16
16
  export interface ReactHmrStrategyOptions {
17
17
  context: DefaultHmrContext;
18
+ projectRoot?: string;
18
19
  pageMetadataCache: HmrPageMetadataCache;
19
20
  runtimeManifest: BrowserRuntimeManifest;
20
21
  mdxCompilerOptions?: CompileOptions;
@@ -34,6 +35,7 @@ export interface ReactHmrStrategyOptions {
34
35
  export declare class ReactHmrStrategy extends HmrStrategy {
35
36
  readonly type: 100;
36
37
  private mdxCompilerOptions?;
38
+ private readonly projectRoot;
37
39
  private readonly ownedTemplateExtensions;
38
40
  private readonly allTemplateExtensions;
39
41
  private readonly context;
@@ -70,5 +72,6 @@ export declare class ReactHmrStrategy extends HmrStrategy {
70
72
  private collectReactPageBuildTargets;
71
73
  private resolveBuildTargets;
72
74
  private partitionBuildTargets;
75
+ private createProcessContext;
73
76
  process(_filePath: string): Promise<HmrAction>;
74
77
  }
@@ -18,6 +18,7 @@ import { someInConfigTree } from '../client-graph/component-config-traversal.js'
18
18
  import { getReactClientGraphAllowSpecifiers } from '../bundling/runtime-alias-map.js';
19
19
  import { getComponentIdentity } from '@ecopages/core';
20
20
  import { buildReactDevTransformPlugins, resolveReactDeclaredModulesForEntrypoint, } from './react-hmr-dev-transform-plugins.js';
21
+ import { buildHmrAction, collectHmrUpdateUrls, ensureWatchedEntrypointOwnership, resolveRequestedTargets, scanDependencyHits, } from './hmr-strategy-process.js';
21
22
  const appLogger = new Logger('[ReactHmrStrategy]');
22
23
  /**
23
24
  * Strategy for handling React component HMR updates.
@@ -25,6 +26,7 @@ const appLogger = new Logger('[ReactHmrStrategy]');
25
26
  export class ReactHmrStrategy extends HmrStrategy {
26
27
  type = HmrStrategyType.INTEGRATION;
27
28
  mdxCompilerOptions;
29
+ projectRoot;
28
30
  ownedTemplateExtensions;
29
31
  allTemplateExtensions;
30
32
  context;
@@ -38,6 +40,7 @@ export class ReactHmrStrategy extends HmrStrategy {
38
40
  return {
39
41
  pageMetadataCache: this.pageMetadataCache,
40
42
  mdxCompilerOptions: this.mdxCompilerOptions,
43
+ projectRoot: this.projectRoot,
41
44
  getBuildPlugins: (declaredModules) => this.getBuildPlugins(declaredModules),
42
45
  importNodePageModule: (entrypointPath) => this.importNodePageModule(entrypointPath),
43
46
  };
@@ -45,6 +48,7 @@ export class ReactHmrStrategy extends HmrStrategy {
45
48
  constructor(options) {
46
49
  super();
47
50
  this.context = options.context;
51
+ this.projectRoot = options.projectRoot ?? path.dirname(this.context.getSrcDir());
48
52
  this.pageMetadataCache = options.pageMetadataCache;
49
53
  this.runtimeManifest = options.runtimeManifest;
50
54
  this.clientGraphBoundaryCache = options.clientGraphBoundaryCache ?? new ClientGraphBoundaryCache();
@@ -60,8 +64,8 @@ export class ReactHmrStrategy extends HmrStrategy {
60
64
  });
61
65
  return [
62
66
  createClientGraphBoundaryPlugin({
63
- projectRoot: path.dirname(this.context.getSrcDir()),
64
- absWorkingDir: path.dirname(this.context.getSrcDir()),
67
+ projectRoot: this.projectRoot,
68
+ absWorkingDir: this.projectRoot,
65
69
  alwaysAllowSpecifiers: allowSpecifiers,
66
70
  declaredModules,
67
71
  cache: this.clientGraphBoundaryCache,
@@ -242,6 +246,24 @@ export class ReactHmrStrategy extends HmrStrategy {
242
246
  nonPageTargets: requestedTargets.filter((target) => !groupedPageEntrypoints.has(target.entrypointPath) && !this.isPageEntrypoint(target.entrypointPath)),
243
247
  };
244
248
  }
249
+ createProcessContext(resolvedFilePath, watchedFiles) {
250
+ return {
251
+ resolvedFilePath,
252
+ watchedFiles,
253
+ isLayoutFile: (filePath) => this.isLayoutFile(filePath),
254
+ isPageEntrypoint: (filePath) => this.isPageEntrypoint(filePath),
255
+ isReactEntrypoint: (filePath) => this.isReactEntrypoint(filePath),
256
+ ownsWatchedEntrypoint: (filePath) => this.ownsWatchedEntrypoint(filePath),
257
+ isDevTransformOutputUrl: (outputUrl) => this.isDevTransformOutputUrl(outputUrl),
258
+ collectReactPageBuildTargets: () => this.collectReactPageBuildTargets(),
259
+ hasLayoutOwnedDependencyTarget: (changedFilePath, requestedTargets) => this.hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets),
260
+ resolveBuildTargets: (requestedTargets, changedFilePath) => this.resolveBuildTargets(requestedTargets, changedFilePath),
261
+ partitionBuildTargets: (requestedTargets, groupedPageTargets) => this.partitionBuildTargets(requestedTargets, groupedPageTargets),
262
+ queueDevTransformOutputUpdates: (targets, requestedOutputUrls, updates) => this.queueDevTransformOutputUpdates(targets, requestedOutputUrls, updates),
263
+ markOwnedEntrypoint: (filePath) => this.pageMetadataCache.markOwnedEntrypoint(filePath),
264
+ getDependencyEntrypoints: (filePath) => this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(filePath),
265
+ };
266
+ }
245
267
  async process(_filePath) {
246
268
  appLogger.debug(`Processing ${_filePath}`);
247
269
  const resolvedFilePath = path.resolve(_filePath);
@@ -250,102 +272,41 @@ export class ReactHmrStrategy extends HmrStrategy {
250
272
  appLogger.debug(`No watched files`);
251
273
  return { type: 'none' };
252
274
  }
253
- const isLayout = this.isLayoutFile(resolvedFilePath);
254
- const isChangedPageEntrypoint = this.isPageEntrypoint(resolvedFilePath);
275
+ const processContext = this.createProcessContext(resolvedFilePath, watchedFiles);
276
+ const isLayout = processContext.isLayoutFile(resolvedFilePath);
277
+ const isChangedPageEntrypoint = processContext.isPageEntrypoint(resolvedFilePath);
255
278
  if (isLayout) {
256
279
  appLogger.debug(`Detected layout file change: ${resolvedFilePath}`);
257
280
  }
258
281
  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
- }
282
+ if (ensureWatchedEntrypointOwnership(processContext, changedEntrypointOutput) === 'abort') {
283
+ appLogger.debug(`Skipping non-React watched entrypoint: ${resolvedFilePath}`);
284
+ return { type: 'none' };
293
285
  }
294
- if (changedEntrypointOutput && !isLayout && !isChangedPageEntrypoint) {
295
- layoutOwnedPageTargets = await this.collectReactPageBuildTargets();
296
- hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(resolvedFilePath, layoutOwnedPageTargets);
286
+ const dependencyHits = processContext.getDependencyEntrypoints(resolvedFilePath);
287
+ const dependencyScan = scanDependencyHits(processContext, changedEntrypointOutput);
288
+ if (dependencyScan.shouldAbort) {
289
+ appLogger.debug(`Dependency hits found but none map to React-owned watched entrypoints`);
290
+ return { type: 'none' };
297
291
  }
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);
292
+ const { requestedTargets, hasLayoutOwnedRequestedTarget: initialLayoutOwned } = await resolveRequestedTargets(processContext, changedEntrypointOutput, isLayout, isChangedPageEntrypoint, dependencyScan.hasOwnedLayoutDependencyHit, dependencyScan.affectedEntrypoints, dependencyHits.size > 0);
293
+ const groupedPageTargets = await processContext.resolveBuildTargets(requestedTargets, resolvedFilePath);
294
+ const { pageTargets, nonPageTargets } = processContext.partitionBuildTargets(requestedTargets, groupedPageTargets);
295
+ let hasLayoutOwnedRequestedTarget = initialLayoutOwned;
309
296
  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}`);
297
+ hasLayoutOwnedRequestedTarget = await processContext.hasLayoutOwnedDependencyTarget(resolvedFilePath, requestedTargets);
325
298
  }
299
+ const requiresLayoutRefresh = isLayout || dependencyScan.hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
300
+ const updates = collectHmrUpdateUrls(processContext, requestedTargets, pageTargets, nonPageTargets);
326
301
  if (requiresLayoutRefresh) {
327
302
  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
303
  }
337
- if (updates.length > 0) {
304
+ else if (updates.length > 0) {
338
305
  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
306
  }
348
- appLogger.debug(`No updates generated`);
349
- return { type: 'none' };
307
+ else {
308
+ appLogger.debug(`No updates generated`);
309
+ }
310
+ return buildHmrAction(requiresLayoutRefresh, updates);
350
311
  }
351
312
  }
@@ -15,6 +15,7 @@ type ImportedReactPageModule = {
15
15
  export type ReactHmrDevTransformPluginOptions = {
16
16
  pageMetadataCache: HmrPageMetadataCache;
17
17
  mdxCompilerOptions?: CompileOptions;
18
+ projectRoot: string;
18
19
  getBuildPlugins: (declaredModules?: readonly string[]) => EcoBuildPlugin[];
19
20
  importNodePageModule: (entrypointPath: string) => Promise<ImportedReactPageModule>;
20
21
  };
@@ -14,7 +14,10 @@ export async function resolveReactDeclaredModulesForEntrypoint(options, entrypoi
14
14
  export function buildReactDevTransformPlugins(options, declaredModules, shouldEnableMdx) {
15
15
  const plugins = options.getBuildPlugins(declaredModules);
16
16
  if (shouldEnableMdx && options.mdxCompilerOptions) {
17
- plugins.unshift(createReactMdxLoaderPlugin(options.mdxCompilerOptions));
17
+ plugins.unshift(createReactMdxLoaderPlugin({
18
+ compilerOptions: options.mdxCompilerOptions,
19
+ projectRoot: options.projectRoot,
20
+ }));
18
21
  }
19
22
  return plugins;
20
23
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Browser-side React Island Host lifecycle.
3
+ *
4
+ * @remarks
5
+ * This module intentionally receives React's browser runtime as a value. The
6
+ * server entry compiler can therefore keep the application's React and
7
+ * ReactDOM imports external while bundling this framework-owned lifecycle.
8
+ */
9
+ export type IslandComponent = (props: Record<string, unknown>) => unknown;
10
+ export type IslandReactRuntime = {
11
+ hydrateRoot: (target: HTMLElement, tree: unknown, options?: {
12
+ onRecoverableError?: (error: unknown) => void;
13
+ }) => IslandRoot;
14
+ createElement: (type: unknown, props: Record<string, unknown>) => unknown;
15
+ useEffect: (effect: () => void, dependencies: unknown[]) => void;
16
+ };
17
+ export type IslandRoot = {
18
+ render: (tree: unknown) => void;
19
+ unmount: () => void;
20
+ };
21
+ /** Shared browser state for all Island Host entries on one document. */
22
+ export type IslandHydrationRuntime = {
23
+ islandRoots: Record<string, IslandRoot>;
24
+ islandComponents: Record<string, IslandComponent>;
25
+ observer?: MutationObserver;
26
+ };
27
+ /** Configuration for one compiled React Island Host entry. */
28
+ export type IslandHydrationOptions = {
29
+ targetSelector: string;
30
+ componentModule: Record<string, unknown>;
31
+ componentRef?: string;
32
+ componentFile?: string;
33
+ scriptId: string;
34
+ runtime: IslandReactRuntime;
35
+ runtimeState: IslandHydrationRuntime;
36
+ };
37
+ /**
38
+ * Returns the shared page runtime used by all React Island Host entries.
39
+ *
40
+ * @remarks
41
+ * Keeping initialization here means generated entries only describe their
42
+ * component and selector; they do not duplicate global runtime setup.
43
+ *
44
+ * @returns The shared mutable state used by all island entries on this page.
45
+ */
46
+ export declare function getIslandHydrationRuntime(): IslandHydrationRuntime;
47
+ /**
48
+ * Registers the development HMR callback for one component module.
49
+ *
50
+ * @remarks
51
+ * The callback imports the replacement module and delegates to
52
+ * {@link updateIslands}, which updates every live host matching this entry.
53
+ * The dynamic import function is supplied by the generated entry so HMR keeps
54
+ * the browser's normal module-resolution behavior.
55
+ *
56
+ * @param options - Entry configuration whose hosts should receive updates.
57
+ * @param importModule - Browser dynamic-import function for the replacement module.
58
+ * @param importPath - HMR source URL used as the global handler key.
59
+ */
60
+ export declare function registerIslandHmr(options: IslandHydrationOptions, importModule: (url: string) => Promise<Record<string, unknown>>, importPath?: string): void;
61
+ /**
62
+ * Hydrates every eligible host for one component entry.
63
+ *
64
+ * @remarks
65
+ * Existing host records are skipped. This makes rerun scripts idempotent and
66
+ * avoids calling `render` while an initial `hydrateRoot` commit is
67
+ * still pending.
68
+ *
69
+ * @param options - Component, selector, React runtime, and shared state for the entry.
70
+ */
71
+ export declare function mountIslands(options: IslandHydrationOptions): void;
72
+ /**
73
+ * Applies a hot-reloaded component to every live host owned by this entry.
74
+ *
75
+ * @remarks
76
+ * Updates arriving before the initial commit are stored on each host and
77
+ * rendered by {@link IslandLifecycle} after it marks that host hydrated.
78
+ *
79
+ * @param options - The live entry configuration and runtime state.
80
+ * @param newModule - Newly imported component module.
81
+ */
82
+ export declare function updateIslands(options: IslandHydrationOptions, newModule: Record<string, unknown>): void;
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Browser-side React Island Host lifecycle.
3
+ *
4
+ * @remarks
5
+ * This module intentionally receives React's browser runtime as a value. The
6
+ * server entry compiler can therefore keep the application's React and
7
+ * ReactDOM imports external while bundling this framework-owned lifecycle.
8
+ */
9
+ /**
10
+ * Returns the shared page runtime used by all React Island Host entries.
11
+ *
12
+ * @remarks
13
+ * Keeping initialization here means generated entries only describe their
14
+ * component and selector; they do not duplicate global runtime setup.
15
+ *
16
+ * @returns The shared mutable state used by all island entries on this page.
17
+ */
18
+ export function getIslandHydrationRuntime() {
19
+ const pageWindow = window;
20
+ const pageRuntime = (pageWindow.__ECO_PAGES__ ??= {});
21
+ pageRuntime.islandRoots ??= {};
22
+ pageRuntime.islandComponents ??= {};
23
+ pageRuntime.__ecoIslandRuntime ??= {
24
+ islandRoots: pageRuntime.islandRoots,
25
+ islandComponents: pageRuntime.islandComponents,
26
+ };
27
+ pageRuntime.__ecoIslandRuntime.islandRoots = pageRuntime.islandRoots;
28
+ pageRuntime.__ecoIslandRuntime.islandComponents = pageRuntime.islandComponents;
29
+ return pageRuntime.__ecoIslandRuntime;
30
+ }
31
+ /**
32
+ * Registers the development HMR callback for one component module.
33
+ *
34
+ * @remarks
35
+ * The callback imports the replacement module and delegates to
36
+ * {@link updateIslands}, which updates every live host matching this entry.
37
+ * The dynamic import function is supplied by the generated entry so HMR keeps
38
+ * the browser's normal module-resolution behavior.
39
+ *
40
+ * @param options - Entry configuration whose hosts should receive updates.
41
+ * @param importModule - Browser dynamic-import function for the replacement module.
42
+ * @param importPath - HMR source URL used as the global handler key.
43
+ */
44
+ export function registerIslandHmr(options, importModule, importPath) {
45
+ if (!importPath)
46
+ return;
47
+ const pageWindow = window;
48
+ const pageRuntime = (pageWindow.__ECO_PAGES__ ??= {});
49
+ pageRuntime.hmrHandlers ??= {};
50
+ pageRuntime.hmrHandlers[importPath] = async (url) => {
51
+ updateIslands(options, await importModule(url));
52
+ };
53
+ }
54
+ /**
55
+ * Selects the component exported by a browser entry for the current Island Host.
56
+ *
57
+ * @remarks
58
+ * Component identity is preferred when a file exports several components. The
59
+ * default export and then the first function remain compatibility fallbacks for
60
+ * entries without framework identity metadata.
61
+ */
62
+ function resolveComponent(module, componentRef, componentFile) {
63
+ const values = Object.values(module).filter((entry) => typeof entry === 'function');
64
+ if (componentRef) {
65
+ const matchById = values.find((entry) => entry.config?.identity?.id === componentRef);
66
+ if (matchById)
67
+ return matchById;
68
+ }
69
+ if (componentFile) {
70
+ const matchByFile = values.find((entry) => entry.config?.identity?.file === componentFile);
71
+ if (matchByFile)
72
+ return matchByFile;
73
+ }
74
+ if (typeof module.default === 'function')
75
+ return module.default;
76
+ return values[0] ?? null;
77
+ }
78
+ function getComponentId(target) {
79
+ return target.getAttribute('data-eco-component-id');
80
+ }
81
+ function getIslandIdentity(target) {
82
+ return getComponentId(target) ?? target.getAttribute('data-eco-component-key') ?? 'unknown';
83
+ }
84
+ /**
85
+ * Adds the initial-commit marker while keeping one stable React component type
86
+ * around the application component. A stable type lets HMR update props without
87
+ * remounting this lifecycle boundary on every render.
88
+ */
89
+ function IslandLifecycle({ target, runtime, Component, props }) {
90
+ runtime.useEffect(() => {
91
+ target.setAttribute('data-eco-hydrated', 'true');
92
+ const record = target.__eco_island;
93
+ if (!record)
94
+ return;
95
+ record.hydrated = true;
96
+ if (record.pendingComponent) {
97
+ const pendingComponent = record.pendingComponent;
98
+ record.pendingComponent = undefined;
99
+ record.root.render(runtime.createElement(IslandLifecycle, {
100
+ target,
101
+ runtime,
102
+ Component: pendingComponent,
103
+ props: readProps(target),
104
+ }));
105
+ }
106
+ }, [target, runtime]);
107
+ return runtime.createElement(Component, props);
108
+ }
109
+ /**
110
+ * Decodes the serialized props stamped on an Island Host by the server.
111
+ * Malformed or non-object payloads become an empty props object so a broken
112
+ * diagnostic attribute cannot prevent the rest of the page from hydrating.
113
+ */
114
+ function readProps(target) {
115
+ try {
116
+ const encoded = target.getAttribute('data-eco-props') ?? 'e30=';
117
+ const parsed = JSON.parse(atob(encoded));
118
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
119
+ ? parsed
120
+ : {};
121
+ }
122
+ catch {
123
+ return {};
124
+ }
125
+ }
126
+ /**
127
+ * Unmounts a disconnected island and removes only its matching registry entry.
128
+ *
129
+ * @remarks
130
+ * Connectivity is checked by the observer callback, after the mutation batch,
131
+ * so moving a host within the document does not release its React root.
132
+ */
133
+ function releaseIsland(target, runtimeState) {
134
+ if (target.isConnected)
135
+ return;
136
+ const record = target.__eco_island;
137
+ if (!record)
138
+ return;
139
+ record.root.unmount();
140
+ const componentId = getComponentId(target);
141
+ if (componentId && runtimeState.islandRoots[componentId] === record.root) {
142
+ delete runtimeState.islandRoots[componentId];
143
+ }
144
+ delete target.__eco_island;
145
+ }
146
+ /**
147
+ * Installs the one document observer shared by all island entries on the page.
148
+ * The observer releases roots for removed hosts and their descendants.
149
+ */
150
+ function ensureObserver(runtimeState) {
151
+ if (runtimeState.observer || !document.documentElement)
152
+ return;
153
+ runtimeState.observer = new MutationObserver((mutations) => {
154
+ for (const mutation of mutations) {
155
+ for (const node of mutation.removedNodes) {
156
+ if (!(node instanceof HTMLElement))
157
+ continue;
158
+ releaseIsland(node, runtimeState);
159
+ for (const target of node.querySelectorAll('[data-eco-island]'))
160
+ releaseIsland(target, runtimeState);
161
+ }
162
+ }
163
+ });
164
+ runtimeState.observer.observe(document.documentElement, { childList: true, subtree: true });
165
+ }
166
+ /**
167
+ * Hydrates one server-emitted Island Host in place and records its lifecycle.
168
+ *
169
+ * @remarks
170
+ * The record is attached immediately after `hydrateRoot` returns so
171
+ * duplicate startup and HMR can see the host before React's initial effect runs.
172
+ */
173
+ function hydrateTarget(target, component, runtime, runtimeState) {
174
+ const root = runtime.hydrateRoot(target, runtime.createElement(IslandLifecycle, { target, runtime, Component: component, props: readProps(target) }), {
175
+ onRecoverableError: (error) => console.warn('[ecopages] Island hydration error', getIslandIdentity(target), error),
176
+ });
177
+ const record = { root, hydrated: false, component };
178
+ target.__eco_island = record;
179
+ const componentId = getComponentId(target);
180
+ if (componentId)
181
+ runtimeState.islandRoots[componentId] = record.root;
182
+ }
183
+ /**
184
+ * Hydrates every eligible host for one component entry.
185
+ *
186
+ * @remarks
187
+ * Existing host records are skipped. This makes rerun scripts idempotent and
188
+ * avoids calling `render` while an initial `hydrateRoot` commit is
189
+ * still pending.
190
+ *
191
+ * @param options - Component, selector, React runtime, and shared state for the entry.
192
+ */
193
+ export function mountIslands(options) {
194
+ const resolvedComponent = resolveComponent(options.componentModule, options.componentRef ?? '', options.componentFile ?? '');
195
+ ensureObserver(options.runtimeState);
196
+ const pageRuntime = (window.__ECO_PAGES__ ??= {});
197
+ pageRuntime.rerunScripts ??= {};
198
+ pageRuntime.rerunScripts[options.scriptId] = () => mountIslands(options);
199
+ const scriptId = options.scriptId;
200
+ const component = options.runtimeState.islandComponents[scriptId] ?? resolvedComponent;
201
+ if (!component)
202
+ return;
203
+ options.runtimeState.islandComponents[scriptId] = component;
204
+ for (const element of document.querySelectorAll(options.targetSelector)) {
205
+ const target = element;
206
+ if (target.__eco_island?.root)
207
+ continue;
208
+ hydrateTarget(target, component, options.runtime, options.runtimeState);
209
+ }
210
+ }
211
+ /**
212
+ * Applies a hot-reloaded component to every live host owned by this entry.
213
+ *
214
+ * @remarks
215
+ * Updates arriving before the initial commit are stored on each host and
216
+ * rendered by {@link IslandLifecycle} after it marks that host hydrated.
217
+ *
218
+ * @param options - The live entry configuration and runtime state.
219
+ * @param newModule - Newly imported component module.
220
+ */
221
+ export function updateIslands(options, newModule) {
222
+ const component = resolveComponent(newModule, options.componentRef ?? '', options.componentFile ?? '');
223
+ if (!component)
224
+ return;
225
+ options.componentModule = newModule;
226
+ const scriptId = options.scriptId;
227
+ options.runtimeState.islandComponents[scriptId] = component;
228
+ for (const element of document.querySelectorAll(options.targetSelector)) {
229
+ const target = element;
230
+ const record = target.__eco_island;
231
+ if (!record) {
232
+ hydrateTarget(target, component, options.runtime, options.runtimeState);
233
+ continue;
234
+ }
235
+ record.component = component;
236
+ if (!record.hydrated) {
237
+ record.pendingComponent = component;
238
+ continue;
239
+ }
240
+ record.root.render(options.runtime.createElement(IslandLifecycle, {
241
+ target,
242
+ runtime: options.runtime,
243
+ Component: component,
244
+ props: readProps(target),
245
+ }));
246
+ }
247
+ }
@@ -0,0 +1,11 @@
1
+ import type { PageHydrationOptions } from './page-hydration.js';
2
+ /**
3
+ * Imports and applies one HMR page update.
4
+ */
5
+ export declare function handlePageHmr(options: PageHydrationOptions, newUrl: string, generation: number, readPageData: (options: PageHydrationOptions) => {
6
+ moduleUrl?: string;
7
+ props: Record<string, unknown>;
8
+ }, setPageState: (options: PageHydrationOptions, pageData: {
9
+ moduleUrl?: string;
10
+ props: Record<string, unknown>;
11
+ }) => void, getPageDataFromDocument: (options: PageHydrationOptions) => Record<string, unknown>): Promise<void>;