@ecopages/react 0.3.2 → 0.5.0

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 (36) hide show
  1. package/README.md +21 -6
  2. package/package.json +10 -10
  3. package/src/client-graph/reachability-analyzer.d.ts +1 -2
  4. package/src/client-graph/reachability-analyzer.js +2 -4
  5. package/src/client-graph/reachability-client-roots.d.ts +1 -8
  6. package/src/client-graph/reachability-client-roots.js +8 -25
  7. package/src/client-graph/reachability-top-level-index.d.ts +1 -2
  8. package/src/client-graph/reachability-top-level-index.js +7 -11
  9. package/src/content/lazy-collection-components.d.ts +38 -0
  10. package/src/content/lazy-collection-components.js +104 -0
  11. package/src/hydration/browser/page-hydration-hmr.js +8 -13
  12. package/src/hydration/browser/page-hydration-module.d.ts +2 -6
  13. package/src/hydration/browser/page-hydration-module.js +3 -9
  14. package/src/hydration/browser/page-hydration.d.ts +8 -6
  15. package/src/hydration/browser/page-hydration.js +120 -50
  16. package/src/hydration/compiled-page-hydration-options.d.ts +0 -1
  17. package/src/hydration/hydration-asset.d.ts +5 -10
  18. package/src/hydration/hydration-asset.js +11 -54
  19. package/src/hydration/hydration-page-entry-source.js +8 -10
  20. package/src/plugin/react.constants.d.ts +4 -0
  21. package/src/plugin/react.constants.js +4 -0
  22. package/src/plugin/react.plugin.js +11 -2
  23. package/src/plugin/react.types.d.ts +23 -0
  24. package/src/render/component-ssr.d.ts +5 -6
  25. package/src/render/component-ssr.js +8 -9
  26. package/src/render/errors.d.ts +1 -1
  27. package/src/render/errors.js +2 -2
  28. package/src/render/layout-compose.d.ts +1 -1
  29. package/src/render/react-renderer.d.ts +2 -11
  30. package/src/render/react-renderer.js +30 -65
  31. package/src/render/react-runtime.d.ts +50 -2
  32. package/src/render/react-runtime.js +131 -1
  33. package/src/client-graph/reachability-preload.d.ts +0 -10
  34. package/src/client-graph/reachability-preload.js +0 -30
  35. package/src/content/collection-component-cache.d.ts +0 -25
  36. package/src/content/collection-component-cache.js +0 -62
package/README.md CHANGED
@@ -26,7 +26,7 @@ For component-level islands, Ecopages React uses this contract:
26
26
 
27
27
  - SSR output preserves the authored DOM structure (no unnecessary wrapper elements).
28
28
  - A stable island host contract is stamped on the component SSR root via core (`data-eco-island`, `data-eco-island-integration`, `data-eco-component-id`, optional `data-eco-component-key` / `data-eco-props`).
29
- - During non-HMR runtime rendering, island and lazy-entry client modules are built together from the page client plan, in one grouped browser build during route preparation. Static production export contributes React hydration and lazy entries, every Integration's Page Browser Graph entries, and HTML Page and `html.html` shell module scripts to compatible app-wide browser build groups. Hydration scripts import the recorded output URLs. Same-integration Page, Layout, and includes are hydrated by the page bootstrap. The Html shell is not an island, even when its Integration differs from the page owner. Only a React component whose Integration differs from its parent's, on another owner's page, receives a per-component island script. SSR stamps the host and attaches those assets; it does not start a per-island build.
29
+ - During non-HMR runtime rendering, island and lazy-entry client modules are built together from the page client plan, in one grouped browser build during route preparation. Static production export contributes React hydration and lazy entries, every Integration's Page Browser Graph entries, and HTML Page and `html.html` shell module scripts to compatible app-wide browser build groups. Hydration scripts import the recorded output URLs. Same-integration Page, Layout, and includes are hydrated by the page bootstrap. The Html shell is not an island, even when its Integration differs from the page owner. Only a React component whose Integration differs from its parent's, on another owner's page, receives a per-component island script. Those scripts join the page's assets during route preparation; SSR only stamps the host and never starts a per-island build.
30
30
  - Each island component gets its own hydration script, keyed by its component identity. A file that exports several island components is built once and its declared modules are merged, while each component's hosts hydrate the export whose identity matches.
31
31
  - The island runtime keeps the SSR host and its children in place and hydrates that host with `hydrateRoot()`. The host uses `display: contents` so it does not introduce an extra layout box. Full-page hydration paths also use `hydrateRoot()`.
32
32
 
@@ -87,7 +87,9 @@ Keep server helpers close, but separate them physically or logically so they do
87
87
 
88
88
  The `.server` naming rule comes from the browser-safe `@ecopages/core/build/contracts` entry. React applies it during import pruning before core's browser resolution guard runs. A Page that uses `.server.ts` imports only in server options such as `middleware` still builds: the imports and server options are removed before resolution.
89
89
 
90
- For a hydratable Page that renders collection MDX, use `createCollectionComponentCache()` with the collection's `/browser` loader. Export `preload` from the Page so hydration, router navigation, and HMR load the current entry before synchronous render. The server may prime the same cache with `/server`'s `getComponent()` inside `staticProps`; `dependencies` remains server-only and is removed from the Page Browser Graph.
90
+ For a hydratable Page that renders collection MDX, call `createLazyCollectionComponents()` from `@ecopages/react/lazy-collection-components` once at module level with the collection's `/component` loader. Its `get(slug)` returns one `React.lazy` component per slug, so the Page reads `const Content = posts.get(entry.slug)` and renders `<Content />` inside a `<Suspense>` boundary. The server waits for the entry and sends it in the HTML, hydration keeps that HTML until the browser has loaded the entry, and `dependencies` stays server-only and is removed from the Page Browser Graph. Keep the boundary at a fixed place in the Page, not keyed by slug: when a client navigation moves to another entry, React then leaves the current Page on screen until the next entry has loaded instead of showing the fallback. When the browser cannot load an entry during a client navigation (a replaced chunk, a dropped connection), `@ecopages/react-router` falls back to a full navigation to that URL. The helper keeps one lookup per collection outside the Page module. In development, HMR of the Page module therefore renders the already-loaded entry again without the Suspense fallback; the Page's own DOM is still replaced, because the reloaded Page is a new component. An edited MDX file re-renders that entry in place without a document reload. On the server, a reloaded server module graph starts a new lookup.
91
+
92
+ A load that fails while the first Page hydrates is not retried. React tears the Page root down, and the server HTML is put back, so the Page stays readable but is no longer interactive. Nodes that other scripts added to the body stay, and in development the next edit to the Page reloads the document. The same happens for any uncaught error on the first-loaded Page, such as a lazy modal chunk that fails later, until the Page re-renders or the router has navigated; after a client navigation the router turns a Page render error into a full navigation instead. A Page-level error boundary around the entry catches the error first: the rest of the Page stays and the boundary fallback is shown. Those outcomes are the same with and without the router. The Playwright specs below run against `ecopages dev`, where the lazy import is a separate request.
91
93
 
92
94
  ## Client Graph Boundary Architecture
93
95
 
@@ -216,6 +218,11 @@ The main regression coverage lives in:
216
218
  - [src/render/react-renderer.locals.test.ts](src/render/react-renderer.locals.test.ts): verifies only declared `requires` keys are serialized into hydration payloads.
217
219
  - [src/hydration/hydration-script-compiler.test.ts](src/hydration/hydration-script-compiler.test.ts): verifies editable browser sources compile to readable and minified entries.
218
220
  - [../../react-router/test/layout-persistence.test.browser.ts](../../react-router/test/layout-persistence.test.browser.ts): verifies router-backed layout hydration receives `locals` with `persistLayouts` both enabled and disabled.
221
+ - [src/hydration/hydration-lifecycle.test.browser.ts](src/hydration/hydration-lifecycle.test.browser.ts): an uncaught `React.lazy` rejection during first hydration restores the server HTML, keeps body nodes added after mount, drops the page root and makes the next HMR update reload; a Page-level error boundary around the entry still shows its fallback.
222
+ - [../../../playground/kitchen-sink/e2e/content-lazy.test.e2e.ts](../../../playground/kitchen-sink/e2e/content-lazy.test.e2e.ts): a collection chunk that fails during first hydration restores the server HTML (including the playground shell) and is not retried. A Page-level error boundary around the entry keeps the rest of the Page and shows the boundary fallback.
223
+ - [../../../e2e/fixtures/react-lazy-first-load/lazy-first-load.test.e2e.ts](../../../e2e/fixtures/react-lazy-first-load/lazy-first-load.test.e2e.ts): the same first-hydration outcomes for a React Page without the router.
224
+ - [src/content/lazy-collection-components.test.tsx](src/content/lazy-collection-components.test.tsx): in the browser a new loader for the same collection keeps loaded lazy types and renders an edited entry under the same type; on the server a new loader starts a new lookup.
225
+ - [../../../playground/kitchen-sink/e2e/content-hmr.test.e2e.ts](../../../playground/kitchen-sink/e2e/content-hmr.test.e2e.ts): HMR of a collection Page renders the entry through the same resolved lazy type without the Suspense fallback. An edited MDX file still updates without a document reload.
219
226
 
220
227
  If you change the AST transform or hydration flow, update the corresponding tests in the same change.
221
228
 
@@ -223,7 +230,7 @@ If you change the AST transform or hydration flow, update the corresponding test
223
230
 
224
231
  Pages may declare `layout` as a single component or an **outer → inner** array on `eco.page()`. On the server, React-managed layout stacks compose through `composeDocumentShell` + `composeLayoutPageTree` so provider context reaches nested pages during SSR. On the client, `@ecopages/react-router` `PageContent` uses the same `composeLayoutPageTree` helper unless `persistLayouts` is enabled (then each tier is cached independently).
225
232
 
226
- During SSR, `ReactRenderer` passes the app-resolved React runtime into `composeLayoutPageTree` via `options.react` so layout trees are built with the same module instance as `renderToString`. App code should import hooks and context from `react` normally; keep a single React version in the app dependency graph (avoid duplicate `react` copies in monorepos).
233
+ During SSR, `ReactRenderer` passes the app-resolved React runtime into `composeLayoutPageTree` via `options.react` so layout trees are built with the same module instance the server renders them with. App code should import hooks and context from `react` normally; keep a single React version in the app dependency graph (avoid duplicate `react` copies in monorepos).
227
234
 
228
235
  Layout prop factories receive `LayoutPropsContext` (`params`, `query`, `locals`). Route-scoped `locals` are passed to layout tiers via document-shell props during SSR; serialized `pageProps.locals` follow `Page.requires` and are intended for the page component.
229
236
 
@@ -320,9 +327,17 @@ Use the dev toolbar **Deps** panel to inspect vendor URLs loaded by the active P
320
327
  - `../../core/src/assets/asset-processing-service/browser-runtime-entry-resolution.test.ts`: ESM entry resolution and default-export policy for React vs TanStack Query.
321
328
  - `../../../e2e/fixtures/react-router/persist-layouts.test.e2e.ts`: one QueryClient shared across Page navigation with an explicit `runtimeModules` entry.
322
329
 
323
- ### Client-only code in SSR trees
330
+ ### Suspense on the server
331
+
332
+ Server rendering waits for every `<Suspense>` boundary before it returns HTML, in Pages, Layouts and every other React component they render. A `React.lazy()` component or any other suspending child renders its content into the HTML, not its fallback. Foreign Children inside a suspended subtree resolve as they do anywhere else. The response is still sent as one complete document; it is not streamed. Waiting stops after 10 seconds by default. The limit covers the whole Page render, every React tree in it included: unfinished boundaries stay in their fallback for the browser to retry, the rest of the Page is served, and one warning names the Page. A tree that is still waiting outside every boundary has no HTML to serve, so the render fails instead. React components in a Page of another Integration each get the full limit. Pass `reactPlugin({ renderTimeoutMs: 5_000 })` to change the limit, a whole number of milliseconds from 1 to 2147483647.
333
+
334
+ React's own error handling applies. A component that throws, or a `React.lazy()` import that rejects, inside a boundary is logged on the server with `console.error`, and that boundary's fallback is served for the browser to retry. The rest of the Page renders normally. An error outside every boundary fails the render.
324
335
 
325
- Pages and layouts SSR through `renderToString`, which does not support `<Suspense>`. Do not use `React.lazy()` + `<Suspense>` in `eco.page()` or `eco.layout()` trees.
336
+ A boundary that renders a `<link rel="stylesheet" precedence>` also fails the render: React moves that content after its fallback and reveals it with an inline script. Declare the stylesheet as a Dependency instead.
337
+
338
+ - [src/test/react-ssr-suspense.test.tsx](src/test/react-ssr-suspense.test.tsx): lazy content in Pages, Layouts, Island Hosts and around Foreign Children, concurrent renders, failing boundaries and shells, the render time limit, and a precedence stylesheet that fails the render.
339
+
340
+ ### Client-only code in SSR trees
326
341
 
327
342
  Wrap browser-only UI in `ClientOnly`:
328
343
 
@@ -342,4 +357,4 @@ export const RootLayout = eco.layout({
342
357
  });
343
358
  ```
344
359
 
345
- For code-split client-only modules, `import()` inside `useEffect` within `ClientOnly` — not `lazy()`. `dynamic({ ssr: false })` must also stay inside `ClientOnly`; it renders `null` on the server and `lazy()` in the browser.
360
+ For code-split client-only modules, `import()` inside `useEffect` within `ClientOnly` — not `lazy()`, which loads and renders the module on the server. `dynamic({ ssr: false })` must also stay inside `ClientOnly`; it renders `null` on the server and `lazy()` in the browser.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/react",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "React integration for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -46,9 +46,9 @@
46
46
  "types": "./src/render/layout-compose.d.ts",
47
47
  "default": "./src/render/layout-compose.js"
48
48
  },
49
- "./collection-component-cache": {
50
- "types": "./src/content/collection-component-cache.d.ts",
51
- "default": "./src/content/collection-component-cache.js"
49
+ "./lazy-collection-components": {
50
+ "types": "./src/content/lazy-collection-components.d.ts",
51
+ "default": "./src/content/lazy-collection-components.js"
52
52
  },
53
53
  "./serialize-page-data-script": {
54
54
  "types": "./src/hydration/serialize-page-data-script.d.ts",
@@ -85,9 +85,9 @@
85
85
  "types": "./src/render/layout-compose.d.ts",
86
86
  "default": "./src/render/layout-compose.js"
87
87
  },
88
- "./collection-component-cache.ts": {
89
- "types": "./src/content/collection-component-cache.d.ts",
90
- "default": "./src/content/collection-component-cache.js"
88
+ "./lazy-collection-components.ts": {
89
+ "types": "./src/content/lazy-collection-components.d.ts",
90
+ "default": "./src/content/lazy-collection-components.js"
91
91
  },
92
92
  "./serialize-page-data-script.ts": {
93
93
  "types": "./src/hydration/serialize-page-data-script.d.ts",
@@ -104,16 +104,16 @@
104
104
  "directory": "packages/integrations/react"
105
105
  },
106
106
  "peerDependencies": {
107
- "@ecopages/core": "0.3.2",
107
+ "@ecopages/core": "0.5.0",
108
108
  "@types/react": "^19",
109
109
  "@types/react-dom": "^19",
110
110
  "react": "^19",
111
111
  "react-dom": "^19"
112
112
  },
113
113
  "dependencies": {
114
- "@ecopages/file-system": "0.3.2",
114
+ "@ecopages/file-system": "0.5.0",
115
115
  "@ecopages/logger": "^0.2.3",
116
- "@ecopages/mdx": "0.3.2",
116
+ "@ecopages/mdx": "0.5.0",
117
117
  "@mdx-js/mdx": "^3.1.1",
118
118
  "oxc-parser": "^0.141.0",
119
119
  "rolldown": "^1.1.0"
@@ -6,7 +6,6 @@
6
6
  * dependencies (imports, variables, functions, and classes) that begin from explicit client roots.
7
7
  */
8
8
  import type { ParseResult } from 'oxc-parser';
9
- export { hasPagePreloadExport } from './reachability-preload.js';
10
9
  import type { ExplicitlyRequestedExports } from './reachability-export-names.js';
11
10
  /**
12
11
  * Represents the computed results of a reachability analysis pass.
@@ -21,6 +20,6 @@ export type ReachabilityResult = {
21
20
  /**
22
21
  * Analyzes a module using Oxc AST and extracts a strict reachability graph
23
22
  * starting from client roots: `render`, `errorBoundary`, and `loadingFallback` of
24
- * `eco.page`, `eco.layout`, or `eco.component`, plus a Page's named `preload` export.
23
+ * `eco.page`, `eco.layout`, or `eco.component`.
25
24
  */
26
25
  export declare function analyzeReachability(source: string, filename: string, program?: ParseResult['program'], explicitlyRequestedExports?: ExplicitlyRequestedExports): ReachabilityResult;
@@ -6,9 +6,7 @@
6
6
  * dependencies (imports, variables, functions, and classes) that begin from explicit client roots.
7
7
  */
8
8
  import { parseModuleSource } from '@ecopages/core/build';
9
- import { finalizeClientRoots } from './reachability-client-roots.js';
10
9
  import { resolveFallbackClientRoots } from './reachability-fallback-roots.js';
11
- export { hasPagePreloadExport } from './reachability-preload.js';
12
10
  import { buildTopLevelIndex } from './reachability-top-level-index.js';
13
11
  import { runReachabilityTraversal } from './reachability-traverse.js';
14
12
  function emptyReachabilityResult(isFallbackRoots) {
@@ -23,7 +21,7 @@ function emptyReachabilityResult(isFallbackRoots) {
23
21
  /**
24
22
  * Analyzes a module using Oxc AST and extracts a strict reachability graph
25
23
  * starting from client roots: `render`, `errorBoundary`, and `loadingFallback` of
26
- * `eco.page`, `eco.layout`, or `eco.component`, plus a Page's named `preload` export.
24
+ * `eco.page`, `eco.layout`, or `eco.component`.
27
25
  */
28
26
  export function analyzeReachability(source, filename, program, explicitlyRequestedExports) {
29
27
  let resolvedProgram;
@@ -39,7 +37,7 @@ export function analyzeReachability(source, filename, program, explicitlyRequest
39
37
  }
40
38
  }
41
39
  const index = buildTopLevelIndex(resolvedProgram);
42
- const potentialClientRoots = finalizeClientRoots(index.clientRootState);
40
+ const potentialClientRoots = index.clientRoots;
43
41
  const isFallbackRoots = resolveFallbackClientRoots(resolvedProgram, potentialClientRoots, explicitlyRequestedExports);
44
42
  const { reachableImports, reachableDeclarations } = runReachabilityTraversal(potentialClientRoots, index.topLevelImports, index.topLevelDeclarations, explicitlyRequestedExports);
45
43
  const unreachableSideEffectImports = index.topLevelImports
@@ -1,8 +1 @@
1
- export type ClientRootScanState = {
2
- potentialClientRoots: unknown[];
3
- pagePreloadRoots: unknown[];
4
- hasEcoPageRoot: boolean;
5
- };
6
- export declare function createClientRootScanState(): ClientRootScanState;
7
- export declare function checkPotentialClientRoot(node: unknown, state: ClientRootScanState): void;
8
- export declare function finalizeClientRoots(state: ClientRootScanState): unknown[];
1
+ export declare function checkPotentialClientRoot(node: unknown, roots: unknown[]): void;
@@ -1,28 +1,17 @@
1
- export function createClientRootScanState() {
2
- return {
3
- potentialClientRoots: [],
4
- pagePreloadRoots: [],
5
- hasEcoPageRoot: false,
6
- };
7
- }
8
- function collectEcoPageClientProperties(arg, state) {
1
+ function collectEcoPageClientProperties(arg, roots) {
9
2
  if (!arg || arg.type !== 'ObjectExpression')
10
3
  return;
11
4
  for (const prop of arg.properties ?? []) {
12
5
  if (prop?.type === 'Property' && prop.key?.type === 'Identifier') {
13
6
  if (['render', 'errorBoundary', 'loadingFallback', 'clientScripts'].includes(prop.key.name)) {
14
- state.potentialClientRoots.push(prop.value);
7
+ roots.push(prop.value);
15
8
  }
16
9
  }
17
10
  }
18
11
  }
19
- function inspectEcoMemberCall(node, state) {
20
- const propName = node.callee.property?.name;
21
- if (propName === 'page') {
22
- state.hasEcoPageRoot = true;
23
- }
24
- state.potentialClientRoots.push(node.callee);
25
- collectEcoPageClientProperties(node.arguments?.[0], state);
12
+ function inspectEcoMemberCall(node, roots) {
13
+ roots.push(node.callee);
14
+ collectEcoPageClientProperties(node.arguments?.[0], roots);
26
15
  }
27
16
  /**
28
17
  * Inspects a node to determine if it represents an Ecopages client root declaration.
@@ -37,23 +26,17 @@ function isEcoFactoryCall(node) {
37
26
  prop?.type === 'Identifier' &&
38
27
  (prop.name === 'page' || prop.name === 'component' || prop.name === 'layout'));
39
28
  }
40
- export function checkPotentialClientRoot(node, state) {
29
+ export function checkPotentialClientRoot(node, roots) {
41
30
  if (!node || typeof node !== 'object')
42
31
  return;
43
32
  const astNode = node;
44
33
  if (astNode.type === 'CallExpression' && isEcoFactoryCall(astNode)) {
45
- inspectEcoMemberCall(astNode, state);
34
+ inspectEcoMemberCall(astNode, roots);
46
35
  return;
47
36
  }
48
37
  if (astNode.type === 'CallExpression' &&
49
38
  astNode.callee?.type === 'Identifier' &&
50
39
  astNode.callee.name === 'dynamic') {
51
- state.potentialClientRoots.push(node);
52
- }
53
- }
54
- export function finalizeClientRoots(state) {
55
- if (state.hasEcoPageRoot) {
56
- state.potentialClientRoots.push(...state.pagePreloadRoots);
40
+ roots.push(node);
57
41
  }
58
- return state.potentialClientRoots;
59
42
  }
@@ -1,5 +1,4 @@
1
1
  import type { ParseResult } from 'oxc-parser';
2
- import { type ClientRootScanState } from './reachability-client-roots.js';
3
2
  export type TopLevelImportEntry = {
4
3
  node: unknown;
5
4
  specifier: string;
@@ -9,6 +8,6 @@ export type TopLevelImportEntry = {
9
8
  export type TopLevelIndex = {
10
9
  topLevelImports: TopLevelImportEntry[];
11
10
  topLevelDeclarations: Map<string, unknown>;
12
- clientRootState: ClientRootScanState;
11
+ clientRoots: unknown[];
13
12
  };
14
13
  export declare function buildTopLevelIndex(program: ParseResult['program']): TopLevelIndex;
@@ -1,5 +1,4 @@
1
- import { checkPotentialClientRoot, createClientRootScanState, } from './reachability-client-roots.js';
2
- import { isPreloadExportStatement } from './reachability-preload.js';
1
+ import { checkPotentialClientRoot } from './reachability-client-roots.js';
3
2
  function indexImportDeclaration(statement, topLevelImports) {
4
3
  if (statement.importKind === 'type') {
5
4
  return;
@@ -26,9 +25,6 @@ function indexImportDeclaration(statement, topLevelImports) {
26
25
  }
27
26
  function indexExportNamedDeclaration(statement, index) {
28
27
  const decl = statement.declaration;
29
- if (isPreloadExportStatement(statement)) {
30
- index.clientRootState.pagePreloadRoots.push(statement);
31
- }
32
28
  if (!decl) {
33
29
  return;
34
30
  }
@@ -42,7 +38,7 @@ function indexExportNamedDeclaration(statement, index) {
42
38
  for (const v of decl.declarations) {
43
39
  if (v.id.type === 'Identifier') {
44
40
  index.topLevelDeclarations.set(v.id.name, statement);
45
- checkPotentialClientRoot(v.init, index.clientRootState);
41
+ checkPotentialClientRoot(v.init, index.clientRoots);
46
42
  }
47
43
  }
48
44
  }
@@ -51,7 +47,7 @@ export function buildTopLevelIndex(program) {
51
47
  const index = {
52
48
  topLevelImports: [],
53
49
  topLevelDeclarations: new Map(),
54
- clientRootState: createClientRootScanState(),
50
+ clientRoots: [],
55
51
  };
56
52
  for (const statement of program.body) {
57
53
  if (statement.type === 'ImportDeclaration') {
@@ -62,7 +58,7 @@ export function buildTopLevelIndex(program) {
62
58
  for (const decl of statement.declarations) {
63
59
  if (decl.id.type === 'Identifier') {
64
60
  index.topLevelDeclarations.set(decl.id.name, statement);
65
- checkPotentialClientRoot(decl.init, index.clientRootState);
61
+ checkPotentialClientRoot(decl.init, index.clientRoots);
66
62
  }
67
63
  }
68
64
  continue;
@@ -78,15 +74,15 @@ export function buildTopLevelIndex(program) {
78
74
  continue;
79
75
  }
80
76
  if (statement.type === 'ExportDefaultDeclaration') {
81
- checkPotentialClientRoot(statement.declaration, index.clientRootState);
77
+ checkPotentialClientRoot(statement.declaration, index.clientRoots);
82
78
  continue;
83
79
  }
84
80
  if (statement.type === 'ExpressionStatement') {
85
- checkPotentialClientRoot(statement.expression, index.clientRootState);
81
+ checkPotentialClientRoot(statement.expression, index.clientRoots);
86
82
  continue;
87
83
  }
88
84
  if (statement.type === 'ExportAllDeclaration' && statement.source) {
89
- index.clientRootState.potentialClientRoots.push(statement);
85
+ index.clientRoots.push(statement);
90
86
  }
91
87
  }
92
88
  return index;
@@ -0,0 +1,38 @@
1
+ import { type ComponentType, type LazyExoticComponent } from 'react';
2
+ import type { EcoComponent } from '@ecopages/core';
3
+ type CollectionComponent = EcoComponent<Record<string, unknown>>;
4
+ /** Structural copy of the content-processor `ContentCollectionLoader`, which this package does not depend on. */
5
+ type CollectionLoader = {
6
+ (slug: string): Promise<CollectionComponent>;
7
+ readonly collection: string;
8
+ };
9
+ export type LazyCollectionComponents = {
10
+ get(slug: string): LazyExoticComponent<ComponentType<Record<string, unknown>>>;
11
+ };
12
+ /**
13
+ * Creates the lookup that gives a Page one `React.lazy` component per collection entry.
14
+ *
15
+ * @remarks
16
+ * Call it once at module level so every render of a slug receives the same
17
+ * component type; React keeps the loaded entry and does not remount it.
18
+ * Server rendering waits for the entry before sending HTML, and hydration keeps
19
+ * that HTML until the browser entry has loaded.
20
+ *
21
+ * There is one lookup per collection, kept in this module, which Page HMR does not replace.
22
+ * In the browser, a later call for the same collection with a new loader (a Page module
23
+ * evaluated again by HMR or another Page sharing the collection) returns that lookup: loaded
24
+ * entries keep their lazy type and stay on screen without the Suspense fallback, and later
25
+ * loads use the new loader. Each loaded entry is loaded again through the new loader and
26
+ * re-renders in place when its module changed, which is how an edited MDX file shows up;
27
+ * a failed reload keeps the entry on screen.
28
+ * On the server a new loader means the server module graph was reloaded, so the call
29
+ * starts a new lookup instead of serving entries from the old graph. A failed load is
30
+ * dropped from the lookup, so a later render retries instead of replaying the rejection.
31
+ *
32
+ * The component suspends, so a Suspense boundary above it decides what shows
33
+ * meanwhile. Keep the boundary at a stable position in the Page: when a client
34
+ * navigation switches entries inside it, React holds the current content until
35
+ * the next entry is ready instead of showing a fallback.
36
+ */
37
+ export declare function createLazyCollectionComponents(loadComponent: CollectionLoader): LazyCollectionComponents;
38
+ export {};
@@ -0,0 +1,104 @@
1
+ import { createElement, lazy, useSyncExternalStore } from 'react';
2
+ const lookups = new Map();
3
+ /**
4
+ * @remarks
5
+ * The lazy type resolves to `Host` once, so React keeps it mounted. A newer component for the
6
+ * entry re-renders `Host` instead of suspending again, so the Suspense fallback is not shown.
7
+ */
8
+ function createLoadedEntry(initial) {
9
+ let current = initial;
10
+ const listeners = new Set();
11
+ const subscribe = (listener) => {
12
+ listeners.add(listener);
13
+ return () => listeners.delete(listener);
14
+ };
15
+ const getSnapshot = () => current;
16
+ function LoadedCollectionEntry(props) {
17
+ return createElement(useSyncExternalStore(subscribe, getSnapshot, getSnapshot), props);
18
+ }
19
+ return {
20
+ Host: LoadedCollectionEntry,
21
+ set(component) {
22
+ if (component === current)
23
+ return;
24
+ current = component;
25
+ for (const listener of listeners)
26
+ listener();
27
+ },
28
+ };
29
+ }
30
+ function createLookup(loader) {
31
+ const components = new Map();
32
+ const loaded = new Map();
33
+ const lookup = {
34
+ loader,
35
+ get(slug) {
36
+ let component = components.get(slug);
37
+ if (!component) {
38
+ component = lazy(async () => {
39
+ try {
40
+ const entry = createLoadedEntry(await lookup.loader(slug));
41
+ loaded.set(slug, entry);
42
+ return { default: entry.Host };
43
+ }
44
+ catch (error) {
45
+ components.delete(slug);
46
+ throw error;
47
+ }
48
+ });
49
+ components.set(slug, component);
50
+ }
51
+ return component;
52
+ },
53
+ refresh() {
54
+ const current = lookup.loader;
55
+ for (const [slug, entry] of loaded) {
56
+ current(slug).then((component) => {
57
+ if (lookup.loader === current)
58
+ entry.set(component);
59
+ }, (error) => {
60
+ console.error(`[ecopages] Reloading collection entry "${slug}" failed; keeping the loaded entry:`, error);
61
+ });
62
+ }
63
+ },
64
+ };
65
+ return lookup;
66
+ }
67
+ /**
68
+ * Creates the lookup that gives a Page one `React.lazy` component per collection entry.
69
+ *
70
+ * @remarks
71
+ * Call it once at module level so every render of a slug receives the same
72
+ * component type; React keeps the loaded entry and does not remount it.
73
+ * Server rendering waits for the entry before sending HTML, and hydration keeps
74
+ * that HTML until the browser entry has loaded.
75
+ *
76
+ * There is one lookup per collection, kept in this module, which Page HMR does not replace.
77
+ * In the browser, a later call for the same collection with a new loader (a Page module
78
+ * evaluated again by HMR or another Page sharing the collection) returns that lookup: loaded
79
+ * entries keep their lazy type and stay on screen without the Suspense fallback, and later
80
+ * loads use the new loader. Each loaded entry is loaded again through the new loader and
81
+ * re-renders in place when its module changed, which is how an edited MDX file shows up;
82
+ * a failed reload keeps the entry on screen.
83
+ * On the server a new loader means the server module graph was reloaded, so the call
84
+ * starts a new lookup instead of serving entries from the old graph. A failed load is
85
+ * dropped from the lookup, so a later render retries instead of replaying the rejection.
86
+ *
87
+ * The component suspends, so a Suspense boundary above it decides what shows
88
+ * meanwhile. Keep the boundary at a stable position in the Page: when a client
89
+ * navigation switches entries inside it, React holds the current content until
90
+ * the next entry is ready instead of showing a fallback.
91
+ */
92
+ export function createLazyCollectionComponents(loadComponent) {
93
+ const existing = lookups.get(loadComponent.collection);
94
+ if (existing?.loader === loadComponent)
95
+ return existing;
96
+ if (existing && typeof window !== 'undefined') {
97
+ existing.loader = loadComponent;
98
+ existing.refresh();
99
+ return existing;
100
+ }
101
+ const created = createLookup(loadComponent);
102
+ lookups.set(loadComponent.collection, created);
103
+ return created;
104
+ }
@@ -1,16 +1,16 @@
1
- import { resolvePageModule } from './page-hydration-module.js';
1
+ import { resolvePageComponent } from './page-hydration-module.js';
2
2
  function getRuntime() {
3
3
  return (window.__ECO_PAGES__ ??= {});
4
4
  }
5
5
  function isCurrentMountGeneration(generation) {
6
6
  return (getRuntime().react?.mountGeneration ?? 0) === generation;
7
7
  }
8
- async function applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, _nextProps) {
8
+ async function applyRouterHmrUpdate(options, newUrl, currentPage, nextPage) {
9
9
  if (!options.hasRouter || getRuntime().navigation?.getOwnerState?.().owner !== 'react-router') {
10
10
  return false;
11
11
  }
12
12
  const currentLayoutStack = options.hmr.getLayoutStack?.(currentPage) ?? '';
13
- const nextLayoutStack = options.hmr.getLayoutStack?.(nextPage.Page) ?? '';
13
+ const nextLayoutStack = options.hmr.getLayoutStack?.(nextPage) ?? '';
14
14
  await getRuntime().navigation?.reloadCurrentPage?.({
15
15
  clearCache: currentLayoutStack !== nextLayoutStack,
16
16
  moduleUrl: newUrl,
@@ -24,7 +24,7 @@ function applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPag
24
24
  if (!activeRoot || !isCurrentMountGeneration(generation))
25
25
  return;
26
26
  setPageState(options, readPageData(options));
27
- activeRoot.render(options.createTree(nextPage.Page, nextProps));
27
+ activeRoot.render(options.createTree(nextPage, nextProps));
28
28
  console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated`);
29
29
  }
30
30
  /**
@@ -37,18 +37,13 @@ export async function handlePageHmr(options, newUrl, generation, readPageData, s
37
37
  const newModule = (await import(/* @vite-ignore */ newUrl));
38
38
  if (!isCurrentMountGeneration(generation))
39
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;
40
+ const nextPage = resolvePageComponent(newModule, options.isMdx, options.normalizePageConfig);
45
41
  const currentPage = options.Page;
46
- options.Page = nextPage.Page;
47
- options.preload = nextPage.preload;
48
- if (await applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, nextProps)) {
42
+ options.Page = nextPage;
43
+ if (await applyRouterHmrUpdate(options, newUrl, currentPage, nextPage)) {
49
44
  return;
50
45
  }
51
- applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPageState, generation);
46
+ applyDirectHmrRender(options, nextPage, getPageDataFromDocument(options), readPageData, setPageState, generation);
52
47
  }
53
48
  catch (error) {
54
49
  console.error(`[ecopages] Failed to hot-reload ${options.isMdx ? 'MDX' : 'React'} component:`, error);
@@ -1,8 +1,4 @@
1
- export type PageModule = {
2
- Page: unknown;
3
- preload?: (props: Record<string, unknown>) => void | Promise<void>;
4
- };
5
1
  /**
6
- * Normalizes a loaded Page module into the shape used by hydration and HMR.
2
+ * Returns the Page component of a loaded Page module, attaching an MDX module's config to it.
7
3
  */
8
- export declare function resolvePageModule(module: Record<string, unknown>, isMdx: boolean, normalizePageConfig?: (config: unknown) => void): PageModule;
4
+ export declare function resolvePageComponent(module: Record<string, unknown>, isMdx: boolean, normalizePageConfig?: (config: unknown) => void): unknown;
@@ -1,17 +1,11 @@
1
- function isPagePreload(value) {
2
- return typeof value === 'function';
3
- }
4
1
  /**
5
- * Normalizes a loaded Page module into the shape used by hydration and HMR.
2
+ * Returns the Page component of a loaded Page module, attaching an MDX module's config to it.
6
3
  */
7
- export function resolvePageModule(module, isMdx, normalizePageConfig) {
4
+ export function resolvePageComponent(module, isMdx, normalizePageConfig) {
8
5
  const Page = module.default ?? module;
9
6
  if (isMdx && module.config && Page && typeof Page === 'function') {
10
7
  Object.assign(Page, { config: module.config });
11
8
  normalizePageConfig?.(module.config);
12
9
  }
13
- return {
14
- Page,
15
- preload: isPagePreload(module.preload) ? module.preload : undefined,
16
- };
10
+ return Page;
17
11
  }
@@ -10,18 +10,21 @@ export type PageRoot = {
10
10
  render: (tree: unknown) => void;
11
11
  unmount: () => void;
12
12
  };
13
+ export type PageHydrateRootOptions = {
14
+ onRecoverableError?: (error: unknown) => void;
15
+ onUncaughtError?: (error: unknown, errorInfo: {
16
+ componentStack?: string | null;
17
+ }) => void;
18
+ };
13
19
  export type PageReactRuntime = {
14
- hydrateRoot: (target: HTMLElement, tree: unknown, options?: {
15
- onRecoverableError?: (error: unknown) => void;
16
- }) => PageRoot;
20
+ hydrateRoot: (target: HTMLElement, tree: unknown, options?: PageHydrateRootOptions) => PageRoot;
17
21
  createElement: (...args: unknown[]) => unknown;
18
22
  };
19
23
  export type PageData = {
20
24
  moduleUrl?: string;
21
25
  props: Record<string, unknown>;
22
26
  };
23
- export type { PageModule } from './page-hydration-module.js';
24
- export { resolvePageModule } from './page-hydration-module.js';
27
+ export { resolvePageComponent } from './page-hydration-module.js';
25
28
  /** Configuration passed from a generated Page hydration entry. */
26
29
  export type PageHydrationOptions = {
27
30
  scriptId: string;
@@ -40,7 +43,6 @@ export type PageHydrationOptions = {
40
43
  importPath: string;
41
44
  getLayoutStack?: (Page: unknown) => string;
42
45
  };
43
- preload?: (props: Record<string, unknown>) => void | Promise<void>;
44
46
  };
45
47
  /**
46
48
  * Registers and starts the Page lifecycle when its persistent script is present.