@ecopages/react 0.3.0 → 0.3.2

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.
package/README.md CHANGED
@@ -27,6 +27,7 @@ For component-level islands, Ecopages React uses this contract:
27
27
  - SSR output preserves the authored DOM structure (no unnecessary wrapper elements).
28
28
  - A stable island host contract is stamped on the component SSR root via core (`data-eco-island`, `data-eco-island-integration`, `data-eco-component-id`, optional `data-eco-component-key` / `data-eco-props`).
29
29
  - During non-HMR runtime rendering, island and lazy-entry client modules are built together from the page client plan, in one grouped browser build during route preparation. Static production export contributes React hydration and lazy entries, every Integration's Page Browser Graph entries, and HTML Page and `html.html` shell module scripts to compatible app-wide browser build groups. Hydration scripts import the recorded output URLs. Same-integration Page, Layout, and includes are hydrated by the page bootstrap. The Html shell is not an island, even when its Integration differs from the page owner. Only a React component whose Integration differs from its parent's, on another owner's page, receives a per-component island script. SSR stamps the host and attaches those assets; it does not start a per-island build.
30
+ - Each island component gets its own hydration script, keyed by its component identity. A file that exports several island components is built once and its declared modules are merged, while each component's hosts hydrate the export whose identity matches.
30
31
  - The island runtime keeps the SSR host and its children in place and hydrates that host with `hydrateRoot()`. The host uses `display: contents` so it does not introduce an extra layout box. Full-page hydration paths also use `hydrateRoot()`.
31
32
 
32
33
  > [!TIP]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/react",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "React integration for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -104,21 +104,18 @@
104
104
  "directory": "packages/integrations/react"
105
105
  },
106
106
  "peerDependencies": {
107
- "@ecopages/core": "0.3.0",
107
+ "@ecopages/core": "0.3.2",
108
108
  "@types/react": "^19",
109
109
  "@types/react-dom": "^19",
110
110
  "react": "^19",
111
111
  "react-dom": "^19"
112
112
  },
113
113
  "dependencies": {
114
- "@ecopages/file-system": "0.3.0",
114
+ "@ecopages/file-system": "0.3.2",
115
115
  "@ecopages/logger": "^0.2.3",
116
- "@ecopages/mdx": "0.3.0",
116
+ "@ecopages/mdx": "0.3.2",
117
117
  "@mdx-js/mdx": "^3.1.1",
118
118
  "oxc-parser": "^0.141.0",
119
- "oxc-transform": "^0.141.0",
120
- "rolldown": "^1.1.0",
121
- "source-map": "^0.8.0",
122
- "vfile": "^6.0.3"
119
+ "rolldown": "^1.1.0"
123
120
  }
124
121
  }
@@ -1,4 +1,4 @@
1
- import fs from 'node:fs';
1
+ import { fileSystem } from '@ecopages/file-system';
2
2
  function escapeRegExp(value) {
3
3
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4
4
  }
@@ -16,7 +16,7 @@ export function createReactDomRuntimeInteropPlugin(options) {
16
16
  }));
17
17
  }
18
18
  build.onLoad({ filter: reactDomFileFilter }, (args) => {
19
- const content = fs.readFileSync(args.path, 'utf-8');
19
+ const content = fileSystem.readFileSync(args.path);
20
20
  if (!reactRequirePattern.test(content)) {
21
21
  return undefined;
22
22
  }
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from 'node:fs';
1
+ import { fileSystem } from '@ecopages/file-system';
2
2
  import { dirname, resolve, sep } from 'node:path';
3
3
  const READ_FILE_SYNC_PATTERN = /\bfs\.readFileSync\s*\(\s*path\.resolve\s*\(\s*(['"`])([^'"`\n]+)\1\s*\)\s*,\s*['"`]utf-?8['"`]\s*\)/g;
4
4
  function inferProjectRootFromSourcePath(filePath) {
@@ -17,7 +17,7 @@ function resolveReadFileCandidate(relPath, sourcePath, absWorkingDir) {
17
17
  resolve(sourceDir, relPath),
18
18
  ...(inferredProjectRoot ? [resolve(inferredProjectRoot, relPath)] : []),
19
19
  ];
20
- return candidates.find((candidate) => existsSync(candidate));
20
+ return candidates.find((candidate) => fileSystem.exists(candidate));
21
21
  }
22
22
  /**
23
23
  * Inlines `fs.readFileSync(path.resolve(...), 'utf8')` calls when the target file exists.
@@ -33,7 +33,7 @@ export function inlineReadFileSyncCalls(source, sourcePath, absWorkingDir) {
33
33
  const absolutePath = resolveReadFileCandidate(relPath, sourcePath, absWorkingDir);
34
34
  if (!absolutePath)
35
35
  return '""';
36
- return JSON.stringify(readFileSync(absolutePath, 'utf-8'));
36
+ return JSON.stringify(fileSystem.readFileSync(absolutePath));
37
37
  }
38
38
  catch {
39
39
  return '""';
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Build plugin securing the Ecopages isomorphic compilation pipeline.
5
5
  */
6
- import { readFileSync } from 'node:fs';
6
+ import { fileSystem } from '@ecopages/file-system';
7
7
  import path from 'node:path';
8
8
  import { parseDeclaredModules, toModuleBaseSpecifier } from './specifier-classification.js';
9
9
  import { classifyClientGraphModule } from './module-classification.js';
@@ -81,7 +81,7 @@ function loadClientGraphBoundaryModule(args, options, requestedExports, isEntryp
81
81
  }
82
82
  let source;
83
83
  try {
84
- source = readFileSync(args.path, 'utf-8');
84
+ source = fileSystem.readFileSync(args.path);
85
85
  }
86
86
  catch {
87
87
  return undefined;
@@ -98,7 +98,7 @@ function loadClientGraphBoundaryModule(args, options, requestedExports, isEntryp
98
98
  }
99
99
  function resolveEntryImports(entrypointFiles, entrypoint) {
100
100
  try {
101
- const source = readFileSync(entrypoint, 'utf-8');
101
+ const source = fileSystem.readFileSync(entrypoint);
102
102
  const wrapper = /^\s*(?:export\s+\*\s+from|import)\s+(['"])([^'"\n]+)\1\s*;?\s*$/.exec(source);
103
103
  const specifier = wrapper?.[2];
104
104
  if (!specifier)
@@ -23,13 +23,14 @@ export type IslandHydrationRuntime = {
23
23
  islandRoots: Record<string, IslandRoot>;
24
24
  islandComponents: Record<string, IslandComponent>;
25
25
  observer?: MutationObserver;
26
+ /** Island entries by HMR module path, then by script id. One file can declare several islands. */
27
+ hmrEntries?: Map<string, Map<string, IslandHydrationOptions>>;
26
28
  };
27
29
  /** Configuration for one compiled React Island Host entry. */
28
30
  export type IslandHydrationOptions = {
29
31
  targetSelector: string;
30
32
  componentModule: Record<string, unknown>;
31
33
  componentRef?: string;
32
- componentFile?: string;
33
34
  scriptId: string;
34
35
  runtime: IslandReactRuntime;
35
36
  runtimeState: IslandHydrationRuntime;
@@ -48,10 +49,11 @@ export declare function getIslandHydrationRuntime(): IslandHydrationRuntime;
48
49
  * Registers the development HMR callback for one component module.
49
50
  *
50
51
  * @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.
52
+ * The callback imports the replacement module once and delegates to
53
+ * {@link updateIslands} for every island entry registered under the same module
54
+ * path, since every island of one file shares that path. The dynamic import
55
+ * function is supplied by the generated entry so HMR keeps the browser's normal
56
+ * module-resolution behavior.
55
57
  *
56
58
  * @param options - Entry configuration whose hosts should receive updates.
57
59
  * @param importModule - Browser dynamic-import function for the replacement module.
@@ -76,6 +78,11 @@ export declare function mountIslands(options: IslandHydrationOptions): void;
76
78
  * Updates arriving before the initial commit are stored on each host and
77
79
  * rendered by {@link IslandLifecycle} after it marks that host hydrated.
78
80
  *
81
+ * An entry with a component id throws when the new module exports nothing with
82
+ * that id, for example after the declaration was renamed. Falling back to another
83
+ * export could render a sibling or a helper; the thrown error makes the HMR
84
+ * client reload the page instead.
85
+ *
79
86
  * @param options - The live entry configuration and runtime state.
80
87
  * @param newModule - Newly imported component module.
81
88
  */
@@ -32,10 +32,11 @@ export function getIslandHydrationRuntime() {
32
32
  * Registers the development HMR callback for one component module.
33
33
  *
34
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.
35
+ * The callback imports the replacement module once and delegates to
36
+ * {@link updateIslands} for every island entry registered under the same module
37
+ * path, since every island of one file shares that path. The dynamic import
38
+ * function is supplied by the generated entry so HMR keeps the browser's normal
39
+ * module-resolution behavior.
39
40
  *
40
41
  * @param options - Entry configuration whose hosts should receive updates.
41
42
  * @param importModule - Browser dynamic-import function for the replacement module.
@@ -44,36 +45,39 @@ export function getIslandHydrationRuntime() {
44
45
  export function registerIslandHmr(options, importModule, importPath) {
45
46
  if (!importPath)
46
47
  return;
48
+ options.runtimeState.hmrEntries ??= new Map();
49
+ const entries = options.runtimeState.hmrEntries.get(importPath) ?? new Map();
50
+ options.runtimeState.hmrEntries.set(importPath, entries);
51
+ entries.set(options.scriptId, options);
47
52
  const pageWindow = window;
48
53
  const pageRuntime = (pageWindow.__ECO_PAGES__ ??= {});
49
54
  pageRuntime.hmrHandlers ??= {};
50
55
  pageRuntime.hmrHandlers[importPath] = async (url) => {
51
- updateIslands(options, await importModule(url));
56
+ const newModule = await importModule(url);
57
+ for (const entry of entries.values())
58
+ updateIslands(entry, newModule);
52
59
  };
53
60
  }
61
+ function findComponentById(module, componentRef) {
62
+ return Object.values(module).find((entry) => typeof entry === 'function' &&
63
+ entry.config?.identity?.id === componentRef);
64
+ }
54
65
  /**
55
66
  * Selects the component exported by a browser entry for the current Island Host.
56
67
  *
57
68
  * @remarks
58
- * Component identity is preferred when a file exports several components. The
69
+ * Component identity is preferred when a file exports several components; each
70
+ * declaration has its own id, so the file alone cannot tell them apart. The
59
71
  * default export and then the first function remain compatibility fallbacks for
60
72
  * entries without framework identity metadata.
61
73
  */
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
+ function resolveComponent(module, componentRef) {
75
+ const matchById = componentRef ? findComponentById(module, componentRef) : undefined;
76
+ if (matchById)
77
+ return matchById;
74
78
  if (typeof module.default === 'function')
75
79
  return module.default;
76
- return values[0] ?? null;
80
+ return Object.values(module).find((entry) => typeof entry === 'function') ?? null;
77
81
  }
78
82
  function getComponentId(target) {
79
83
  return target.getAttribute('data-eco-component-id');
@@ -195,7 +199,7 @@ function hydrateTarget(target, component, runtime, runtimeState) {
195
199
  * @param options - Component, selector, React runtime, and shared state for the entry.
196
200
  */
197
201
  export function mountIslands(options) {
198
- const resolvedComponent = resolveComponent(options.componentModule, options.componentRef ?? '', options.componentFile ?? '');
202
+ const resolvedComponent = resolveComponent(options.componentModule, options.componentRef ?? '');
199
203
  ensureObserver(options.runtimeState);
200
204
  const pageRuntime = (window.__ECO_PAGES__ ??= {});
201
205
  pageRuntime.rerunScripts ??= {};
@@ -219,13 +223,22 @@ export function mountIslands(options) {
219
223
  * Updates arriving before the initial commit are stored on each host and
220
224
  * rendered by {@link IslandLifecycle} after it marks that host hydrated.
221
225
  *
226
+ * An entry with a component id throws when the new module exports nothing with
227
+ * that id, for example after the declaration was renamed. Falling back to another
228
+ * export could render a sibling or a helper; the thrown error makes the HMR
229
+ * client reload the page instead.
230
+ *
222
231
  * @param options - The live entry configuration and runtime state.
223
232
  * @param newModule - Newly imported component module.
224
233
  */
225
234
  export function updateIslands(options, newModule) {
226
- const component = resolveComponent(newModule, options.componentRef ?? '', options.componentFile ?? '');
227
- if (!component)
228
- return;
235
+ const componentRef = options.componentRef;
236
+ const component = componentRef ? findComponentById(newModule, componentRef) : resolveComponent(newModule, '');
237
+ if (!component) {
238
+ if (!componentRef)
239
+ return;
240
+ throw new Error(`[ecopages] The updated module no longer exports island component "${componentRef}".`);
241
+ }
229
242
  options.componentModule = newModule;
230
243
  const scriptId = options.scriptId;
231
244
  options.runtimeState.islandComponents[scriptId] = component;
@@ -100,6 +100,7 @@ export declare class HydrationAssetService {
100
100
  file: string;
101
101
  config?: EcoComponentConfig;
102
102
  }>): Promise<PageClientBuildEntry[]>;
103
+ /** Keeps one entry per component; a file that declares several island components keeps each of them. */
103
104
  private uniqueIslands;
104
105
  private buildHmrPageClientRenderAssets;
105
106
  private buildGroupedPageClientRenderAssets;
@@ -158,7 +158,7 @@ export class HydrationAssetService {
158
158
  /** Collects React island hydration entries for the production app browser build. */
159
159
  async collectAppBrowserClientBuildEntries(islands) {
160
160
  const uniqueIslands = this.uniqueIslands(islands);
161
- const groupedEntrypointFiles = uniqueIslands.map(({ file }) => file);
161
+ const groupedEntrypointFiles = [...new Set(uniqueIslands.map(({ file }) => file))];
162
162
  const groupedDeclaredModules = [
163
163
  ...new Set(uniqueIslands.flatMap(({ config }) => collectDeclaredModulesInConfig(config))),
164
164
  ];
@@ -185,14 +185,16 @@ export class HydrationAssetService {
185
185
  }
186
186
  return entries;
187
187
  }
188
+ /** Keeps one entry per component; a file that declares several island components keeps each of them. */
188
189
  uniqueIslands(islands) {
189
190
  const uniqueIslands = [];
190
- const seenFiles = new Set();
191
+ const seenKeys = new Set();
191
192
  for (const island of islands) {
192
- if (seenFiles.has(island.file)) {
193
+ const key = getIslandComponentKey(island.file, island.config);
194
+ if (seenKeys.has(key)) {
193
195
  continue;
194
196
  }
195
- seenFiles.add(island.file);
197
+ seenKeys.add(key);
196
198
  uniqueIslands.push(island);
197
199
  }
198
200
  return uniqueIslands;
@@ -203,7 +205,7 @@ export class HydrationAssetService {
203
205
  for (const island of uniqueIslands) {
204
206
  this.config.hmrPageMetadataCache?.markOwnedEntrypoint(island.file);
205
207
  const assets = await this.buildHmrIslandRenderAssets(island.file, island.config);
206
- assetsByFile.set(island.file, assets);
208
+ assetsByFile.set(island.file, [...(assetsByFile.get(island.file) ?? []), ...assets]);
207
209
  processedAssets.push(...assets);
208
210
  }
209
211
  if (lazyEntries?.length) {
@@ -229,16 +231,23 @@ export class HydrationAssetService {
229
231
  }
230
232
  async createGroupedIslandEntries(uniqueIslands) {
231
233
  const islandEntries = [];
232
- const groupedEntrypointFiles = uniqueIslands.map(({ file }) => file);
234
+ const declaredModulesByFile = new Map();
235
+ for (const { file, config } of uniqueIslands) {
236
+ const declaredModules = declaredModulesByFile.get(file) ?? new Set();
237
+ for (const module of collectDeclaredModulesInConfig(config))
238
+ declaredModules.add(module);
239
+ declaredModulesByFile.set(file, declaredModules);
240
+ }
241
+ const groupedEntrypointFiles = [...declaredModulesByFile.keys()];
233
242
  const groupedDeclaredModules = [
234
243
  ...new Set(uniqueIslands.flatMap(({ config }) => collectDeclaredModulesInConfig(config))),
235
244
  ];
236
- for (const island of uniqueIslands) {
237
- const componentName = this.getIslandBundleName(island.file);
238
- const bundleOptions = await this.config.bundleService.createBundleOptions(componentName, false, collectDeclaredModulesInConfig(island.config), {}, island.file, groupedEntrypointFiles, groupedDeclaredModules);
245
+ for (const [file, declaredModules] of declaredModulesByFile) {
246
+ const componentName = this.getIslandBundleName(file);
247
+ const bundleOptions = await this.config.bundleService.createBundleOptions(componentName, false, [...declaredModules], {}, file, groupedEntrypointFiles, groupedDeclaredModules);
239
248
  islandEntries.push(createAppBrowserClientEntry({
240
249
  entryName: componentName,
241
- importPath: island.file,
250
+ importPath: file,
242
251
  reexport: true,
243
252
  packageRole: 'dynamic-chunk',
244
253
  bundleOptions,
@@ -286,8 +295,9 @@ export class HydrationAssetService {
286
295
  const componentName = this.getIslandBundleName(island.file);
287
296
  const hydrationName = this.getIslandHydrationName(componentName, getIslandComponentKey(island.file, island.config));
288
297
  const islandAsset = processedClientEntries.find((processed) => processed.groupedBundle?.entryName === componentName);
298
+ const fileAssets = assetsByFile.get(island.file);
289
299
  assetsByFile.set(island.file, [
290
- ...(islandAsset ? [islandAsset] : []),
300
+ ...(fileAssets ?? (islandAsset ? [islandAsset] : [])),
291
301
  ...(hydrationByName.get(hydrationName) ?? []),
292
302
  ]);
293
303
  }
@@ -310,7 +320,6 @@ export class HydrationAssetService {
310
320
  reactDomClientImportPath: runtimeImports.reactDomClient,
311
321
  targetSelector: `[data-eco-component-key="${componentKey}"]`,
312
322
  componentRef: config?.identity?.id,
313
- componentFile,
314
323
  minify: !hmrEnabled,
315
324
  hmrEnabled,
316
325
  });
@@ -41,7 +41,7 @@ function buildHmrOptions(options) {
41
41
  if (!options.hmrEnabled)
42
42
  return '';
43
43
  const layoutStack = options.routerComponents
44
- ? 'getLayoutStack: (Page) => (Page.config?.layouts ?? []).map((layout) => layout?.config?.identity?.file ?? "").join("|"),'
44
+ ? 'getLayoutStack: (Page) => (Page.config?.layouts ?? []).map((layout) => layout?.config?.identity?.id ?? "").join("|"),'
45
45
  : '';
46
46
  return `hmr: {
47
47
  importPath: ${JSON.stringify(options.importPath)},
@@ -6,7 +6,6 @@ export type CompiledIslandHydrationOptions = {
6
6
  reactDomClientImportPath: string;
7
7
  targetSelector: string;
8
8
  componentRef?: string;
9
- componentFile?: string;
10
9
  minify: boolean;
11
10
  hmrEnabled?: boolean;
12
11
  };
@@ -1,4 +1,5 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { fileURLToPath } from 'node:url';
2
+ import { fileSystem } from '@ecopages/file-system';
2
3
  import { rolldown } from 'rolldown';
3
4
  const ISLAND_BOOTSTRAP_ID = '\0ecopages-react-island-bootstrap';
4
5
  const PAGE_BOOTSTRAP_ID = '\0ecopages-react-page-bootstrap';
@@ -29,7 +30,6 @@ const configuration = {
29
30
  targetSelector: ${JSON.stringify(options.targetSelector)},
30
31
  componentModule: ComponentModule,
31
32
  componentRef: ${JSON.stringify(options.componentRef ?? '')},
32
- componentFile: ${JSON.stringify(options.componentFile ?? '')},
33
33
  scriptId: ${JSON.stringify(options.scriptId)},
34
34
  runtime: { hydrateRoot, createElement, useEffect },
35
35
  runtimeState: getIslandHydrationRuntime()
@@ -57,7 +57,7 @@ function createBootstrapPlugin() {
57
57
  throw new Error(`Unknown hydration bootstrap module: ${id}`);
58
58
  for (const relativePath of candidates) {
59
59
  try {
60
- return readFileSync(new URL(`./browser/${relativePath}`, import.meta.url), 'utf8');
60
+ return fileSystem.readFileSync(fileURLToPath(new URL(`./browser/${relativePath}`, import.meta.url)));
61
61
  }
62
62
  catch {
63
63
  continue;
@@ -87,7 +87,7 @@ function createBootstrapPlugin() {
87
87
  load(id) {
88
88
  if (id === PAGE_DATA_MANIFEST_ID) {
89
89
  return {
90
- code: readFileSync(new URL('./page-data-manifest.js', import.meta.url), 'utf8'),
90
+ code: fileSystem.readFileSync(fileURLToPath(new URL('./page-data-manifest.js', import.meta.url))),
91
91
  moduleType: 'ts',
92
92
  };
93
93
  }
@@ -1 +0,0 @@
1
- export {};
@@ -1,38 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { Suspense } from 'react';
3
- import { createRoot } from 'react-dom/client';
4
- import { afterEach, describe, expect, it } from 'vitest';
5
- import { page } from 'vitest/browser';
6
- import { dynamic } from './dynamic.js';
7
- function createDeferredImport() {
8
- let resolve;
9
- const promise = new Promise((innerResolve) => {
10
- resolve = innerResolve;
11
- });
12
- return {
13
- promise,
14
- resolve,
15
- };
16
- }
17
- describe('dynamic', () => {
18
- let container;
19
- let root;
20
- afterEach(() => {
21
- root.unmount();
22
- container.remove();
23
- });
24
- it('returns a browser lazy component that resolves through Suspense', async () => {
25
- const deferredImport = createDeferredImport();
26
- const DynamicComponent = dynamic(() => deferredImport.promise);
27
- container = document.createElement('div');
28
- document.body.appendChild(container);
29
- root = createRoot(container);
30
- root.render(_jsx(Suspense, { fallback: _jsx("span", { children: "Loading dynamic component" }), children: _jsx(DynamicComponent, {}) }));
31
- await expect.element(page.getByText('Loading dynamic component')).toBeInTheDocument();
32
- deferredImport.resolve({
33
- default: () => _jsx("span", { children: "Dynamic content" }),
34
- });
35
- await expect.element(page.getByText('Dynamic content')).toBeInTheDocument();
36
- await expect.element(page.getByText('Loading dynamic component')).not.toBeInTheDocument();
37
- });
38
- });
@@ -1,4 +0,0 @@
1
- /**
2
- * Test helper: assert generated hydration bootstrap source has no bare `@ecopages/*` imports.
3
- */
4
- export declare function assertNoBareEcopagesImports(source: string): void;
@@ -1,7 +0,0 @@
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
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,461 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from 'vitest';
2
- import { createElement, useEffect } from 'react';
3
- import { hydrateRoot } from 'react-dom/client';
4
- import { mountIslands, updateIslands } from './browser/island-hydration.js';
5
- import { startPageHydration } from './browser/page-hydration.js';
6
- /**
7
- * Resolves after the browser has run every task queued before the call.
8
- *
9
- * @remarks
10
- * For asserting that something did not happen. A message-channel round trip runs after all pending
11
- * promise reactions without a timer, so it cannot be mistaken for waiting out a delay.
12
- */
13
- function flushTasks() {
14
- return new Promise((resolve) => {
15
- const channel = new MessageChannel();
16
- channel.port1.onmessage = () => resolve();
17
- channel.port2.postMessage(null);
18
- });
19
- }
20
- function createPageOptions(testWindow, router, pageRoot) {
21
- const runtime = testWindow.__ECO_REACT_HYDRATION_TEST__;
22
- const Page = () => null;
23
- const reactRuntime = {
24
- hydrateRoot: (target, tree, options) => {
25
- runtime.hydrateCalls.push({
26
- containerTag: target.tagName,
27
- hasRecoverableErrorHandler: typeof options?.onRecoverableError === 'function',
28
- tree,
29
- });
30
- return (pageRoot ?? {
31
- render: (nextTree) => runtime.renderCalls.push(nextTree),
32
- unmount: () => {
33
- runtime.unmountCount += 1;
34
- },
35
- });
36
- },
37
- createElement: (...args) => ({ args }),
38
- };
39
- return {
40
- scriptId: 'ecopages-react-page',
41
- pageModuleUrl: '/assets/page.js',
42
- Page,
43
- pageDataReader: {
44
- readPageDataDocument: () => ({ props: { title: 'Hello React', locals: { theme: 'dark' } } }),
45
- getPageDataFromDocument: () => ({ title: 'Hello React' }),
46
- },
47
- runtime: reactRuntime,
48
- createTree: (Component, props) => ({ Component, props }),
49
- hasRouter: router,
50
- isMdx: false,
51
- };
52
- }
53
- describe('React page lifecycle', () => {
54
- afterEach(() => {
55
- document.body.innerHTML = '';
56
- delete window.__ECO_PAGES__;
57
- delete window.__ECO_REACT_HYDRATION_TEST__;
58
- });
59
- it('registers router ownership and cleanup', async () => {
60
- const testWindow = window;
61
- const testState = {
62
- hydrateCalls: [],
63
- renderCalls: [],
64
- claimedOwners: [],
65
- releasedOwners: [],
66
- registrations: [],
67
- unmountCount: 0,
68
- };
69
- testWindow.__ECO_REACT_HYDRATION_TEST__ = testState;
70
- testWindow.__ECO_PAGES__ = {
71
- navigation: {
72
- getOwnerState: () => ({ owner: 'html', canHandleSpaNavigation: false }),
73
- register: (registration) => testState.registrations.push(registration),
74
- claimOwnership: (owner) => testState.claimedOwners.push(owner),
75
- releaseOwnership: (owner) => testState.releasedOwners.push(owner),
76
- },
77
- };
78
- document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
79
- startPageHydration(createPageOptions(testWindow, true));
80
- await vi.waitFor(() => expect(testState.hydrateCalls).toHaveLength(1), { interval: 1 });
81
- expect(testState.hydrateCalls).toHaveLength(1);
82
- expect(testState.hydrateCalls[0].containerTag).toBe('BODY');
83
- expect(testState.hydrateCalls[0].hasRecoverableErrorHandler).toBe(true);
84
- expect(testState.claimedOwners).toEqual(['react-router']);
85
- expect(testState.registrations).toHaveLength(1);
86
- expect(typeof testWindow.__ECO_PAGES__?.react?.cleanupPageRoot).toBe('function');
87
- await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
88
- expect(testState.unmountCount).toBe(1);
89
- expect(testState.releasedOwners).toEqual(['react-router']);
90
- expect(testWindow.__ECO_PAGES__?.page).toBeUndefined();
91
- expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBeNull();
92
- });
93
- it('reuses an existing router-owned page root on rerun', async () => {
94
- const testWindow = window;
95
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
96
- hydrateCalls: [],
97
- renderCalls: [],
98
- claimedOwners: [],
99
- releasedOwners: [],
100
- registrations: [],
101
- unmountCount: 0,
102
- };
103
- const existingRoot = {
104
- render: (tree) => testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree),
105
- unmount: () => {
106
- testWindow.__ECO_REACT_HYDRATION_TEST__.unmountCount += 1;
107
- },
108
- };
109
- testWindow.__ECO_PAGES__ = {
110
- navigation: {
111
- getOwnerState: () => ({ owner: 'react-router', canHandleSpaNavigation: true }),
112
- },
113
- react: { pageRoot: existingRoot },
114
- };
115
- document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
116
- startPageHydration(createPageOptions(testWindow, true, existingRoot));
117
- await flushTasks();
118
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
119
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
120
- expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBe(existingRoot);
121
- });
122
- it('coalesces concurrent startup and cancels a preload after cleanup', async () => {
123
- const testWindow = window;
124
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
125
- hydrateCalls: [],
126
- renderCalls: [],
127
- claimedOwners: [],
128
- releasedOwners: [],
129
- registrations: [],
130
- unmountCount: 0,
131
- };
132
- document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
133
- let resolvePreload;
134
- const preload = new Promise((resolve) => {
135
- resolvePreload = resolve;
136
- });
137
- const options = createPageOptions(testWindow, false);
138
- options.preload = () => preload;
139
- options.hmr = { importPath: '/assets/page.js' };
140
- startPageHydration(options);
141
- expect(typeof testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js']).toBe('function');
142
- const rerun = testWindow.__ECO_PAGES__?.rerunScripts?.['ecopages-react-page'];
143
- rerun?.();
144
- await Promise.resolve();
145
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
146
- await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
147
- resolvePreload();
148
- await flushTasks();
149
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
150
- });
151
- it('ignores an HMR update that settles after navigation cleanup', async () => {
152
- const testWindow = window;
153
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
154
- hydrateCalls: [],
155
- renderCalls: [],
156
- claimedOwners: [],
157
- releasedOwners: [],
158
- registrations: [],
159
- unmountCount: 0,
160
- };
161
- document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
162
- const options = createPageOptions(testWindow, false);
163
- options.hmr = { importPath: '/assets/page.js' };
164
- startPageHydration(options);
165
- await vi.waitFor(() => expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1), {
166
- interval: 1,
167
- });
168
- let resolveUpdate;
169
- globalThis.__ECO_TEST_HMR_RELEASE__ = new Promise((resolve) => {
170
- resolveUpdate = resolve;
171
- });
172
- const source = [
173
- 'export default function UpdatedPage() {}',
174
- 'export async function preload() {',
175
- ' globalThis.__ECO_TEST_HMR_PRELOAD_STARTED__ = true',
176
- ' await globalThis.__ECO_TEST_HMR_RELEASE__',
177
- '}',
178
- ].join('\n');
179
- const hmrHandler = testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js'];
180
- expect(hmrHandler).toBeDefined();
181
- const update = hmrHandler?.(`data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`);
182
- await vi.waitFor(() => expect(globalThis.__ECO_TEST_HMR_PRELOAD_STARTED__).toBe(true), {
183
- interval: 1,
184
- });
185
- await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
186
- const replacementRoot = {
187
- render: (tree) => testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree),
188
- unmount: () => undefined,
189
- };
190
- testWindow.__ECO_PAGES__.react.pageRoot = replacementRoot;
191
- resolveUpdate();
192
- await update;
193
- await hmrHandler?.('data:text/javascript,export default function RemovedPage() {}');
194
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
195
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
196
- delete globalThis.__ECO_TEST_HMR_RELEASE__;
197
- delete globalThis.__ECO_TEST_HMR_PRELOAD_STARTED__;
198
- });
199
- it('restores HMR handler with updated generation on page reactivation after cleanup', async () => {
200
- const testWindow = window;
201
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
202
- hydrateCalls: [],
203
- renderCalls: [],
204
- claimedOwners: [],
205
- releasedOwners: [],
206
- registrations: [],
207
- unmountCount: 0,
208
- };
209
- document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
210
- const options = createPageOptions(testWindow, false);
211
- options.hmr = { importPath: '/assets/page.js' };
212
- startPageHydration(options);
213
- await vi.waitFor(() => expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1), {
214
- interval: 1,
215
- });
216
- const initialHmr = testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js'];
217
- expect(initialHmr).toBeDefined();
218
- await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
219
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
220
- await initialHmr?.('data:text/javascript,export default function IgnoredPage() {}');
221
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
222
- await testWindow.__ECO_PAGES__.rerunScripts['ecopages-react-page']();
223
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(2);
224
- const restoredHmr = testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js'];
225
- expect(restoredHmr).toBeDefined();
226
- await restoredHmr?.('data:text/javascript,export default function UpdatedPage() {}');
227
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(1);
228
- });
229
- it('publishes a replacement only after its preload completes', async () => {
230
- const testWindow = window;
231
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
232
- hydrateCalls: [],
233
- renderCalls: [],
234
- claimedOwners: [],
235
- releasedOwners: [],
236
- registrations: [],
237
- unmountCount: 0,
238
- };
239
- document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
240
- let releaseInitial;
241
- let releaseUpdate;
242
- let signalUpdate;
243
- const initialPreload = new Promise((resolve) => {
244
- releaseInitial = resolve;
245
- });
246
- const updateStarted = new Promise((resolve) => {
247
- signalUpdate = resolve;
248
- });
249
- const updatePreload = new Promise((resolve) => {
250
- releaseUpdate = resolve;
251
- });
252
- const testGlobals = globalThis;
253
- testGlobals.__ECO_TEST_PENDING_PRELOAD__ = () => {
254
- signalUpdate();
255
- return updatePreload;
256
- };
257
- const options = createPageOptions(testWindow, false);
258
- const initialPage = options.Page;
259
- options.preload = () => initialPreload;
260
- options.hmr = { importPath: '/assets/page.js' };
261
- try {
262
- startPageHydration(options);
263
- const handler = testWindow.__ECO_PAGES__.hmrHandlers['/assets/page.js'];
264
- const source = 'export default function ReadyPage() {} export const preload = () => globalThis.__ECO_TEST_PENDING_PRELOAD__();';
265
- const update = handler(`data:text/javascript,${encodeURIComponent(source)}`);
266
- await updateStarted;
267
- expect(options.Page).toBe(initialPage);
268
- releaseInitial();
269
- await testWindow.__ECO_PAGES__.rerunScripts['ecopages-react-page']();
270
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__.hydrateCalls[0]?.tree).toMatchObject({
271
- Component: initialPage,
272
- });
273
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__.renderCalls).toHaveLength(0);
274
- releaseUpdate();
275
- await update;
276
- expect(options.Page).not.toBe(initialPage);
277
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__.renderCalls).toEqual([
278
- { Component: options.Page, props: { title: 'Hello React' } },
279
- ]);
280
- }
281
- finally {
282
- releaseInitial();
283
- releaseUpdate();
284
- delete testGlobals.__ECO_TEST_PENDING_PRELOAD__;
285
- }
286
- });
287
- });
288
- describe('React Island Host lifecycle', () => {
289
- afterEach(() => {
290
- document.body.innerHTML = '';
291
- });
292
- it('hydrates in place, ignores repeated startup, and releases removed hosts', async () => {
293
- const host = document.createElement('eco-island');
294
- host.setAttribute('data-eco-island', '');
295
- host.setAttribute('data-eco-island-integration', 'react');
296
- host.setAttribute('data-eco-component-id', 'instance-1');
297
- host.setAttribute('data-eco-component-key', 'component-1');
298
- host.setAttribute('data-eco-props', btoa(JSON.stringify({ value: 'server' })));
299
- const child = document.createElement('input');
300
- child.value = 'typed before hydration';
301
- host.appendChild(child);
302
- document.body.appendChild(host);
303
- const calls = { hydrate: 0, render: 0, unmount: 0, recoverableErrors: 0 };
304
- const hydratedComponents = [];
305
- const runtime = { islandRoots: {}, islandComponents: {} };
306
- const reactRuntime = {
307
- hydrateRoot: (target, tree, options) => {
308
- calls.hydrate += 1;
309
- if (options?.onRecoverableError)
310
- calls.recoverableErrors += 1;
311
- hydratedComponents.push(tree.props.Component);
312
- const root = {
313
- render: (nextTree) => {
314
- calls.render += 1;
315
- hydratedComponents.push(nextTree.props.Component);
316
- },
317
- unmount: () => {
318
- calls.unmount += 1;
319
- },
320
- };
321
- tree.type(tree.props);
322
- void target;
323
- return root;
324
- },
325
- createElement: (type, props) => ({ type, props }),
326
- useEffect: (effect) => queueMicrotask(effect),
327
- };
328
- const Component = () => null;
329
- const options = {
330
- targetSelector: '[data-eco-component-key="component-1"]',
331
- componentModule: { default: Component },
332
- scriptId: 'island-script',
333
- runtime: reactRuntime,
334
- runtimeState: runtime,
335
- };
336
- mountIslands(options);
337
- mountIslands(options);
338
- await flushTasks();
339
- expect(calls.hydrate).toBe(1);
340
- expect(host.firstElementChild).toBe(child);
341
- expect(host.getAttribute('data-eco-hydrated')).toBe('true');
342
- expect(calls.recoverableErrors).toBe(1);
343
- const NextComponent = () => null;
344
- updateIslands(options, { default: NextComponent });
345
- expect(calls.render).toBe(1);
346
- expect(hydratedComponents[hydratedComponents.length - 1]).toBe(NextComponent);
347
- const secondHost = host.cloneNode(false);
348
- document.body.appendChild(secondHost);
349
- mountIslands(options);
350
- expect(calls.hydrate).toBe(2);
351
- expect(hydratedComponents[hydratedComponents.length - 1]).toBe(NextComponent);
352
- host.remove();
353
- await vi.waitFor(() => expect(calls.unmount).toBe(1), { interval: 1 });
354
- runtime.observer?.disconnect();
355
- });
356
- it('hydrates with props that contain non-Latin-1 text', () => {
357
- const host = document.createElement('eco-island');
358
- host.setAttribute('data-eco-island', '');
359
- host.setAttribute('data-eco-component-key', 'component-unicode');
360
- /** Props `{ label: '10 €', city: '東京', icon: '🙂' }` as core's `encodeIslandProps` writes them. */
361
- host.setAttribute('data-eco-props', 'eyJsYWJlbCI6IjEwIOKCrCIsImNpdHkiOiLmnbHkuqwiLCJpY29uIjoi8J+ZgiJ9');
362
- document.body.appendChild(host);
363
- const Component = () => null;
364
- const renderedProps = [];
365
- const runtime = { islandRoots: {}, islandComponents: {} };
366
- mountIslands({
367
- targetSelector: '[data-eco-component-key="component-unicode"]',
368
- componentModule: { default: Component },
369
- scriptId: 'island-script-unicode',
370
- runtimeState: runtime,
371
- runtime: {
372
- hydrateRoot: (_target, tree) => {
373
- const element = tree;
374
- element.type(element.props);
375
- return { render: () => { }, unmount: () => { } };
376
- },
377
- createElement: (type, elementProps) => {
378
- if (type === Component)
379
- renderedProps.push(elementProps);
380
- return { type, props: elementProps };
381
- },
382
- useEffect: () => { },
383
- },
384
- });
385
- expect(renderedProps).toEqual([{ label: '10 €', city: '東京', icon: '🙂' }]);
386
- runtime.observer?.disconnect();
387
- });
388
- it('preserves a focused uncontrolled input with the real React hydrator', async () => {
389
- const host = document.createElement('eco-island');
390
- host.setAttribute('data-eco-island', '');
391
- host.setAttribute('data-eco-component-id', 'real-instance');
392
- host.setAttribute('data-eco-component-key', 'real-component');
393
- host.setAttribute('data-eco-props', btoa(JSON.stringify({ value: 'server value' })));
394
- const input = document.createElement('input');
395
- input.defaultValue = 'server value';
396
- input.value = 'typed before hydration';
397
- host.appendChild(input);
398
- document.body.appendChild(host);
399
- input.focus();
400
- const Component = (props) => createElement('input', { defaultValue: String(props.value ?? '') });
401
- const reactRuntime = {
402
- hydrateRoot: (target, tree, options) => {
403
- const root = hydrateRoot(target, tree, options);
404
- return {
405
- render: (nextTree) => root.render(nextTree),
406
- unmount: () => root.unmount(),
407
- };
408
- },
409
- createElement: (type, props) => createElement(type, props),
410
- useEffect: (effect) => {
411
- useEffect(effect);
412
- },
413
- };
414
- const runtime = { islandRoots: {}, islandComponents: {} };
415
- mountIslands({
416
- targetSelector: '[data-eco-component-key="real-component"]',
417
- componentModule: { default: Component },
418
- scriptId: 'real-island-script',
419
- runtime: reactRuntime,
420
- runtimeState: runtime,
421
- });
422
- await vi.waitFor(() => expect(host.getAttribute('data-eco-hydrated')).toBe('true'), { interval: 1 });
423
- expect(host.firstElementChild).toBe(input);
424
- expect(input.value).toBe('typed before hydration');
425
- expect(document.activeElement).toBe(input);
426
- expect(host.getAttribute('data-eco-hydrated')).toBe('true');
427
- runtime.observer?.disconnect();
428
- });
429
- it('resolves the component matching componentRef when a module exports multiple components from the same file', async () => {
430
- const host = document.createElement('eco-island');
431
- host.setAttribute('data-eco-island', '');
432
- host.setAttribute('data-eco-component-id', 'multi-instance');
433
- host.setAttribute('data-eco-component-key', 'multi-component');
434
- document.body.appendChild(host);
435
- const Helper = () => null;
436
- Helper.config = { identity: { id: 'Helper', file: '/app/Counter.tsx' } };
437
- const Target = () => null;
438
- Target.config = { identity: { id: 'Target', file: '/app/Counter.tsx' } };
439
- let hydratedComponent;
440
- const reactRuntime = {
441
- hydrateRoot: (_target, tree) => {
442
- hydratedComponent = tree.props.Component;
443
- return { render: () => { }, unmount: () => { } };
444
- },
445
- createElement: (type, props) => ({ type, props }),
446
- useEffect: () => { },
447
- };
448
- const runtime = { islandRoots: {}, islandComponents: {} };
449
- mountIslands({
450
- targetSelector: '[data-eco-component-key="multi-component"]',
451
- componentModule: { Helper, Target },
452
- componentRef: 'Target',
453
- componentFile: '/app/Counter.tsx',
454
- scriptId: 'multi-island-script',
455
- runtime: reactRuntime,
456
- runtimeState: runtime,
457
- });
458
- expect(hydratedComponent).toBe(Target);
459
- runtime.observer?.disconnect();
460
- });
461
- });