@ecopages/react 0.2.0-beta.4 → 0.2.0-beta.41

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 (142) hide show
  1. package/README.md +175 -7
  2. package/package.json +54 -29
  3. package/src/app/client-only.js +15 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +31 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +23 -8
  9. package/src/bundling/bundle.js +120 -0
  10. package/src/bundling/discover-layout-runtime-modules.d.ts +32 -0
  11. package/src/bundling/discover-layout-runtime-modules.js +191 -0
  12. package/src/bundling/runtime-alias-map.d.ts +13 -0
  13. package/src/bundling/runtime-alias-map.js +113 -0
  14. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +30 -5
  15. package/src/bundling/runtime-bundle.js +258 -0
  16. package/src/bundling/runtime-interop-plugin.js +34 -0
  17. package/src/bundling/runtime-mode.d.ts +9 -0
  18. package/src/bundling/runtime-mode.js +11 -0
  19. package/src/bundling/runtime-modules.d.ts +29 -0
  20. package/src/bundling/runtime-modules.js +49 -0
  21. package/src/client-graph/ast-transform.d.ts +18 -0
  22. package/src/client-graph/ast-transform.js +426 -0
  23. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +23 -13
  24. package/src/client-graph/boundary-cache.js +182 -0
  25. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +4 -13
  26. package/src/client-graph/boundary-plugin.js +149 -0
  27. package/src/client-graph/component-config-traversal.js +77 -0
  28. package/src/client-graph/declared-modules.js +69 -0
  29. package/src/client-graph/module-classification.d.ts +3 -0
  30. package/src/client-graph/module-classification.js +43 -0
  31. package/src/{utils → client-graph}/reachability-analyzer.d.ts +4 -12
  32. package/src/client-graph/reachability-analyzer.js +515 -0
  33. package/src/client-graph/specifier-classification.d.ts +75 -0
  34. package/src/client-graph/specifier-classification.js +223 -0
  35. package/src/contracts/router-adapter.js +6 -0
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  37. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  38. package/src/hmr/hmr-scripts.js +44 -0
  39. package/src/hmr/hmr-strategy.d.ts +74 -0
  40. package/src/hmr/hmr-strategy.js +351 -0
  41. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  42. package/src/hmr/page-metadata-cache.js +44 -0
  43. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  44. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  45. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  46. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  47. package/src/hydration/bootstrap-imports.d.ts +25 -0
  48. package/src/hydration/bootstrap-imports.js +33 -0
  49. package/src/hydration/hydration-asset.d.ts +84 -0
  50. package/src/hydration/hydration-asset.js +227 -0
  51. package/src/hydration/hydration-scripts.d.ts +104 -0
  52. package/src/hydration/hydration-scripts.js +483 -0
  53. package/src/hydration/hydration-scripts.test.browser.js +199 -0
  54. package/src/hydration/page-data-manifest.d.ts +58 -0
  55. package/src/hydration/page-data-manifest.js +97 -0
  56. package/src/hydration/page-data-reader.d.ts +31 -0
  57. package/src/hydration/page-data-reader.js +77 -0
  58. package/src/hydration/page-payload.d.ts +67 -0
  59. package/src/hydration/page-payload.js +106 -0
  60. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  61. package/src/hydration/serialize-page-data-script.js +30 -0
  62. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +6 -6
  63. package/src/mdx/mdx-config-dependency.js +110 -0
  64. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  65. package/src/mdx/mdx-loader-plugin.js +8 -0
  66. package/src/page/page-module.d.ts +46 -0
  67. package/src/page/page-module.js +74 -0
  68. package/src/plugin/react.constants.js +1 -0
  69. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +9 -3
  70. package/src/plugin/react.plugin.js +241 -0
  71. package/src/plugin/react.types.d.ts +152 -0
  72. package/src/plugin/react.types.js +1 -0
  73. package/src/render/component-ownership.d.ts +49 -0
  74. package/src/render/component-ownership.js +46 -0
  75. package/src/render/component-ssr.d.ts +113 -0
  76. package/src/render/component-ssr.js +180 -0
  77. package/src/render/eco-embed.js +9 -0
  78. package/src/render/errors.d.ts +16 -0
  79. package/src/render/errors.js +23 -0
  80. package/src/render/html-boundary.js +59 -0
  81. package/src/render/layout-compose.d.ts +66 -0
  82. package/src/render/layout-compose.js +134 -0
  83. package/src/render/react-renderer.d.ts +138 -0
  84. package/src/render/react-renderer.js +448 -0
  85. package/src/render/react-runtime.d.ts +13 -0
  86. package/src/render/react-runtime.js +26 -0
  87. package/src/render/unified-layout-composition.d.ts +53 -0
  88. package/src/render/unified-layout-composition.js +78 -0
  89. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  90. package/src/eco-embed.js +0 -11
  91. package/src/react-hmr-strategy.d.ts +0 -230
  92. package/src/react-hmr-strategy.js +0 -657
  93. package/src/react-renderer.d.ts +0 -233
  94. package/src/react-renderer.js +0 -622
  95. package/src/react.constants.js +0 -4
  96. package/src/react.plugin.js +0 -205
  97. package/src/react.types.d.ts +0 -88
  98. package/src/react.types.js +0 -0
  99. package/src/router-adapter.js +0 -0
  100. package/src/services/pages-index.d.ts +0 -64
  101. package/src/services/pages-index.js +0 -73
  102. package/src/services/react-bundle.service.js +0 -86
  103. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  104. package/src/services/react-hydration-asset.service.d.ts +0 -84
  105. package/src/services/react-hydration-asset.service.js +0 -217
  106. package/src/services/react-mdx-config-dependency.service.js +0 -122
  107. package/src/services/react-page-module.service.d.ts +0 -88
  108. package/src/services/react-page-module.service.js +0 -166
  109. package/src/services/react-page-payload.service.d.ts +0 -46
  110. package/src/services/react-page-payload.service.js +0 -67
  111. package/src/services/react-runtime-bundle.service.js +0 -186
  112. package/src/utils/client-graph-boundary-cache.js +0 -116
  113. package/src/utils/client-graph-boundary-plugin.js +0 -552
  114. package/src/utils/client-only.js +0 -19
  115. package/src/utils/component-config-traversal.js +0 -54
  116. package/src/utils/declared-modules.js +0 -47
  117. package/src/utils/dynamic.js +0 -12
  118. package/src/utils/dynamic.test.browser.js +0 -33
  119. package/src/utils/hmr-scripts.js +0 -31
  120. package/src/utils/html-boundary.js +0 -55
  121. package/src/utils/hydration-scripts.d.ts +0 -92
  122. package/src/utils/hydration-scripts.js +0 -358
  123. package/src/utils/hydration-scripts.test.browser.js +0 -198
  124. package/src/utils/reachability-analyzer.js +0 -339
  125. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  126. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  127. package/src/utils/react-mdx-loader-plugin.js +0 -45
  128. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  129. package/src/utils/react-runtime-alias-map.js +0 -90
  130. /package/src/{utils → app}/client-only.d.ts +0 -0
  131. /package/src/{utils → app}/dynamic.d.ts +0 -0
  132. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  133. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  134. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  135. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  136. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  137. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  138. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  139. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  140. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  141. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  142. /package/src/{utils → render}/html-boundary.d.ts +0 -0
package/README.md CHANGED
@@ -30,7 +30,7 @@ export default config;
30
30
  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
- - A stable `data-eco-component-id` attribute is attached to the component SSR root.
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
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()`.
35
35
 
36
36
  > [!TIP]
@@ -109,6 +109,16 @@ Think about each React page as two related graphs:
109
109
 
110
110
  The React integration builds the client graph conservatively. If a server-only module becomes reachable from the hydrated render path, the build should fail rather than silently shipping unsafe code.
111
111
 
112
+ The boundary cache is owned by the React plugin and shared by normal Page Browser Graph bundles and HMR. Cache entries include the module source, allow-list package names with their permitted exports, and inbound requested exports; each build still starts with a fresh requested-export registry. Modules that inline external file contents are never cached. Set `ECO_AST_PROFILE=1` to emit one structured timing record per client-graph cache lookup and analysis while investigating a docs build or development rebuild.
113
+
114
+ ### `explicitGraph` option
115
+
116
+ `reactPlugin({ explicitGraph: true })` forces the page browser graph (hydration assets) to emit for every React page, even when the page does not declare `dependencies.modules` and no router is configured.
117
+
118
+ It does **not** disable the client-graph AST boundary. Server-only `eco.page(...)` options such as `middleware` and `requires` are still stripped from browser bundles. With a router adapter, page hydration is already always on, so the option is redundant for SPA apps.
119
+
120
+ The option name is historical — it forces hydration asset emission, it does not mean “skip graph transforms.”
121
+
112
122
  ### What Stays and What Goes
113
123
 
114
124
  The client bundle keeps:
@@ -131,7 +141,7 @@ Important:
131
141
 
132
142
  ### AST Pipeline Order
133
143
 
134
- The browser-bound transform in [src/utils/client-graph-boundary-plugin.ts](src/utils/client-graph-boundary-plugin.ts) follows this order:
144
+ The browser-bound transform in [src/client-graph/boundary-plugin.ts](src/client-graph/boundary-plugin.ts) follows this order:
135
145
 
136
146
  1. Parse the module and build a reachability view of the client render graph.
137
147
  2. Remove imports that are not allowed or not reachable from the client graph.
@@ -166,7 +176,7 @@ The fix is to strip server-only `eco.page(...)` options after import pruning, wh
166
176
 
167
177
  The browser must not receive arbitrary request-scoped data.
168
178
 
169
- The React renderer in [src/react-renderer.ts](src/react-renderer.ts) serializes only the top-level `locals` keys explicitly declared by `Page.requires`. If a page does not declare `requires`, no `locals` are serialized for hydration.
179
+ The React renderer in [src/render/react-renderer.ts](src/render/react-renderer.ts) serializes only the top-level `locals` keys explicitly declared by `Page.requires`. If a page does not declare `requires`, no `locals` are serialized for hydration.
170
180
 
171
181
  Example:
172
182
 
@@ -191,7 +201,7 @@ Hydration must rebuild the same tree the server rendered.
191
201
 
192
202
  That applies to both:
193
203
 
194
- - non-router hydration scripts in [src/utils/hydration-scripts.ts](src/utils/hydration-scripts.ts)
204
+ - non-router hydration scripts in [src/hydration/hydration-scripts.ts](src/hydration/hydration-scripts.ts)
195
205
  - router-backed hydration in [../../react-router/src/router.ts](../../react-router/src/router.ts)
196
206
 
197
207
  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.
@@ -200,9 +210,167 @@ If the page render receives `locals` on the server and the layout also depends o
200
210
 
201
211
  The main regression coverage lives in:
202
212
 
203
- - [src/utils/client-graph-boundary-plugin.test.ts](src/utils/client-graph-boundary-plugin.test.ts): verifies server-only `eco.page(...)` options are stripped from browser bundles.
204
- - [src/react-renderer.locals.test.ts](src/react-renderer.locals.test.ts): verifies only declared `requires` keys are serialized into hydration payloads.
205
- - [src/utils/hydration-scripts.test.ts](src/utils/hydration-scripts.test.ts): verifies non-router hydration passes serialized `locals` into layouts.
213
+ - [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
+ - [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.
206
216
  - [../../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.
207
217
 
208
218
  If you change the AST transform or hydration flow, update the corresponding tests in the same change.
219
+
220
+ ### Nested layouts and unified SSR
221
+
222
+ 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).
223
+
224
+ 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).
225
+
226
+ 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.
227
+
228
+ - [src/render/layout-compose.ts](src/render/layout-compose.ts): shared client/SSR tree builder.
229
+ - [src/test/react-ssr-hydration-parity.test.tsx](src/test/react-ssr-hydration-parity.test.tsx): nested tier order parity between SSR and `composeLayoutPageTree`.
230
+ - [src/test/react-ssr-unified.test.tsx](src/test/react-ssr-unified.test.tsx): provider context through nested SSR layouts.
231
+
232
+ ### Shared runtime vendors (SPA + persisted layouts)
233
+
234
+ #### Mental model
235
+
236
+ With `ecoRouter()`, Ecopages keeps outer layout tiers mounted across client navigation (`persistLayouts` defaults to `true`). Each page chunk still loads separately, but provider layouts stay alive in the DOM.
237
+
238
+ That creates a module identity problem: if TanStack Query (or any shared provider library) is bundled into every page chunk separately, each chunk gets its own copy of the library and its own React context. Navigation then breaks with errors such as `No QueryClient set`, even though the provider component is still mounted.
239
+
240
+ The fix is **shared browser runtime vendors**: selected npm packages are built once into `/assets/vendors/*.js` and every page chunk imports the same public URL. React, React DOM, the router bundle, and auto-discovered layout runtime packages all follow this path.
241
+
242
+ 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
+
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.
245
+
246
+ 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
+
248
+ #### When auto-discovery runs
249
+
250
+ Auto-discovery runs at plugin setup when **both** are true:
251
+
252
+ - `router` is passed to `reactPlugin()`
253
+ - The app config exposes `absolutePaths.projectDir`, `layoutsDir`, and `componentsDir`
254
+
255
+ Without `router`, only explicit `runtimeModules` entries are vendored.
256
+
257
+ #### Discovery modes
258
+
259
+ | Mode | Trigger | Layout roots scanned | npm packages collected |
260
+ | ---------------------------------- | ------------------------------------------------ | ---------------------------------------------------------- | ----------------------------------------------------------- |
261
+ | **Runtime-provider** (recommended) | At least one layout sets `runtimeProvider: true` | Only flagged layouts | Every reachable npm package in that layout's `render` graph |
262
+ | **Provider-scoped fallback** | No layout sets `runtimeProvider: true` | All `eco.layout(` files under `layouts/` and `components/` | npm packages imported from provider/context modules only |
263
+
264
+ The fallback exists for backward compatibility. Ecopages logs a debug message when fallback mode is active. Prefer explicit `runtimeProvider: true` on provider root layouts (for example a query-client tier) and omit it from shell-only layouts.
265
+
266
+ #### What gets discovered
267
+
268
+ 1. Select layout entry files using the mode above.
269
+ 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.
270
+ 3. Collect npm package roots (for example `@tanstack/react-query`, not `@tanstack/react-query/devtools`).
271
+ 4. Register each discovered package as a shared vendor.
272
+
273
+ **Excluded automatically:** React, React DOM, jsx runtimes, the router bundle, `@ecopages/*`, workspace packages under `@techn.es/*`, `*-devtools` packages, and packages already vendored by the React plugin.
274
+
275
+ Path aliases resolve from `tsconfig.json` `compilerOptions.paths` (oxc-resolver), same as the Ecopages alias resolver plugin.
276
+
277
+ #### Recommended setup
278
+
279
+ Plugin config — no manual vendor list when provider layouts are flagged:
280
+
281
+ ```ts
282
+ import { ConfigBuilder } from '@ecopages/core/config-builder';
283
+ import { reactPlugin } from '@ecopages/react';
284
+ import { ecoRouter } from '@ecopages/react-router';
285
+
286
+ const config = await new ConfigBuilder().setIntegrations([reactPlugin({ router: ecoRouter() })]).build();
287
+
288
+ export default config;
289
+ ```
290
+
291
+ Provider root layout — set `runtimeProvider: true` on the tier that mounts shared client state:
292
+
293
+ ```tsx
294
+ import type { ReactNode } from 'react';
295
+ import { eco } from '@ecopages/core';
296
+ import { QueryProvider } from '@/shared/query/query-provider';
297
+
298
+ export const QueryRootLayout = eco.layout<ReactNode>({
299
+ runtimeProvider: true,
300
+ render: ({ children }) => <QueryProvider>{children}</QueryProvider>,
301
+ });
302
+ ```
303
+
304
+ Shell layouts that do not mount shared runtime state omit the flag:
305
+
306
+ ```tsx
307
+ export const AppShellLayout = eco.layout({
308
+ render: ({ children }) => <AppShell>{children}</AppShell>,
309
+ });
310
+ ```
311
+
312
+ Stack provider roots before shell tiers in page `layout` arrays so context wraps the shell on both SSR and persisted client navigation.
313
+
314
+ Requires matching tsconfig paths when using aliases:
315
+
316
+ ```json
317
+ {
318
+ "compilerOptions": {
319
+ "paths": {
320
+ "@/*": ["./src/*"]
321
+ }
322
+ }
323
+ }
324
+ ```
325
+
326
+ #### Overrides and escape hatches
327
+
328
+ Use explicit `runtimeModules` when discovery misses a package, when `router` is not enabled, or when you need custom vendor output names or externals:
329
+
330
+ ```ts
331
+ reactPlugin({
332
+ router: ecoRouter(),
333
+ runtimeModules: ['@tanstack/react-query', { specifier: '@acme/ui', outputName: 'acme-ui', externals: ['react'] }],
334
+ });
335
+ ```
336
+
337
+ Manual entries **override** auto-discovered entries for the same specifier.
338
+
339
+ #### Troubleshooting
340
+
341
+ | Symptom | Likely cause | Fix |
342
+ | ------------------------------------------ | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
343
+ | `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 |
344
+ | Wrong packages vendored (slow dev startup) | Shell layout scanned as discovery root | Set `runtimeProvider: true` only on provider roots; keep shell layouts unflagged |
345
+ | Package not discovered | Layout outside `layouts/` / `components/`, or import not reachable from `render` | Move layout file or add explicit `runtimeModules` entry |
346
+ | `@/` alias not followed | Missing or invalid tsconfig paths | Add `compilerOptions.paths`; ensure `include` globs are valid JSON (not broken by comment stripping) |
347
+
348
+ #### Tests
349
+
350
+ - [src/bundling/discover-layout-runtime-modules.test.ts](src/bundling/discover-layout-runtime-modules.test.ts): discovery modes, provider scoping, tsconfig aliases, stacked layouts.
351
+ - [src/bundling/runtime-bundle.test.ts](src/bundling/runtime-bundle.test.ts): vendor registration and manifest paths.
352
+ - [../../core/src/services/assets/asset-processing-service/browser-runtime-entry-resolution.test.ts](../../core/src/services/assets/asset-processing-service/browser-runtime-entry-resolution.test.ts): ESM entry resolution and default-export policy for React vs TanStack Query.
353
+
354
+ ### Client-only code in SSR trees
355
+
356
+ Pages and layouts SSR through `renderToString`, which does not support `<Suspense>`. Do not use `React.lazy()` + `<Suspense>` in `eco.page()` or `eco.layout()` trees.
357
+
358
+ Wrap browser-only UI in `ClientOnly`:
359
+
360
+ ```tsx
361
+ import { eco } from '@ecopages/core';
362
+ import { ClientOnly } from '@ecopages/react/utils/client-only';
363
+
364
+ export const RootLayout = eco.layout({
365
+ render: ({ children }) => (
366
+ <>
367
+ {children}
368
+ <ClientOnly fallback={null}>
369
+ <DevtoolsPanel />
370
+ </ClientOnly>
371
+ </>
372
+ ),
373
+ });
374
+ ```
375
+
376
+ 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/react",
3
- "version": "0.2.0-beta.4",
3
+ "version": "0.2.0-beta.41",
4
4
  "description": "React integration for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -8,80 +8,105 @@
8
8
  "plugin"
9
9
  ],
10
10
  "license": "MIT",
11
- "main": "./src/react.plugin.js",
12
- "types": "./src/react.plugin.d.ts",
11
+ "main": "./src/plugin/react.plugin.js",
12
+ "types": "./src/plugin/react.plugin.d.ts",
13
13
  "type": "module",
14
14
  "exports": {
15
15
  ".": {
16
- "default": "./src/react.plugin.js",
17
- "types": "./src/react.plugin.d.ts"
16
+ "default": "./src/plugin/react.plugin.js",
17
+ "types": "./src/plugin/react.plugin.d.ts"
18
18
  },
19
19
  "./eco-embed": {
20
- "default": "./src/eco-embed.js",
21
- "types": "./src/eco-embed.d.ts"
20
+ "default": "./src/render/eco-embed.js",
21
+ "types": "./src/render/eco-embed.d.ts"
22
22
  },
23
23
  "./declarations": {
24
- "types": "./src/declarations.d.ts"
24
+ "types": "./src/contracts/declarations.d.ts"
25
25
  },
26
26
  "./utils/dynamic": {
27
- "types": "./src/utils/dynamic.d.ts",
28
- "default": "./src/utils/dynamic.js"
27
+ "types": "./src/app/dynamic.d.ts",
28
+ "default": "./src/app/dynamic.js"
29
29
  },
30
30
  "./utils/client-only": {
31
- "types": "./src/utils/client-only.d.ts",
32
- "default": "./src/utils/client-only.js"
31
+ "types": "./src/app/client-only.d.ts",
32
+ "default": "./src/app/client-only.js"
33
33
  },
34
34
  "./runtime/use-sync-external-store-with-selector": {
35
35
  "types": "./src/runtime/use-sync-external-store-with-selector.d.ts",
36
36
  "default": "./src/runtime/use-sync-external-store-with-selector.js"
37
37
  },
38
38
  "./router-adapter": {
39
- "types": "./src/router-adapter.d.ts",
40
- "default": "./src/router-adapter.js"
39
+ "types": "./src/contracts/router-adapter.d.ts",
40
+ "default": "./src/contracts/router-adapter.js"
41
+ },
42
+ "./layout-compose": {
43
+ "types": "./src/render/layout-compose.d.ts",
44
+ "default": "./src/render/layout-compose.js"
45
+ },
46
+ "./serialize-page-data-script": {
47
+ "types": "./src/hydration/serialize-page-data-script.d.ts",
48
+ "default": "./src/hydration/serialize-page-data-script.js"
49
+ },
50
+ "./page-data-reader": {
51
+ "types": "./src/hydration/page-data-reader.d.ts",
52
+ "default": "./src/hydration/page-data-reader.js"
41
53
  },
42
54
  "./eco-embed.ts": {
43
- "default": "./src/eco-embed.js",
44
- "types": "./src/eco-embed.d.ts"
55
+ "default": "./src/render/eco-embed.js",
56
+ "types": "./src/render/eco-embed.d.ts"
45
57
  },
46
58
  "./declarations.ts": {
47
- "types": "./src/declarations.d.ts"
59
+ "types": "./src/contracts/declarations.d.ts"
48
60
  },
49
61
  "./utils/dynamic.ts": {
50
- "types": "./src/utils/dynamic.d.ts",
51
- "default": "./src/utils/dynamic.js"
62
+ "types": "./src/app/dynamic.d.ts",
63
+ "default": "./src/app/dynamic.js"
52
64
  },
53
65
  "./utils/client-only.ts": {
54
- "types": "./src/utils/client-only.d.ts",
55
- "default": "./src/utils/client-only.js"
66
+ "types": "./src/app/client-only.d.ts",
67
+ "default": "./src/app/client-only.js"
56
68
  },
57
69
  "./runtime/use-sync-external-store-with-selector.ts": {
58
70
  "types": "./src/runtime/use-sync-external-store-with-selector.d.ts",
59
71
  "default": "./src/runtime/use-sync-external-store-with-selector.js"
60
72
  },
61
73
  "./router-adapter.ts": {
62
- "types": "./src/router-adapter.d.ts",
63
- "default": "./src/router-adapter.js"
74
+ "types": "./src/contracts/router-adapter.d.ts",
75
+ "default": "./src/contracts/router-adapter.js"
76
+ },
77
+ "./layout-compose.ts": {
78
+ "types": "./src/render/layout-compose.d.ts",
79
+ "default": "./src/render/layout-compose.js"
80
+ },
81
+ "./serialize-page-data-script.ts": {
82
+ "types": "./src/hydration/serialize-page-data-script.d.ts",
83
+ "default": "./src/hydration/serialize-page-data-script.js"
84
+ },
85
+ "./page-data-reader.ts": {
86
+ "types": "./src/hydration/page-data-reader.d.ts",
87
+ "default": "./src/hydration/page-data-reader.js"
64
88
  }
65
89
  },
66
90
  "repository": {
67
91
  "type": "git",
68
- "url": "https://github.com/ecopages/ecopages.git",
92
+ "url": "git+https://github.com/ecopages/ecopages.git",
69
93
  "directory": "packages/integrations/react"
70
94
  },
71
95
  "peerDependencies": {
72
- "@ecopages/core": "0.2.0-beta.4",
96
+ "@ecopages/core": "0.2.0-beta.41",
73
97
  "@types/react": "^19",
74
98
  "@types/react-dom": "^19",
75
99
  "react": "^19",
76
100
  "react-dom": "^19"
77
101
  },
78
102
  "dependencies": {
79
- "@ecopages/file-system": "0.2.0-beta.4",
103
+ "@ecopages/file-system": "0.2.0-beta.41",
80
104
  "@ecopages/logger": "^0.2.3",
105
+ "@ecopages/mdx": "0.2.0-beta.41",
81
106
  "@mdx-js/mdx": "^3.1.1",
82
- "oxc-parser": "^0.124.0",
83
- "oxc-transform": "^0.124.0",
84
- "source-map": "^0.7.6",
107
+ "oxc-parser": "^0.141.0",
108
+ "oxc-transform": "^0.141.0",
109
+ "source-map": "^0.8.0",
85
110
  "vfile": "^6.0.3"
86
111
  }
87
112
  }
@@ -0,0 +1,15 @@
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
+ };
9
+ export const ClientOnly = ({ children, fallback = null }) => {
10
+ const isClient = useIsClient();
11
+ if (!isClient) {
12
+ return fallback;
13
+ }
14
+ return children;
15
+ };
@@ -0,0 +1,9 @@
1
+ import { lazy } from 'react';
2
+ const NullComponent = () => null;
3
+ export function dynamic(importFn, options = {}) {
4
+ const { ssr = false } = options;
5
+ if (ssr || typeof window !== 'undefined') {
6
+ return lazy(importFn);
7
+ }
8
+ return NullComponent;
9
+ }
@@ -0,0 +1,31 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Suspense } from 'react';
3
+ import { afterEach, describe, expect, it } from 'vitest';
4
+ import { cleanup, render, screen } from '@testing-library/react';
5
+ import { dynamic } from './dynamic.js';
6
+ function createDeferredImport() {
7
+ let resolve;
8
+ const promise = new Promise((innerResolve) => {
9
+ resolve = innerResolve;
10
+ });
11
+ return {
12
+ promise,
13
+ resolve,
14
+ };
15
+ }
16
+ describe('dynamic', () => {
17
+ afterEach(() => {
18
+ cleanup();
19
+ });
20
+ it('returns a browser lazy component that resolves through Suspense', async () => {
21
+ const deferredImport = createDeferredImport();
22
+ const DynamicComponent = dynamic(() => deferredImport.promise);
23
+ render(_jsx(Suspense, { fallback: _jsx("span", { children: "Loading dynamic component" }), children: _jsx(DynamicComponent, {}) }));
24
+ expect(screen.getByText('Loading dynamic component')).toBeTruthy();
25
+ deferredImport.resolve({
26
+ default: () => _jsx("span", { children: "Dynamic content" }),
27
+ });
28
+ expect(await screen.findByText('Dynamic content')).toBeTruthy();
29
+ expect(screen.queryByText('Loading dynamic component')).toBeNull();
30
+ });
31
+ });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Bare package specifiers for React page hydration bootstrap helpers.
3
+ */
4
+ export declare const PAGE_LAYOUT_NORMALIZATION_PACKAGE = "@ecopages/core/eco/page-layout-normalization";
5
+ export declare const LAYOUT_COMPOSE_PACKAGE = "@ecopages/react/layout-compose";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Bare package specifiers for React page hydration bootstrap helpers.
3
+ */
4
+ export const PAGE_LAYOUT_NORMALIZATION_PACKAGE = '@ecopages/core/eco/page-layout-normalization';
5
+ export const LAYOUT_COMPOSE_PACKAGE = '@ecopages/react/layout-compose';
@@ -6,18 +6,24 @@
6
6
  *
7
7
  * @module
8
8
  */
9
- import type { ReactRouterAdapter } from '../router-adapter.js';
9
+ import type { EcoPagesAppConfig } from '@ecopages/core';
10
+ import type { AssetProcessingService } from '@ecopages/core/services/asset-processing-service';
11
+ import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
10
12
  import type { CompileOptions } from '@mdx-js/mdx';
11
- import { type ReactRuntimeImports } from './react-runtime-bundle.service.js';
13
+ import { type ReactRuntimeImports } from './runtime-bundle.js';
14
+ import type { ResolvedReactPluginRuntimeModule } from './runtime-modules.js';
15
+ import type { ClientGraphBoundaryCache } from '../client-graph/boundary-cache.js';
12
16
  /**
13
- * Configuration for the ReactBundleService.
17
+ * Configuration for the BundleService.
14
18
  */
15
- export interface ReactBundleServiceConfig {
19
+ export interface BundleServiceConfig {
16
20
  rootDir: string;
21
+ appConfig: EcoPagesAppConfig;
22
+ hostIntegrationName: string;
17
23
  routerAdapter?: ReactRouterAdapter;
24
+ runtimeModules?: ResolvedReactPluginRuntimeModule[];
18
25
  mdxCompilerOptions?: CompileOptions;
19
- nonReactExtensions?: string[];
20
- jsxImportSource?: string;
26
+ clientGraphBoundaryCache?: ClientGraphBoundaryCache;
21
27
  }
22
28
  /**
23
29
  * Optional flags that adjust how a React client entry is bundled.
@@ -36,14 +42,23 @@ export interface ReactClientBundleOptions {
36
42
  /**
37
43
  * Manages bundle configuration and plugin creation for React page/component builds.
38
44
  */
39
- export declare class ReactBundleService {
45
+ export declare class BundleService {
40
46
  private readonly runtimeBundleService;
41
47
  private readonly config;
42
- constructor(config: ReactBundleServiceConfig);
48
+ private pageLayoutNormalizationVendorPromise;
49
+ constructor(config: BundleServiceConfig);
43
50
  /**
44
51
  * Returns resolved runtime import paths for the React runtime.
45
52
  */
46
53
  getRuntimeImports(): ReactRuntimeImports;
54
+ /**
55
+ * Processes the MDX-only page-layout-normalization vendor once per BundleService instance.
56
+ *
57
+ * @remarks
58
+ * Concurrent callers share the same in-flight promise. Asset processing itself caches
59
+ * by dependency key, so repeats after success remain cheap.
60
+ */
61
+ ensurePageLayoutNormalizationVendorProcessed(assetProcessingService: Pick<AssetProcessingService, 'processDependencies'>): Promise<void>;
47
62
  /**
48
63
  * Creates bundle options for a page or component entry.
49
64
  *
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Bundle configuration service for React integration.
3
+ *
4
+ * Encapsulates all build plugin creation and bundle options
5
+ * for client-side React component builds.
6
+ *
7
+ * @module
8
+ */
9
+ import { createClientGraphBoundaryPlugin } from '../client-graph/boundary-plugin.js';
10
+ import { getReactClientGraphAllowSpecifiers, getReactRuntimeExternalSpecifiers } from './runtime-alias-map.js';
11
+ import { createBrowserRuntimePlugin } from '@ecopages/core/build/browser-runtime-plugin';
12
+ import { getHostScopedJsxOwnershipPlugins } from '@ecopages/core/build/jsx-ownership-plugins';
13
+ import { RuntimeBundleService } from './runtime-bundle.js';
14
+ import { createReactMdxLoaderPlugin } from '../mdx/mdx-loader-plugin.js';
15
+ import { isReactProductionRuntime } from './runtime-mode.js';
16
+ /**
17
+ * Manages bundle configuration and plugin creation for React page/component builds.
18
+ */
19
+ export class BundleService {
20
+ runtimeBundleService;
21
+ config;
22
+ pageLayoutNormalizationVendorPromise;
23
+ constructor(config) {
24
+ this.config = config;
25
+ this.runtimeBundleService = new RuntimeBundleService({
26
+ rootDir: config.rootDir,
27
+ routerAdapter: config.routerAdapter,
28
+ runtimeModules: config.runtimeModules,
29
+ });
30
+ }
31
+ /**
32
+ * Returns resolved runtime import paths for the React runtime.
33
+ */
34
+ getRuntimeImports() {
35
+ return this.runtimeBundleService.getRuntimeImports();
36
+ }
37
+ /**
38
+ * Processes the MDX-only page-layout-normalization vendor once per BundleService instance.
39
+ *
40
+ * @remarks
41
+ * Concurrent callers share the same in-flight promise. Asset processing itself caches
42
+ * by dependency key, so repeats after success remain cheap.
43
+ */
44
+ async ensurePageLayoutNormalizationVendorProcessed(assetProcessingService) {
45
+ if (!this.pageLayoutNormalizationVendorPromise) {
46
+ this.pageLayoutNormalizationVendorPromise = assetProcessingService
47
+ .processDependencies(this.runtimeBundleService.getPageLayoutNormalizationDependencies(), 'react:page-layout-normalization')
48
+ .then(() => undefined)
49
+ .catch((error) => {
50
+ this.pageLayoutNormalizationVendorPromise = undefined;
51
+ throw error;
52
+ });
53
+ }
54
+ await this.pageLayoutNormalizationVendorPromise;
55
+ }
56
+ /**
57
+ * Creates bundle options for a page or component entry.
58
+ *
59
+ * @remarks
60
+ * React derives runtime specifier mappings from the core browser runtime manifest
61
+ * so ESM imports resolve to concrete runtime asset URLs during module loading.
62
+ *
63
+ * @param componentName - Generated unique component name for output naming
64
+ * @param isMdx - Whether the source file is an MDX file
65
+ * @param declaredModules - Explicitly declared browser module specifiers
66
+ * @returns Bundle options object for the build adapter
67
+ */
68
+ async createBundleOptions(componentName, isMdx, declaredModules, bundleOptions = {}) {
69
+ const runtimeImports = this.getRuntimeImports();
70
+ const options = {
71
+ mainFields: ['module', 'browser', 'main'],
72
+ naming: `${componentName}.[ext]`,
73
+ ...(isReactProductionRuntime() && {
74
+ minify: true,
75
+ treeshaking: true,
76
+ }),
77
+ ...(bundleOptions.splitting === undefined ? {} : { splitting: bundleOptions.splitting }),
78
+ };
79
+ if (!bundleOptions.includeRuntime) {
80
+ const reactRuntimeSpecifiers = new Set(getReactRuntimeExternalSpecifiers());
81
+ options.external = [
82
+ ...Object.values(runtimeImports).filter((specifier) => Boolean(specifier) &&
83
+ !reactRuntimeSpecifiers.has(specifier)),
84
+ ];
85
+ }
86
+ const graphBoundaryPlugin = createClientGraphBoundaryPlugin({
87
+ projectRoot: this.config.appConfig?.absolutePaths?.projectDir ?? this.config.rootDir,
88
+ absWorkingDir: this.config.rootDir,
89
+ declaredModules,
90
+ alwaysAllowSpecifiers: getReactClientGraphAllowSpecifiers(this.runtimeBundleService.getConfiguredRuntimeModuleSpecifiers(), this.config.routerAdapter),
91
+ cache: this.config.clientGraphBoundaryCache,
92
+ });
93
+ const [foreignJsxOverridePlugin] = getHostScopedJsxOwnershipPlugins(this.config.appConfig, this.config.hostIntegrationName, { name: 'react-renderer-foreign-jsx-override' });
94
+ const runtimeManifest = this.runtimeBundleService.getRuntimeManifest();
95
+ const runtimeRewritePlugin = createBrowserRuntimePlugin({
96
+ name: 'react-renderer-runtime-import-rewrite',
97
+ manifest: runtimeManifest,
98
+ });
99
+ const runtimePlugins = bundleOptions.includeRuntime
100
+ ? []
101
+ : [runtimeRewritePlugin].filter((plugin) => plugin !== null);
102
+ if (isMdx && this.config.mdxCompilerOptions) {
103
+ const mdxPlugin = createReactMdxLoaderPlugin(this.config.mdxCompilerOptions);
104
+ options.plugins = [
105
+ ...(foreignJsxOverridePlugin ? [foreignJsxOverridePlugin] : []),
106
+ graphBoundaryPlugin,
107
+ ...runtimePlugins,
108
+ mdxPlugin,
109
+ ];
110
+ }
111
+ else {
112
+ options.plugins = [
113
+ ...(foreignJsxOverridePlugin ? [foreignJsxOverridePlugin] : []),
114
+ graphBoundaryPlugin,
115
+ ...runtimePlugins,
116
+ ];
117
+ }
118
+ return options;
119
+ }
120
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Discovers npm packages reachable from persisted `eco.layout()` client graphs.
3
+ *
4
+ * @module
5
+ */
6
+ export type LayoutRuntimeDiscoveryMode = 'runtime-provider-layouts' | 'provider-scoped-fallback';
7
+ export type LayoutRuntimeDiscoveryResult = {
8
+ specifiers: string[];
9
+ mode: LayoutRuntimeDiscoveryMode;
10
+ };
11
+ /**
12
+ * Returns true when a layout opts into runtime-provider auto-vendoring discovery.
13
+ */
14
+ export declare function isRuntimeProviderLayoutSource(source: string): boolean;
15
+ /**
16
+ * Returns true when a module looks like it mounts shared client runtime state
17
+ * (React context providers, query clients, etc.).
18
+ */
19
+ export declare function isProviderRuntimeModulePath(filePath: string, source: string): boolean;
20
+ /**
21
+ * Normalizes import specifiers to the package entry used for browser vendors.
22
+ */
23
+ export declare function normalizeRuntimePackageSpecifier(specifier: string): string;
24
+ /**
25
+ * Finds npm packages imported from persisted layout client graphs under the given directories.
26
+ */
27
+ export declare function discoverLayoutRuntimeModuleSpecifiers(options: {
28
+ searchDirs: string[];
29
+ projectRoot?: string;
30
+ extensions?: readonly string[];
31
+ routerImportPath?: string;
32
+ }): LayoutRuntimeDiscoveryResult;