@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.
Files changed (66) hide show
  1. package/README.md +21 -4
  2. package/package.json +5 -4
  3. package/src/app/client-only.js +3 -8
  4. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  5. package/src/client-graph/ast-transform-eco-page.js +71 -0
  6. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  7. package/src/client-graph/ast-transform-import-edits.js +75 -0
  8. package/src/client-graph/ast-transform-walk-imports.d.ts +19 -0
  9. package/src/client-graph/ast-transform-walk-imports.js +103 -0
  10. package/src/client-graph/ast-transform.d.ts +1 -7
  11. package/src/client-graph/ast-transform.js +42 -379
  12. package/src/client-graph/ast-walk.d.ts +10 -0
  13. package/src/client-graph/ast-walk.js +26 -0
  14. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +8 -0
  15. package/src/client-graph/boundary-plugin-read-file-inline.js +45 -0
  16. package/src/client-graph/boundary-plugin-transform.d.ts +18 -0
  17. package/src/client-graph/boundary-plugin-transform.js +61 -0
  18. package/src/client-graph/boundary-plugin.d.ts +0 -20
  19. package/src/client-graph/boundary-plugin.js +16 -98
  20. package/src/client-graph/reachability-analyzer.d.ts +2 -43
  21. package/src/client-graph/reachability-analyzer.js +20 -518
  22. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  23. package/src/client-graph/reachability-client-roots.js +59 -0
  24. package/src/client-graph/reachability-export-names.d.ts +5 -0
  25. package/src/client-graph/reachability-export-names.js +34 -0
  26. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  27. package/src/client-graph/reachability-fallback-roots.js +71 -0
  28. package/src/client-graph/reachability-preload.d.ts +10 -0
  29. package/src/client-graph/reachability-preload.js +30 -0
  30. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  31. package/src/client-graph/reachability-top-level-index.js +93 -0
  32. package/src/client-graph/reachability-traverse.d.ts +7 -0
  33. package/src/client-graph/reachability-traverse.js +201 -0
  34. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  35. package/src/hmr/hmr-strategy-process.js +83 -0
  36. package/src/hmr/hmr-strategy.d.ts +1 -0
  37. package/src/hmr/hmr-strategy.js +42 -84
  38. package/src/hydration/browser/island-hydration.d.ts +82 -0
  39. package/src/hydration/browser/island-hydration.js +247 -0
  40. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  41. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  42. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  43. package/src/hydration/browser/page-hydration-module.js +17 -0
  44. package/src/hydration/browser/page-hydration.d.ts +54 -0
  45. package/src/hydration/browser/page-hydration.js +177 -0
  46. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  47. package/src/hydration/hydration-asset.d.ts +20 -1
  48. package/src/hydration/hydration-asset.js +42 -24
  49. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  50. package/src/hydration/hydration-lifecycle.test.browser.js +409 -0
  51. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  52. package/src/hydration/hydration-page-entry-source.js +87 -0
  53. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  54. package/src/hydration/hydration-script-compiler.js +213 -0
  55. package/src/hydration/page-data-reader.d.ts +0 -14
  56. package/src/hydration/page-data-reader.js +1 -47
  57. package/src/render/component-ssr.d.ts +17 -0
  58. package/src/render/component-ssr.js +19 -1
  59. package/src/render/react-renderer.d.ts +2 -1
  60. package/src/render/react-renderer.js +5 -1
  61. package/src/render/unified-layout-composition.d.ts +2 -0
  62. package/src/render/unified-layout-composition.js +5 -1
  63. package/src/hydration/hydration-scripts.d.ts +0 -112
  64. package/src/hydration/hydration-scripts.js +0 -517
  65. package/src/hydration/hydration-scripts.test.browser.js +0 -199
  66. /package/src/hydration/{hydration-scripts.test.browser.d.ts → compiled-page-hydration-options.js} +0 -0
@@ -0,0 +1,177 @@
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 { resolvePageModule } from './page-hydration-module.js';
10
+ import { handlePageHmr } from './page-hydration-hmr.js';
11
+ /** Returns and lazily initializes the shared page runtime on `window`. */
12
+ function getRuntime() {
13
+ const pageWindow = window;
14
+ const runtime = (pageWindow.__ECO_PAGES__ ??= {});
15
+ runtime.react ??= {};
16
+ return runtime;
17
+ }
18
+ /** Records the development hydration duration when the dev marker is present. */
19
+ function recordHydrationTiming() {
20
+ const pageWindow = window;
21
+ if (pageWindow.__ECO_DEV_HYDRATION_STARTED__ == null)
22
+ return;
23
+ pageWindow.__ECO_DEV_HYDRATION_MS__ = Math.round(performance.now() - pageWindow.__ECO_DEV_HYDRATION_STARTED__);
24
+ }
25
+ /** Reads the current page-data document through the shared reader contract. */
26
+ function readPageData(options) {
27
+ return options.pageDataReader.readPageDataDocument();
28
+ }
29
+ /** Publishes the current module URL and props for router/navigation consumers. */
30
+ function setPageState(options, pageData) {
31
+ const runtime = getRuntime();
32
+ runtime.page = {
33
+ module: pageData.moduleUrl || options.pageModuleUrl,
34
+ props: pageData.props,
35
+ };
36
+ }
37
+ /**
38
+ * Invalidates pending startup, releases the page root, and hands navigation
39
+ * ownership back to the document runtime.
40
+ *
41
+ * @remarks
42
+ * Incrementing the generation prevents an already-running preload from
43
+ * hydrating after cleanup. The pending promise is cleared so a later page can
44
+ * start independently while the old preload settles.
45
+ */
46
+ function cleanupPageRoot(root) {
47
+ const runtime = getRuntime();
48
+ if (runtime.react) {
49
+ runtime.react.mountGeneration = (runtime.react.mountGeneration ?? 0) + 1;
50
+ delete runtime.react.mountPromise;
51
+ }
52
+ const activeRoot = runtime.react?.pageRoot || root;
53
+ runtime.react.pageRoot = null;
54
+ runtime.navigation?.releaseOwnership?.('react-router');
55
+ delete runtime.page;
56
+ activeRoot?.unmount();
57
+ }
58
+ /** Registers React Router as the page navigation owner when this page uses it. */
59
+ function registerRouterOwnership(options) {
60
+ if (!options.hasRouter)
61
+ return;
62
+ const runtime = getRuntime();
63
+ const ownerState = runtime.navigation?.getOwnerState?.();
64
+ if (ownerState?.owner === 'react-router' && ownerState.canHandleSpaNavigation)
65
+ return;
66
+ runtime.navigation?.register?.({
67
+ owner: 'react-router',
68
+ cleanupBeforeHandoff: async () => cleanupPageRoot(runtime.react?.pageRoot ?? null),
69
+ });
70
+ runtime.navigation?.claimOwnership?.('react-router');
71
+ }
72
+ /**
73
+ * Checks whether asynchronous work still belongs to the current page instance.
74
+ *
75
+ * @remarks
76
+ * Cleanup increments this token before unmounting. Any import or preload that
77
+ * settles afterward must leave the document alone, even if a new page has
78
+ * already mounted a root in the same global runtime slot.
79
+ */
80
+ function isCurrentMountGeneration(generation) {
81
+ return (getRuntime().react?.mountGeneration ?? 0) === generation;
82
+ }
83
+ /**
84
+ * Registers HMR before initial preload and binds it to this page generation.
85
+ *
86
+ * @remarks
87
+ * The global handler index can outlive the page. Capturing the generation here
88
+ * makes retained callbacks inert after cleanup, including calls that begin only
89
+ * after another page has mounted. Reactivation renews this binding for the
90
+ * new generation.
91
+ */
92
+ function registerHmr(options) {
93
+ if (!options.hmr)
94
+ return;
95
+ const runtime = getRuntime();
96
+ const generation = runtime.react?.mountGeneration ?? 0;
97
+ runtime.hmrHandlers ??= {};
98
+ runtime.hmrHandlers[options.hmr.importPath] = (newUrl) => handlePageHmr(options, newUrl, generation, readPageData, setPageState, (opts) => opts.pageDataReader.getPageDataFromDocument());
99
+ }
100
+ /**
101
+ * Coalesces concurrent page starts into one promise.
102
+ *
103
+ * @remarks
104
+ * Rerun scripts and DOM-ready callbacks can arrive together. Sharing the
105
+ * pending promise prevents two calls to `hydrateRoot` for document.body.
106
+ */
107
+ async function mount(options) {
108
+ const runtime = getRuntime();
109
+ const reactRuntime = runtime.react;
110
+ if (reactRuntime.mountPromise)
111
+ return reactRuntime.mountPromise;
112
+ const generation = reactRuntime.mountGeneration ?? 0;
113
+ const pendingMount = mountPage(options, generation);
114
+ reactRuntime.mountPromise = pendingMount;
115
+ pendingMount.then(() => {
116
+ if (reactRuntime.mountPromise === pendingMount)
117
+ delete reactRuntime.mountPromise;
118
+ }, () => {
119
+ if (reactRuntime.mountPromise === pendingMount)
120
+ delete reactRuntime.mountPromise;
121
+ });
122
+ return pendingMount;
123
+ }
124
+ /** Performs one page start after the caller has reserved the current generation. */
125
+ async function mountPage(options, generation) {
126
+ const runtime = getRuntime();
127
+ const pageData = readPageData(options);
128
+ setPageState(options, pageData);
129
+ if (runtime.react?.pageRoot) {
130
+ if (!options.hasRouter) {
131
+ runtime.react.pageRoot.render(options.createTree(options.Page, pageData.props));
132
+ }
133
+ return;
134
+ }
135
+ await options.preload?.(pageData.props);
136
+ if (!isCurrentMountGeneration(generation))
137
+ return;
138
+ if (runtime.react?.pageRoot)
139
+ return;
140
+ window.__ECO_DEV_HYDRATION_STARTED__ = performance.now();
141
+ const root = options.runtime.hydrateRoot(document.body, options.createTree(options.Page, pageData.props), {
142
+ onRecoverableError: (error) => console.warn('[ecopages] Hydration error:', error),
143
+ });
144
+ runtime.react.pageRoot = root;
145
+ recordHydrationTiming();
146
+ }
147
+ /**
148
+ * Registers and starts the Page lifecycle when its persistent script is present.
149
+ *
150
+ * @remarks
151
+ * Restores lifecycle registration, router ownership, and HMR generation binding
152
+ * whenever the page is activated or rerun after navigation.
153
+ *
154
+ * @param options - Generated entry configuration for the current Page.
155
+ */
156
+ export function startPageHydration(options) {
157
+ if (!document.querySelector(`script[data-eco-script-id="${options.scriptId}"]`))
158
+ return;
159
+ const runtime = getRuntime();
160
+ runtime.react.pageRoot ??= null;
161
+ const initialPageData = readPageData(options);
162
+ setPageState(options, initialPageData);
163
+ const activatePage = () => {
164
+ runtime.react.cleanupPageRoot = () => cleanupPageRoot(runtime.react?.pageRoot ?? null);
165
+ registerRouterOwnership(options);
166
+ registerHmr(options);
167
+ return mount(options);
168
+ };
169
+ runtime.rerunScripts ??= {};
170
+ runtime.rerunScripts[options.scriptId] = activatePage;
171
+ if (document.readyState === 'loading') {
172
+ document.addEventListener('DOMContentLoaded', activatePage, { once: true });
173
+ }
174
+ else {
175
+ void activatePage();
176
+ }
177
+ }
@@ -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
+ };
@@ -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,