@ecopages/core 0.4.0 → 0.6.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 (163) hide show
  1. package/README.md +19 -15
  2. package/package.json +13 -4
  3. package/src/adapters/create-app.js +9 -5
  4. package/src/adapters/node/create-app.d.ts +18 -16
  5. package/src/adapters/node/create-app.js +26 -30
  6. package/src/adapters/node/server-adapter.d.ts +26 -9
  7. package/src/adapters/node/server-adapter.js +38 -8
  8. package/src/adapters/shared/hmr/hmr-manager.js +3 -2
  9. package/src/adapters/shared/http/api-request-pipeline.js +2 -2
  10. package/src/adapters/shared/http/dist-file-handler.js +25 -7
  11. package/src/adapters/shared/runtime/render-context.d.ts +2 -1
  12. package/src/adapters/shared/runtime/render-context.js +18 -21
  13. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +4 -3
  14. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +6 -4
  15. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +6 -1
  16. package/src/adapters/shared/runtime/server-request-pipeline.js +11 -10
  17. package/src/adapters/shared/runtime/server-route-handler.js +4 -4
  18. package/src/adapters/shared/runtime/server-static-builder.d.ts +11 -11
  19. package/src/adapters/shared/runtime/server-static-builder.js +37 -18
  20. package/src/assets/app-browser-client-build.js +8 -21
  21. package/src/assets/app-browser-client-manifest.d.ts +1 -4
  22. package/src/assets/app-browser-client-manifest.js +6 -78
  23. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +2 -2
  24. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +2 -2
  25. package/src/assets/browser-asset-output.d.ts +1 -1
  26. package/src/assets/browser-asset-output.js +1 -1
  27. package/src/build/app-build-manifest-runtime.d.ts +11 -1
  28. package/src/build/app-build-manifest-runtime.js +17 -3
  29. package/src/build/cache/pages-unified-graph-build.d.ts +32 -35
  30. package/src/build/cache/pages-unified-graph-build.js +206 -124
  31. package/src/build/cache/server-module-entries.d.ts +35 -0
  32. package/src/build/cache/server-module-entries.js +109 -0
  33. package/src/build/contracts/build-contracts.d.ts +5 -0
  34. package/src/build/contracts/content-virtual-modules.d.ts +9 -3
  35. package/src/build/contracts/content-virtual-modules.js +11 -5
  36. package/src/build/contracts.d.ts +1 -1
  37. package/src/build/contracts.js +1 -1
  38. package/src/build/copy-server-files.d.ts +10 -0
  39. package/src/build/copy-server-files.js +37 -0
  40. package/src/build/preserve-import-meta-transform.d.ts +1 -1
  41. package/src/build/preserve-import-meta-transform.js +1 -1
  42. package/src/build/production-build-id.d.ts +9 -0
  43. package/src/build/production-build-id.js +19 -0
  44. package/src/build/production-dist-complete.d.ts +5 -0
  45. package/src/build/production-dist-complete.js +101 -0
  46. package/src/build/production-route-list.d.ts +26 -0
  47. package/src/build/production-route-list.js +78 -0
  48. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +2 -2
  49. package/src/build/rolldown/rolldown-adapter-helpers.js +56 -4
  50. package/src/build/rolldown/rolldown-build-adapter.js +1 -1
  51. package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
  52. package/src/build/runtime/build-request-identity.js +2 -1
  53. package/src/build/runtime/build-request-policy.d.ts +3 -2
  54. package/src/build/runtime/build-request-policy.js +5 -3
  55. package/src/build/server/import-view-module.d.ts +11 -0
  56. package/src/build/server/import-view-module.js +21 -0
  57. package/src/build/server/imported-view-plugin.d.ts +16 -0
  58. package/src/build/server/imported-view-plugin.js +59 -0
  59. package/src/build/server/page-module-import.service.d.ts +19 -20
  60. package/src/build/server/page-module-import.service.js +65 -36
  61. package/src/build/server/resolve-static-view.d.ts +9 -0
  62. package/src/build/server/resolve-static-view.js +28 -0
  63. package/src/build/server/route-module-build-cache-registry.d.ts +5 -3
  64. package/src/build/server/route-module-build-cache-registry.js +5 -3
  65. package/src/build/server/server-modules-manifest.d.ts +51 -0
  66. package/src/build/server/server-modules-manifest.js +129 -0
  67. package/src/build/server/view-reference.d.ts +38 -0
  68. package/src/build/server/view-reference.js +112 -0
  69. package/src/build/server-bundle-deploy-manifest.d.ts +9 -9
  70. package/src/build/server-bundle-deploy-manifest.js +24 -28
  71. package/src/build.d.ts +4 -2
  72. package/src/build.js +4 -2
  73. package/src/config/assembly/app-runtime.d.ts +15 -2
  74. package/src/config/assembly/app-runtime.js +3 -1
  75. package/src/config/assembly/finalize-config.js +64 -13
  76. package/src/config/index.d.ts +1 -0
  77. package/src/config/index.js +1 -0
  78. package/src/config/internal-types.d.ts +6 -0
  79. package/src/config/load-eco-config.d.ts +1 -0
  80. package/src/config/load-eco-config.js +11 -2
  81. package/src/config/resolve-eco-config-path.d.ts +2 -1
  82. package/src/config/resolve-eco-config-path.js +21 -15
  83. package/src/config/user-config-types.d.ts +9 -2
  84. package/src/dev/transform-server/dev-transform-server.js +1 -1
  85. package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
  86. package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
  87. package/src/errors/http-error.d.ts +9 -0
  88. package/src/errors/http-error.js +11 -0
  89. package/src/html/html-transformer.service.d.ts +0 -21
  90. package/src/html/html-transformer.service.js +0 -32
  91. package/src/html-pages/html-page-module.d.ts +19 -0
  92. package/src/html-pages/html-page-module.js +66 -13
  93. package/src/html-pages/html-page-renderer.d.ts +6 -1
  94. package/src/html-pages/html-page-renderer.js +14 -6
  95. package/src/html-pages/html-pages.plugin.d.ts +10 -0
  96. package/src/html-pages/html-pages.plugin.js +7 -1
  97. package/src/index.d.ts +2 -0
  98. package/src/index.js +2 -0
  99. package/src/integration.d.ts +2 -2
  100. package/src/integration.js +1 -1
  101. package/src/islands/island-host.d.ts +1 -2
  102. package/src/islands/island-host.js +1 -2
  103. package/src/page-cache/page-cache-service.d.ts +8 -0
  104. package/src/page-cache/page-cache-service.js +12 -0
  105. package/src/plugins/integration-plugin.d.ts +34 -7
  106. package/src/plugins/integration-plugin.js +14 -2
  107. package/src/plugins/processor.d.ts +18 -1
  108. package/src/plugins/processor.js +20 -1
  109. package/src/plugins/server-dom.d.ts +29 -0
  110. package/src/plugins/server-dom.js +36 -0
  111. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  112. package/src/plugins/tsconfig-import-resolver.js +4 -2
  113. package/src/processor.d.ts +1 -1
  114. package/src/route-renderer/error-pages/error-page-renderer.d.ts +6 -4
  115. package/src/route-renderer/error-pages/error-page-renderer.js +9 -5
  116. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
  117. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
  118. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
  119. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
  120. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
  121. package/src/route-renderer/orchestration/integration-renderer.d.ts +21 -44
  122. package/src/route-renderer/orchestration/integration-renderer.js +69 -117
  123. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
  124. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
  125. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
  126. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
  127. package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
  128. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.d.ts +21 -0
  129. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.js +31 -0
  130. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +58 -24
  131. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.d.ts +12 -0
  132. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.js +55 -0
  133. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
  134. package/src/router/server/route-registry.d.ts +23 -1
  135. package/src/router/server/route-registry.js +41 -14
  136. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +8 -2
  137. package/src/static-site-generator/production-page-browser-graph-prebuild.js +14 -13
  138. package/src/static-site-generator/static-site-generator.d.ts +19 -3
  139. package/src/static-site-generator/static-site-generator.js +78 -40
  140. package/src/types/build-types.d.ts +6 -0
  141. package/src/types/contracts.d.ts +26 -35
  142. package/src/types/eco-api-types.d.ts +1 -1
  143. package/src/types/public-types.d.ts +1 -0
  144. package/src/types/view-reference.d.ts +31 -0
  145. package/src/types/view-reference.js +15 -0
  146. package/src/utils/additional-watch-paths.d.ts +3 -3
  147. package/src/utils/additional-watch-paths.js +3 -1
  148. package/src/utils/resolve-entry-file.d.ts +4 -2
  149. package/src/utils/resolve-entry-file.js +4 -2
  150. package/src/utils/root-relative-path.d.ts +4 -0
  151. package/src/utils/root-relative-path.js +8 -0
  152. package/src/utils/server-bundle-context.d.ts +14 -0
  153. package/src/utils/server-bundle-context.js +45 -0
  154. package/src/watchers/project-watcher-ignore.d.ts +2 -5
  155. package/src/watchers/project-watcher-ignore.js +2 -5
  156. package/src/watchers/project-watcher.d.ts +9 -7
  157. package/src/watchers/project-watcher.js +100 -52
  158. package/src/watchers/workspace-package-watch-roots.d.ts +4 -4
  159. package/src/watchers/workspace-package-watch-roots.js +41 -25
  160. package/src/build/server/view-module-loader.d.ts +0 -10
  161. package/src/build/server/view-module-loader.js +0 -46
  162. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
  163. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js +0 -32
package/README.md CHANGED
@@ -26,17 +26,18 @@ The important ownership rules are:
26
26
  - Component identity attribution is one build plugin, shared by server, browser, and HMR compilation paths: after a lexical `eco.` gate, it uses Oxc to wrap supported factory options with `bindComponentIdentity()`, which factories retain as `config.identity`.
27
27
  - Component ownership follows `config.integration`, then `config.identity.integration`, then the inherited owner through the exported `getComponentOwner()` helper. Integration plugins opt into page-owned asset bundling with `bundlesPageDependencies`; React and Ecopages JSX enable it. Bundling only combines consecutive eligible assets so custom-attribute files keep their declared order.
28
28
  - Direct local Eco Component imports (including named `export { X } from` barrels) and relative side-effect CSS imports supply Dependencies by default through the shared transform and existing collector; explicit asset declarations override inference, and inferred styles stay keyed by identity until collection. Eco owns the component render context used by its factories. See [eco](src/eco/README.md) and [Plugin Contracts](src/plugins/README.md).
29
- - Every Integration shares one renderer and the app-owned `AssetProcessingService` across route renders, explicit views, and foreign-child handoffs. Integration-owned asset processing calls pass their owning Integration so its optional dependency-preparation hook can run; one service cache covers grouped and ungrouped processor results. Route preparation records one component graph for ownership validation, dependencies, client assets, and dev cache paths. Dependency collection uses the service to turn declared assets into runtime-ready output instead of treating a missing service as an empty asset set. Route renders keep assets and foreign-renderer caches in per-render sessions, with async context storage isolating concurrent renders. See [Route Renderer](src/route-renderer/README.md).
30
- - Custom Integrations can create a renderer with `createIntegrationRenderer()` and opt into component, page-graph, document-shell props and composition, foreign-child, route lifecycle, grouped island assets, and finalization hooks without rebuilding the route pipeline. Hook factories receive app-owned renderer options plus helpers for Integration-wide dependencies, component-owned dependencies, dependency paths, and pending lazy triggers. Core handles queued-child resolution and island-host finalization around component hooks. See [Custom Integration](../../apps/docs/src/content/docs/plugins/custom-integration.mdx).
29
+ - Server DOM constructors (`HTMLElement`, `customElements`, `document`) are installed once per process from Integration `serverDom` contributors: complete surfaces first, then repairs. The result does not depend on Integration order in the config or on which Page is requested first. See [Plugin Contracts](src/plugins/README.md).
30
+ - Every Integration shares one renderer and the app-owned `AssetProcessingService` across route renders, explicit views, and foreign-child handoffs. Integration-owned asset processing calls pass their owning Integration so its optional dependency-preparation hook can run; one service cache covers grouped and ungrouped processor results. Route preparation records one component graph for ownership validation, dependencies, client assets, and dev cache paths; a development render fails on a component outside it. Dependency collection uses the service to turn declared assets into runtime-ready output instead of treating a missing service as an empty asset set. Route preparation builds each Page Package once; component renders return HTML and attributes only and add no assets. Route renders keep Integration dependencies and foreign-renderer caches in per-render sessions, with async context storage isolating concurrent renders. See [Route Renderer](src/route-renderer/README.md).
31
+ - Custom Integrations can create a renderer with `createIntegrationRenderer()` and opt into component, page-graph, document-shell props and composition, foreign-child, route lifecycle, grouped island assets, and finalization hooks without rebuilding the route pipeline. Hook factories receive app-owned renderer options plus helpers for Integration-wide dependencies, dependency paths, and pending lazy triggers. Core handles queued-child resolution and island-host finalization around component hooks. See [Custom Integration](../../apps/docs/src/content/docs/plugins/custom-integration.mdx).
31
32
  - Browser bundling and server module loading are separate paths. SSR-enabled lazy scripts execute on the server before rendering and in the browser only on their configured trigger.
32
- - The Project Watcher batches file and directory events, sends matching Processors one `onChanges` notification for each non-restart file batch, and dispatches every HMR-eligible path once per debounce window. Directory-only Pages batches refresh routes without Processor or HMR notifications. Sustained edits are scheduled no later than one second after the first; processing is serialized and startup fails if the filesystem subscription is not ready within 30 seconds. See [Project Watcher](src/watchers/README.md).
33
+ - The Project Watcher uses `@ecopages/file-system` recursive subscriptions, batches file and directory events, sends matching Processors one `onChanges` notification for each non-restart file batch, and dispatches every HMR-eligible path once per debounce window. Directory-only Pages batches refresh routes without Processor or HMR notifications. It activates linked package roots only when a recorded build input uses them, and retries a failed activation when additional inputs arrive during registration. Sustained edits are scheduled no later than one second after the first; processing is serialized and startup fails if the filesystem subscription is not ready within 30 seconds. See [Project Watcher](src/watchers/README.md).
33
34
  - Development Page prewarm renders run in the background without delaying server readiness. App configuration declares `devPrewarmPaths`; Processors append the pathnames they own to that list from `setup()`, which finishes before the server reports that it is listening. A path that fails to render is skipped and logged at debug level. See [Runtime Adapters](src/adapters/README.md) and [Plugin Contracts](src/plugins/README.md).
34
35
  - Watch-mode resources belong to one `DevSession`, including the watcher, HMR manager, client bridge, Page prewarm, and Dev Toolbar. `EcopagesApp` shares one readiness promise across concurrent startup and request-only calls; after `stop()`, `start()` and `fetch()` initialize a fresh server adapter.
35
- - App shutdown tears down Integration runtime resources, including Lit workers. See [Runtime Adapters](src/adapters/README.md).
36
+ - App shutdown tears down Integration runtime resources, including a Lit static-export worker if one is still running. Serving does not start that worker. See [Runtime Adapters](src/adapters/README.md).
36
37
  - HMR and invalidation use shared graph-aware services instead of runtime-specific ad hoc wiring. One Development Invalidation service belongs to each `AppRuntime` and is shared by its Project Watcher and HMR manager. Editing a `source` module used by both a server route and a browser entrypoint reloads the browser so server-rendered markup and the island refresh together.
37
38
  - Browser and React navigation use one core-owned document commit pipeline; each router supplies its page swap and scroll handling while core coordinates fetch/cache/parse, head reconciliation, script activation, view transitions, and lifecycle events. A later navigation supersedes cleanup from earlier transitions, including when it skips animation; a failed or uncommitted page swap clears transition names. Browser-router always morphs the incoming body, keeping nodes with matching persistence keys attached when their ancestor structure remains compatible; during rerun refresh, custom-element descendants on that path also stay in place when their markup remains structurally compatible. Superseded stylesheet waits settle when a later page removes their staged links. For rerun scripts matched by relative `src` (without an explicit script id or HTML `id`), core keeps identity stable across pages with different `<base>` URLs while loading external modules from the incoming page's resolved URL. See [Router Layer](src/router/README.md).
38
- - `serveDistFile()` handles both runtime static fallbacks and preview through the app's `RuntimeHost`, with safe path resolution, HEAD and 405 responses, gzip negotiation, ETags, conditional 304s, and the shared cache policy. `immutable` applies only to outputs the build recorded as content-hashed; HTML stays revalidated. See [Runtime Adapters](src/adapters/README.md).
39
- - The build adapter returns each build's plugin-recorded inputs by module alongside source-module closures, and passes an explicit recorder to Rolldown plugin hooks. Cache owners bind only the paths read by their entry closure, so development invalidates affected Page Browser Graphs, HTML entries, route modules, and browser entrypoints. Grouped browser scripts merge external modules, compatible plugin instances, and non-conflicting define values within their build group, disable splitting when any entry opts out, resolve by the path or name the caller passed (and the bundler's facade when that spelling differs), and cache only complete groups with matching dependency sets. Static production export combines grouped Page entries and HTML module scripts in compatible app-wide browser build groups, saves their route associations in the server manifest, and lets `ecopages start` restore listed route assets before SSR requests. Non-exact route templates also get a parameter-free plan without running route data hooks; later params reuse its output when grouped browser dependencies and page-client entries match, while a new dependency graph keeps the request-time build fallback. Entry-specific plugins with a `bundleGroupKey` retain their own configuration inside the shared build, while entries with different bundle options keep separate requests. In-process Page caches also track reachable generated artifacts. On-demand page-cache path invalidation removes query and development runtime variants of the pathname and releases their build-input bindings. See [Build Layer](src/build/README.md), [Page Cache](src/page-cache/README.md), and [Asset Processing](src/assets/README.md).
39
+ - `serveDistFile()` handles runtime static fallbacks and preview through the app's `RuntimeHost`, serving only `dist/client/` with real-path containment, HEAD and 405 responses, gzip negotiation, ETags, conditional 304s, and the shared cache policy. The private `dist/server/` output is a sibling of the served directory. `immutable` applies only to outputs the build recorded as content-hashed; HTML stays revalidated. See [Runtime Adapters](src/adapters/README.md).
40
+ - The build adapter returns each build's plugin-recorded inputs by module alongside source-module closures, and passes an explicit recorder to Rolldown plugin hooks. Cache owners bind only the paths read by their entry closure, so development invalidates affected Page Browser Graphs, HTML entries, route modules, and browser entrypoints. Grouped browser scripts merge external modules, compatible plugin instances, and non-conflicting define values within their build group, disable splitting when any entry opts out, resolve by the path or name the caller passed (and the bundler's facade when that spelling differs), and cache only complete groups with matching dependency sets. Static production export combines grouped Page entries and HTML module scripts in compatible app-wide browser build groups, saves their route associations in the server manifest, and lets `ecopages start` restore listed route assets before SSR requests. Non-exact route templates also get a parameter-free plan without running route data hooks, Dynamic Pages that declare `staticPaths` get a per-entry plan, and so does every `app.static` route instance. Later params reuse a planned graph when grouped browser dependencies and page-client entries match. After `ecopages start` restores the manifest, a request whose graph is not listed is an error that names the route and the missing entry; it is never built. Entry-specific plugins with a `bundleGroupKey` retain their own configuration inside the shared build, while entries with different bundle options keep separate requests. In-process Page caches also track reachable generated artifacts. On-demand page-cache path invalidation removes query and development runtime variants of the pathname and releases their build-input bindings. See [Build Layer](src/build/README.md), [Page Cache](src/page-cache/README.md), and [Asset Processing](src/assets/README.md).
40
41
 
41
42
  ### Bootstrap And Runtime Ownership
42
43
 
@@ -96,7 +97,7 @@ The manager/orchestration layer is core-owned, but framework-specific strategies
96
97
  - `RouteRegistry` gives exact and dynamic Pages priority over catch-alls, selects the most specific matching catch-all prefix, and shares segment matching and one-time URL decoding with API, explicit, and WebSocket routes.
97
98
  - Browser runtime package entries resolve from the application root with ESM import conditions, so framework-local packages cannot shadow app dependencies.
98
99
  - `createApp()` resolves config and CLI mode once, then returns the concrete `EcopagesApp`, which owns route registration and the Node HTTP server lifecycle.
99
- - One bundled adapter builds the app with Rolldown.
100
+ - One bundled adapter builds the app with Rolldown. Preserved server-module names stay flat and use a stable digest when deep package-store paths need shortening.
100
101
 
101
102
  ## Source Layering
102
103
 
@@ -119,18 +120,18 @@ Use this package README as the top-level map, then drill into the focused subsys
119
120
 
120
121
  - `src/config/README.md`: config loading, assembly, and app-owned runtime/build state
121
122
  - `src/types/README.md`: public, internal, and per-app runtime contracts
122
- - `src/errors/README.md`, `src/global/README.md`, `src/utils/README.md`, and `src/client/README.md`: shared Foundation modules, including path containment, markup escaping, entity decoding, regex escaping, and SHA-256 content hashes (`contentHash` from `@ecopages/core/build`)
123
+ - `src/errors/README.md`, `src/global/README.md`, `src/utils/README.md`, and `src/client/README.md`: shared Foundation modules, including path containment, markup escaping, entity decoding, regex escaping, SHA-256 content hashes (`contentHash` from `@ecopages/core/build`), and production server-bundle context
123
124
  - `src/cache/README.md`: Build-layer module parse cache
124
125
  - `src/diagnostics/README.md`: per-app request-pipeline metrics and the startup trace
125
126
  - `src/plugins/README.md`: integration and processor authoring contracts
126
- - `src/build/README.md`: build adapter, app-scoped server module loading, shared `.server` browser import guard, development build coordination, standalone Node server packaging and its deploy layout
127
+ - `src/build/README.md`: build adapter, app-scoped server module loading, shared `.server` browser import guard, per-module production output for shared SSR dependencies, development build coordination, standalone Node server packaging and its deploy layout
127
128
  - `src/page-cache/README.md`: HTML cache strategies, ISR, and source-aware invalidation
128
129
  - `src/assets/README.md`: shared asset processing and browser build coordination
129
130
  - `src/validation/README.md`: request validation with Standard Schema
130
131
  - `src/html/README.md`: streaming HTML rewriting, per-render document contributions, source parsing, and escaped asset tags
131
132
  - `src/adapters/README.md`: Node HTTP host and shared adapter boundaries
132
133
  - `src/dev/README.md`: development invalidation, dev transform server, in-memory on-demand vendor bundles, and client delivery (including workspace-package `@fs` URLs)
133
- - `src/watchers/README.md`: recursive source subscriptions with bounded readiness and scheduled debounce batches, external build-input and linked-package watching, batched `applyDevFileChanges`, and restart invalidation
134
+ - `src/watchers/README.md`: recursive filesystem subscriptions with bounded readiness and scheduled debounce batches, external build-input and linked-package watching, batched `applyDevFileChanges`, and restart invalidation
134
135
  - `src/dev/invalidation/README.md`: file-change classification and dirty-marking for bounded watcher batches
135
136
  - `src/hmr/README.md`: HMR strategy, update-layer ownership, and build error presentation
136
137
  - `src/dev-toolbar/README.md`: toolbar enablement, custom clients, and build error event contract
@@ -295,18 +296,21 @@ export const GET = defineGet({
295
296
  });
296
297
  ```
297
298
 
298
- The file's rules (405 and `Allow`, load errors, `app.ts` routes on the same URL) are in the [Routing docs](https://ecopages.app/docs/core/routing#endpoint-files); the contracts are in `src/router/README.md` and `src/adapters/README.md`. A build of an app with an endpoint file checks each file's exports, then emits the server bundle (`dist/.server/`) even when nothing else registers a handler, so `ecopages start` serves it.
299
+ The file's rules (405 and `Allow`, load errors, `app.ts` routes on the same URL) are in the [Endpoint Files docs](https://ecopages.app/docs/server/endpoint-files); the contracts are in `src/router/README.md` and `src/adapters/README.md`. A build of an app with an endpoint file publishes the server bundle (`dist/server/`), emits server modules, then checks each file's exports, even when nothing else registers a handler, so `ecopages start` serves it.
299
300
 
300
301
  ### 6. Error pages
301
302
 
302
303
  Filesystem `src/pages/404.*` and `500.*` take precedence. For explicit-route apps, register views on the app:
303
304
 
304
305
  ```typescript
305
- app.notFound('./src/views/not-found.kita');
306
- app.serverError('./src/views/server-error.kita');
306
+ import NotFoundView from './src/views/not-found.kita';
307
+ import ServerErrorView from './src/views/server-error.kita';
308
+
309
+ app.notFound(NotFoundView);
310
+ app.serverError(ServerErrorView);
307
311
  ```
308
312
 
309
- String and URL view paths passed to `app.static()`, `app.notFound()`, and `app.serverError()` load through the server-module transpiler. Raw dynamic `import()` skips component-identity transforms. A full explicit view renders through the same route pipeline as a filesystem Page, including its layouts, default metadata, robots meta, and page client plan. Props passed to the render are available to the view's `metadata`.
313
+ Import a view and pass it to `ctx.render`, `ctx.renderPartial`, `app.static()`, or an error-page helper. An Integration-owned import becomes a view reference: development loads it through the app module loader so a save reloads without a restart, and production reads the module `ecopages build` wrote to `dist/server/`. A full explicit view renders through the same route pipeline as a filesystem Page, including its layouts, default metadata, robots meta, and page client plan. Props passed to the render are available to the view's `metadata`.
310
314
 
311
315
  When no custom page is configured, built-in HTML defaults are served instead.
312
316
 
@@ -370,6 +374,6 @@ Use `@ecopages/core/client` for browser navigation and client runtime helpers.
370
374
 
371
375
  ### Runtime-Loaded Entries
372
376
 
373
- `@ecopages/core/config/write-types` and `@ecopages/core/hmr/client/hmr-runtime` remain exported because Ecopages loads them by path at runtime. They are implementation entries, not general authoring surfaces.
377
+ `@ecopages/core/config/write-types`, `@ecopages/core/hmr/client/hmr-runtime`, and `@ecopages/core/view-reference` remain exported because Ecopages loads them by path at runtime. They are implementation entries, not general authoring surfaces. App authors import the view file, not this subpath.
374
378
 
375
379
  `@ecopages/core/errors` remains an alias for the root error exports.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/core",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Core package for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -21,13 +21,12 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@clack/prompts": "^1.7.0",
24
- "@ecopages/file-system": "0.4.0",
24
+ "@ecopages/file-system": "0.6.0",
25
25
  "@ecopages/logger": "^0.2.3",
26
26
  "@ecopages/scripts-injector": "^0.1.5",
27
27
  "@jridgewell/remapping": "^2.3.5",
28
28
  "@standard-schema/spec": "^1.1.0",
29
29
  "@standard-schema/utils": "^0.3.0",
30
- "chokidar": "^5.0.0",
31
30
  "magic-string": "^1.4.3",
32
31
  "oxc-parser": "^0.141.0",
33
32
  "oxc-resolver": "^11.24.2",
@@ -35,7 +34,7 @@
35
34
  "ws": "^8.20.1"
36
35
  },
37
36
  "peerDependencies": {
38
- "@ecopages/dev-toolbar": "0.4.0"
37
+ "@ecopages/dev-toolbar": "0.6.0"
39
38
  },
40
39
  "peerDependenciesMeta": {
41
40
  "@ecopages/dev-toolbar": {
@@ -101,6 +100,11 @@
101
100
  "types": "./src/errors/index.d.ts",
102
101
  "default": "./src/errors/index.js"
103
102
  },
103
+ "./view-reference": {
104
+ "import": "./src/build/server/view-reference.js",
105
+ "types": "./src/build/server/view-reference.d.ts",
106
+ "default": "./src/build/server/view-reference.js"
107
+ },
104
108
  "./create-app.ts": {
105
109
  "import": "./src/adapters/create-app.js",
106
110
  "types": "./src/adapters/create-app.d.ts",
@@ -152,6 +156,11 @@
152
156
  "./errors.ts": {
153
157
  "types": "./src/errors/index.d.ts",
154
158
  "default": "./src/errors/index.js"
159
+ },
160
+ "./view-reference.ts": {
161
+ "import": "./src/build/server/view-reference.js",
162
+ "types": "./src/build/server/view-reference.d.ts",
163
+ "default": "./src/build/server/view-reference.js"
155
164
  }
156
165
  },
157
166
  "types": "./src/index.d.ts"
@@ -1,16 +1,19 @@
1
1
  import { finalizeEcoPagesConfig } from '../config/assembly/finalize-config.js';
2
- import { loadEcoPagesConfig } from '../config/load-eco-config.js';
2
+ import { loadEcoPagesConfig, loadEcoPagesConfigFromServerBundle } from '../config/load-eco-config.js';
3
3
  import { parseCliArgs } from '../utils/parse-cli-args.js';
4
+ import { getProductionServerBundleDir } from '../utils/server-bundle-context.js';
4
5
  import { createNodeApp } from './node/create-app.js';
5
6
  export { EcopagesApp } from './node/create-app.js';
6
- async function resolveAppConfig(options) {
7
+ async function resolveAppConfig(options, serverBundleDir) {
7
8
  if (options.appConfig) {
8
9
  return options.appConfig;
9
10
  }
10
11
  if (options.userConfig) {
11
12
  return await finalizeEcoPagesConfig(options.userConfig);
12
13
  }
13
- return await loadEcoPagesConfig({ configFile: options.configFile });
14
+ return serverBundleDir
15
+ ? await loadEcoPagesConfigFromServerBundle({ configFile: options.configFile }, serverBundleDir)
16
+ : await loadEcoPagesConfig({ configFile: options.configFile });
14
17
  }
15
18
  /**
16
19
  * Creates and initializes an EcoPages application instance.
@@ -45,7 +48,8 @@ async function resolveAppConfig(options) {
45
48
  * ```
46
49
  */
47
50
  export async function createApp(options = {}) {
48
- const appConfig = await resolveAppConfig(options);
51
+ const serverBundleDir = getProductionServerBundleDir();
52
+ const appConfig = await resolveAppConfig(options, serverBundleDir);
49
53
  const cliArgs = parseCliArgs();
50
- return createNodeApp({ appConfig, serverOptions: options.serverOptions, cliArgs });
54
+ return createNodeApp({ appConfig, serverOptions: options.serverOptions, cliArgs, serverBundleDir });
51
55
  }
@@ -1,9 +1,10 @@
1
1
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
- import type { ApiHandler, ApiHandlerContext, ErrorHandler, MiddlewareContext, MiddlewareList, RouteGroupBuilder, RouteMethod, RouteOptions, RouteSchema, RouteHandlerContext, ViewLoader, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
2
+ import type { ApiHandler, ApiHandlerContext, ErrorHandler, MiddlewareContext, MiddlewareList, RouteGroupBuilder, RouteMethod, RouteOptions, RouteSchema, RouteHandlerContext, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
3
3
  import { type HttpErrorPageStatus } from '../../errors/http-error-page-contract.js';
4
4
  import type { ReturnParseCliArgs } from '../../utils/parse-cli-args.js';
5
5
  import { type RuntimeHost } from './runtime-host.js';
6
6
  import { NodeServerAdapter, type NodeServerAdapterParams, type NodeServerInstance } from './server-adapter.js';
7
+ import { type StaticViewInput } from '../../build/server/resolve-static-view.js';
7
8
  export interface AppStartInfo {
8
9
  origin: string;
9
10
  /**
@@ -21,6 +22,7 @@ export type EcopagesAppRuntimeOptions = {
21
22
  appConfig: EcoPagesAppConfig;
22
23
  serverOptions?: Record<string, unknown>;
23
24
  cliArgs: ReturnParseCliArgs;
25
+ serverBundleDir?: string;
24
26
  };
25
27
  /**
26
28
  * @remarks
@@ -39,6 +41,7 @@ export declare class EcopagesApp implements AsyncDisposable {
39
41
  private readonly appConfig;
40
42
  private readonly serverOptions;
41
43
  private readonly cliArgs;
44
+ private readonly requireCompleteDist;
42
45
  private readonly apiHandlers;
43
46
  private readonly staticRoutes;
44
47
  private errorPageLoaders;
@@ -90,36 +93,35 @@ export declare class EcopagesApp implements AsyncDisposable {
90
93
  * Register a view for static generation at build time.
91
94
  * The view must have staticPaths defined for dynamic routes.
92
95
  *
93
- * String and URL inputs load through the server-module transpiler so HMR and
94
- * component identity transforms remain active in development.
95
- *
96
96
  * @param path - URL path pattern (e.g., '/posts/:slug')
97
- * @param loader - A view loader function, source path, or URL for the eco.page view module
97
+ * @param view - An imported view, an `eco.page` component, or a view loader
98
98
  * @example
99
99
  * ```typescript
100
- * app.static('/login', './src/views/login.kita')
101
- * app.static('/posts/:slug', './src/views/post-view.kita')
100
+ * import LoginView from './src/views/login.kita';
101
+ * import PostView from './src/views/post-view.kita';
102
+ *
103
+ * app.static('/login', LoginView)
104
+ * app.static('/posts/:slug', PostView)
102
105
  * ```
103
106
  */
104
- static<P>(path: string, loader: ViewLoader<P> | string | URL): this;
105
- private resolveViewLoader;
107
+ static<P>(path: string, view: StaticViewInput<P>): this;
106
108
  /**
107
109
  * Registers a semantic HTML error page used when no filesystem `pages/{status}.*`
108
110
  * file exists.
109
111
  */
110
- errorPage(status: HttpErrorPageStatus, loader: ViewLoader<ErrorPageTemplateProps> | string | URL): this;
111
- badRequest(loader: ViewLoader<ErrorPageTemplateProps> | string | URL): this;
112
- unauthorized(loader: ViewLoader<ErrorPageTemplateProps> | string | URL): this;
113
- forbidden(loader: ViewLoader<ErrorPageTemplateProps> | string | URL): this;
112
+ errorPage(status: HttpErrorPageStatus, view: StaticViewInput<ErrorPageTemplateProps>): this;
113
+ badRequest(view: StaticViewInput<ErrorPageTemplateProps>): this;
114
+ unauthorized(view: StaticViewInput<ErrorPageTemplateProps>): this;
115
+ forbidden(view: StaticViewInput<ErrorPageTemplateProps>): this;
114
116
  /**
115
117
  * Registers the not-found page used when no filesystem `pages/404.*` file exists.
116
118
  */
117
- notFound(loader: ViewLoader<ErrorPageTemplateProps> | string | URL): this;
118
- conflict(loader: ViewLoader<ErrorPageTemplateProps> | string | URL): this;
119
+ notFound(view: StaticViewInput<ErrorPageTemplateProps>): this;
120
+ conflict(view: StaticViewInput<ErrorPageTemplateProps>): this;
119
121
  /**
120
122
  * Registers the server-error page used when no filesystem `pages/500.*` file exists.
121
123
  */
122
- serverError(loader: ViewLoader<ErrorPageTemplateProps> | string | URL): this;
124
+ serverError(view: StaticViewInput<ErrorPageTemplateProps>): this;
123
125
  getErrorPageLoaders(): ErrorPageLoaders;
124
126
  /**
125
127
  * Register a WebSocket handler for the given path pattern.
@@ -11,7 +11,7 @@ import { NodeRuntimeHost } from './runtime-host.js';
11
11
  import { NodeServerAdapter } from './server-adapter.js';
12
12
  import { resolveAppStartRoutes } from '../../utils/ecopages-route-info.js';
13
13
  import { requireAppRuntime } from '../../utils/app-runtime.js';
14
- import { createViewModuleLoader } from '../../build/server/view-module-loader.js';
14
+ import { resolveStaticView } from '../../build/server/resolve-static-view.js';
15
15
  import { invariant } from '../../utils/invariant.js';
16
16
  function formatRestartStopFailure(error) {
17
17
  if (error instanceof Error) {
@@ -36,6 +36,7 @@ export class EcopagesApp {
36
36
  appConfig;
37
37
  serverOptions;
38
38
  cliArgs;
39
+ requireCompleteDist;
39
40
  apiHandlers = [];
40
41
  staticRoutes = [];
41
42
  errorPageLoaders = {};
@@ -65,6 +66,7 @@ export class EcopagesApp {
65
66
  this.appConfig = options.appConfig;
66
67
  this.serverOptions = options.serverOptions || {};
67
68
  this.cliArgs = options.cliArgs;
69
+ this.requireCompleteDist = this.cliArgs.start && options.serverBundleDir !== undefined;
68
70
  this.runtimeHost = dependencies.runtimeHost;
69
71
  this.createServerAdapter =
70
72
  dependencies.createServerAdapter ?? (async (params) => new NodeServerAdapter(params));
@@ -147,60 +149,53 @@ export class EcopagesApp {
147
149
  * Register a view for static generation at build time.
148
150
  * The view must have staticPaths defined for dynamic routes.
149
151
  *
150
- * String and URL inputs load through the server-module transpiler so HMR and
151
- * component identity transforms remain active in development.
152
- *
153
152
  * @param path - URL path pattern (e.g., '/posts/:slug')
154
- * @param loader - A view loader function, source path, or URL for the eco.page view module
153
+ * @param view - An imported view, an `eco.page` component, or a view loader
155
154
  * @example
156
155
  * ```typescript
157
- * app.static('/login', './src/views/login.kita')
158
- * app.static('/posts/:slug', './src/views/post-view.kita')
156
+ * import LoginView from './src/views/login.kita';
157
+ * import PostView from './src/views/post-view.kita';
158
+ *
159
+ * app.static('/login', LoginView)
160
+ * app.static('/posts/:slug', PostView)
159
161
  * ```
160
162
  */
161
- static(path, loader) {
162
- const resolvedLoader = this.resolveViewLoader(loader);
163
- this.staticRoutes.push({ path, loader: resolvedLoader });
163
+ static(path, view) {
164
+ this.staticRoutes.push({ path, loader: resolveStaticView(this.appConfig, view) });
164
165
  return this;
165
166
  }
166
- resolveViewLoader(loader) {
167
- return typeof loader === 'string' || loader instanceof URL
168
- ? createViewModuleLoader(this.appConfig, loader)
169
- : loader;
170
- }
171
167
  /**
172
168
  * Registers a semantic HTML error page used when no filesystem `pages/{status}.*`
173
169
  * file exists.
174
170
  */
175
- errorPage(status, loader) {
171
+ errorPage(status, view) {
176
172
  const kind = ERROR_PAGE_KIND_BY_STATUS[status];
177
- const resolvedLoader = this.resolveViewLoader(loader);
178
- this.errorPageLoaders = { ...this.errorPageLoaders, [kind]: resolvedLoader };
173
+ this.errorPageLoaders = { ...this.errorPageLoaders, [kind]: resolveStaticView(this.appConfig, view) };
179
174
  return this;
180
175
  }
181
- badRequest(loader) {
182
- return this.errorPage(400, loader);
176
+ badRequest(view) {
177
+ return this.errorPage(400, view);
183
178
  }
184
- unauthorized(loader) {
185
- return this.errorPage(401, loader);
179
+ unauthorized(view) {
180
+ return this.errorPage(401, view);
186
181
  }
187
- forbidden(loader) {
188
- return this.errorPage(403, loader);
182
+ forbidden(view) {
183
+ return this.errorPage(403, view);
189
184
  }
190
185
  /**
191
186
  * Registers the not-found page used when no filesystem `pages/404.*` file exists.
192
187
  */
193
- notFound(loader) {
194
- return this.errorPage(404, loader);
188
+ notFound(view) {
189
+ return this.errorPage(404, view);
195
190
  }
196
- conflict(loader) {
197
- return this.errorPage(409, loader);
191
+ conflict(view) {
192
+ return this.errorPage(409, view);
198
193
  }
199
194
  /**
200
195
  * Registers the server-error page used when no filesystem `pages/500.*` file exists.
201
196
  */
202
- serverError(loader) {
203
- return this.errorPage(500, loader);
197
+ serverError(view) {
198
+ return this.errorPage(500, view);
204
199
  }
205
200
  getErrorPageLoaders() {
206
201
  return this.errorPageLoaders;
@@ -306,6 +301,7 @@ export class EcopagesApp {
306
301
  options: { watch: binding.watch },
307
302
  serveOptions: binding.serveOptions,
308
303
  runtimeAssetSetup: this.resolveRuntimeAssetSetup(),
304
+ requireCompleteDist: this.requireCompleteDist,
309
305
  allowPortFallback: binding.allowPortFallback,
310
306
  onDevelopmentRestart: this.createDevelopmentRestartHandler(),
311
307
  });
@@ -25,12 +25,18 @@ export interface NodeServerAdapterParams {
25
25
  * When Processors and Integrations set up.
26
26
  *
27
27
  * @remarks
28
- * `start` sets Processors up before routes are read and activates Integrations before a network server handles
29
- * requests. Request-only `app.fetch()` activates only the Integrations used by that request. `export` empties
30
- * `dist/` first and prepares the export runtime; `none` leaves runtime assets alone for a preview that serves an
31
- * earlier export.
28
+ * `start` sets Processors up before routes are read, except production `ecopages start` with the unified
29
+ * graph, which restores from `dist/server/` and does not call Processor `setup()`. It activates Integrations
30
+ * before a network server handles requests. Request-only `app.fetch()` activates only the Integrations used by
31
+ * that request. `export` empties `dist/` first and prepares the export runtime; `none` leaves runtime assets
32
+ * alone for a preview that serves an earlier export.
32
33
  */
33
34
  runtimeAssetSetup?: 'start' | 'export' | 'none';
35
+ /**
36
+ * When true, production `start` refuses to run unless `dist/` is a complete
37
+ * export. `ecopages start` sets this; in-process `app.fetch()` tests do not.
38
+ */
39
+ requireCompleteDist?: boolean;
34
40
  allowPortFallback?: boolean;
35
41
  onDevelopmentRestart?: (changedFile: string) => Promise<void>;
36
42
  }
@@ -68,6 +74,7 @@ export declare class NodeServerAdapter {
68
74
  private staticBuilder;
69
75
  private devSession;
70
76
  private readonly runtimeAssetSetup;
77
+ private readonly requireCompleteDist;
71
78
  private readonly allowPortFallback;
72
79
  private readonly onDevelopmentRestart?;
73
80
  private readonly runtimeHost;
@@ -90,16 +97,26 @@ export declare class NodeServerAdapter {
90
97
  * Order is intentional:
91
98
  * 1. **Loaders** are registered first so processors and integrations can
92
99
  * reference loader-provided file types in their own plugins.
93
- * 2. **Public dir** is copied before any build so static assets are in `distDir`
94
- * before the first request arrives.
100
+ * 2. **Public dir** is copied into the client output before any request arrives. Serve-only
101
+ * preview (`none`) and production start from a complete output leave it untouched.
95
102
  * 3. **Processors** are set up after the public dir is in place so they can
96
- * safely reference dist-relative paths. An export (`build`, `preview`)
97
- * empties `dist/` first. Integrations activate at the runtime boundary that
98
- * uses them.
103
+ * safely reference output-relative paths. Serve-only preview skips both; production
104
+ * start from a complete output restores them from the emitted server-modules map.
105
+ * An export (`build`, `preview`) empties the configured output directory first. Integrations
106
+ * activate at the runtime boundary that uses them.
99
107
  * 4. **Router** is initialised last because it may depend on files written by
100
108
  * processors during their `setup()` calls, and in build mode it imports Pages.
101
109
  */
102
110
  initialize(): Promise<void>;
111
+ /**
112
+ * True for production `ecopages start`, which serves only what `ecopages build` wrote.
113
+ *
114
+ * @remarks
115
+ * Such a start checks that `dist/` is complete, restores Processors from the emitted
116
+ * server-modules map instead of calling `setup()`, and leaves `dist/` untouched: the build
117
+ * already copied the public directory, and the deploy may hold no sources.
118
+ */
119
+ private startsFromCompleteDist;
103
120
  private initializeResources;
104
121
  getServerOptions(): NodeServeAdapterServerOptions;
105
122
  applyBoundPort(input: {
@@ -6,6 +6,7 @@ import { appLogger } from '../../global/app-logger.js';
6
6
  import { attachNodeHttpWebSocketUpgrades } from '../shared/ws/node-http-websocket-upgrades.js';
7
7
  import { StaticSiteGenerator } from '../../static-site-generator/static-site-generator.js';
8
8
  import { ServerRequestPipeline } from '../shared/runtime/server-request-pipeline.js';
9
+ import { runWithBuildInputIndex } from '../../build/cache/build-input-dependency-index.js';
9
10
  import { ServerStaticBuilder } from '../shared/runtime/server-static-builder.js';
10
11
  import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from '../../constants.js';
11
12
  import { disposeDevResources, prepareRuntimePublicDir } from '../shared/runtime/runtime-server-lifecycle.js';
@@ -14,6 +15,9 @@ import { bindRuntimeServer } from '../shared/runtime/bind-runtime-server.js';
14
15
  import { serveDistFile } from '../shared/http/dist-file-handler.js';
15
16
  import { DevSession } from './dev-session.js';
16
17
  import { prebuildProductionPageBrowserGraphsFromManifest } from '../../static-site-generator/production-page-browser-graph-prebuild.js';
18
+ import { assertProductionDistComplete } from '../../build/production-dist-complete.js';
19
+ import { requireProductionServerModules } from '../../build/server/server-modules-manifest.js';
20
+ import { isProductionRuntime } from '../../env.js';
17
21
  /**
18
22
  * Node.js HTTP server adapter for the Ecopages runtime.
19
23
  *
@@ -48,6 +52,7 @@ export class NodeServerAdapter {
48
52
  staticBuilder;
49
53
  devSession;
50
54
  runtimeAssetSetup;
55
+ requireCompleteDist;
51
56
  allowPortFallback;
52
57
  onDevelopmentRestart;
53
58
  runtimeHost;
@@ -77,8 +82,12 @@ export class NodeServerAdapter {
77
82
  appConfig: this.appConfig,
78
83
  runtime: this.runtime,
79
84
  watch: this.options.watch,
85
+ runInRequestBuildScope: this.options.watch
86
+ ? (operation) => this.runtime.buildQueue.withRequestScope(() => runWithBuildInputIndex(this.runtime.buildInputIndex, operation))
87
+ : undefined,
80
88
  });
81
89
  this.runtimeAssetSetup = options.runtimeAssetSetup ?? 'start';
90
+ this.requireCompleteDist = options.requireCompleteDist === true;
82
91
  this.allowPortFallback = options.allowPortFallback !== false;
83
92
  this.onDevelopmentRestart = options.onDevelopmentRestart;
84
93
  this.apiHandlers = options.apiHandlers || [];
@@ -94,12 +103,13 @@ export class NodeServerAdapter {
94
103
  * Order is intentional:
95
104
  * 1. **Loaders** are registered first so processors and integrations can
96
105
  * reference loader-provided file types in their own plugins.
97
- * 2. **Public dir** is copied before any build so static assets are in `distDir`
98
- * before the first request arrives.
106
+ * 2. **Public dir** is copied into the client output before any request arrives. Serve-only
107
+ * preview (`none`) and production start from a complete output leave it untouched.
99
108
  * 3. **Processors** are set up after the public dir is in place so they can
100
- * safely reference dist-relative paths. An export (`build`, `preview`)
101
- * empties `dist/` first. Integrations activate at the runtime boundary that
102
- * uses them.
109
+ * safely reference output-relative paths. Serve-only preview skips both; production
110
+ * start from a complete output restores them from the emitted server-modules map.
111
+ * An export (`build`, `preview`) empties the configured output directory first. Integrations
112
+ * activate at the runtime boundary that uses them.
103
113
  * 4. **Router** is initialised last because it may depend on files written by
104
114
  * processors during their `setup()` calls, and in build mode it imports Pages.
105
115
  */
@@ -126,8 +136,20 @@ export class NodeServerAdapter {
126
136
  });
127
137
  return this.ready;
128
138
  }
139
+ /**
140
+ * True for production `ecopages start`, which serves only what `ecopages build` wrote.
141
+ *
142
+ * @remarks
143
+ * Such a start checks that `dist/` is complete, restores Processors from the emitted
144
+ * server-modules map instead of calling `setup()`, and leaves `dist/` untouched: the build
145
+ * already copied the public directory, and the deploy may hold no sources.
146
+ */
147
+ startsFromCompleteDist() {
148
+ return this.runtimeAssetSetup === 'start' && this.requireCompleteDist && isProductionRuntime();
149
+ }
129
150
  async initializeResources() {
130
- if (this.runtimeAssetSetup !== 'export') {
151
+ const fromCompleteDist = this.startsFromCompleteDist();
152
+ if (this.runtimeAssetSetup === 'start' && !fromCompleteDist) {
131
153
  prepareRuntimePublicDir(this.appConfig);
132
154
  }
133
155
  this.staticSiteGenerator = new StaticSiteGenerator({ appConfig: this.appConfig });
@@ -142,8 +164,13 @@ export class NodeServerAdapter {
142
164
  await this.staticBuilder.prepareExport();
143
165
  }
144
166
  else if (this.runtimeAssetSetup === 'start') {
167
+ if (fromCompleteDist) {
168
+ assertProductionDistComplete(this.appConfig.rootDir, this.appConfig.distDir);
169
+ requireProductionServerModules(this.appConfig);
170
+ }
145
171
  await setupAppRuntimePlugins({
146
172
  appConfig: this.appConfig,
173
+ skipProcessorSetup: fromCompleteDist,
147
174
  });
148
175
  }
149
176
  await this.requestPipeline.initializeRouteHandling({
@@ -187,9 +214,9 @@ export class NodeServerAdapter {
187
214
  */
188
215
  async servePreviewOnly() {
189
216
  await this.initialize();
190
- const distPath = path.join(this.appConfig.rootDir, this.appConfig.distDir);
217
+ const distPath = this.appConfig.absolutePaths.distDir;
191
218
  if (!fileSystem.exists(distPath)) {
192
- throw new Error(`Cannot serve preview without building first: dist directory "${this.appConfig.distDir}" not found in "${this.appConfig.rootDir}".`);
219
+ throw new Error(`Cannot serve preview without building first: client output directory "${path.relative(this.appConfig.rootDir, distPath)}" not found in "${this.appConfig.rootDir}".`);
193
220
  }
194
221
  return this.startPreviewServer();
195
222
  }
@@ -370,6 +397,9 @@ export class NodeServerAdapter {
370
397
  else {
371
398
  if (this.runtimeAssetSetup === 'start') {
372
399
  await setupAppRuntimeIntegrations({ appConfig: this.appConfig });
400
+ if (this.startsFromCompleteDist()) {
401
+ requireProductionServerModules(this.appConfig);
402
+ }
373
403
  const { routeRendererFactory } = this.requestPipeline.getStaticBuildContext();
374
404
  await prebuildProductionPageBrowserGraphsFromManifest(this.appConfig, routeRendererFactory);
375
405
  }
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import { getServerModuleBuildCacheOutdir } from '../../../build/server/route-module-build-cache-registry.js';
2
3
  import { fileURLToPath } from 'node:url';
3
4
  import { HMR_RUNTIME_SCRIPT_URL, resolveHmrRuntimeWorkDir } from '../../../hmr/hmr-runtime-paths.js';
4
5
  import { bundleDevClientRuntime, injectDevClientRuntimes, readDevClientRuntime, } from '../../../hmr/dev-client-runtime.js';
@@ -15,7 +16,7 @@ import { appLogger } from '../../../global/app-logger.js';
15
16
  import { DevTransformEntrypointRegistry } from './dev-transform-entrypoint-registry.js';
16
17
  import { BrowserBundleService } from '../../../assets/browser-bundle.service.js';
17
18
  import { requireAppRuntime } from '../../../utils/app-runtime.js';
18
- import { resolveInternalExecutionDir, resolveInternalWorkDir } from '../../../utils/resolve-work-dir.js';
19
+ import { resolveInternalWorkDir } from '../../../utils/resolve-work-dir.js';
19
20
  import { DevTransformServer } from '../../../dev/transform-server/dev-transform-server.js';
20
21
  export class HmrManager {
21
22
  appConfig;
@@ -348,7 +349,7 @@ export class HmrManager {
348
349
  getEntrypointDependencyGraph: () => this.entrypointDependencyGraph,
349
350
  importServerModule: async (filePath) => await requireAppRuntime(this.appConfig).moduleLoader.importModule({
350
351
  filePath,
351
- outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
352
+ outdir: getServerModuleBuildCacheOutdir(this.appConfig),
352
353
  externalPackages: true,
353
354
  }),
354
355
  };
@@ -85,8 +85,8 @@ export class ApiRequestPipeline {
85
85
  appLogger.error('[ecopages] Error in custom error handler', handlerError);
86
86
  }
87
87
  }
88
- if (error instanceof HttpError)
89
- return error.toResponse();
88
+ if (HttpError.isHttpError(error))
89
+ return HttpError.responseFor(error);
90
90
  appLogger.error('[ecopages] Error handling request', error);
91
91
  return new Response('Internal Server Error', { status: 500 });
92
92
  }