@ecopages/core 0.2.0-rc.10 → 0.2.0-rc.13

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 (161) hide show
  1. package/README.md +0 -9
  2. package/package.json +3 -152
  3. package/src/adapters/README.md +8 -2
  4. package/src/adapters/abstract/application-adapter.d.ts +6 -32
  5. package/src/adapters/abstract/application-adapter.js +6 -45
  6. package/src/adapters/abstract/ws-pattern-matcher.d.ts +0 -5
  7. package/src/adapters/abstract/ws-pattern-matcher.js +0 -9
  8. package/src/adapters/bun/create-app.d.ts +8 -12
  9. package/src/adapters/bun/create-app.js +13 -55
  10. package/src/adapters/bun/hmr-manager.d.ts +0 -1
  11. package/src/adapters/bun/hmr-manager.js +2 -4
  12. package/src/adapters/bun/server-adapter.d.ts +9 -19
  13. package/src/adapters/bun/server-adapter.js +19 -66
  14. package/src/adapters/bun/static-preview-host.d.ts +1 -0
  15. package/src/adapters/bun/static-preview-host.js +1 -1
  16. package/src/adapters/create-app.d.ts +1 -1
  17. package/src/adapters/create-app.js +2 -1
  18. package/src/adapters/node/create-app.d.ts +4 -8
  19. package/src/adapters/node/create-app.js +7 -12
  20. package/src/adapters/node/runtime-host.d.ts +10 -10
  21. package/src/adapters/node/runtime-host.js +4 -4
  22. package/src/adapters/node/server-adapter-dependencies.d.ts +2 -10
  23. package/src/adapters/node/server-adapter-dependencies.js +8 -13
  24. package/src/adapters/node/server-adapter.d.ts +25 -31
  25. package/src/adapters/node/server-adapter.js +43 -64
  26. package/src/adapters/shared/hmr/shared-hmr-manager.d.ts +0 -4
  27. package/src/adapters/shared/hmr/shared-hmr-manager.js +0 -12
  28. package/src/adapters/shared/http/api-request-pipeline.d.ts +27 -1
  29. package/src/adapters/shared/http/api-request-pipeline.js +31 -16
  30. package/src/adapters/shared/http/fs-server-response-factory.d.ts +0 -1
  31. package/src/adapters/shared/http/fs-server-response-factory.js +0 -3
  32. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.d.ts +1 -3
  33. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.js +1 -4
  34. package/src/adapters/shared/runtime/runtime-app-bootstrap.d.ts +0 -10
  35. package/src/adapters/shared/runtime/runtime-app-bootstrap.js +0 -7
  36. package/src/adapters/shared/runtime/runtime-host.d.ts +5 -2
  37. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +1 -1
  38. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +1 -1
  39. package/src/adapters/shared/runtime/server-adapter.d.ts +13 -0
  40. package/src/adapters/shared/runtime/server-adapter.js +22 -0
  41. package/src/adapters/shared/ws/node-http-websocket-upgrades.d.ts +9 -1
  42. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +8 -2
  43. package/src/build/README.md +5 -6
  44. package/src/build/cache/cache-constants.d.ts +0 -2
  45. package/src/build/cache/cache-constants.js +0 -2
  46. package/src/build/cache/cache-keys.d.ts +0 -2
  47. package/src/build/cache/cache-keys.js +0 -2
  48. package/src/build/cache/output-imports.d.ts +35 -0
  49. package/src/build/cache/output-imports.js +87 -0
  50. package/src/build/cache/pages-unified-graph-build.d.ts +6 -1
  51. package/src/build/cache/pages-unified-graph-build.js +49 -18
  52. package/src/build/cache/production-build-cache.d.ts +2 -2
  53. package/src/build/cache/production-build-cache.js +2 -2
  54. package/src/build/cache/server-entry-build-cache.d.ts +1 -2
  55. package/src/build/cache/server-entry-build-cache.js +4 -5
  56. package/src/build/contracts/build-contracts.d.ts +1 -13
  57. package/src/build/rolldown/runtime-build-output-normalizer.js +3 -6
  58. package/src/build/runtime/build-request-identity.d.ts +2 -6
  59. package/src/build/runtime/build-request-identity.js +2 -8
  60. package/src/build/runtime/deduping-build-executor.d.ts +0 -1
  61. package/src/build/runtime/deduping-build-executor.js +0 -1
  62. package/src/cache/index.d.ts +1 -1
  63. package/src/cache/index.js +1 -1
  64. package/src/cache/module-parse-cache.d.ts +2 -29
  65. package/src/cache/module-parse-cache.js +6 -39
  66. package/src/config/README.md +3 -3
  67. package/src/config/apply-user-config.d.ts +3 -1
  68. package/src/config/apply-user-config.js +3 -2
  69. package/src/config/config-builder.d.ts +1 -0
  70. package/src/config/config-builder.js +2 -2
  71. package/src/config/constants.d.ts +0 -4
  72. package/src/config/constants.js +0 -4
  73. package/src/config/index.d.ts +1 -1
  74. package/src/config/index.js +1 -1
  75. package/src/config/load-eco-config.d.ts +1 -1
  76. package/src/config/load-eco-config.js +18 -11
  77. package/src/config/resolve-eco-config-path.d.ts +9 -0
  78. package/src/config/resolve-eco-config-path.js +11 -0
  79. package/src/config/server-config-bundle.js +2 -2
  80. package/src/config/user-config-types.d.ts +9 -3
  81. package/src/dev/host-runtime.d.ts +0 -1
  82. package/src/dev/host-runtime.js +0 -3
  83. package/src/dev/sc-server.d.ts +4 -1
  84. package/src/dev/sc-server.js +11 -20
  85. package/src/dev/transform-server/dev-transform-import-rewriter.js +2 -2
  86. package/src/hmr/hmr-file-change-prep.d.ts +0 -1
  87. package/src/hmr/hmr-file-change-prep.js +2 -5
  88. package/src/hmr/hmr-strategy.d.ts +3 -8
  89. package/src/hmr/hmr-strategy.js +3 -8
  90. package/src/index.browser.d.ts +1 -2
  91. package/src/index.browser.js +1 -2
  92. package/src/index.d.ts +5 -6
  93. package/src/index.js +5 -6
  94. package/src/islands/island-host.d.ts +0 -9
  95. package/src/islands/island-host.js +1 -13
  96. package/src/plugins/component-import-discovery.js +2 -2
  97. package/src/plugins/eco-component-meta-plugin.js +5 -5
  98. package/src/plugins/integration-plugin.d.ts +0 -1
  99. package/src/plugins/integration-plugin.js +0 -4
  100. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -4
  101. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +25 -24
  102. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +18 -20
  103. package/src/route-renderer/orchestration/integration-renderer.d.ts +24 -7
  104. package/src/route-renderer/orchestration/integration-renderer.js +44 -33
  105. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +1 -1
  106. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -1
  107. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +1 -1
  108. package/src/services/README.md +1 -1
  109. package/src/services/assets/browser-bundle.service.d.ts +1 -6
  110. package/src/services/error-pages/default-error-pages.d.ts +1 -6
  111. package/src/services/error-pages/default-error-pages.js +0 -8
  112. package/src/services/html/html-rewriter.d.ts +77 -0
  113. package/src/services/html/html-rewriter.js +751 -0
  114. package/src/services/html/html-rewriter.parity.test.bun.d.ts +1 -0
  115. package/src/services/html/html-rewriter.parity.test.bun.js +74 -0
  116. package/src/services/html/html-transformer.service.d.ts +29 -42
  117. package/src/services/html/html-transformer.service.js +85 -157
  118. package/src/services/invalidation/development-invalidation.service.d.ts +2 -19
  119. package/src/services/invalidation/development-invalidation.service.js +1 -39
  120. package/src/services/module-loading/README.md +1 -1
  121. package/src/services/module-loading/app-module-loader.service.d.ts +0 -2
  122. package/src/services/module-loading/app-server-module-transpiler.service.d.ts +1 -1
  123. package/src/services/module-loading/app-server-module-transpiler.service.js +0 -10
  124. package/src/services/module-loading/collection-server-module-build.service.d.ts +0 -1
  125. package/src/services/module-loading/collection-server-module-build.service.js +0 -3
  126. package/src/services/module-loading/host-module-loader-registry.d.ts +0 -1
  127. package/src/services/module-loading/host-module-loader-registry.js +0 -3
  128. package/src/services/module-loading/route-module-build-cache-registry.d.ts +0 -4
  129. package/src/services/module-loading/route-module-build-cache-registry.js +0 -4
  130. package/src/services/module-loading/route-module-build-cache.store.d.ts +3 -0
  131. package/src/services/module-loading/route-module-build-cache.store.js +20 -5
  132. package/src/services/module-loading/route-module-build-manifest.d.ts +12 -1
  133. package/src/services/module-loading/route-module-build-manifest.js +7 -3
  134. package/src/services/module-loading/route-module-dependency-hasher.d.ts +3 -2
  135. package/src/services/module-loading/server-module-transpiler.service.d.ts +1 -15
  136. package/src/services/module-loading/server-module-transpiler.service.js +0 -24
  137. package/src/services/runtime-state/entrypoint-dependency-graph.service.js +0 -12
  138. package/src/services/runtime-state/server-invalidation-state.service.d.ts +4 -2
  139. package/src/services/runtime-state/server-invalidation-state.service.js +7 -14
  140. package/src/types/internal-types.d.ts +0 -38
  141. package/src/types/public-types.d.ts +0 -112
  142. package/src/watchers/project-watcher.d.ts +0 -15
  143. package/src/watchers/project-watcher.js +1 -27
  144. package/src/watchers/project-watcher.test-helpers.d.ts +10 -1
  145. package/src/watchers/project-watcher.test-helpers.js +12 -0
  146. package/src/adapters/abstract/router-adapter.d.ts +0 -26
  147. package/src/adapters/abstract/router-adapter.js +0 -13
  148. package/src/adapters/bun/index.d.ts +0 -2
  149. package/src/adapters/bun/index.js +0 -2
  150. package/src/adapters/index.d.ts +0 -2
  151. package/src/adapters/index.js +0 -2
  152. package/src/eco/eco.utils.d.ts +0 -1
  153. package/src/eco/eco.utils.js +0 -1
  154. package/src/services/cache/index.d.ts +0 -9
  155. package/src/services/cache/index.js +0 -8
  156. package/src/services/html/html-rewriter-provider.service.d.ts +0 -40
  157. package/src/services/html/html-rewriter-provider.service.js +0 -68
  158. package/src/services/module-loading/route-module-build-cache.d.ts +0 -4
  159. package/src/services/module-loading/route-module-build-cache.js +0 -3
  160. package/src/services/runtime-state/dev-graph.service.d.ts +0 -118
  161. package/src/services/runtime-state/dev-graph.service.js +0 -170
@@ -82,6 +82,19 @@ export declare abstract class SharedServerAdapter<TOptions extends ServerAdapter
82
82
  private tryHandleSharedHmrRequest;
83
83
  private injectSharedHmrHtmlResponse;
84
84
  private tryHandleSharedApiRequest;
85
+ /**
86
+ * Recognises a runtime-specific client disconnect so it answers 499.
87
+ *
88
+ * @remarks
89
+ * Only the Node adapter overrides it: its request bridge raises a dedicated
90
+ * error when the socket closes while the body is read.
91
+ */
92
+ protected isClientAbortError(_error: unknown): boolean;
93
+ /**
94
+ * Resolves an error that escaped {@link handleSharedRequest} with the same
95
+ * precedence as API handler errors, so `app.onError` sees it on every runtime.
96
+ */
97
+ protected handleUnexpectedRequestError(error: unknown, request: Request, context: SharedRequestContext): Promise<Response>;
85
98
  /**
86
99
  * Universally processes an incoming WinterCG Web standard Request.
87
100
  *
@@ -33,6 +33,7 @@ export class SharedServerAdapter extends AbstractServerAdapter {
33
33
  schemaValidator: this.schemaValidator,
34
34
  getRenderContext: () => this.getRenderContext(),
35
35
  getCacheService: () => this.getCacheService(),
36
+ isClientAbort: (error) => this.isClientAbortError(error),
36
37
  });
37
38
  hostOwnsDevClient = false;
38
39
  devStaticRoutePrewarmStarted = false;
@@ -261,6 +262,27 @@ export class SharedServerAdapter extends AbstractServerAdapter {
261
262
  async tryHandleSharedApiRequest(request, context) {
262
263
  return await this.apiRequestPipeline.tryHandle(request, context.apiHandlers, context.serverInstance, context.errorHandler);
263
264
  }
265
+ /**
266
+ * Recognises a runtime-specific client disconnect so it answers 499.
267
+ *
268
+ * @remarks
269
+ * Only the Node adapter overrides it: its request bridge raises a dedicated
270
+ * error when the socket closes while the body is read.
271
+ */
272
+ isClientAbortError(_error) {
273
+ return false;
274
+ }
275
+ /**
276
+ * Resolves an error that escaped {@link handleSharedRequest} with the same
277
+ * precedence as API handler errors, so `app.onError` sees it on every runtime.
278
+ */
279
+ async handleUnexpectedRequestError(error, request, context) {
280
+ return await this.apiRequestPipeline.handleError(error, {
281
+ request,
282
+ serverInstance: context.serverInstance,
283
+ errorHandler: context.errorHandler,
284
+ });
285
+ }
264
286
  /**
265
287
  * Universally processes an incoming WinterCG Web standard Request.
266
288
  *
@@ -12,10 +12,18 @@ export type AttachNodeHttpWebSocketUpgradesOptions = {
12
12
  passthroughUnmatched?: boolean;
13
13
  preflight?: NodeHttpWebSocketUpgradePreflight;
14
14
  };
15
+ /** Upgrade options a host passes when it attaches Ecopages to a server it shares. */
16
+ export type WebSocketUpgradeOptions = Pick<AttachNodeHttpWebSocketUpgradesOptions, 'passthroughUnmatched'>;
15
17
  /**
16
- * Wires Ecopages user WebSocket routes onto a Node HTTP server's `upgrade` event.
18
+ * Wires Ecopages WebSocket upgrades onto a Node HTTP server's `upgrade` event.
17
19
  *
18
20
  * Used by the Node adapter in standalone mode and by host integrations such as
19
21
  * the Vite plugin that embed Ecopages behind a foreign HTTP server.
22
+ *
23
+ * @remarks
24
+ * This is the single owner of the unmatched-upgrade policy: an upgrade claimed
25
+ * by `preflight` (for example `/_hmr`) or a user route is handled here, and
26
+ * anything else is destroyed unless `passthroughUnmatched` leaves it for other
27
+ * listeners on a shared server.
20
28
  */
21
29
  export declare function attachNodeHttpWebSocketUpgrades(server: NodeHttpServer, options: AttachNodeHttpWebSocketUpgradesOptions): void;
@@ -71,13 +71,19 @@ async function setupNodeWebSocketConnection(ws, wsMatch, req, runtimeOrigin, sea
71
71
  });
72
72
  }
73
73
  /**
74
- * Wires Ecopages user WebSocket routes onto a Node HTTP server's `upgrade` event.
74
+ * Wires Ecopages WebSocket upgrades onto a Node HTTP server's `upgrade` event.
75
75
  *
76
76
  * Used by the Node adapter in standalone mode and by host integrations such as
77
77
  * the Vite plugin that embed Ecopages behind a foreign HTTP server.
78
+ *
79
+ * @remarks
80
+ * This is the single owner of the unmatched-upgrade policy: an upgrade claimed
81
+ * by `preflight` (for example `/_hmr`) or a user route is handled here, and
82
+ * anything else is destroyed unless `passthroughUnmatched` leaves it for other
83
+ * listeners on a shared server.
78
84
  */
79
85
  export function attachNodeHttpWebSocketUpgrades(server, options) {
80
- if (options.websocketHandlers.size === 0) {
86
+ if (options.websocketHandlers.size === 0 && !options.preflight) {
81
87
  return;
82
88
  }
83
89
  if (attachedUpgradeServers.has(server)) {
@@ -63,6 +63,7 @@ build/
63
63
  - `cache/server-entry-build-cache.ts`: production server-entry bundle cache (`.eco/.server-entry/.build-cache.json` + `dist/.server/manifest.json`).
64
64
  - `server-bundle-publication.ts`: stages the server entry, emitted config, and deploy manifest together, then publishes the complete directory with rollback.
65
65
  - `cache/cache-constants.ts`: shared `.build-cache.json` filename for persisted production caches.
66
+ - `cache/output-imports.ts`: lists the local files reachable from a compiled module, including shared chunks, so a cached module is reused only while they exist.
66
67
  - `*.test.ts`: regression coverage colocated with each module.
67
68
 
68
69
  ## Default Flow
@@ -139,13 +140,9 @@ App-manifest plugins keep canonical registration order and cannot be silently re
139
140
 
140
141
  ## BuildOptions Caveats
141
142
 
142
- `BuildOptions` is modeled on the bundler's options shape. Most fields map cleanly. The exceptions:
143
+ `BuildOptions` is modeled on the bundler's options shape. Most fields map cleanly. The exception:
143
144
 
144
145
  - `splitting` — when `false` with a single entrypoint, maps to Rolldown `codeSplitting: false` so dynamic imports stay in one file. Multi-entrypoint builds ignore `splitting: false` because Rolldown cannot inline across multiple inputs.
145
- - `bundle` — accepted but ignored. The bundler always bundles.
146
- - `outbase` — accepted but ignored. The adapter derives the base from `options.root` directly.
147
-
148
- These fields are kept in the type so existing call-sites compile. The proper fix is a more focused `BuildOptions` schema in a follow-up.
149
146
 
150
147
  ## Dev / watch path
151
148
 
@@ -191,7 +188,9 @@ Production static exports compile all template pages in one Rolldown invocation
191
188
  | Graph manifest | `.eco/.server-pages-graph/.build-cache.json` |
192
189
  | Chunk outputs | `.eco/.server-modules/` (shared with per-route cache) |
193
190
 
194
- `StaticSiteGenerator` calls `ensurePagesUnifiedGraphBuilt()` before the export loop. `PageModuleImportService` imports prebuilt chunks via `importPagesUnifiedGraphModule()` and falls back to per-page Rolldown on miss. This is separate from production Page Browser Graph prebuild (`production-page-browser-graph-prebuild.ts`), which warms browser assets in `page-browser-graph-session`.
191
+ `StaticSiteGenerator` calls `ensurePagesUnifiedGraphBuilt()` before the export loop. `PageModuleImportService` imports prebuilt chunks via `importPagesUnifiedGraphModule()` and falls back to per-page Rolldown on miss.
192
+
193
+ A persisted graph is reused only when it matches the core package version, the build inputs and the build key, and every local file reachable from its outputs still exists. `importPagesUnifiedGraphModule()` applies the same check, because pages can be imported before the export loop runs. This is separate from production Page Browser Graph prebuild (`production-page-browser-graph-prebuild.ts`), which warms browser assets in `page-browser-graph-session`.
195
194
 
196
195
  `ECOPAGES_ROLLDOWN_BUILD_METRICS=1` enables `rolldown/rolldown-build-invocation-metrics.ts` counters used by bench and parity tests.
197
196
 
@@ -1,4 +1,2 @@
1
1
  /** Filename written beside persisted production build artifacts that store incremental metadata. */
2
2
  export declare const ROUTE_MODULE_BUILD_CACHE_FILENAME = ".build-cache.json";
3
- /** @deprecated Use {@link ROUTE_MODULE_BUILD_CACHE_FILENAME}; server-entry caches share the same filename. */
4
- export declare const SERVER_ENTRY_BUILD_CACHE_FILENAME = ".build-cache.json";
@@ -1,4 +1,2 @@
1
1
  /** Filename written beside persisted production build artifacts that store incremental metadata. */
2
2
  export const ROUTE_MODULE_BUILD_CACHE_FILENAME = '.build-cache.json';
3
- /** @deprecated Use {@link ROUTE_MODULE_BUILD_CACHE_FILENAME}; server-entry caches share the same filename. */
4
- export const SERVER_ENTRY_BUILD_CACHE_FILENAME = ROUTE_MODULE_BUILD_CACHE_FILENAME;
@@ -18,5 +18,3 @@ export declare function createSourceTransformCacheKey(sourceTransforms: BuildOpt
18
18
  * agree within one install; not stable across minifiers or renames.
19
19
  */
20
20
  export declare function hashFunctionIdentity(fn: (...args: never[]) => unknown): string;
21
- /** @deprecated Use {@link hashFunctionIdentity}. */
22
- export declare const hashPluginSetup: typeof hashFunctionIdentity;
@@ -67,5 +67,3 @@ export function hashFunctionIdentity(fn) {
67
67
  }
68
68
  return (hash >>> 0).toString(36);
69
69
  }
70
- /** @deprecated Use {@link hashFunctionIdentity}. */
71
- export const hashPluginSetup = hashFunctionIdentity;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Lists the local files a compiled module imports: relative, absolute and
3
+ * `file:` specifiers in static imports, re-exports and literal dynamic imports.
4
+ *
5
+ * @remarks
6
+ * {@link collectReachableLocalImports} follows these edges so persisted build
7
+ * caches can check that the shared chunks and generated modules a cached module
8
+ * loads (for example `.server-collections`) still exist. Uses `parseSync`
9
+ * directly rather than the shared parse cache, so large compiled bundles are not
10
+ * retained in memory.
11
+ */
12
+ export declare function collectLocalImports(code: string, modulePath: string): string[];
13
+ export type LocalImportFileAccess = {
14
+ exists: (filePath: string) => boolean;
15
+ readFile: (filePath: string) => string;
16
+ };
17
+ /**
18
+ * Lists every local file reachable from `modulePath` through local imports.
19
+ *
20
+ * @remarks
21
+ * {@link collectLocalImports} alone misses shared chunks that a page output only
22
+ * reaches through another chunk. Persisted caches record this full set and are
23
+ * reused only while every file in it exists. `modulePath` itself is omitted,
24
+ * because callers already check that the compiled output exists.
25
+ *
26
+ * A missing file is listed but not followed, so a cache recorded against it
27
+ * never validates.
28
+ *
29
+ * Pass one `directImportsCache` to every walk of a single build so shared chunks
30
+ * are read and parsed once instead of once per output.
31
+ */
32
+ export declare function collectReachableLocalImports(modulePath: string, options?: {
33
+ fileAccess?: LocalImportFileAccess;
34
+ directImportsCache?: Map<string, string[]>;
35
+ }): string[];
@@ -0,0 +1,87 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { fileSystem } from '@ecopages/file-system';
4
+ import { parseSync } from 'oxc-parser';
5
+ /**
6
+ * Lists the local files a compiled module imports: relative, absolute and
7
+ * `file:` specifiers in static imports, re-exports and literal dynamic imports.
8
+ *
9
+ * @remarks
10
+ * {@link collectReachableLocalImports} follows these edges so persisted build
11
+ * caches can check that the shared chunks and generated modules a cached module
12
+ * loads (for example `.server-collections`) still exist. Uses `parseSync`
13
+ * directly rather than the shared parse cache, so large compiled bundles are not
14
+ * retained in memory.
15
+ */
16
+ export function collectLocalImports(code, modulePath) {
17
+ const { module } = parseSync(modulePath, code, { lang: 'js', sourceType: 'module' });
18
+ const specifiers = [
19
+ ...module.staticImports.map((entry) => entry.moduleRequest.value),
20
+ ...module.staticExports.flatMap((entry) => entry.entries.map((exportEntry) => exportEntry.moduleRequest?.value)),
21
+ ...module.dynamicImports.map((entry) => readStringLiteral(code.slice(entry.moduleRequest.start, entry.moduleRequest.end))),
22
+ ];
23
+ const directory = path.dirname(modulePath);
24
+ const localImports = new Set();
25
+ for (const specifier of specifiers) {
26
+ const resolved = specifier ? resolveLocalSpecifier(specifier, directory) : undefined;
27
+ if (resolved)
28
+ localImports.add(resolved);
29
+ }
30
+ return [...localImports];
31
+ }
32
+ const defaultLocalImportFileAccess = {
33
+ exists: (filePath) => fileSystem.exists(filePath),
34
+ readFile: (filePath) => fileSystem.readFileSync(filePath),
35
+ };
36
+ /**
37
+ * Lists every local file reachable from `modulePath` through local imports.
38
+ *
39
+ * @remarks
40
+ * {@link collectLocalImports} alone misses shared chunks that a page output only
41
+ * reaches through another chunk. Persisted caches record this full set and are
42
+ * reused only while every file in it exists. `modulePath` itself is omitted,
43
+ * because callers already check that the compiled output exists.
44
+ *
45
+ * A missing file is listed but not followed, so a cache recorded against it
46
+ * never validates.
47
+ *
48
+ * Pass one `directImportsCache` to every walk of a single build so shared chunks
49
+ * are read and parsed once instead of once per output.
50
+ */
51
+ export function collectReachableLocalImports(modulePath, options = {}) {
52
+ const { fileAccess = defaultLocalImportFileAccess, directImportsCache = new Map() } = options;
53
+ const reachable = new Set();
54
+ const pending = [modulePath];
55
+ const visited = new Set();
56
+ while (pending.length > 0) {
57
+ const current = pending.pop();
58
+ if (!current || visited.has(current)) {
59
+ continue;
60
+ }
61
+ visited.add(current);
62
+ if (current !== modulePath) {
63
+ reachable.add(current);
64
+ }
65
+ if (current !== modulePath && !fileAccess.exists(current)) {
66
+ continue;
67
+ }
68
+ let directImports = directImportsCache.get(current);
69
+ if (!directImports) {
70
+ directImports = collectLocalImports(fileAccess.readFile(current), current);
71
+ directImportsCache.set(current, directImports);
72
+ }
73
+ pending.push(...directImports);
74
+ }
75
+ return [...reachable];
76
+ }
77
+ function resolveLocalSpecifier(specifier, directory) {
78
+ const bare = specifier.replace(/[?#].*$/, '');
79
+ if (bare.startsWith('file:'))
80
+ return fileURLToPath(bare);
81
+ if (bare.startsWith('.'))
82
+ return path.resolve(directory, bare);
83
+ return path.isAbsolute(bare) ? bare : undefined;
84
+ }
85
+ function readStringLiteral(source) {
86
+ return /^(['"`])([^'"`$]*)\1$/.exec(source.trim())?.[2];
87
+ }
@@ -9,11 +9,16 @@ import type { EcoPagesAppConfig } from '../../types/internal-types.js';
9
9
  export declare const PAGES_UNIFIED_GRAPH_CACHE_DIR = ".server-pages-graph";
10
10
  export declare const PAGES_UNIFIED_GRAPH_CACHE_FILENAME = ".build-cache.json";
11
11
  export interface PagesUnifiedGraphCacheManifest {
12
- invalidationVersion: string;
12
+ corePackageVersion: string;
13
13
  buildInputsFingerprint: string;
14
14
  buildKey: string;
15
15
  builtAt: number;
16
16
  outputs: Record<string, string>;
17
+ /**
18
+ * Local files reachable from the outputs through local imports, including
19
+ * shared chunks. The graph is reused only while all of them exist.
20
+ */
21
+ outputImports: string[];
17
22
  }
18
23
  export declare function isPagesUnifiedGraphEnabled(): boolean;
19
24
  /** True when the unified graph should build or serve prebuilt page modules. */
@@ -15,8 +15,9 @@ import { createServerBuildRequest, resolveServerAppBuildPlugins } from '../runti
15
15
  import { createBuildInputsFingerprint, hashAppConfigFile } from './build-input-fingerprint.js';
16
16
  import { isProductionCacheManifestCurrent, matchesProductionCacheBuildKey, matchesProductionCacheFingerprint, readProductionCacheManifest, writeProductionCacheManifest, } from './production-build-cache.js';
17
17
  import { getCorePackageVersion } from './cache-keys.js';
18
+ import { collectReachableLocalImports } from './output-imports.js';
18
19
  import { resolveInternalExecutionDir } from '../../utils/resolve-work-dir.js';
19
- import { getSharedRouteModuleBuildCache } from '../../services/module-loading/route-module-build-cache-registry.js';
20
+ import { getServerModuleBuildCacheOutdir, getSharedRouteModuleBuildCache, } from '../../services/module-loading/route-module-build-cache-registry.js';
20
21
  import { resolveRouteModuleDependencyPaths } from '../../services/module-loading/route-module-dependency-hasher.js';
21
22
  export const PAGES_UNIFIED_GRAPH_CACHE_DIR = '.server-pages-graph';
22
23
  export const PAGES_UNIFIED_GRAPH_CACHE_FILENAME = '.build-cache.json';
@@ -56,9 +57,14 @@ function createPagesUnifiedGraphBuildKey(appConfig, outdir) {
56
57
  'external-packages',
57
58
  ].join('::');
58
59
  }
60
+ /**
61
+ * @remarks
62
+ * Manifests without `outputImports` predate import validation and cannot show
63
+ * that their chunks still exist, so they are treated as absent.
64
+ */
59
65
  function readPagesUnifiedGraphManifest(appConfig) {
60
66
  const manifest = readProductionCacheManifest(getPagesUnifiedGraphCachePath(appConfig));
61
- if (!manifest?.outputs) {
67
+ if (!manifest?.outputs || !Array.isArray(manifest.outputImports)) {
62
68
  return undefined;
63
69
  }
64
70
  return manifest;
@@ -95,21 +101,39 @@ function resolveOutputForEntrypoint(entryPath, entryKey, buildResult) {
95
101
  }
96
102
  return undefined;
97
103
  }
104
+ /**
105
+ * Whether `manifest` was written by the current core version, build inputs and graph
106
+ * setup, and every file its outputs import still exists.
107
+ */
108
+ function isGraphManifestCurrent(manifest, appConfig, outdir) {
109
+ return (isProductionCacheManifestCurrent(manifest, getCorePackageVersion()) &&
110
+ matchesProductionCacheFingerprint(manifest, createBuildInputsFingerprint(appConfig)) &&
111
+ matchesProductionCacheBuildKey(manifest, createPagesUnifiedGraphBuildKey(appConfig, outdir)) &&
112
+ manifest.outputImports.every((filePath) => fileSystem.exists(filePath)));
113
+ }
98
114
  function isManifestValidForEntries(manifest, appConfig, outdir, entryPaths) {
99
- if (!isProductionCacheManifestCurrent(manifest, getCorePackageVersion())) {
100
- return false;
101
- }
102
- if (!matchesProductionCacheFingerprint(manifest, createBuildInputsFingerprint(appConfig))) {
103
- return false;
104
- }
105
- if (!matchesProductionCacheBuildKey(manifest, createPagesUnifiedGraphBuildKey(appConfig, outdir))) {
106
- return false;
107
- }
108
- return entryPaths.every((entryPath) => {
109
- const resolvedEntryPath = path.resolve(entryPath);
110
- const outputPath = manifest.outputs[resolvedEntryPath];
111
- return outputPath ? fileSystem.exists(outputPath) : false;
112
- });
115
+ return (isGraphManifestCurrent(manifest, appConfig, outdir) &&
116
+ entryPaths.every((entryPath) => {
117
+ const outputPath = manifest.outputs[path.resolve(entryPath)];
118
+ return outputPath ? fileSystem.exists(outputPath) : false;
119
+ }));
120
+ }
121
+ const importableGraphs = new WeakMap();
122
+ /**
123
+ * {@link isGraphManifestCurrent} for page imports, memoized per manifest write.
124
+ *
125
+ * @remarks
126
+ * Page modules can be imported before the static site generator calls
127
+ * {@link ensurePagesUnifiedGraphBuilt} (for example while collecting static
128
+ * paths), so the import path must not trust a manifest left by an older build.
129
+ */
130
+ function isGraphImportable(manifest, appConfig) {
131
+ const known = importableGraphs.get(appConfig);
132
+ if (known?.builtAt === manifest.builtAt)
133
+ return known.current;
134
+ const current = isGraphManifestCurrent(manifest, appConfig, getServerModuleBuildCacheOutdir(appConfig));
135
+ importableGraphs.set(appConfig, { builtAt: manifest.builtAt, current });
136
+ return current;
113
137
  }
114
138
  /**
115
139
  * Builds eligible static pages in one Rolldown invocation and seeds route-module disk cache.
@@ -155,6 +179,8 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
155
179
  throw new Error(`Pages unified graph build failed: ${details}`);
156
180
  }
157
181
  const outputs = {};
182
+ const outputImports = new Set();
183
+ const directImportsCache = new Map();
158
184
  for (const entryPath of eligibleEntryPaths) {
159
185
  const fileHash = fileSystem.hash(entryPath);
160
186
  const entryKey = entryKeysByPath.get(entryPath);
@@ -163,6 +189,9 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
163
189
  throw new Error(`Pages unified graph build produced no output for ${entryPath}`);
164
190
  }
165
191
  outputs[entryPath] = compiledOutput;
192
+ const compiledOutputImports = collectReachableLocalImports(compiledOutput, { directImportsCache });
193
+ for (const importPath of compiledOutputImports)
194
+ outputImports.add(importPath);
166
195
  routeModuleBuildCache.recordBuild({
167
196
  filePath: entryPath,
168
197
  rootDir: options.appConfig.rootDir,
@@ -172,14 +201,16 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
172
201
  dependencyModulePaths: resolveRouteModuleDependencyPaths(buildResult, entryPath, options.appConfig.rootDir),
173
202
  externalPackages: true,
174
203
  plugins,
204
+ outputImports: compiledOutputImports,
175
205
  });
176
206
  }
177
207
  const manifest = {
178
- invalidationVersion: getCorePackageVersion(),
208
+ corePackageVersion: getCorePackageVersion(),
179
209
  buildInputsFingerprint: createBuildInputsFingerprint(options.appConfig),
180
210
  buildKey: createPagesUnifiedGraphBuildKey(options.appConfig, outdir),
181
211
  builtAt: Date.now(),
182
212
  outputs,
213
+ outputImports: [...outputImports],
183
214
  };
184
215
  writePagesUnifiedGraphManifest(options.appConfig, manifest);
185
216
  appLogger.debug(`Built pages unified graph for ${eligibleEntryPaths.length} entries`);
@@ -187,7 +218,7 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
187
218
  }
188
219
  export async function importPagesUnifiedGraphModule(appConfig, filePath) {
189
220
  const manifest = readPagesUnifiedGraphManifest(appConfig);
190
- if (!manifest) {
221
+ if (!manifest || !isGraphImportable(manifest, appConfig)) {
191
222
  return undefined;
192
223
  }
193
224
  const resolvedFilePath = path.resolve(filePath);
@@ -3,7 +3,7 @@ import type { EcoPagesAppConfig } from '../../types/internal-types.js';
3
3
  * Shared manifest fields for persisted production build caches.
4
4
  */
5
5
  export interface ProductionCacheManifestBase {
6
- invalidationVersion?: string;
6
+ /** `getCorePackageVersion()` of the build that wrote the manifest. */
7
7
  corePackageVersion?: string;
8
8
  buildInputsFingerprint?: string;
9
9
  buildKey?: string;
@@ -16,6 +16,6 @@ export declare function getProductionBuildCacheManifestPaths(appConfig: EcoPages
16
16
  export declare function clearPersistedProductionBuildCacheManifests(appConfig: EcoPagesAppConfig): void;
17
17
  export declare function readProductionCacheManifest<T extends ProductionCacheManifestBase>(manifestPath: string): T | undefined;
18
18
  export declare function writeProductionCacheManifest(manifestPath: string, manifest: unknown): void;
19
- export declare function isProductionCacheManifestCurrent(manifest: ProductionCacheManifestBase | undefined, packageVersion: string): boolean;
19
+ export declare function isProductionCacheManifestCurrent(manifest: ProductionCacheManifestBase | undefined, corePackageVersion: string): boolean;
20
20
  export declare function matchesProductionCacheFingerprint(manifest: ProductionCacheManifestBase | undefined, buildInputsFingerprint: string): boolean;
21
21
  export declare function matchesProductionCacheBuildKey(manifest: ProductionCacheManifestBase | undefined, buildKey: string): boolean;
@@ -45,8 +45,8 @@ export function writeProductionCacheManifest(manifestPath, manifest) {
45
45
  fileSystem.ensureDir(path.dirname(manifestPath));
46
46
  fileSystem.write(manifestPath, `${JSON.stringify(manifest, null, '\t')}\n`);
47
47
  }
48
- export function isProductionCacheManifestCurrent(manifest, packageVersion) {
49
- return (manifest?.corePackageVersion ?? manifest?.invalidationVersion) === packageVersion;
48
+ export function isProductionCacheManifestCurrent(manifest, corePackageVersion) {
49
+ return manifest?.corePackageVersion === corePackageVersion;
50
50
  }
51
51
  export function matchesProductionCacheFingerprint(manifest, buildInputsFingerprint) {
52
52
  return manifest?.buildInputsFingerprint === buildInputsFingerprint;
@@ -1,6 +1,5 @@
1
1
  import type { BuildResult } from '../build-adapter.js';
2
2
  import type { EcoPagesAppConfig } from '../../types/internal-types.js';
3
- export { SERVER_ENTRY_BUILD_CACHE_FILENAME } from './cache-constants.js';
4
3
  export declare const SERVER_BUNDLE_MANIFEST_FILENAME = "manifest.json";
5
4
  export interface ServerBundleDeployManifest {
6
5
  serverEntry: string;
@@ -18,7 +17,7 @@ export interface ServerBundleDeployManifest {
18
17
  emittedConfigHash?: string;
19
18
  }
20
19
  export interface ServerEntryBuildCacheManifest {
21
- invalidationVersion: string;
20
+ corePackageVersion: string;
22
21
  entryPath: string;
23
22
  entryHash: string;
24
23
  configHash: string;
@@ -7,14 +7,13 @@ import { createPluginCacheKey, getCorePackageVersion } from './cache-keys.js';
7
7
  import { RouteModuleDependencyHasher, createRouteModuleDependencyHashes, } from '../../services/module-loading/route-module-dependency-hasher.js';
8
8
  import { resolveInternalExecutionDir } from '../../utils/resolve-work-dir.js';
9
9
  import { SERVER_BUNDLE_DIR, SERVER_BUNDLE_FILENAME } from '../../utils/resolve-entry-file.js';
10
- import { SERVER_ENTRY_BUILD_CACHE_FILENAME } from './cache-constants.js';
11
- export { SERVER_ENTRY_BUILD_CACHE_FILENAME } from './cache-constants.js';
10
+ import { ROUTE_MODULE_BUILD_CACHE_FILENAME } from './cache-constants.js';
12
11
  export const SERVER_BUNDLE_MANIFEST_FILENAME = 'manifest.json';
13
12
  function getServerEntryCacheDir(appConfig) {
14
13
  return path.join(resolveInternalExecutionDir(appConfig), '.server-entry');
15
14
  }
16
15
  function getServerEntryCacheManifestPath(appConfig) {
17
- return path.join(getServerEntryCacheDir(appConfig), SERVER_ENTRY_BUILD_CACHE_FILENAME);
16
+ return path.join(getServerEntryCacheDir(appConfig), ROUTE_MODULE_BUILD_CACHE_FILENAME);
18
17
  }
19
18
  function hashDependencyGraph(entryPath, dependencyGraph, hasher, rootDir) {
20
19
  if (!dependencyGraph) {
@@ -55,7 +54,7 @@ export function readServerEntryBuildCacheManifest(appConfig) {
55
54
  return readProductionCacheManifest(getServerEntryCacheManifestPath(appConfig));
56
55
  }
57
56
  function writeServerEntryBuildCacheManifest(appConfig, manifest) {
58
- writeProductionCacheManifest(path.join(getServerEntryCacheDir(appConfig), SERVER_ENTRY_BUILD_CACHE_FILENAME), manifest);
57
+ writeProductionCacheManifest(path.join(getServerEntryCacheDir(appConfig), ROUTE_MODULE_BUILD_CACHE_FILENAME), manifest);
59
58
  }
60
59
  function hashExistingFile(filePath) {
61
60
  return filePath && fileSystem.exists(filePath) ? fileSystem.hash(filePath) : undefined;
@@ -229,7 +228,7 @@ export function recordServerEntryBuildCache(options) {
229
228
  : {};
230
229
  const dependencyHashes = { ...appDependencyHashes, ...configDependencyHashes };
231
230
  const manifest = {
232
- invalidationVersion: getCorePackageVersion(),
231
+ corePackageVersion: getCorePackageVersion(),
233
232
  entryPath,
234
233
  entryHash,
235
234
  configHash,
@@ -34,21 +34,11 @@ export interface BuildResult {
34
34
  *
35
35
  * @remarks
36
36
  * Fields that the adapter can forward are honored. `splitting: false` disables
37
- * Rolldown code splitting for single-entrypoint builds. `bundle` and `outbase`
38
- * are accepted for call-site compatibility but ignored.
37
+ * Rolldown code splitting for single-entrypoint builds.
39
38
  */
40
39
  export interface BuildOptions {
41
40
  entrypoints: string[] | Record<string, string>;
42
41
  outdir?: string;
43
- /**
44
- * Base directory for `[dir]` placeholders in `naming`. Currently
45
- * the bundled adapter derives the base from `root` directly and
46
- * ignores this field.
47
- *
48
- * @deprecated Accepted for call-site compatibility only. Use record-form
49
- * `entrypoints` keys to preserve directory structure.
50
- */
51
- outbase?: string;
52
42
  naming?: string;
53
43
  conditions?: string[];
54
44
  define?: Record<string, string>;
@@ -60,8 +50,6 @@ export interface BuildOptions {
60
50
  /** When `false` with a single entrypoint, inlines dynamic imports into one output file. */
61
51
  splitting?: boolean;
62
52
  root?: string;
63
- /** @deprecated Accepted for call-site compatibility only. */
64
- bundle?: boolean;
65
53
  externalPackages?: boolean;
66
54
  external?: string[];
67
55
  jsx?: {
@@ -2,6 +2,7 @@ import { createRequire } from 'node:module';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
+ import { appLogger } from '../../global/app-logger.js';
5
6
  import { isBarePackageImportSpecifier } from '../../plugins/tsconfig-import-resolver.js';
6
7
  const corePackageRequire = createRequire(new URL('../../../package.json', import.meta.url));
7
8
  const appDeclaredPackageCache = new Map();
@@ -201,9 +202,7 @@ function rewriteRuntimeBuildOutputImports(code, rootDir) {
201
202
  });
202
203
  }
203
204
  export function normalizeNodeRuntimeBuildOutputFile(filePath, rootDir) {
204
- if (process.env.ECOPAGES_LOGGER_DEBUG === 'true') {
205
- console.log(`[normalizeNodeRuntimeBuildOutputFile] Checking ${filePath}`);
206
- }
205
+ appLogger.debug(`[normalizeNodeRuntimeBuildOutputFile] Checking ${filePath}`);
207
206
  if (!/\.(?:[cm]?js)$/u.test(filePath)) {
208
207
  return;
209
208
  }
@@ -214,9 +213,7 @@ export function normalizeNodeRuntimeBuildOutputFile(filePath, rootDir) {
214
213
  const code = fileSystem.readFileSync(filePath, 'utf-8');
215
214
  const rewritten = rewriteRuntimeBuildOutputImports(code, rootDir);
216
215
  if (rewritten !== code) {
217
- if (process.env.ECOPAGES_LOGGER_DEBUG === 'true') {
218
- console.log(`[normalizeNodeRuntimeBuildOutputFile] Rewriting ${filePath}`);
219
- }
216
+ appLogger.debug(`[normalizeNodeRuntimeBuildOutputFile] Rewriting ${filePath}`);
220
217
  fileSystem.writeFileSync(filePath, rewritten);
221
218
  }
222
219
  }
@@ -7,11 +7,7 @@ import type { BuildOptions } from '../contracts/build-contracts.js';
7
7
  * are sorted. Plugin, `conditions`, and source-transform order is preserved because
8
8
  * Rolldown hook and `conditionNames` precedence depend on it.
9
9
  *
10
- * Deprecated / ignored adapter fields (`splitting`, `bundle`, `outbase`) still
11
- * participate in the key so requests that differ only on those fields do not
12
- * coalesce. Empty `conditions` / `define` / `external` normalize to the same
13
- * sentinel as `undefined`.
10
+ * Empty `conditions` / `define` / `external` normalize to the same sentinel as
11
+ * `undefined`.
14
12
  */
15
13
  export declare function createBuildRequestIdentity(options: BuildOptions): string;
16
- /** @deprecated Use {@link createBuildRequestIdentity}. */
17
- export declare const createBuildOptionsDedupeKey: typeof createBuildRequestIdentity;
@@ -47,19 +47,15 @@ function normalizeDefine(define) {
47
47
  * are sorted. Plugin, `conditions`, and source-transform order is preserved because
48
48
  * Rolldown hook and `conditionNames` precedence depend on it.
49
49
  *
50
- * Deprecated / ignored adapter fields (`splitting`, `bundle`, `outbase`) still
51
- * participate in the key so requests that differ only on those fields do not
52
- * coalesce. Empty `conditions` / `define` / `external` normalize to the same
53
- * sentinel as `undefined`.
50
+ * Empty `conditions` / `define` / `external` normalize to the same sentinel as
51
+ * `undefined`.
54
52
  */
55
53
  export function createBuildRequestIdentity(options) {
56
54
  return [
57
55
  normalizeEntrypoints(options.entrypoints),
58
56
  options.root ? path.resolve(options.root) : 'root:default',
59
57
  options.outdir ? path.resolve(options.outdir) : 'outdir:default',
60
- options.outbase ? path.resolve(options.outbase) : 'outbase:default',
61
58
  options.splitting ?? 'splitting:default',
62
- options.bundle ?? 'bundle:default',
63
59
  options.externalPackages ?? 'externalPackages:default',
64
60
  options.target ?? 'target:default',
65
61
  options.format ?? 'format:default',
@@ -75,5 +71,3 @@ export function createBuildRequestIdentity(options) {
75
71
  createSourceTransformCacheKey(options.sourceTransforms),
76
72
  ].join('::');
77
73
  }
78
- /** @deprecated Use {@link createBuildRequestIdentity}. */
79
- export const createBuildOptionsDedupeKey = createBuildRequestIdentity;
@@ -1,5 +1,4 @@
1
1
  import type { BuildExecutor, BuildOptions, BuildResult } from '../build-adapter.js';
2
- export { createBuildRequestIdentity, createBuildOptionsDedupeKey } from './build-request-identity.js';
3
2
  /**
4
3
  * In-flight build coalescing wrapper.
5
4
  *
@@ -1,5 +1,4 @@
1
1
  import { createBuildRequestIdentity } from './build-request-identity.js';
2
- export { createBuildRequestIdentity, createBuildOptionsDedupeKey } from './build-request-identity.js';
3
2
  /**
4
3
  * In-flight build coalescing wrapper.
5
4
  *
@@ -3,5 +3,5 @@
3
3
  *
4
4
  * @module @ecopages/core/cache
5
5
  */
6
- export { ModuleParseCache, moduleParseCache, cachedParseSync, parseModuleSource, parserLanguageForFile, type ModuleParseOptions, type ParserLanguage, } from './module-parse-cache.js';
6
+ export { parseModuleSource, type ModuleParseOptions } from './module-parse-cache.js';
7
7
  export { recordModuleTransformProfile } from './module-transform-profiler.js';