@ecopages/core 0.3.0 → 0.3.2

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 (201) hide show
  1. package/README.md +2 -2
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +40 -11
  4. package/src/adapters/node/create-app.js +95 -69
  5. package/src/adapters/node/dev-session.js +0 -1
  6. package/src/adapters/node/http-request-bridge.d.ts +4 -0
  7. package/src/adapters/node/http-request-bridge.js +9 -1
  8. package/src/adapters/node/runtime-host.d.ts +28 -6
  9. package/src/adapters/node/runtime-host.js +35 -9
  10. package/src/adapters/node/server-adapter.d.ts +10 -35
  11. package/src/adapters/node/server-adapter.js +21 -58
  12. package/src/adapters/shared/hmr/hmr-manager.d.ts +21 -7
  13. package/src/adapters/shared/hmr/hmr-manager.js +58 -70
  14. package/src/adapters/shared/http/api-request-pipeline.d.ts +3 -12
  15. package/src/adapters/shared/http/api-request-pipeline.js +7 -7
  16. package/src/adapters/shared/http/dist-file-handler.d.ts +16 -0
  17. package/src/adapters/shared/http/dist-file-handler.js +172 -0
  18. package/src/adapters/shared/http/explicit-static-route-matcher.js +2 -1
  19. package/src/adapters/shared/http/fs-server-response-matcher.js +3 -2
  20. package/src/adapters/shared/runtime/bind-runtime-server.d.ts +5 -7
  21. package/src/adapters/shared/runtime/bind-runtime-server.js +8 -12
  22. package/src/adapters/shared/runtime/copy-runtime-public-dir.js +10 -9
  23. package/src/adapters/shared/runtime/port-manager.d.ts +8 -11
  24. package/src/adapters/shared/runtime/port-manager.js +19 -30
  25. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +6 -9
  26. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +2 -5
  27. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +1 -3
  28. package/src/adapters/shared/runtime/server-request-pipeline.js +1 -5
  29. package/src/adapters/shared/runtime/server-static-builder.d.ts +3 -3
  30. package/src/adapters/shared/runtime/server-static-builder.js +3 -3
  31. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +2 -1
  32. package/src/adapters/shared/ws/websocket-lifecycle.d.ts +5 -6
  33. package/src/adapters/shared/ws/websocket-lifecycle.js +1 -2
  34. package/src/assets/app-browser-client-build.js +1 -2
  35. package/src/assets/asset-processing-service/browser-runtime-entry-resolution.js +8 -8
  36. package/src/assets/asset-processing-service/browser-runtime-entry.factory.js +4 -4
  37. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +12 -8
  38. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +36 -16
  39. package/src/assets/asset-processing-service/processors/stylesheet/file-stylesheet.processor.js +11 -6
  40. package/src/assets/browser-asset-output.d.ts +19 -0
  41. package/src/assets/browser-asset-output.js +30 -0
  42. package/src/assets/hashed-browser-asset.d.ts +8 -6
  43. package/src/assets/hashed-browser-asset.js +8 -6
  44. package/src/build/build-adapter.d.ts +2 -19
  45. package/src/build/build-adapter.js +0 -21
  46. package/src/build/build-graph.js +2 -2
  47. package/src/build/cache/cache-keys.d.ts +0 -3
  48. package/src/build/cache/cache-keys.js +0 -14
  49. package/src/build/cache/pages-unified-graph-build.js +2 -17
  50. package/src/build/contracts/build-contracts.d.ts +0 -3
  51. package/src/build/preserve-import-meta-transform.js +2 -2
  52. package/src/build/rolldown/app-package-declarations.js +3 -3
  53. package/src/build/rolldown/rolldown-adapter-helpers.js +3 -3
  54. package/src/build/rolldown/rolldown-build-adapter.d.ts +0 -1
  55. package/src/build/rolldown/rolldown-build-adapter.js +1 -2
  56. package/src/build/rolldown/rolldown-build-invocation-metrics.d.ts +1 -2
  57. package/src/build/rolldown/rolldown-build-invocation-metrics.js +5 -12
  58. package/src/build/rolldown/server-side-css-shim-plugin.js +3 -3
  59. package/src/build/runtime/build-queue.d.ts +8 -13
  60. package/src/build/runtime/build-queue.js +6 -17
  61. package/src/build/server/app-module-loader.service.d.ts +1 -1
  62. package/src/build/server/app-module-loader.service.js +0 -2
  63. package/src/build/server/page-module-import.service.d.ts +2 -3
  64. package/src/build/server/page-module-import.service.js +3 -4
  65. package/src/build/server-bundle-deploy-manifest.d.ts +5 -0
  66. package/src/build/server-bundle-deploy-manifest.js +15 -1
  67. package/src/build/server-bundle-publication.js +4 -5
  68. package/src/build.d.ts +2 -2
  69. package/src/build.js +2 -2
  70. package/src/config/assembly/app-runtime.d.ts +2 -2
  71. package/src/config/assembly/app-runtime.js +2 -2
  72. package/src/config/assembly/finalize-config.d.ts +4 -4
  73. package/src/config/assembly/finalize-config.js +4 -5
  74. package/src/config/config-module-files.js +2 -3
  75. package/src/config/internal-types.d.ts +0 -7
  76. package/src/config/user-config-types.d.ts +0 -4
  77. package/src/diagnostics/request-pipeline-metrics.d.ts +3 -3
  78. package/src/diagnostics/request-pipeline-metrics.js +4 -4
  79. package/src/diagnostics/startup-trace.js +2 -5
  80. package/src/errors/http-error.d.ts +2 -2
  81. package/src/errors/http-error.js +4 -4
  82. package/src/hmr/client/hmr-runtime.js +16 -7
  83. package/src/hmr/client/module-update.d.ts +7 -0
  84. package/src/hmr/client/module-update.js +21 -4
  85. package/src/hmr/hmr-strategy.d.ts +0 -3
  86. package/src/hmr/hmr-strategy.js +0 -3
  87. package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -3
  88. package/src/hmr/strategies/js-hmr-strategy.js +3 -6
  89. package/src/html-pages/html-page-module-scripts.js +4 -3
  90. package/src/html-pages/html-page-renderer.js +2 -3
  91. package/src/plugins/alias-resolver-cache.d.ts +4 -3
  92. package/src/plugins/alias-resolver-cache.js +4 -3
  93. package/src/plugins/component-import-discovery.js +4 -4
  94. package/src/plugins/eco-component-meta-plugin.d.ts +10 -1
  95. package/src/plugins/eco-component-meta-plugin.js +66 -10
  96. package/src/plugins/foreign-jsx-override-plugin.js +4 -3
  97. package/src/plugins/tsconfig-import-resolver.js +12 -12
  98. package/src/route-renderer/error-pages/default-error-pages.js +2 -1
  99. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -1
  100. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +0 -1
  101. package/src/route-renderer/orchestration/integration-renderer.d.ts +10 -5
  102. package/src/route-renderer/orchestration/integration-renderer.js +13 -14
  103. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -23
  104. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -29
  105. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +10 -32
  106. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +2 -2
  107. package/src/route-renderer/page-loading/page-dependency-bundling.js +5 -5
  108. package/src/route-renderer/page-loading/page-module-loader.js +1 -1
  109. package/src/route-renderer/route-renderer.d.ts +2 -5
  110. package/src/route-renderer/route-renderer.js +2 -4
  111. package/src/router/client/link-navigation-policy.d.ts +4 -1
  112. package/src/router/client/link-navigation-policy.js +20 -6
  113. package/src/router/server/route-registry.d.ts +0 -1
  114. package/src/router/server/route-registry.js +3 -13
  115. package/src/router/server/segment-path-matcher.d.ts +12 -0
  116. package/src/router/server/segment-path-matcher.js +30 -0
  117. package/src/static-site-generator/static-site-generator.d.ts +0 -5
  118. package/src/static-site-generator/static-site-generator.js +2 -15
  119. package/src/types/contracts.d.ts +17 -27
  120. package/src/types/public-types.d.ts +1 -1
  121. package/src/utils/format-error-chain.d.ts +9 -0
  122. package/src/utils/format-error-chain.js +20 -0
  123. package/src/utils/invariant.d.ts +6 -1
  124. package/src/utils/invariant.js +7 -2
  125. package/src/watchers/project-watcher.d.ts +20 -1
  126. package/src/watchers/project-watcher.js +40 -9
  127. package/src/watchers/workspace-package-watch-roots.js +5 -5
  128. package/src/adapters/README.md +0 -58
  129. package/src/adapters/shared/hmr/hmr-manager.test-helpers.d.ts +0 -28
  130. package/src/adapters/shared/hmr/hmr-manager.test-helpers.js +0 -53
  131. package/src/adapters/shared/runtime/runtime-host.d.ts +0 -15
  132. package/src/adapters/shared/runtime/runtime-host.js +0 -1
  133. package/src/assets/README.md +0 -35
  134. package/src/build/README.md +0 -298
  135. package/src/build/server/README.md +0 -50
  136. package/src/cache/README.md +0 -5
  137. package/src/client/README.md +0 -5
  138. package/src/client/navigation-scripts/navigation-scripts.test.browser.d.ts +0 -1
  139. package/src/client/navigation-scripts/navigation-scripts.test.browser.js +0 -111
  140. package/src/client/scroll.test.browser.d.ts +0 -1
  141. package/src/client/scroll.test.browser.js +0 -31
  142. package/src/client/view-transitions.test.browser.d.ts +0 -1
  143. package/src/client/view-transitions.test.browser.js +0 -53
  144. package/src/config/README.md +0 -58
  145. package/src/config/constants.d.ts +0 -1
  146. package/src/config/constants.js +0 -1
  147. package/src/dev/README.md +0 -61
  148. package/src/dev/invalidation/README.md +0 -11
  149. package/src/dev-toolbar/README.md +0 -66
  150. package/src/diagnostics/README.md +0 -11
  151. package/src/eco/README.md +0 -776
  152. package/src/errors/README.md +0 -5
  153. package/src/global/README.md +0 -5
  154. package/src/hmr/README.md +0 -64
  155. package/src/hmr/client/build-error-overlay.test.browser.d.ts +0 -1
  156. package/src/hmr/client/build-error-overlay.test.browser.js +0 -48
  157. package/src/hmr/client/hmr-runtime.test.browser.d.ts +0 -1
  158. package/src/hmr/client/hmr-runtime.test.browser.js +0 -32
  159. package/src/hmr/entrypoint-dependency-graph.d.ts +0 -12
  160. package/src/hmr/entrypoint-dependency-graph.js +0 -27
  161. package/src/hmr/hmr-file-change-prep.d.ts +0 -9
  162. package/src/hmr/hmr-file-change-prep.js +0 -11
  163. package/src/html/README.md +0 -15
  164. package/src/html-pages/README.md +0 -104
  165. package/src/islands/README.md +0 -44
  166. package/src/page-cache/README.md +0 -17
  167. package/src/plugins/README.md +0 -53
  168. package/src/route-renderer/GRAPH.md +0 -142
  169. package/src/route-renderer/README.md +0 -160
  170. package/src/route-renderer/error-pages/README.md +0 -11
  171. package/src/route-renderer/orchestration/custom-element-scripts/README.md +0 -15
  172. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.d.ts +0 -39
  173. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +0 -94
  174. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.d.ts +0 -35
  175. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.js +0 -69
  176. package/src/router/README.md +0 -160
  177. package/src/router/client/link-intent.test.browser.d.ts +0 -1
  178. package/src/router/client/link-intent.test.browser.js +0 -33
  179. package/src/router/client/link-navigation-policy.test.browser.d.ts +0 -1
  180. package/src/router/client/link-navigation-policy.test.browser.js +0 -142
  181. package/src/router/client/navigation-commit.test.browser.d.ts +0 -1
  182. package/src/router/client/navigation-commit.test.browser.js +0 -116
  183. package/src/router/client/navigation-document.test.browser.d.ts +0 -1
  184. package/src/router/client/navigation-document.test.browser.js +0 -77
  185. package/src/router/client/navigation-head.test.browser.d.ts +0 -1
  186. package/src/router/client/navigation-head.test.browser.js +0 -101
  187. package/src/router/client/navigation-lifecycle.test.browser.d.ts +0 -1
  188. package/src/router/client/navigation-lifecycle.test.browser.js +0 -97
  189. package/src/router/client/navigation-view-transition.test.browser.d.ts +0 -1
  190. package/src/router/client/navigation-view-transition.test.browser.js +0 -189
  191. package/src/router/client/staged-stylesheets.test-fixtures.d.ts +0 -18
  192. package/src/router/client/staged-stylesheets.test-fixtures.js +0 -31
  193. package/src/static-site-generator/README.md +0 -67
  194. package/src/static-site-generator/static-site-generator.test-utils.d.ts +0 -2
  195. package/src/static-site-generator/static-site-generator.test-utils.js +0 -41
  196. package/src/types/README.md +0 -5
  197. package/src/utils/README.md +0 -7
  198. package/src/validation/README.md +0 -9
  199. package/src/watchers/README.md +0 -15
  200. package/src/watchers/project-watcher.test-helpers.d.ts +0 -60
  201. package/src/watchers/project-watcher.test-helpers.js +0 -108
@@ -3,20 +3,10 @@ import type { ApiHandler, ApiHandlerContext, CacheInvalidator, ErrorHandler, Pag
3
3
  export type ApiRequestPipelineOptions = {
4
4
  getRenderContext: () => RenderContext;
5
5
  getCacheService: () => CacheInvalidator | null;
6
- /**
7
- * Recognises a client that disconnected mid-request.
8
- *
9
- * @remarks
10
- * Such errors are a normal browser behaviour, not a server fault, so
11
- * {@link ApiRequestPipeline.handleError} answers them with 499 without logging or
12
- * calling `app.onError`. Only the Node adapter supplies it.
13
- */
14
- isClientAbort?: (error: unknown) => boolean;
15
6
  };
16
7
  export declare class ApiRequestPipeline<TRequest extends Request = Request, TServer = unknown> {
17
8
  private readonly getRenderContext;
18
9
  private readonly getCacheService;
19
- private readonly isClientAbort;
20
10
  constructor(options: ApiRequestPipelineOptions);
21
11
  match(request: TRequest, apiHandlers: ApiHandler<string, TRequest, TServer>[], parsedPathSegments?: ParsedSegmentPath): {
22
12
  routeConfig: ApiHandler<string, TRequest, TServer>;
@@ -30,8 +20,9 @@ export declare class ApiRequestPipeline<TRequest extends Request = Request, TSer
30
20
  * @remarks
31
21
  * Precedence is a thrown `Response`, then a client abort (499), then the app
32
22
  * `onError` handler, then `HttpError.toResponse()`, then a logged plain 500.
33
- * Runtime adapters reuse this for errors that escape the whole request
34
- * pipeline so `app.onError` behaves the same on Bun and Node.
23
+ * A client abort is a browser leaving mid-request, not a server fault, so it
24
+ * is neither logged nor passed to `onError`. Runtime adapters reuse this for errors that escape the whole request
25
+ * pipeline so `app.onError` also covers them.
35
26
  */
36
27
  handleError(error: unknown, options: {
37
28
  request: TRequest;
@@ -4,16 +4,15 @@ import { ApiResponseBuilder } from './api-response.js';
4
4
  import { runMiddlewareChain } from './run-middleware-chain.js';
5
5
  import { matchParsedSegmentPath, parseSegmentPath, scoreSegmentPathPattern, } from '../../../router/server/segment-path-matcher.js';
6
6
  import { appLogger } from '../../../global/app-logger.js';
7
+ import { isNodeClientAbortError } from '../../node/http-request-bridge.js';
7
8
  import { validateRequest } from '../../../validation/validate-request.js';
8
9
  import { parseSearchParams } from '../../../router/server/parse-search-params.js';
9
10
  export class ApiRequestPipeline {
10
11
  getRenderContext;
11
12
  getCacheService;
12
- isClientAbort;
13
13
  constructor(options) {
14
14
  this.getRenderContext = options.getRenderContext;
15
15
  this.getCacheService = options.getCacheService;
16
- this.isClientAbort = options.isClientAbort ?? (() => false);
17
16
  }
18
17
  match(request, apiHandlers, parsedPathSegments) {
19
18
  const pathname = new URL(request.url).pathname;
@@ -67,13 +66,14 @@ export class ApiRequestPipeline {
67
66
  * @remarks
68
67
  * Precedence is a thrown `Response`, then a client abort (499), then the app
69
68
  * `onError` handler, then `HttpError.toResponse()`, then a logged plain 500.
70
- * Runtime adapters reuse this for errors that escape the whole request
71
- * pipeline so `app.onError` behaves the same on Bun and Node.
69
+ * A client abort is a browser leaving mid-request, not a server fault, so it
70
+ * is neither logged nor passed to `onError`. Runtime adapters reuse this for errors that escape the whole request
71
+ * pipeline so `app.onError` also covers them.
72
72
  */
73
73
  async handleError(error, options) {
74
74
  if (error instanceof Response)
75
75
  return error;
76
- if (this.isClientAbort(error))
76
+ if (isNodeClientAbortError(error))
77
77
  return new Response(null, { status: 499 });
78
78
  if (options.errorHandler) {
79
79
  try {
@@ -155,7 +155,7 @@ export class ApiRequestPipeline {
155
155
  return { value };
156
156
  }
157
157
  catch (error) {
158
- if (this.isClientAbort(error))
158
+ if (isNodeClientAbortError(error))
159
159
  throw error;
160
160
  return { response: responseBuilder.status(400).json({ error: 'Invalid request body' }) };
161
161
  }
@@ -168,7 +168,7 @@ export class ApiRequestPipeline {
168
168
  : { value: undefined };
169
169
  }
170
170
  catch (error) {
171
- if (this.isClientAbort(error))
171
+ if (isNodeClientAbortError(error))
172
172
  throw error;
173
173
  return { response: responseBuilder.status(400).json({ error: 'Invalid request body' }) };
174
174
  }
@@ -0,0 +1,16 @@
1
+ export type ServeDistFileOptions = {
2
+ distDir: string;
3
+ watchMode: boolean;
4
+ resolveExportedPages?: boolean;
5
+ staticFilesOnly?: boolean;
6
+ notFound?: (request: Request) => Response | Promise<Response>;
7
+ };
8
+ /**
9
+ * Serves one request from an application's emitted `dist` directory.
10
+ *
11
+ * @remarks
12
+ * The runtime fallback and static preview share path validation, file lookup, cache headers, ETags, and gzip
13
+ * negotiation. Callers provide their own 404 so runtime requests can render an error Page while preview reads
14
+ * the exported `404.html`.
15
+ */
16
+ export declare function serveDistFile(request: Request, options: ServeDistFileOptions): Promise<Response>;
@@ -0,0 +1,172 @@
1
+ import { STATUS_MESSAGE } from '../../../constants.js';
2
+ import { appLogger } from '../../../global/app-logger.js';
3
+ import { fileSystem } from '@ecopages/file-system';
4
+ import path from 'node:path';
5
+ import { HASHED_BROWSER_ASSET_INDEX_FILENAME, hashBrowserAssetBytes, isHashedBrowserAsset, } from '../../../assets/hashed-browser-asset.js';
6
+ import { ServerUtils } from '../../../utils/server-utils.module.js';
7
+ /**
8
+ * Serves one request from an application's emitted `dist` directory.
9
+ *
10
+ * @remarks
11
+ * The runtime fallback and static preview share path validation, file lookup, cache headers, ETags, and gzip
12
+ * negotiation. Callers provide their own 404 so runtime requests can render an error Page while preview reads
13
+ * the exported `404.html`.
14
+ */
15
+ export async function serveDistFile(request, options) {
16
+ const method = request.method.toUpperCase();
17
+ if (method !== 'GET' && method !== 'HEAD') {
18
+ return new Response(method === 'HEAD' ? null : 'Method Not Allowed', {
19
+ status: 405,
20
+ headers: { Allow: 'GET, HEAD', 'Content-Type': 'text/plain' },
21
+ });
22
+ }
23
+ const distDir = path.resolve(options.distDir);
24
+ const target = resolveRequestTarget(request, distDir);
25
+ if (!target) {
26
+ return createBadRequestResponse(method);
27
+ }
28
+ const candidate = findDistFile(target, options);
29
+ const response = candidate
30
+ ? await createDistFileResponse(candidate, ServerUtils.getContentType(candidate), request, options.watchMode)
31
+ : null;
32
+ if (!response) {
33
+ return await createNotFoundResponse(request, options, distDir, method);
34
+ }
35
+ return method === 'HEAD' ? responseWithoutBody(response) : response;
36
+ }
37
+ function resolveRequestTarget(request, distDir) {
38
+ let pathname;
39
+ try {
40
+ pathname = decodeURIComponent(new URL(request.url).pathname);
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ const relativePath = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
46
+ const requestedPath = path.resolve(distDir, relativePath);
47
+ return isPathInside(distDir, requestedPath) ? { pathname, requestedPath } : undefined;
48
+ }
49
+ function findDistFile({ pathname, requestedPath }, options) {
50
+ if (options.staticFilesOnly && !ServerUtils.hasKnownStaticExtension(pathname)) {
51
+ return undefined;
52
+ }
53
+ const candidate = options.resolveExportedPages
54
+ ? ServerUtils.resolveStaticFilePath(requestedPath)
55
+ : fileSystem.exists(requestedPath) && !fileSystem.isDirectory(requestedPath)
56
+ ? requestedPath
57
+ : undefined;
58
+ return candidate && path.basename(candidate) !== HASHED_BROWSER_ASSET_INDEX_FILENAME ? candidate : undefined;
59
+ }
60
+ async function createNotFoundResponse(request, options, distDir, method) {
61
+ const response = options.notFound
62
+ ? await options.notFound(request)
63
+ : await createDistNotFoundResponse(request, distDir);
64
+ return method === 'HEAD' ? responseWithoutBody(response) : response;
65
+ }
66
+ function isPathInside(root, candidate) {
67
+ const relativePath = path.relative(root, candidate);
68
+ return relativePath !== '..' && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
69
+ }
70
+ function createBadRequestResponse(method) {
71
+ return new Response(method === 'HEAD' ? null : 'Invalid path', {
72
+ status: 400,
73
+ headers: { 'Content-Type': 'text/plain' },
74
+ });
75
+ }
76
+ async function createDistNotFoundResponse(request, distDir) {
77
+ const notFoundPath = path.join(distDir, '404.html');
78
+ if (fileSystem.exists(notFoundPath) && !fileSystem.isDirectory(notFoundPath)) {
79
+ const body = request.method === 'HEAD' ? null : fileSystem.readFileAsBuffer(notFoundPath);
80
+ return new Response(body, {
81
+ status: 404,
82
+ headers: { 'Content-Type': 'text/html' },
83
+ });
84
+ }
85
+ return new Response(request.method === 'HEAD' ? null : STATUS_MESSAGE[404], {
86
+ status: 404,
87
+ headers: { 'Content-Type': 'text/plain' },
88
+ });
89
+ }
90
+ async function createDistFileResponse(filePath, contentType, request, watchMode) {
91
+ try {
92
+ const gzipPath = `${filePath}.gz`;
93
+ const gzipEligible = !watchMode && (contentType === 'text/javascript' || contentType === 'text/css');
94
+ const hasGzipVariant = gzipEligible && fileSystem.exists(gzipPath);
95
+ const useGzip = hasGzipVariant && acceptsGzip(request.headers.get('Accept-Encoding'));
96
+ const file = fileSystem.readFileAsBuffer(useGzip ? gzipPath : filePath);
97
+ const cacheHeaders = fileCacheHeaders(filePath, file, watchMode);
98
+ const headers = new Headers({
99
+ 'Content-Type': contentType,
100
+ ...cacheHeaders,
101
+ ...(useGzip ? { 'Content-Encoding': 'gzip' } : {}),
102
+ ...(hasGzipVariant ? { Vary: 'Accept-Encoding' } : {}),
103
+ });
104
+ if (matchesIfNoneMatch(request.headers.get('If-None-Match'), cacheHeaders.ETag)) {
105
+ return new Response(null, { status: 304, headers });
106
+ }
107
+ return new Response(file, { headers });
108
+ }
109
+ catch (error) {
110
+ const errorDetails = error instanceof Error ? error : new Error(String(error));
111
+ const errorCode = getErrorCode(error);
112
+ if (errorCode === 'ENOENT') {
113
+ appLogger.debug('File not found', filePath);
114
+ }
115
+ else {
116
+ appLogger.error('Error reading file', filePath, errorDetails);
117
+ }
118
+ return null;
119
+ }
120
+ }
121
+ function getErrorCode(error) {
122
+ if (typeof error !== 'object' || error === null)
123
+ return undefined;
124
+ const maybeError = error;
125
+ if (typeof maybeError.code === 'string')
126
+ return maybeError.code;
127
+ if (typeof maybeError.cause === 'object' && maybeError.cause !== null) {
128
+ const causeCode = maybeError.cause.code;
129
+ if (typeof causeCode === 'string')
130
+ return causeCode;
131
+ }
132
+ return undefined;
133
+ }
134
+ function responseWithoutBody(response) {
135
+ return new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers });
136
+ }
137
+ function fileCacheHeaders(filePath, file, watchMode) {
138
+ const etag = `"${hashBrowserAssetBytes(file)}"`;
139
+ const extension = path.extname(filePath).toLowerCase();
140
+ if (extension === '.html') {
141
+ return { 'Cache-Control': 'public, max-age=0, must-revalidate', ETag: etag };
142
+ }
143
+ if (watchMode) {
144
+ return { 'Cache-Control': 'no-cache', ETag: etag };
145
+ }
146
+ if (isHashedBrowserAsset(filePath)) {
147
+ return { 'Cache-Control': 'public, max-age=31536000, immutable', ETag: etag };
148
+ }
149
+ return { 'Cache-Control': 'public, max-age=0, must-revalidate', ETag: etag };
150
+ }
151
+ function acceptsGzip(acceptEncoding) {
152
+ const encodings = (acceptEncoding ?? '').split(',').map((value) => {
153
+ const [encoding, ...parameters] = value.trim().toLowerCase().split(';');
154
+ const quality = parameters
155
+ .find((parameter) => parameter.trim().startsWith('q='))
156
+ ?.trim()
157
+ .slice(2);
158
+ return { encoding, quality };
159
+ });
160
+ const explicitGzip = encodings.find(({ encoding }) => encoding === 'gzip');
161
+ const selectedEncoding = explicitGzip ?? encodings.find(({ encoding }) => encoding === '*');
162
+ return (selectedEncoding !== undefined &&
163
+ (selectedEncoding.quality === undefined || Number(selectedEncoding.quality) > 0));
164
+ }
165
+ function matchesIfNoneMatch(ifNoneMatch, etag) {
166
+ if (!ifNoneMatch)
167
+ return false;
168
+ return ifNoneMatch.split(',').some((value) => {
169
+ const candidate = value.trim();
170
+ return candidate === '*' || candidate === etag || candidate === `W/${etag}`;
171
+ });
172
+ }
@@ -1,5 +1,6 @@
1
1
  import { appLogger } from '../../../global/app-logger.js';
2
2
  import { requireAppRuntime } from '../../../utils/app-runtime.js';
3
+ import { formatErrorChain } from '../../../utils/format-error-chain.js';
3
4
  import { shouldLogPageFailure } from '../../../errors/http-error-page-contract.js';
4
5
  import { prepareExplicitStaticRender } from '../../../route-renderer/explicit-view-render-preparation.js';
5
6
  import { matchParsedSegmentPath, parseSegmentPath, } from '../../../router/server/segment-path-matcher.js';
@@ -55,7 +56,7 @@ export class ExplicitStaticRouteMatcher {
55
56
  }
56
57
  catch (error) {
57
58
  if (shouldLogPageFailure(error)) {
58
- appLogger.error(`Error rendering explicit static route ${route.path}:`, error instanceof Error ? error : String(error));
59
+ appLogger.error(`Error rendering explicit static route ${route.path}:`, formatErrorChain(error));
59
60
  }
60
61
  throw error;
61
62
  }
@@ -3,6 +3,7 @@ import { PageRequestCacheCoordinator } from '../../../page-cache/page-request-ca
3
3
  import { FileRouteMiddlewarePipeline } from './file-route-middleware-pipeline.js';
4
4
  import { classifyPageFailure } from '../../../errors/http-error-page-contract.js';
5
5
  import { isDevelopmentRuntime } from '../../../utils/runtime.js';
6
+ import { formatErrorChain } from '../../../utils/format-error-chain.js';
6
7
  import { ErrorPageRenderer, logErrorPageFailure } from '../../../route-renderer/error-pages/error-page-renderer.js';
7
8
  import { serveDistFile } from './dist-file-handler.js';
8
9
  import { requireAppRuntime } from '../../../utils/app-runtime.js';
@@ -166,10 +167,10 @@ export class FileSystemResponseMatcher {
166
167
  async createServerErrorResponse(pathname, classification, error) {
167
168
  const message = error instanceof Error ? error.message : 'Internal Server Error';
168
169
  if (isDevelopmentRuntime() || appLogger.isDebugEnabled()) {
169
- appLogger.error(`[FileSystemResponseMatcher] ${message} at ${pathname}`, error);
170
+ appLogger.error(`[FileSystemResponseMatcher] ${message} at ${pathname}`, formatErrorChain(error));
170
171
  }
171
172
  else {
172
- appLogger.error(`[FileSystemResponseMatcher] Render error at ${pathname}`, error);
173
+ appLogger.error(`[FileSystemResponseMatcher] Render error at ${pathname}`, formatErrorChain(error));
173
174
  }
174
175
  try {
175
176
  return await this.renderErrorResponse(classification, error);
@@ -1,17 +1,15 @@
1
- import type { RuntimeHost, RuntimeHostStartOptions } from './runtime-host.js';
1
+ import type { Server as NodeHttpServer } from 'node:http';
2
+ import type { NodeRuntimeServeOptions, RuntimeHost } from '../../node/runtime-host.js';
2
3
  /**
3
4
  * Starts a runtime server, optionally negotiating a fallback port via
4
5
  * {@link PortManager}.
5
6
  */
6
- export declare function bindRuntimeServer<TServer, TServeOptions extends {
7
- port?: number | string;
8
- hostname?: string;
9
- }>(runtimeHost: RuntimeHost<TServer, TServeOptions>, options: {
10
- startOptions: RuntimeHostStartOptions<TServeOptions>;
7
+ export declare function bindRuntimeServer(runtimeHost: RuntimeHost, options: {
8
+ serveOptions: NodeRuntimeServeOptions;
11
9
  allowPortFallback: boolean;
12
10
  usePortManager: boolean;
13
11
  }): Promise<{
14
- server: TServer;
12
+ server: NodeHttpServer;
15
13
  port: number;
16
14
  runtimeOrigin: string;
17
15
  }>;
@@ -1,14 +1,15 @@
1
- import { PortManager } from './port-manager.js';
1
+ import { DEFAULT_ECOPAGES_HOSTNAME } from '../../../constants.js';
2
+ import { isPortAvailable, PortManager } from './port-manager.js';
2
3
  import { appLogger } from '../../../global/app-logger.js';
3
4
  /**
4
5
  * Starts a runtime server, optionally negotiating a fallback port via
5
6
  * {@link PortManager}.
6
7
  */
7
8
  export async function bindRuntimeServer(runtimeHost, options) {
8
- const preferredPort = Number(options.startOptions.serveOptions.port);
9
+ const preferredPort = Number(options.serveOptions.port);
9
10
  if (!options.usePortManager) {
10
- const server = await runtimeHost.start(options.startOptions);
11
- const runtimeOrigin = runtimeHost.getOrigin(server, options.startOptions.serveOptions);
11
+ const server = await runtimeHost.start(options.serveOptions);
12
+ const runtimeOrigin = runtimeHost.getOrigin(server, options.serveOptions);
12
13
  return {
13
14
  server,
14
15
  port: Number(new URL(runtimeOrigin).port || preferredPort),
@@ -19,20 +20,15 @@ export async function bindRuntimeServer(runtimeHost, options) {
19
20
  let activeRuntimeOrigin;
20
21
  const portManager = new PortManager({
21
22
  startOnPort: async (port) => {
22
- const serveOptions = {
23
- ...options.startOptions.serveOptions,
24
- port,
25
- };
26
- const server = await runtimeHost.start({
27
- ...options.startOptions,
28
- serveOptions,
29
- });
23
+ const serveOptions = { ...options.serveOptions, port };
24
+ const server = await runtimeHost.start(serveOptions);
30
25
  const runtimeOrigin = runtimeHost.getOrigin(server, serveOptions);
31
26
  const boundPort = Number(new URL(runtimeOrigin).port || port);
32
27
  activeServer = server;
33
28
  activeRuntimeOrigin = runtimeOrigin;
34
29
  return boundPort;
35
30
  },
31
+ probePort: (port) => isPortAvailable(port, options.serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME),
36
32
  warn: (message) => appLogger.warn(message),
37
33
  });
38
34
  const boundPort = await portManager.bind({
@@ -1,9 +1,8 @@
1
- import { lstatSync, readdirSync, readlinkSync } from 'node:fs';
2
1
  import path from 'node:path';
3
2
  import { fileSystem } from '@ecopages/file-system';
4
3
  function tryLstat(filePath) {
5
4
  try {
6
- return lstatSync(filePath);
5
+ return fileSystem.lstat(filePath);
7
6
  }
8
7
  catch (error) {
9
8
  if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
@@ -17,7 +16,7 @@ export function copyRuntimePublicFileIfChanged(sourcePath, destinationPath) {
17
16
  return;
18
17
  }
19
18
  fileSystem.ensureDir(path.dirname(destinationPath));
20
- const destinationIsSymbolicLink = tryLstat(destinationPath)?.isSymbolicLink() ?? false;
19
+ const destinationIsSymbolicLink = tryLstat(destinationPath)?.isSymbolicLink ?? false;
21
20
  if (destinationIsSymbolicLink) {
22
21
  fileSystem.remove(destinationPath);
23
22
  }
@@ -42,18 +41,20 @@ export async function copyRuntimePublicFile(sourcePath, destinationPath) {
42
41
  */
43
42
  export function copyRuntimePublicDirIfChanged(sourceDir, destinationDir) {
44
43
  fileSystem.ensureDir(destinationDir);
45
- for (const entry of readdirSync(sourceDir, { withFileTypes: true })) {
44
+ for (const entry of fileSystem.readdir(sourceDir)) {
46
45
  const sourcePath = path.join(sourceDir, entry.name);
47
46
  const destinationPath = path.join(destinationDir, entry.name);
48
- if (entry.isDirectory()) {
47
+ if (entry.isDirectory) {
49
48
  copyRuntimePublicDirIfChanged(sourcePath, destinationPath);
50
49
  continue;
51
50
  }
52
- if (entry.isSymbolicLink()) {
53
- const sourceTarget = readlinkSync(sourcePath);
51
+ if (entry.isSymbolicLink) {
52
+ const sourceTarget = fileSystem.readlink(sourcePath);
54
53
  const destinationStats = tryLstat(destinationPath);
55
54
  const destinationExists = destinationStats !== undefined;
56
- const destinationTarget = destinationStats?.isSymbolicLink() ? readlinkSync(destinationPath) : undefined;
55
+ const destinationTarget = destinationStats?.isSymbolicLink
56
+ ? fileSystem.readlink(destinationPath)
57
+ : undefined;
57
58
  if (sourceTarget === destinationTarget) {
58
59
  continue;
59
60
  }
@@ -63,7 +64,7 @@ export function copyRuntimePublicDirIfChanged(sourceDir, destinationDir) {
63
64
  fileSystem.copyFile(sourcePath, destinationPath);
64
65
  continue;
65
66
  }
66
- if (!entry.isFile()) {
67
+ if (!entry.isFile) {
67
68
  continue;
68
69
  }
69
70
  copyRuntimePublicFileIfChanged(sourcePath, destinationPath);
@@ -1,21 +1,18 @@
1
1
  /**
2
- * Detects whether a thrown error indicates the requested port is already in
3
- * use.
4
- *
5
- * @remarks
6
- * Matches Node's `code: 'EADDRINUSE'` and Bun's surface, where the error
7
- * carries the same `code` plus a human-readable message such as
8
- * `"Failed to start server. Is port 3000 in use?"`. Older Bun builds that do
9
- * not set `.code` are covered by a fallback match on `syscall === 'listen'`
10
- * plus the message shape.
2
+ * Detects the error Node raises when `listen()` targets a port that is already in use.
11
3
  */
12
4
  export declare function isPortInUseError(error: unknown): boolean;
13
5
  /**
14
6
  * Probes whether a TCP port is currently bindable from this process. Uses a
15
- * short-lived Node `net.Server` so both Node and Bun can run it via their
16
- * Node-compatible core.
7
+ * short-lived Node `net.Server`.
17
8
  *
18
9
  * @remarks
10
+ * `hostname` is resolved to a single address first and the probe binds that
11
+ * address, mirroring what the server bind does. Passing the hostname straight
12
+ * to `listen()` makes some runtimes (Bun) try every resolved address, so a
13
+ * taken port can be reported as free. A hostname that does not resolve reports
14
+ * the port as unavailable.
15
+ *
19
16
  * A successful probe only guarantees the port was free at probe time; callers
20
17
  * must still handle EADDRINUSE when they actually bind, since release races
21
18
  * can flip the answer between probe and bind.
@@ -1,56 +1,45 @@
1
+ import { lookup } from 'node:dns/promises';
1
2
  import { createServer as createNetServer } from 'node:net';
2
3
  import { createClackDefaultPrompt } from './port-manager-default-prompt.js';
3
4
  /**
4
- * Detects whether a thrown error indicates the requested port is already in
5
- * use.
6
- *
7
- * @remarks
8
- * Matches Node's `code: 'EADDRINUSE'` and Bun's surface, where the error
9
- * carries the same `code` plus a human-readable message such as
10
- * `"Failed to start server. Is port 3000 in use?"`. Older Bun builds that do
11
- * not set `.code` are covered by a fallback match on `syscall === 'listen'`
12
- * plus the message shape.
5
+ * Detects the error Node raises when `listen()` targets a port that is already in use.
13
6
  */
14
7
  export function isPortInUseError(error) {
15
- if (!(error instanceof Error) && (typeof error !== 'object' || error === null)) {
16
- return false;
17
- }
18
- const maybeErr = error;
19
- const code = typeof maybeErr.code === 'string' || typeof maybeErr.code === 'number' ? String(maybeErr.code) : undefined;
20
- const syscall = typeof maybeErr.syscall === 'string' ? maybeErr.syscall : undefined;
21
- const message = error instanceof Error ? error.message : String(maybeErr.message ?? '');
22
- if (code === 'EADDRINUSE') {
23
- return true;
24
- }
25
- if (message.includes('EADDRINUSE')) {
26
- return true;
27
- }
28
- if (syscall === 'listen' && /is port \d+ in use\??/i.test(message)) {
29
- return true;
30
- }
31
- return false;
8
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'EADDRINUSE';
32
9
  }
33
10
  function sleep(ms) {
34
11
  return new Promise((resolve) => setTimeout(resolve, ms));
35
12
  }
36
13
  /**
37
14
  * Probes whether a TCP port is currently bindable from this process. Uses a
38
- * short-lived Node `net.Server` so both Node and Bun can run it via their
39
- * Node-compatible core.
15
+ * short-lived Node `net.Server`.
40
16
  *
41
17
  * @remarks
18
+ * `hostname` is resolved to a single address first and the probe binds that
19
+ * address, mirroring what the server bind does. Passing the hostname straight
20
+ * to `listen()` makes some runtimes (Bun) try every resolved address, so a
21
+ * taken port can be reported as free. A hostname that does not resolve reports
22
+ * the port as unavailable.
23
+ *
42
24
  * A successful probe only guarantees the port was free at probe time; callers
43
25
  * must still handle EADDRINUSE when they actually bind, since release races
44
26
  * can flip the answer between probe and bind.
45
27
  */
46
- export function isPortAvailable(port, hostname = '127.0.0.1') {
28
+ export async function isPortAvailable(port, hostname = '127.0.0.1') {
29
+ let address;
30
+ try {
31
+ ({ address } = await lookup(hostname));
32
+ }
33
+ catch {
34
+ return false;
35
+ }
47
36
  return new Promise((resolve) => {
48
37
  const tester = createNetServer();
49
38
  tester.once('error', () => resolve(false));
50
39
  tester.once('listening', () => {
51
40
  tester.close(() => resolve(true));
52
41
  });
53
- tester.listen(port, hostname);
42
+ tester.listen(port, address);
54
43
  });
55
44
  }
56
45
  const PORT_RELEASE_RACE_RETRIES = 2;
@@ -25,21 +25,18 @@ export declare function startDevWarmup(options: {
25
25
  appConfig: EcoPagesAppConfig;
26
26
  }): Promise<void>;
27
27
  /**
28
- * Releases shared dev resources in a consistent order across server adapters.
28
+ * Closes the watch-mode resources, then tears the activated Integrations down.
29
29
  *
30
30
  * @remarks
31
- * Bun calls `ensureRuntimeReady()` during `initialize()` when watch is enabled; Node defers
32
- * runtime creation to `completeInitialization()`. Transport-specific setup stays in
33
- * each adapter — only shared teardown lives here. Integration `setup()` calls still in flight
31
+ * A server that never ran a `DevSession` passes only `appConfig`. Integration `setup()` calls still in flight
34
32
  * settle before any `teardown()`, so a late setup cannot recreate released resources. A failed
35
33
  * integration `teardown()` still clears activation state, so the next startup runs `setup()` again.
36
34
  */
37
35
  export declare function disposeDevResources(options: {
38
- projectWatcher: ProjectWatcher | null | undefined;
39
36
  appConfig: EcoPagesAppConfig;
40
- hmrManager?: IHmrManager | null | undefined;
41
- bridge: {
37
+ projectWatcher?: ProjectWatcher;
38
+ hmrManager?: IHmrManager;
39
+ bridge?: {
42
40
  destroy(): void;
43
- } | null | undefined;
44
- stopPreviewServer: () => Promise<void>;
41
+ };
45
42
  }): Promise<void>;
@@ -56,12 +56,10 @@ export async function startDevWarmup(options) {
56
56
  }
57
57
  }
58
58
  /**
59
- * Releases shared dev resources in a consistent order across server adapters.
59
+ * Closes the watch-mode resources, then tears the activated Integrations down.
60
60
  *
61
61
  * @remarks
62
- * Bun calls `ensureRuntimeReady()` during `initialize()` when watch is enabled; Node defers
63
- * runtime creation to `completeInitialization()`. Transport-specific setup stays in
64
- * each adapter — only shared teardown lives here. Integration `setup()` calls still in flight
62
+ * A server that never ran a `DevSession` passes only `appConfig`. Integration `setup()` calls still in flight
65
63
  * settle before any `teardown()`, so a late setup cannot recreate released resources. A failed
66
64
  * integration `teardown()` still clears activation state, so the next startup runs `setup()` again.
67
65
  */
@@ -72,7 +70,6 @@ export async function disposeDevResources(options) {
72
70
  () => options.projectWatcher?.close(),
73
71
  () => hmrManager?.stop(),
74
72
  () => options.bridge?.destroy(),
75
- options.stopPreviewServer,
76
73
  () => teardownAppRuntimeIntegrations({ appConfig: options.appConfig }),
77
74
  ];
78
75
  const errors = [];
@@ -16,13 +16,11 @@ export type ServerRequestPipelineOptions = {
16
16
  appConfig: EcoPagesAppConfig;
17
17
  runtime: AppRuntime;
18
18
  watch?: boolean;
19
- isClientAbortError?: (error: unknown) => boolean;
20
19
  };
21
20
  export declare class ServerRequestPipeline {
22
21
  protected readonly appConfig: EcoPagesAppConfig;
23
22
  protected readonly runtime: AppRuntime;
24
23
  private readonly watchMode;
25
- private clientAbortDetector;
26
24
  protected router: RouteRegistry;
27
25
  protected fileSystemResponseMatcher: FileSystemResponseMatcher;
28
26
  protected routeRendererFactory: RouteRendererFactory;
@@ -46,7 +44,7 @@ export declare class ServerRequestPipeline {
46
44
  /**
47
45
  * Scans the filesystem and dynamically constructs the Route Registry.
48
46
  *
49
- * This process runs identically across both Bun and Node wrappers. It analyzes the configured pages
47
+ * It analyzes the configured pages
50
48
  * directory, building a map of all available UI routes and API endpoints.
51
49
  * The resulting `RouteRegistry` instance becomes the central nervous system for mapping WinterCG incoming
52
50
  * Web Requests (`Request`) to their corresponding internal execution paths.