@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.
- package/README.md +2 -2
- package/package.json +3 -3
- package/src/adapters/node/create-app.d.ts +40 -11
- package/src/adapters/node/create-app.js +95 -69
- package/src/adapters/node/dev-session.js +0 -1
- package/src/adapters/node/http-request-bridge.d.ts +4 -0
- package/src/adapters/node/http-request-bridge.js +9 -1
- package/src/adapters/node/runtime-host.d.ts +28 -6
- package/src/adapters/node/runtime-host.js +35 -9
- package/src/adapters/node/server-adapter.d.ts +10 -35
- package/src/adapters/node/server-adapter.js +21 -58
- package/src/adapters/shared/hmr/hmr-manager.d.ts +21 -7
- package/src/adapters/shared/hmr/hmr-manager.js +58 -70
- package/src/adapters/shared/http/api-request-pipeline.d.ts +3 -12
- package/src/adapters/shared/http/api-request-pipeline.js +7 -7
- package/src/adapters/shared/http/dist-file-handler.d.ts +16 -0
- package/src/adapters/shared/http/dist-file-handler.js +172 -0
- package/src/adapters/shared/http/explicit-static-route-matcher.js +2 -1
- package/src/adapters/shared/http/fs-server-response-matcher.js +3 -2
- package/src/adapters/shared/runtime/bind-runtime-server.d.ts +5 -7
- package/src/adapters/shared/runtime/bind-runtime-server.js +8 -12
- package/src/adapters/shared/runtime/copy-runtime-public-dir.js +10 -9
- package/src/adapters/shared/runtime/port-manager.d.ts +8 -11
- package/src/adapters/shared/runtime/port-manager.js +19 -30
- package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +6 -9
- package/src/adapters/shared/runtime/runtime-server-lifecycle.js +2 -5
- package/src/adapters/shared/runtime/server-request-pipeline.d.ts +1 -3
- package/src/adapters/shared/runtime/server-request-pipeline.js +1 -5
- package/src/adapters/shared/runtime/server-static-builder.d.ts +3 -3
- package/src/adapters/shared/runtime/server-static-builder.js +3 -3
- package/src/adapters/shared/ws/node-http-websocket-upgrades.js +2 -1
- package/src/adapters/shared/ws/websocket-lifecycle.d.ts +5 -6
- package/src/adapters/shared/ws/websocket-lifecycle.js +1 -2
- package/src/assets/app-browser-client-build.js +1 -2
- package/src/assets/asset-processing-service/browser-runtime-entry-resolution.js +8 -8
- package/src/assets/asset-processing-service/browser-runtime-entry.factory.js +4 -4
- package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +12 -8
- package/src/assets/asset-processing-service/processors/script/file-script.processor.js +36 -16
- package/src/assets/asset-processing-service/processors/stylesheet/file-stylesheet.processor.js +11 -6
- package/src/assets/browser-asset-output.d.ts +19 -0
- package/src/assets/browser-asset-output.js +30 -0
- package/src/assets/hashed-browser-asset.d.ts +8 -6
- package/src/assets/hashed-browser-asset.js +8 -6
- package/src/build/build-adapter.d.ts +2 -19
- package/src/build/build-adapter.js +0 -21
- package/src/build/build-graph.js +2 -2
- package/src/build/cache/cache-keys.d.ts +0 -3
- package/src/build/cache/cache-keys.js +0 -14
- package/src/build/cache/pages-unified-graph-build.js +2 -17
- package/src/build/contracts/build-contracts.d.ts +0 -3
- package/src/build/preserve-import-meta-transform.js +2 -2
- package/src/build/rolldown/app-package-declarations.js +3 -3
- package/src/build/rolldown/rolldown-adapter-helpers.js +3 -3
- package/src/build/rolldown/rolldown-build-adapter.d.ts +0 -1
- package/src/build/rolldown/rolldown-build-adapter.js +1 -2
- package/src/build/rolldown/rolldown-build-invocation-metrics.d.ts +1 -2
- package/src/build/rolldown/rolldown-build-invocation-metrics.js +5 -12
- package/src/build/rolldown/server-side-css-shim-plugin.js +3 -3
- package/src/build/runtime/build-queue.d.ts +8 -13
- package/src/build/runtime/build-queue.js +6 -17
- package/src/build/server/app-module-loader.service.d.ts +1 -1
- package/src/build/server/app-module-loader.service.js +0 -2
- package/src/build/server/page-module-import.service.d.ts +2 -3
- package/src/build/server/page-module-import.service.js +3 -4
- package/src/build/server-bundle-deploy-manifest.d.ts +5 -0
- package/src/build/server-bundle-deploy-manifest.js +15 -1
- package/src/build/server-bundle-publication.js +4 -5
- package/src/build.d.ts +2 -2
- package/src/build.js +2 -2
- package/src/config/assembly/app-runtime.d.ts +2 -2
- package/src/config/assembly/app-runtime.js +2 -2
- package/src/config/assembly/finalize-config.d.ts +4 -4
- package/src/config/assembly/finalize-config.js +4 -5
- package/src/config/config-module-files.js +2 -3
- package/src/config/internal-types.d.ts +0 -7
- package/src/config/user-config-types.d.ts +0 -4
- package/src/diagnostics/request-pipeline-metrics.d.ts +3 -3
- package/src/diagnostics/request-pipeline-metrics.js +4 -4
- package/src/diagnostics/startup-trace.js +2 -5
- package/src/errors/http-error.d.ts +2 -2
- package/src/errors/http-error.js +4 -4
- package/src/hmr/client/hmr-runtime.js +16 -7
- package/src/hmr/client/module-update.d.ts +7 -0
- package/src/hmr/client/module-update.js +21 -4
- package/src/hmr/hmr-strategy.d.ts +0 -3
- package/src/hmr/hmr-strategy.js +0 -3
- package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -3
- package/src/hmr/strategies/js-hmr-strategy.js +3 -6
- package/src/html-pages/html-page-module-scripts.js +4 -3
- package/src/html-pages/html-page-renderer.js +2 -3
- package/src/plugins/alias-resolver-cache.d.ts +4 -3
- package/src/plugins/alias-resolver-cache.js +4 -3
- package/src/plugins/component-import-discovery.js +4 -4
- package/src/plugins/eco-component-meta-plugin.d.ts +10 -1
- package/src/plugins/eco-component-meta-plugin.js +66 -10
- package/src/plugins/foreign-jsx-override-plugin.js +4 -3
- package/src/plugins/tsconfig-import-resolver.js +12 -12
- package/src/route-renderer/error-pages/default-error-pages.js +2 -1
- package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -1
- package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +0 -1
- package/src/route-renderer/orchestration/integration-renderer.d.ts +10 -5
- package/src/route-renderer/orchestration/integration-renderer.js +13 -14
- package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -23
- package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -29
- package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +10 -32
- package/src/route-renderer/page-loading/ecopages-virtual-imports.js +2 -2
- package/src/route-renderer/page-loading/page-dependency-bundling.js +5 -5
- package/src/route-renderer/page-loading/page-module-loader.js +1 -1
- package/src/route-renderer/route-renderer.d.ts +2 -5
- package/src/route-renderer/route-renderer.js +2 -4
- package/src/router/client/link-navigation-policy.d.ts +4 -1
- package/src/router/client/link-navigation-policy.js +20 -6
- package/src/router/server/route-registry.d.ts +0 -1
- package/src/router/server/route-registry.js +3 -13
- package/src/router/server/segment-path-matcher.d.ts +12 -0
- package/src/router/server/segment-path-matcher.js +30 -0
- package/src/static-site-generator/static-site-generator.d.ts +0 -5
- package/src/static-site-generator/static-site-generator.js +2 -15
- package/src/types/contracts.d.ts +17 -27
- package/src/types/public-types.d.ts +1 -1
- package/src/utils/format-error-chain.d.ts +9 -0
- package/src/utils/format-error-chain.js +20 -0
- package/src/utils/invariant.d.ts +6 -1
- package/src/utils/invariant.js +7 -2
- package/src/watchers/project-watcher.d.ts +20 -1
- package/src/watchers/project-watcher.js +40 -9
- package/src/watchers/workspace-package-watch-roots.js +5 -5
- package/src/adapters/README.md +0 -58
- package/src/adapters/shared/hmr/hmr-manager.test-helpers.d.ts +0 -28
- package/src/adapters/shared/hmr/hmr-manager.test-helpers.js +0 -53
- package/src/adapters/shared/runtime/runtime-host.d.ts +0 -15
- package/src/adapters/shared/runtime/runtime-host.js +0 -1
- package/src/assets/README.md +0 -35
- package/src/build/README.md +0 -298
- package/src/build/server/README.md +0 -50
- package/src/cache/README.md +0 -5
- package/src/client/README.md +0 -5
- package/src/client/navigation-scripts/navigation-scripts.test.browser.d.ts +0 -1
- package/src/client/navigation-scripts/navigation-scripts.test.browser.js +0 -111
- package/src/client/scroll.test.browser.d.ts +0 -1
- package/src/client/scroll.test.browser.js +0 -31
- package/src/client/view-transitions.test.browser.d.ts +0 -1
- package/src/client/view-transitions.test.browser.js +0 -53
- package/src/config/README.md +0 -58
- package/src/config/constants.d.ts +0 -1
- package/src/config/constants.js +0 -1
- package/src/dev/README.md +0 -61
- package/src/dev/invalidation/README.md +0 -11
- package/src/dev-toolbar/README.md +0 -66
- package/src/diagnostics/README.md +0 -11
- package/src/eco/README.md +0 -776
- package/src/errors/README.md +0 -5
- package/src/global/README.md +0 -5
- package/src/hmr/README.md +0 -64
- package/src/hmr/client/build-error-overlay.test.browser.d.ts +0 -1
- package/src/hmr/client/build-error-overlay.test.browser.js +0 -48
- package/src/hmr/client/hmr-runtime.test.browser.d.ts +0 -1
- package/src/hmr/client/hmr-runtime.test.browser.js +0 -32
- package/src/hmr/entrypoint-dependency-graph.d.ts +0 -12
- package/src/hmr/entrypoint-dependency-graph.js +0 -27
- package/src/hmr/hmr-file-change-prep.d.ts +0 -9
- package/src/hmr/hmr-file-change-prep.js +0 -11
- package/src/html/README.md +0 -15
- package/src/html-pages/README.md +0 -104
- package/src/islands/README.md +0 -44
- package/src/page-cache/README.md +0 -17
- package/src/plugins/README.md +0 -53
- package/src/route-renderer/GRAPH.md +0 -142
- package/src/route-renderer/README.md +0 -160
- package/src/route-renderer/error-pages/README.md +0 -11
- package/src/route-renderer/orchestration/custom-element-scripts/README.md +0 -15
- package/src/route-renderer/orchestration/integration-renderer.test-fixtures.d.ts +0 -39
- package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +0 -94
- package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.d.ts +0 -35
- package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.js +0 -69
- package/src/router/README.md +0 -160
- package/src/router/client/link-intent.test.browser.d.ts +0 -1
- package/src/router/client/link-intent.test.browser.js +0 -33
- package/src/router/client/link-navigation-policy.test.browser.d.ts +0 -1
- package/src/router/client/link-navigation-policy.test.browser.js +0 -142
- package/src/router/client/navigation-commit.test.browser.d.ts +0 -1
- package/src/router/client/navigation-commit.test.browser.js +0 -116
- package/src/router/client/navigation-document.test.browser.d.ts +0 -1
- package/src/router/client/navigation-document.test.browser.js +0 -77
- package/src/router/client/navigation-head.test.browser.d.ts +0 -1
- package/src/router/client/navigation-head.test.browser.js +0 -101
- package/src/router/client/navigation-lifecycle.test.browser.d.ts +0 -1
- package/src/router/client/navigation-lifecycle.test.browser.js +0 -97
- package/src/router/client/navigation-view-transition.test.browser.d.ts +0 -1
- package/src/router/client/navigation-view-transition.test.browser.js +0 -189
- package/src/router/client/staged-stylesheets.test-fixtures.d.ts +0 -18
- package/src/router/client/staged-stylesheets.test-fixtures.js +0 -31
- package/src/static-site-generator/README.md +0 -67
- package/src/static-site-generator/static-site-generator.test-utils.d.ts +0 -2
- package/src/static-site-generator/static-site-generator.test-utils.js +0 -41
- package/src/types/README.md +0 -5
- package/src/utils/README.md +0 -7
- package/src/validation/README.md +0 -9
- package/src/watchers/README.md +0 -15
- package/src/watchers/project-watcher.test-helpers.d.ts +0 -60
- package/src/watchers/project-watcher.test-helpers.js +0 -108
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ The important ownership rules are:
|
|
|
21
21
|
|
|
22
22
|
- Core runtime mode and `ECOPAGES_*` settings are read through `src/env.ts`. Its typed accessors define the supported variable names, parse `true` and `1` as enabled and `false` and `0` as disabled, and provide the runtime-mode helpers used by core, integrations and Processors. The user-facing settings are documented in the [CLI reference](../ecopages/README.md#environment--runtime-options).
|
|
23
23
|
|
|
24
|
-
- Every `loadEcoPagesConfig()` call imports the config module through the module cache, then finalizes a distinct app config and `AppRuntime`. Build state, HTML Page warnings, custom-element preload scopes, and request-pipeline metrics stay with that runtime; pure memo caches remain shared.
|
|
24
|
+
- Every `loadEcoPagesConfig()` call imports the config module through the module cache, then finalizes a distinct app config and `AppRuntime`. Build state, HTML Page warnings, custom-element preload scopes, and request-pipeline metrics stay with that runtime; pure memo caches remain shared. Each runtime keeps the one build queue finalization created.
|
|
25
25
|
- Build requests declare server or browser environment independently of scheduling. Integrations and Processors contribute one environment-selected plugin list; config rejects duplicate names within an environment. Core's own transforms preserve source locations and the bridge composes chained maps. See [Build Layer](src/build/README.md) and [Plugin Contracts](src/plugins/README.md) for migration.
|
|
26
26
|
- Component identity attribution is one build plugin, shared by server, browser, and HMR compilation paths: after a lexical `eco.` gate, it uses Oxc to wrap supported factory options with `bindComponentIdentity()`, which factories retain as `config.identity`.
|
|
27
27
|
- Component ownership follows `config.integration`, then `config.identity.integration`, then the inherited owner through the exported `getComponentOwner()` helper. Integration plugins opt into page-owned asset bundling with `bundlesPageDependencies`; React and Ecopages JSX enable it. Bundling only combines consecutive eligible assets so custom-attribute files keep their declared order.
|
|
@@ -90,7 +90,7 @@ The manager/orchestration layer is core-owned, but framework-specific strategies
|
|
|
90
90
|
|
|
91
91
|
### Practical Summary
|
|
92
92
|
|
|
93
|
-
- Config finalization seeds one app-owned `AppRuntime` (build adapter, build manifest, build queue, build-input index, and module caches); the HMR manager
|
|
93
|
+
- Config finalization seeds one app-owned `AppRuntime` (build adapter, build manifest, build queue, build-input index, and module caches); the HMR manager records the imports of each served browser module in that build-input index. Server startup refreshes the build queue.
|
|
94
94
|
- `BrowserBundleService` is the shared browser build seam used by HMR and asset-oriented browser output paths; callers choose the `build` or `hmr` scheduling lane explicitly.
|
|
95
95
|
- `AppModuleLoader` is created once per app runtime and supplies the app root and shared build queue for server-side source loading, including HMR metadata imports.
|
|
96
96
|
- `RouteRegistry` gives exact and dynamic Pages priority over catch-alls, selects the most specific matching catch-all prefix, and shares segment matching and one-time URL decoding with API, explicit, and WebSocket routes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecopages/core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Core package for Ecopages",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ecopages",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@clack/prompts": "^1.7.0",
|
|
24
|
-
"@ecopages/file-system": "0.3.
|
|
24
|
+
"@ecopages/file-system": "0.3.2",
|
|
25
25
|
"@ecopages/logger": "^0.2.3",
|
|
26
26
|
"@ecopages/scripts-injector": "^0.1.5",
|
|
27
27
|
"@jridgewell/remapping": "^2.3.5",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"ws": "^8.20.1"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
|
-
"@ecopages/dev-toolbar": "0.3.
|
|
38
|
+
"@ecopages/dev-toolbar": "0.3.2"
|
|
39
39
|
},
|
|
40
40
|
"peerDependenciesMeta": {
|
|
41
41
|
"@ecopages/dev-toolbar": {
|
|
@@ -2,10 +2,8 @@ import type { EcoPagesAppConfig } from '../../config/internal-types.js';
|
|
|
2
2
|
import type { ApiHandler, ApiHandlerContext, ErrorHandler, Middleware, RouteGroupBuilder, RouteOptions, ViewLoader, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
|
|
3
3
|
import { type HttpErrorPageStatus } from '../../errors/http-error-page-contract.js';
|
|
4
4
|
import type { ReturnParseCliArgs } from '../../utils/parse-cli-args.js';
|
|
5
|
-
import type
|
|
6
|
-
import { type
|
|
7
|
-
import { type NodeServerAdapter, type NodeServerAdapterParams } from './server-adapter.js';
|
|
8
|
-
import type { NodeServerInstance } from './server-adapter.js';
|
|
5
|
+
import { type RuntimeHost } from './runtime-host.js';
|
|
6
|
+
import { NodeServerAdapter, type NodeServerAdapterParams, type NodeServerInstance } from './server-adapter.js';
|
|
9
7
|
export interface AppStartInfo {
|
|
10
8
|
origin: string;
|
|
11
9
|
/**
|
|
@@ -24,9 +22,13 @@ export type EcopagesAppRuntimeOptions = {
|
|
|
24
22
|
serverOptions?: Record<string, unknown>;
|
|
25
23
|
cliArgs: ReturnParseCliArgs;
|
|
26
24
|
};
|
|
25
|
+
/**
|
|
26
|
+
* @remarks
|
|
27
|
+
* Tests pass a fake runtime host and server adapter to drive the app lifecycle in isolation.
|
|
28
|
+
*/
|
|
27
29
|
export type EcopagesAppDependencies = {
|
|
28
|
-
runtimeHost: RuntimeHost
|
|
29
|
-
createServerAdapter?: (params: NodeServerAdapterParams) =>
|
|
30
|
+
runtimeHost: RuntimeHost;
|
|
31
|
+
createServerAdapter?: (params: NodeServerAdapterParams) => Promise<NodeServerAdapter>;
|
|
30
32
|
};
|
|
31
33
|
/**
|
|
32
34
|
* Handler function type for route handlers
|
|
@@ -52,10 +54,19 @@ export declare class EcopagesApp implements AsyncDisposable {
|
|
|
52
54
|
private onAppStartCallback?;
|
|
53
55
|
private readonly runtimeLabel;
|
|
54
56
|
private readonly runtimeHost;
|
|
55
|
-
private readonly
|
|
57
|
+
private readonly createServerAdapter;
|
|
56
58
|
/** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
|
|
57
59
|
serverAdapter: NodeServerAdapter | undefined;
|
|
58
60
|
private lifecycle;
|
|
61
|
+
/**
|
|
62
|
+
* Counts `stop()` calls.
|
|
63
|
+
*
|
|
64
|
+
* @remarks
|
|
65
|
+
* A `start()` or `fetch()` that waits for a running stop compares it after the
|
|
66
|
+
* wait, so a later `stop()` cancels it instead of sharing the first stop's promise
|
|
67
|
+
* and letting it start a new session afterwards.
|
|
68
|
+
*/
|
|
69
|
+
private stopCount;
|
|
59
70
|
constructor(options: EcopagesAppRuntimeOptions, dependencies: EcopagesAppDependencies);
|
|
60
71
|
private register;
|
|
61
72
|
get<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
|
|
@@ -117,7 +128,7 @@ export declare class EcopagesApp implements AsyncDisposable {
|
|
|
117
128
|
* and routes lifecycle events to `handler`.
|
|
118
129
|
*
|
|
119
130
|
* Supports dynamic segments via `:param` syntax. The handler receives
|
|
120
|
-
* typed `params` and `search` fields, and a typed `context` produced by
|
|
131
|
+
* typed `params` and `search` fields (a query key repeated in the URL is an array in `search`), and a typed `context` produced by
|
|
121
132
|
* the optional `context()` factory.
|
|
122
133
|
*
|
|
123
134
|
* One pattern registration matches infinite path variations. For example,
|
|
@@ -130,7 +141,8 @@ export declare class EcopagesApp implements AsyncDisposable {
|
|
|
130
141
|
* ```typescript
|
|
131
142
|
* app.websocket<ChatContext, { roomId: string }>('/ws/chat/:roomId', {
|
|
132
143
|
* async context({ params, search }) {
|
|
133
|
-
*
|
|
144
|
+
* const username = Array.isArray(search.username) ? search.username[0] : search.username;
|
|
145
|
+
* return { username: username ?? 'anonymous', roomId: params.roomId };
|
|
134
146
|
* },
|
|
135
147
|
* onConnect(socket) {
|
|
136
148
|
* socket.send(`Welcome to room ${socket.context.roomId}`);
|
|
@@ -163,16 +175,31 @@ export declare class EcopagesApp implements AsyncDisposable {
|
|
|
163
175
|
* ```
|
|
164
176
|
*/
|
|
165
177
|
onError(handler: ErrorHandler<Request, unknown>): this;
|
|
166
|
-
private createServerAdapter;
|
|
167
178
|
private resolveRuntimeAssetSetup;
|
|
168
|
-
private
|
|
179
|
+
private initializeSession;
|
|
169
180
|
/**
|
|
170
181
|
* Boot the server. When `onAppStart` is passed, it runs once the runtime can take traffic.
|
|
182
|
+
*
|
|
183
|
+
* @remarks
|
|
184
|
+
* Resolves without a server when `stop()` is called before startup finishes;
|
|
185
|
+
* that startup does not continue. It still rejects when the step in flight
|
|
186
|
+
* fails, such as a bind failure. A call made while `stop()` runs waits for it,
|
|
187
|
+
* and resolves without a server when another `stop()` arrives in that wait.
|
|
171
188
|
*/
|
|
172
189
|
start(onAppStart?: OnAppStartCallback): Promise<NodeServerInstance | void>;
|
|
173
190
|
private bootServer;
|
|
191
|
+
/**
|
|
192
|
+
* Whether `stop()` has not yet claimed `session`.
|
|
193
|
+
*
|
|
194
|
+
* @remarks
|
|
195
|
+
* `stop()` always replaces the lifecycle, so startup work re-checks this after
|
|
196
|
+
* each await and abandons a session that is being stopped.
|
|
197
|
+
*/
|
|
198
|
+
private isActive;
|
|
199
|
+
/** Resolves `undefined` when `stop()` is called before the session is ready. */
|
|
174
200
|
private getReadySession;
|
|
175
201
|
private runStartup;
|
|
202
|
+
private releaseFailedStartup;
|
|
176
203
|
private logServerStarted;
|
|
177
204
|
private notifyListening;
|
|
178
205
|
/**
|
|
@@ -188,6 +215,8 @@ export declare class EcopagesApp implements AsyncDisposable {
|
|
|
188
215
|
*
|
|
189
216
|
* @remarks
|
|
190
217
|
* Shutdown releases the bound HTTP server and adapter-owned runtime resources.
|
|
218
|
+
* During startup it waits for the step in flight, which then stops, and
|
|
219
|
+
* releases whatever that step created.
|
|
191
220
|
*/
|
|
192
221
|
stop(force?: boolean): Promise<void>;
|
|
193
222
|
private disposeSession;
|
|
@@ -8,7 +8,7 @@ import { resolveRuntimeBinding } from '../shared/runtime/runtime-app-bootstrap.j
|
|
|
8
8
|
import { bindRuntimeServer } from '../shared/runtime/bind-runtime-server.js';
|
|
9
9
|
import { NodeHttpRequestBridge } from './http-request-bridge.js';
|
|
10
10
|
import { NodeRuntimeHost } from './runtime-host.js';
|
|
11
|
-
import {
|
|
11
|
+
import { NodeServerAdapter } from './server-adapter.js';
|
|
12
12
|
import { resolveAppStartRoutes } from '../../utils/ecopages-route-info.js';
|
|
13
13
|
import { requireAppRuntime } from '../../utils/app-runtime.js';
|
|
14
14
|
import { createViewModuleLoader } from '../../build/server/view-module-loader.js';
|
|
@@ -47,18 +47,27 @@ export class EcopagesApp {
|
|
|
47
47
|
onAppStartCallback;
|
|
48
48
|
runtimeLabel;
|
|
49
49
|
runtimeHost;
|
|
50
|
-
|
|
50
|
+
createServerAdapter;
|
|
51
51
|
/** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
|
|
52
52
|
serverAdapter;
|
|
53
53
|
lifecycle = { phase: 'idle' };
|
|
54
|
+
/**
|
|
55
|
+
* Counts `stop()` calls.
|
|
56
|
+
*
|
|
57
|
+
* @remarks
|
|
58
|
+
* A `start()` or `fetch()` that waits for a running stop compares it after the
|
|
59
|
+
* wait, so a later `stop()` cancels it instead of sharing the first stop's promise
|
|
60
|
+
* and letting it start a new session afterwards.
|
|
61
|
+
*/
|
|
62
|
+
stopCount = 0;
|
|
54
63
|
constructor(options, dependencies) {
|
|
55
64
|
this.runtimeLabel = resolveProcessRuntimeLabel();
|
|
56
65
|
this.appConfig = options.appConfig;
|
|
57
66
|
this.serverOptions = options.serverOptions || {};
|
|
58
67
|
this.cliArgs = options.cliArgs;
|
|
59
68
|
this.runtimeHost = dependencies.runtimeHost;
|
|
60
|
-
this.
|
|
61
|
-
dependencies.createServerAdapter ?? ((params) =>
|
|
69
|
+
this.createServerAdapter =
|
|
70
|
+
dependencies.createServerAdapter ?? (async (params) => new NodeServerAdapter(params));
|
|
62
71
|
startupTrace.markConfigReady();
|
|
63
72
|
}
|
|
64
73
|
register(path, method, handler, options) {
|
|
@@ -217,7 +226,7 @@ export class EcopagesApp {
|
|
|
217
226
|
* and routes lifecycle events to `handler`.
|
|
218
227
|
*
|
|
219
228
|
* Supports dynamic segments via `:param` syntax. The handler receives
|
|
220
|
-
* typed `params` and `search` fields, and a typed `context` produced by
|
|
229
|
+
* typed `params` and `search` fields (a query key repeated in the URL is an array in `search`), and a typed `context` produced by
|
|
221
230
|
* the optional `context()` factory.
|
|
222
231
|
*
|
|
223
232
|
* One pattern registration matches infinite path variations. For example,
|
|
@@ -230,7 +239,8 @@ export class EcopagesApp {
|
|
|
230
239
|
* ```typescript
|
|
231
240
|
* app.websocket<ChatContext, { roomId: string }>('/ws/chat/:roomId', {
|
|
232
241
|
* async context({ params, search }) {
|
|
233
|
-
*
|
|
242
|
+
* const username = Array.isArray(search.username) ? search.username[0] : search.username;
|
|
243
|
+
* return { username: username ?? 'anonymous', roomId: params.roomId };
|
|
234
244
|
* },
|
|
235
245
|
* onConnect(socket) {
|
|
236
246
|
* socket.send(`Welcome to room ${socket.context.roomId}`);
|
|
@@ -284,9 +294,6 @@ export class EcopagesApp {
|
|
|
284
294
|
this.errorHandler = handler;
|
|
285
295
|
return this;
|
|
286
296
|
}
|
|
287
|
-
createServerAdapter(params) {
|
|
288
|
-
return Promise.resolve(this.serverAdapterFactory(params));
|
|
289
|
-
}
|
|
290
297
|
resolveRuntimeAssetSetup() {
|
|
291
298
|
const { build, preview, serveOnly } = this.cliArgs;
|
|
292
299
|
if (preview && serveOnly) {
|
|
@@ -294,7 +301,7 @@ export class EcopagesApp {
|
|
|
294
301
|
}
|
|
295
302
|
return build || preview ? 'export' : 'start';
|
|
296
303
|
}
|
|
297
|
-
async
|
|
304
|
+
async initializeSession() {
|
|
298
305
|
const binding = resolveRuntimeBinding({
|
|
299
306
|
cliArgs: this.cliArgs,
|
|
300
307
|
serverOptions: this.serverOptions,
|
|
@@ -303,6 +310,7 @@ export class EcopagesApp {
|
|
|
303
310
|
runtime.origin = binding.runtimeOrigin;
|
|
304
311
|
const serverAdapter = await this.createServerAdapter({
|
|
305
312
|
runtime,
|
|
313
|
+
runtimeHost: this.runtimeHost,
|
|
306
314
|
appConfig: this.appConfig,
|
|
307
315
|
apiHandlers: this.apiHandlers,
|
|
308
316
|
staticRoutes: this.staticRoutes,
|
|
@@ -327,10 +335,16 @@ export class EcopagesApp {
|
|
|
327
335
|
}
|
|
328
336
|
throw error;
|
|
329
337
|
}
|
|
330
|
-
return serverAdapter;
|
|
338
|
+
return { adapter: serverAdapter, server: undefined, allowPortFallback: binding.allowPortFallback };
|
|
331
339
|
}
|
|
332
340
|
/**
|
|
333
341
|
* Boot the server. When `onAppStart` is passed, it runs once the runtime can take traffic.
|
|
342
|
+
*
|
|
343
|
+
* @remarks
|
|
344
|
+
* Resolves without a server when `stop()` is called before startup finishes;
|
|
345
|
+
* that startup does not continue. It still rejects when the step in flight
|
|
346
|
+
* fails, such as a bind failure. A call made while `stop()` runs waits for it,
|
|
347
|
+
* and resolves without a server when another `stop()` arrives in that wait.
|
|
334
348
|
*/
|
|
335
349
|
async start(onAppStart) {
|
|
336
350
|
if (onAppStart) {
|
|
@@ -340,12 +354,12 @@ export class EcopagesApp {
|
|
|
340
354
|
}
|
|
341
355
|
async bootServer() {
|
|
342
356
|
const session = await this.getReadySession();
|
|
357
|
+
if (!session || !this.isActive(session))
|
|
358
|
+
return;
|
|
343
359
|
const current = this.lifecycle;
|
|
344
|
-
if (current.phase === 'starting')
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
await current.stopped;
|
|
348
|
-
return await this.bootServer();
|
|
360
|
+
if (current.phase === 'starting') {
|
|
361
|
+
await current.ready;
|
|
362
|
+
return this.isActive(session) ? session.server : undefined;
|
|
349
363
|
}
|
|
350
364
|
if (session.server)
|
|
351
365
|
return session.server;
|
|
@@ -362,25 +376,43 @@ export class EcopagesApp {
|
|
|
362
376
|
this.lifecycle = { phase: 'ready', session };
|
|
363
377
|
throw error;
|
|
364
378
|
}
|
|
365
|
-
return session.server;
|
|
379
|
+
return this.isActive(session) ? session.server : undefined;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Whether `stop()` has not yet claimed `session`.
|
|
383
|
+
*
|
|
384
|
+
* @remarks
|
|
385
|
+
* `stop()` always replaces the lifecycle, so startup work re-checks this after
|
|
386
|
+
* each await and abandons a session that is being stopped.
|
|
387
|
+
*/
|
|
388
|
+
isActive(session) {
|
|
389
|
+
const current = this.lifecycle;
|
|
390
|
+
return (current.phase === 'ready' || current.phase === 'starting') && current.session === session;
|
|
366
391
|
}
|
|
392
|
+
/** Resolves `undefined` when `stop()` is called before the session is ready. */
|
|
367
393
|
async getReadySession() {
|
|
368
394
|
const current = this.lifecycle;
|
|
369
395
|
if (current.phase === 'ready')
|
|
370
396
|
return current.session;
|
|
371
|
-
if (current.phase === 'starting')
|
|
372
|
-
|
|
397
|
+
if (current.phase === 'starting') {
|
|
398
|
+
const session = await current.ready;
|
|
399
|
+
return this.isActive(session) ? session : undefined;
|
|
400
|
+
}
|
|
373
401
|
if (current.phase === 'stopping') {
|
|
402
|
+
const stopCount = this.stopCount;
|
|
374
403
|
await current.stopped;
|
|
404
|
+
if (this.stopCount !== stopCount)
|
|
405
|
+
return undefined;
|
|
375
406
|
return await this.getReadySession();
|
|
376
407
|
}
|
|
377
|
-
const ready = this.
|
|
408
|
+
const ready = this.initializeSession();
|
|
378
409
|
const starting = { phase: 'starting', ready };
|
|
379
410
|
this.lifecycle = starting;
|
|
380
411
|
try {
|
|
381
412
|
const session = await ready;
|
|
382
|
-
if (this.lifecycle
|
|
383
|
-
|
|
413
|
+
if (this.lifecycle !== starting)
|
|
414
|
+
return undefined;
|
|
415
|
+
this.lifecycle = { phase: 'ready', session };
|
|
384
416
|
this.serverAdapter = session.adapter;
|
|
385
417
|
return session;
|
|
386
418
|
}
|
|
@@ -394,7 +426,7 @@ export class EcopagesApp {
|
|
|
394
426
|
const { build, preview, serveOnly, keepGoing } = this.cliArgs;
|
|
395
427
|
if (preview && serveOnly) {
|
|
396
428
|
const previewOrigin = await session.adapter.servePreviewOnly();
|
|
397
|
-
if (previewOrigin)
|
|
429
|
+
if (previewOrigin && this.isActive(session))
|
|
398
430
|
await this.notifyListening(previewOrigin);
|
|
399
431
|
return;
|
|
400
432
|
}
|
|
@@ -402,57 +434,58 @@ export class EcopagesApp {
|
|
|
402
434
|
appLogger.debugTime('Building static pages');
|
|
403
435
|
const previewOrigin = await session.adapter.buildStatic({ preview, keepGoing });
|
|
404
436
|
appLogger.debugTimeEnd('Building static pages');
|
|
405
|
-
if (preview && previewOrigin)
|
|
437
|
+
if (preview && previewOrigin && this.isActive(session))
|
|
406
438
|
await this.notifyListening(previewOrigin);
|
|
407
439
|
return;
|
|
408
440
|
}
|
|
409
|
-
const serveOptions = session.adapter.getServerOptions();
|
|
410
|
-
const binding = resolveRuntimeBinding({
|
|
411
|
-
cliArgs: this.cliArgs,
|
|
412
|
-
serverOptions: this.serverOptions,
|
|
413
|
-
});
|
|
414
441
|
startupTrace.beginServerListen();
|
|
415
442
|
const bindingResult = await bindRuntimeServer(this.runtimeHost, {
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
handleRequest: async (request) => await session.adapter.handleServerRequest(request),
|
|
420
|
-
},
|
|
443
|
+
serveOptions: {
|
|
444
|
+
...session.adapter.getServerOptions(),
|
|
445
|
+
handleRequest: async (request) => await session.adapter.handleServerRequest(request),
|
|
421
446
|
},
|
|
422
|
-
allowPortFallback:
|
|
447
|
+
allowPortFallback: session.allowPortFallback,
|
|
423
448
|
usePortManager: this.cliArgs.dev,
|
|
424
449
|
});
|
|
425
450
|
session.server = bindingResult.server;
|
|
451
|
+
if (!this.isActive(session))
|
|
452
|
+
return;
|
|
426
453
|
session.adapter.applyBoundPort(bindingResult);
|
|
427
454
|
try {
|
|
428
455
|
await session.adapter.completeInitialization(session.server);
|
|
429
456
|
}
|
|
430
457
|
catch (error) {
|
|
431
|
-
|
|
432
|
-
const failedServer = session.server;
|
|
433
|
-
session.server = undefined;
|
|
434
|
-
try {
|
|
435
|
-
await this.runtimeHost.stop(failedServer, { force: true });
|
|
436
|
-
}
|
|
437
|
-
catch (stopError) {
|
|
438
|
-
errors.push(stopError);
|
|
439
|
-
}
|
|
440
|
-
try {
|
|
441
|
-
await session.adapter.dispose();
|
|
442
|
-
}
|
|
443
|
-
catch (disposeError) {
|
|
444
|
-
errors.push(disposeError);
|
|
445
|
-
}
|
|
446
|
-
if (this.serverAdapter === session.adapter)
|
|
447
|
-
this.serverAdapter = undefined;
|
|
448
|
-
if (this.lifecycle.phase === 'starting')
|
|
449
|
-
this.lifecycle = { phase: 'stopped' };
|
|
450
|
-
if (errors.length > 1)
|
|
451
|
-
throw new AggregateError(errors, 'Server startup and cleanup failed');
|
|
452
|
-
throw error;
|
|
458
|
+
await this.releaseFailedStartup(session, error);
|
|
453
459
|
}
|
|
460
|
+
if (!this.isActive(session))
|
|
461
|
+
return;
|
|
454
462
|
await this.notifyListening(requireAppRuntime(this.appConfig).origin);
|
|
455
463
|
}
|
|
464
|
+
async releaseFailedStartup(session, error) {
|
|
465
|
+
const errors = [error];
|
|
466
|
+
const failedServer = session.server;
|
|
467
|
+
session.server = undefined;
|
|
468
|
+
try {
|
|
469
|
+
if (failedServer)
|
|
470
|
+
await this.runtimeHost.stop(failedServer, { force: true });
|
|
471
|
+
}
|
|
472
|
+
catch (stopError) {
|
|
473
|
+
errors.push(stopError);
|
|
474
|
+
}
|
|
475
|
+
try {
|
|
476
|
+
await session.adapter.dispose();
|
|
477
|
+
}
|
|
478
|
+
catch (disposeError) {
|
|
479
|
+
errors.push(disposeError);
|
|
480
|
+
}
|
|
481
|
+
if (this.serverAdapter === session.adapter)
|
|
482
|
+
this.serverAdapter = undefined;
|
|
483
|
+
if (this.lifecycle.phase === 'starting')
|
|
484
|
+
this.lifecycle = { phase: 'stopped' };
|
|
485
|
+
if (errors.length > 1)
|
|
486
|
+
throw new AggregateError(errors, 'Server startup and cleanup failed');
|
|
487
|
+
throw error;
|
|
488
|
+
}
|
|
456
489
|
logServerStarted(origin) {
|
|
457
490
|
appLogger.info(formatRuntimeServerStartedMessage(this.runtimeLabel, origin));
|
|
458
491
|
}
|
|
@@ -500,8 +533,11 @@ export class EcopagesApp {
|
|
|
500
533
|
*
|
|
501
534
|
* @remarks
|
|
502
535
|
* Shutdown releases the bound HTTP server and adapter-owned runtime resources.
|
|
536
|
+
* During startup it waits for the step in flight, which then stops, and
|
|
537
|
+
* releases whatever that step created.
|
|
503
538
|
*/
|
|
504
539
|
stop(force = true) {
|
|
540
|
+
this.stopCount += 1;
|
|
505
541
|
const current = this.lifecycle;
|
|
506
542
|
if (current.phase === 'idle' || current.phase === 'stopped')
|
|
507
543
|
return Promise.resolve();
|
|
@@ -514,18 +550,7 @@ export class EcopagesApp {
|
|
|
514
550
|
return stopped;
|
|
515
551
|
}
|
|
516
552
|
async disposeSession(current, force) {
|
|
517
|
-
|
|
518
|
-
if (current.phase === 'starting') {
|
|
519
|
-
try {
|
|
520
|
-
session ??= await current.ready;
|
|
521
|
-
}
|
|
522
|
-
catch {
|
|
523
|
-
if (!session) {
|
|
524
|
-
this.lifecycle = { phase: 'stopped' };
|
|
525
|
-
return;
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
}
|
|
553
|
+
const session = current.phase === 'starting' ? await current.ready.catch(() => current.session) : current.session;
|
|
529
554
|
const errors = [];
|
|
530
555
|
if (session?.server) {
|
|
531
556
|
const activeServer = session.server;
|
|
@@ -563,6 +588,7 @@ export class EcopagesApp {
|
|
|
563
588
|
*/
|
|
564
589
|
async fetch(request) {
|
|
565
590
|
const session = await this.getReadySession();
|
|
591
|
+
invariant(session !== undefined, 'The app was stopped before it could handle the request.');
|
|
566
592
|
return session.adapter.handleRequest(request);
|
|
567
593
|
}
|
|
568
594
|
createDevelopmentRestartHandler() {
|
|
@@ -52,6 +52,10 @@ export declare class NodeHttpRequestBridge {
|
|
|
52
52
|
* as server-sent events. The bridge therefore forwards the `ReadableStream`
|
|
53
53
|
* directly into the Node writable response instead of materializing an
|
|
54
54
|
* intermediate `ArrayBuffer`.
|
|
55
|
+
*
|
|
56
|
+
* `Headers.forEach` yields every `Set-Cookie` value as a separate entry, so
|
|
57
|
+
* writing them one by one would let each overwrite the previous. They are
|
|
58
|
+
* collected with `getSetCookie()` and written as a single array value.
|
|
55
59
|
*/
|
|
56
60
|
sendNodeResponse(res: ServerResponse, response: Response): Promise<void>;
|
|
57
61
|
}
|
|
@@ -178,12 +178,20 @@ export class NodeHttpRequestBridge {
|
|
|
178
178
|
* as server-sent events. The bridge therefore forwards the `ReadableStream`
|
|
179
179
|
* directly into the Node writable response instead of materializing an
|
|
180
180
|
* intermediate `ArrayBuffer`.
|
|
181
|
+
*
|
|
182
|
+
* `Headers.forEach` yields every `Set-Cookie` value as a separate entry, so
|
|
183
|
+
* writing them one by one would let each overwrite the previous. They are
|
|
184
|
+
* collected with `getSetCookie()` and written as a single array value.
|
|
181
185
|
*/
|
|
182
186
|
async sendNodeResponse(res, response) {
|
|
183
187
|
res.statusCode = response.status;
|
|
184
188
|
response.headers.forEach((value, key) => {
|
|
185
|
-
|
|
189
|
+
if (key !== 'set-cookie')
|
|
190
|
+
res.setHeader(key, value);
|
|
186
191
|
});
|
|
192
|
+
const setCookies = response.headers.getSetCookie();
|
|
193
|
+
if (setCookies.length > 0)
|
|
194
|
+
res.setHeader('set-cookie', setCookies);
|
|
187
195
|
if (!response.body) {
|
|
188
196
|
res.end();
|
|
189
197
|
return;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { createServer, type Server as NodeServerInstance } from 'node:http';
|
|
2
|
-
import type { RuntimeHost, RuntimeHostStartOptions } from '../shared/runtime/runtime-host.js';
|
|
3
2
|
import { NodeHttpRequestBridge } from './http-request-bridge.js';
|
|
4
3
|
type NodeServerFactory = typeof createServer;
|
|
5
4
|
export type NodeRuntimeServeOptions = {
|
|
@@ -7,6 +6,13 @@ export type NodeRuntimeServeOptions = {
|
|
|
7
6
|
hostname?: string;
|
|
8
7
|
handleRequest(request: Request): Promise<Response>;
|
|
9
8
|
};
|
|
9
|
+
/**
|
|
10
|
+
* The transport surface `EcopagesApp` and `NodeServerAdapter` use.
|
|
11
|
+
*
|
|
12
|
+
* @remarks
|
|
13
|
+
* Tests pass a fake with this shape to run the app lifecycle without binding a port.
|
|
14
|
+
*/
|
|
15
|
+
export type RuntimeHost = Pick<NodeRuntimeHost, 'start' | 'stop' | 'getOrigin'>;
|
|
10
16
|
/**
|
|
11
17
|
* Node runtime host that binds the shared Web-request pipeline onto a concrete
|
|
12
18
|
* Node HTTP server.
|
|
@@ -16,12 +22,19 @@ export type NodeRuntimeServeOptions = {
|
|
|
16
22
|
* requests through `NodeHttpRequestBridge`, and handling socket-level failures.
|
|
17
23
|
* Routing and rendering remain in the shared server adapter.
|
|
18
24
|
*/
|
|
19
|
-
export declare class NodeRuntimeHost
|
|
25
|
+
export declare class NodeRuntimeHost {
|
|
20
26
|
private readonly requestBridge;
|
|
21
27
|
private readonly serverFactory;
|
|
22
28
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
29
|
+
* Every open socket per started server, including upgraded WebSocket sockets.
|
|
30
|
+
*
|
|
31
|
+
* @remarks
|
|
32
|
+
* `closeAllConnections()` stops tracking a socket once it is upgraded, yet
|
|
33
|
+
* `server.close()` still waits for it, so a forced stop destroys these too.
|
|
34
|
+
*/
|
|
35
|
+
private readonly sockets;
|
|
36
|
+
/**
|
|
37
|
+
* Creates a Node runtime host; tests inject the request bridge and server factory.
|
|
25
38
|
*/
|
|
26
39
|
constructor(requestBridge: NodeHttpRequestBridge, serverFactory?: NodeServerFactory);
|
|
27
40
|
/**
|
|
@@ -32,11 +45,20 @@ export declare class NodeRuntimeHost implements RuntimeHost<NodeServerInstance,
|
|
|
32
45
|
* Client disconnects are treated as normal aborts and are not logged. Other
|
|
33
46
|
* failures here (the response write, or an uninitialised adapter) are logged
|
|
34
47
|
* with their stack and answered with 500.
|
|
48
|
+
*
|
|
49
|
+
* The hostname is resolved to its first address before `listen()`, which is
|
|
50
|
+
* what Node does internally. Bun instead tries every address the name resolves
|
|
51
|
+
* to, so when `localhost:<port>` is taken on `::1` it binds `127.0.0.1` and
|
|
52
|
+
* never reports `EADDRINUSE`, leaving two servers behind one origin.
|
|
35
53
|
*/
|
|
36
|
-
start(
|
|
54
|
+
start(serveOptions: NodeRuntimeServeOptions): Promise<NodeServerInstance>;
|
|
37
55
|
/**
|
|
38
56
|
* Stops the Node HTTP server and, by default, force-closes any remaining open
|
|
39
|
-
* connections.
|
|
57
|
+
* connections, WebSocket connections included.
|
|
58
|
+
*
|
|
59
|
+
* @remarks
|
|
60
|
+
* With `force: false` the returned promise waits until every connection ends
|
|
61
|
+
* on its own, so an open WebSocket keeps it pending.
|
|
40
62
|
*/
|
|
41
63
|
stop(server: NodeServerInstance, options?: {
|
|
42
64
|
force?: boolean;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { lookup } from 'node:dns/promises';
|
|
1
2
|
import { createServer } from 'node:http';
|
|
2
3
|
import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from '../../constants.js';
|
|
3
4
|
import { appLogger } from '../../global/app-logger.js';
|
|
@@ -16,8 +17,15 @@ export class NodeRuntimeHost {
|
|
|
16
17
|
requestBridge;
|
|
17
18
|
serverFactory;
|
|
18
19
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
20
|
+
* Every open socket per started server, including upgraded WebSocket sockets.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* `closeAllConnections()` stops tracking a socket once it is upgraded, yet
|
|
24
|
+
* `server.close()` still waits for it, so a forced stop destroys these too.
|
|
25
|
+
*/
|
|
26
|
+
sockets = new WeakMap();
|
|
27
|
+
/**
|
|
28
|
+
* Creates a Node runtime host; tests inject the request bridge and server factory.
|
|
21
29
|
*/
|
|
22
30
|
constructor(requestBridge, serverFactory = createServer) {
|
|
23
31
|
this.requestBridge = requestBridge;
|
|
@@ -31,16 +39,22 @@ export class NodeRuntimeHost {
|
|
|
31
39
|
* Client disconnects are treated as normal aborts and are not logged. Other
|
|
32
40
|
* failures here (the response write, or an uninitialised adapter) are logged
|
|
33
41
|
* with their stack and answered with 500.
|
|
42
|
+
*
|
|
43
|
+
* The hostname is resolved to its first address before `listen()`, which is
|
|
44
|
+
* what Node does internally. Bun instead tries every address the name resolves
|
|
45
|
+
* to, so when `localhost:<port>` is taken on `::1` it binds `127.0.0.1` and
|
|
46
|
+
* never reports `EADDRINUSE`, leaving two servers behind one origin.
|
|
34
47
|
*/
|
|
35
|
-
async start(
|
|
36
|
-
const hostname = String(
|
|
37
|
-
const port = Number(
|
|
48
|
+
async start(serveOptions) {
|
|
49
|
+
const hostname = String(serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME);
|
|
50
|
+
const port = Number(serveOptions.port ?? DEFAULT_ECOPAGES_PORT);
|
|
51
|
+
const { address } = await lookup(hostname);
|
|
38
52
|
let server;
|
|
39
53
|
server = this.serverFactory(async (req, res) => {
|
|
40
54
|
try {
|
|
41
|
-
const runtimeOrigin = this.getOrigin(server,
|
|
55
|
+
const runtimeOrigin = this.getOrigin(server, serveOptions);
|
|
42
56
|
const webRequest = this.requestBridge.createWebRequest(req, runtimeOrigin);
|
|
43
|
-
const response = await
|
|
57
|
+
const response = await serveOptions.handleRequest(webRequest);
|
|
44
58
|
await this.requestBridge.sendNodeResponse(res, response);
|
|
45
59
|
}
|
|
46
60
|
catch (error) {
|
|
@@ -52,9 +66,15 @@ export class NodeRuntimeHost {
|
|
|
52
66
|
res.end('Internal Server Error');
|
|
53
67
|
}
|
|
54
68
|
});
|
|
69
|
+
const sockets = new Set();
|
|
70
|
+
this.sockets.set(server, sockets);
|
|
71
|
+
server.on('connection', (socket) => {
|
|
72
|
+
sockets.add(socket);
|
|
73
|
+
socket.once('close', () => sockets.delete(socket));
|
|
74
|
+
});
|
|
55
75
|
await new Promise((resolve, reject) => {
|
|
56
76
|
server.once('error', reject);
|
|
57
|
-
server.listen(port,
|
|
77
|
+
server.listen(port, address, () => {
|
|
58
78
|
server.off('error', reject);
|
|
59
79
|
resolve();
|
|
60
80
|
});
|
|
@@ -63,7 +83,11 @@ export class NodeRuntimeHost {
|
|
|
63
83
|
}
|
|
64
84
|
/**
|
|
65
85
|
* Stops the Node HTTP server and, by default, force-closes any remaining open
|
|
66
|
-
* connections.
|
|
86
|
+
* connections, WebSocket connections included.
|
|
87
|
+
*
|
|
88
|
+
* @remarks
|
|
89
|
+
* With `force: false` the returned promise waits until every connection ends
|
|
90
|
+
* on its own, so an open WebSocket keeps it pending.
|
|
67
91
|
*/
|
|
68
92
|
async stop(server, options) {
|
|
69
93
|
await new Promise((resolve, reject) => {
|
|
@@ -76,6 +100,8 @@ export class NodeRuntimeHost {
|
|
|
76
100
|
});
|
|
77
101
|
if (options?.force ?? true) {
|
|
78
102
|
server.closeAllConnections();
|
|
103
|
+
for (const socket of this.sockets.get(server) ?? [])
|
|
104
|
+
socket.destroy();
|
|
79
105
|
}
|
|
80
106
|
});
|
|
81
107
|
}
|