@ecopages/react 0.2.0-rc.1 → 0.2.0-rc.10

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 (83) hide show
  1. package/README.md +68 -14
  2. package/package.json +17 -5
  3. package/src/app/client-only.js +3 -8
  4. package/src/bundling/bundle.js +4 -1
  5. package/src/bundling/runtime-alias-map.d.ts +0 -1
  6. package/src/bundling/runtime-alias-map.js +1 -4
  7. package/src/bundling/runtime-bundle.d.ts +9 -2
  8. package/src/bundling/runtime-bundle.js +27 -16
  9. package/src/bundling/runtime-modules.d.ts +21 -0
  10. package/src/bundling/runtime-modules.js +25 -0
  11. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  12. package/src/client-graph/ast-transform-eco-page.js +71 -0
  13. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  14. package/src/client-graph/ast-transform-import-edits.js +75 -0
  15. package/src/client-graph/ast-transform-walk-imports.d.ts +19 -0
  16. package/src/client-graph/ast-transform-walk-imports.js +103 -0
  17. package/src/client-graph/ast-transform.d.ts +1 -7
  18. package/src/client-graph/ast-transform.js +42 -378
  19. package/src/client-graph/ast-walk.d.ts +10 -0
  20. package/src/client-graph/ast-walk.js +26 -0
  21. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +8 -0
  22. package/src/client-graph/boundary-plugin-read-file-inline.js +45 -0
  23. package/src/client-graph/boundary-plugin-transform.d.ts +18 -0
  24. package/src/client-graph/boundary-plugin-transform.js +61 -0
  25. package/src/client-graph/boundary-plugin.d.ts +0 -20
  26. package/src/client-graph/boundary-plugin.js +16 -98
  27. package/src/client-graph/reachability-analyzer.d.ts +4 -36
  28. package/src/client-graph/reachability-analyzer.js +23 -483
  29. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  30. package/src/client-graph/reachability-client-roots.js +59 -0
  31. package/src/client-graph/reachability-export-names.d.ts +5 -0
  32. package/src/client-graph/reachability-export-names.js +34 -0
  33. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  34. package/src/client-graph/reachability-fallback-roots.js +71 -0
  35. package/src/client-graph/reachability-preload.d.ts +10 -0
  36. package/src/client-graph/reachability-preload.js +30 -0
  37. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  38. package/src/client-graph/reachability-top-level-index.js +93 -0
  39. package/src/client-graph/reachability-traverse.d.ts +7 -0
  40. package/src/client-graph/reachability-traverse.js +201 -0
  41. package/src/client-graph/specifier-classification.d.ts +3 -2
  42. package/src/client-graph/specifier-classification.js +6 -2
  43. package/src/content/collection-component-cache.d.ts +25 -0
  44. package/src/content/collection-component-cache.js +62 -0
  45. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  46. package/src/hmr/hmr-strategy-process.js +83 -0
  47. package/src/hmr/hmr-strategy.d.ts +3 -0
  48. package/src/hmr/hmr-strategy.js +47 -86
  49. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +1 -0
  50. package/src/hmr/react-hmr-dev-transform-plugins.js +4 -1
  51. package/src/hydration/browser/island-hydration.d.ts +82 -0
  52. package/src/hydration/browser/island-hydration.js +247 -0
  53. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  54. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  55. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  56. package/src/hydration/browser/page-hydration-module.js +17 -0
  57. package/src/hydration/browser/page-hydration.d.ts +54 -0
  58. package/src/hydration/browser/page-hydration.js +177 -0
  59. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  60. package/src/hydration/hydration-asset.d.ts +21 -1
  61. package/src/hydration/hydration-asset.js +54 -24
  62. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  63. package/src/hydration/hydration-lifecycle.test.browser.js +409 -0
  64. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  65. package/src/hydration/hydration-page-entry-source.js +87 -0
  66. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  67. package/src/hydration/hydration-script-compiler.js +213 -0
  68. package/src/hydration/page-data-reader.d.ts +0 -14
  69. package/src/hydration/page-data-reader.js +1 -47
  70. package/src/mdx/mdx-loader-plugin.d.ts +5 -1
  71. package/src/mdx/mdx-loader-plugin.js +4 -2
  72. package/src/plugin/react.plugin.js +8 -1
  73. package/src/plugin/react.types.d.ts +11 -2
  74. package/src/render/component-ssr.d.ts +17 -0
  75. package/src/render/component-ssr.js +19 -1
  76. package/src/render/react-renderer.d.ts +2 -1
  77. package/src/render/react-renderer.js +5 -1
  78. package/src/render/unified-layout-composition.d.ts +2 -0
  79. package/src/render/unified-layout-composition.js +5 -1
  80. package/src/hydration/hydration-scripts.d.ts +0 -104
  81. package/src/hydration/hydration-scripts.js +0 -483
  82. package/src/hydration/hydration-scripts.test.browser.js +0 -199
  83. /package/src/hydration/{hydration-scripts.test.browser.d.ts → compiled-page-hydration-options.js} +0 -0
package/README.md CHANGED
@@ -31,7 +31,7 @@ For component-level islands, Ecopages React uses this contract:
31
31
 
32
32
  - SSR output preserves the authored DOM structure (no unnecessary wrapper elements).
33
33
  - 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`).
34
- - The island runtime replaces the SSR host with a dedicated client-owned container and mounts it with `createRoot()`. Full-page hydration paths use `hydrateRoot()`.
34
+ - 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()`.
35
35
 
36
36
  > [!TIP]
37
37
  > **Full React SPA Routing:**
@@ -75,6 +75,7 @@ Important:
75
75
 
76
76
  - Components that may render foreign children must declare those children in `config.dependencies.components`.
77
77
  - Ecopages validates mixed-renderer ownership from declared dependencies during render preparation. It does not infer every foreign subtree from rendered HTML alone.
78
+ - Route-level dependency resolvers can supply Components at request time; React includes those resolved roots when deciding whether a Foreign Subtree needs handoff.
78
79
  - React still keeps its own child transport and hydration rules for React-owned subtrees.
79
80
 
80
81
  ## Server and Client Graph Contract
@@ -87,6 +88,8 @@ The React integration supports Node.js modules and server-only code **only on th
87
88
 
88
89
  Keep server helpers close, but separate them physically or logically so they do not leak into the client bundle.
89
90
 
91
+ 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.
92
+
90
93
  ## Client Graph Boundary Architecture
91
94
 
92
95
  This section explains the internal contract used to keep the browser bundle minimal while preventing server-only code and request-only configuration from leaking into client output.
@@ -201,7 +204,7 @@ Hydration must rebuild the same tree the server rendered.
201
204
 
202
205
  That applies to both:
203
206
 
204
- - non-router hydration scripts in [src/hydration/hydration-scripts.ts](src/hydration/hydration-scripts.ts)
207
+ - page hydration lifecycle in [src/hydration/browser/page-hydration.ts](src/hydration/browser/page-hydration.ts)
205
208
  - router-backed hydration in [../../react-router/src/router.ts](../../react-router/src/router.ts)
206
209
 
207
210
  If the page render receives `locals` on the server and the layout also depends on those values, the client must pass the same serialized `locals` into the layout during hydration. Otherwise React will detect a mismatch.
@@ -212,7 +215,7 @@ The main regression coverage lives in:
212
215
 
213
216
  - [src/client-graph/boundary-plugin.test.ts](src/client-graph/boundary-plugin.test.ts): verifies server-only `eco.page(...)` options are stripped from browser bundles.
214
217
  - [src/render/react-renderer.locals.test.ts](src/render/react-renderer.locals.test.ts): verifies only declared `requires` keys are serialized into hydration payloads.
215
- - [src/hydration/hydration-scripts.test.ts](src/hydration/hydration-scripts.test.ts): verifies non-router hydration passes serialized `locals` into layouts.
218
+ - [src/hydration/hydration-script-compiler.test.ts](src/hydration/hydration-script-compiler.test.ts): verifies editable browser sources compile to readable and minified entries.
216
219
  - [../../react-router/test/hmr-reload.test.browser.ts](../../react-router/test/hmr-reload.test.browser.ts): verifies router-backed layout hydration receives `locals` with `persistLayouts` both enabled and disabled.
217
220
 
218
221
  If you change the AST transform or hydration flow, update the corresponding tests in the same change.
@@ -241,7 +244,23 @@ The fix is **shared browser runtime vendors**: selected npm packages are built o
241
244
 
242
245
  In `ecopages dev`, page modules are served from `/assets/__eco_dev__/` and should import `/assets/vendors/*` for shared packages instead of inlining `node_modules`. Kitchen-sink routes `/vendor-share/a` and `/vendor-share/b` (with `runtimeModules: ['zod']`) are the reference fixture; see `playground/kitchen-sink/e2e/shared-vendors.test.e2e.ts`.
243
246
 
244
- The Ecopages dev toolbar **Islands** app inspects `data-eco-island`, `data-eco-component-id`, `data-eco-props`, and `window.__ECO_PAGES__.islandRoots` during development.
247
+ The Ecopages dev toolbar **Islands** app inspects `data-eco-island`, `data-eco-component-id`, `data-eco-props`, and `window.__ECO_PAGES__.islandRoots` during development. React component islands are emitted as `<eco-island style="display:contents">` hosts during SSR and hydrated in place; the client adds `data-eco-hydrated` after the initial commit. `display: contents` keeps the host from introducing a layout box while preserving it as the hydration and diagnostics boundary.
248
+
249
+ The browser lifecycle is maintained as typed code in `src/hydration/browser/`.
250
+ Production island bootstraps are generated from that source by the server-side
251
+ Rolldown compiler in `src/hydration/hydration-script-compiler.ts`, which keeps
252
+ React, ReactDOM, and the component entry as external browser imports. This keeps
253
+ the generated script compact without requiring a second handwritten minified
254
+ implementation.
255
+
256
+ Page HMR registers before initial preload, but publishes a replacement component
257
+ only after its preload succeeds. Each handler belongs to the page generation in
258
+ which it was registered. Navigation cleanup invalidates both pending updates and
259
+ later calls to retained handlers, preventing updates to a replacement page root.
260
+
261
+ Hydration preserves the SSR DOM when the server and client trees match. A
262
+ component that renders different markup in the browser can still produce a
263
+ normal React hydration mismatch or layout shift.
245
264
 
246
265
  Auto-discovery removes the need to hand-maintain `runtimeModules` for the common case — a query-client layout that imports `@tanstack/react-query` is enough when discovery is configured correctly.
247
266
 
@@ -268,7 +287,7 @@ The fallback exists for backward compatibility. Ecopages logs a debug message wh
268
287
  #### What gets discovered
269
288
 
270
289
  1. Select layout entry files using the mode above.
271
- 2. From each root layout's **`render` client graph** (reachability analysis), follow relative imports and tsconfig path aliases. Type-only imports and `.server.ts` modules are skipped.
290
+ 2. From each root layout's **`render` client graph** (reachability analysis), follow relative imports and tsconfig path aliases. Type-only imports, side-effect-only imports (for example `import "mobx"`), and `.server.ts` modules are skipped.
272
291
  3. Collect npm package roots (for example `@tanstack/react-query`, not `@tanstack/react-query/devtools`).
273
292
  4. Register each discovered package as a shared vendor.
274
293
 
@@ -336,18 +355,53 @@ reactPlugin({
336
355
  });
337
356
  ```
338
357
 
339
- Manual entries **override** auto-discovered entries for the same specifier.
358
+ Manual entries **override** auto-discovered entries for the same specifier. Discovery normalizes package subpaths to package roots; import rewrite matches **exact** specifiers registered in `runtimeModules`.
359
+
360
+ Each vendor entry is built from the package's browser ESM surface: Ecopages follows an `exports` import target when present and otherwise prefers a package's legacy `module` field over CJS `main`. ESM files are re-exported with `export *`. CJS files (including React's published `index.js` / `jsx-runtime`) emit explicit named exports from that same file so the vendor can provide `jsx`. Keep `runtimeModules` at package roots. A package subpath is a separate module contract and must either be registered explicitly or bundled with the consuming page/library.
361
+
362
+ `externals` on a library vendor must already be shared vendors (React, the router bundle, or another `runtimeModules` specifier). Unmapped externals throw at plugin setup instead of emitting a bare specifier the browser cannot resolve.
363
+
364
+ #### Singleton packages (MobX, Redux, Query client, audio engines)
365
+
366
+ Some npm packages must exist as **one browser module** across layout vendors, page chunks, and dev lazy prebundles. React context, MobX observables, Redux stores, TanStack Query clients, and audio runtimes (for example Tone.js) all break when two copies load.
367
+
368
+ Layout auto-discovery only walks `eco.layout()` render graphs. Page-level imports of a singleton that is not registered in `runtimeModules` may be lazily prebundled into a **second** vendor in dev, or inlined into page chunks in production. If a shared library vendor also bundles that singleton internally, you get duplicate instances even though both sides "import the same package name."
369
+
370
+ **Library packaging:** ship singleton deps as `peerDependencies` and keep them external in the library build so `dist/` retains `import … from "mobx"` (or equivalent) instead of inlining a private copy.
371
+
372
+ **Ecopages app config:** register each singleton as its own `runtimeModules` entry and list it in `externals` on any library vendor that imports it:
373
+
374
+ ```ts
375
+ reactPlugin({
376
+ router: ecoRouter(),
377
+ runtimeModules: [
378
+ { specifier: 'mobx', outputName: 'mobx' },
379
+ { specifier: 'mobx-react-lite', outputName: 'mobx-react-lite' },
380
+ {
381
+ specifier: '@acme/store-ui',
382
+ outputName: 'acme-store-ui',
383
+ externals: ['mobx', 'mobx-react-lite', 'react', 'react-dom'],
384
+ },
385
+ ],
386
+ });
387
+ ```
388
+
389
+ Registering only the library vendor, or only the singleton, is not enough when the published library still inlines the singleton. Rebuild vendors (and clear `.eco` / `dist/assets/vendors` in dev) after changing package entry points or `runtimeModules`.
340
390
 
341
391
  #### Troubleshooting
342
392
 
343
- | Symptom | Likely cause | Fix |
344
- | ------------------------------------------ | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
345
- | `No QueryClient set` after SPA navigation | Provider library bundled per page chunk | Ensure `router` is enabled; add `runtimeProvider: true` on the provider layout; rebuild vendors |
346
- | Duplicate React context / Tone init logs | Provider package is bundled through multiple client entrypoints | Import through the package root and register that root in `runtimeModules` |
347
- | Wrong packages vendored (slow dev startup) | Shell layout scanned as discovery root | Set `runtimeProvider: true` only on provider roots; keep shell layouts unflagged |
348
- | Package not discovered | Layout outside `layouts/` / `components/`, or import not reachable from `render` | Move layout file or add explicit `runtimeModules` entry |
349
- | `@/` alias not followed | Missing or invalid tsconfig paths | Add `compilerOptions.paths`; ensure `include` globs are valid JSON (not broken by comment stripping) |
350
- | Stale bootstrap script hash in dev | Rendered HTML cached before runtime vendors/bootstrap scripts changed | Rebuild or touch a route file; development HTML cache keys include browser-runtime generation |
393
+ | Symptom | Likely cause | Fix |
394
+ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
395
+ | `No QueryClient set` after SPA navigation | Provider library bundled per page chunk | Ensure `router` is enabled; add `runtimeProvider: true` on the provider layout; rebuild vendors |
396
+ | Duplicate React context / Tone init logs | Provider package is bundled through multiple client entrypoints | Import through the package root and register that root in `runtimeModules` |
397
+ | Store updates / `reaction` / `observer` no-op | Duplicate singleton (for example MobX) — layout vendor inlines one copy, page or dev prebundle loads another | Peer the singleton in the library; add explicit `runtimeModules` for it; list it in `externals` on the library vendor; rebuild vendors |
398
+ | Wrong packages vendored (slow dev startup) | Shell layout scanned as discovery root | Set `runtimeProvider: true` only on provider roots; keep shell layouts unflagged |
399
+ | Package not discovered | Layout outside `layouts/` / `components/`, or import not reachable from `render` | Move layout file or add explicit `runtimeModules` entry |
400
+ | `@/` alias not followed | Missing or invalid tsconfig paths | Add `compilerOptions.paths`; ensure `include` globs are valid JSON (not broken by comment stripping) |
401
+ | Stale bootstrap script hash in dev | Rendered HTML cached before runtime vendors/bootstrap scripts changed | Rebuild or touch a route file; development HTML cache keys include browser-runtime generation |
402
+ | `MISSING_EXPORT` for names like `BasePlugin` | Vendor listed CJS enumerable keys that the ESM file does not export | Register the package root only; rebuild vendors. Subpath plugins are a separate module and must be bundled or declared themselves |
403
+ | `does not provide an export named 'jsx'` | Stale React vendor generated with `export *` from CJS `jsx-runtime` | Clear `.eco` / `dist/assets/vendors` and rebuild so the CJS entry lists `jsx` / `jsxs` explicitly |
404
+ | `Calling require for "/assets/vendors/…"` | A CJS vendor graph `require()`d another runtime module after URL rewrite | Prefer packages with an ESM/`module` entry; keep sibling singletons as `runtimeModules` + `externals` |
351
405
 
352
406
  #### Tests
353
407
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/react",
3
- "version": "0.2.0-rc.1",
3
+ "version": "0.2.0-rc.10",
4
4
  "description": "React integration for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -11,6 +11,9 @@
11
11
  "main": "./src/plugin/react.plugin.js",
12
12
  "types": "./src/plugin/react.plugin.d.ts",
13
13
  "type": "module",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
14
17
  "exports": {
15
18
  ".": {
16
19
  "default": "./src/plugin/react.plugin.js",
@@ -43,6 +46,10 @@
43
46
  "types": "./src/render/layout-compose.d.ts",
44
47
  "default": "./src/render/layout-compose.js"
45
48
  },
49
+ "./collection-component-cache": {
50
+ "types": "./src/content/collection-component-cache.d.ts",
51
+ "default": "./src/content/collection-component-cache.js"
52
+ },
46
53
  "./serialize-page-data-script": {
47
54
  "types": "./src/hydration/serialize-page-data-script.d.ts",
48
55
  "default": "./src/hydration/serialize-page-data-script.js"
@@ -78,6 +85,10 @@
78
85
  "types": "./src/render/layout-compose.d.ts",
79
86
  "default": "./src/render/layout-compose.js"
80
87
  },
88
+ "./collection-component-cache.ts": {
89
+ "types": "./src/content/collection-component-cache.d.ts",
90
+ "default": "./src/content/collection-component-cache.js"
91
+ },
81
92
  "./serialize-page-data-script.ts": {
82
93
  "types": "./src/hydration/serialize-page-data-script.d.ts",
83
94
  "default": "./src/hydration/serialize-page-data-script.js"
@@ -93,20 +104,21 @@
93
104
  "directory": "packages/integrations/react"
94
105
  },
95
106
  "peerDependencies": {
96
- "@ecopages/core": "0.2.0-rc.1",
107
+ "@ecopages/core": "0.2.0-rc.10",
97
108
  "@types/react": "^19",
98
109
  "@types/react-dom": "^19",
99
110
  "react": "^19",
100
111
  "react-dom": "^19"
101
112
  },
102
113
  "dependencies": {
103
- "@ecopages/file-system": "0.2.0-rc.1",
114
+ "@ecopages/file-system": "0.2.0-rc.10",
104
115
  "@ecopages/logger": "^0.2.3",
105
- "@ecopages/mdx": "0.2.0-rc.1",
116
+ "@ecopages/mdx": "0.2.0-rc.10",
106
117
  "@mdx-js/mdx": "^3.1.1",
107
118
  "oxc-parser": "^0.141.0",
108
119
  "oxc-transform": "^0.141.0",
120
+ "rolldown": "^1.1.0",
109
121
  "source-map": "^0.8.0",
110
122
  "vfile": "^6.0.3"
111
123
  }
112
- }
124
+ }
@@ -1,11 +1,6 @@
1
- import { useEffect, useState } from 'react';
2
- export const useIsClient = () => {
3
- const [isClient, setIsClient] = useState(false);
4
- useEffect(() => {
5
- setIsClient(true);
6
- }, []);
7
- return isClient;
8
- };
1
+ import { useSyncExternalStore } from 'react';
2
+ const emptySubscribe = () => () => { };
3
+ export const useIsClient = () => useSyncExternalStore(emptySubscribe, () => true, () => false);
9
4
  export const ClientOnly = ({ children, fallback = null }) => {
10
5
  const isClient = useIsClient();
11
6
  if (!isClient) {
@@ -100,7 +100,10 @@ export class BundleService {
100
100
  ? []
101
101
  : [runtimeRewritePlugin].filter((plugin) => plugin !== null);
102
102
  if (isMdx && this.config.mdxCompilerOptions) {
103
- const mdxPlugin = createReactMdxLoaderPlugin(this.config.mdxCompilerOptions);
103
+ const mdxPlugin = createReactMdxLoaderPlugin({
104
+ compilerOptions: this.config.mdxCompilerOptions,
105
+ projectRoot: this.config.rootDir,
106
+ });
104
107
  options.plugins = [
105
108
  ...(foreignJsxOverridePlugin ? [foreignJsxOverridePlugin] : []),
106
109
  graphBoundaryPlugin,
@@ -6,7 +6,6 @@ export type BuildReactRuntimeManifestOptions = {
6
6
  routerImportPath?: string;
7
7
  };
8
8
  export declare const REACT_RUNTIME_SPECIFIERS: readonly ["react", "react-dom", "react/jsx-runtime", "react/jsx-dev-runtime", "react-dom/client"];
9
- export declare function buildReactRuntimeAliasMap(runtimeImports: ReactRuntimeImports): Record<string, string>;
10
9
  export declare function buildConfiguredRuntimeModuleManifestEntries(modules: readonly ResolvedReactPluginRuntimeModule[], getPublicPath: (outputName: string) => string): BrowserRuntimeAssetDeclaration[];
11
10
  export declare function buildReactRuntimeManifest(runtimeImports: ReactRuntimeImports, configuredRuntimeModules?: readonly ResolvedReactPluginRuntimeModule[], getConfiguredRuntimeModulePublicPath?: (outputName: string) => string, options?: BuildReactRuntimeManifestOptions): BrowserRuntimeManifest;
12
11
  export declare function getReactRuntimeExternalSpecifiers(): string[];
@@ -1,4 +1,4 @@
1
- import { createBrowserRuntimeManifest, getBrowserRuntimeSpecifierMap, } from '@ecopages/core/build/browser-runtime-manifest';
1
+ import { createBrowserRuntimeManifest, } from '@ecopages/core/build/browser-runtime-manifest';
2
2
  import { LAYOUT_COMPOSE_PACKAGE } from './bootstrap-package-paths.js';
3
3
  export const REACT_RUNTIME_SPECIFIERS = [
4
4
  'react',
@@ -7,9 +7,6 @@ export const REACT_RUNTIME_SPECIFIERS = [
7
7
  'react/jsx-dev-runtime',
8
8
  'react-dom/client',
9
9
  ];
10
- export function buildReactRuntimeAliasMap(runtimeImports) {
11
- return Object.fromEntries(getBrowserRuntimeSpecifierMap(buildReactRuntimeManifest(runtimeImports)));
12
- }
13
10
  export function buildConfiguredRuntimeModuleManifestEntries(modules, getPublicPath) {
14
11
  return modules.map((module) => ({
15
12
  specifier: module.specifier,
@@ -9,7 +9,7 @@
9
9
  import type { EcoBuildPlugin } from '@ecopages/core/plugins/integration-plugin';
10
10
  import { type AssetDefinition } from '@ecopages/core/services/asset-processing-service';
11
11
  import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
12
- import type { ResolvedReactPluginRuntimeModule } from './runtime-modules.js';
12
+ import { type ResolvedReactPluginRuntimeModule } from './runtime-modules.js';
13
13
  import { type BrowserRuntimeManifest } from '@ecopages/core/build/browser-runtime-manifest';
14
14
  export type ReactRuntimeImports = {
15
15
  react: string;
@@ -65,6 +65,13 @@ export declare class RuntimeBundleService {
65
65
  getPageLayoutNormalizationDependencies(options?: {
66
66
  modes?: RuntimeMode[];
67
67
  }): AssetDefinition[];
68
- createRuntimeAliasPlugin(mode?: RuntimeMode): EcoBuildPlugin;
68
+ /**
69
+ * Builds the vendor import-rewrite plugin for one runtime asset.
70
+ *
71
+ * @remarks
72
+ * `omitSpecifiers` drops the module being bundled so a self-import cannot
73
+ * rewrite to the file currently being emitted.
74
+ */
75
+ createRuntimeAliasPlugin(mode?: RuntimeMode, omitSpecifiers?: readonly string[]): EcoBuildPlugin;
69
76
  }
70
77
  export {};
@@ -10,8 +10,9 @@ import { createBrowserRuntimePlugin } from '@ecopages/core/build/browser-runtime
10
10
  import { DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME } from '@ecopages/core/build/browser-runtime-plugin';
11
11
  import { buildBrowserRuntimeAssetUrl, createBrowserRuntimeModuleAsset, createBrowserRuntimeScriptAsset, } from '@ecopages/core/services/asset-processing-service';
12
12
  import { createReactDomRuntimeInteropPlugin } from './runtime-interop-plugin.js';
13
- import { buildReactRuntimeAliasMap, buildReactRuntimeManifest, getReactRuntimeExternalSpecifiers, } from './runtime-alias-map.js';
14
- import { createBrowserRuntimeManifest, } from '@ecopages/core/build/browser-runtime-manifest';
13
+ import { buildReactRuntimeManifest, getReactRuntimeExternalSpecifiers } from './runtime-alias-map.js';
14
+ import { assertReactRuntimeModuleExternalsAreVendored, } from './runtime-modules.js';
15
+ import { createBrowserRuntimeManifest, getBrowserRuntimeSpecifierMap, } from '@ecopages/core/build/browser-runtime-manifest';
15
16
  import { LAYOUT_COMPOSE_PACKAGE, PAGE_LAYOUT_NORMALIZATION_PACKAGE } from './bootstrap-package-paths.js';
16
17
  export class RuntimeBundleService {
17
18
  config;
@@ -114,7 +115,7 @@ export class RuntimeBundleService {
114
115
  return runtimeImports;
115
116
  }
116
117
  getRuntimeAliasMap(mode = this.getCurrentRuntimeMode()) {
117
- return buildReactRuntimeAliasMap(this.getRuntimeImports(mode));
118
+ return Object.fromEntries(getBrowserRuntimeSpecifierMap(this.getRuntimeManifest(mode)));
118
119
  }
119
120
  getRuntimeManifest(mode = this.getCurrentRuntimeMode()) {
120
121
  return buildReactRuntimeManifest(this.getRuntimeImports(mode), this.getConfiguredRuntimeModules(), (outputName) => buildBrowserRuntimeAssetUrl(this.getConfiguredRuntimeModuleFileName(outputName, mode)), { routerImportPath: this.config.routerAdapter?.bundle.importPath });
@@ -139,8 +140,7 @@ export class RuntimeBundleService {
139
140
  ]),
140
141
  });
141
142
  const reactDomBundlePlugins = [reactRuntimeAliasPlugin, reactDomRuntimeInteropPlugin].filter((plugin) => plugin !== null);
142
- const runtimeAliasPlugin = this.createRuntimeAliasPlugin(mode);
143
- const mappedSpecifiers = new Set(Object.keys(this.getRuntimeAliasMap(mode)));
143
+ const mappedSpecifiers = new Set(this.getRuntimeManifest(mode).bySpecifier.keys());
144
144
  dependencies.push(createBrowserRuntimeModuleAsset({
145
145
  modules: [
146
146
  { specifier: 'react', defaultExport: true },
@@ -196,11 +196,17 @@ export class RuntimeBundleService {
196
196
  bundleOptions: {
197
197
  define: this.createRuntimeDefines(mode),
198
198
  external: unresolvedExternals,
199
- plugins: [runtimeAliasPlugin],
199
+ plugins: [
200
+ this.createRuntimeAliasPlugin(mode, [
201
+ this.config.routerAdapter.bundle.importPath,
202
+ '@ecopages/react-router',
203
+ ]),
204
+ ],
200
205
  },
201
206
  }));
202
207
  }
203
208
  for (const runtimeModule of this.getConfiguredRuntimeModules()) {
209
+ assertReactRuntimeModuleExternalsAreVendored(runtimeModule, mappedSpecifiers);
204
210
  dependencies.push(createBrowserRuntimeModuleAsset({
205
211
  modules: [{ specifier: runtimeModule.specifier, defaultExport: true }],
206
212
  name: runtimeModule.outputName,
@@ -212,7 +218,7 @@ export class RuntimeBundleService {
212
218
  define: this.createRuntimeDefines(mode),
213
219
  external: this.getRuntimeModuleBundleExternals(runtimeModule, mappedSpecifiers),
214
220
  excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
215
- plugins: [runtimeAliasPlugin],
221
+ plugins: [this.createRuntimeAliasPlugin(mode, [runtimeModule.specifier])],
216
222
  },
217
223
  }));
218
224
  }
@@ -242,17 +248,22 @@ export class RuntimeBundleService {
242
248
  }
243
249
  return dependencies;
244
250
  }
245
- createRuntimeAliasPlugin(mode = this.getCurrentRuntimeMode()) {
246
- const aliasMap = this.getRuntimeAliasMap(mode);
247
- const manifest = createBrowserRuntimeManifest(Object.entries(aliasMap).map(([specifier, publicPath]) => ({
248
- specifier,
249
- owner: '',
250
- importPath: specifier,
251
- publicPath,
252
- })));
251
+ /**
252
+ * Builds the vendor import-rewrite plugin for one runtime asset.
253
+ *
254
+ * @remarks
255
+ * `omitSpecifiers` drops the module being bundled so a self-import cannot
256
+ * rewrite to the file currently being emitted.
257
+ */
258
+ createRuntimeAliasPlugin(mode = this.getCurrentRuntimeMode(), omitSpecifiers = []) {
259
+ const manifest = this.getRuntimeManifest(mode);
260
+ const omitted = new Set(omitSpecifiers);
261
+ const pluginManifest = omitted.size === 0
262
+ ? manifest
263
+ : createBrowserRuntimeManifest(manifest.assets.filter((asset) => !omitted.has(asset.specifier)));
253
264
  return createBrowserRuntimePlugin({
254
265
  name: `react-plugin-runtime-alias-${mode}`,
255
- manifest,
266
+ manifest: pluginManifest,
256
267
  });
257
268
  }
258
269
  }
@@ -6,6 +6,14 @@
6
6
  export type ReactPluginRuntimeModule = string | {
7
7
  specifier: string;
8
8
  outputName?: string;
9
+ /**
10
+ * Packages left unbundled in this vendor chunk.
11
+ *
12
+ * @remarks
13
+ * Each entry must already be a shared vendor — React, the router bundle, or
14
+ * another `runtimeModules` specifier — so import rewrite can emit
15
+ * `/assets/vendors/*.js`. Unmapped externals throw at plugin setup.
16
+ */
9
17
  externals?: string[];
10
18
  };
11
19
  export type ResolvedReactPluginRuntimeModule = {
@@ -27,3 +35,16 @@ export declare function resolveReactPluginRuntimeModules(modules: ReactPluginRun
27
35
  * @remarks Manual entries win when both sources declare the same specifier.
28
36
  */
29
37
  export declare function mergeReactPluginRuntimeModules(manualModules: ResolvedReactPluginRuntimeModule[], autoSpecifiers: string[]): ResolvedReactPluginRuntimeModule[];
38
+ /**
39
+ * Thrown when a `runtimeModules` entry lists an `externals` specifier that is
40
+ * not a shared browser vendor.
41
+ */
42
+ export declare class UnmappedReactRuntimeModuleExternalError extends Error {
43
+ readonly moduleSpecifier: string;
44
+ readonly unmappedExternals: string[];
45
+ constructor(moduleSpecifier: string, unmappedExternals: string[]);
46
+ }
47
+ /**
48
+ * Ensures every `externals` specifier on a runtime module is already a vendor.
49
+ */
50
+ export declare function assertReactRuntimeModuleExternalsAreVendored(module: ResolvedReactPluginRuntimeModule, vendoredSpecifiers: ReadonlySet<string>): void;
@@ -47,3 +47,28 @@ export function mergeReactPluginRuntimeModules(manualModules, autoSpecifiers) {
47
47
  }
48
48
  return [...merged.values()];
49
49
  }
50
+ /**
51
+ * Thrown when a `runtimeModules` entry lists an `externals` specifier that is
52
+ * not a shared browser vendor.
53
+ */
54
+ export class UnmappedReactRuntimeModuleExternalError extends Error {
55
+ moduleSpecifier;
56
+ unmappedExternals;
57
+ constructor(moduleSpecifier, unmappedExternals) {
58
+ super(`reactPlugin runtimeModules entry "${moduleSpecifier}" lists externals that are not shared vendors: ${unmappedExternals.join(', ')}. ` +
59
+ 'Register each as its own runtimeModules entry (React and the router bundle are already vendored) so browser imports rewrite to /assets/vendors/*.js.');
60
+ this.name = 'UnmappedReactRuntimeModuleExternalError';
61
+ this.moduleSpecifier = moduleSpecifier;
62
+ this.unmappedExternals = unmappedExternals;
63
+ }
64
+ }
65
+ /**
66
+ * Ensures every `externals` specifier on a runtime module is already a vendor.
67
+ */
68
+ export function assertReactRuntimeModuleExternalsAreVendored(module, vendoredSpecifiers) {
69
+ const unmappedExternals = module.externals.filter((external) => !vendoredSpecifiers.has(external));
70
+ if (unmappedExternals.length === 0) {
71
+ return;
72
+ }
73
+ throw new UnmappedReactRuntimeModuleExternalError(module.specifier, unmappedExternals);
74
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Strips server-only `eco.page(...)` option keys from browser-bound modules.
3
+ */
4
+ /**
5
+ * Removes server-only `eco.page(...)` options from browser-bound modules.
6
+ */
7
+ export declare function stripServerOnlyEcoPageOptions(source: string, program: any): {
8
+ transformed: string;
9
+ modified: boolean;
10
+ };
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Strips server-only `eco.page(...)` option keys from browser-bound modules.
3
+ */
4
+ import { walkAstNodes } from './ast-walk.js';
5
+ import { applySourceEdits } from './ast-transform-import-edits.js';
6
+ const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = new Set([
7
+ 'cache',
8
+ 'middleware',
9
+ 'dependencies',
10
+ 'requires',
11
+ 'metadata',
12
+ 'staticProps',
13
+ 'staticPaths',
14
+ ]);
15
+ function isEcoPageOptionsCall(node) {
16
+ return (node.type === 'CallExpression' &&
17
+ node.callee?.type === 'MemberExpression' &&
18
+ node.callee.object?.type === 'Identifier' &&
19
+ node.callee.object.name === 'eco' &&
20
+ node.callee.property?.type === 'Identifier' &&
21
+ node.callee.property.name === 'page' &&
22
+ node.arguments?.[0]?.type === 'ObjectExpression');
23
+ }
24
+ function collectEcoPageOptionStripEdit(node, source, edits) {
25
+ if (!isEcoPageOptionsCall(node))
26
+ return;
27
+ const objectExpression = node.arguments[0];
28
+ const keptProperties = [];
29
+ let removedProperty = false;
30
+ for (const property of objectExpression.properties ?? []) {
31
+ if (property?.type === 'Property') {
32
+ const keyName = getObjectPropertyKeyName(property.key);
33
+ if (keyName && SERVER_ONLY_ECO_PAGE_OPTION_KEYS.has(keyName)) {
34
+ removedProperty = true;
35
+ continue;
36
+ }
37
+ }
38
+ keptProperties.push(source.slice(property.start, property.end));
39
+ }
40
+ if (!removedProperty)
41
+ return;
42
+ const replacement = keptProperties.length > 0 ? `{ ${keptProperties.join(', ')} }` : '{}';
43
+ edits.push({
44
+ start: objectExpression.start,
45
+ end: objectExpression.end,
46
+ replacement,
47
+ });
48
+ }
49
+ function getObjectPropertyKeyName(node) {
50
+ if (!node)
51
+ return undefined;
52
+ if (node.type === 'Identifier')
53
+ return node.name;
54
+ if (node.type === 'StringLiteral' || node.type === 'Literal') {
55
+ return typeof node.value === 'string' ? node.value : undefined;
56
+ }
57
+ return undefined;
58
+ }
59
+ /**
60
+ * Removes server-only `eco.page(...)` options from browser-bound modules.
61
+ */
62
+ export function stripServerOnlyEcoPageOptions(source, program) {
63
+ const edits = [];
64
+ walkAstNodes(program, (node) => {
65
+ collectEcoPageOptionStripEdit(node, source, edits);
66
+ });
67
+ if (edits.length === 0) {
68
+ return { transformed: source, modified: false };
69
+ }
70
+ return { transformed: applySourceEdits(source, edits), modified: true };
71
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Builds source edits for import declaration specifier pruning.
3
+ */
4
+ export type SourceEdit = {
5
+ start: number;
6
+ end: number;
7
+ replacement: string;
8
+ };
9
+ /**
10
+ * Applies range replacements from last-to-first so earlier offsets stay valid.
11
+ */
12
+ export declare function applySourceEdits(source: string, edits: SourceEdit[]): string;
13
+ export declare function buildImportDeclarationRewrite(node: any, specifier: string, rules: Set<string>): SourceEdit | undefined;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Builds source edits for import declaration specifier pruning.
3
+ */
4
+ /**
5
+ * Applies range replacements from last-to-first so earlier offsets stay valid.
6
+ */
7
+ export function applySourceEdits(source, edits) {
8
+ edits.sort((a, b) => b.start - a.start);
9
+ let transformed = source;
10
+ for (const edit of edits) {
11
+ transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
12
+ }
13
+ return transformed;
14
+ }
15
+ function collectKeptImportSpecifiers(node, rules) {
16
+ const kept = { keptSpecifierCount: 0, namedImportNodes: [] };
17
+ for (const spec of node.specifiers) {
18
+ if (spec.type === 'ImportSpecifier') {
19
+ appendKeptNamedSpecifier(spec, rules, kept);
20
+ }
21
+ else if (spec.type === 'ImportDefaultSpecifier') {
22
+ appendKeptDefaultSpecifier(spec, rules, kept);
23
+ }
24
+ else if (spec.type === 'ImportNamespaceSpecifier') {
25
+ appendKeptNamespaceSpecifier(spec, rules, kept);
26
+ }
27
+ }
28
+ return kept;
29
+ }
30
+ function appendKeptNamedSpecifier(spec, rules, kept) {
31
+ const importedName = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value;
32
+ if (!rules.has(importedName))
33
+ return;
34
+ kept.keptSpecifierCount += 1;
35
+ const localName = spec.local?.name;
36
+ kept.namedImportNodes.push(localName && localName !== importedName ? `${importedName} as ${localName}` : importedName);
37
+ }
38
+ function appendKeptDefaultSpecifier(spec, rules, kept) {
39
+ if (!rules.has('default'))
40
+ return;
41
+ kept.keptSpecifierCount += 1;
42
+ kept.defaultImportLocal = spec.local.name;
43
+ }
44
+ function appendKeptNamespaceSpecifier(spec, rules, kept) {
45
+ if (!rules.has('*'))
46
+ return;
47
+ kept.keptSpecifierCount += 1;
48
+ kept.namespaceImportLocal = spec.local.name;
49
+ }
50
+ export function buildImportDeclarationRewrite(node, specifier, rules) {
51
+ const { keptSpecifierCount, defaultImportLocal, namespaceImportLocal, namedImportNodes } = collectKeptImportSpecifiers(node, rules);
52
+ if (keptSpecifierCount === 0) {
53
+ return { start: node.start, end: node.end, replacement: '' };
54
+ }
55
+ if (keptSpecifierCount >= node.specifiers.length) {
56
+ return undefined;
57
+ }
58
+ const newDeclaration = formatPrunedImportDeclaration(specifier, defaultImportLocal, namespaceImportLocal, namedImportNodes);
59
+ return { start: node.start, end: node.end, replacement: newDeclaration };
60
+ }
61
+ function formatPrunedImportDeclaration(specifier, defaultImportLocal, namespaceImportLocal, namedImportNodes) {
62
+ if (defaultImportLocal && namespaceImportLocal) {
63
+ return `import ${defaultImportLocal}, * as ${namespaceImportLocal} from '${specifier}';`;
64
+ }
65
+ if (namespaceImportLocal) {
66
+ return `import * as ${namespaceImportLocal} from '${specifier}';`;
67
+ }
68
+ if (defaultImportLocal && namedImportNodes.length > 0) {
69
+ return `import ${defaultImportLocal}, { ${namedImportNodes.join(', ')} } from '${specifier}';`;
70
+ }
71
+ if (defaultImportLocal) {
72
+ return `import ${defaultImportLocal} from '${specifier}';`;
73
+ }
74
+ return `import { ${namedImportNodes.join(', ')} } from '${specifier}';`;
75
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * AST walk that prunes forbidden imports and rewrites named import surfaces.
3
+ */
4
+ import type { ReachabilityResult } from './reachability-analyzer.js';
5
+ import { type SourceEdit } from './ast-transform-import-edits.js';
6
+ export type ProcessSpecifierResult = {
7
+ allowed: boolean;
8
+ rules?: Set<string> | '*';
9
+ };
10
+ export type WalkImportsContext = {
11
+ filename: string;
12
+ reachability: ReachabilityResult;
13
+ edits: SourceEdit[];
14
+ allowedMap: Map<string, Set<string> | '*'>;
15
+ };
16
+ /**
17
+ * Walks a parsed program and collects import-pruning edits.
18
+ */
19
+ export declare function collectImportTransformEdits(program: any, ctx: Omit<WalkImportsContext, 'edits'>): SourceEdit[];