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

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 (159) hide show
  1. package/README.md +0 -9
  2. package/package.json +3 -144
  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 +27 -0
  49. package/src/build/cache/output-imports.js +80 -0
  50. package/src/build/cache/pages-unified-graph-build.d.ts +6 -1
  51. package/src/build/cache/pages-unified-graph-build.js +42 -17
  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/integration-renderer.d.ts +0 -6
  102. package/src/route-renderer/orchestration/integration-renderer.js +1 -11
  103. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +1 -1
  104. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -1
  105. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +1 -1
  106. package/src/services/README.md +1 -1
  107. package/src/services/assets/browser-bundle.service.d.ts +1 -6
  108. package/src/services/error-pages/default-error-pages.d.ts +1 -6
  109. package/src/services/error-pages/default-error-pages.js +0 -8
  110. package/src/services/html/html-rewriter.d.ts +77 -0
  111. package/src/services/html/html-rewriter.js +751 -0
  112. package/src/services/html/html-rewriter.parity.test.bun.d.ts +1 -0
  113. package/src/services/html/html-rewriter.parity.test.bun.js +74 -0
  114. package/src/services/html/html-transformer.service.d.ts +26 -39
  115. package/src/services/html/html-transformer.service.js +81 -153
  116. package/src/services/invalidation/development-invalidation.service.d.ts +2 -19
  117. package/src/services/invalidation/development-invalidation.service.js +1 -39
  118. package/src/services/module-loading/README.md +1 -1
  119. package/src/services/module-loading/app-module-loader.service.d.ts +0 -2
  120. package/src/services/module-loading/app-server-module-transpiler.service.d.ts +1 -1
  121. package/src/services/module-loading/app-server-module-transpiler.service.js +0 -10
  122. package/src/services/module-loading/collection-server-module-build.service.d.ts +0 -1
  123. package/src/services/module-loading/collection-server-module-build.service.js +0 -3
  124. package/src/services/module-loading/host-module-loader-registry.d.ts +0 -1
  125. package/src/services/module-loading/host-module-loader-registry.js +0 -3
  126. package/src/services/module-loading/route-module-build-cache-registry.d.ts +0 -4
  127. package/src/services/module-loading/route-module-build-cache-registry.js +0 -4
  128. package/src/services/module-loading/route-module-build-cache.store.d.ts +3 -0
  129. package/src/services/module-loading/route-module-build-cache.store.js +18 -5
  130. package/src/services/module-loading/route-module-build-manifest.d.ts +6 -1
  131. package/src/services/module-loading/route-module-build-manifest.js +1 -2
  132. package/src/services/module-loading/route-module-dependency-hasher.d.ts +3 -2
  133. package/src/services/module-loading/server-module-transpiler.service.d.ts +1 -15
  134. package/src/services/module-loading/server-module-transpiler.service.js +0 -24
  135. package/src/services/runtime-state/entrypoint-dependency-graph.service.js +0 -12
  136. package/src/services/runtime-state/server-invalidation-state.service.d.ts +4 -2
  137. package/src/services/runtime-state/server-invalidation-state.service.js +7 -14
  138. package/src/types/internal-types.d.ts +0 -38
  139. package/src/types/public-types.d.ts +0 -112
  140. package/src/watchers/project-watcher.d.ts +0 -15
  141. package/src/watchers/project-watcher.js +1 -27
  142. package/src/watchers/project-watcher.test-helpers.d.ts +10 -1
  143. package/src/watchers/project-watcher.test-helpers.js +12 -0
  144. package/src/adapters/abstract/router-adapter.d.ts +0 -26
  145. package/src/adapters/abstract/router-adapter.js +0 -13
  146. package/src/adapters/bun/index.d.ts +0 -2
  147. package/src/adapters/bun/index.js +0 -2
  148. package/src/adapters/index.d.ts +0 -2
  149. package/src/adapters/index.js +0 -2
  150. package/src/eco/eco.utils.d.ts +0 -1
  151. package/src/eco/eco.utils.js +0 -1
  152. package/src/services/cache/index.d.ts +0 -9
  153. package/src/services/cache/index.js +0 -8
  154. package/src/services/html/html-rewriter-provider.service.d.ts +0 -40
  155. package/src/services/html/html-rewriter-provider.service.js +0 -68
  156. package/src/services/module-loading/route-module-build-cache.d.ts +0 -4
  157. package/src/services/module-loading/route-module-build-cache.js +0 -3
  158. package/src/services/runtime-state/dev-graph.service.d.ts +0 -118
  159. package/src/services/runtime-state/dev-graph.service.js +0 -170
@@ -1,11 +1,10 @@
1
1
  import { type Server as NodeHttpServer } from 'node:http';
2
2
  import type { EcoPagesAppConfig } from '../../types/internal-types.js';
3
3
  import type { ApiHandler, ErrorHandler, StaticRoute, ErrorPageLoaders, EcopagesWebSocketHandler } from '../../types/public-types.js';
4
+ import { type WebSocketUpgradeOptions } from '../shared/ws/node-http-websocket-upgrades.js';
4
5
  import { SharedServerAdapter } from '../shared/runtime/server-adapter.js';
5
6
  import type { ServerAdapterResult } from '../abstract/server-adapter.js';
6
- import { NodeHttpRequestBridge } from './http-request-bridge.js';
7
7
  import type { StaticPreviewHost } from '../shared/runtime/static-preview-host.js';
8
- import { type NodeServerDevRuntimeFactory } from './server-adapter-dependencies.js';
9
8
  export type NodeServerInstance = NodeHttpServer;
10
9
  export type NodeServeAdapterServerOptions = {
11
10
  port?: number;
@@ -29,15 +28,11 @@ export interface NodeServerAdapterParams {
29
28
  allowPortFallback?: boolean;
30
29
  onDevelopmentRestart?: (changedFile: string) => Promise<void>;
31
30
  previewHost?: StaticPreviewHost;
32
- requestBridge?: NodeHttpRequestBridge;
33
- devRuntimeFactory?: NodeServerDevRuntimeFactory;
34
31
  }
35
32
  export interface NodeServerAdapterResult extends ServerAdapterResult {
36
- completeInitialization: (server: NodeServerInstance) => Promise<void>;
33
+ completeInitialization: (server: NodeServerInstance, options?: WebSocketUpgradeOptions) => Promise<void>;
37
34
  handleRequest: (request: Request) => Promise<Response>;
38
- attachUserWebSocketUpgrades: (server: NodeServerInstance, options?: {
39
- passthroughUnmatched?: boolean;
40
- }) => void;
35
+ attachUserWebSocketUpgrades: (server: NodeServerInstance, options?: WebSocketUpgradeOptions) => void;
41
36
  dispose: () => Promise<void>;
42
37
  }
43
38
  /**
@@ -54,9 +49,10 @@ export interface NodeServerAdapterResult extends ServerAdapterResult {
54
49
  * Conditionally wires HMR, WebSocket upgrades, and the file watcher when
55
50
  * `options.watch` is `true`.
56
51
  * 3. `handleRequest(request)` — delegates to `handleSharedRequest` for routing;
57
- * intercepts `ClientAbortError` to return 499 instead of 500.
58
- * 4. `buildStatic()` — spins up an ephemeral runtime server, generates all static
59
- * pages against it, then tears it down.
52
+ * intercepts `ClientAbortError` to return 499 instead of 500 and sends every
53
+ * other escaped error through the shared `app.onError` boundary.
54
+ * 4. `buildStatic()` — generates static pages in-process through the shared
55
+ * static builder (no runtime server), then optionally starts the preview server.
60
56
  *
61
57
  * @see SharedServerAdapter for routing, caching and response handler logic.
62
58
  */
@@ -75,8 +71,6 @@ export declare class NodeServerAdapter extends SharedServerAdapter<NodeServerAda
75
71
  private readonly allowPortFallback;
76
72
  private readonly onDevelopmentRestart?;
77
73
  private readonly previewHost;
78
- private readonly requestBridge;
79
- private readonly devRuntimeFactory;
80
74
  /**
81
75
  * Reference to the application-level WebSocket handlers map.
82
76
  *
@@ -92,23 +86,17 @@ export declare class NodeServerAdapter extends SharedServerAdapter<NodeServerAda
92
86
  * Host integrations such as the Vite plugin call this so `app.websocket()`
93
87
  * handlers work while HTTP is still served by the host dev server.
94
88
  */
95
- attachUserWebSocketUpgrades(server: NodeServerInstance, options?: {
96
- passthroughUnmatched?: boolean;
97
- }): void;
98
- private wireUserWebSocketUpgrades;
89
+ attachUserWebSocketUpgrades(server: NodeServerInstance, options?: WebSocketUpgradeOptions): void;
99
90
  /**
100
91
  * @remarks
101
- * `previewHost`, `requestBridge`, and `devRuntimeFactory` are optional on the
102
- * public {@link NodeServerAdapterParams} so factory callers can omit them, but
103
- * they are mandatory by the time the concrete adapter is constructed —
104
- * {@link createNodeServerAdapter} fills in Node-specific defaults first. The
105
- * constructor signature makes that invariant explicit instead of relying on
106
- * non-null assertions.
92
+ * `previewHost` is optional on the public {@link NodeServerAdapterParams} so
93
+ * factory callers can omit it, but it is mandatory by the time the concrete
94
+ * adapter is constructed — {@link createNodeServerAdapter} fills in the Node
95
+ * default first. The constructor signature makes that invariant explicit
96
+ * instead of relying on non-null assertions.
107
97
  */
108
98
  constructor(options: NodeServerAdapterParams & {
109
99
  previewHost: StaticPreviewHost;
110
- requestBridge: NodeHttpRequestBridge;
111
- devRuntimeFactory: NodeServerDevRuntimeFactory;
112
100
  });
113
101
  /**
114
102
  * Prepares the adapter for use.
@@ -148,12 +136,16 @@ export declare class NodeServerAdapter extends SharedServerAdapter<NodeServerAda
148
136
  * Handles a single incoming Web `Request` and returns a Web `Response`.
149
137
  *
150
138
  * Delegates to `handleSharedRequest` for all routing, caching, and response
151
- * handler logic. The only Node-specific concern here is translating a
152
- * `ClientAbortError` — which the body `ReadableStream` raises when the
153
- * underlying socket closes early — into a 499 response so it does not
154
- * incorrectly surface as a 500 in application logs.
139
+ * handler logic. Escaped errors go through the shared `app.onError`
140
+ * boundary, which answers client aborts (see {@link isClientAbortError}) with 499.
155
141
  */
156
142
  handleRequest(request: Request): Promise<Response>;
143
+ /**
144
+ * @remarks
145
+ * The request body stream raises `NodeClientAbortError` when the socket closes
146
+ * early (closed tab, network drop, programmatic abort).
147
+ */
148
+ protected isClientAbortError(error: unknown): boolean;
157
149
  /**
158
150
  * Called once the HTTP server is bound and listening.
159
151
  *
@@ -168,9 +160,11 @@ export declare class NodeServerAdapter extends SharedServerAdapter<NodeServerAda
168
160
  * refreshes the router and response handlers when pages are added or removed.
169
161
  *
170
162
  * WebSocket upgrade requests that do not match a known path are rejected with an
171
- * immediate socket destroy to prevent unhandled upgrade leaks.
163
+ * immediate socket destroy to prevent unhandled upgrade leaks, unless
164
+ * `passthroughUnmatched` is set because a host (for example Vite) shares the
165
+ * server and owns other upgrade paths.
172
166
  */
173
- completeInitialization(server: NodeServerInstance): Promise<void>;
167
+ completeInitialization(server: NodeServerInstance, options?: WebSocketUpgradeOptions): Promise<void>;
174
168
  }
175
169
  /**
176
170
  * Factory function that creates and fully initialises a `NodeServerAdapter`.
@@ -15,9 +15,9 @@ import { ServerStaticBuilder } from '../shared/runtime/server-static-builder.js'
15
15
  import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from '../../config/constants.js';
16
16
  import { attachHmrToIntegrations, disposeDevResources, prepareRuntimePublicDir, startDevWarmup, } from '../shared/runtime/runtime-server-lifecycle.js';
17
17
  import { resolveServeRuntimeOrigin } from '../shared/runtime/runtime-app-bootstrap.js';
18
- import { NodeClientAbortError, NodeHttpRequestBridge } from './http-request-bridge.js';
18
+ import { isNodeClientAbortError } from './http-request-bridge.js';
19
19
  import { NodeStaticPreviewHost } from './static-preview-host.js';
20
- import { DefaultNodeServerDevRuntimeFactory } from './server-adapter-dependencies.js';
20
+ import { createNodeServerDevRuntime } from './server-adapter-dependencies.js';
21
21
  /**
22
22
  * Node.js HTTP server adapter for the Ecopages runtime.
23
23
  *
@@ -32,9 +32,10 @@ import { DefaultNodeServerDevRuntimeFactory } from './server-adapter-dependencie
32
32
  * Conditionally wires HMR, WebSocket upgrades, and the file watcher when
33
33
  * `options.watch` is `true`.
34
34
  * 3. `handleRequest(request)` — delegates to `handleSharedRequest` for routing;
35
- * intercepts `ClientAbortError` to return 499 instead of 500.
36
- * 4. `buildStatic()` — spins up an ephemeral runtime server, generates all static
37
- * pages against it, then tears it down.
35
+ * intercepts `ClientAbortError` to return 499 instead of 500 and sends every
36
+ * other escaped error through the shared `app.onError` boundary.
37
+ * 4. `buildStatic()` — generates static pages in-process through the shared
38
+ * static builder (no runtime server), then optionally starts the preview server.
38
39
  *
39
40
  * @see SharedServerAdapter for routing, caching and response handler logic.
40
41
  */
@@ -53,8 +54,6 @@ export class NodeServerAdapter extends SharedServerAdapter {
53
54
  allowPortFallback;
54
55
  onDevelopmentRestart;
55
56
  previewHost;
56
- requestBridge;
57
- devRuntimeFactory;
58
57
  /**
59
58
  * Reference to the application-level WebSocket handlers map.
60
59
  *
@@ -77,22 +76,13 @@ export class NodeServerAdapter extends SharedServerAdapter {
77
76
  passthroughUnmatched: options?.passthroughUnmatched,
78
77
  });
79
78
  }
80
- wireUserWebSocketUpgrades(server, preflight) {
81
- attachNodeHttpWebSocketUpgrades(server, {
82
- runtimeOrigin: this.runtimeOrigin,
83
- websocketHandlers: this.websocketHandlers,
84
- passthroughUnmatched: false,
85
- preflight,
86
- });
87
- }
88
79
  /**
89
80
  * @remarks
90
- * `previewHost`, `requestBridge`, and `devRuntimeFactory` are optional on the
91
- * public {@link NodeServerAdapterParams} so factory callers can omit them, but
92
- * they are mandatory by the time the concrete adapter is constructed —
93
- * {@link createNodeServerAdapter} fills in Node-specific defaults first. The
94
- * constructor signature makes that invariant explicit instead of relying on
95
- * non-null assertions.
81
+ * `previewHost` is optional on the public {@link NodeServerAdapterParams} so
82
+ * factory callers can omit it, but it is mandatory by the time the concrete
83
+ * adapter is constructed — {@link createNodeServerAdapter} fills in the Node
84
+ * default first. The constructor signature makes that invariant explicit
85
+ * instead of relying on non-null assertions.
96
86
  */
97
87
  constructor(options) {
98
88
  super(options);
@@ -104,8 +94,6 @@ export class NodeServerAdapter extends SharedServerAdapter {
104
94
  this.errorPageLoaders = options.errorPageLoaders ?? {};
105
95
  this.errorHandler = options.errorHandler;
106
96
  this.previewHost = options.previewHost;
107
- this.requestBridge = options.requestBridge;
108
- this.devRuntimeFactory = options.devRuntimeFactory;
109
97
  if (options.websocketHandlers) {
110
98
  this.websocketHandlers = options.websocketHandlers;
111
99
  }
@@ -238,37 +226,34 @@ export class NodeServerAdapter extends SharedServerAdapter {
238
226
  * Handles a single incoming Web `Request` and returns a Web `Response`.
239
227
  *
240
228
  * Delegates to `handleSharedRequest` for all routing, caching, and response
241
- * handler logic. The only Node-specific concern here is translating a
242
- * `ClientAbortError` — which the body `ReadableStream` raises when the
243
- * underlying socket closes early — into a 499 response so it does not
244
- * incorrectly surface as a 500 in application logs.
229
+ * handler logic. Escaped errors go through the shared `app.onError`
230
+ * boundary, which answers client aborts (see {@link isClientAbortError}) with 499.
245
231
  */
246
232
  async handleRequest(request) {
247
233
  if (!this.initialized) {
248
234
  throw new Error('Node server adapter is not initialized. Call createAdapter() first.');
249
235
  }
236
+ const context = {
237
+ apiHandlers: this.apiHandlers,
238
+ errorHandler: this.errorHandler,
239
+ serverInstance: this.serverInstance,
240
+ hmrManager: this.hmrManager ?? undefined,
241
+ };
250
242
  try {
251
- const response = await this.handleSharedRequest(request, {
252
- apiHandlers: this.apiHandlers,
253
- errorHandler: this.errorHandler,
254
- serverInstance: this.serverInstance,
255
- hmrManager: this.hmrManager ?? undefined,
256
- });
257
- return response;
243
+ return await this.handleSharedRequest(request, context);
258
244
  }
259
245
  catch (error) {
260
- if (error instanceof NodeClientAbortError) {
261
- /**
262
- * The client disconnected before the response was sent (killed tab,
263
- * network drop, or programmatic abort). This is a normal browser behaviour,
264
- * not a server fault. Return 499 (Client Closed Request) silently so the
265
- * error does not surface in application logs as a 500.
266
- */
267
- return new Response(null, { status: 499 });
268
- }
269
- throw error;
246
+ return await this.handleUnexpectedRequestError(error, request, context);
270
247
  }
271
248
  }
249
+ /**
250
+ * @remarks
251
+ * The request body stream raises `NodeClientAbortError` when the socket closes
252
+ * early (closed tab, network drop, programmatic abort).
253
+ */
254
+ isClientAbortError(error) {
255
+ return isNodeClientAbortError(error);
256
+ }
272
257
  /**
273
258
  * Called once the HTTP server is bound and listening.
274
259
  *
@@ -283,13 +268,15 @@ export class NodeServerAdapter extends SharedServerAdapter {
283
268
  * refreshes the router and response handlers when pages are added or removed.
284
269
  *
285
270
  * WebSocket upgrade requests that do not match a known path are rejected with an
286
- * immediate socket destroy to prevent unhandled upgrade leaks.
271
+ * immediate socket destroy to prevent unhandled upgrade leaks, unless
272
+ * `passthroughUnmatched` is set because a host (for example Vite) shares the
273
+ * server and owns other upgrade paths.
287
274
  */
288
- async completeInitialization(server) {
275
+ async completeInitialization(server, options) {
289
276
  this.serverInstance = server;
290
- const hasUserWs = this.websocketHandlers.size > 0;
277
+ const passthroughUnmatched = options?.passthroughUnmatched;
291
278
  if (this.options?.watch) {
292
- const devRuntime = this.devRuntimeFactory.create({ appConfig: this.appConfig });
279
+ const devRuntime = createNodeServerDevRuntime(this.appConfig);
293
280
  const wss = devRuntime.websocketServer;
294
281
  this.bridge = devRuntime.bridge;
295
282
  this.hmrManager = devRuntime.hmrManager;
@@ -306,16 +293,12 @@ export class NodeServerAdapter extends SharedServerAdapter {
306
293
  });
307
294
  return true;
308
295
  };
309
- if (hasUserWs) {
310
- this.wireUserWebSocketUpgrades(server, hmrPreflight);
311
- }
312
- else {
313
- server.on('upgrade', (req, socket, head) => {
314
- if (!hmrPreflight(req, socket, head)) {
315
- socket.destroy();
316
- }
317
- });
318
- }
296
+ attachNodeHttpWebSocketUpgrades(server, {
297
+ runtimeOrigin: this.runtimeOrigin,
298
+ websocketHandlers: this.websocketHandlers,
299
+ passthroughUnmatched,
300
+ preflight: hmrPreflight,
301
+ });
319
302
  attachHmrToIntegrations(this.appConfig, this.hmrManager);
320
303
  startDevWarmup({
321
304
  appConfig: this.appConfig,
@@ -343,8 +326,8 @@ export class NodeServerAdapter extends SharedServerAdapter {
343
326
  this.projectWatcher = watcher;
344
327
  await watcher.createWatcherSubscription();
345
328
  }
346
- else if (hasUserWs) {
347
- this.wireUserWebSocketUpgrades(server);
329
+ else {
330
+ this.attachUserWebSocketUpgrades(server, { passthroughUnmatched });
348
331
  }
349
332
  appLogger.debug('Node server adapter initialization completed', {
350
333
  apiHandlers: this.apiHandlers.length,
@@ -364,14 +347,10 @@ export class NodeServerAdapter extends SharedServerAdapter {
364
347
  export async function createNodeServerAdapter(params) {
365
348
  const runtimeOrigin = params.runtimeOrigin ?? resolveServeRuntimeOrigin(params.serveOptions);
366
349
  const previewHost = params.previewHost ?? new NodeStaticPreviewHost();
367
- const requestBridge = params.requestBridge ?? new NodeHttpRequestBridge();
368
- const devRuntimeFactory = params.devRuntimeFactory ?? new DefaultNodeServerDevRuntimeFactory();
369
350
  const adapter = new NodeServerAdapter({
370
351
  ...params,
371
352
  runtimeOrigin,
372
353
  previewHost,
373
- requestBridge,
374
- devRuntimeFactory,
375
354
  });
376
355
  return adapter.createAdapter();
377
356
  }
@@ -1,4 +1,3 @@
1
- import fs from 'node:fs';
2
1
  import { type ResolvedHmrEntrypoint } from '../../../hmr/hmr-entrypoint-output.js';
3
2
  import type { DefaultHmrContext, EcoPagesAppConfig, IHmrManager, IClientBridge } from '../../../types/internal-types.js';
4
3
  import { type HmrStrategy } from '../../../hmr/hmr-strategy.js';
@@ -18,7 +17,6 @@ type SharedHmrManagerParams = {
18
17
  export declare abstract class SharedHmrManager implements IHmrManager {
19
18
  readonly appConfig: EcoPagesAppConfig;
20
19
  protected readonly bridge: IClientBridge;
21
- protected watchers: Map<string, fs.FSWatcher>;
22
20
  protected runtimeWorkDir: string;
23
21
  protected enabled: boolean;
24
22
  protected strategies: HmrStrategy[];
@@ -47,14 +45,12 @@ export declare abstract class SharedHmrManager implements IHmrManager {
47
45
  registerStrategy(strategy: HmrStrategy): void;
48
46
  setEnabled(enabled: boolean): void;
49
47
  isEnabled(): boolean;
50
- isRuntimeReady(): boolean;
51
48
  /**
52
49
  * Builds the browser HMR runtime once per manager session and reuses the in-flight build for concurrent callers.
53
50
  */
54
51
  ensureRuntimeReady(): Promise<boolean>;
55
52
  private ensureHmrRuntimeReady;
56
53
  private ensureDevToolbarRuntimeReady;
57
- buildRuntime(): Promise<void>;
58
54
  getRuntimePath(): string;
59
55
  private buildDevToolbarRuntimeInternal;
60
56
  getDevToolbarRuntimePath(): string;
@@ -1,4 +1,3 @@
1
- import fs from 'node:fs';
2
1
  import path from 'node:path';
3
2
  import { fileURLToPath } from 'node:url';
4
3
  import { HMR_RUNTIME_SCRIPT_URL, resolveHmrRuntimeWorkDir } from '../../../hmr/hmr-runtime-paths.js';
@@ -22,7 +21,6 @@ import { DevTransformServer } from '../../../dev/transform-server/dev-transform-
22
21
  export class SharedHmrManager {
23
22
  appConfig;
24
23
  bridge;
25
- watchers = new Map();
26
24
  runtimeWorkDir;
27
25
  enabled = false;
28
26
  strategies = [];
@@ -121,9 +119,6 @@ export class SharedHmrManager {
121
119
  isEnabled() {
122
120
  return this.enabled;
123
121
  }
124
- isRuntimeReady() {
125
- return this.runtimeReady && fileSystem.exists(this.getRuntimePath());
126
- }
127
122
  /**
128
123
  * Builds the browser HMR runtime once per manager session and reuses the in-flight build for concurrent callers.
129
124
  */
@@ -171,9 +166,6 @@ export class SharedHmrManager {
171
166
  this.devToolbarBuildPromise = null;
172
167
  }
173
168
  }
174
- async buildRuntime() {
175
- await this.ensureRuntimeReady();
176
- }
177
169
  getRuntimePath() {
178
170
  return path.join(this.runtimeWorkDir, path.basename(HMR_RUNTIME_SCRIPT_URL));
179
171
  }
@@ -409,10 +401,6 @@ export class SharedHmrManager {
409
401
  this.runtimeReady = false;
410
402
  this.entrypointRegistry.clearAll();
411
403
  this.devTransformServer.reset();
412
- for (const watcher of this.watchers.values()) {
413
- watcher.close();
414
- }
415
- this.watchers.clear();
416
404
  this.entrypointDependencyGraph.reset();
417
405
  }
418
406
  clearFailedEntrypointRegistration(entrypointPath) {
@@ -1,14 +1,24 @@
1
1
  import type { SchemaValidationService } from '../../../services/validation/schema-validation-service.js';
2
- import type { ApiHandler, CacheInvalidator, ErrorHandler, RenderContext } from '../../../types/public-types.js';
2
+ import type { ApiHandler, ApiHandlerContext, CacheInvalidator, ErrorHandler, RenderContext } from '../../../types/public-types.js';
3
3
  export type ApiRequestPipelineOptions = {
4
4
  schemaValidator: SchemaValidationService;
5
5
  getRenderContext: () => RenderContext;
6
6
  getCacheService: () => CacheInvalidator | null;
7
+ /**
8
+ * Recognises a client that disconnected mid-request.
9
+ *
10
+ * @remarks
11
+ * Such errors are a normal browser behaviour, not a server fault, so
12
+ * {@link ApiRequestPipeline.handleError} answers them with 499 without logging or
13
+ * calling `app.onError`. Only the Node adapter supplies it.
14
+ */
15
+ isClientAbort?: (error: unknown) => boolean;
7
16
  };
8
17
  export declare class ApiRequestPipeline<TRequest extends Request = Request, TServer = unknown> {
9
18
  private readonly schemaValidator;
10
19
  private readonly getRenderContext;
11
20
  private readonly getCacheService;
21
+ private readonly isClientAbort;
12
22
  constructor(options: ApiRequestPipelineOptions);
13
23
  match(request: TRequest, apiHandlers: ApiHandler<string, TRequest, TServer>[]): {
14
24
  routeConfig: ApiHandler<string, TRequest, TServer>;
@@ -16,6 +26,22 @@ export declare class ApiRequestPipeline<TRequest extends Request = Request, TSer
16
26
  } | null;
17
27
  tryHandle(request: TRequest, apiHandlers: ApiHandler<string, TRequest, TServer>[], serverInstance: TServer | undefined, errorHandler?: ErrorHandler<TRequest, TServer>): Promise<Response | null>;
18
28
  execute(request: TRequest, params: Record<string, string | string[]>, routeConfig: ApiHandler<string, TRequest, TServer>, serverInstance: TServer | undefined, errorHandler?: ErrorHandler<TRequest, TServer>): Promise<Response>;
29
+ /**
30
+ * Resolves an error that escaped a handler into a response.
31
+ *
32
+ * @remarks
33
+ * Precedence is a thrown `Response`, then a client abort (499), then the app
34
+ * `onError` handler, then `HttpError.toResponse()`, then a logged plain 500.
35
+ * Runtime adapters reuse this for errors that escape the whole request
36
+ * pipeline so `app.onError` behaves the same on Bun and Node.
37
+ */
38
+ handleError(error: unknown, options: {
39
+ request: TRequest;
40
+ params?: Record<string, string | string[]>;
41
+ serverInstance: TServer | undefined;
42
+ errorHandler?: ErrorHandler<TRequest, TServer>;
43
+ context?: ApiHandlerContext<TRequest, TServer>;
44
+ }): Promise<Response>;
19
45
  private createContext;
20
46
  private normalizeParams;
21
47
  private applyRequestSchema;
@@ -8,10 +8,12 @@ export class ApiRequestPipeline {
8
8
  schemaValidator;
9
9
  getRenderContext;
10
10
  getCacheService;
11
+ isClientAbort;
11
12
  constructor(options) {
12
13
  this.schemaValidator = options.schemaValidator;
13
14
  this.getRenderContext = options.getRenderContext;
14
15
  this.getCacheService = options.getCacheService;
16
+ this.isClientAbort = options.isClientAbort ?? (() => false);
15
17
  }
16
18
  match(request, apiHandlers) {
17
19
  const pathname = new URL(request.url).pathname;
@@ -49,24 +51,37 @@ export class ApiRequestPipeline {
49
51
  return await this.runMiddlewareChain(context, routeConfig);
50
52
  }
51
53
  catch (error) {
52
- if (error instanceof Response)
53
- return error;
54
- if (errorHandler) {
55
- try {
56
- if (!context) {
57
- context = this.createContext(request, params, serverInstance);
58
- }
59
- return await errorHandler(error, context);
60
- }
61
- catch (handlerError) {
62
- appLogger.error(`[ecopages] Error in custom error handler: ${handlerError}`);
63
- }
54
+ return await this.handleError(error, { request, params, serverInstance, errorHandler, context });
55
+ }
56
+ }
57
+ /**
58
+ * Resolves an error that escaped a handler into a response.
59
+ *
60
+ * @remarks
61
+ * Precedence is a thrown `Response`, then a client abort (499), then the app
62
+ * `onError` handler, then `HttpError.toResponse()`, then a logged plain 500.
63
+ * Runtime adapters reuse this for errors that escape the whole request
64
+ * pipeline so `app.onError` behaves the same on Bun and Node.
65
+ */
66
+ async handleError(error, options) {
67
+ if (error instanceof Response)
68
+ return error;
69
+ if (this.isClientAbort(error))
70
+ return new Response(null, { status: 499 });
71
+ if (options.errorHandler) {
72
+ try {
73
+ const context = options.context ??
74
+ this.createContext(options.request, options.params ?? {}, options.serverInstance);
75
+ return await options.errorHandler(error, context);
76
+ }
77
+ catch (handlerError) {
78
+ appLogger.error('[ecopages] Error in custom error handler', handlerError);
64
79
  }
65
- if (error instanceof HttpError)
66
- return error.toResponse();
67
- appLogger.error(`[ecopages] Error handling API request: ${error}`);
68
- return new Response('Internal Server Error', { status: 500 });
69
80
  }
81
+ if (error instanceof HttpError)
82
+ return error.toResponse();
83
+ appLogger.error('[ecopages] Error handling request', error);
84
+ return new Response('Internal Server Error', { status: 500 });
70
85
  }
71
86
  createContext(request, params, serverInstance) {
72
87
  const locals = {};
@@ -8,7 +8,6 @@ export declare class FileSystemServerResponseFactory {
8
8
  constructor({ options }: {
9
9
  options: FileSystemServerOptions;
10
10
  });
11
- isHtml(contentType: string): contentType is "text/html";
12
11
  shouldEnableGzip(contentType: string): boolean;
13
12
  createResponseWithBody(body: RouteRendererBody, init?: ResponseInit): Promise<Response>;
14
13
  /**
@@ -9,9 +9,6 @@ export class FileSystemServerResponseFactory {
9
9
  constructor({ options }) {
10
10
  this.options = options;
11
11
  }
12
- isHtml(contentType) {
13
- return contentType === 'text/html';
14
- }
15
12
  shouldEnableGzip(contentType) {
16
13
  if (this.options.watchMode)
17
14
  return false;
@@ -1,11 +1,9 @@
1
1
  import type { EcoPagesAppConfig } from '../../../types/internal-types.js';
2
- import type { DevPrewarmReadiness } from './dev-static-route-prewarm.js';
3
2
  export type DevPrewarmPlan = {
4
3
  pathnames: readonly string[];
5
4
  beforeReadyPathnames: readonly string[];
6
- readiness: DevPrewarmReadiness;
7
5
  };
8
6
  /**
9
- * Aggregates processor-declared dev prewarm pathnames and readiness into one plan.
7
+ * Aggregates processor-declared dev prewarm pathnames into one plan.
10
8
  */
11
9
  export declare function collectAppDevPrewarmPlan(appConfig: EcoPagesAppConfig): Promise<DevPrewarmPlan>;
@@ -1,10 +1,9 @@
1
1
  /**
2
- * Aggregates processor-declared dev prewarm pathnames and readiness into one plan.
2
+ * Aggregates processor-declared dev prewarm pathnames into one plan.
3
3
  */
4
4
  export async function collectAppDevPrewarmPlan(appConfig) {
5
5
  const pathnames = new Set(appConfig.devPrewarmPaths ?? []);
6
6
  const beforeReadyPathnames = new Set(appConfig.devPrewarmBeforeReadyPaths ?? []);
7
- let readiness = 'background';
8
7
  for (const processor of appConfig.processors.values()) {
9
8
  const contributor = processor;
10
9
  const plan = await contributor.collectDevPrewarmPlan();
@@ -12,7 +11,6 @@ export async function collectAppDevPrewarmPlan(appConfig) {
12
11
  pathnames.add(pathname);
13
12
  }
14
13
  if (plan.readiness === 'beforeReady') {
15
- readiness = 'beforeReady';
16
14
  for (const pathname of plan.pathnames) {
17
15
  beforeReadyPathnames.add(pathname);
18
16
  }
@@ -24,6 +22,5 @@ export async function collectAppDevPrewarmPlan(appConfig) {
24
22
  return {
25
23
  pathnames: [...pathnames],
26
24
  beforeReadyPathnames: [...beforeReadyPathnames],
27
- readiness,
28
25
  };
29
26
  }
@@ -1,17 +1,11 @@
1
1
  import type { ReturnParseCliArgs } from '../../../utils/parse-cli-args.js';
2
- import type { EcoPagesAppConfig } from '../../../types/internal-types.js';
3
2
  export type RuntimeBinding = {
4
- preferredPort: number;
5
- preferredHostname: string;
6
3
  runtimeOrigin: string;
7
4
  serveOptions: Record<string, unknown>;
8
5
  watch: boolean;
9
6
  /** Whether preview may bind to the next free port when the preferred port is busy. */
10
7
  allowPortFallback: boolean;
11
8
  };
12
- export type StaticRuntimeMode = {
13
- canBuildWithoutRuntimeServer: boolean;
14
- };
15
9
  export declare function resolveServeRuntimeOrigin(serveOptions: {
16
10
  hostname?: string;
17
11
  port?: number | string;
@@ -21,7 +15,3 @@ export declare function resolveRuntimeBinding(options: {
21
15
  serverOptions?: Record<string, unknown>;
22
16
  env?: NodeJS.ProcessEnv;
23
17
  }): RuntimeBinding;
24
- export declare function resolveStaticRuntimeMode(options: {
25
- appConfig: EcoPagesAppConfig;
26
- cliArgs: ReturnParseCliArgs;
27
- }): StaticRuntimeMode;
@@ -16,8 +16,6 @@ export function resolveRuntimeBinding(options) {
16
16
  const preferredPort = options.cliArgs.port ?? (env.ECOPAGES_PORT ? Number(env.ECOPAGES_PORT) : undefined) ?? DEFAULT_ECOPAGES_PORT;
17
17
  const preferredHostname = options.cliArgs.hostname ?? env.ECOPAGES_HOSTNAME ?? DEFAULT_ECOPAGES_HOSTNAME;
18
18
  return {
19
- preferredPort,
20
- preferredHostname,
21
19
  allowPortFallback: !portExplicitlyConfigured,
22
20
  runtimeOrigin: resolveServeRuntimeOrigin({
23
21
  hostname: preferredHostname,
@@ -31,8 +29,3 @@ export function resolveRuntimeBinding(options) {
31
29
  watch: options.cliArgs.dev,
32
30
  };
33
31
  }
34
- export function resolveStaticRuntimeMode(options) {
35
- return {
36
- canBuildWithoutRuntimeServer: options.cliArgs.build || options.cliArgs.preview,
37
- };
38
- }
@@ -5,8 +5,11 @@ export interface RuntimeHost<TServer, TServeOptions> {
5
5
  }): Promise<void>;
6
6
  getOrigin(server: TServer, fallbackServeOptions: TServeOptions): string;
7
7
  }
8
+ /**
9
+ * @remarks
10
+ * Request handling travels inside `serveOptions`, as Bun's `fetch` does, so each
11
+ * runtime host receives only the callbacks it actually calls.
12
+ */
8
13
  export interface RuntimeHostStartOptions<TServeOptions> {
9
14
  serveOptions: TServeOptions;
10
- handleRequest(request: Request): Promise<Response>;
11
- onError(error: Error): Promise<void> | void;
12
15
  }
@@ -28,7 +28,7 @@ export declare function startDevWarmup(options: {
28
28
  * Releases shared dev resources in a consistent order across server adapters.
29
29
  *
30
30
  * @remarks
31
- * Bun calls `buildRuntime()` during `initialize()` when watch is enabled; Node defers
31
+ * Bun calls `ensureRuntimeReady()` during `initialize()` when watch is enabled; Node defers
32
32
  * runtime creation to `completeInitialization()`. Transport-specific setup stays in
33
33
  * each adapter — only shared teardown lives here.
34
34
  */
@@ -56,7 +56,7 @@ export function startDevWarmup(options) {
56
56
  * Releases shared dev resources in a consistent order across server adapters.
57
57
  *
58
58
  * @remarks
59
- * Bun calls `buildRuntime()` during `initialize()` when watch is enabled; Node defers
59
+ * Bun calls `ensureRuntimeReady()` during `initialize()` when watch is enabled; Node defers
60
60
  * runtime creation to `completeInitialization()`. Transport-specific setup stays in
61
61
  * each adapter — only shared teardown lives here.
62
62
  */