@ecopages/react 0.2.0-rc.6 → 0.2.0-rc.8
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 +21 -4
- package/package.json +5 -4
- package/src/app/client-only.js +3 -8
- package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
- package/src/client-graph/ast-transform-eco-page.js +71 -0
- package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
- package/src/client-graph/ast-transform-import-edits.js +75 -0
- package/src/client-graph/ast-transform-walk-imports.d.ts +19 -0
- package/src/client-graph/ast-transform-walk-imports.js +103 -0
- package/src/client-graph/ast-transform.d.ts +1 -7
- package/src/client-graph/ast-transform.js +42 -379
- package/src/client-graph/ast-walk.d.ts +10 -0
- package/src/client-graph/ast-walk.js +26 -0
- package/src/client-graph/boundary-plugin-read-file-inline.d.ts +8 -0
- package/src/client-graph/boundary-plugin-read-file-inline.js +45 -0
- package/src/client-graph/boundary-plugin-transform.d.ts +18 -0
- package/src/client-graph/boundary-plugin-transform.js +61 -0
- package/src/client-graph/boundary-plugin.d.ts +0 -20
- package/src/client-graph/boundary-plugin.js +16 -98
- package/src/client-graph/reachability-analyzer.d.ts +2 -43
- package/src/client-graph/reachability-analyzer.js +20 -518
- package/src/client-graph/reachability-client-roots.d.ts +8 -0
- package/src/client-graph/reachability-client-roots.js +59 -0
- package/src/client-graph/reachability-export-names.d.ts +5 -0
- package/src/client-graph/reachability-export-names.js +34 -0
- package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
- package/src/client-graph/reachability-fallback-roots.js +71 -0
- package/src/client-graph/reachability-preload.d.ts +10 -0
- package/src/client-graph/reachability-preload.js +30 -0
- package/src/client-graph/reachability-top-level-index.d.ts +14 -0
- package/src/client-graph/reachability-top-level-index.js +93 -0
- package/src/client-graph/reachability-traverse.d.ts +7 -0
- package/src/client-graph/reachability-traverse.js +201 -0
- package/src/hmr/hmr-strategy-process.d.ts +34 -0
- package/src/hmr/hmr-strategy-process.js +83 -0
- package/src/hmr/hmr-strategy.d.ts +1 -0
- package/src/hmr/hmr-strategy.js +42 -84
- package/src/hydration/browser/island-hydration.d.ts +82 -0
- package/src/hydration/browser/island-hydration.js +247 -0
- package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
- package/src/hydration/browser/page-hydration-hmr.js +56 -0
- package/src/hydration/browser/page-hydration-module.d.ts +8 -0
- package/src/hydration/browser/page-hydration-module.js +17 -0
- package/src/hydration/browser/page-hydration.d.ts +54 -0
- package/src/hydration/browser/page-hydration.js +177 -0
- package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
- package/src/hydration/hydration-asset.d.ts +20 -1
- package/src/hydration/hydration-asset.js +42 -24
- package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
- package/src/hydration/hydration-lifecycle.test.browser.js +409 -0
- package/src/hydration/hydration-page-entry-source.d.ts +5 -0
- package/src/hydration/hydration-page-entry-source.js +87 -0
- package/src/hydration/hydration-script-compiler.d.ts +48 -0
- package/src/hydration/hydration-script-compiler.js +213 -0
- package/src/hydration/page-data-reader.d.ts +0 -14
- package/src/hydration/page-data-reader.js +1 -47
- package/src/render/component-ssr.d.ts +17 -0
- package/src/render/component-ssr.js +19 -1
- package/src/render/react-renderer.d.ts +2 -1
- package/src/render/react-renderer.js +5 -1
- package/src/render/unified-layout-composition.d.ts +2 -0
- package/src/render/unified-layout-composition.js +5 -1
- package/src/hydration/hydration-scripts.d.ts +0 -112
- package/src/hydration/hydration-scripts.js +0 -517
- package/src/hydration/hydration-scripts.test.browser.js +0 -199
- /package/src/hydration/{hydration-scripts.test.browser.d.ts → compiled-page-hydration-options.js} +0 -0
package/src/hmr/hmr-strategy.js
CHANGED
|
@@ -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.
|
|
@@ -245,6 +246,24 @@ export class ReactHmrStrategy extends HmrStrategy {
|
|
|
245
246
|
nonPageTargets: requestedTargets.filter((target) => !groupedPageEntrypoints.has(target.entrypointPath) && !this.isPageEntrypoint(target.entrypointPath)),
|
|
246
247
|
};
|
|
247
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
|
+
}
|
|
248
267
|
async process(_filePath) {
|
|
249
268
|
appLogger.debug(`Processing ${_filePath}`);
|
|
250
269
|
const resolvedFilePath = path.resolve(_filePath);
|
|
@@ -253,102 +272,41 @@ export class ReactHmrStrategy extends HmrStrategy {
|
|
|
253
272
|
appLogger.debug(`No watched files`);
|
|
254
273
|
return { type: 'none' };
|
|
255
274
|
}
|
|
256
|
-
const
|
|
257
|
-
const
|
|
275
|
+
const processContext = this.createProcessContext(resolvedFilePath, watchedFiles);
|
|
276
|
+
const isLayout = processContext.isLayoutFile(resolvedFilePath);
|
|
277
|
+
const isChangedPageEntrypoint = processContext.isPageEntrypoint(resolvedFilePath);
|
|
258
278
|
if (isLayout) {
|
|
259
279
|
appLogger.debug(`Detected layout file change: ${resolvedFilePath}`);
|
|
260
280
|
}
|
|
261
281
|
const changedEntrypointOutput = watchedFiles.get(resolvedFilePath);
|
|
262
|
-
if (changedEntrypointOutput
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
}
|
|
266
|
-
else {
|
|
267
|
-
appLogger.debug(`Skipping non-React watched entrypoint: ${resolvedFilePath}`);
|
|
268
|
-
return { type: 'none' };
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(resolvedFilePath);
|
|
272
|
-
const hasDependencyHits = dependencyHits.size > 0;
|
|
273
|
-
const affectedEntrypoints = new Map();
|
|
274
|
-
let hasOwnedLayoutDependencyHit = false;
|
|
275
|
-
let layoutOwnedPageTargets = [];
|
|
276
|
-
let hasLayoutOwnedRequestedTarget = false;
|
|
277
|
-
if (hasDependencyHits && !changedEntrypointOutput) {
|
|
278
|
-
for (const entrypoint of dependencyHits) {
|
|
279
|
-
const resolvedEntrypoint = path.resolve(entrypoint);
|
|
280
|
-
const outputUrl = watchedFiles.get(resolvedEntrypoint);
|
|
281
|
-
if (outputUrl &&
|
|
282
|
-
(this.ownsWatchedEntrypoint(resolvedEntrypoint) || this.isDevTransformOutputUrl(outputUrl))) {
|
|
283
|
-
affectedEntrypoints.set(resolvedEntrypoint, outputUrl);
|
|
284
|
-
continue;
|
|
285
|
-
}
|
|
286
|
-
if (this.isLayoutFile(resolvedEntrypoint) && this.ownsWatchedEntrypoint(resolvedEntrypoint)) {
|
|
287
|
-
hasOwnedLayoutDependencyHit = true;
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
if (affectedEntrypoints.size === 0 && !hasOwnedLayoutDependencyHit) {
|
|
291
|
-
if (!isLayout) {
|
|
292
|
-
appLogger.debug(`Dependency hits found but none map to React-owned watched entrypoints`);
|
|
293
|
-
return { type: 'none' };
|
|
294
|
-
}
|
|
295
|
-
}
|
|
282
|
+
if (ensureWatchedEntrypointOwnership(processContext, changedEntrypointOutput) === 'abort') {
|
|
283
|
+
appLogger.debug(`Skipping non-React watched entrypoint: ${resolvedFilePath}`);
|
|
284
|
+
return { type: 'none' };
|
|
296
285
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
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' };
|
|
300
291
|
}
|
|
301
|
-
const requestedTargets = changedEntrypointOutput
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
: hasOwnedLayoutDependencyHit
|
|
306
|
-
? await this.collectReactPageBuildTargets()
|
|
307
|
-
: hasDependencyHits
|
|
308
|
-
? Array.from(affectedEntrypoints, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }))
|
|
309
|
-
: Array.from(watchedFiles, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }));
|
|
310
|
-
const groupedPageTargets = await this.resolveBuildTargets(requestedTargets, resolvedFilePath);
|
|
311
|
-
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;
|
|
312
296
|
if (!changedEntrypointOutput) {
|
|
313
|
-
hasLayoutOwnedRequestedTarget = await
|
|
314
|
-
}
|
|
315
|
-
const requiresLayoutRefresh = isLayout || hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
|
|
316
|
-
const updates = [];
|
|
317
|
-
const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
|
|
318
|
-
this.queueDevTransformOutputUpdates(pageTargets, requestedOutputUrls, updates);
|
|
319
|
-
for (const { outputUrl } of nonPageTargets) {
|
|
320
|
-
if (!requestedOutputUrls.has(outputUrl)) {
|
|
321
|
-
continue;
|
|
322
|
-
}
|
|
323
|
-
if (this.isDevTransformOutputUrl(outputUrl)) {
|
|
324
|
-
updates.push(outputUrl);
|
|
325
|
-
continue;
|
|
326
|
-
}
|
|
327
|
-
appLogger.debug(`Skipping non-dev-transform HMR output: ${outputUrl}`);
|
|
297
|
+
hasLayoutOwnedRequestedTarget = await processContext.hasLayoutOwnedDependencyTarget(resolvedFilePath, requestedTargets);
|
|
328
298
|
}
|
|
299
|
+
const requiresLayoutRefresh = isLayout || dependencyScan.hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
|
|
300
|
+
const updates = collectHmrUpdateUrls(processContext, requestedTargets, pageTargets, nonPageTargets);
|
|
329
301
|
if (requiresLayoutRefresh) {
|
|
330
302
|
appLogger.debug(`Layout update detected, sending layout-update event`);
|
|
331
|
-
return {
|
|
332
|
-
type: 'broadcast',
|
|
333
|
-
events: [
|
|
334
|
-
{
|
|
335
|
-
type: 'layout-update',
|
|
336
|
-
},
|
|
337
|
-
],
|
|
338
|
-
};
|
|
339
303
|
}
|
|
340
|
-
if (updates.length > 0) {
|
|
304
|
+
else if (updates.length > 0) {
|
|
341
305
|
appLogger.debug(`Broadcasting ${updates.length} updates`);
|
|
342
|
-
return {
|
|
343
|
-
type: 'broadcast',
|
|
344
|
-
events: updates.map((path) => ({
|
|
345
|
-
type: 'update',
|
|
346
|
-
path,
|
|
347
|
-
timestamp: Date.now(),
|
|
348
|
-
})),
|
|
349
|
-
};
|
|
350
306
|
}
|
|
351
|
-
|
|
352
|
-
|
|
307
|
+
else {
|
|
308
|
+
appLogger.debug(`No updates generated`);
|
|
309
|
+
}
|
|
310
|
+
return buildHmrAction(requiresLayoutRefresh, updates);
|
|
353
311
|
}
|
|
354
312
|
}
|
|
@@ -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>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { resolvePageModule } from './page-hydration-module.js';
|
|
2
|
+
function getRuntime() {
|
|
3
|
+
return (window.__ECO_PAGES__ ??= {});
|
|
4
|
+
}
|
|
5
|
+
function isCurrentMountGeneration(generation) {
|
|
6
|
+
return (getRuntime().react?.mountGeneration ?? 0) === generation;
|
|
7
|
+
}
|
|
8
|
+
async function applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, _nextProps) {
|
|
9
|
+
if (!options.hasRouter || getRuntime().navigation?.getOwnerState?.().owner !== 'react-router') {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
const currentLayoutStack = options.hmr.getLayoutStack?.(currentPage) ?? '';
|
|
13
|
+
const nextLayoutStack = options.hmr.getLayoutStack?.(nextPage.Page) ?? '';
|
|
14
|
+
await getRuntime().navigation?.reloadCurrentPage?.({
|
|
15
|
+
clearCache: currentLayoutStack !== nextLayoutStack,
|
|
16
|
+
moduleUrl: newUrl,
|
|
17
|
+
source: 'react-router',
|
|
18
|
+
});
|
|
19
|
+
console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated via router`);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
function applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPageState, generation) {
|
|
23
|
+
const activeRoot = getRuntime().react?.pageRoot ?? null;
|
|
24
|
+
if (!activeRoot || !isCurrentMountGeneration(generation))
|
|
25
|
+
return;
|
|
26
|
+
setPageState(options, readPageData(options));
|
|
27
|
+
activeRoot.render(options.createTree(nextPage.Page, nextProps));
|
|
28
|
+
console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated`);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Imports and applies one HMR page update.
|
|
32
|
+
*/
|
|
33
|
+
export async function handlePageHmr(options, newUrl, generation, readPageData, setPageState, getPageDataFromDocument) {
|
|
34
|
+
if (!options.hmr || !isCurrentMountGeneration(generation))
|
|
35
|
+
return;
|
|
36
|
+
try {
|
|
37
|
+
const newModule = (await import(/* @vite-ignore */ newUrl));
|
|
38
|
+
if (!isCurrentMountGeneration(generation))
|
|
39
|
+
return;
|
|
40
|
+
const nextPage = resolvePageModule(newModule, options.isMdx, options.normalizePageConfig);
|
|
41
|
+
const nextProps = getPageDataFromDocument(options);
|
|
42
|
+
await nextPage.preload?.(nextProps);
|
|
43
|
+
if (!isCurrentMountGeneration(generation))
|
|
44
|
+
return;
|
|
45
|
+
const currentPage = options.Page;
|
|
46
|
+
options.Page = nextPage.Page;
|
|
47
|
+
options.preload = nextPage.preload;
|
|
48
|
+
if (await applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, nextProps)) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPageState, generation);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
console.error(`[ecopages] Failed to hot-reload ${options.isMdx ? 'MDX' : 'React'} component:`, error);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type PageModule = {
|
|
2
|
+
Page: unknown;
|
|
3
|
+
preload?: (props: Record<string, unknown>) => void | Promise<void>;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* Normalizes a loaded Page module into the shape used by hydration and HMR.
|
|
7
|
+
*/
|
|
8
|
+
export declare function resolvePageModule(module: Record<string, unknown>, isMdx: boolean, normalizePageConfig?: (config: unknown) => void): PageModule;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
function isPagePreload(value) {
|
|
2
|
+
return typeof value === 'function';
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Normalizes a loaded Page module into the shape used by hydration and HMR.
|
|
6
|
+
*/
|
|
7
|
+
export function resolvePageModule(module, isMdx, normalizePageConfig) {
|
|
8
|
+
const Page = module.default ?? module;
|
|
9
|
+
if (isMdx && module.config && Page && typeof Page === 'function') {
|
|
10
|
+
Object.assign(Page, { config: module.config });
|
|
11
|
+
normalizePageConfig?.(module.config);
|
|
12
|
+
}
|
|
13
|
+
return {
|
|
14
|
+
Page,
|
|
15
|
+
preload: isPagePreload(module.preload) ? module.preload : undefined,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-side React page lifecycle.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* The entry module supplies the page tree and module resolution details. This
|
|
6
|
+
* module owns document state, navigation ownership, cleanup, and HMR so those
|
|
7
|
+
* behaviors stay identical for readable and compiled bootstraps.
|
|
8
|
+
*/
|
|
9
|
+
export type PageRoot = {
|
|
10
|
+
render: (tree: unknown) => void;
|
|
11
|
+
unmount: () => void;
|
|
12
|
+
};
|
|
13
|
+
export type PageReactRuntime = {
|
|
14
|
+
hydrateRoot: (target: HTMLElement, tree: unknown, options?: {
|
|
15
|
+
onRecoverableError?: (error: unknown) => void;
|
|
16
|
+
}) => PageRoot;
|
|
17
|
+
createElement: (...args: unknown[]) => unknown;
|
|
18
|
+
};
|
|
19
|
+
export type PageData = {
|
|
20
|
+
moduleUrl?: string;
|
|
21
|
+
props: Record<string, unknown>;
|
|
22
|
+
};
|
|
23
|
+
export type { PageModule } from './page-hydration-module.js';
|
|
24
|
+
export { resolvePageModule } from './page-hydration-module.js';
|
|
25
|
+
/** Configuration passed from a generated Page hydration entry. */
|
|
26
|
+
export type PageHydrationOptions = {
|
|
27
|
+
scriptId: string;
|
|
28
|
+
pageModuleUrl: string;
|
|
29
|
+
Page: unknown;
|
|
30
|
+
pageDataReader: {
|
|
31
|
+
readPageDataDocument: () => PageData;
|
|
32
|
+
getPageDataFromDocument: () => Record<string, unknown>;
|
|
33
|
+
};
|
|
34
|
+
runtime: PageReactRuntime;
|
|
35
|
+
createTree: (Page: unknown, props: Record<string, unknown>) => unknown;
|
|
36
|
+
hasRouter: boolean;
|
|
37
|
+
isMdx: boolean;
|
|
38
|
+
normalizePageConfig?: (config: unknown) => void;
|
|
39
|
+
hmr?: {
|
|
40
|
+
importPath: string;
|
|
41
|
+
getLayoutStack?: (Page: unknown) => string;
|
|
42
|
+
};
|
|
43
|
+
preload?: (props: Record<string, unknown>) => void | Promise<void>;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Registers and starts the Page lifecycle when its persistent script is present.
|
|
47
|
+
*
|
|
48
|
+
* @remarks
|
|
49
|
+
* Restores lifecycle registration, router ownership, and HMR generation binding
|
|
50
|
+
* whenever the page is activated or rerun after navigation.
|
|
51
|
+
*
|
|
52
|
+
* @param options - Generated entry configuration for the current Page.
|
|
53
|
+
*/
|
|
54
|
+
export declare function startPageHydration(options: PageHydrationOptions): void;
|