@orkestrel/server 0.0.16 → 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 +477 -393
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +583 -415
- package/dist/src/server/index.d.ts +583 -415
- package/dist/src/server/index.js +468 -384
- package/dist/src/server/index.js.map +1 -1
- package/package.json +15 -15
|
@@ -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,27 +370,29 @@ export declare function createNegotiator(): NegotiatorInterface;
|
|
|
349
370
|
export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
|
|
350
371
|
|
|
351
372
|
/**
|
|
352
|
-
*
|
|
353
|
-
*
|
|
354
|
-
*
|
|
355
|
-
* @remarks
|
|
356
|
-
* Restores the standard base64 alphabet + padding before decoding with
|
|
357
|
-
* `atob`. THROWS `DOMException` on a malformed input — callers on the
|
|
358
|
-
* untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
|
|
373
|
+
* Creates a {@link StreamInterface} — a generic Server-Sent-Events stream whose
|
|
374
|
+
* `response` is a fetch-standard streaming `Response` a route returns.
|
|
359
375
|
*
|
|
360
|
-
* @param
|
|
361
|
-
* @returns
|
|
362
|
-
* @throws {DOMException} When `value` is not valid base64url
|
|
376
|
+
* @param options - {@link StreamOptions}
|
|
377
|
+
* @returns A {@link StreamInterface} whose stream is open
|
|
363
378
|
*
|
|
364
379
|
* @example
|
|
365
380
|
* ```ts
|
|
366
|
-
*
|
|
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
|
|
367
390
|
* ```
|
|
368
391
|
*/
|
|
369
|
-
export declare function
|
|
392
|
+
export declare function createStream(options?: StreamOptions): StreamInterface;
|
|
370
393
|
|
|
371
394
|
/**
|
|
372
|
-
*
|
|
395
|
+
* Decodes a cookie value with `decodeURIComponent`, falling back to the raw
|
|
373
396
|
* text when the value is not valid percent-encoding.
|
|
374
397
|
*
|
|
375
398
|
* @param raw - The raw (trimmed) cookie value
|
|
@@ -384,14 +407,17 @@ export declare function decodeBase64Url(value: string): Uint8Array<ArrayBuffer>;
|
|
|
384
407
|
export declare function decodeCookieValue(raw: string): string;
|
|
385
408
|
|
|
386
409
|
/**
|
|
387
|
-
*
|
|
410
|
+
* Decodes + narrows a signed token's base64url JSON payload, honoring its
|
|
388
411
|
* expiry — the shared decode step {@link verifyToken} applies after a
|
|
389
412
|
* signature match.
|
|
390
413
|
*
|
|
391
414
|
* @remarks
|
|
392
|
-
* Decodes the
|
|
393
|
-
*
|
|
394
|
-
*
|
|
415
|
+
* Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
|
|
416
|
+
* non-canonical base64url segment answers `undefined` rather than throwing),
|
|
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
|
|
419
|
+
* decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
|
|
420
|
+
* throws, and its `catch` answers `undefined` too.
|
|
395
421
|
*
|
|
396
422
|
* @param encoded - The base64url-encoded payload segment (before the last `.`)
|
|
397
423
|
* @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
|
|
@@ -399,15 +425,15 @@ export declare function decodeCookieValue(raw: string): string;
|
|
|
399
425
|
export declare function decodeTokenPayload(encoded: string): string | undefined;
|
|
400
426
|
|
|
401
427
|
/**
|
|
402
|
-
*
|
|
403
|
-
*
|
|
428
|
+
* Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
|
|
429
|
+
* transparently through `DecompressionStream`, capping the DECOMPRESSED output —
|
|
404
430
|
* the zip-bomb defense.
|
|
405
431
|
*
|
|
406
432
|
* @remarks
|
|
407
433
|
* Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
|
|
408
434
|
* `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
|
|
409
435
|
* total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
|
|
410
|
-
* has no `maxOutputLength` knob
|
|
436
|
+
* has no `maxOutputLength` knob. A cap breach surfaces
|
|
411
437
|
* as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
|
|
412
438
|
* compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
|
|
413
439
|
* (never conflated with the cap). A non-positive `cap` means uncapped.
|
|
@@ -421,11 +447,11 @@ export declare function decodeTokenPayload(encoded: string): string | undefined;
|
|
|
421
447
|
*/
|
|
422
448
|
export declare function decompressRequestBody(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
423
449
|
|
|
424
|
-
/**
|
|
450
|
+
/** Names the default maximum request body size (bytes) `readBody` accepts before a 413. */
|
|
425
451
|
export declare const DEFAULT_BODY_LIMIT = 1048576;
|
|
426
452
|
|
|
427
453
|
/**
|
|
428
|
-
*
|
|
454
|
+
* Names the default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
|
|
429
455
|
* the body pipeline's byte-counting `TransformStream` enforces when
|
|
430
456
|
* transparently decompressing a `Content-Encoding` request body.
|
|
431
457
|
*
|
|
@@ -436,17 +462,20 @@ export declare const DEFAULT_BODY_LIMIT = 1048576;
|
|
|
436
462
|
* output would exceed this, BEFORE the full bomb is materialized, so the
|
|
437
463
|
* inflation can never exhaust memory. Defaults to `16 MiB` — a generous
|
|
438
464
|
* ceiling for a legitimate compressed JSON / form body, far below an OOM. A
|
|
439
|
-
* consumer raises it
|
|
465
|
+
* consumer raises it through {@link import('./types.js').BodyOptions}
|
|
440
466
|
* `decompression` for a workload that genuinely ships larger decompressed
|
|
441
467
|
* bodies.
|
|
442
468
|
*/
|
|
443
469
|
export declare const DEFAULT_DECOMPRESSED_LIMIT = 16777216;
|
|
444
470
|
|
|
445
|
-
/**
|
|
471
|
+
/**
|
|
472
|
+
* Names the default graceful-stop deadline (ms) the server gives in-flight
|
|
473
|
+
* requests on `stop()`.
|
|
474
|
+
*/
|
|
446
475
|
export declare const DEFAULT_DRAIN_MS = 10000;
|
|
447
476
|
|
|
448
477
|
/**
|
|
449
|
-
*
|
|
478
|
+
* Lists the default {@link Encoding} content-codings the substrate offers, in
|
|
450
479
|
* PREFERENCE order — `gzip` / `deflate`.
|
|
451
480
|
*
|
|
452
481
|
* @remarks
|
|
@@ -459,8 +488,8 @@ export declare const DEFAULT_DRAIN_MS = 10000;
|
|
|
459
488
|
export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
460
489
|
|
|
461
490
|
/**
|
|
462
|
-
*
|
|
463
|
-
* 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.
|
|
464
493
|
*
|
|
465
494
|
* @remarks
|
|
466
495
|
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
@@ -470,11 +499,16 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
|
470
499
|
* port. It binds then immediately closes a probe server, so the returned
|
|
471
500
|
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
472
501
|
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
473
|
-
* `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.
|
|
474
507
|
*
|
|
475
508
|
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
476
509
|
* fall back to an ephemeral port
|
|
477
510
|
* @returns A free TCP port number
|
|
511
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
478
512
|
*
|
|
479
513
|
* @example
|
|
480
514
|
* ```ts
|
|
@@ -486,56 +520,21 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
|
486
520
|
export declare function discoverPort(preferred?: number): Promise<number>;
|
|
487
521
|
|
|
488
522
|
/**
|
|
489
|
-
*
|
|
490
|
-
* {@link verifyToken} use, and the signature encoding for the HMAC.
|
|
491
|
-
*
|
|
492
|
-
* @param bytes - The bytes to encode
|
|
493
|
-
* @returns The base64url string (no padding)
|
|
494
|
-
*
|
|
495
|
-
* @example
|
|
496
|
-
* ```ts
|
|
497
|
-
* encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
|
|
498
|
-
* ```
|
|
499
|
-
*/
|
|
500
|
-
export declare function encodeBase64Url(bytes: Uint8Array): string;
|
|
501
|
-
|
|
502
|
-
/**
|
|
503
|
-
* A content-coding the substrate compresses / decompresses with — the
|
|
523
|
+
* Represents a content-coding the substrate compresses / decompresses with — the
|
|
504
524
|
* `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
|
|
505
525
|
*
|
|
506
526
|
* @remarks
|
|
507
527
|
* `gzip` / `deflate` map to `CompressionStream` / `DecompressionStream`
|
|
508
528
|
* (web-standard, no external codec); `identity` is the no-op "uncompressed"
|
|
509
529
|
* coding. Brotli (`br`) has no `CompressionStream` implementation yet, so it
|
|
510
|
-
* is deliberately OMITTED here — Brotli parity is the
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
* 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.
|
|
514
533
|
*/
|
|
515
534
|
export declare type Encoding = 'gzip' | 'deflate' | 'identity';
|
|
516
535
|
|
|
517
536
|
/**
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
* @param controller - The stream controller, when the stream has started
|
|
521
|
-
* @param encoder - The encoder used for the stream's byte representation
|
|
522
|
-
* @param closed - Whether the stream has already ended or been cancelled
|
|
523
|
-
* @param text - The text to encode and enqueue
|
|
524
|
-
* @returns Nothing
|
|
525
|
-
*
|
|
526
|
-
* @example
|
|
527
|
-
* ```ts
|
|
528
|
-
* const body = new ReadableStream<Uint8Array>({
|
|
529
|
-
* start(controller) {
|
|
530
|
-
* enqueueStreamText(controller, new TextEncoder(), false, 'hello')
|
|
531
|
-
* },
|
|
532
|
-
* })
|
|
533
|
-
* ```
|
|
534
|
-
*/
|
|
535
|
-
export declare function enqueueStreamText(controller: ReadableStreamDefaultController<Uint8Array> | undefined, encoder: TextEncoder, closed: boolean, text: string): void;
|
|
536
|
-
|
|
537
|
-
/**
|
|
538
|
-
* A map of media type → handler for {@link NegotiatorInterface.format} — the
|
|
537
|
+
* Represents a map of media type → handler for {@link NegotiatorInterface.format} — the
|
|
539
538
|
* content-negotiation dispatch table.
|
|
540
539
|
*
|
|
541
540
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
@@ -553,7 +552,7 @@ export declare function enqueueStreamText(controller: ReadableStreamDefaultContr
|
|
|
553
552
|
export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
|
|
554
553
|
|
|
555
554
|
/**
|
|
556
|
-
*
|
|
555
|
+
* Names the `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
|
|
557
556
|
* an instance thrown by ANOTHER copy of this package (the dual-package
|
|
558
557
|
* hazard — a version-skewed or workspace-linked duplicate install), where
|
|
559
558
|
* `instanceof` alone fails because the two copies' `HTTPError` constructors
|
|
@@ -568,7 +567,7 @@ export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request:
|
|
|
568
567
|
export declare const HTTP_ERROR_BRAND: unique symbol;
|
|
569
568
|
|
|
570
569
|
/**
|
|
571
|
-
*
|
|
570
|
+
* Represents an error a handler (or middleware) throws to produce an HTTP response of a
|
|
572
571
|
* specific status.
|
|
573
572
|
*
|
|
574
573
|
* @remarks
|
|
@@ -579,7 +578,8 @@ export declare const HTTP_ERROR_BRAND: unique symbol;
|
|
|
579
578
|
* deliberate signal), unlike a generic throw whose message is hidden unless
|
|
580
579
|
* `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
|
|
581
580
|
* specific statuses, or throw it directly. Narrow a caught value with
|
|
582
|
-
* {@link isHTTPError}.
|
|
581
|
+
* {@link isHTTPError}. The machine-readable discriminator is `status`; there is
|
|
582
|
+
* no separate `code`.
|
|
583
583
|
*
|
|
584
584
|
* @example
|
|
585
585
|
* ```ts
|
|
@@ -600,36 +600,17 @@ export declare class HTTPError extends Error {
|
|
|
600
600
|
}
|
|
601
601
|
|
|
602
602
|
/**
|
|
603
|
-
*
|
|
604
|
-
* input is not a plain IPv6 address to collapse.
|
|
605
|
-
*
|
|
606
|
-
* @remarks
|
|
607
|
-
* Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
|
|
608
|
-
* is the identity) or any string that does not expand to exactly eight
|
|
609
|
-
* hextets. Expands a single `::` into the missing zero hextets, takes the
|
|
610
|
-
* first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
|
|
611
|
-
* zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
|
|
612
|
-
* first. Total — a malformed address returns `undefined`.
|
|
613
|
-
*
|
|
614
|
-
* @param address - The candidate IPv6 address
|
|
615
|
-
* @returns The `/64` network string, or `undefined` when not a plain IPv6 address
|
|
616
|
-
*
|
|
617
|
-
* @example
|
|
618
|
-
* ```ts
|
|
619
|
-
* ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
|
|
620
|
-
* ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
|
|
621
|
-
* ```
|
|
622
|
-
*/
|
|
623
|
-
export declare function ipv6Network(address: string): string | undefined;
|
|
624
|
-
|
|
625
|
-
/**
|
|
626
|
-
* Whether a `node:net` `server.address()` return is the structured
|
|
603
|
+
* Checks whether a `node:net` `server.address()` return is the structured
|
|
627
604
|
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
628
|
-
* or `null` — the total, never-throwing narrow
|
|
605
|
+
* or `null` — the total, never-throwing narrow `discoverPort`
|
|
629
606
|
* and the `Server`'s own port resolution read the bound port through.
|
|
630
607
|
*
|
|
608
|
+
* @remarks
|
|
609
|
+
* Checks the `address`, `family`, and `port` members `node:net` declares as
|
|
610
|
+
* `string`, `string`, and `number`.
|
|
611
|
+
*
|
|
631
612
|
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
632
|
-
* @returns
|
|
613
|
+
* @returns True if `value` is an `AddressInfo`; false otherwise
|
|
633
614
|
*
|
|
634
615
|
* @example
|
|
635
616
|
* ```ts
|
|
@@ -642,7 +623,7 @@ export declare function ipv6Network(address: string): string | undefined;
|
|
|
642
623
|
export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
643
624
|
|
|
644
625
|
/**
|
|
645
|
-
*
|
|
626
|
+
* Checks whether a `Content-Type` is worth compressing.
|
|
646
627
|
*
|
|
647
628
|
* @remarks
|
|
648
629
|
* Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
|
|
@@ -652,7 +633,7 @@ export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
|
652
633
|
* absent/empty type is not compressible. TOTAL.
|
|
653
634
|
*
|
|
654
635
|
* @param type - The response `Content-Type` header value (with or without parameters)
|
|
655
|
-
* @returns
|
|
636
|
+
* @returns True if the type is text-shaped and worth compressing; false otherwise
|
|
656
637
|
*
|
|
657
638
|
* @example
|
|
658
639
|
* ```ts
|
|
@@ -663,7 +644,7 @@ export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
|
663
644
|
export declare function isCompressibleType(type: string): boolean;
|
|
664
645
|
|
|
665
646
|
/**
|
|
666
|
-
*
|
|
647
|
+
* Checks whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
|
|
667
648
|
* (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
|
|
668
649
|
* attributes with before emitting them.
|
|
669
650
|
*
|
|
@@ -674,7 +655,7 @@ export declare function isCompressibleType(type: string): boolean;
|
|
|
674
655
|
* directive. Total — never throws (a bad value returns `false`).
|
|
675
656
|
*
|
|
676
657
|
* @param value - The candidate attribute value (a `Domain` or `Path`)
|
|
677
|
-
* @returns
|
|
658
|
+
* @returns True if `value` carries no separator / whitespace / control char; false otherwise
|
|
678
659
|
*
|
|
679
660
|
* @example
|
|
680
661
|
* ```ts
|
|
@@ -685,7 +666,7 @@ export declare function isCompressibleType(type: string): boolean;
|
|
|
685
666
|
export declare function isCookieAttribute(value: string): boolean;
|
|
686
667
|
|
|
687
668
|
/**
|
|
688
|
-
*
|
|
669
|
+
* Checks whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
|
|
689
670
|
* cookie-token chars with NO surrounding (or interior) whitespace.
|
|
690
671
|
*
|
|
691
672
|
* @remarks
|
|
@@ -695,7 +676,7 @@ export declare function isCookieAttribute(value: string): boolean;
|
|
|
695
676
|
* `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
|
|
696
677
|
*
|
|
697
678
|
* @param value - The candidate cookie name
|
|
698
|
-
* @returns
|
|
679
|
+
* @returns True if `value` is a valid, whitespace-free cookie token; false otherwise
|
|
699
680
|
*
|
|
700
681
|
* @example
|
|
701
682
|
* ```ts
|
|
@@ -706,12 +687,12 @@ export declare function isCookieAttribute(value: string): boolean;
|
|
|
706
687
|
export declare function isCookieName(value: string): boolean;
|
|
707
688
|
|
|
708
689
|
/**
|
|
709
|
-
*
|
|
690
|
+
* Checks whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
|
|
710
691
|
* or `prototype` — the three keys that, assigned onto a normal object, can
|
|
711
692
|
* reach and mutate `Object.prototype`.
|
|
712
693
|
*
|
|
713
694
|
* @param key - The candidate object key
|
|
714
|
-
* @returns
|
|
695
|
+
* @returns True if `key` is one of the three prototype-pollution keys; false otherwise
|
|
715
696
|
*
|
|
716
697
|
* @example
|
|
717
698
|
* ```ts
|
|
@@ -722,18 +703,18 @@ export declare function isCookieName(value: string): boolean;
|
|
|
722
703
|
export declare function isDangerousKey(key: string): boolean;
|
|
723
704
|
|
|
724
705
|
/**
|
|
725
|
-
*
|
|
706
|
+
* Narrows an unknown caught value to an {@link HTTPError} (including its
|
|
726
707
|
* subclasses, e.g. {@link ContentTooLargeError}).
|
|
727
708
|
*
|
|
728
709
|
* @param value - The value to test (typically a `catch` binding)
|
|
729
|
-
* @returns
|
|
710
|
+
* @returns True if `value` is an {@link HTTPError}; false otherwise
|
|
730
711
|
*
|
|
731
712
|
* @remarks
|
|
732
713
|
* Tries `instanceof` first, then falls back to a total structural check for
|
|
733
714
|
* an instance built by a DIFFERENT copy of this package (the dual-package
|
|
734
715
|
* hazard — version skew, a linked workspace duplicate) whose `HTTPError`
|
|
735
716
|
* constructor is a distinct object from this copy's: the value must carry
|
|
736
|
-
* the cross-copy brand (interned
|
|
717
|
+
* the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
|
|
737
718
|
* same key) AND expose the exact fields the server's error boundary reads off
|
|
738
719
|
* a recognized `HTTPError` — a numeric `status` and a string `message`. A
|
|
739
720
|
* plain object that merely carries a `status` WITHOUT the brand is rejected.
|
|
@@ -752,7 +733,36 @@ export declare function isDangerousKey(key: string): boolean;
|
|
|
752
733
|
export declare function isHTTPError(value: unknown): value is HTTPError;
|
|
753
734
|
|
|
754
735
|
/**
|
|
755
|
-
*
|
|
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
|
|
756
766
|
* header + `context.state`.
|
|
757
767
|
*
|
|
758
768
|
* @remarks
|
|
@@ -763,7 +773,7 @@ export declare function isHTTPError(value: unknown): value is HTTPError;
|
|
|
763
773
|
* TOTAL — never throws.
|
|
764
774
|
*
|
|
765
775
|
* @param value - The candidate incoming request id
|
|
766
|
-
* @returns
|
|
776
|
+
* @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
|
|
767
777
|
*
|
|
768
778
|
* @example
|
|
769
779
|
* ```ts
|
|
@@ -774,29 +784,7 @@ export declare function isHTTPError(value: unknown): value is HTTPError;
|
|
|
774
784
|
export declare function isValidRequestId(value: string): boolean;
|
|
775
785
|
|
|
776
786
|
/**
|
|
777
|
-
*
|
|
778
|
-
* `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
|
|
779
|
-
*
|
|
780
|
-
* @remarks
|
|
781
|
-
* Prefers an exact match, then a primary-tag prefix match (`en` accepts
|
|
782
|
-
* `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
|
|
783
|
-
* is an explicit rejection).
|
|
784
|
-
*
|
|
785
|
-
* @param entries - The parsed {@link AcceptEntry} list
|
|
786
|
-
* @param candidate - The candidate language tag to score (e.g. `'en-US'`)
|
|
787
|
-
* @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
788
|
-
*
|
|
789
|
-
* @example
|
|
790
|
-
* ```ts
|
|
791
|
-
* languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
|
|
792
|
-
* languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
|
|
793
|
-
* languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
|
|
794
|
-
* ```
|
|
795
|
-
*/
|
|
796
|
-
export declare function languageQuality(entries: readonly AcceptEntry[], candidate: string): number;
|
|
797
|
-
|
|
798
|
-
/**
|
|
799
|
-
* 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
|
|
800
788
|
* `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
|
|
801
789
|
*
|
|
802
790
|
* @remarks
|
|
@@ -804,12 +792,12 @@ export declare function languageQuality(entries: readonly AcceptEntry[], candida
|
|
|
804
792
|
* listed tag matches), or the `*` wildcard (matches ANY current
|
|
805
793
|
* representation — only a list of exactly `*` is the wildcard). Comparison is
|
|
806
794
|
* WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
|
|
807
|
-
*
|
|
795
|
+
* through {@link unwrapETag} before comparing the opaque body). TOTAL — a
|
|
808
796
|
* malformed/empty header matches nothing, never throws.
|
|
809
797
|
*
|
|
810
798
|
* @param header - The raw `If-None-Match` header value
|
|
811
799
|
* @param etag - The resource's current `ETag`
|
|
812
|
-
* @returns
|
|
800
|
+
* @returns True if the conditional matches (the caller answers `304`); false otherwise
|
|
813
801
|
*
|
|
814
802
|
* @example
|
|
815
803
|
* ```ts
|
|
@@ -820,7 +808,7 @@ export declare function languageQuality(entries: readonly AcceptEntry[], candida
|
|
|
820
808
|
export declare function matchesETag(header: string, etag: string): boolean;
|
|
821
809
|
|
|
822
810
|
/**
|
|
823
|
-
*
|
|
811
|
+
* Reports the rank + quality of one `candidate` media type against the parsed `Accept`
|
|
824
812
|
* entries — the generic media-type primitive the `Negotiator`'s `negotiate`
|
|
825
813
|
* uses to score each `available` candidate.
|
|
826
814
|
*
|
|
@@ -835,7 +823,7 @@ export declare function matchesETag(header: string, etag: string): boolean;
|
|
|
835
823
|
*
|
|
836
824
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
837
825
|
* @param candidate - The candidate media type to score (e.g. `'text/html'`)
|
|
838
|
-
* @returns The
|
|
826
|
+
* @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
|
|
839
827
|
*
|
|
840
828
|
* @example
|
|
841
829
|
* ```ts
|
|
@@ -845,13 +833,26 @@ export declare function matchesETag(header: string, etag: string): boolean;
|
|
|
845
833
|
* matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
|
|
846
834
|
* ```
|
|
847
835
|
*/
|
|
848
|
-
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 {
|
|
849
850
|
readonly q: number;
|
|
850
851
|
readonly rank: number;
|
|
851
|
-
}
|
|
852
|
+
}
|
|
852
853
|
|
|
853
854
|
/**
|
|
854
|
-
*
|
|
855
|
+
* Merges a `Vary` value into an existing `Vary` header without duplication.
|
|
855
856
|
*
|
|
856
857
|
* @remarks
|
|
857
858
|
* Splits `existing` on `,`, trims each member, and appends `value` only when
|
|
@@ -873,7 +874,7 @@ export declare function matchMediaType(entries: readonly AcceptEntry[], candidat
|
|
|
873
874
|
export declare function mergeVary(existing: string | undefined, value: string): string;
|
|
874
875
|
|
|
875
876
|
/**
|
|
876
|
-
*
|
|
877
|
+
* Represents the composition context — plain data, one per request, shared by every
|
|
877
878
|
* middleware AND (as `state`) by the route handlers behind the dispatcher.
|
|
878
879
|
*
|
|
879
880
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
@@ -907,14 +908,14 @@ export declare interface MiddlewareContext<TState> {
|
|
|
907
908
|
}
|
|
908
909
|
|
|
909
910
|
/**
|
|
910
|
-
*
|
|
911
|
+
* Represents one link in the middleware onion — runs around the rest of the chain.
|
|
911
912
|
*
|
|
912
913
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
913
914
|
*
|
|
914
915
|
* @remarks
|
|
915
916
|
* Transform the request (call `next(newRequest)`), transform the response
|
|
916
917
|
* (`await next()` then modify the result), short-circuit (return a `Response`
|
|
917
|
-
* without calling `next`), or thread data
|
|
918
|
+
* without calling `next`), or thread data through `context.state` — no mutable
|
|
918
919
|
* framework object anywhere, only fetch-standard `Request`/`Response`.
|
|
919
920
|
*
|
|
920
921
|
* @example
|
|
@@ -929,15 +930,15 @@ export declare interface MiddlewareContext<TState> {
|
|
|
929
930
|
export declare type MiddlewareHandler<TState> = (request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response | Promise<Response>;
|
|
930
931
|
|
|
931
932
|
/**
|
|
932
|
-
*
|
|
933
|
+
* Selects the best content-coding for a raw `Accept-Encoding` header from the
|
|
933
934
|
* codings the server offers.
|
|
934
935
|
*
|
|
935
936
|
* @remarks
|
|
936
|
-
* Parses the header ({@link parseAcceptHeader}) and
|
|
937
|
-
*
|
|
938
|
-
* the
|
|
939
|
-
* client
|
|
940
|
-
*
|
|
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.
|
|
941
942
|
*
|
|
942
943
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
943
944
|
* @param header - The raw `Accept-Encoding` header value
|
|
@@ -952,7 +953,7 @@ export declare type MiddlewareHandler<TState> = (request: Request, context: Midd
|
|
|
952
953
|
export declare function negotiateEncoding<T extends string>(header: string, available: readonly T[]): T | undefined;
|
|
953
954
|
|
|
954
955
|
/**
|
|
955
|
-
*
|
|
956
|
+
* Represents the content-negotiation machine over the weighted `Accept` family — a
|
|
956
957
|
* reusable, cross-middleware ENTITY (not a middleware). Implements exactly
|
|
957
958
|
* {@link NegotiatorInterface}.
|
|
958
959
|
*
|
|
@@ -976,6 +977,9 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
976
977
|
encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
|
|
977
978
|
language(header: string, available: readonly string[]): string | undefined;
|
|
978
979
|
/**
|
|
980
|
+
* Dispatches the request to the handler its `Accept` header negotiates,
|
|
981
|
+
* answering 406 when none matches.
|
|
982
|
+
*
|
|
979
983
|
* @remarks
|
|
980
984
|
* Errors thrown by the negotiated handler propagate UNMODIFIED — the
|
|
981
985
|
* server boundary classifies them, never this negotiator.
|
|
@@ -984,7 +988,7 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
984
988
|
}
|
|
985
989
|
|
|
986
990
|
/**
|
|
987
|
-
*
|
|
991
|
+
* Represents content negotiation over the weighted `Accept` family — a reusable,
|
|
988
992
|
* cross-middleware machine (not itself a middleware).
|
|
989
993
|
*
|
|
990
994
|
* @remarks
|
|
@@ -1006,7 +1010,7 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
1006
1010
|
*/
|
|
1007
1011
|
export declare interface NegotiatorInterface {
|
|
1008
1012
|
/**
|
|
1009
|
-
*
|
|
1013
|
+
* Picks the best `available` value for a weighted `Accept`-style `header` —
|
|
1010
1014
|
* the generic media-type primitive (`encoding` / `language` build on it).
|
|
1011
1015
|
*
|
|
1012
1016
|
* @param header - The raw weighted header value (e.g. `text/html, application/json;q=0.9`)
|
|
@@ -1015,16 +1019,25 @@ export declare interface NegotiatorInterface {
|
|
|
1015
1019
|
*/
|
|
1016
1020
|
negotiate(header: string, available: readonly string[]): string | undefined;
|
|
1017
1021
|
/**
|
|
1018
|
-
*
|
|
1019
|
-
* —
|
|
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`).
|
|
1020
1025
|
*
|
|
1021
1026
|
* @param header - The raw `Accept-Encoding` header value (e.g. `gzip;q=1.0, deflate;q=0.8`)
|
|
1022
1027
|
* @param available - The codings the server offers, in preference order
|
|
1023
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.
|
|
1024
1037
|
*/
|
|
1025
1038
|
encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
|
|
1026
1039
|
/**
|
|
1027
|
-
*
|
|
1040
|
+
* Picks the best `available` language for an `Accept-Language` header —
|
|
1028
1041
|
* `negotiate` with a language-prefix match (`en` accepts `en-US`) and a
|
|
1029
1042
|
* bare `*` wildcard.
|
|
1030
1043
|
*
|
|
@@ -1034,9 +1047,9 @@ export declare interface NegotiatorInterface {
|
|
|
1034
1047
|
*/
|
|
1035
1048
|
language(header: string, available: readonly string[]): string | undefined;
|
|
1036
1049
|
/**
|
|
1037
|
-
*
|
|
1038
|
-
* the request `Accept`,
|
|
1039
|
-
* 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.
|
|
1040
1053
|
*
|
|
1041
1054
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1042
1055
|
* @param request - The in-flight `Request`
|
|
@@ -1048,7 +1061,7 @@ export declare interface NegotiatorInterface {
|
|
|
1048
1061
|
}
|
|
1049
1062
|
|
|
1050
1063
|
/**
|
|
1051
|
-
*
|
|
1064
|
+
* Represents the downstream continuation a {@link MiddlewareHandler} invokes to run the
|
|
1052
1065
|
* rest of the onion.
|
|
1053
1066
|
*
|
|
1054
1067
|
* @remarks
|
|
@@ -1064,7 +1077,7 @@ export declare interface NegotiatorInterface {
|
|
|
1064
1077
|
export declare type NextFunction = (request?: Request) => Promise<Response>;
|
|
1065
1078
|
|
|
1066
1079
|
/**
|
|
1067
|
-
*
|
|
1080
|
+
* Normalizes a {@link TokenSecret} to a concrete list of USABLE secrets —
|
|
1068
1081
|
* backs both {@link signToken} and {@link verifyToken}.
|
|
1069
1082
|
*
|
|
1070
1083
|
* @remarks
|
|
@@ -1084,49 +1097,7 @@ export declare type NextFunction = (request?: Request) => Promise<Response>;
|
|
|
1084
1097
|
export declare function normalizeSecret(secret: TokenSecret): readonly string[];
|
|
1085
1098
|
|
|
1086
1099
|
/**
|
|
1087
|
-
*
|
|
1088
|
-
* whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
|
|
1089
|
-
*
|
|
1090
|
-
* @remarks
|
|
1091
|
-
* Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
|
|
1092
|
-
* merged under any `options.headers` (a seam-owned key is never overridden),
|
|
1093
|
-
* at `options.status` (default `200`). The returned {@link StreamInterface}'s
|
|
1094
|
-
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
1095
|
-
* returns whether the controller still has positive desired size. A producer
|
|
1096
|
-
* receiving `false` can await `drain()`; its event-driven promise resolves on
|
|
1097
|
-
* the next consumer pull that restores capacity, or on stream closure.
|
|
1098
|
-
* `comment` writes a `: text` keep-alive line a conforming parser ignores;
|
|
1099
|
-
* `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
|
|
1100
|
-
* by `end()`, or the consumer cancelled the stream), so a late write never
|
|
1101
|
-
* throws.
|
|
1102
|
-
*
|
|
1103
|
-
* This readiness reflects only the process-local `ReadableStream` queue — it
|
|
1104
|
-
* is not proof that a remote peer consumed bytes. When the response pump
|
|
1105
|
-
* honors its socket sink's drain state, socket pressure stops body pulls and
|
|
1106
|
-
* therefore keeps this queue full, allowing a cooperative producer to bound
|
|
1107
|
-
* buffering. Ignoring the return value preserves the prior unconditional-
|
|
1108
|
-
* enqueue behavior. The default stream strategy counts chunks rather than
|
|
1109
|
-
* their byte length, so a byte-bounded producer must also cap each message.
|
|
1110
|
-
* Return `response` before awaiting a `false` write, because the consumer
|
|
1111
|
-
* cannot pull until it receives the response.
|
|
1112
|
-
*
|
|
1113
|
-
* @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
|
|
1114
|
-
* @returns The {@link StreamInterface} handle
|
|
1115
|
-
*
|
|
1116
|
-
* @example
|
|
1117
|
-
* ```ts
|
|
1118
|
-
* const stream = openStream()
|
|
1119
|
-
* void Promise.resolve().then(async () => {
|
|
1120
|
-
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
1121
|
-
* stream.end()
|
|
1122
|
-
* })
|
|
1123
|
-
* // return stream.response from the route handler
|
|
1124
|
-
* ```
|
|
1125
|
-
*/
|
|
1126
|
-
export declare function openStream(options?: StreamOptions): StreamInterface;
|
|
1127
|
-
|
|
1128
|
-
/**
|
|
1129
|
-
* Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
1100
|
+
* Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
1130
1101
|
* into its q-sorted entries.
|
|
1131
1102
|
*
|
|
1132
1103
|
* @remarks
|
|
@@ -1151,7 +1122,7 @@ export declare function openStream(options?: StreamOptions): StreamInterface;
|
|
|
1151
1122
|
export declare function parseAcceptHeader(header: string): readonly AcceptEntry[];
|
|
1152
1123
|
|
|
1153
1124
|
/**
|
|
1154
|
-
*
|
|
1125
|
+
* Parses a raw `Cookie:` request header into a `name → value` lookup.
|
|
1155
1126
|
*
|
|
1156
1127
|
* @remarks
|
|
1157
1128
|
* Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
|
|
@@ -1161,7 +1132,7 @@ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[
|
|
|
1161
1132
|
* {@link isCookieName} rather than silently reconciling into a
|
|
1162
1133
|
* prefix-protected `__Host-` name. A pair without `=`, or with an invalid
|
|
1163
1134
|
* name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
|
|
1164
|
-
* malformed header yields an empty record, never throws
|
|
1135
|
+
* malformed header yields an empty record, never throws.
|
|
1165
1136
|
*
|
|
1166
1137
|
* @param header - The raw `Cookie` header value (possibly `undefined`)
|
|
1167
1138
|
* @returns A record of every parsed cookie, `name → decoded value`
|
|
@@ -1174,7 +1145,30 @@ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[
|
|
|
1174
1145
|
export declare function parseCookies(header: string | undefined): Record<string, string>;
|
|
1175
1146
|
|
|
1176
1147
|
/**
|
|
1177
|
-
*
|
|
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` —
|
|
1178
1172
|
* TOTAL, returning a {@link RangeSpec} or `undefined`.
|
|
1179
1173
|
*
|
|
1180
1174
|
* @remarks
|
|
@@ -1201,10 +1195,17 @@ export declare function parseCookies(header: string | undefined): Record<string,
|
|
|
1201
1195
|
export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
|
|
1202
1196
|
|
|
1203
1197
|
/**
|
|
1204
|
-
*
|
|
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.
|
|
1205
1205
|
*
|
|
1206
1206
|
* @param port - The requested port, with `0` selecting an ephemeral port
|
|
1207
1207
|
* @returns The bound port after the probe server has closed
|
|
1208
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
1208
1209
|
*
|
|
1209
1210
|
* @example
|
|
1210
1211
|
* ```ts
|
|
@@ -1214,7 +1215,7 @@ export declare function parseRange(header: string | undefined, size: number): Ra
|
|
|
1214
1215
|
export declare function probePort(port: number): Promise<number>;
|
|
1215
1216
|
|
|
1216
1217
|
/**
|
|
1217
|
-
*
|
|
1218
|
+
* Represents the parsed outcome of an HTTP `Range` request header.
|
|
1218
1219
|
*
|
|
1219
1220
|
* @remarks
|
|
1220
1221
|
* A `Range: bytes=start-end` against a known resource `size` resolves to ONE
|
|
@@ -1240,7 +1241,7 @@ export declare type RangeSpec = {
|
|
|
1240
1241
|
};
|
|
1241
1242
|
|
|
1242
1243
|
/**
|
|
1243
|
-
*
|
|
1244
|
+
* Collects + decodes a `Request` body — the shared body-collection pipeline
|
|
1244
1245
|
* surfaced to middleware and handlers as the middleware context's cached
|
|
1245
1246
|
* `body()`.
|
|
1246
1247
|
*
|
|
@@ -1251,14 +1252,20 @@ export declare type RangeSpec = {
|
|
|
1251
1252
|
* through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
|
|
1252
1253
|
* `options.decompression`, default {@link
|
|
1253
1254
|
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
|
|
1254
|
-
* content type: `application/json` is parsed
|
|
1255
|
+
* content type: `application/json` is parsed by using `@orkestrel/contract`'s
|
|
1255
1256
|
* `parseJSON` and scrubbed of prototype-pollution keys ({@link
|
|
1256
1257
|
* scrubPrototype}); any other type decodes as UTF-8 text; an empty body
|
|
1257
1258
|
* decodes to `undefined`.
|
|
1258
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
|
+
*
|
|
1259
1265
|
* @param request - The `Request` to read the body from
|
|
1260
1266
|
* @param options - The {@link BodyOptions} `limit` + `decompression` caps
|
|
1261
|
-
* @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
|
|
1262
1269
|
* @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
|
|
1263
1270
|
* @throws {HTTPError} When the compressed body is corrupt (400)
|
|
1264
1271
|
*
|
|
@@ -1270,7 +1277,7 @@ export declare type RangeSpec = {
|
|
|
1270
1277
|
export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;
|
|
1271
1278
|
|
|
1272
1279
|
/**
|
|
1273
|
-
*
|
|
1280
|
+
* Reads + verifies a SIGNED cookie off a request — TOTAL, returning the
|
|
1274
1281
|
* embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
|
|
1275
1282
|
*
|
|
1276
1283
|
* @remarks
|
|
@@ -1292,40 +1299,58 @@ export declare function readBody(request: Request, options?: BodyOptions): Promi
|
|
|
1292
1299
|
export declare function readSignedCookie(request: Request, name: string, secret: TokenSecret): Promise<string | undefined>;
|
|
1293
1300
|
|
|
1294
1301
|
/**
|
|
1295
|
-
*
|
|
1302
|
+
* Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
|
|
1296
1303
|
* to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
|
|
1297
1304
|
* / control-char-bearing incoming id is REJECTED (a fresh id is minted
|
|
1298
|
-
* instead) rather than ever riding into a response header or `context.state
|
|
1299
|
-
*
|
|
1300
|
-
* 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.
|
|
1301
1307
|
*/
|
|
1302
1308
|
export declare const REQUEST_ID_PATTERN: Readonly<RegExp>;
|
|
1303
1309
|
|
|
1304
1310
|
/**
|
|
1305
|
-
*
|
|
1306
|
-
*
|
|
1307
|
-
* whether a request body needs transparent decompression.
|
|
1311
|
+
* Identifies the request a server-level fault came from — its method and its
|
|
1312
|
+
* parsed URL.
|
|
1308
1313
|
*
|
|
1309
1314
|
* @remarks
|
|
1310
|
-
*
|
|
1311
|
-
*
|
|
1312
|
-
* the
|
|
1313
|
-
*
|
|
1314
|
-
|
|
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.
|
|
1315
1328
|
*
|
|
1316
|
-
* @
|
|
1317
|
-
*
|
|
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
|
|
1318
1343
|
*
|
|
1319
1344
|
* @example
|
|
1320
1345
|
* ```ts
|
|
1321
|
-
*
|
|
1322
|
-
*
|
|
1346
|
+
* resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'
|
|
1347
|
+
* resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined
|
|
1323
1348
|
* ```
|
|
1324
1349
|
*/
|
|
1325
|
-
export declare function
|
|
1350
|
+
export declare function resolveCoding<T extends string>(entries: readonly AcceptEntry[], available: readonly T[]): T | undefined;
|
|
1326
1351
|
|
|
1327
1352
|
/**
|
|
1328
|
-
*
|
|
1353
|
+
* Resolves the `Access-Control-Allow-Origin` value for a request.
|
|
1329
1354
|
*
|
|
1330
1355
|
* @remarks
|
|
1331
1356
|
* `'*'` and a single origin string pass straight through. An allow-list
|
|
@@ -1348,7 +1373,7 @@ export declare function requestEncoding(header: string | null): Exclude<Encoding
|
|
|
1348
1373
|
export declare function resolveOrigin(origin: string | readonly string[], requestOrigin: string | undefined): string | undefined;
|
|
1349
1374
|
|
|
1350
1375
|
/**
|
|
1351
|
-
*
|
|
1376
|
+
* Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}
|
|
1352
1377
|
* `secure` setting and whether the request arrived over TLS.
|
|
1353
1378
|
*
|
|
1354
1379
|
* @remarks
|
|
@@ -1358,7 +1383,10 @@ export declare function resolveOrigin(origin: string | readonly string[], reques
|
|
|
1358
1383
|
* gets `Secure` automatically while local-dev HTTP still works.
|
|
1359
1384
|
*
|
|
1360
1385
|
* @param secure - The {@link CookieOptions} `secure` setting
|
|
1361
|
-
* @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.
|
|
1362
1390
|
* @returns The concrete `Secure` flag to emit
|
|
1363
1391
|
*
|
|
1364
1392
|
* @example
|
|
@@ -1371,11 +1399,11 @@ export declare function resolveOrigin(origin: string | readonly string[], reques
|
|
|
1371
1399
|
export declare function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean;
|
|
1372
1400
|
|
|
1373
1401
|
/**
|
|
1374
|
-
*
|
|
1402
|
+
* Resolves one opt-out, value-bearing security header.
|
|
1375
1403
|
*
|
|
1376
1404
|
* @remarks
|
|
1377
1405
|
* The shared "a `string` value, or `false` to omit, or a default when unset"
|
|
1378
|
-
* resolution (
|
|
1406
|
+
* resolution (a value-or-off union, not a behavioral toggle):
|
|
1379
1407
|
* `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
|
|
1380
1408
|
* override, `undefined` (unset) ⇒ `fallback` (the secure default).
|
|
1381
1409
|
*
|
|
@@ -1393,8 +1421,24 @@ export declare function resolveSecure(secure: boolean | undefined, encrypted: bo
|
|
|
1393
1421
|
export declare function resolveSecurityHeader(value: string | false | undefined, fallback: string): string | undefined;
|
|
1394
1422
|
|
|
1395
1423
|
/**
|
|
1396
|
-
*
|
|
1397
|
-
*
|
|
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.
|
|
1398
1442
|
*
|
|
1399
1443
|
* @remarks
|
|
1400
1444
|
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
|
|
@@ -1417,7 +1461,7 @@ export declare function resolveSecurityHeader(value: string | false | undefined,
|
|
|
1417
1461
|
export declare function scrubPrototype(value: unknown): unknown;
|
|
1418
1462
|
|
|
1419
1463
|
/**
|
|
1420
|
-
*
|
|
1464
|
+
* Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
|
|
1421
1465
|
*
|
|
1422
1466
|
* @remarks
|
|
1423
1467
|
* URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
|
|
@@ -1425,10 +1469,9 @@ export declare function scrubPrototype(value: unknown): unknown;
|
|
|
1425
1469
|
* `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
|
|
1426
1470
|
* (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
|
|
1427
1471
|
* with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
|
|
1428
|
-
* injection attempt (a programmer misconfiguration
|
|
1429
|
-
* 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
|
|
1430
1473
|
* the `secure` option (the spec requires it); an un-resolved `undefined`
|
|
1431
|
-
* `secure` here falls to OFF — request-aware callers resolve it first
|
|
1474
|
+
* `secure` here falls to OFF — request-aware callers resolve it first through
|
|
1432
1475
|
* {@link resolveSecure}.
|
|
1433
1476
|
*
|
|
1434
1477
|
* @param name - The cookie name
|
|
@@ -1445,7 +1488,7 @@ export declare function scrubPrototype(value: unknown): unknown;
|
|
|
1445
1488
|
export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
|
|
1446
1489
|
|
|
1447
1490
|
/**
|
|
1448
|
-
*
|
|
1491
|
+
* Serializes one {@link SSEMessage} to the SSE wire.
|
|
1449
1492
|
*
|
|
1450
1493
|
* @remarks
|
|
1451
1494
|
* Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
|
|
@@ -1466,14 +1509,14 @@ export declare function serializeCookie(name: string, value: string, options?: C
|
|
|
1466
1509
|
export declare function serializeEvent(message: SSEMessage): string;
|
|
1467
1510
|
|
|
1468
1511
|
/**
|
|
1469
|
-
*
|
|
1512
|
+
* Represents the HTTP server facade — an observable `node:http` lifecycle composing this
|
|
1470
1513
|
* module's own middleware onion around a consumed `@orkestrel/router`
|
|
1471
1514
|
* dispatcher.
|
|
1472
1515
|
*
|
|
1473
1516
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1474
1517
|
*
|
|
1475
1518
|
* @remarks
|
|
1476
|
-
* - **Lifecycle
|
|
1519
|
+
* - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
|
|
1477
1520
|
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
1478
1521
|
* ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
|
|
1479
1522
|
* bound address), exposes that {@link AddressInfo} through `address`, observes
|
|
@@ -1487,15 +1530,15 @@ export declare function serializeEvent(message: SSEMessage): string;
|
|
|
1487
1530
|
* busy-loop), then closes → `stopped`, forcing whatever the deadline caught
|
|
1488
1531
|
* still open. `destroy()` is the idempotent final teardown.
|
|
1489
1532
|
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
1490
|
-
* `close`); a `Request` is built
|
|
1491
|
-
* `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
|
|
1492
1535
|
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
1493
1536
|
* `buildRequest`'s own abort, armed by BOTH request-side and response-side
|
|
1494
|
-
* teardown, composes with the server's stop signal
|
|
1495
|
-
* 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
|
|
1496
1539
|
* {@link ServerOptions.state} from the connection facts; the composed
|
|
1497
1540
|
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
1498
|
-
* written back
|
|
1541
|
+
* written back through `sendResponse`.
|
|
1499
1542
|
* - **The built-in boundary** wraps the WHOLE per-request chain, including
|
|
1500
1543
|
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1501
1544
|
* throw (e.g. a malformed `Host` header) to a silent `400` with no
|
|
@@ -1513,14 +1556,14 @@ export declare function serializeEvent(message: SSEMessage): string;
|
|
|
1513
1556
|
* A CLAIMED socket joins `#upgraded` until it closes: the claimant still
|
|
1514
1557
|
* owns it, and the tracking exists because node detaches an upgraded socket
|
|
1515
1558
|
* from the set its own close calls walk, so nothing else can end it.
|
|
1516
|
-
* - **Observable
|
|
1559
|
+
* - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
1517
1560
|
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
1518
1561
|
* routes it to the `error` OPTION (not the domain `error` event).
|
|
1519
1562
|
*/
|
|
1520
1563
|
export declare class Server<TState> implements ServerInterface<TState> {
|
|
1521
1564
|
#private;
|
|
1522
|
-
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
1523
1565
|
constructor(options: ServerOptions<TState>);
|
|
1566
|
+
get id(): string;
|
|
1524
1567
|
get status(): ServerStatus;
|
|
1525
1568
|
get port(): number | undefined;
|
|
1526
1569
|
get address(): AddressInfo | undefined;
|
|
@@ -1535,7 +1578,54 @@ export declare class Server<TState> implements ServerInterface<TState> {
|
|
|
1535
1578
|
}
|
|
1536
1579
|
|
|
1537
1580
|
/**
|
|
1538
|
-
*
|
|
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.
|
|
1539
1629
|
*
|
|
1540
1630
|
* @remarks
|
|
1541
1631
|
* - `start` — `listen()` resolved; carries the actually-bound port (an
|
|
@@ -1569,24 +1659,14 @@ export declare type ServerEventMap = {
|
|
|
1569
1659
|
readonly start: readonly [port: number];
|
|
1570
1660
|
readonly request: readonly [method: string, pathname: string];
|
|
1571
1661
|
readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
|
|
1572
|
-
readonly error: readonly [error: unknown, request?:
|
|
1573
|
-
method: string;
|
|
1574
|
-
url: URL;
|
|
1575
|
-
}];
|
|
1662
|
+
readonly error: readonly [error: unknown, request?: RequestLine];
|
|
1576
1663
|
readonly stop: readonly [];
|
|
1577
1664
|
readonly drain: readonly [pending: number, upgraded: number];
|
|
1578
|
-
readonly response: readonly [
|
|
1579
|
-
event: {
|
|
1580
|
-
method: string;
|
|
1581
|
-
pathname: string;
|
|
1582
|
-
status: number;
|
|
1583
|
-
ms: number;
|
|
1584
|
-
}
|
|
1585
|
-
];
|
|
1665
|
+
readonly response: readonly [event: ResponseRecord];
|
|
1586
1666
|
};
|
|
1587
1667
|
|
|
1588
1668
|
/**
|
|
1589
|
-
*
|
|
1669
|
+
* Represents the HTTP server facade — an observable `node:http` lifecycle that composes
|
|
1590
1670
|
* a middleware onion (this module's own middleware seam) around a consumed
|
|
1591
1671
|
* `@orkestrel/router` {@link DispatcherInterface}.
|
|
1592
1672
|
*
|
|
@@ -1603,34 +1683,65 @@ export declare type ServerEventMap = {
|
|
|
1603
1683
|
* connections, fires the stop signal so in-flight handlers can observe it,
|
|
1604
1684
|
* drains in-flight requests and claimed upgraded sockets up to the configured
|
|
1605
1685
|
* deadline, then closes — forcing whatever is left. `destroy()` is the final
|
|
1606
|
-
* idempotent teardown. Per request: a `Request` is built
|
|
1686
|
+
* idempotent teardown. Per request: a `Request` is built through the router's
|
|
1607
1687
|
* `buildRequest` (its signal linked to the server's stop signal), the composed
|
|
1608
1688
|
* middleware onion runs terminating in `dispatcher.handle`, and the result is
|
|
1609
|
-
* written back
|
|
1689
|
+
* written back through `sendResponse` — every escaping throw is caught by the
|
|
1610
1690
|
* built-in boundary (`HTTPError` → its status; anything else → a
|
|
1611
1691
|
* hidden-unless-`expose` `500`) so a handler error can never crash the process.
|
|
1612
1692
|
*/
|
|
1613
1693
|
export declare interface ServerInterface<TState> {
|
|
1694
|
+
/** Holds the instance's correlation id, minted once per `Server` and stable for its lifetime. */
|
|
1614
1695
|
readonly id: string;
|
|
1696
|
+
/** Reports the current lifecycle phase — see {@link ServerStatus}. */
|
|
1615
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
|
+
*/
|
|
1616
1702
|
readonly port: number | undefined;
|
|
1617
|
-
/**
|
|
1703
|
+
/** Holds the bound listener address, or `undefined` while no listener is active. */
|
|
1618
1704
|
readonly address: AddressInfo | undefined;
|
|
1705
|
+
/** Holds the `@orkestrel/router` dispatcher the composed middleware onion terminates into. */
|
|
1619
1706
|
readonly dispatcher: DispatcherInterface<TState>;
|
|
1707
|
+
/** Holds the lifecycle emitter over {@link ServerEventMap}. */
|
|
1620
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
|
+
*/
|
|
1621
1718
|
use(middleware: MiddlewareHandler<TState>): void;
|
|
1622
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
|
+
*/
|
|
1623
1725
|
upgrade(handler: UpgradeHandler): void;
|
|
1624
1726
|
/**
|
|
1625
|
-
*
|
|
1727
|
+
* Binds the configured listener and resolves its actually-bound port.
|
|
1626
1728
|
*
|
|
1627
1729
|
* @param signal - Optional caller cancellation observed only while startup
|
|
1628
1730
|
* is pending; aborting after this method resolves does not stop the server.
|
|
1629
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`.
|
|
1630
1741
|
*/
|
|
1631
1742
|
start(signal?: AbortSignal): Promise<number>;
|
|
1632
1743
|
/**
|
|
1633
|
-
*
|
|
1744
|
+
* Stops gracefully: refuses new connections, fires the stop signal, drains, closes.
|
|
1634
1745
|
*
|
|
1635
1746
|
* @remarks
|
|
1636
1747
|
* Drainable work is every in-flight request PLUS every upgraded socket a
|
|
@@ -1645,7 +1756,7 @@ export declare interface ServerInterface<TState> {
|
|
|
1645
1756
|
*/
|
|
1646
1757
|
stop(): Promise<void>;
|
|
1647
1758
|
/**
|
|
1648
|
-
*
|
|
1759
|
+
* Tears down for good: force-closes the listener and every socket, then the emitter.
|
|
1649
1760
|
*
|
|
1650
1761
|
* @returns Resolves once nothing is left open; idempotent from any state
|
|
1651
1762
|
*/
|
|
@@ -1663,7 +1774,7 @@ export declare interface ServerInterface<TState> {
|
|
|
1663
1774
|
* is never implicitly trusted here; a deployment behind a trusted proxy
|
|
1664
1775
|
* derives its own client key in this function or in middleware.
|
|
1665
1776
|
* @param middleware - Initial middleware, run in array order (outer-first);
|
|
1666
|
-
* more may be added later
|
|
1777
|
+
* more may be added later by using `use`.
|
|
1667
1778
|
* @param host - The network interface `start()` binds to (`node:http`
|
|
1668
1779
|
* `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
|
|
1669
1780
|
* @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
|
|
@@ -1703,9 +1814,9 @@ export declare interface ServerInterface<TState> {
|
|
|
1703
1814
|
* to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
|
|
1704
1815
|
* `maxRequestsPerSocket` (`0` disables the limit). Every present value must
|
|
1705
1816
|
* be a non-negative integer. Omitted leaves preserve node's defaults.
|
|
1706
|
-
* @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
|
|
1707
|
-
*
|
|
1708
|
-
* @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
|
|
1709
1820
|
* listener throw routes here, never to the domain `error` event.
|
|
1710
1821
|
*/
|
|
1711
1822
|
export declare interface ServerOptions<TState> {
|
|
@@ -1717,10 +1828,7 @@ export declare interface ServerOptions<TState> {
|
|
|
1717
1828
|
readonly drain?: number;
|
|
1718
1829
|
readonly limit?: number;
|
|
1719
1830
|
readonly expose?: boolean;
|
|
1720
|
-
readonly report?: (error: unknown, request?:
|
|
1721
|
-
method: string;
|
|
1722
|
-
url: URL;
|
|
1723
|
-
}) => void;
|
|
1831
|
+
readonly report?: (error: unknown, request?: RequestLine) => void;
|
|
1724
1832
|
readonly timeouts?: {
|
|
1725
1833
|
readonly start?: number;
|
|
1726
1834
|
readonly request?: number;
|
|
@@ -1737,7 +1845,7 @@ export declare interface ServerOptions<TState> {
|
|
|
1737
1845
|
}
|
|
1738
1846
|
|
|
1739
1847
|
/**
|
|
1740
|
-
*
|
|
1848
|
+
* Represents the `Server`'s lifecycle state.
|
|
1741
1849
|
*
|
|
1742
1850
|
* @remarks
|
|
1743
1851
|
* `idle` (never started, or a fresh instance) → `starting` (binding the
|
|
@@ -1749,17 +1857,17 @@ export declare interface ServerOptions<TState> {
|
|
|
1749
1857
|
export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
|
|
1750
1858
|
|
|
1751
1859
|
/**
|
|
1752
|
-
*
|
|
1860
|
+
* Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
|
|
1753
1861
|
*
|
|
1754
1862
|
* @remarks
|
|
1755
1863
|
* The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
|
|
1756
1864
|
* absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
|
|
1757
1865
|
* the expiry is HMAC-COVERED — a client cannot extend it without invalidating
|
|
1758
|
-
* the signature), signed
|
|
1866
|
+
* the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the FIRST
|
|
1759
1867
|
* {@link TokenSecret} (the current secret, or the head of a rotation list).
|
|
1760
1868
|
* Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
|
|
1761
1869
|
* misconfigured secret with no usable entry THROWS an {@link HTTPError}
|
|
1762
|
-
* (`500`) — fail-closed, a programmer error
|
|
1870
|
+
* (`500`) — fail-closed, a programmer error. Verify with
|
|
1763
1871
|
* {@link verifyToken}. Omitting `ttl` mints a token that never expires.
|
|
1764
1872
|
*
|
|
1765
1873
|
* @param value - The opaque value to embed (a session id, a deployment marker)
|
|
@@ -1776,20 +1884,21 @@ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping
|
|
|
1776
1884
|
export declare function signToken(value: string, options: TokenOptions): Promise<string>;
|
|
1777
1885
|
|
|
1778
1886
|
/**
|
|
1779
|
-
*
|
|
1887
|
+
* Holds the SSE response headers a `Stream` always sets on its response.
|
|
1780
1888
|
*
|
|
1781
1889
|
* @remarks
|
|
1782
1890
|
* `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
|
|
1783
1891
|
* keeps a proxy from caching the stream; `keep-alive` holds the connection
|
|
1784
1892
|
* open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
|
|
1785
1893
|
* events flush promptly rather than batching. Frozen so a consumer can read
|
|
1786
|
-
* but never mutate the shared default; `
|
|
1787
|
-
* {@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.
|
|
1788
1897
|
*/
|
|
1789
1898
|
export declare const SSE_HEADERS: Readonly<Record<string, string>>;
|
|
1790
1899
|
|
|
1791
1900
|
/**
|
|
1792
|
-
*
|
|
1901
|
+
* Represents one Server-Sent Event to serialize to the wire.
|
|
1793
1902
|
*
|
|
1794
1903
|
* @remarks
|
|
1795
1904
|
* - `data` — the event payload (required). Serialized as one or more `data:`
|
|
@@ -1803,16 +1912,72 @@ export declare const SSE_HEADERS: Readonly<Record<string, string>>;
|
|
|
1803
1912
|
*/
|
|
1804
1913
|
export declare interface SSEMessage {
|
|
1805
1914
|
readonly data: string;
|
|
1806
|
-
/**
|
|
1915
|
+
/** Requires a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
|
|
1807
1916
|
readonly event?: string;
|
|
1808
|
-
/**
|
|
1917
|
+
/** Requires a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
|
|
1809
1918
|
readonly id?: string;
|
|
1810
1919
|
readonly retry?: number;
|
|
1811
1920
|
}
|
|
1812
1921
|
|
|
1813
1922
|
/**
|
|
1814
|
-
*
|
|
1815
|
-
* `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
|
|
1816
1981
|
* `ReadableStream`.
|
|
1817
1982
|
*
|
|
1818
1983
|
* @remarks
|
|
@@ -1839,28 +2004,28 @@ export declare interface SSEMessage {
|
|
|
1839
2004
|
* until it receives the response.
|
|
1840
2005
|
*/
|
|
1841
2006
|
export declare interface StreamInterface {
|
|
1842
|
-
/**
|
|
2007
|
+
/** Holds the streaming `Response` to return from the route handler. */
|
|
1843
2008
|
readonly response: Response;
|
|
1844
|
-
/**
|
|
2009
|
+
/** Reports whether the underlying stream is done (ended, or the consumer disconnected). */
|
|
1845
2010
|
readonly closed: boolean;
|
|
1846
2011
|
/**
|
|
1847
|
-
*
|
|
2012
|
+
* Serializes + enqueues one {@link SSEMessage} to the wire.
|
|
1848
2013
|
*
|
|
1849
2014
|
* @param message - The event to send (its `data` split on `\n` into `data:` lines)
|
|
1850
|
-
* @returns
|
|
1851
|
-
* accepting the event;
|
|
1852
|
-
* 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
|
|
1853
2018
|
* `true`; await {@link drain} before producing another event.
|
|
1854
2019
|
*/
|
|
1855
2020
|
write(message: SSEMessage): boolean;
|
|
1856
2021
|
/**
|
|
1857
|
-
*
|
|
2022
|
+
* Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores.
|
|
1858
2023
|
*
|
|
1859
2024
|
* @param text - The comment text (sent after the `: ` prefix)
|
|
1860
2025
|
*/
|
|
1861
2026
|
comment(text: string): void;
|
|
1862
2027
|
/**
|
|
1863
|
-
*
|
|
2028
|
+
* Parks until the process-local stream queue has capacity again.
|
|
1864
2029
|
*
|
|
1865
2030
|
* @returns A promise that resolves when a consumer pull restores positive
|
|
1866
2031
|
* desired size, or immediately when capacity is already available or the
|
|
@@ -1868,18 +2033,19 @@ export declare interface StreamInterface {
|
|
|
1868
2033
|
* not prove that a remote peer consumed the queued bytes.
|
|
1869
2034
|
*/
|
|
1870
2035
|
drain(): Promise<void>;
|
|
1871
|
-
/**
|
|
2036
|
+
/** Ends the stream, completing the response (a no-op once already `closed`). */
|
|
1872
2037
|
end(): void;
|
|
1873
2038
|
}
|
|
1874
2039
|
|
|
1875
2040
|
/**
|
|
1876
|
-
* Options for
|
|
2041
|
+
* Options for a {@link StreamInterface} — how `createStream` opens the
|
|
2042
|
+
* streaming response.
|
|
1877
2043
|
*
|
|
1878
2044
|
* @param status - The HTTP status the streaming response is opened with;
|
|
1879
2045
|
* defaults to `200`.
|
|
1880
|
-
* @param headers - Extra response headers merged
|
|
1881
|
-
* seam always sets ({@link SSE_HEADERS})
|
|
1882
|
-
*
|
|
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.
|
|
1883
2049
|
*/
|
|
1884
2050
|
export declare interface StreamOptions {
|
|
1885
2051
|
readonly status?: number;
|
|
@@ -1903,7 +2069,7 @@ export declare interface TokenOptions {
|
|
|
1903
2069
|
}
|
|
1904
2070
|
|
|
1905
2071
|
/**
|
|
1906
|
-
*
|
|
2072
|
+
* Represents a secret (or rotation list) for signing + verifying a stateless, HMAC-signed
|
|
1907
2073
|
* token.
|
|
1908
2074
|
*
|
|
1909
2075
|
* @remarks
|
|
@@ -1916,7 +2082,7 @@ export declare interface TokenOptions {
|
|
|
1916
2082
|
export declare type TokenSecret = string | readonly string[];
|
|
1917
2083
|
|
|
1918
2084
|
/**
|
|
1919
|
-
*
|
|
2085
|
+
* Strips the WEAK indicator (`W/`) from an entity-tag, returning its opaque
|
|
1920
2086
|
* comparison body — the reduction {@link matchesETag} applies to both sides
|
|
1921
2087
|
* before the RFC 7232 §2.3.2 weak comparison.
|
|
1922
2088
|
*
|
|
@@ -1931,17 +2097,17 @@ export declare type TokenSecret = string | readonly string[];
|
|
|
1931
2097
|
export declare function unwrapETag(tag: string): string;
|
|
1932
2098
|
|
|
1933
2099
|
/**
|
|
1934
|
-
*
|
|
2100
|
+
* Represents a raw `node:http` protocol-upgrade claimant — registered through
|
|
1935
2101
|
* {@link ServerInterface.upgrade}.
|
|
1936
2102
|
*
|
|
1937
2103
|
* @remarks
|
|
1938
|
-
* Fan-out semantics
|
|
2104
|
+
* Fan-out semantics: handlers run in registration
|
|
1939
2105
|
* order, the FIRST to return `true` CLAIMS (owns) the socket and stops the
|
|
1940
2106
|
* fan-out; a handler that THROWS is treated as declined (the throw surfaces
|
|
1941
2107
|
* on the `error` event) and the fan-out continues; if NONE claim it, the
|
|
1942
2108
|
* socket is destroyed so an unhandled upgrade never leaks a dangling
|
|
1943
2109
|
* connection. `request` / `socket` / `head` are node's own raw values, handed
|
|
1944
|
-
* over verbatim — no assertion at this boundary
|
|
2110
|
+
* over verbatim — no assertion at this boundary.
|
|
1945
2111
|
*
|
|
1946
2112
|
* A CLAIMED socket is TRACKED until it closes. The handler still owns it —
|
|
1947
2113
|
* the server only watches — but `stop()` now drains that socket like an
|
|
@@ -1956,23 +2122,25 @@ export declare function unwrapETag(tag: string): string;
|
|
|
1956
2122
|
* @param request - The raw `node:http` upgrade request
|
|
1957
2123
|
* @param socket - The raw, now-detached `Duplex` connection
|
|
1958
2124
|
* @param head - The first packet of the upgraded stream, if any
|
|
1959
|
-
* @returns
|
|
1960
|
-
*
|
|
2125
|
+
* @returns True if the handler CLAIMS the socket (this handler now owns
|
|
2126
|
+
* it); false otherwise, declining so a later handler can try
|
|
1961
2127
|
*/
|
|
1962
2128
|
export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
1963
2129
|
|
|
1964
2130
|
/**
|
|
1965
|
-
*
|
|
2131
|
+
* Verifies a stateless token and returns its embedded value — TOTAL, never throws.
|
|
1966
2132
|
*
|
|
1967
2133
|
* @remarks
|
|
1968
2134
|
* The inverse of {@link signToken}: splits the token on its LAST `.` (so a
|
|
1969
|
-
* value containing dots survives),
|
|
1970
|
-
*
|
|
2135
|
+
* value containing dots survives), decodes the signature with
|
|
2136
|
+
* `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
|
|
2137
|
+
* base64url is refused there, before any key import — and checks the payload's
|
|
2138
|
+
* HMAC-SHA256 signature against EACH {@link TokenSecret} candidate through
|
|
1971
2139
|
* `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
|
|
1972
|
-
* retired
|
|
2140
|
+
* retired), accepting the token on the first match (the
|
|
1973
2141
|
* rotation path). It then decodes + narrows the payload (`isRecord` +
|
|
1974
|
-
* `typeof`, never `as`
|
|
1975
|
-
*
|
|
2142
|
+
* `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
|
|
2143
|
+
* token. ANY failure — a malformed token, a bad signature,
|
|
1976
2144
|
* a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
|
|
1977
2145
|
* yields `undefined` rather than throwing.
|
|
1978
2146
|
*
|
|
@@ -1988,7 +2156,7 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
|
|
|
1988
2156
|
export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
|
|
1989
2157
|
|
|
1990
2158
|
/**
|
|
1991
|
-
*
|
|
2159
|
+
* Wraps one middleware layer around its downstream handler.
|
|
1992
2160
|
*
|
|
1993
2161
|
* @remarks
|
|
1994
2162
|
* The returned handler enforces the one-call `next` invariant while preserving
|
|
@@ -2010,15 +2178,15 @@ export declare function verifyToken(token: string, secret: TokenSecret): Promise
|
|
|
2010
2178
|
export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
|
|
2011
2179
|
|
|
2012
2180
|
/**
|
|
2013
|
-
*
|
|
2014
|
-
* 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}).
|
|
2015
2183
|
*
|
|
2016
2184
|
* @remarks
|
|
2017
2185
|
* The cookie value is `await signToken(value, { secret })`
|
|
2018
2186
|
* (`<payload>.<signature>`), so a signed cookie is a stateless token in a
|
|
2019
2187
|
* cookie — the same secret rotation and tamper rejection, no second HMAC
|
|
2020
|
-
* scheme. Appends (never clobbers)
|
|
2021
|
-
*
|
|
2188
|
+
* scheme. Appends (never clobbers) through `Headers.append`, which accumulates
|
|
2189
|
+
* repeated headers. Async — WebCrypto signing is asynchronous.
|
|
2022
2190
|
*
|
|
2023
2191
|
* @param headers - The response `Headers` to write into
|
|
2024
2192
|
* @param name - The cookie name
|