@ecopages/core 0.3.0 → 0.3.1

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 (176) hide show
  1. package/README.md +2 -2
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +29 -11
  4. package/src/adapters/node/create-app.js +78 -67
  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 +23 -6
  9. package/src/adapters/node/runtime-host.js +27 -8
  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 +9 -5
  13. package/src/adapters/shared/hmr/hmr-manager.js +38 -54
  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 +5 -11
  22. package/src/adapters/shared/runtime/port-manager.d.ts +2 -11
  23. package/src/adapters/shared/runtime/port-manager.js +3 -28
  24. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +6 -9
  25. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +2 -5
  26. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +1 -3
  27. package/src/adapters/shared/runtime/server-request-pipeline.js +1 -5
  28. package/src/adapters/shared/runtime/server-static-builder.d.ts +3 -3
  29. package/src/adapters/shared/runtime/server-static-builder.js +3 -3
  30. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +2 -1
  31. package/src/adapters/shared/ws/websocket-lifecycle.d.ts +5 -6
  32. package/src/adapters/shared/ws/websocket-lifecycle.js +1 -2
  33. package/src/build/build-adapter.d.ts +2 -19
  34. package/src/build/build-adapter.js +0 -21
  35. package/src/build/cache/cache-keys.d.ts +0 -3
  36. package/src/build/cache/cache-keys.js +0 -14
  37. package/src/build/cache/pages-unified-graph-build.js +2 -17
  38. package/src/build/contracts/build-contracts.d.ts +0 -3
  39. package/src/build/rolldown/rolldown-build-adapter.d.ts +0 -1
  40. package/src/build/rolldown/rolldown-build-adapter.js +1 -2
  41. package/src/build/rolldown/rolldown-build-invocation-metrics.d.ts +1 -2
  42. package/src/build/rolldown/rolldown-build-invocation-metrics.js +5 -12
  43. package/src/build/runtime/build-queue.d.ts +8 -13
  44. package/src/build/runtime/build-queue.js +6 -17
  45. package/src/build/server/app-module-loader.service.d.ts +1 -1
  46. package/src/build/server/app-module-loader.service.js +0 -2
  47. package/src/build/server/page-module-import.service.d.ts +2 -3
  48. package/src/build/server/page-module-import.service.js +3 -4
  49. package/src/build/server-bundle-deploy-manifest.d.ts +5 -0
  50. package/src/build/server-bundle-deploy-manifest.js +15 -1
  51. package/src/build.d.ts +2 -2
  52. package/src/build.js +2 -2
  53. package/src/config/assembly/app-runtime.d.ts +2 -2
  54. package/src/config/assembly/app-runtime.js +2 -2
  55. package/src/config/assembly/finalize-config.d.ts +4 -4
  56. package/src/config/assembly/finalize-config.js +4 -5
  57. package/src/config/internal-types.d.ts +0 -7
  58. package/src/config/user-config-types.d.ts +0 -4
  59. package/src/diagnostics/request-pipeline-metrics.d.ts +3 -3
  60. package/src/diagnostics/request-pipeline-metrics.js +4 -4
  61. package/src/errors/http-error.d.ts +2 -2
  62. package/src/errors/http-error.js +4 -4
  63. package/src/hmr/client/hmr-runtime.js +16 -7
  64. package/src/hmr/client/module-update.d.ts +7 -0
  65. package/src/hmr/client/module-update.js +21 -4
  66. package/src/hmr/hmr-strategy.d.ts +0 -3
  67. package/src/hmr/hmr-strategy.js +0 -3
  68. package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -3
  69. package/src/hmr/strategies/js-hmr-strategy.js +3 -6
  70. package/src/plugins/alias-resolver-cache.d.ts +4 -3
  71. package/src/plugins/alias-resolver-cache.js +4 -3
  72. package/src/plugins/eco-component-meta-plugin.d.ts +10 -1
  73. package/src/plugins/eco-component-meta-plugin.js +66 -10
  74. package/src/plugins/foreign-jsx-override-plugin.js +2 -1
  75. package/src/route-renderer/error-pages/default-error-pages.js +2 -1
  76. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -1
  77. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +0 -1
  78. package/src/route-renderer/orchestration/integration-renderer.d.ts +10 -5
  79. package/src/route-renderer/orchestration/integration-renderer.js +13 -14
  80. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -6
  81. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -6
  82. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +10 -32
  83. package/src/route-renderer/page-loading/page-module-loader.js +1 -1
  84. package/src/route-renderer/route-renderer.d.ts +2 -5
  85. package/src/route-renderer/route-renderer.js +2 -4
  86. package/src/router/client/link-navigation-policy.d.ts +4 -1
  87. package/src/router/client/link-navigation-policy.js +20 -6
  88. package/src/router/server/route-registry.d.ts +0 -1
  89. package/src/router/server/route-registry.js +2 -11
  90. package/src/router/server/segment-path-matcher.d.ts +12 -0
  91. package/src/router/server/segment-path-matcher.js +30 -0
  92. package/src/static-site-generator/static-site-generator.d.ts +0 -5
  93. package/src/static-site-generator/static-site-generator.js +2 -15
  94. package/src/types/contracts.d.ts +17 -27
  95. package/src/types/public-types.d.ts +1 -1
  96. package/src/utils/format-error-chain.d.ts +9 -0
  97. package/src/utils/format-error-chain.js +20 -0
  98. package/src/utils/invariant.d.ts +6 -1
  99. package/src/utils/invariant.js +7 -2
  100. package/src/watchers/project-watcher.d.ts +20 -1
  101. package/src/watchers/project-watcher.js +40 -9
  102. package/src/watchers/workspace-package-watch-roots.js +5 -5
  103. package/src/adapters/README.md +0 -58
  104. package/src/adapters/shared/hmr/hmr-manager.test-helpers.d.ts +0 -28
  105. package/src/adapters/shared/hmr/hmr-manager.test-helpers.js +0 -53
  106. package/src/adapters/shared/runtime/runtime-host.d.ts +0 -15
  107. package/src/adapters/shared/runtime/runtime-host.js +0 -1
  108. package/src/assets/README.md +0 -35
  109. package/src/build/README.md +0 -298
  110. package/src/build/server/README.md +0 -50
  111. package/src/cache/README.md +0 -5
  112. package/src/client/README.md +0 -5
  113. package/src/client/navigation-scripts/navigation-scripts.test.browser.d.ts +0 -1
  114. package/src/client/navigation-scripts/navigation-scripts.test.browser.js +0 -111
  115. package/src/client/scroll.test.browser.d.ts +0 -1
  116. package/src/client/scroll.test.browser.js +0 -31
  117. package/src/client/view-transitions.test.browser.d.ts +0 -1
  118. package/src/client/view-transitions.test.browser.js +0 -53
  119. package/src/config/README.md +0 -58
  120. package/src/config/constants.d.ts +0 -1
  121. package/src/config/constants.js +0 -1
  122. package/src/dev/README.md +0 -61
  123. package/src/dev/invalidation/README.md +0 -11
  124. package/src/dev-toolbar/README.md +0 -66
  125. package/src/diagnostics/README.md +0 -11
  126. package/src/eco/README.md +0 -776
  127. package/src/errors/README.md +0 -5
  128. package/src/global/README.md +0 -5
  129. package/src/hmr/README.md +0 -64
  130. package/src/hmr/client/build-error-overlay.test.browser.d.ts +0 -1
  131. package/src/hmr/client/build-error-overlay.test.browser.js +0 -48
  132. package/src/hmr/client/hmr-runtime.test.browser.d.ts +0 -1
  133. package/src/hmr/client/hmr-runtime.test.browser.js +0 -32
  134. package/src/hmr/entrypoint-dependency-graph.d.ts +0 -12
  135. package/src/hmr/entrypoint-dependency-graph.js +0 -27
  136. package/src/hmr/hmr-file-change-prep.d.ts +0 -9
  137. package/src/hmr/hmr-file-change-prep.js +0 -11
  138. package/src/html/README.md +0 -15
  139. package/src/html-pages/README.md +0 -104
  140. package/src/islands/README.md +0 -44
  141. package/src/page-cache/README.md +0 -17
  142. package/src/plugins/README.md +0 -53
  143. package/src/route-renderer/GRAPH.md +0 -142
  144. package/src/route-renderer/README.md +0 -160
  145. package/src/route-renderer/error-pages/README.md +0 -11
  146. package/src/route-renderer/orchestration/custom-element-scripts/README.md +0 -15
  147. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.d.ts +0 -39
  148. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +0 -94
  149. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.d.ts +0 -35
  150. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.js +0 -69
  151. package/src/router/README.md +0 -160
  152. package/src/router/client/link-intent.test.browser.d.ts +0 -1
  153. package/src/router/client/link-intent.test.browser.js +0 -33
  154. package/src/router/client/link-navigation-policy.test.browser.d.ts +0 -1
  155. package/src/router/client/link-navigation-policy.test.browser.js +0 -142
  156. package/src/router/client/navigation-commit.test.browser.d.ts +0 -1
  157. package/src/router/client/navigation-commit.test.browser.js +0 -116
  158. package/src/router/client/navigation-document.test.browser.d.ts +0 -1
  159. package/src/router/client/navigation-document.test.browser.js +0 -77
  160. package/src/router/client/navigation-head.test.browser.d.ts +0 -1
  161. package/src/router/client/navigation-head.test.browser.js +0 -101
  162. package/src/router/client/navigation-lifecycle.test.browser.d.ts +0 -1
  163. package/src/router/client/navigation-lifecycle.test.browser.js +0 -97
  164. package/src/router/client/navigation-view-transition.test.browser.d.ts +0 -1
  165. package/src/router/client/navigation-view-transition.test.browser.js +0 -189
  166. package/src/router/client/staged-stylesheets.test-fixtures.d.ts +0 -18
  167. package/src/router/client/staged-stylesheets.test-fixtures.js +0 -31
  168. package/src/static-site-generator/README.md +0 -67
  169. package/src/static-site-generator/static-site-generator.test-utils.d.ts +0 -2
  170. package/src/static-site-generator/static-site-generator.test-utils.js +0 -41
  171. package/src/types/README.md +0 -5
  172. package/src/utils/README.md +0 -7
  173. package/src/validation/README.md +0 -9
  174. package/src/watchers/README.md +0 -15
  175. package/src/watchers/project-watcher.test-helpers.d.ts +0 -60
  176. package/src/watchers/project-watcher.test-helpers.js +0 -108
@@ -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
  }>;
@@ -5,10 +5,10 @@ import { appLogger } from '../../../global/app-logger.js';
5
5
  * {@link PortManager}.
6
6
  */
7
7
  export async function bindRuntimeServer(runtimeHost, options) {
8
- const preferredPort = Number(options.startOptions.serveOptions.port);
8
+ const preferredPort = Number(options.serveOptions.port);
9
9
  if (!options.usePortManager) {
10
- const server = await runtimeHost.start(options.startOptions);
11
- const runtimeOrigin = runtimeHost.getOrigin(server, options.startOptions.serveOptions);
10
+ const server = await runtimeHost.start(options.serveOptions);
11
+ const runtimeOrigin = runtimeHost.getOrigin(server, options.serveOptions);
12
12
  return {
13
13
  server,
14
14
  port: Number(new URL(runtimeOrigin).port || preferredPort),
@@ -19,14 +19,8 @@ export async function bindRuntimeServer(runtimeHost, options) {
19
19
  let activeRuntimeOrigin;
20
20
  const portManager = new PortManager({
21
21
  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
- });
22
+ const serveOptions = { ...options.serveOptions, port };
23
+ const server = await runtimeHost.start(serveOptions);
30
24
  const runtimeOrigin = runtimeHost.getOrigin(server, serveOptions);
31
25
  const boundPort = Number(new URL(runtimeOrigin).port || port);
32
26
  activeServer = server;
@@ -1,19 +1,10 @@
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
19
10
  * A successful probe only guarantees the port was free at probe time; callers
@@ -1,42 +1,17 @@
1
1
  import { createServer as createNetServer } from 'node:net';
2
2
  import { createClackDefaultPrompt } from './port-manager-default-prompt.js';
3
3
  /**
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.
4
+ * Detects the error Node raises when `listen()` targets a port that is already in use.
13
5
  */
14
6
  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;
7
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'EADDRINUSE';
32
8
  }
33
9
  function sleep(ms) {
34
10
  return new Promise((resolve) => setTimeout(resolve, ms));
35
11
  }
36
12
  /**
37
13
  * 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.
14
+ * short-lived Node `net.Server`.
40
15
  *
41
16
  * @remarks
42
17
  * A successful probe only guarantees the port was free at probe time; callers
@@ -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.
@@ -21,7 +21,6 @@ export class ServerRequestPipeline {
21
21
  appConfig;
22
22
  runtime;
23
23
  watchMode;
24
- clientAbortDetector = () => false;
25
24
  router;
26
25
  fileSystemResponseMatcher;
27
26
  routeRendererFactory;
@@ -29,14 +28,12 @@ export class ServerRequestPipeline {
29
28
  apiRequestPipeline = new ApiRequestPipeline({
30
29
  getRenderContext: () => this.getRenderContext(),
31
30
  getCacheService: () => this.getCacheService(),
32
- isClientAbort: (error) => this.clientAbortDetector(error),
33
31
  });
34
32
  sharedPageCacheService;
35
33
  constructor(options) {
36
34
  this.appConfig = options.appConfig;
37
35
  this.runtime = options.runtime;
38
36
  this.watchMode = options.watch ?? false;
39
- this.clientAbortDetector = options.isClientAbortError ?? (() => false);
40
37
  }
41
38
  /** Renders one declared path inside the request build scope for a DevSession prewarm. */
42
39
  async renderDevPrewarmPath(pathname, runtimeOrigin) {
@@ -56,7 +53,6 @@ export class ServerRequestPipeline {
56
53
  }
57
54
  this.routeRendererFactory = new RouteRendererFactory({
58
55
  appConfig: this.appConfig,
59
- runtime: this.runtime,
60
56
  });
61
57
  }
62
58
  createWatchRefreshCallback(options) {
@@ -82,7 +78,7 @@ export class ServerRequestPipeline {
82
78
  /**
83
79
  * Scans the filesystem and dynamically constructs the Route Registry.
84
80
  *
85
- * This process runs identically across both Bun and Node wrappers. It analyzes the configured pages
81
+ * It analyzes the configured pages
86
82
  * directory, building a map of all available UI routes and API endpoints.
87
83
  * The resulting `RouteRegistry` instance becomes the central nervous system for mapping WinterCG incoming
88
84
  * Web Requests (`Request`) to their corresponding internal execution paths.
@@ -62,12 +62,12 @@ export declare class ServerStaticBuilder {
62
62
  */
63
63
  private prepareExportDirectory;
64
64
  /**
65
- * Empties `dist/`, copies the public directory into it and sets the Processors and Integrations up.
65
+ * Empties `dist/`, copies the public directory into it and sets the Processors up.
66
66
  *
67
67
  * @remarks
68
68
  * Call it before the router reads any Page, so a Page module that resolves what a Processor generates in
69
- * `setup()` finds it. The next {@link build} then skips this work once; a build without a prior call prepares
70
- * the export itself.
69
+ * `setup()` finds it. Integrations are set up later, when the static site generator starts rendering. The next
70
+ * {@link build} then skips this work once; a build without a prior call prepares the export itself.
71
71
  */
72
72
  prepareExport(): Promise<void>;
73
73
  private refreshRuntimeAssets;
@@ -54,12 +54,12 @@ export class ServerStaticBuilder {
54
54
  fileSystem.ensureDir(path.join(exportDir, RESOLVED_ASSETS_DIR));
55
55
  }
56
56
  /**
57
- * Empties `dist/`, copies the public directory into it and sets the Processors and Integrations up.
57
+ * Empties `dist/`, copies the public directory into it and sets the Processors up.
58
58
  *
59
59
  * @remarks
60
60
  * Call it before the router reads any Page, so a Page module that resolves what a Processor generates in
61
- * `setup()` finds it. The next {@link build} then skips this work once; a build without a prior call prepares
62
- * the export itself.
61
+ * `setup()` finds it. Integrations are set up later, when the static site generator starts rendering. The next
62
+ * {@link build} then skips this work once; a build without a prior call prepares the export itself.
63
63
  */
64
64
  async prepareExport() {
65
65
  this.prepareExportDirectory();
@@ -1,6 +1,7 @@
1
1
  import { WebSocketServer } from 'ws';
2
2
  import { HttpError } from '../../../errors/http-error.js';
3
3
  import { appLogger } from '../../../global/app-logger.js';
4
+ import { parseSearchParams } from '../../../router/server/parse-search-params.js';
4
5
  import { findWebSocketRoute } from './ws-pattern-matcher.js';
5
6
  import { createEcopagesSocket, invokeWebSocketHandlerHook, toWebSocketCloseInfo } from './websocket-lifecycle.js';
6
7
  const attachedUpgradeServers = new WeakSet();
@@ -112,7 +113,7 @@ export function attachNodeHttpWebSocketUpgrades(server, options) {
112
113
  return;
113
114
  }
114
115
  userWss.handleUpgrade(req, socket, head, (ws) => {
115
- const search = Object.fromEntries(url.searchParams.entries());
116
+ const search = parseSearchParams(url.searchParams);
116
117
  void setupNodeWebSocketConnection(ws, wsMatch, req, options.runtimeOrigin, search).catch((error) => {
117
118
  appLogger.error(`[WS:${wsMatch.kind}] unexpected error:`, error);
118
119
  ws.close(1011, 'internal error');
@@ -1,8 +1,8 @@
1
- import type { EcopagesSocket, WebSocketCloseInfo } from '../../../types/contracts.js';
1
+ import type { EcopagesSocket, PageQuery, WebSocketCloseInfo } from '../../../types/contracts.js';
2
2
  /**
3
3
  * @remarks
4
- * Bun and Node expose different raw socket types but share the same
5
- * {@link OutgoingWebSocketMessage} contract. Adapters supply only `send`/`close`;
4
+ * Adapters expose their raw socket through the
5
+ * {@link OutgoingWebSocketMessage} contract and supply only `send`/`close`;
6
6
  * {@link createEcopagesSocket} owns message normalization and stream forwarding.
7
7
  */
8
8
  export interface WebSocketSendTransport {
@@ -11,13 +11,12 @@ export interface WebSocketSendTransport {
11
11
  }
12
12
  /**
13
13
  * @remarks
14
- * Bun and Node adapters previously duplicated outgoing-message dispatch and
15
- * stream forwarding; this is the shared implementation both transports delegate to.
14
+ * Owns outgoing-message dispatch and stream forwarding for every transport.
16
15
  */
17
16
  export declare function createEcopagesSocket<TContext, TParams extends Record<string, string>>(transport: WebSocketSendTransport, meta: {
18
17
  kind: string;
19
18
  params: TParams;
20
- search: Record<string, string>;
19
+ search: PageQuery;
21
20
  context: TContext;
22
21
  }): EcopagesSocket<TContext, TParams>;
23
22
  export declare function toWebSocketCloseInfo(code: number, reason: string): WebSocketCloseInfo;
@@ -18,8 +18,7 @@ function sendOutgoingMessage(transport, message) {
18
18
  }
19
19
  /**
20
20
  * @remarks
21
- * Bun and Node adapters previously duplicated outgoing-message dispatch and
22
- * stream forwarding; this is the shared implementation both transports delegate to.
21
+ * Owns outgoing-message dispatch and stream forwarding for every transport.
23
22
  */
24
23
  export function createEcopagesSocket(transport, meta) {
25
24
  return {
@@ -9,25 +9,8 @@
9
9
  * - `BuildExecutor` — the runtime-facing facade; the app's `BuildQueue`,
10
10
  * stored on `AppRuntime.buildQueue`, implements it.
11
11
  */
12
- import { type BuildAdapter, type BuildOwnership } from './contracts/build-contracts.js';
13
- export type { BuildAdapter, BuildFormat, BuildChunk, BuildDependencyGraph, BuildExecutor, BuildFailure, BuildLog, BuildOptions, BuildOutput, BuildOwnership, BuildResult, BuildSourcemap, BuildSuccess, BuildTarget, BuildTranspileOptions, BuildEnvironment, } from './contracts/build-contracts.js';
12
+ import { type BuildAdapter } from './contracts/build-contracts.js';
13
+ export type { BuildAdapter, BuildFormat, BuildChunk, BuildDependencyGraph, BuildExecutor, BuildFailure, BuildLog, BuildOptions, BuildOutput, BuildResult, BuildSourcemap, BuildSuccess, BuildTarget, BuildTranspileOptions, BuildEnvironment, } from './contracts/build-contracts.js';
14
14
  /** Constructs the Rolldown build adapter. */
15
15
  export declare function createBuildAdapter(): BuildAdapter;
16
- /** The shared default-bundler backend instance. */
17
- export declare const defaultRolldownBuildAdapter: BuildAdapter;
18
- /**
19
- * Global default build adapter.
20
- *
21
- * @remarks
22
- * Resolves to the bundled default-bundler adapter. App-aware code reads `requireAppRuntime(appConfig).buildAdapter`.
23
- */
24
- export declare const defaultBuildAdapter: BuildAdapter;
25
- /** Resolves the default build adapter. */
26
- export declare function getDefaultBuildAdapter(): BuildAdapter;
27
- /**
28
- * Reads the {@link BuildOwnership} declared on a {@link BuildAdapter}.
29
- *
30
- * @param buildAdapter - When `undefined`, defaults to `'rolldown'`.
31
- */
32
- export declare function getBuildAdapterOwnership(buildAdapter: BuildAdapter | undefined): BuildOwnership;
33
16
  export { ensureIntegrationRuntimeReady, sealAppBuildManifest, setupAppRuntimeIntegrations, setupAppRuntimePlugins, teardownAppRuntimeIntegrations, } from './app-build-manifest-runtime.js';
@@ -15,25 +15,4 @@ import { createRolldownBuildAdapter } from './rolldown/rolldown-build-adapter.js
15
15
  export function createBuildAdapter() {
16
16
  return createRolldownBuildAdapter();
17
17
  }
18
- /** The shared default-bundler backend instance. */
19
- export const defaultRolldownBuildAdapter = createBuildAdapter();
20
- /**
21
- * Global default build adapter.
22
- *
23
- * @remarks
24
- * Resolves to the bundled default-bundler adapter. App-aware code reads `requireAppRuntime(appConfig).buildAdapter`.
25
- */
26
- export const defaultBuildAdapter = defaultRolldownBuildAdapter;
27
- /** Resolves the default build adapter. */
28
- export function getDefaultBuildAdapter() {
29
- return defaultRolldownBuildAdapter;
30
- }
31
- /**
32
- * Reads the {@link BuildOwnership} declared on a {@link BuildAdapter}.
33
- *
34
- * @param buildAdapter - When `undefined`, defaults to `'rolldown'`.
35
- */
36
- export function getBuildAdapterOwnership(buildAdapter) {
37
- return buildAdapter?.ownership ?? 'rolldown';
38
- }
39
18
  export { ensureIntegrationRuntimeReady, sealAppBuildManifest, setupAppRuntimeIntegrations, setupAppRuntimePlugins, teardownAppRuntimeIntegrations, } from './app-build-manifest-runtime.js';
@@ -1,7 +1,4 @@
1
1
  import type { EcoBuildPlugin } from '../contracts/build-types.js';
2
- import type { BuildOptions } from '../contracts/build-contracts.js';
3
- /** Stable fingerprint for JSX options used in build and in-process cache keys. */
4
- export declare function createJsxCacheKey(jsx: BuildOptions['jsx']): string;
5
2
  /**
6
3
  * Stable fingerprint for ordered build plugins: each name, its environments and its
7
4
  * {@link EcoBuildPlugin.cacheKey}.
@@ -1,17 +1,3 @@
1
- /** Stable fingerprint for JSX options used in build and in-process cache keys. */
2
- export function createJsxCacheKey(jsx) {
3
- if (!jsx) {
4
- return 'jsx:default';
5
- }
6
- return JSON.stringify({
7
- development: jsx.development ?? false,
8
- factory: jsx.factory ?? null,
9
- fragment: jsx.fragment ?? null,
10
- importSource: jsx.importSource ?? null,
11
- runtime: jsx.runtime ?? null,
12
- sideEffects: jsx.sideEffects ?? null,
13
- });
14
- }
15
1
  /**
16
2
  * Stable fingerprint for ordered build plugins: each name, its environments and its
17
3
  * {@link EcoBuildPlugin.cacheKey}.