@ecopages/react 0.2.0-rc.7 → 0.2.0-rc.9
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/package.json +4 -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/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 +2 -18
- package/src/hydration/browser/page-hydration.js +3 -80
- package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
- package/src/hydration/compiled-page-hydration-options.js +1 -0
- package/src/hydration/hydration-lifecycle.test.browser.js +12 -11
- 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 +2 -20
- package/src/hydration/hydration-script-compiler.js +14 -69
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,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
|
+
}
|
|
@@ -20,24 +20,8 @@ export type PageData = {
|
|
|
20
20
|
moduleUrl?: string;
|
|
21
21
|
props: Record<string, unknown>;
|
|
22
22
|
};
|
|
23
|
-
export type PageModule
|
|
24
|
-
|
|
25
|
-
preload?: (props: Record<string, unknown>) => void | Promise<void>;
|
|
26
|
-
};
|
|
27
|
-
/**
|
|
28
|
-
* Normalizes a loaded Page module into the shape used by hydration and HMR.
|
|
29
|
-
*
|
|
30
|
-
* @remarks
|
|
31
|
-
* MDX modules carry page configuration as a named export and need layout
|
|
32
|
-
* normalization before React reconstructs the page tree. Plain React modules
|
|
33
|
-
* use their default export while still allowing a named `preload`.
|
|
34
|
-
*
|
|
35
|
-
* @param module - Imported Page or MDX module namespace.
|
|
36
|
-
* @param isMdx - Whether the module carries MDX page configuration.
|
|
37
|
-
* @param normalizePageConfig - Integration helper for normalizing MDX layouts.
|
|
38
|
-
* @returns The Page component and optional preload hook used by hydration/HMR.
|
|
39
|
-
*/
|
|
40
|
-
export declare function resolvePageModule(module: Record<string, unknown>, isMdx: boolean, normalizePageConfig?: (config: unknown) => void): PageModule;
|
|
23
|
+
export type { PageModule } from './page-hydration-module.js';
|
|
24
|
+
export { resolvePageModule } from './page-hydration-module.js';
|
|
41
25
|
/** Configuration passed from a generated Page hydration entry. */
|
|
42
26
|
export type PageHydrationOptions = {
|
|
43
27
|
scriptId: string;
|
|
@@ -6,34 +6,8 @@
|
|
|
6
6
|
* module owns document state, navigation ownership, cleanup, and HMR so those
|
|
7
7
|
* behaviors stay identical for readable and compiled bootstraps.
|
|
8
8
|
*/
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
return typeof value === 'function';
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Normalizes a loaded Page module into the shape used by hydration and HMR.
|
|
15
|
-
*
|
|
16
|
-
* @remarks
|
|
17
|
-
* MDX modules carry page configuration as a named export and need layout
|
|
18
|
-
* normalization before React reconstructs the page tree. Plain React modules
|
|
19
|
-
* use their default export while still allowing a named `preload`.
|
|
20
|
-
*
|
|
21
|
-
* @param module - Imported Page or MDX module namespace.
|
|
22
|
-
* @param isMdx - Whether the module carries MDX page configuration.
|
|
23
|
-
* @param normalizePageConfig - Integration helper for normalizing MDX layouts.
|
|
24
|
-
* @returns The Page component and optional preload hook used by hydration/HMR.
|
|
25
|
-
*/
|
|
26
|
-
export function resolvePageModule(module, isMdx, normalizePageConfig) {
|
|
27
|
-
const Page = module.default ?? module;
|
|
28
|
-
if (isMdx && module.config && Page && typeof Page === 'function') {
|
|
29
|
-
Object.assign(Page, { config: module.config });
|
|
30
|
-
normalizePageConfig?.(module.config);
|
|
31
|
-
}
|
|
32
|
-
return {
|
|
33
|
-
Page,
|
|
34
|
-
preload: isPagePreload(module.preload) ? module.preload : undefined,
|
|
35
|
-
};
|
|
36
|
-
}
|
|
9
|
+
export { resolvePageModule } from './page-hydration-module.js';
|
|
10
|
+
import { handlePageHmr } from './page-hydration-hmr.js';
|
|
37
11
|
/** Returns and lazily initializes the shared page runtime on `window`. */
|
|
38
12
|
function getRuntime() {
|
|
39
13
|
const pageWindow = window;
|
|
@@ -95,10 +69,6 @@ function registerRouterOwnership(options) {
|
|
|
95
69
|
});
|
|
96
70
|
runtime.navigation?.claimOwnership?.('react-router');
|
|
97
71
|
}
|
|
98
|
-
/** Returns the live page root without selecting a root by page or component key. */
|
|
99
|
-
function getPageRoot() {
|
|
100
|
-
return getRuntime().react?.pageRoot ?? null;
|
|
101
|
-
}
|
|
102
72
|
/**
|
|
103
73
|
* Checks whether asynchronous work still belongs to the current page instance.
|
|
104
74
|
*
|
|
@@ -110,53 +80,6 @@ function getPageRoot() {
|
|
|
110
80
|
function isCurrentMountGeneration(generation) {
|
|
111
81
|
return (getRuntime().react?.mountGeneration ?? 0) === generation;
|
|
112
82
|
}
|
|
113
|
-
/**
|
|
114
|
-
* Imports and applies one HMR page update.
|
|
115
|
-
*
|
|
116
|
-
* @remarks
|
|
117
|
-
* The registration generation is checked before importing and after each await,
|
|
118
|
-
* so handlers retained across navigation cannot update a replacement page.
|
|
119
|
-
* The replacement is published only after its preload succeeds. Initial startup
|
|
120
|
-
* may finish with the previous component while that preload is pending; it must
|
|
121
|
-
* never render the replacement before its dependencies are ready.
|
|
122
|
-
*/
|
|
123
|
-
async function handleHmr(options, newUrl, generation) {
|
|
124
|
-
if (!options.hmr || !isCurrentMountGeneration(generation))
|
|
125
|
-
return;
|
|
126
|
-
try {
|
|
127
|
-
const newModule = (await import(/* @vite-ignore */ newUrl));
|
|
128
|
-
if (!isCurrentMountGeneration(generation))
|
|
129
|
-
return;
|
|
130
|
-
const nextPage = resolvePageModule(newModule, options.isMdx, options.normalizePageConfig);
|
|
131
|
-
const nextProps = options.pageDataReader.getPageDataFromDocument();
|
|
132
|
-
await nextPage.preload?.(nextProps);
|
|
133
|
-
if (!isCurrentMountGeneration(generation))
|
|
134
|
-
return;
|
|
135
|
-
const currentPage = options.Page;
|
|
136
|
-
options.Page = nextPage.Page;
|
|
137
|
-
options.preload = nextPage.preload;
|
|
138
|
-
if (options.hasRouter && getRuntime().navigation?.getOwnerState?.().owner === 'react-router') {
|
|
139
|
-
const currentLayoutStack = options.hmr.getLayoutStack?.(currentPage) ?? '';
|
|
140
|
-
const nextLayoutStack = options.hmr.getLayoutStack?.(nextPage.Page) ?? '';
|
|
141
|
-
await getRuntime().navigation?.reloadCurrentPage?.({
|
|
142
|
-
clearCache: currentLayoutStack !== nextLayoutStack,
|
|
143
|
-
moduleUrl: newUrl,
|
|
144
|
-
source: 'react-router',
|
|
145
|
-
});
|
|
146
|
-
console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated via router`);
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
const activeRoot = getPageRoot();
|
|
150
|
-
if (!activeRoot || !isCurrentMountGeneration(generation))
|
|
151
|
-
return;
|
|
152
|
-
setPageState(options, readPageData(options));
|
|
153
|
-
activeRoot.render(options.createTree(nextPage.Page, nextProps));
|
|
154
|
-
console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated`);
|
|
155
|
-
}
|
|
156
|
-
catch (error) {
|
|
157
|
-
console.error(`[ecopages] Failed to hot-reload ${options.isMdx ? 'MDX' : 'React'} component:`, error);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
83
|
/**
|
|
161
84
|
* Registers HMR before initial preload and binds it to this page generation.
|
|
162
85
|
*
|
|
@@ -172,7 +95,7 @@ function registerHmr(options) {
|
|
|
172
95
|
const runtime = getRuntime();
|
|
173
96
|
const generation = runtime.react?.mountGeneration ?? 0;
|
|
174
97
|
runtime.hmrHandlers ??= {};
|
|
175
|
-
runtime.hmrHandlers[options.hmr.importPath] = (newUrl) =>
|
|
98
|
+
runtime.hmrHandlers[options.hmr.importPath] = (newUrl) => handlePageHmr(options, newUrl, generation, readPageData, setPageState, (opts) => opts.pageDataReader.getPageDataFromDocument());
|
|
176
99
|
}
|
|
177
100
|
/**
|
|
178
101
|
* Coalesces concurrent page starts into one promise.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Complete inputs that affect a Page hydration script's generated source. */
|
|
2
|
+
export type CompiledPageHydrationOptions = {
|
|
3
|
+
importPath: string;
|
|
4
|
+
pageModuleUrlExpression: string;
|
|
5
|
+
scriptId: string;
|
|
6
|
+
reactImportPath: string;
|
|
7
|
+
reactDomClientImportPath: string;
|
|
8
|
+
routerImportPath?: string;
|
|
9
|
+
layoutComposeImportPath: string;
|
|
10
|
+
pageLayoutNormalizationImportPath: string;
|
|
11
|
+
routerComponents?: {
|
|
12
|
+
router: string;
|
|
13
|
+
pageContent: string;
|
|
14
|
+
};
|
|
15
|
+
routerPropsExpression?: string;
|
|
16
|
+
hmrEnabled: boolean;
|
|
17
|
+
isMdx: boolean;
|
|
18
|
+
hasPagePreload: boolean;
|
|
19
|
+
minify: boolean;
|
|
20
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -44,7 +44,7 @@ describe('React page lifecycle', () => {
|
|
|
44
44
|
});
|
|
45
45
|
it('registers router ownership and cleanup', async () => {
|
|
46
46
|
const testWindow = window;
|
|
47
|
-
|
|
47
|
+
const testState = {
|
|
48
48
|
hydrateCalls: [],
|
|
49
49
|
renderCalls: [],
|
|
50
50
|
claimedOwners: [],
|
|
@@ -52,26 +52,27 @@ describe('React page lifecycle', () => {
|
|
|
52
52
|
registrations: [],
|
|
53
53
|
unmountCount: 0,
|
|
54
54
|
};
|
|
55
|
+
testWindow.__ECO_REACT_HYDRATION_TEST__ = testState;
|
|
55
56
|
testWindow.__ECO_PAGES__ = {
|
|
56
57
|
navigation: {
|
|
57
58
|
getOwnerState: () => ({ owner: 'html', canHandleSpaNavigation: false }),
|
|
58
|
-
register: (registration) =>
|
|
59
|
-
claimOwnership: (owner) =>
|
|
60
|
-
releaseOwnership: (owner) =>
|
|
59
|
+
register: (registration) => testState.registrations.push(registration),
|
|
60
|
+
claimOwnership: (owner) => testState.claimedOwners.push(owner),
|
|
61
|
+
releaseOwnership: (owner) => testState.releasedOwners.push(owner),
|
|
61
62
|
},
|
|
62
63
|
};
|
|
63
64
|
document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
|
|
64
65
|
startPageHydration(createPageOptions(testWindow, true));
|
|
65
66
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
66
|
-
expect(
|
|
67
|
-
expect(
|
|
68
|
-
expect(
|
|
69
|
-
expect(
|
|
70
|
-
expect(
|
|
67
|
+
expect(testState.hydrateCalls).toHaveLength(1);
|
|
68
|
+
expect(testState.hydrateCalls[0].containerTag).toBe('BODY');
|
|
69
|
+
expect(testState.hydrateCalls[0].hasRecoverableErrorHandler).toBe(true);
|
|
70
|
+
expect(testState.claimedOwners).toEqual(['react-router']);
|
|
71
|
+
expect(testState.registrations).toHaveLength(1);
|
|
71
72
|
expect(typeof testWindow.__ECO_PAGES__?.react?.cleanupPageRoot).toBe('function');
|
|
72
73
|
await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
|
|
73
|
-
expect(
|
|
74
|
-
expect(
|
|
74
|
+
expect(testState.unmountCount).toBe(1);
|
|
75
|
+
expect(testState.releasedOwners).toEqual(['react-router']);
|
|
75
76
|
expect(testWindow.__ECO_PAGES__?.page).toBeUndefined();
|
|
76
77
|
expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBeNull();
|
|
77
78
|
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
function assertRouterConfiguration(options) {
|
|
2
|
+
if (options.routerComponents && !options.routerImportPath) {
|
|
3
|
+
throw new Error('routerImportPath is required when router components are configured');
|
|
4
|
+
}
|
|
5
|
+
if (options.routerComponents && !options.routerPropsExpression) {
|
|
6
|
+
throw new Error('routerPropsExpression is required when router components are configured');
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
function buildPageImport(options) {
|
|
10
|
+
if (options.isMdx || options.hasPagePreload) {
|
|
11
|
+
return `import * as PageModule from ${JSON.stringify(options.importPath)};`;
|
|
12
|
+
}
|
|
13
|
+
return `import Page from ${JSON.stringify(options.importPath)};`;
|
|
14
|
+
}
|
|
15
|
+
function buildInitialPageBinding(options) {
|
|
16
|
+
if (options.isMdx || options.hasPagePreload) {
|
|
17
|
+
return `const initialPage = resolvePageModule(PageModule, ${options.isMdx}, ${options.isMdx ? 'ensurePageConfigLayouts' : 'undefined'});`;
|
|
18
|
+
}
|
|
19
|
+
return `const initialPage = resolvePageModule({ default: Page }, false);`;
|
|
20
|
+
}
|
|
21
|
+
function buildRouterImports(options) {
|
|
22
|
+
if (!options.routerComponents)
|
|
23
|
+
return '';
|
|
24
|
+
return `import { ${options.routerComponents.router}, ${options.routerComponents.pageContent} } from ${JSON.stringify(options.routerImportPath)};`;
|
|
25
|
+
}
|
|
26
|
+
function buildRouterTree(options) {
|
|
27
|
+
if (!options.routerComponents) {
|
|
28
|
+
return 'const createTree = (Page, props) => composeLayoutPageTree(Page, props);';
|
|
29
|
+
}
|
|
30
|
+
return `const createTree = (Page, props) => {
|
|
31
|
+
const pageContent = createElement(${options.routerComponents.pageContent});
|
|
32
|
+
return createElement(${options.routerComponents.router}, ${options.routerPropsExpression}, pageContent);
|
|
33
|
+
};`;
|
|
34
|
+
}
|
|
35
|
+
function buildNormalizationImport(options) {
|
|
36
|
+
if (!options.isMdx)
|
|
37
|
+
return '';
|
|
38
|
+
return `import { ensurePageConfigLayouts } from ${JSON.stringify(options.pageLayoutNormalizationImportPath)};`;
|
|
39
|
+
}
|
|
40
|
+
function buildHmrOptions(options) {
|
|
41
|
+
if (!options.hmrEnabled)
|
|
42
|
+
return '';
|
|
43
|
+
const layoutStack = options.routerComponents
|
|
44
|
+
? 'getLayoutStack: (Page) => (Page.config?.layouts ?? []).map((layout) => layout?.config?.identity?.file ?? "").join("|"),'
|
|
45
|
+
: '';
|
|
46
|
+
return `hmr: {
|
|
47
|
+
importPath: ${JSON.stringify(options.importPath)},
|
|
48
|
+
${layoutStack}
|
|
49
|
+
},`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates the Page entry contract consumed by the browser lifecycle.
|
|
53
|
+
*/
|
|
54
|
+
export function createPageEntrySource(options) {
|
|
55
|
+
assertRouterConfiguration(options);
|
|
56
|
+
const pageBootstrapId = '\0ecopages-react-page-bootstrap';
|
|
57
|
+
const pageDataReaderId = '\0ecopages-react-page-data-reader';
|
|
58
|
+
return `
|
|
59
|
+
import { hydrateRoot } from ${JSON.stringify(options.reactDomClientImportPath)};
|
|
60
|
+
import { createElement } from ${JSON.stringify(options.reactImportPath)};
|
|
61
|
+
import { resolvePageModule, startPageHydration } from ${JSON.stringify(pageBootstrapId)};
|
|
62
|
+
import { readPageDataDocument, getPageDataFromDocument } from ${JSON.stringify(pageDataReaderId)};
|
|
63
|
+
${options.routerComponents ? '' : `import { composeLayoutPageTree } from ${JSON.stringify(options.layoutComposeImportPath)};`}
|
|
64
|
+
${buildRouterImports(options)}
|
|
65
|
+
${buildNormalizationImport(options)}
|
|
66
|
+
${buildPageImport(options)}
|
|
67
|
+
const pageModuleUrl = ${options.pageModuleUrlExpression};
|
|
68
|
+
${buildInitialPageBinding(options)}
|
|
69
|
+
${buildRouterTree(options)}
|
|
70
|
+
export default initialPage.Page;
|
|
71
|
+
${options.hasPagePreload ? 'export const preload = initialPage.preload;' : ''}
|
|
72
|
+
export const config = initialPage.Page.config;
|
|
73
|
+
startPageHydration({
|
|
74
|
+
scriptId: ${JSON.stringify(options.scriptId)},
|
|
75
|
+
pageModuleUrl,
|
|
76
|
+
Page: initialPage.Page,
|
|
77
|
+
pageDataReader: { readPageDataDocument, getPageDataFromDocument },
|
|
78
|
+
runtime: { hydrateRoot, createElement },
|
|
79
|
+
createTree,
|
|
80
|
+
hasRouter: ${Boolean(options.routerComponents)},
|
|
81
|
+
isMdx: ${options.isMdx},
|
|
82
|
+
${options.isMdx ? 'normalizePageConfig: ensurePageConfigLayouts,' : ''}
|
|
83
|
+
${options.hasPagePreload ? 'preload: initialPage.preload,' : ''}
|
|
84
|
+
${buildHmrOptions(options)}
|
|
85
|
+
});
|
|
86
|
+
`.trim();
|
|
87
|
+
}
|
|
@@ -10,26 +10,8 @@ export type CompiledIslandHydrationOptions = {
|
|
|
10
10
|
minify: boolean;
|
|
11
11
|
hmrEnabled?: boolean;
|
|
12
12
|
};
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
importPath: string;
|
|
16
|
-
pageModuleUrlExpression: string;
|
|
17
|
-
scriptId: string;
|
|
18
|
-
reactImportPath: string;
|
|
19
|
-
reactDomClientImportPath: string;
|
|
20
|
-
routerImportPath?: string;
|
|
21
|
-
layoutComposeImportPath: string;
|
|
22
|
-
pageLayoutNormalizationImportPath: string;
|
|
23
|
-
routerComponents?: {
|
|
24
|
-
router: string;
|
|
25
|
-
pageContent: string;
|
|
26
|
-
};
|
|
27
|
-
routerPropsExpression?: string;
|
|
28
|
-
hmrEnabled: boolean;
|
|
29
|
-
isMdx: boolean;
|
|
30
|
-
hasPagePreload: boolean;
|
|
31
|
-
minify: boolean;
|
|
32
|
-
};
|
|
13
|
+
export type { CompiledPageHydrationOptions } from './compiled-page-hydration-options.js';
|
|
14
|
+
import type { CompiledPageHydrationOptions } from './compiled-page-hydration-options.js';
|
|
33
15
|
/**
|
|
34
16
|
* Compiles the editable React Island Host lifecycle into a browser ESM string.
|
|
35
17
|
*
|