@orkestrel/server 0.0.17 → 0.0.18
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 +4 -4
- package/dist/src/server/index.cjs +461 -339
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +584 -387
- package/dist/src/server/index.d.ts +584 -387
- package/dist/src/server/index.js +453 -333
- package/dist/src/server/index.js.map +1 -1
- package/package.json +15 -16
|
@@ -7,9 +7,9 @@ import { EmitterInterface } from '@orkestrel/emitter';
|
|
|
7
7
|
import { IncomingMessage } from 'node:http';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
11
|
-
* header — a value and its quality weight, the element type
|
|
12
|
-
* returns (sorted by `q` descending).
|
|
10
|
+
* Represents one parsed entry of a weighted `Accept` / `Accept-Encoding` /
|
|
11
|
+
* `Accept-Language` header — a value and its quality weight, the element type
|
|
12
|
+
* `parseAcceptHeader` returns (sorted by `q` descending).
|
|
13
13
|
*
|
|
14
14
|
* @remarks
|
|
15
15
|
* `value` is the lower-cased token (`text/html`, `gzip`, `en-us`, or a
|
|
@@ -23,29 +23,6 @@ export declare interface AcceptEntry {
|
|
|
23
23
|
readonly q: number;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
/**
|
|
27
|
-
* Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
|
|
28
|
-
* clobbering a prior one.
|
|
29
|
-
*
|
|
30
|
-
* @remarks
|
|
31
|
-
* `Headers.append` already accumulates repeated headers (unlike node's
|
|
32
|
-
* `setHeader`), so this is a thin, self-documenting wrapper naming the
|
|
33
|
-
* cookie-append intent — the primitive {@link writeSignedCookie} /
|
|
34
|
-
* {@link clearCookie} use.
|
|
35
|
-
*
|
|
36
|
-
* @param headers - The response `Headers` to write into
|
|
37
|
-
* @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
|
|
38
|
-
*
|
|
39
|
-
* @example
|
|
40
|
-
* ```ts
|
|
41
|
-
* const headers = new Headers()
|
|
42
|
-
* appendCookie(headers, serializeCookie('a', '1'))
|
|
43
|
-
* appendCookie(headers, serializeCookie('b', '2'))
|
|
44
|
-
* headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
|
|
45
|
-
* ```
|
|
46
|
-
*/
|
|
47
|
-
export declare function appendCookie(headers: Headers, cookie: string): void;
|
|
48
|
-
|
|
49
26
|
/**
|
|
50
27
|
* Options for `readBody` — how the shared body-collection pipeline caps and
|
|
51
28
|
* decompresses a request body.
|
|
@@ -69,7 +46,7 @@ export declare interface BodyOptions {
|
|
|
69
46
|
}
|
|
70
47
|
|
|
71
48
|
/**
|
|
72
|
-
*
|
|
49
|
+
* Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
|
|
73
50
|
*
|
|
74
51
|
* @remarks
|
|
75
52
|
* Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
|
|
@@ -89,52 +66,7 @@ export declare interface BodyOptions {
|
|
|
89
66
|
export declare function clearCookie(headers: Headers, name: string, options?: CookieOptions): void;
|
|
90
67
|
|
|
91
68
|
/**
|
|
92
|
-
*
|
|
93
|
-
* its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
|
|
94
|
-
*
|
|
95
|
-
* @remarks
|
|
96
|
-
* A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
|
|
97
|
-
* per-`/128` rate limit is trivially bypassed by rotating host bits — the
|
|
98
|
-
* real identity is the `/64` network. Delegates the IPv6 collapse to
|
|
99
|
-
* {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
|
|
100
|
-
* a malformed string) is kept unchanged.
|
|
101
|
-
*
|
|
102
|
-
* @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
|
|
103
|
-
* @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
|
|
104
|
-
*
|
|
105
|
-
* @example
|
|
106
|
-
* ```ts
|
|
107
|
-
* clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
|
|
108
|
-
* clientRateKey('192.0.2.1') // '192.0.2.1'
|
|
109
|
-
* ```
|
|
110
|
-
*/
|
|
111
|
-
export declare function clientRateKey(address: string): string;
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* The client's quality (q) for one content-coding from the parsed
|
|
115
|
-
* `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
|
|
116
|
-
* server-preference selection.
|
|
117
|
-
*
|
|
118
|
-
* @remarks
|
|
119
|
-
* Prefers an EXACT named match (including an explicit `;q=0` rejection);
|
|
120
|
-
* failing that, a bare `*` wildcard's q applies. A coding that is neither
|
|
121
|
-
* named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
|
|
122
|
-
* over a `*` (a specific rejection beats the wildcard), so it scores `0`.
|
|
123
|
-
*
|
|
124
|
-
* @param entries - The parsed {@link AcceptEntry} list
|
|
125
|
-
* @param coding - The candidate coding to score
|
|
126
|
-
* @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
127
|
-
*
|
|
128
|
-
* @example
|
|
129
|
-
* ```ts
|
|
130
|
-
* codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
|
|
131
|
-
* codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
|
|
132
|
-
* ```
|
|
133
|
-
*/
|
|
134
|
-
export declare function codingQuality(entries: readonly AcceptEntry[], coding: string): number;
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
|
|
69
|
+
* Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.
|
|
138
70
|
*
|
|
139
71
|
* @remarks
|
|
140
72
|
* Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
|
|
@@ -156,8 +88,8 @@ export declare function codingQuality(entries: readonly AcceptEntry[], coding: s
|
|
|
156
88
|
export declare function collectRequestBody(request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
157
89
|
|
|
158
90
|
/**
|
|
159
|
-
*
|
|
160
|
-
* handler into one request handler — the frozen middleware seam
|
|
91
|
+
* Composes an ordered chain of {@link MiddlewareHandler}s around a `terminal`
|
|
92
|
+
* handler into one request handler — the frozen middleware seam.
|
|
161
93
|
*
|
|
162
94
|
* @remarks
|
|
163
95
|
* `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
|
|
@@ -190,7 +122,7 @@ export declare function collectRequestBody(request: Request, limit: number): Pro
|
|
|
190
122
|
export declare function compose<TState>(middleware: ReadonlyArray<MiddlewareHandler<TState>>, terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
|
|
191
123
|
|
|
192
124
|
/**
|
|
193
|
-
*
|
|
125
|
+
* Holds the set of bare `Content-Type`s `isCompressibleType` treats as
|
|
194
126
|
* COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
|
|
195
127
|
* `+xml`) rules that helper also applies.
|
|
196
128
|
*
|
|
@@ -198,13 +130,14 @@ export declare function compose<TState>(middleware: ReadonlyArray<MiddlewareHand
|
|
|
198
130
|
* The text-shaped application types worth compressing (JSON / JavaScript /
|
|
199
131
|
* XML / SVG / WASM / a few document formats) — NOT already-compressed
|
|
200
132
|
* binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
|
|
201
|
-
* `woff2`), which gzip/deflate would only bloat.
|
|
202
|
-
*
|
|
133
|
+
* `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
|
|
134
|
+
* withholds `add` / `delete` / `clear` from the shared default, so a consumer
|
|
135
|
+
* reads it without reaching a mutator.
|
|
203
136
|
*/
|
|
204
137
|
export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
|
|
205
138
|
|
|
206
139
|
/**
|
|
207
|
-
*
|
|
140
|
+
* Computes a CONTENT `ETag` over a fully-buffered response body by using WebCrypto.
|
|
208
141
|
*
|
|
209
142
|
* @remarks
|
|
210
143
|
* Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
|
|
@@ -214,7 +147,8 @@ export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
|
|
|
214
147
|
* (`"<hash>"`, byte-identity) when `weak` is `false`.
|
|
215
148
|
*
|
|
216
149
|
* @param body - The full (uncompressed) response body to hash
|
|
217
|
-
* @param weak - `true`
|
|
150
|
+
* @param weak - If `true` (the default), returns a weak `W/"…"` validator; if
|
|
151
|
+
* `false`, returns a strong `"…"` one.
|
|
218
152
|
* @returns The `ETag` header value
|
|
219
153
|
*
|
|
220
154
|
* @example
|
|
@@ -225,7 +159,98 @@ export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
|
|
|
225
159
|
export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: boolean): Promise<string>;
|
|
226
160
|
|
|
227
161
|
/**
|
|
228
|
-
*
|
|
162
|
+
* Collapses a client IP into its rate-limit BUCKET key — an IPv6 address to
|
|
163
|
+
* its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
|
|
164
|
+
*
|
|
165
|
+
* @remarks
|
|
166
|
+
* A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
|
|
167
|
+
* per-`/128` rate limit is trivially bypassed by rotating host bits — the
|
|
168
|
+
* real identity is the `/64` network. Delegates the IPv6 collapse to
|
|
169
|
+
* {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
|
|
170
|
+
* a malformed string) is kept unchanged.
|
|
171
|
+
*
|
|
172
|
+
* @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})
|
|
173
|
+
* @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```ts
|
|
177
|
+
* computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
|
|
178
|
+
* computeClientKey('192.0.2.1') // '192.0.2.1'
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
export declare function computeClientKey(address: string): string;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Computes the client's quality (q) for one content-coding from the parsed
|
|
185
|
+
* `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over
|
|
186
|
+
* each offered coding.
|
|
187
|
+
*
|
|
188
|
+
* @remarks
|
|
189
|
+
* Prefers an EXACT named match (including an explicit `;q=0` rejection);
|
|
190
|
+
* failing that, a bare `*` wildcard's q applies. A coding that is neither
|
|
191
|
+
* named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
|
|
192
|
+
* over a `*` (a specific rejection beats the wildcard), so it scores `0`.
|
|
193
|
+
*
|
|
194
|
+
* @param entries - The parsed {@link AcceptEntry} list
|
|
195
|
+
* @param coding - The candidate coding to score
|
|
196
|
+
* @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```ts
|
|
200
|
+
* computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
|
|
201
|
+
* computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
export declare function computeCodingQuality(entries: readonly AcceptEntry[], coding: string): number;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Computes the `/64` network of a full IPv6 address, or `undefined` when the
|
|
208
|
+
* input is not a plain IPv6 address to collapse.
|
|
209
|
+
*
|
|
210
|
+
* @remarks
|
|
211
|
+
* Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
|
|
212
|
+
* is the identity) or any string that does not expand to exactly eight
|
|
213
|
+
* hextets. Expands a single `::` into the missing zero hextets, takes the
|
|
214
|
+
* first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
|
|
215
|
+
* zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
|
|
216
|
+
* first. Total — a malformed address returns `undefined`.
|
|
217
|
+
*
|
|
218
|
+
* @param address - The candidate IPv6 address
|
|
219
|
+
* @returns The `/64` network string, or `undefined` when not a plain IPv6 address
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```ts
|
|
223
|
+
* computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
|
|
224
|
+
* computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed
|
|
225
|
+
* ```
|
|
226
|
+
*/
|
|
227
|
+
export declare function computeIPv6Network(address: string): string | undefined;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Computes the client's quality for one `candidate` language from the parsed
|
|
231
|
+
* `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`
|
|
232
|
+
* axis runs over each offered tag.
|
|
233
|
+
*
|
|
234
|
+
* @remarks
|
|
235
|
+
* Prefers an exact match, then a primary-tag prefix match (`en` accepts
|
|
236
|
+
* `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
|
|
237
|
+
* is an explicit rejection).
|
|
238
|
+
*
|
|
239
|
+
* @param entries - The parsed {@link AcceptEntry} list
|
|
240
|
+
* @param candidate - The candidate language tag to score (e.g. `'en-US'`)
|
|
241
|
+
* @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* ```ts
|
|
245
|
+
* computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
|
|
246
|
+
* computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
|
|
247
|
+
* computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
export declare function computeLanguageQuality(entries: readonly AcceptEntry[], candidate: string): number;
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Represents the per-request connection facts the server face injects — the ONLY data
|
|
229
254
|
* that genuinely exists solely on the socket, surfaced so middleware and a
|
|
230
255
|
* consumer's `state` factory stay core-pure.
|
|
231
256
|
*
|
|
@@ -236,22 +261,22 @@ export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: bo
|
|
|
236
261
|
* - `encrypted` — whether the connection is TLS, for an auto-`Secure` cookie
|
|
237
262
|
* decision ({@link CookieOptions.secure} left `undefined`).
|
|
238
263
|
*/
|
|
239
|
-
export declare interface
|
|
264
|
+
export declare interface Connection {
|
|
240
265
|
readonly ip?: string;
|
|
241
266
|
readonly encrypted: boolean;
|
|
242
267
|
}
|
|
243
268
|
|
|
244
269
|
/**
|
|
245
270
|
* Derives a consumer's per-request `TState` from the adapter-injected
|
|
246
|
-
* {@link
|
|
271
|
+
* {@link Connection} — `ServerOptions.state`, invoked once per request
|
|
247
272
|
* before the middleware onion runs.
|
|
248
273
|
*
|
|
249
274
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
250
275
|
*/
|
|
251
|
-
export declare type ConnectionStateFunction<TState> = (connection:
|
|
276
|
+
export declare type ConnectionStateFunction<TState> = (connection: Connection) => TState;
|
|
252
277
|
|
|
253
278
|
/**
|
|
254
|
-
*
|
|
279
|
+
* Represents the {@link HTTPError} thrown when a request body exceeds the body
|
|
255
280
|
* pipeline's size limit — a `413 Content Too Large`.
|
|
256
281
|
*
|
|
257
282
|
* @remarks
|
|
@@ -276,7 +301,7 @@ export declare class ContentTooLargeError extends HTTPError {
|
|
|
276
301
|
}
|
|
277
302
|
|
|
278
303
|
/**
|
|
279
|
-
*
|
|
304
|
+
* Represents the `Set-Cookie` attributes for `serializeCookie` (and any signed-cookie
|
|
280
305
|
* transport built over it).
|
|
281
306
|
*
|
|
282
307
|
* @param path - The `Path` directive; defaults to `'/'`.
|
|
@@ -286,9 +311,9 @@ export declare class ContentTooLargeError extends HTTPError {
|
|
|
286
311
|
* @param httpOnly - The `HttpOnly` directive; defaults to `true`.
|
|
287
312
|
* @param secure - The `Secure` directive: `true` forces it, `false`
|
|
288
313
|
* suppresses it, and omitted/`undefined` (the default) derives it from the
|
|
289
|
-
* connection
|
|
314
|
+
* connection through {@link import('./helpers.js').resolveSecure} — `Secure` on
|
|
290
315
|
* a TLS connection, off over plaintext HTTP ({@link
|
|
291
|
-
*
|
|
316
|
+
* Connection.encrypted}). A `sameSite: 'None'` cookie is ALWAYS
|
|
292
317
|
* `Secure` regardless (the spec requires it).
|
|
293
318
|
* @param sameSite - The `SameSite` directive; defaults to `'Lax'`.
|
|
294
319
|
*/
|
|
@@ -302,13 +327,9 @@ export declare interface CookieOptions {
|
|
|
302
327
|
}
|
|
303
328
|
|
|
304
329
|
/**
|
|
305
|
-
*
|
|
330
|
+
* Creates a {@link NegotiatorInterface} — the reusable content-negotiation
|
|
306
331
|
* machine over the weighted `Accept` family.
|
|
307
332
|
*
|
|
308
|
-
* @remarks
|
|
309
|
-
* Prefer this over `new Negotiator()` at call sites that only need the
|
|
310
|
-
* interface.
|
|
311
|
-
*
|
|
312
333
|
* @returns A {@link NegotiatorInterface}
|
|
313
334
|
*
|
|
314
335
|
* @example
|
|
@@ -323,7 +344,7 @@ export declare interface CookieOptions {
|
|
|
323
344
|
export declare function createNegotiator(): NegotiatorInterface;
|
|
324
345
|
|
|
325
346
|
/**
|
|
326
|
-
*
|
|
347
|
+
* Creates a {@link ServerInterface} — the node face's HTTP server facade over
|
|
327
348
|
* a consumed `@orkestrel/router` dispatcher.
|
|
328
349
|
*
|
|
329
350
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
@@ -349,7 +370,29 @@ export declare function createNegotiator(): NegotiatorInterface;
|
|
|
349
370
|
export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
|
|
350
371
|
|
|
351
372
|
/**
|
|
352
|
-
*
|
|
373
|
+
* Creates a {@link StreamInterface} — a generic Server-Sent-Events stream whose
|
|
374
|
+
* `response` is a fetch-standard streaming `Response` a route returns.
|
|
375
|
+
*
|
|
376
|
+
* @param options - {@link StreamOptions}
|
|
377
|
+
* @returns A {@link StreamInterface} whose stream is open
|
|
378
|
+
*
|
|
379
|
+
* @example
|
|
380
|
+
* ```ts
|
|
381
|
+
* import { createStream } from '@src/server'
|
|
382
|
+
*
|
|
383
|
+
* const stream = createStream()
|
|
384
|
+
* void Promise.resolve().then(async () => {
|
|
385
|
+
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
386
|
+
* stream.comment('keep-alive')
|
|
387
|
+
* stream.end()
|
|
388
|
+
* })
|
|
389
|
+
* // return stream.response from the route handler
|
|
390
|
+
* ```
|
|
391
|
+
*/
|
|
392
|
+
export declare function createStream(options?: StreamOptions): StreamInterface;
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Decodes a cookie value with `decodeURIComponent`, falling back to the raw
|
|
353
396
|
* text when the value is not valid percent-encoding.
|
|
354
397
|
*
|
|
355
398
|
* @param raw - The raw (trimmed) cookie value
|
|
@@ -364,15 +407,15 @@ export declare function createServer<TState>(options: ServerOptions<TState>): Se
|
|
|
364
407
|
export declare function decodeCookieValue(raw: string): string;
|
|
365
408
|
|
|
366
409
|
/**
|
|
367
|
-
*
|
|
410
|
+
* Decodes + narrows a signed token's base64url JSON payload, honoring its
|
|
368
411
|
* expiry — the shared decode step {@link verifyToken} applies after a
|
|
369
412
|
* signature match.
|
|
370
413
|
*
|
|
371
414
|
* @remarks
|
|
372
415
|
* Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
|
|
373
416
|
* non-canonical base64url segment answers `undefined` rather than throwing),
|
|
374
|
-
* reads it as UTF-8 JSON, narrows it to a record with a string `value`
|
|
375
|
-
*
|
|
417
|
+
* reads it as UTF-8 JSON, narrows it to a record with a string `value` without
|
|
418
|
+
* `as`, and rejects an expired `exp`. TOTAL — any
|
|
376
419
|
* decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
|
|
377
420
|
* throws, and its `catch` answers `undefined` too.
|
|
378
421
|
*
|
|
@@ -382,15 +425,15 @@ export declare function decodeCookieValue(raw: string): string;
|
|
|
382
425
|
export declare function decodeTokenPayload(encoded: string): string | undefined;
|
|
383
426
|
|
|
384
427
|
/**
|
|
385
|
-
*
|
|
386
|
-
*
|
|
428
|
+
* Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
|
|
429
|
+
* transparently through `DecompressionStream`, capping the DECOMPRESSED output —
|
|
387
430
|
* the zip-bomb defense.
|
|
388
431
|
*
|
|
389
432
|
* @remarks
|
|
390
433
|
* Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
|
|
391
434
|
* `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
|
|
392
435
|
* total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
|
|
393
|
-
* has no `maxOutputLength` knob
|
|
436
|
+
* has no `maxOutputLength` knob. A cap breach surfaces
|
|
394
437
|
* as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
|
|
395
438
|
* compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
|
|
396
439
|
* (never conflated with the cap). A non-positive `cap` means uncapped.
|
|
@@ -404,11 +447,11 @@ export declare function decodeTokenPayload(encoded: string): string | undefined;
|
|
|
404
447
|
*/
|
|
405
448
|
export declare function decompressRequestBody(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
406
449
|
|
|
407
|
-
/**
|
|
450
|
+
/** Names the default maximum request body size (bytes) `readBody` accepts before a 413. */
|
|
408
451
|
export declare const DEFAULT_BODY_LIMIT = 1048576;
|
|
409
452
|
|
|
410
453
|
/**
|
|
411
|
-
*
|
|
454
|
+
* Names the default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
|
|
412
455
|
* the body pipeline's byte-counting `TransformStream` enforces when
|
|
413
456
|
* transparently decompressing a `Content-Encoding` request body.
|
|
414
457
|
*
|
|
@@ -419,17 +462,20 @@ export declare const DEFAULT_BODY_LIMIT = 1048576;
|
|
|
419
462
|
* output would exceed this, BEFORE the full bomb is materialized, so the
|
|
420
463
|
* inflation can never exhaust memory. Defaults to `16 MiB` — a generous
|
|
421
464
|
* ceiling for a legitimate compressed JSON / form body, far below an OOM. A
|
|
422
|
-
* consumer raises it
|
|
465
|
+
* consumer raises it through {@link import('./types.js').BodyOptions}
|
|
423
466
|
* `decompression` for a workload that genuinely ships larger decompressed
|
|
424
467
|
* bodies.
|
|
425
468
|
*/
|
|
426
469
|
export declare const DEFAULT_DECOMPRESSED_LIMIT = 16777216;
|
|
427
470
|
|
|
428
|
-
/**
|
|
471
|
+
/**
|
|
472
|
+
* Names the default graceful-stop deadline (ms) the server gives in-flight
|
|
473
|
+
* requests on `stop()`.
|
|
474
|
+
*/
|
|
429
475
|
export declare const DEFAULT_DRAIN_MS = 10000;
|
|
430
476
|
|
|
431
477
|
/**
|
|
432
|
-
*
|
|
478
|
+
* Lists the default {@link Encoding} content-codings the substrate offers, in
|
|
433
479
|
* PREFERENCE order — `gzip` / `deflate`.
|
|
434
480
|
*
|
|
435
481
|
* @remarks
|
|
@@ -442,8 +488,8 @@ export declare const DEFAULT_DRAIN_MS = 10000;
|
|
|
442
488
|
export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
443
489
|
|
|
444
490
|
/**
|
|
445
|
-
*
|
|
446
|
-
* OS-assigned port,
|
|
491
|
+
* Finds a FREE TCP port — binds a throwaway `node:net` server, reads the
|
|
492
|
+
* OS-assigned port, closes it, and resolves that port.
|
|
447
493
|
*
|
|
448
494
|
* @remarks
|
|
449
495
|
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
@@ -453,11 +499,16 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
|
453
499
|
* port. It binds then immediately closes a probe server, so the returned
|
|
454
500
|
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
455
501
|
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
456
|
-
* `preferred` port (e.g. a permission fault).
|
|
502
|
+
* `preferred` port (e.g. a permission fault). A listener whose address is not
|
|
503
|
+
* an {@link import('node:net').AddressInfo} — a pipe listener, which this
|
|
504
|
+
* package's options cannot request — rejects with a `TypeError` rather than
|
|
505
|
+
* reporting `0`, because `0` is this package's own request for an ephemeral
|
|
506
|
+
* port and never means an unknown one.
|
|
457
507
|
*
|
|
458
508
|
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
459
509
|
* fall back to an ephemeral port
|
|
460
510
|
* @returns A free TCP port number
|
|
511
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
461
512
|
*
|
|
462
513
|
* @example
|
|
463
514
|
* ```ts
|
|
@@ -469,42 +520,21 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
|
469
520
|
export declare function discoverPort(preferred?: number): Promise<number>;
|
|
470
521
|
|
|
471
522
|
/**
|
|
472
|
-
*
|
|
523
|
+
* Represents a content-coding the substrate compresses / decompresses with — the
|
|
473
524
|
* `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
|
|
474
525
|
*
|
|
475
526
|
* @remarks
|
|
476
527
|
* `gzip` / `deflate` map to `CompressionStream` / `DecompressionStream`
|
|
477
528
|
* (web-standard, no external codec); `identity` is the no-op "uncompressed"
|
|
478
529
|
* coding. Brotli (`br`) has no `CompressionStream` implementation yet, so it
|
|
479
|
-
* is deliberately OMITTED here — Brotli parity is the
|
|
480
|
-
*
|
|
481
|
-
*
|
|
482
|
-
* behavioral toggle (AGENTS §4.4).
|
|
530
|
+
* is deliberately OMITTED here — Brotli parity is the middleware package's
|
|
531
|
+
* node-entry decision, not this core's. A constrained set of external-spec
|
|
532
|
+
* literals, so it stays a union, not a behavioral toggle.
|
|
483
533
|
*/
|
|
484
534
|
export declare type Encoding = 'gzip' | 'deflate' | 'identity';
|
|
485
535
|
|
|
486
536
|
/**
|
|
487
|
-
*
|
|
488
|
-
*
|
|
489
|
-
* @param controller - The stream controller, when the stream has started
|
|
490
|
-
* @param encoder - The encoder used for the stream's byte representation
|
|
491
|
-
* @param closed - Whether the stream has already ended or been cancelled
|
|
492
|
-
* @param text - The text to encode and enqueue
|
|
493
|
-
* @returns Nothing
|
|
494
|
-
*
|
|
495
|
-
* @example
|
|
496
|
-
* ```ts
|
|
497
|
-
* const body = new ReadableStream<Uint8Array>({
|
|
498
|
-
* start(controller) {
|
|
499
|
-
* enqueueStreamText(controller, new TextEncoder(), false, 'hello')
|
|
500
|
-
* },
|
|
501
|
-
* })
|
|
502
|
-
* ```
|
|
503
|
-
*/
|
|
504
|
-
export declare function enqueueStreamText(controller: ReadableStreamDefaultController<Uint8Array> | undefined, encoder: TextEncoder, closed: boolean, text: string): void;
|
|
505
|
-
|
|
506
|
-
/**
|
|
507
|
-
* A map of media type → handler for {@link NegotiatorInterface.format} — the
|
|
537
|
+
* Represents a map of media type → handler for {@link NegotiatorInterface.format} — the
|
|
508
538
|
* content-negotiation dispatch table.
|
|
509
539
|
*
|
|
510
540
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
@@ -522,7 +552,7 @@ export declare function enqueueStreamText(controller: ReadableStreamDefaultContr
|
|
|
522
552
|
export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
|
|
523
553
|
|
|
524
554
|
/**
|
|
525
|
-
*
|
|
555
|
+
* Names the `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
|
|
526
556
|
* an instance thrown by ANOTHER copy of this package (the dual-package
|
|
527
557
|
* hazard — a version-skewed or workspace-linked duplicate install), where
|
|
528
558
|
* `instanceof` alone fails because the two copies' `HTTPError` constructors
|
|
@@ -537,7 +567,7 @@ export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request:
|
|
|
537
567
|
export declare const HTTP_ERROR_BRAND: unique symbol;
|
|
538
568
|
|
|
539
569
|
/**
|
|
540
|
-
*
|
|
570
|
+
* Represents an error a handler (or middleware) throws to produce an HTTP response of a
|
|
541
571
|
* specific status.
|
|
542
572
|
*
|
|
543
573
|
* @remarks
|
|
@@ -548,7 +578,8 @@ export declare const HTTP_ERROR_BRAND: unique symbol;
|
|
|
548
578
|
* deliberate signal), unlike a generic throw whose message is hidden unless
|
|
549
579
|
* `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
|
|
550
580
|
* specific statuses, or throw it directly. Narrow a caught value with
|
|
551
|
-
* {@link isHTTPError}.
|
|
581
|
+
* {@link isHTTPError}. The machine-readable discriminator is `status`; there is
|
|
582
|
+
* no separate `code`.
|
|
552
583
|
*
|
|
553
584
|
* @example
|
|
554
585
|
* ```ts
|
|
@@ -569,36 +600,17 @@ export declare class HTTPError extends Error {
|
|
|
569
600
|
}
|
|
570
601
|
|
|
571
602
|
/**
|
|
572
|
-
*
|
|
573
|
-
* input is not a plain IPv6 address to collapse.
|
|
574
|
-
*
|
|
575
|
-
* @remarks
|
|
576
|
-
* Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
|
|
577
|
-
* is the identity) or any string that does not expand to exactly eight
|
|
578
|
-
* hextets. Expands a single `::` into the missing zero hextets, takes the
|
|
579
|
-
* first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
|
|
580
|
-
* zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
|
|
581
|
-
* first. Total — a malformed address returns `undefined`.
|
|
582
|
-
*
|
|
583
|
-
* @param address - The candidate IPv6 address
|
|
584
|
-
* @returns The `/64` network string, or `undefined` when not a plain IPv6 address
|
|
585
|
-
*
|
|
586
|
-
* @example
|
|
587
|
-
* ```ts
|
|
588
|
-
* ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
|
|
589
|
-
* ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
|
|
590
|
-
* ```
|
|
591
|
-
*/
|
|
592
|
-
export declare function ipv6Network(address: string): string | undefined;
|
|
593
|
-
|
|
594
|
-
/**
|
|
595
|
-
* Whether a `node:net` `server.address()` return is the structured
|
|
603
|
+
* Checks whether a `node:net` `server.address()` return is the structured
|
|
596
604
|
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
597
|
-
* or `null` — the total, never-throwing narrow
|
|
605
|
+
* or `null` — the total, never-throwing narrow `discoverPort`
|
|
598
606
|
* and the `Server`'s own port resolution read the bound port through.
|
|
599
607
|
*
|
|
608
|
+
* @remarks
|
|
609
|
+
* Checks the `address`, `family`, and `port` members `node:net` declares as
|
|
610
|
+
* `string`, `string`, and `number`.
|
|
611
|
+
*
|
|
600
612
|
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
601
|
-
* @returns
|
|
613
|
+
* @returns True if `value` is an `AddressInfo`; false otherwise
|
|
602
614
|
*
|
|
603
615
|
* @example
|
|
604
616
|
* ```ts
|
|
@@ -611,7 +623,7 @@ export declare function ipv6Network(address: string): string | undefined;
|
|
|
611
623
|
export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
612
624
|
|
|
613
625
|
/**
|
|
614
|
-
*
|
|
626
|
+
* Checks whether a `Content-Type` is worth compressing.
|
|
615
627
|
*
|
|
616
628
|
* @remarks
|
|
617
629
|
* Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
|
|
@@ -621,7 +633,7 @@ export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
|
621
633
|
* absent/empty type is not compressible. TOTAL.
|
|
622
634
|
*
|
|
623
635
|
* @param type - The response `Content-Type` header value (with or without parameters)
|
|
624
|
-
* @returns
|
|
636
|
+
* @returns True if the type is text-shaped and worth compressing; false otherwise
|
|
625
637
|
*
|
|
626
638
|
* @example
|
|
627
639
|
* ```ts
|
|
@@ -632,7 +644,7 @@ export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
|
632
644
|
export declare function isCompressibleType(type: string): boolean;
|
|
633
645
|
|
|
634
646
|
/**
|
|
635
|
-
*
|
|
647
|
+
* Checks whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
|
|
636
648
|
* (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
|
|
637
649
|
* attributes with before emitting them.
|
|
638
650
|
*
|
|
@@ -643,7 +655,7 @@ export declare function isCompressibleType(type: string): boolean;
|
|
|
643
655
|
* directive. Total — never throws (a bad value returns `false`).
|
|
644
656
|
*
|
|
645
657
|
* @param value - The candidate attribute value (a `Domain` or `Path`)
|
|
646
|
-
* @returns
|
|
658
|
+
* @returns True if `value` carries no separator / whitespace / control char; false otherwise
|
|
647
659
|
*
|
|
648
660
|
* @example
|
|
649
661
|
* ```ts
|
|
@@ -654,7 +666,7 @@ export declare function isCompressibleType(type: string): boolean;
|
|
|
654
666
|
export declare function isCookieAttribute(value: string): boolean;
|
|
655
667
|
|
|
656
668
|
/**
|
|
657
|
-
*
|
|
669
|
+
* Checks whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
|
|
658
670
|
* cookie-token chars with NO surrounding (or interior) whitespace.
|
|
659
671
|
*
|
|
660
672
|
* @remarks
|
|
@@ -664,7 +676,7 @@ export declare function isCookieAttribute(value: string): boolean;
|
|
|
664
676
|
* `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
|
|
665
677
|
*
|
|
666
678
|
* @param value - The candidate cookie name
|
|
667
|
-
* @returns
|
|
679
|
+
* @returns True if `value` is a valid, whitespace-free cookie token; false otherwise
|
|
668
680
|
*
|
|
669
681
|
* @example
|
|
670
682
|
* ```ts
|
|
@@ -675,12 +687,12 @@ export declare function isCookieAttribute(value: string): boolean;
|
|
|
675
687
|
export declare function isCookieName(value: string): boolean;
|
|
676
688
|
|
|
677
689
|
/**
|
|
678
|
-
*
|
|
690
|
+
* Checks whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
|
|
679
691
|
* or `prototype` — the three keys that, assigned onto a normal object, can
|
|
680
692
|
* reach and mutate `Object.prototype`.
|
|
681
693
|
*
|
|
682
694
|
* @param key - The candidate object key
|
|
683
|
-
* @returns
|
|
695
|
+
* @returns True if `key` is one of the three prototype-pollution keys; false otherwise
|
|
684
696
|
*
|
|
685
697
|
* @example
|
|
686
698
|
* ```ts
|
|
@@ -691,18 +703,18 @@ export declare function isCookieName(value: string): boolean;
|
|
|
691
703
|
export declare function isDangerousKey(key: string): boolean;
|
|
692
704
|
|
|
693
705
|
/**
|
|
694
|
-
*
|
|
706
|
+
* Narrows an unknown caught value to an {@link HTTPError} (including its
|
|
695
707
|
* subclasses, e.g. {@link ContentTooLargeError}).
|
|
696
708
|
*
|
|
697
709
|
* @param value - The value to test (typically a `catch` binding)
|
|
698
|
-
* @returns
|
|
710
|
+
* @returns True if `value` is an {@link HTTPError}; false otherwise
|
|
699
711
|
*
|
|
700
712
|
* @remarks
|
|
701
713
|
* Tries `instanceof` first, then falls back to a total structural check for
|
|
702
714
|
* an instance built by a DIFFERENT copy of this package (the dual-package
|
|
703
715
|
* hazard — version skew, a linked workspace duplicate) whose `HTTPError`
|
|
704
716
|
* constructor is a distinct object from this copy's: the value must carry
|
|
705
|
-
* the cross-copy brand (interned
|
|
717
|
+
* the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
|
|
706
718
|
* same key) AND expose the exact fields the server's error boundary reads off
|
|
707
719
|
* a recognized `HTTPError` — a numeric `status` and a string `message`. A
|
|
708
720
|
* plain object that merely carries a `status` WITHOUT the brand is rejected.
|
|
@@ -721,7 +733,36 @@ export declare function isDangerousKey(key: string): boolean;
|
|
|
721
733
|
export declare function isHTTPError(value: unknown): value is HTTPError;
|
|
722
734
|
|
|
723
735
|
/**
|
|
724
|
-
*
|
|
736
|
+
* Narrows an unknown caught value to a {@link ServerError}.
|
|
737
|
+
*
|
|
738
|
+
* @param value - The value to test (typically a `catch` binding)
|
|
739
|
+
* @returns True if `value` is a {@link ServerError}; false otherwise
|
|
740
|
+
*
|
|
741
|
+
* @remarks
|
|
742
|
+
* Recognizes an instance built by THIS copy of the package. A `ServerError`
|
|
743
|
+
* is raised by a `Server` to the caller that just invoked it, so both sides
|
|
744
|
+
* hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
|
|
745
|
+
* consumer here.
|
|
746
|
+
*
|
|
747
|
+
* @example
|
|
748
|
+
* ```ts
|
|
749
|
+
* import { createServer, isServerError } from '@src/server'
|
|
750
|
+
* import { createDispatcher } from '@orkestrel/router'
|
|
751
|
+
*
|
|
752
|
+
* const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })
|
|
753
|
+
* await server.start()
|
|
754
|
+
* try {
|
|
755
|
+
* await server.start()
|
|
756
|
+
* } catch (error) {
|
|
757
|
+
* if (isServerError(error)) console.log(error.code) // 'STATUS'
|
|
758
|
+
* }
|
|
759
|
+
* await server.stop()
|
|
760
|
+
* ```
|
|
761
|
+
*/
|
|
762
|
+
export declare function isServerError(value: unknown): value is ServerError;
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Checks whether a client-supplied `X-Request-ID` is SAFE to echo into a response
|
|
725
766
|
* header + `context.state`.
|
|
726
767
|
*
|
|
727
768
|
* @remarks
|
|
@@ -732,7 +773,7 @@ export declare function isHTTPError(value: unknown): value is HTTPError;
|
|
|
732
773
|
* TOTAL — never throws.
|
|
733
774
|
*
|
|
734
775
|
* @param value - The candidate incoming request id
|
|
735
|
-
* @returns
|
|
776
|
+
* @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
|
|
736
777
|
*
|
|
737
778
|
* @example
|
|
738
779
|
* ```ts
|
|
@@ -743,29 +784,7 @@ export declare function isHTTPError(value: unknown): value is HTTPError;
|
|
|
743
784
|
export declare function isValidRequestId(value: string): boolean;
|
|
744
785
|
|
|
745
786
|
/**
|
|
746
|
-
*
|
|
747
|
-
* `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
|
|
748
|
-
*
|
|
749
|
-
* @remarks
|
|
750
|
-
* Prefers an exact match, then a primary-tag prefix match (`en` accepts
|
|
751
|
-
* `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
|
|
752
|
-
* is an explicit rejection).
|
|
753
|
-
*
|
|
754
|
-
* @param entries - The parsed {@link AcceptEntry} list
|
|
755
|
-
* @param candidate - The candidate language tag to score (e.g. `'en-US'`)
|
|
756
|
-
* @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
757
|
-
*
|
|
758
|
-
* @example
|
|
759
|
-
* ```ts
|
|
760
|
-
* languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
|
|
761
|
-
* languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
|
|
762
|
-
* languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
|
|
763
|
-
* ```
|
|
764
|
-
*/
|
|
765
|
-
export declare function languageQuality(entries: readonly AcceptEntry[], candidate: string): number;
|
|
766
|
-
|
|
767
|
-
/**
|
|
768
|
-
* Whether a request's `If-None-Match` header matches a resource's current
|
|
787
|
+
* Checks whether a request's `If-None-Match` header matches a resource's current
|
|
769
788
|
* `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
|
|
770
789
|
*
|
|
771
790
|
* @remarks
|
|
@@ -773,12 +792,12 @@ export declare function languageQuality(entries: readonly AcceptEntry[], candida
|
|
|
773
792
|
* listed tag matches), or the `*` wildcard (matches ANY current
|
|
774
793
|
* representation — only a list of exactly `*` is the wildcard). Comparison is
|
|
775
794
|
* WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
|
|
776
|
-
*
|
|
795
|
+
* through {@link unwrapETag} before comparing the opaque body). TOTAL — a
|
|
777
796
|
* malformed/empty header matches nothing, never throws.
|
|
778
797
|
*
|
|
779
798
|
* @param header - The raw `If-None-Match` header value
|
|
780
799
|
* @param etag - The resource's current `ETag`
|
|
781
|
-
* @returns
|
|
800
|
+
* @returns True if the conditional matches (the caller answers `304`); false otherwise
|
|
782
801
|
*
|
|
783
802
|
* @example
|
|
784
803
|
* ```ts
|
|
@@ -789,7 +808,7 @@ export declare function languageQuality(entries: readonly AcceptEntry[], candida
|
|
|
789
808
|
export declare function matchesETag(header: string, etag: string): boolean;
|
|
790
809
|
|
|
791
810
|
/**
|
|
792
|
-
*
|
|
811
|
+
* Reports the rank + quality of one `candidate` media type against the parsed `Accept`
|
|
793
812
|
* entries — the generic media-type primitive the `Negotiator`'s `negotiate`
|
|
794
813
|
* uses to score each `available` candidate.
|
|
795
814
|
*
|
|
@@ -804,7 +823,7 @@ export declare function matchesETag(header: string, etag: string): boolean;
|
|
|
804
823
|
*
|
|
805
824
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
806
825
|
* @param candidate - The candidate media type to score (e.g. `'text/html'`)
|
|
807
|
-
* @returns The
|
|
826
|
+
* @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
|
|
808
827
|
*
|
|
809
828
|
* @example
|
|
810
829
|
* ```ts
|
|
@@ -814,13 +833,26 @@ export declare function matchesETag(header: string, etag: string): boolean;
|
|
|
814
833
|
* matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
|
|
815
834
|
* ```
|
|
816
835
|
*/
|
|
817
|
-
export declare function matchMediaType(entries: readonly AcceptEntry[], candidate: string):
|
|
836
|
+
export declare function matchMediaType(entries: readonly AcceptEntry[], candidate: string): MediaMatch | undefined;
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Rates one candidate media type against a parsed `Accept` header — the
|
|
840
|
+
* quality and specificity `matchMediaType` reports for the best matching
|
|
841
|
+
* {@link AcceptEntry}.
|
|
842
|
+
*
|
|
843
|
+
* @remarks
|
|
844
|
+
* `q` is the client's quality weight in `[0, 1]`. `rank` is the specificity of
|
|
845
|
+
* the entry that matched: `0` for an exact type, `1` for a subtype wildcard
|
|
846
|
+
* (`type/*`), `2` for the any-range (`* / *`). A lower `rank` wins, and a
|
|
847
|
+
* higher `q` breaks a rank tie.
|
|
848
|
+
*/
|
|
849
|
+
export declare interface MediaMatch {
|
|
818
850
|
readonly q: number;
|
|
819
851
|
readonly rank: number;
|
|
820
|
-
}
|
|
852
|
+
}
|
|
821
853
|
|
|
822
854
|
/**
|
|
823
|
-
*
|
|
855
|
+
* Merges a `Vary` value into an existing `Vary` header without duplication.
|
|
824
856
|
*
|
|
825
857
|
* @remarks
|
|
826
858
|
* Splits `existing` on `,`, trims each member, and appends `value` only when
|
|
@@ -842,7 +874,7 @@ export declare function matchMediaType(entries: readonly AcceptEntry[], candidat
|
|
|
842
874
|
export declare function mergeVary(existing: string | undefined, value: string): string;
|
|
843
875
|
|
|
844
876
|
/**
|
|
845
|
-
*
|
|
877
|
+
* Represents the composition context — plain data, one per request, shared by every
|
|
846
878
|
* middleware AND (as `state`) by the route handlers behind the dispatcher.
|
|
847
879
|
*
|
|
848
880
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
@@ -876,14 +908,14 @@ export declare interface MiddlewareContext<TState> {
|
|
|
876
908
|
}
|
|
877
909
|
|
|
878
910
|
/**
|
|
879
|
-
*
|
|
911
|
+
* Represents one link in the middleware onion — runs around the rest of the chain.
|
|
880
912
|
*
|
|
881
913
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
882
914
|
*
|
|
883
915
|
* @remarks
|
|
884
916
|
* Transform the request (call `next(newRequest)`), transform the response
|
|
885
917
|
* (`await next()` then modify the result), short-circuit (return a `Response`
|
|
886
|
-
* without calling `next`), or thread data
|
|
918
|
+
* without calling `next`), or thread data through `context.state` — no mutable
|
|
887
919
|
* framework object anywhere, only fetch-standard `Request`/`Response`.
|
|
888
920
|
*
|
|
889
921
|
* @example
|
|
@@ -898,15 +930,15 @@ export declare interface MiddlewareContext<TState> {
|
|
|
898
930
|
export declare type MiddlewareHandler<TState> = (request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response | Promise<Response>;
|
|
899
931
|
|
|
900
932
|
/**
|
|
901
|
-
*
|
|
933
|
+
* Selects the best content-coding for a raw `Accept-Encoding` header from the
|
|
902
934
|
* codings the server offers.
|
|
903
935
|
*
|
|
904
936
|
* @remarks
|
|
905
|
-
* Parses the header ({@link parseAcceptHeader}) and
|
|
906
|
-
*
|
|
907
|
-
* the
|
|
908
|
-
* client
|
|
909
|
-
*
|
|
937
|
+
* Parses the header ({@link parseAcceptHeader}) and hands the entries to
|
|
938
|
+
* {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
|
|
939
|
+
* the two doors onto this axis cannot drift. Returns `undefined` when the
|
|
940
|
+
* client accepts none of `available` (identity — no compression). TOTAL on
|
|
941
|
+
* hostile input.
|
|
910
942
|
*
|
|
911
943
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
912
944
|
* @param header - The raw `Accept-Encoding` header value
|
|
@@ -921,7 +953,7 @@ export declare type MiddlewareHandler<TState> = (request: Request, context: Midd
|
|
|
921
953
|
export declare function negotiateEncoding<T extends string>(header: string, available: readonly T[]): T | undefined;
|
|
922
954
|
|
|
923
955
|
/**
|
|
924
|
-
*
|
|
956
|
+
* Represents the content-negotiation machine over the weighted `Accept` family — a
|
|
925
957
|
* reusable, cross-middleware ENTITY (not a middleware). Implements exactly
|
|
926
958
|
* {@link NegotiatorInterface}.
|
|
927
959
|
*
|
|
@@ -945,6 +977,9 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
945
977
|
encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
|
|
946
978
|
language(header: string, available: readonly string[]): string | undefined;
|
|
947
979
|
/**
|
|
980
|
+
* Dispatches the request to the handler its `Accept` header negotiates,
|
|
981
|
+
* answering 406 when none matches.
|
|
982
|
+
*
|
|
948
983
|
* @remarks
|
|
949
984
|
* Errors thrown by the negotiated handler propagate UNMODIFIED — the
|
|
950
985
|
* server boundary classifies them, never this negotiator.
|
|
@@ -953,7 +988,7 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
953
988
|
}
|
|
954
989
|
|
|
955
990
|
/**
|
|
956
|
-
*
|
|
991
|
+
* Represents content negotiation over the weighted `Accept` family — a reusable,
|
|
957
992
|
* cross-middleware machine (not itself a middleware).
|
|
958
993
|
*
|
|
959
994
|
* @remarks
|
|
@@ -975,7 +1010,7 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
975
1010
|
*/
|
|
976
1011
|
export declare interface NegotiatorInterface {
|
|
977
1012
|
/**
|
|
978
|
-
*
|
|
1013
|
+
* Picks the best `available` value for a weighted `Accept`-style `header` —
|
|
979
1014
|
* the generic media-type primitive (`encoding` / `language` build on it).
|
|
980
1015
|
*
|
|
981
1016
|
* @param header - The raw weighted header value (e.g. `text/html, application/json;q=0.9`)
|
|
@@ -984,16 +1019,25 @@ export declare interface NegotiatorInterface {
|
|
|
984
1019
|
*/
|
|
985
1020
|
negotiate(header: string, available: readonly string[]): string | undefined;
|
|
986
1021
|
/**
|
|
987
|
-
*
|
|
988
|
-
* —
|
|
1022
|
+
* Picks the best `available` content-coding for an `Accept-Encoding` header
|
|
1023
|
+
* — the coding axis of the same q-value parser (a bare `*` wildcard ⇒ the
|
|
1024
|
+
* first `available`).
|
|
989
1025
|
*
|
|
990
1026
|
* @param header - The raw `Accept-Encoding` header value (e.g. `gzip;q=1.0, deflate;q=0.8`)
|
|
991
1027
|
* @param available - The codings the server offers, in preference order
|
|
992
1028
|
* @returns The best acceptable coding, or `undefined` when none is
|
|
1029
|
+
*
|
|
1030
|
+
* @remarks
|
|
1031
|
+
* An absent, empty, or unparseable header resolves to `undefined` — no
|
|
1032
|
+
* compression — rather than to the first offered coding, because an absent
|
|
1033
|
+
* `Accept-Encoding` makes identity the correct answer.
|
|
1034
|
+
* {@link NegotiatorInterface.negotiate} and
|
|
1035
|
+
* {@link NegotiatorInterface.language} fall back to the first offered value
|
|
1036
|
+
* instead.
|
|
993
1037
|
*/
|
|
994
1038
|
encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
|
|
995
1039
|
/**
|
|
996
|
-
*
|
|
1040
|
+
* Picks the best `available` language for an `Accept-Language` header —
|
|
997
1041
|
* `negotiate` with a language-prefix match (`en` accepts `en-US`) and a
|
|
998
1042
|
* bare `*` wildcard.
|
|
999
1043
|
*
|
|
@@ -1003,9 +1047,9 @@ export declare interface NegotiatorInterface {
|
|
|
1003
1047
|
*/
|
|
1004
1048
|
language(header: string, available: readonly string[]): string | undefined;
|
|
1005
1049
|
/**
|
|
1006
|
-
*
|
|
1007
|
-
* the request `Accept`,
|
|
1008
|
-
* winner; `406` when none is acceptable.
|
|
1050
|
+
* Dispatches to the handler whose media type the client most prefers —
|
|
1051
|
+
* reads the request `Accept`, negotiates against `handlers`' keys, and
|
|
1052
|
+
* invokes the winner; `406` when none is acceptable.
|
|
1009
1053
|
*
|
|
1010
1054
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1011
1055
|
* @param request - The in-flight `Request`
|
|
@@ -1017,7 +1061,7 @@ export declare interface NegotiatorInterface {
|
|
|
1017
1061
|
}
|
|
1018
1062
|
|
|
1019
1063
|
/**
|
|
1020
|
-
*
|
|
1064
|
+
* Represents the downstream continuation a {@link MiddlewareHandler} invokes to run the
|
|
1021
1065
|
* rest of the onion.
|
|
1022
1066
|
*
|
|
1023
1067
|
* @remarks
|
|
@@ -1033,7 +1077,7 @@ export declare interface NegotiatorInterface {
|
|
|
1033
1077
|
export declare type NextFunction = (request?: Request) => Promise<Response>;
|
|
1034
1078
|
|
|
1035
1079
|
/**
|
|
1036
|
-
*
|
|
1080
|
+
* Normalizes a {@link TokenSecret} to a concrete list of USABLE secrets —
|
|
1037
1081
|
* backs both {@link signToken} and {@link verifyToken}.
|
|
1038
1082
|
*
|
|
1039
1083
|
* @remarks
|
|
@@ -1053,49 +1097,7 @@ export declare type NextFunction = (request?: Request) => Promise<Response>;
|
|
|
1053
1097
|
export declare function normalizeSecret(secret: TokenSecret): readonly string[];
|
|
1054
1098
|
|
|
1055
1099
|
/**
|
|
1056
|
-
*
|
|
1057
|
-
* whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
|
|
1058
|
-
*
|
|
1059
|
-
* @remarks
|
|
1060
|
-
* Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
|
|
1061
|
-
* merged under any `options.headers` (a seam-owned key is never overridden),
|
|
1062
|
-
* at `options.status` (default `200`). The returned {@link StreamInterface}'s
|
|
1063
|
-
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
1064
|
-
* returns whether the controller still has positive desired size. A producer
|
|
1065
|
-
* receiving `false` can await `drain()`; its event-driven promise resolves on
|
|
1066
|
-
* the next consumer pull that restores capacity, or on stream closure.
|
|
1067
|
-
* `comment` writes a `: text` keep-alive line a conforming parser ignores;
|
|
1068
|
-
* `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
|
|
1069
|
-
* by `end()`, or the consumer cancelled the stream), so a late write never
|
|
1070
|
-
* throws.
|
|
1071
|
-
*
|
|
1072
|
-
* This readiness reflects only the process-local `ReadableStream` queue — it
|
|
1073
|
-
* is not proof that a remote peer consumed bytes. When the response pump
|
|
1074
|
-
* honors its socket sink's drain state, socket pressure stops body pulls and
|
|
1075
|
-
* therefore keeps this queue full, allowing a cooperative producer to bound
|
|
1076
|
-
* buffering. Ignoring the return value preserves the prior unconditional-
|
|
1077
|
-
* enqueue behavior. The default stream strategy counts chunks rather than
|
|
1078
|
-
* their byte length, so a byte-bounded producer must also cap each message.
|
|
1079
|
-
* Return `response` before awaiting a `false` write, because the consumer
|
|
1080
|
-
* cannot pull until it receives the response.
|
|
1081
|
-
*
|
|
1082
|
-
* @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
|
|
1083
|
-
* @returns The {@link StreamInterface} handle
|
|
1084
|
-
*
|
|
1085
|
-
* @example
|
|
1086
|
-
* ```ts
|
|
1087
|
-
* const stream = openStream()
|
|
1088
|
-
* void Promise.resolve().then(async () => {
|
|
1089
|
-
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
1090
|
-
* stream.end()
|
|
1091
|
-
* })
|
|
1092
|
-
* // return stream.response from the route handler
|
|
1093
|
-
* ```
|
|
1094
|
-
*/
|
|
1095
|
-
export declare function openStream(options?: StreamOptions): StreamInterface;
|
|
1096
|
-
|
|
1097
|
-
/**
|
|
1098
|
-
* Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
1100
|
+
* Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
1099
1101
|
* into its q-sorted entries.
|
|
1100
1102
|
*
|
|
1101
1103
|
* @remarks
|
|
@@ -1120,7 +1122,7 @@ export declare function openStream(options?: StreamOptions): StreamInterface;
|
|
|
1120
1122
|
export declare function parseAcceptHeader(header: string): readonly AcceptEntry[];
|
|
1121
1123
|
|
|
1122
1124
|
/**
|
|
1123
|
-
*
|
|
1125
|
+
* Parses a raw `Cookie:` request header into a `name → value` lookup.
|
|
1124
1126
|
*
|
|
1125
1127
|
* @remarks
|
|
1126
1128
|
* Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
|
|
@@ -1130,7 +1132,7 @@ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[
|
|
|
1130
1132
|
* {@link isCookieName} rather than silently reconciling into a
|
|
1131
1133
|
* prefix-protected `__Host-` name. A pair without `=`, or with an invalid
|
|
1132
1134
|
* name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
|
|
1133
|
-
* malformed header yields an empty record, never throws
|
|
1135
|
+
* malformed header yields an empty record, never throws.
|
|
1134
1136
|
*
|
|
1135
1137
|
* @param header - The raw `Cookie` header value (possibly `undefined`)
|
|
1136
1138
|
* @returns A record of every parsed cookie, `name → decoded value`
|
|
@@ -1143,7 +1145,30 @@ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[
|
|
|
1143
1145
|
export declare function parseCookies(header: string | undefined): Record<string, string>;
|
|
1144
1146
|
|
|
1145
1147
|
/**
|
|
1146
|
-
*
|
|
1148
|
+
* Parses a raw `Content-Encoding` header value into a decompressible
|
|
1149
|
+
* {@link Encoding} — the boundary {@link readBody} coerces through to decide
|
|
1150
|
+
* whether a request body needs transparent decompression.
|
|
1151
|
+
*
|
|
1152
|
+
* @remarks
|
|
1153
|
+
* Lower-cases + trims and returns the matching {@link Encoding} ONLY for
|
|
1154
|
+
* `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
|
|
1155
|
+
* absent header, `identity`, an unknown value, or a
|
|
1156
|
+
* comma-joined multi-coding all yield `undefined` (the body is read as-is).
|
|
1157
|
+
* TOTAL — never asserts the loose `string | null` header.
|
|
1158
|
+
*
|
|
1159
|
+
* @param header - The raw `Content-Encoding` header value
|
|
1160
|
+
* @returns The single decompressible {@link Encoding}, or `undefined` when none applies
|
|
1161
|
+
*
|
|
1162
|
+
* @example
|
|
1163
|
+
* ```ts
|
|
1164
|
+
* parseEncoding('gzip') // 'gzip'
|
|
1165
|
+
* parseEncoding('br') // undefined — unsupported by DecompressionStream
|
|
1166
|
+
* ```
|
|
1167
|
+
*/
|
|
1168
|
+
export declare function parseEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined;
|
|
1169
|
+
|
|
1170
|
+
/**
|
|
1171
|
+
* Parses an HTTP `Range` request header against a known resource `size` —
|
|
1147
1172
|
* TOTAL, returning a {@link RangeSpec} or `undefined`.
|
|
1148
1173
|
*
|
|
1149
1174
|
* @remarks
|
|
@@ -1170,10 +1195,17 @@ export declare function parseCookies(header: string | undefined): Record<string,
|
|
|
1170
1195
|
export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
|
|
1171
1196
|
|
|
1172
1197
|
/**
|
|
1173
|
-
*
|
|
1198
|
+
* Binds and closes a throwaway TCP server to resolve one available port.
|
|
1199
|
+
*
|
|
1200
|
+
* @remarks
|
|
1201
|
+
* The probe always closes, including on the rejection path. A listener whose
|
|
1202
|
+
* address is not an {@link import('node:net').AddressInfo} — a pipe listener,
|
|
1203
|
+
* which a numeric `port` cannot request — has no port to report, so this
|
|
1204
|
+
* rejects rather than substituting a number.
|
|
1174
1205
|
*
|
|
1175
1206
|
* @param port - The requested port, with `0` selecting an ephemeral port
|
|
1176
1207
|
* @returns The bound port after the probe server has closed
|
|
1208
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
1177
1209
|
*
|
|
1178
1210
|
* @example
|
|
1179
1211
|
* ```ts
|
|
@@ -1183,7 +1215,7 @@ export declare function parseRange(header: string | undefined, size: number): Ra
|
|
|
1183
1215
|
export declare function probePort(port: number): Promise<number>;
|
|
1184
1216
|
|
|
1185
1217
|
/**
|
|
1186
|
-
*
|
|
1218
|
+
* Represents the parsed outcome of an HTTP `Range` request header.
|
|
1187
1219
|
*
|
|
1188
1220
|
* @remarks
|
|
1189
1221
|
* A `Range: bytes=start-end` against a known resource `size` resolves to ONE
|
|
@@ -1209,7 +1241,7 @@ export declare type RangeSpec = {
|
|
|
1209
1241
|
};
|
|
1210
1242
|
|
|
1211
1243
|
/**
|
|
1212
|
-
*
|
|
1244
|
+
* Collects + decodes a `Request` body — the shared body-collection pipeline
|
|
1213
1245
|
* surfaced to middleware and handlers as the middleware context's cached
|
|
1214
1246
|
* `body()`.
|
|
1215
1247
|
*
|
|
@@ -1220,14 +1252,20 @@ export declare type RangeSpec = {
|
|
|
1220
1252
|
* through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
|
|
1221
1253
|
* `options.decompression`, default {@link
|
|
1222
1254
|
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
|
|
1223
|
-
* content type: `application/json` is parsed
|
|
1255
|
+
* content type: `application/json` is parsed by using `@orkestrel/contract`'s
|
|
1224
1256
|
* `parseJSON` and scrubbed of prototype-pollution keys ({@link
|
|
1225
1257
|
* scrubPrototype}); any other type decodes as UTF-8 text; an empty body
|
|
1226
1258
|
* decodes to `undefined`.
|
|
1227
1259
|
*
|
|
1260
|
+
* A malformed JSON body is total: it decodes to `undefined` rather than
|
|
1261
|
+
* throwing, so a handler that must reject one checks for `undefined` itself.
|
|
1262
|
+
* That makes `undefined` the answer for two distinct inputs, and nothing in the
|
|
1263
|
+
* returned value tells them apart.
|
|
1264
|
+
*
|
|
1228
1265
|
* @param request - The `Request` to read the body from
|
|
1229
1266
|
* @param options - The {@link BodyOptions} `limit` + `decompression` caps
|
|
1230
|
-
* @returns The parsed JSON value, the raw text, or `undefined` for an empty
|
|
1267
|
+
* @returns The parsed JSON value, the raw text, or `undefined` — for an empty
|
|
1268
|
+
* body, and for an `application/json` body whose text is not valid JSON
|
|
1231
1269
|
* @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
|
|
1232
1270
|
* @throws {HTTPError} When the compressed body is corrupt (400)
|
|
1233
1271
|
*
|
|
@@ -1239,7 +1277,7 @@ export declare type RangeSpec = {
|
|
|
1239
1277
|
export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;
|
|
1240
1278
|
|
|
1241
1279
|
/**
|
|
1242
|
-
*
|
|
1280
|
+
* Reads + verifies a SIGNED cookie off a request — TOTAL, returning the
|
|
1243
1281
|
* embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
|
|
1244
1282
|
*
|
|
1245
1283
|
* @remarks
|
|
@@ -1261,40 +1299,58 @@ export declare function readBody(request: Request, options?: BodyOptions): Promi
|
|
|
1261
1299
|
export declare function readSignedCookie(request: Request, name: string, secret: TokenSecret): Promise<string | undefined>;
|
|
1262
1300
|
|
|
1263
1301
|
/**
|
|
1264
|
-
*
|
|
1302
|
+
* Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
|
|
1265
1303
|
* to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
|
|
1266
1304
|
* / control-char-bearing incoming id is REJECTED (a fresh id is minted
|
|
1267
|
-
* instead) rather than ever riding into a response header or `context.state
|
|
1268
|
-
*
|
|
1269
|
-
* shared default.
|
|
1305
|
+
* instead) rather than ever riding into a response header or `context.state`.
|
|
1306
|
+
* Frozen so a consumer can read but never mutate the shared default.
|
|
1270
1307
|
*/
|
|
1271
1308
|
export declare const REQUEST_ID_PATTERN: Readonly<RegExp>;
|
|
1272
1309
|
|
|
1273
1310
|
/**
|
|
1274
|
-
*
|
|
1275
|
-
*
|
|
1276
|
-
* whether a request body needs transparent decompression.
|
|
1311
|
+
* Identifies the request a server-level fault came from — its method and its
|
|
1312
|
+
* parsed URL.
|
|
1277
1313
|
*
|
|
1278
1314
|
* @remarks
|
|
1279
|
-
*
|
|
1280
|
-
*
|
|
1281
|
-
* the
|
|
1282
|
-
*
|
|
1283
|
-
|
|
1315
|
+
* Carried by {@link ServerEventMap.error}'s optional second element and by
|
|
1316
|
+
* {@link ServerOptions.report}'s optional second parameter, and present only
|
|
1317
|
+
* when the fault happened on the per-request path — an upgrade-handler throw
|
|
1318
|
+
* or a listen failure has no fetch `Request` to derive it from.
|
|
1319
|
+
*/
|
|
1320
|
+
export declare interface RequestLine {
|
|
1321
|
+
readonly method: string;
|
|
1322
|
+
readonly url: URL;
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
/**
|
|
1326
|
+
* Picks the highest-scoring content-coding the server offers against already
|
|
1327
|
+
* parsed `Accept-Encoding` entries.
|
|
1284
1328
|
*
|
|
1285
|
-
* @
|
|
1286
|
-
*
|
|
1329
|
+
* @remarks
|
|
1330
|
+
* The single selection leaf behind both doors onto this axis —
|
|
1331
|
+
* {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the
|
|
1332
|
+
* entity — so the scoring loop has one implementation. Scores each `available`
|
|
1333
|
+
* coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
|
|
1334
|
+
* keeps the earlier-offered coding on a client-side tie, which is what makes
|
|
1335
|
+
* `available` the SERVER's preference order. An empty `available` list, and a
|
|
1336
|
+
* list the client rejects outright, both yield `undefined` (identity — no
|
|
1337
|
+
* compression). TOTAL on hostile input.
|
|
1338
|
+
*
|
|
1339
|
+
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
1340
|
+
* @param entries - The parsed {@link AcceptEntry} list
|
|
1341
|
+
* @param available - The codings the server offers, in preference (tie-break) order
|
|
1342
|
+
* @returns The winning coding, or `undefined` when none of `available` is acceptable
|
|
1287
1343
|
*
|
|
1288
1344
|
* @example
|
|
1289
1345
|
* ```ts
|
|
1290
|
-
*
|
|
1291
|
-
*
|
|
1346
|
+
* resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'
|
|
1347
|
+
* resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined
|
|
1292
1348
|
* ```
|
|
1293
1349
|
*/
|
|
1294
|
-
export declare function
|
|
1350
|
+
export declare function resolveCoding<T extends string>(entries: readonly AcceptEntry[], available: readonly T[]): T | undefined;
|
|
1295
1351
|
|
|
1296
1352
|
/**
|
|
1297
|
-
*
|
|
1353
|
+
* Resolves the `Access-Control-Allow-Origin` value for a request.
|
|
1298
1354
|
*
|
|
1299
1355
|
* @remarks
|
|
1300
1356
|
* `'*'` and a single origin string pass straight through. An allow-list
|
|
@@ -1317,7 +1373,7 @@ export declare function requestEncoding(header: string | null): Exclude<Encoding
|
|
|
1317
1373
|
export declare function resolveOrigin(origin: string | readonly string[], requestOrigin: string | undefined): string | undefined;
|
|
1318
1374
|
|
|
1319
1375
|
/**
|
|
1320
|
-
*
|
|
1376
|
+
* Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}
|
|
1321
1377
|
* `secure` setting and whether the request arrived over TLS.
|
|
1322
1378
|
*
|
|
1323
1379
|
* @remarks
|
|
@@ -1327,7 +1383,10 @@ export declare function resolveOrigin(origin: string | readonly string[], reques
|
|
|
1327
1383
|
* gets `Secure` automatically while local-dev HTTP still works.
|
|
1328
1384
|
*
|
|
1329
1385
|
* @param secure - The {@link CookieOptions} `secure` setting
|
|
1330
|
-
* @param encrypted - The connection's TLS flag
|
|
1386
|
+
* @param encrypted - The connection's TLS flag
|
|
1387
|
+
* ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted
|
|
1388
|
+
* `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to
|
|
1389
|
+
* no `Secure` attribute.
|
|
1331
1390
|
* @returns The concrete `Secure` flag to emit
|
|
1332
1391
|
*
|
|
1333
1392
|
* @example
|
|
@@ -1340,11 +1399,11 @@ export declare function resolveOrigin(origin: string | readonly string[], reques
|
|
|
1340
1399
|
export declare function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean;
|
|
1341
1400
|
|
|
1342
1401
|
/**
|
|
1343
|
-
*
|
|
1402
|
+
* Resolves one opt-out, value-bearing security header.
|
|
1344
1403
|
*
|
|
1345
1404
|
* @remarks
|
|
1346
1405
|
* The shared "a `string` value, or `false` to omit, or a default when unset"
|
|
1347
|
-
* resolution (
|
|
1406
|
+
* resolution (a value-or-off union, not a behavioral toggle):
|
|
1348
1407
|
* `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
|
|
1349
1408
|
* override, `undefined` (unset) ⇒ `fallback` (the secure default).
|
|
1350
1409
|
*
|
|
@@ -1362,8 +1421,24 @@ export declare function resolveSecure(secure: boolean | undefined, encrypted: bo
|
|
|
1362
1421
|
export declare function resolveSecurityHeader(value: string | false | undefined, fallback: string): string | undefined;
|
|
1363
1422
|
|
|
1364
1423
|
/**
|
|
1365
|
-
*
|
|
1366
|
-
*
|
|
1424
|
+
* Records one finished request — the payload {@link ServerEventMap.response}
|
|
1425
|
+
* carries.
|
|
1426
|
+
*
|
|
1427
|
+
* @remarks
|
|
1428
|
+
* `method` and `pathname` come from the parsed request, `status` is the status
|
|
1429
|
+
* actually sent (on the success path or the outer-boundary error path), and
|
|
1430
|
+
* `ms` is the elapsed time in whole milliseconds.
|
|
1431
|
+
*/
|
|
1432
|
+
export declare interface ResponseRecord {
|
|
1433
|
+
readonly method: string;
|
|
1434
|
+
readonly pathname: string;
|
|
1435
|
+
readonly status: number;
|
|
1436
|
+
readonly ms: number;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
/**
|
|
1440
|
+
* Strips the prototype-pollution keys from a parsed value IN PLACE,
|
|
1441
|
+
* recursively.
|
|
1367
1442
|
*
|
|
1368
1443
|
* @remarks
|
|
1369
1444
|
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
|
|
@@ -1386,7 +1461,7 @@ export declare function resolveSecurityHeader(value: string | false | undefined,
|
|
|
1386
1461
|
export declare function scrubPrototype(value: unknown): unknown;
|
|
1387
1462
|
|
|
1388
1463
|
/**
|
|
1389
|
-
*
|
|
1464
|
+
* Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
|
|
1390
1465
|
*
|
|
1391
1466
|
* @remarks
|
|
1392
1467
|
* URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
|
|
@@ -1394,10 +1469,9 @@ export declare function scrubPrototype(value: unknown): unknown;
|
|
|
1394
1469
|
* `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
|
|
1395
1470
|
* (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
|
|
1396
1471
|
* with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
|
|
1397
|
-
* injection attempt (a programmer misconfiguration
|
|
1398
|
-
* silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
|
|
1472
|
+
* injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
|
|
1399
1473
|
* the `secure` option (the spec requires it); an un-resolved `undefined`
|
|
1400
|
-
* `secure` here falls to OFF — request-aware callers resolve it first
|
|
1474
|
+
* `secure` here falls to OFF — request-aware callers resolve it first through
|
|
1401
1475
|
* {@link resolveSecure}.
|
|
1402
1476
|
*
|
|
1403
1477
|
* @param name - The cookie name
|
|
@@ -1414,7 +1488,7 @@ export declare function scrubPrototype(value: unknown): unknown;
|
|
|
1414
1488
|
export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
|
|
1415
1489
|
|
|
1416
1490
|
/**
|
|
1417
|
-
*
|
|
1491
|
+
* Serializes one {@link SSEMessage} to the SSE wire.
|
|
1418
1492
|
*
|
|
1419
1493
|
* @remarks
|
|
1420
1494
|
* Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
|
|
@@ -1435,14 +1509,14 @@ export declare function serializeCookie(name: string, value: string, options?: C
|
|
|
1435
1509
|
export declare function serializeEvent(message: SSEMessage): string;
|
|
1436
1510
|
|
|
1437
1511
|
/**
|
|
1438
|
-
*
|
|
1512
|
+
* Represents the HTTP server facade — an observable `node:http` lifecycle composing this
|
|
1439
1513
|
* module's own middleware onion around a consumed `@orkestrel/router`
|
|
1440
1514
|
* dispatcher.
|
|
1441
1515
|
*
|
|
1442
1516
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1443
1517
|
*
|
|
1444
1518
|
* @remarks
|
|
1445
|
-
* - **Lifecycle
|
|
1519
|
+
* - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
|
|
1446
1520
|
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
1447
1521
|
* ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
|
|
1448
1522
|
* bound address), exposes that {@link AddressInfo} through `address`, observes
|
|
@@ -1456,15 +1530,15 @@ export declare function serializeEvent(message: SSEMessage): string;
|
|
|
1456
1530
|
* busy-loop), then closes → `stopped`, forcing whatever the deadline caught
|
|
1457
1531
|
* still open. `destroy()` is the idempotent final teardown.
|
|
1458
1532
|
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
1459
|
-
* `close`); a `Request` is built
|
|
1460
|
-
* `signal` LINKED to this run's stop signal
|
|
1533
|
+
* `close`); a `Request` is built through the router's `buildRequest`, its
|
|
1534
|
+
* `signal` LINKED to this run's stop signal through `@orkestrel/abort`'s
|
|
1461
1535
|
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
1462
1536
|
* `buildRequest`'s own abort, armed by BOTH request-side and response-side
|
|
1463
|
-
* teardown, composes with the server's stop signal
|
|
1464
|
-
* so a handler awaiting `request.signal` observes BOTH); `context.state` is built
|
|
1537
|
+
* teardown, composes with the server's stop signal through `AbortSignal.any`,
|
|
1538
|
+
* so a handler awaiting `request.signal` observes BOTH); `context.state` is built through
|
|
1465
1539
|
* {@link ServerOptions.state} from the connection facts; the composed
|
|
1466
1540
|
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
1467
|
-
* written back
|
|
1541
|
+
* written back through `sendResponse`.
|
|
1468
1542
|
* - **The built-in boundary** wraps the WHOLE per-request chain, including
|
|
1469
1543
|
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1470
1544
|
* throw (e.g. a malformed `Host` header) to a silent `400` with no
|
|
@@ -1482,14 +1556,14 @@ export declare function serializeEvent(message: SSEMessage): string;
|
|
|
1482
1556
|
* A CLAIMED socket joins `#upgraded` until it closes: the claimant still
|
|
1483
1557
|
* owns it, and the tracking exists because node detaches an upgraded socket
|
|
1484
1558
|
* from the set its own close calls walk, so nothing else can end it.
|
|
1485
|
-
* - **Observable
|
|
1559
|
+
* - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
1486
1560
|
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
1487
1561
|
* routes it to the `error` OPTION (not the domain `error` event).
|
|
1488
1562
|
*/
|
|
1489
1563
|
export declare class Server<TState> implements ServerInterface<TState> {
|
|
1490
1564
|
#private;
|
|
1491
|
-
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
1492
1565
|
constructor(options: ServerOptions<TState>);
|
|
1566
|
+
get id(): string;
|
|
1493
1567
|
get status(): ServerStatus;
|
|
1494
1568
|
get port(): number | undefined;
|
|
1495
1569
|
get address(): AddressInfo | undefined;
|
|
@@ -1504,7 +1578,54 @@ export declare class Server<TState> implements ServerInterface<TState> {
|
|
|
1504
1578
|
}
|
|
1505
1579
|
|
|
1506
1580
|
/**
|
|
1507
|
-
*
|
|
1581
|
+
* Represents the error this package raises when a caller programmed a call the
|
|
1582
|
+
* entity refuses.
|
|
1583
|
+
*
|
|
1584
|
+
* @remarks
|
|
1585
|
+
* Carries a machine-readable {@link ServerErrorCode} and an optional `context`
|
|
1586
|
+
* record naming the offending facts. This is a PROGRAMMER error, so it carries
|
|
1587
|
+
* no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
|
|
1588
|
+
* invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
|
|
1589
|
+
* middleware into the request boundary, which reaches it as a generic 500 with
|
|
1590
|
+
* the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
|
|
1591
|
+
* client-facing fault instead. Narrow a caught value with
|
|
1592
|
+
* {@link isServerError}.
|
|
1593
|
+
*
|
|
1594
|
+
* @example
|
|
1595
|
+
* ```ts
|
|
1596
|
+
* import { ServerError } from '@src/server'
|
|
1597
|
+
*
|
|
1598
|
+
* const error = new ServerError('STATUS', "server cannot start from 'listening'", {
|
|
1599
|
+
* status: 'listening',
|
|
1600
|
+
* })
|
|
1601
|
+
* error.code // 'STATUS'
|
|
1602
|
+
* ```
|
|
1603
|
+
*/
|
|
1604
|
+
export declare class ServerError extends Error {
|
|
1605
|
+
readonly code: ServerErrorCode;
|
|
1606
|
+
readonly context?: Readonly<Record<string, unknown>>;
|
|
1607
|
+
constructor(code: ServerErrorCode, message: string, context?: Readonly<Record<string, unknown>>);
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
/**
|
|
1611
|
+
* Represents the machine-readable category a
|
|
1612
|
+
* {@link import('./errors.js').ServerError} carries.
|
|
1613
|
+
*
|
|
1614
|
+
* @remarks
|
|
1615
|
+
* A `ServerError` reports a call the caller programmed and the substrate
|
|
1616
|
+
* refuses, not a client-facing fault — {@link import('./errors.js').HTTPError}
|
|
1617
|
+
* owns the latter and keys on `status` instead. The categories are disjoint, so
|
|
1618
|
+
* a `catch` narrowed by {@link import('./errors.js').isServerError} reads `code`
|
|
1619
|
+
* to tell them apart.
|
|
1620
|
+
*/
|
|
1621
|
+
export declare type ServerErrorCode =
|
|
1622
|
+
/** Identifies a lifecycle call the current {@link ServerStatus} forbids. */
|
|
1623
|
+
'STATUS'
|
|
1624
|
+
/** Identifies a middleware that called its `next` a second time within one invocation. */
|
|
1625
|
+
| 'NEXT';
|
|
1626
|
+
|
|
1627
|
+
/**
|
|
1628
|
+
* Represents the `Server`'s observable lifecycle events.
|
|
1508
1629
|
*
|
|
1509
1630
|
* @remarks
|
|
1510
1631
|
* - `start` — `listen()` resolved; carries the actually-bound port (an
|
|
@@ -1538,24 +1659,14 @@ export declare type ServerEventMap = {
|
|
|
1538
1659
|
readonly start: readonly [port: number];
|
|
1539
1660
|
readonly request: readonly [method: string, pathname: string];
|
|
1540
1661
|
readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
|
|
1541
|
-
readonly error: readonly [error: unknown, request?:
|
|
1542
|
-
method: string;
|
|
1543
|
-
url: URL;
|
|
1544
|
-
}];
|
|
1662
|
+
readonly error: readonly [error: unknown, request?: RequestLine];
|
|
1545
1663
|
readonly stop: readonly [];
|
|
1546
1664
|
readonly drain: readonly [pending: number, upgraded: number];
|
|
1547
|
-
readonly response: readonly [
|
|
1548
|
-
event: {
|
|
1549
|
-
method: string;
|
|
1550
|
-
pathname: string;
|
|
1551
|
-
status: number;
|
|
1552
|
-
ms: number;
|
|
1553
|
-
}
|
|
1554
|
-
];
|
|
1665
|
+
readonly response: readonly [event: ResponseRecord];
|
|
1555
1666
|
};
|
|
1556
1667
|
|
|
1557
1668
|
/**
|
|
1558
|
-
*
|
|
1669
|
+
* Represents the HTTP server facade — an observable `node:http` lifecycle that composes
|
|
1559
1670
|
* a middleware onion (this module's own middleware seam) around a consumed
|
|
1560
1671
|
* `@orkestrel/router` {@link DispatcherInterface}.
|
|
1561
1672
|
*
|
|
@@ -1572,34 +1683,65 @@ export declare type ServerEventMap = {
|
|
|
1572
1683
|
* connections, fires the stop signal so in-flight handlers can observe it,
|
|
1573
1684
|
* drains in-flight requests and claimed upgraded sockets up to the configured
|
|
1574
1685
|
* deadline, then closes — forcing whatever is left. `destroy()` is the final
|
|
1575
|
-
* idempotent teardown. Per request: a `Request` is built
|
|
1686
|
+
* idempotent teardown. Per request: a `Request` is built through the router's
|
|
1576
1687
|
* `buildRequest` (its signal linked to the server's stop signal), the composed
|
|
1577
1688
|
* middleware onion runs terminating in `dispatcher.handle`, and the result is
|
|
1578
|
-
* written back
|
|
1689
|
+
* written back through `sendResponse` — every escaping throw is caught by the
|
|
1579
1690
|
* built-in boundary (`HTTPError` → its status; anything else → a
|
|
1580
1691
|
* hidden-unless-`expose` `500`) so a handler error can never crash the process.
|
|
1581
1692
|
*/
|
|
1582
1693
|
export declare interface ServerInterface<TState> {
|
|
1694
|
+
/** Holds the instance's correlation id, minted once per `Server` and stable for its lifetime. */
|
|
1583
1695
|
readonly id: string;
|
|
1696
|
+
/** Reports the current lifecycle phase — see {@link ServerStatus}. */
|
|
1584
1697
|
readonly status: ServerStatus;
|
|
1698
|
+
/**
|
|
1699
|
+
* Holds the bound listener's TCP port — the `port` of {@link address} — or
|
|
1700
|
+
* `undefined` while no listener is active.
|
|
1701
|
+
*/
|
|
1585
1702
|
readonly port: number | undefined;
|
|
1586
|
-
/**
|
|
1703
|
+
/** Holds the bound listener address, or `undefined` while no listener is active. */
|
|
1587
1704
|
readonly address: AddressInfo | undefined;
|
|
1705
|
+
/** Holds the `@orkestrel/router` dispatcher the composed middleware onion terminates into. */
|
|
1588
1706
|
readonly dispatcher: DispatcherInterface<TState>;
|
|
1707
|
+
/** Holds the lifecycle emitter over {@link ServerEventMap}. */
|
|
1589
1708
|
readonly emitter: EmitterInterface<ServerEventMap>;
|
|
1709
|
+
/**
|
|
1710
|
+
* Appends one middleware, or an array of them in order, to the onion.
|
|
1711
|
+
*
|
|
1712
|
+
* @param middleware - One handler, or the ordered array of handlers to append
|
|
1713
|
+
*
|
|
1714
|
+
* @remarks
|
|
1715
|
+
* Callable before or after `start()`; an appended handler runs on the next
|
|
1716
|
+
* request the composed onion serves.
|
|
1717
|
+
*/
|
|
1590
1718
|
use(middleware: MiddlewareHandler<TState>): void;
|
|
1591
1719
|
use(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void;
|
|
1720
|
+
/**
|
|
1721
|
+
* Registers a protocol-upgrade claimant that runs in registration order.
|
|
1722
|
+
*
|
|
1723
|
+
* @param handler - The claimant; the first to return `true` claims the socket
|
|
1724
|
+
*/
|
|
1592
1725
|
upgrade(handler: UpgradeHandler): void;
|
|
1593
1726
|
/**
|
|
1594
|
-
*
|
|
1727
|
+
* Binds the configured listener and resolves its actually-bound port.
|
|
1595
1728
|
*
|
|
1596
1729
|
* @param signal - Optional caller cancellation observed only while startup
|
|
1597
1730
|
* is pending; aborting after this method resolves does not stop the server.
|
|
1598
1731
|
* @returns The actually-bound TCP port
|
|
1732
|
+
*
|
|
1733
|
+
* @remarks
|
|
1734
|
+
* Rejects with a {@link import('./errors.js').ServerError} of code
|
|
1735
|
+
* `'STATUS'` when the current {@link ServerStatus} is neither `'idle'` nor
|
|
1736
|
+
* `'stopped'`, carrying that status in its `context`. Narrow it with
|
|
1737
|
+
* {@link import('./errors.js').isServerError}. A listener whose address is
|
|
1738
|
+
* not an `AddressInfo` — a pipe listener, which this package's options
|
|
1739
|
+
* cannot request — closes the partial listener and rejects with a
|
|
1740
|
+
* `TypeError` rather than reporting `0`.
|
|
1599
1741
|
*/
|
|
1600
1742
|
start(signal?: AbortSignal): Promise<number>;
|
|
1601
1743
|
/**
|
|
1602
|
-
*
|
|
1744
|
+
* Stops gracefully: refuses new connections, fires the stop signal, drains, closes.
|
|
1603
1745
|
*
|
|
1604
1746
|
* @remarks
|
|
1605
1747
|
* Drainable work is every in-flight request PLUS every upgraded socket a
|
|
@@ -1614,7 +1756,7 @@ export declare interface ServerInterface<TState> {
|
|
|
1614
1756
|
*/
|
|
1615
1757
|
stop(): Promise<void>;
|
|
1616
1758
|
/**
|
|
1617
|
-
*
|
|
1759
|
+
* Tears down for good: force-closes the listener and every socket, then the emitter.
|
|
1618
1760
|
*
|
|
1619
1761
|
* @returns Resolves once nothing is left open; idempotent from any state
|
|
1620
1762
|
*/
|
|
@@ -1632,7 +1774,7 @@ export declare interface ServerInterface<TState> {
|
|
|
1632
1774
|
* is never implicitly trusted here; a deployment behind a trusted proxy
|
|
1633
1775
|
* derives its own client key in this function or in middleware.
|
|
1634
1776
|
* @param middleware - Initial middleware, run in array order (outer-first);
|
|
1635
|
-
* more may be added later
|
|
1777
|
+
* more may be added later by using `use`.
|
|
1636
1778
|
* @param host - The network interface `start()` binds to (`node:http`
|
|
1637
1779
|
* `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
|
|
1638
1780
|
* @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
|
|
@@ -1672,9 +1814,9 @@ export declare interface ServerInterface<TState> {
|
|
|
1672
1814
|
* to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
|
|
1673
1815
|
* `maxRequestsPerSocket` (`0` disables the limit). Every present value must
|
|
1674
1816
|
* be a non-negative integer. Omitted leaves preserve node's defaults.
|
|
1675
|
-
* @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
|
|
1676
|
-
*
|
|
1677
|
-
* @param error - The emitter's listener-error handler
|
|
1817
|
+
* @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap},
|
|
1818
|
+
* wiring initial lifecycle listeners at construction.
|
|
1819
|
+
* @param error - The emitter's listener-error handler — a
|
|
1678
1820
|
* listener throw routes here, never to the domain `error` event.
|
|
1679
1821
|
*/
|
|
1680
1822
|
export declare interface ServerOptions<TState> {
|
|
@@ -1686,10 +1828,7 @@ export declare interface ServerOptions<TState> {
|
|
|
1686
1828
|
readonly drain?: number;
|
|
1687
1829
|
readonly limit?: number;
|
|
1688
1830
|
readonly expose?: boolean;
|
|
1689
|
-
readonly report?: (error: unknown, request?:
|
|
1690
|
-
method: string;
|
|
1691
|
-
url: URL;
|
|
1692
|
-
}) => void;
|
|
1831
|
+
readonly report?: (error: unknown, request?: RequestLine) => void;
|
|
1693
1832
|
readonly timeouts?: {
|
|
1694
1833
|
readonly start?: number;
|
|
1695
1834
|
readonly request?: number;
|
|
@@ -1706,7 +1845,7 @@ export declare interface ServerOptions<TState> {
|
|
|
1706
1845
|
}
|
|
1707
1846
|
|
|
1708
1847
|
/**
|
|
1709
|
-
*
|
|
1848
|
+
* Represents the `Server`'s lifecycle state.
|
|
1710
1849
|
*
|
|
1711
1850
|
* @remarks
|
|
1712
1851
|
* `idle` (never started, or a fresh instance) → `starting` (binding the
|
|
@@ -1718,17 +1857,17 @@ export declare interface ServerOptions<TState> {
|
|
|
1718
1857
|
export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
|
|
1719
1858
|
|
|
1720
1859
|
/**
|
|
1721
|
-
*
|
|
1860
|
+
* Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
|
|
1722
1861
|
*
|
|
1723
1862
|
* @remarks
|
|
1724
1863
|
* The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
|
|
1725
1864
|
* absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
|
|
1726
1865
|
* the expiry is HMAC-COVERED — a client cannot extend it without invalidating
|
|
1727
|
-
* the signature), signed
|
|
1866
|
+
* the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the FIRST
|
|
1728
1867
|
* {@link TokenSecret} (the current secret, or the head of a rotation list).
|
|
1729
1868
|
* Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
|
|
1730
1869
|
* misconfigured secret with no usable entry THROWS an {@link HTTPError}
|
|
1731
|
-
* (`500`) — fail-closed, a programmer error
|
|
1870
|
+
* (`500`) — fail-closed, a programmer error. Verify with
|
|
1732
1871
|
* {@link verifyToken}. Omitting `ttl` mints a token that never expires.
|
|
1733
1872
|
*
|
|
1734
1873
|
* @param value - The opaque value to embed (a session id, a deployment marker)
|
|
@@ -1745,20 +1884,21 @@ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping
|
|
|
1745
1884
|
export declare function signToken(value: string, options: TokenOptions): Promise<string>;
|
|
1746
1885
|
|
|
1747
1886
|
/**
|
|
1748
|
-
*
|
|
1887
|
+
* Holds the SSE response headers a `Stream` always sets on its response.
|
|
1749
1888
|
*
|
|
1750
1889
|
* @remarks
|
|
1751
1890
|
* `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
|
|
1752
1891
|
* keeps a proxy from caching the stream; `keep-alive` holds the connection
|
|
1753
1892
|
* open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
|
|
1754
1893
|
* events flush promptly rather than batching. Frozen so a consumer can read
|
|
1755
|
-
* but never mutate the shared default; `
|
|
1756
|
-
* {@link import('./types.js').StreamOptions.headers}
|
|
1894
|
+
* but never mutate the shared default; a `Stream` merges any
|
|
1895
|
+
* {@link import('./types.js').StreamOptions.headers} OVER these, so a caller
|
|
1896
|
+
* repeating one of these keys replaces its value.
|
|
1757
1897
|
*/
|
|
1758
1898
|
export declare const SSE_HEADERS: Readonly<Record<string, string>>;
|
|
1759
1899
|
|
|
1760
1900
|
/**
|
|
1761
|
-
*
|
|
1901
|
+
* Represents one Server-Sent Event to serialize to the wire.
|
|
1762
1902
|
*
|
|
1763
1903
|
* @remarks
|
|
1764
1904
|
* - `data` — the event payload (required). Serialized as one or more `data:`
|
|
@@ -1772,16 +1912,72 @@ export declare const SSE_HEADERS: Readonly<Record<string, string>>;
|
|
|
1772
1912
|
*/
|
|
1773
1913
|
export declare interface SSEMessage {
|
|
1774
1914
|
readonly data: string;
|
|
1775
|
-
/**
|
|
1915
|
+
/** Requires a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
|
|
1776
1916
|
readonly event?: string;
|
|
1777
|
-
/**
|
|
1917
|
+
/** Requires a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
|
|
1778
1918
|
readonly id?: string;
|
|
1779
1919
|
readonly retry?: number;
|
|
1780
1920
|
}
|
|
1781
1921
|
|
|
1782
1922
|
/**
|
|
1783
|
-
*
|
|
1784
|
-
* `Response
|
|
1923
|
+
* Represents the Server-Sent-Events handle over an open, fetch-standard streaming
|
|
1924
|
+
* `Response`. Implements exactly {@link StreamInterface}.
|
|
1925
|
+
*
|
|
1926
|
+
* @remarks
|
|
1927
|
+
* Builds the `Response` at construction from
|
|
1928
|
+
* {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
|
|
1929
|
+
* merged OVER them, at `options.status` (default `200`). A caller repeating one
|
|
1930
|
+
* of those keys therefore replaces the seam's value, in any casing. The
|
|
1931
|
+
* instance owns the stream's
|
|
1932
|
+
* controller, its text encoder, the closed flag, and the parked producer's
|
|
1933
|
+
* wakeup, so the whole handle is one entity rather than a closure over four
|
|
1934
|
+
* bindings.
|
|
1935
|
+
*
|
|
1936
|
+
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
1937
|
+
* returns whether the controller still has positive desired size. A producer
|
|
1938
|
+
* receiving `false` awaits `drain()`; that promise resolves on the next
|
|
1939
|
+
* consumer pull restoring capacity, or on stream closure. `comment` writes a
|
|
1940
|
+
* `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
|
|
1941
|
+
* stream. Every method is a SAFE NO-OP once `closed` (ended by `end()`, or
|
|
1942
|
+
* the consumer cancelled the stream), so a late write never throws.
|
|
1943
|
+
*
|
|
1944
|
+
* The readiness signal reflects only the process-local `ReadableStream`
|
|
1945
|
+
* queue — it is not proof that a remote peer consumed bytes. When the response
|
|
1946
|
+
* pump honors its socket sink's drain state, socket pressure stops body pulls
|
|
1947
|
+
* and therefore keeps this queue full, letting a cooperative producer bound
|
|
1948
|
+
* its buffering. Ignoring the return value preserves an unconditional-enqueue
|
|
1949
|
+
* producer. The default stream strategy counts chunks rather than their byte
|
|
1950
|
+
* length, so a byte-bounded producer must also cap each message. Return
|
|
1951
|
+
* `response` before awaiting a `false` write, because the consumer cannot pull
|
|
1952
|
+
* until it receives the response.
|
|
1953
|
+
*
|
|
1954
|
+
* @example
|
|
1955
|
+
* ```ts
|
|
1956
|
+
* import { Stream } from '@src/server'
|
|
1957
|
+
*
|
|
1958
|
+
* const stream = new Stream()
|
|
1959
|
+
* void Promise.resolve().then(async () => {
|
|
1960
|
+
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
1961
|
+
* stream.comment('keep-alive')
|
|
1962
|
+
* stream.end()
|
|
1963
|
+
* })
|
|
1964
|
+
* // return stream.response from the route handler
|
|
1965
|
+
* ```
|
|
1966
|
+
*/
|
|
1967
|
+
export declare class Stream implements StreamInterface {
|
|
1968
|
+
#private;
|
|
1969
|
+
constructor(options?: StreamOptions);
|
|
1970
|
+
get response(): Response;
|
|
1971
|
+
get closed(): boolean;
|
|
1972
|
+
write(message: SSEMessage): boolean;
|
|
1973
|
+
comment(text: string): void;
|
|
1974
|
+
drain(): Promise<void>;
|
|
1975
|
+
end(): void;
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
/**
|
|
1979
|
+
* Represents a handle to write Server-Sent Events to an open, fetch-standard streaming
|
|
1980
|
+
* `Response` — the generic streaming surface `createStream` returns over a
|
|
1785
1981
|
* `ReadableStream`.
|
|
1786
1982
|
*
|
|
1787
1983
|
* @remarks
|
|
@@ -1808,28 +2004,28 @@ export declare interface SSEMessage {
|
|
|
1808
2004
|
* until it receives the response.
|
|
1809
2005
|
*/
|
|
1810
2006
|
export declare interface StreamInterface {
|
|
1811
|
-
/**
|
|
2007
|
+
/** Holds the streaming `Response` to return from the route handler. */
|
|
1812
2008
|
readonly response: Response;
|
|
1813
|
-
/**
|
|
2009
|
+
/** Reports whether the underlying stream is done (ended, or the consumer disconnected). */
|
|
1814
2010
|
readonly closed: boolean;
|
|
1815
2011
|
/**
|
|
1816
|
-
*
|
|
2012
|
+
* Serializes + enqueues one {@link SSEMessage} to the wire.
|
|
1817
2013
|
*
|
|
1818
2014
|
* @param message - The event to send (its `data` split on `\n` into `data:` lines)
|
|
1819
|
-
* @returns
|
|
1820
|
-
* accepting the event;
|
|
1821
|
-
* closed. A `false` event was still accepted unless `closed` was already
|
|
2015
|
+
* @returns True if the process-local stream queue has capacity after
|
|
2016
|
+
* accepting the event; false otherwise — the queue is full or the stream
|
|
2017
|
+
* is closed. A `false` event was still accepted unless `closed` was already
|
|
1822
2018
|
* `true`; await {@link drain} before producing another event.
|
|
1823
2019
|
*/
|
|
1824
2020
|
write(message: SSEMessage): boolean;
|
|
1825
2021
|
/**
|
|
1826
|
-
*
|
|
2022
|
+
* Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores.
|
|
1827
2023
|
*
|
|
1828
2024
|
* @param text - The comment text (sent after the `: ` prefix)
|
|
1829
2025
|
*/
|
|
1830
2026
|
comment(text: string): void;
|
|
1831
2027
|
/**
|
|
1832
|
-
*
|
|
2028
|
+
* Parks until the process-local stream queue has capacity again.
|
|
1833
2029
|
*
|
|
1834
2030
|
* @returns A promise that resolves when a consumer pull restores positive
|
|
1835
2031
|
* desired size, or immediately when capacity is already available or the
|
|
@@ -1837,18 +2033,19 @@ export declare interface StreamInterface {
|
|
|
1837
2033
|
* not prove that a remote peer consumed the queued bytes.
|
|
1838
2034
|
*/
|
|
1839
2035
|
drain(): Promise<void>;
|
|
1840
|
-
/**
|
|
2036
|
+
/** Ends the stream, completing the response (a no-op once already `closed`). */
|
|
1841
2037
|
end(): void;
|
|
1842
2038
|
}
|
|
1843
2039
|
|
|
1844
2040
|
/**
|
|
1845
|
-
* Options for
|
|
2041
|
+
* Options for a {@link StreamInterface} — how `createStream` opens the
|
|
2042
|
+
* streaming response.
|
|
1846
2043
|
*
|
|
1847
2044
|
* @param status - The HTTP status the streaming response is opened with;
|
|
1848
2045
|
* defaults to `200`.
|
|
1849
|
-
* @param headers - Extra response headers merged
|
|
1850
|
-
* seam always sets ({@link SSE_HEADERS})
|
|
1851
|
-
*
|
|
2046
|
+
* @param headers - Extra response headers merged OVER the SSE headers the
|
|
2047
|
+
* seam always sets ({@link SSE_HEADERS}); a caller repeating one of those
|
|
2048
|
+
* keys replaces the seam's value, in any casing.
|
|
1852
2049
|
*/
|
|
1853
2050
|
export declare interface StreamOptions {
|
|
1854
2051
|
readonly status?: number;
|
|
@@ -1872,7 +2069,7 @@ export declare interface TokenOptions {
|
|
|
1872
2069
|
}
|
|
1873
2070
|
|
|
1874
2071
|
/**
|
|
1875
|
-
*
|
|
2072
|
+
* Represents a secret (or rotation list) for signing + verifying a stateless, HMAC-signed
|
|
1876
2073
|
* token.
|
|
1877
2074
|
*
|
|
1878
2075
|
* @remarks
|
|
@@ -1885,7 +2082,7 @@ export declare interface TokenOptions {
|
|
|
1885
2082
|
export declare type TokenSecret = string | readonly string[];
|
|
1886
2083
|
|
|
1887
2084
|
/**
|
|
1888
|
-
*
|
|
2085
|
+
* Strips the WEAK indicator (`W/`) from an entity-tag, returning its opaque
|
|
1889
2086
|
* comparison body — the reduction {@link matchesETag} applies to both sides
|
|
1890
2087
|
* before the RFC 7232 §2.3.2 weak comparison.
|
|
1891
2088
|
*
|
|
@@ -1900,17 +2097,17 @@ export declare type TokenSecret = string | readonly string[];
|
|
|
1900
2097
|
export declare function unwrapETag(tag: string): string;
|
|
1901
2098
|
|
|
1902
2099
|
/**
|
|
1903
|
-
*
|
|
2100
|
+
* Represents a raw `node:http` protocol-upgrade claimant — registered through
|
|
1904
2101
|
* {@link ServerInterface.upgrade}.
|
|
1905
2102
|
*
|
|
1906
2103
|
* @remarks
|
|
1907
|
-
* Fan-out semantics
|
|
2104
|
+
* Fan-out semantics: handlers run in registration
|
|
1908
2105
|
* order, the FIRST to return `true` CLAIMS (owns) the socket and stops the
|
|
1909
2106
|
* fan-out; a handler that THROWS is treated as declined (the throw surfaces
|
|
1910
2107
|
* on the `error` event) and the fan-out continues; if NONE claim it, the
|
|
1911
2108
|
* socket is destroyed so an unhandled upgrade never leaks a dangling
|
|
1912
2109
|
* connection. `request` / `socket` / `head` are node's own raw values, handed
|
|
1913
|
-
* over verbatim — no assertion at this boundary
|
|
2110
|
+
* over verbatim — no assertion at this boundary.
|
|
1914
2111
|
*
|
|
1915
2112
|
* A CLAIMED socket is TRACKED until it closes. The handler still owns it —
|
|
1916
2113
|
* the server only watches — but `stop()` now drains that socket like an
|
|
@@ -1925,25 +2122,25 @@ export declare function unwrapETag(tag: string): string;
|
|
|
1925
2122
|
* @param request - The raw `node:http` upgrade request
|
|
1926
2123
|
* @param socket - The raw, now-detached `Duplex` connection
|
|
1927
2124
|
* @param head - The first packet of the upgraded stream, if any
|
|
1928
|
-
* @returns
|
|
1929
|
-
*
|
|
2125
|
+
* @returns True if the handler CLAIMS the socket (this handler now owns
|
|
2126
|
+
* it); false otherwise, declining so a later handler can try
|
|
1930
2127
|
*/
|
|
1931
2128
|
export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
1932
2129
|
|
|
1933
2130
|
/**
|
|
1934
|
-
*
|
|
2131
|
+
* Verifies a stateless token and returns its embedded value — TOTAL, never throws.
|
|
1935
2132
|
*
|
|
1936
2133
|
* @remarks
|
|
1937
2134
|
* The inverse of {@link signToken}: splits the token on its LAST `.` (so a
|
|
1938
2135
|
* value containing dots survives), decodes the signature with
|
|
1939
2136
|
* `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
|
|
1940
2137
|
* base64url is refused there, before any key import — and checks the payload's
|
|
1941
|
-
* HMAC-SHA256 signature against EACH {@link TokenSecret} candidate
|
|
2138
|
+
* HMAC-SHA256 signature against EACH {@link TokenSecret} candidate through
|
|
1942
2139
|
* `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
|
|
1943
|
-
* retired
|
|
2140
|
+
* retired), accepting the token on the first match (the
|
|
1944
2141
|
* rotation path). It then decodes + narrows the payload (`isRecord` +
|
|
1945
|
-
* `typeof`, never `as`
|
|
1946
|
-
*
|
|
2142
|
+
* `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
|
|
2143
|
+
* token. ANY failure — a malformed token, a bad signature,
|
|
1947
2144
|
* a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
|
|
1948
2145
|
* yields `undefined` rather than throwing.
|
|
1949
2146
|
*
|
|
@@ -1959,7 +2156,7 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
|
|
|
1959
2156
|
export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
|
|
1960
2157
|
|
|
1961
2158
|
/**
|
|
1962
|
-
*
|
|
2159
|
+
* Wraps one middleware layer around its downstream handler.
|
|
1963
2160
|
*
|
|
1964
2161
|
* @remarks
|
|
1965
2162
|
* The returned handler enforces the one-call `next` invariant while preserving
|
|
@@ -1981,15 +2178,15 @@ export declare function verifyToken(token: string, secret: TokenSecret): Promise
|
|
|
1981
2178
|
export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
|
|
1982
2179
|
|
|
1983
2180
|
/**
|
|
1984
|
-
*
|
|
1985
|
-
* it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
2181
|
+
* Writes a SIGNED cookie — HMAC-signs `value` with {@link signToken} and
|
|
2182
|
+
* appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
1986
2183
|
*
|
|
1987
2184
|
* @remarks
|
|
1988
2185
|
* The cookie value is `await signToken(value, { secret })`
|
|
1989
2186
|
* (`<payload>.<signature>`), so a signed cookie is a stateless token in a
|
|
1990
2187
|
* cookie — the same secret rotation and tamper rejection, no second HMAC
|
|
1991
|
-
* scheme. Appends (never clobbers)
|
|
1992
|
-
*
|
|
2188
|
+
* scheme. Appends (never clobbers) through `Headers.append`, which accumulates
|
|
2189
|
+
* repeated headers. Async — WebCrypto signing is asynchronous.
|
|
1993
2190
|
*
|
|
1994
2191
|
* @param headers - The response `Headers` to write into
|
|
1995
2192
|
* @param name - The cookie name
|