@ecopages/react 0.2.0-rc.6 → 0.2.0-rc.7

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.
@@ -0,0 +1,254 @@
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
+ /** Identifies a named preload export without widening the module boundary. */
10
+ function isPagePreload(value) {
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
+ }
37
+ /** Returns and lazily initializes the shared page runtime on `window`. */
38
+ function getRuntime() {
39
+ const pageWindow = window;
40
+ const runtime = (pageWindow.__ECO_PAGES__ ??= {});
41
+ runtime.react ??= {};
42
+ return runtime;
43
+ }
44
+ /** Records the development hydration duration when the dev marker is present. */
45
+ function recordHydrationTiming() {
46
+ const pageWindow = window;
47
+ if (pageWindow.__ECO_DEV_HYDRATION_STARTED__ == null)
48
+ return;
49
+ pageWindow.__ECO_DEV_HYDRATION_MS__ = Math.round(performance.now() - pageWindow.__ECO_DEV_HYDRATION_STARTED__);
50
+ }
51
+ /** Reads the current page-data document through the shared reader contract. */
52
+ function readPageData(options) {
53
+ return options.pageDataReader.readPageDataDocument();
54
+ }
55
+ /** Publishes the current module URL and props for router/navigation consumers. */
56
+ function setPageState(options, pageData) {
57
+ const runtime = getRuntime();
58
+ runtime.page = {
59
+ module: pageData.moduleUrl || options.pageModuleUrl,
60
+ props: pageData.props,
61
+ };
62
+ }
63
+ /**
64
+ * Invalidates pending startup, releases the page root, and hands navigation
65
+ * ownership back to the document runtime.
66
+ *
67
+ * @remarks
68
+ * Incrementing the generation prevents an already-running preload from
69
+ * hydrating after cleanup. The pending promise is cleared so a later page can
70
+ * start independently while the old preload settles.
71
+ */
72
+ function cleanupPageRoot(root) {
73
+ const runtime = getRuntime();
74
+ if (runtime.react) {
75
+ runtime.react.mountGeneration = (runtime.react.mountGeneration ?? 0) + 1;
76
+ delete runtime.react.mountPromise;
77
+ }
78
+ const activeRoot = runtime.react?.pageRoot || root;
79
+ runtime.react.pageRoot = null;
80
+ runtime.navigation?.releaseOwnership?.('react-router');
81
+ delete runtime.page;
82
+ activeRoot?.unmount();
83
+ }
84
+ /** Registers React Router as the page navigation owner when this page uses it. */
85
+ function registerRouterOwnership(options) {
86
+ if (!options.hasRouter)
87
+ return;
88
+ const runtime = getRuntime();
89
+ const ownerState = runtime.navigation?.getOwnerState?.();
90
+ if (ownerState?.owner === 'react-router' && ownerState.canHandleSpaNavigation)
91
+ return;
92
+ runtime.navigation?.register?.({
93
+ owner: 'react-router',
94
+ cleanupBeforeHandoff: async () => cleanupPageRoot(runtime.react?.pageRoot ?? null),
95
+ });
96
+ runtime.navigation?.claimOwnership?.('react-router');
97
+ }
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
+ /**
103
+ * Checks whether asynchronous work still belongs to the current page instance.
104
+ *
105
+ * @remarks
106
+ * Cleanup increments this token before unmounting. Any import or preload that
107
+ * settles afterward must leave the document alone, even if a new page has
108
+ * already mounted a root in the same global runtime slot.
109
+ */
110
+ function isCurrentMountGeneration(generation) {
111
+ return (getRuntime().react?.mountGeneration ?? 0) === generation;
112
+ }
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
+ /**
161
+ * Registers HMR before initial preload and binds it to this page generation.
162
+ *
163
+ * @remarks
164
+ * The global handler index can outlive the page. Capturing the generation here
165
+ * makes retained callbacks inert after cleanup, including calls that begin only
166
+ * after another page has mounted. Reactivation renews this binding for the
167
+ * new generation.
168
+ */
169
+ function registerHmr(options) {
170
+ if (!options.hmr)
171
+ return;
172
+ const runtime = getRuntime();
173
+ const generation = runtime.react?.mountGeneration ?? 0;
174
+ runtime.hmrHandlers ??= {};
175
+ runtime.hmrHandlers[options.hmr.importPath] = (newUrl) => handleHmr(options, newUrl, generation);
176
+ }
177
+ /**
178
+ * Coalesces concurrent page starts into one promise.
179
+ *
180
+ * @remarks
181
+ * Rerun scripts and DOM-ready callbacks can arrive together. Sharing the
182
+ * pending promise prevents two calls to `hydrateRoot` for document.body.
183
+ */
184
+ async function mount(options) {
185
+ const runtime = getRuntime();
186
+ const reactRuntime = runtime.react;
187
+ if (reactRuntime.mountPromise)
188
+ return reactRuntime.mountPromise;
189
+ const generation = reactRuntime.mountGeneration ?? 0;
190
+ const pendingMount = mountPage(options, generation);
191
+ reactRuntime.mountPromise = pendingMount;
192
+ pendingMount.then(() => {
193
+ if (reactRuntime.mountPromise === pendingMount)
194
+ delete reactRuntime.mountPromise;
195
+ }, () => {
196
+ if (reactRuntime.mountPromise === pendingMount)
197
+ delete reactRuntime.mountPromise;
198
+ });
199
+ return pendingMount;
200
+ }
201
+ /** Performs one page start after the caller has reserved the current generation. */
202
+ async function mountPage(options, generation) {
203
+ const runtime = getRuntime();
204
+ const pageData = readPageData(options);
205
+ setPageState(options, pageData);
206
+ if (runtime.react?.pageRoot) {
207
+ if (!options.hasRouter) {
208
+ runtime.react.pageRoot.render(options.createTree(options.Page, pageData.props));
209
+ }
210
+ return;
211
+ }
212
+ await options.preload?.(pageData.props);
213
+ if (!isCurrentMountGeneration(generation))
214
+ return;
215
+ if (runtime.react?.pageRoot)
216
+ return;
217
+ window.__ECO_DEV_HYDRATION_STARTED__ = performance.now();
218
+ const root = options.runtime.hydrateRoot(document.body, options.createTree(options.Page, pageData.props), {
219
+ onRecoverableError: (error) => console.warn('[ecopages] Hydration error:', error),
220
+ });
221
+ runtime.react.pageRoot = root;
222
+ recordHydrationTiming();
223
+ }
224
+ /**
225
+ * Registers and starts the Page lifecycle when its persistent script is present.
226
+ *
227
+ * @remarks
228
+ * Restores lifecycle registration, router ownership, and HMR generation binding
229
+ * whenever the page is activated or rerun after navigation.
230
+ *
231
+ * @param options - Generated entry configuration for the current Page.
232
+ */
233
+ export function startPageHydration(options) {
234
+ if (!document.querySelector(`script[data-eco-script-id="${options.scriptId}"]`))
235
+ return;
236
+ const runtime = getRuntime();
237
+ runtime.react.pageRoot ??= null;
238
+ const initialPageData = readPageData(options);
239
+ setPageState(options, initialPageData);
240
+ const activatePage = () => {
241
+ runtime.react.cleanupPageRoot = () => cleanupPageRoot(runtime.react?.pageRoot ?? null);
242
+ registerRouterOwnership(options);
243
+ registerHmr(options);
244
+ return mount(options);
245
+ };
246
+ runtime.rerunScripts ??= {};
247
+ runtime.rerunScripts[options.scriptId] = activatePage;
248
+ if (document.readyState === 'loading') {
249
+ document.addEventListener('DOMContentLoaded', activatePage, { once: true });
250
+ }
251
+ else {
252
+ void activatePage();
253
+ }
254
+ }
@@ -33,12 +33,26 @@ type PageDependencyOptions = {
33
33
  isMdx: boolean;
34
34
  hasPagePreload?: boolean;
35
35
  };
36
+ /**
37
+ * Derives the stable component key used by asset grouping and host selectors.
38
+ *
39
+ * @remarks
40
+ * The key identifies the component entry. Individual SSR instances receive a
41
+ * separate component ID, so repeated uses share browser assets without sharing
42
+ * a React root.
43
+ *
44
+ * @param componentFile - Absolute source path of the React component.
45
+ * @param config - Optional component identity used to distinguish entries.
46
+ * @returns Stable key used in selectors and asset names.
47
+ */
36
48
  export declare function getIslandComponentKey(componentFile: string, config?: EcoComponentConfig): string;
37
49
  /**
38
50
  * Manages the creation of client-side hydration assets for React pages and component islands.
39
51
  */
40
52
  export declare class HydrationAssetService {
41
53
  private readonly config;
54
+ private readonly islandScriptCompiler;
55
+ private readonly pageScriptCompiler;
42
56
  private static readonly ROUTER_PAGE_GROUPED_BUNDLE_ID;
43
57
  constructor(config: HydrationAssetServiceConfig);
44
58
  private getIslandBundleName;
@@ -55,8 +69,13 @@ export declare class HydrationAssetService {
55
69
  resolveAssetImportPath(pagePath: string, assetName: string): Promise<string>;
56
70
  /**
57
71
  * Creates the page-owned route entry asset for hydration and client navigation.
72
+ *
73
+ * @remarks
74
+ * The entry is compiled asynchronously from the editable browser lifecycle.
75
+ * Production router pages may be grouped into the Page Browser Graph, while
76
+ * HMR entries remain separate ESM scripts with browser-resolvable imports.
58
77
  */
59
- createPageDependencies(options: PageDependencyOptions): AssetDefinition[];
78
+ createPageDependencies(options: PageDependencyOptions): Promise<AssetDefinition[]>;
60
79
  /**
61
80
  * Builds client-side assets for a React component island.
62
81
  *
@@ -11,11 +11,23 @@ import { rapidhash } from '@ecopages/core/hash';
11
11
  import { RESOLVED_ASSETS_DIR } from '@ecopages/core/constants';
12
12
  import { isReactProductionRuntime } from '../bundling/runtime-mode.js';
13
13
  import { AssetFactory, } from '@ecopages/core/services/asset-processing-service';
14
- import { createHydrationScript, createIslandHydrationScript } from './hydration-scripts.js';
14
+ import { IslandHydrationScriptCompiler, PageHydrationScriptCompiler } from './hydration-script-compiler.js';
15
15
  import { resolveHydrationBootstrapImports } from './bootstrap-imports.js';
16
16
  import { collectDeclaredModulesInConfig } from '../client-graph/declared-modules.js';
17
17
  import { hasPagePreloadExport } from '../client-graph/reachability-analyzer.js';
18
18
  import { fileSystem } from '@ecopages/file-system';
19
+ /**
20
+ * Derives the stable component key used by asset grouping and host selectors.
21
+ *
22
+ * @remarks
23
+ * The key identifies the component entry. Individual SSR instances receive a
24
+ * separate component ID, so repeated uses share browser assets without sharing
25
+ * a React root.
26
+ *
27
+ * @param componentFile - Absolute source path of the React component.
28
+ * @param config - Optional component identity used to distinguish entries.
29
+ * @returns Stable key used in selectors and asset names.
30
+ */
19
31
  export function getIslandComponentKey(componentFile, config) {
20
32
  return rapidhash(`${componentFile}:${config?.identity?.id ?? ''}`).toString();
21
33
  }
@@ -24,6 +36,8 @@ export function getIslandComponentKey(componentFile, config) {
24
36
  */
25
37
  export class HydrationAssetService {
26
38
  config;
39
+ islandScriptCompiler = new IslandHydrationScriptCompiler();
40
+ pageScriptCompiler = new PageHydrationScriptCompiler();
27
41
  static ROUTER_PAGE_GROUPED_BUNDLE_ID = 'ecopages-react-router-pages';
28
42
  constructor(config) {
29
43
  this.config = config;
@@ -61,15 +75,15 @@ export class HydrationAssetService {
61
75
  }
62
76
  /**
63
77
  * Creates the page-owned route entry asset for hydration and client navigation.
78
+ *
79
+ * @remarks
80
+ * The entry is compiled asynchronously from the editable browser lifecycle.
81
+ * Production router pages may be grouped into the Page Browser Graph, while
82
+ * HMR entries remain separate ESM scripts with browser-resolvable imports.
64
83
  */
65
- createPageDependencies(options) {
84
+ async createPageDependencies(options) {
66
85
  const { pagePath, componentName, importPath, pageModuleUrlExpression, bundleOptions, hmrEnabled, useBrowserRuntimeImports, isMdx, hasPagePreload, } = options;
67
86
  const runtimeImports = this.config.bundleService.getRuntimeImports();
68
- /**
69
- * @remarks
70
- * Production router pages share a grouped bundle. Development HMR keeps each
71
- * page bootstrap independent and unbundled; shared helpers resolve via vendor URLs.
72
- */
73
87
  const groupedBundle = !hmrEnabled && this.config.routerAdapter
74
88
  ? {
75
89
  id: HydrationAssetService.ROUTER_PAGE_GROUPED_BUNDLE_ID,
@@ -81,23 +95,26 @@ export class HydrationAssetService {
81
95
  runtimeImports,
82
96
  routerAdapterImportPath: this.config.routerAdapter?.bundle.importPath,
83
97
  });
98
+ const pageHydrationScript = await this.pageScriptCompiler.compile({
99
+ importPath: hmrEnabled ? importPath : pagePath,
100
+ pageModuleUrlExpression,
101
+ scriptId: componentName,
102
+ reactImportPath: bootstrapImports.reactImportPath,
103
+ reactDomClientImportPath: bootstrapImports.reactDomClientImportPath,
104
+ routerImportPath: bootstrapImports.routerImportPath,
105
+ layoutComposeImportPath: bootstrapImports.layoutComposeImportPath,
106
+ pageLayoutNormalizationImportPath: bootstrapImports.pageLayoutNormalizationImportPath,
107
+ routerComponents: this.config.routerAdapter?.components,
108
+ routerPropsExpression: this.config.routerAdapter?.getRouterProps('Page', 'props'),
109
+ hmrEnabled,
110
+ isMdx,
111
+ hasPagePreload: hasPagePreload === true,
112
+ minify: !hmrEnabled && isReactProductionRuntime(),
113
+ });
84
114
  return [
85
115
  AssetFactory.createContentScript({
86
116
  position: 'head',
87
- content: createHydrationScript({
88
- importPath: hmrEnabled ? importPath : pagePath,
89
- pageModuleUrlExpression,
90
- reactImportPath: bootstrapImports.reactImportPath,
91
- reactDomClientImportPath: bootstrapImports.reactDomClientImportPath,
92
- routerImportPath: bootstrapImports.routerImportPath,
93
- layoutComposeImportPath: bootstrapImports.layoutComposeImportPath,
94
- pageLayoutNormalizationImportPath: bootstrapImports.pageLayoutNormalizationImportPath,
95
- hmrEnabled,
96
- isMdx,
97
- hasPagePreload,
98
- router: this.config.routerAdapter,
99
- scriptId: componentName,
100
- }),
117
+ content: pageHydrationScript,
101
118
  name: componentName,
102
119
  packageRole: 'page-script',
103
120
  /**
@@ -140,7 +157,7 @@ export class HydrationAssetService {
140
157
  }
141
158
  const importPath = await this.resolveAssetImportPath(componentFile, componentName);
142
159
  const runtimeImports = this.config.bundleService.getRuntimeImports();
143
- const islandHydrationScript = createIslandHydrationScript({
160
+ const islandHydrationOptions = {
144
161
  importPath,
145
162
  scriptId: hydrationName,
146
163
  reactImportPath: runtimeImports.react,
@@ -150,7 +167,8 @@ export class HydrationAssetService {
150
167
  componentFile,
151
168
  minify: !hmrEnabled,
152
169
  hmrEnabled,
153
- });
170
+ };
171
+ const islandHydrationScript = await this.islandScriptCompiler.compile(islandHydrationOptions);
154
172
  const hydrationScript = AssetFactory.createContentScript({
155
173
  position: 'head',
156
174
  content: islandHydrationScript,
@@ -223,7 +241,7 @@ export class HydrationAssetService {
223
241
  hasPagePreload = false;
224
242
  }
225
243
  const bundleOptions = await this.config.bundleService.createBundleOptions(componentName, isMdx, declaredModules, { includeRuntime: !useBrowserRuntimeImports, splitting: usesRouterRuntime });
226
- const dependencies = this.createPageDependencies({
244
+ const dependencies = await this.createPageDependencies({
227
245
  pagePath,
228
246
  componentName,
229
247
  importPath,