castrum 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +153 -630
  2. package/castrum.linux-x64-gnu.node +0 -0
  3. package/dist/index.d.ts +1374 -1772
  4. package/dist/index.js +5570 -4169
  5. package/docs/API.md +337 -0
  6. package/docs/ARCHITECTURE.md +106 -14
  7. package/docs/BENCHMARKS.md +83 -47
  8. package/docs/CASE_STUDY.md +240 -0
  9. package/docs/ENVIRONMENT.md +8 -6
  10. package/docs/FFI_BUN_GUIDE.md +327 -0
  11. package/docs/GETTING_STARTED.md +15 -32
  12. package/docs/INGRESS-ROUTER.md +81 -0
  13. package/docs/INGRESS.md +5 -4
  14. package/docs/NATIVE-ROUTE.md +53 -0
  15. package/docs/REPO_MAP.md +46 -26
  16. package/docs/adr/0003-bun-builtins-delegation.md +6 -5
  17. package/docs/bun-builtins-decision-matrix.md +25 -18
  18. package/index.ts +9 -16
  19. package/package.json +36 -24
  20. package/src/ingress/body.ts +167 -27
  21. package/src/ingress/handlers.ts +91 -15
  22. package/src/ingress/health.ts +1 -0
  23. package/src/ingress/index.ts +39 -27
  24. package/src/ingress/packing/gather-raw-headers.ts +85 -21
  25. package/src/ingress/packing/header-packing.ts +5 -5
  26. package/src/ingress/packing/input-packer.ts +17 -3
  27. package/src/ingress/packing/select-headers.ts +12 -6
  28. package/src/ingress/router.ts +237 -0
  29. package/src/ingress/routes/common.ts +42 -1
  30. package/src/ingress/routes/fallback.ts +2 -2
  31. package/src/ingress/routes/head.ts +3 -13
  32. package/src/ingress/routes/index.ts +5 -4
  33. package/src/ingress/routes/json-write.ts +7 -31
  34. package/src/ingress/routes/options.ts +2 -12
  35. package/src/ingress/routes/read.ts +3 -13
  36. package/src/ingress/routes/responder.ts +159 -0
  37. package/src/ingress/server-node.ts +6 -6
  38. package/src/ingress/server.ts +45 -13
  39. package/src/ingress/types.ts +35 -1
  40. package/src/integration/pipeline.ts +3 -0
  41. package/src/integration/streaming.ts +2 -3
  42. package/src/integration/websocket.ts +4 -3
  43. package/src/loader/batch.ts +4 -0
  44. package/src/loader/cost.ts +1 -0
  45. package/src/loader/index.ts +43 -228
  46. package/src/loader/state.ts +84 -0
  47. package/src/loader/types.ts +145 -0
  48. package/src/native/ffi/constants.ts +58 -0
  49. package/src/native/ffi/selftest.ts +729 -0
  50. package/src/native/ffi/types.ts +474 -0
  51. package/src/native/ffi.ts +1063 -829
  52. package/src/native/loader.ts +52 -6
  53. package/src/native/types/instances.ts +274 -0
  54. package/src/native/types.ts +41 -238
  55. package/src/runtime/builtins.ts +131 -0
  56. package/src/runtime/codec.ts +147 -0
  57. package/src/runtime/detect.ts +36 -0
  58. package/src/runtime/index.ts +28 -0
  59. package/src/runtime/native.ts +35 -0
  60. package/src/runtime/server.ts +31 -0
  61. package/src/runtime/transport.ts +64 -0
  62. package/src/runtime/types.ts +173 -0
  63. package/src/runtime/uuid.ts +45 -0
  64. package/src/runtime/websocket.ts +30 -0
  65. package/src/rust-ffi/addon.ts +1 -1
  66. package/src/rust-ffi/batch/build.ts +155 -0
  67. package/src/rust-ffi/batch/index.ts +8 -0
  68. package/src/rust-ffi/batch/types.ts +92 -0
  69. package/src/rust-ffi/client.ts +5 -6
  70. package/src/rust-ffi/context.ts +39 -10
  71. package/src/rust-ffi/index.ts +28 -17
  72. package/src/rust-ffi/into.ts +21 -0
  73. package/src/rust-ffi/options.ts +1 -1
  74. package/src/rust-ffi/packed.ts +2 -2
  75. package/src/rust-ffi/proven.ts +16 -30
  76. package/src/rust-ffi/scalar/crypto.ts +188 -107
  77. package/src/rust-ffi/scalar/factories.ts +253 -27
  78. package/src/rust-ffi/scalar/hashing.ts +43 -41
  79. package/src/rust-ffi/scalar/http.ts +208 -77
  80. package/src/rust-ffi/scalar/index.ts +3 -3
  81. package/src/rust-ffi/scalar/interface.ts +88 -213
  82. package/src/rust-ffi/scalar/json-packed.ts +175 -0
  83. package/src/rust-ffi/scalar/json.ts +28 -12
  84. package/src/rust-ffi/scalar/payload.ts +159 -42
  85. package/src/rust-ffi/text.ts +31 -5
  86. package/src/selection.ts +27 -31
  87. package/src/shared/adaptive.ts +1 -2
  88. package/src/shared/buffer-pool.ts +72 -17
  89. package/src/shared/bytes.ts +75 -6
  90. package/src/shared/codec.ts +78 -0
  91. package/src/shared/env.ts +4 -4
  92. package/src/shared/log.ts +1 -0
  93. package/src/shared/packed/index.ts +10 -0
  94. package/src/shared/packed/parsers.ts +31 -0
  95. package/src/shared/packed/schema.ts +23 -0
  96. package/src/shared/{packed.ts → packed/wire.ts} +31 -39
  97. package/src/shared/proven.ts +189 -496
  98. package/src/shared/runtime.ts +20 -25
  99. package/src/shared/uuid.ts +12 -28
  100. package/src/data/json-rows.ts +0 -33
  101. package/src/rust-ffi/batch.ts +0 -431
  102. package/src/shared/bench-classify.ts +0 -209
package/dist/index.d.ts CHANGED
@@ -15,13 +15,14 @@ export interface SchemaError {
15
15
  export interface SchemaValidatorInstance {
16
16
  /** Validate a single JSON document. */
17
17
  validate(input: Uint8Array): boolean;
18
+ /** Opaque handle (bun:ffi fast path) — `castrum_schema_validator_validate`. */
19
+ innerPtr?(): bigint;
18
20
  /** Validate a single JSON document, returning detailed errors (empty = valid). */
19
21
  validateDetailed(input: Uint8Array): SchemaError[];
20
22
  /** Validate a single JSON document, returning only the first error (null = valid). */
21
23
  validateFirstError(input: Uint8Array): SchemaError | null;
22
24
  validateBatchPackedCount(packed: Uint8Array): number;
23
25
  validateBatchPackedBitset(packed: Uint8Array): Uint8Array;
24
- validateBatchStreaming(batchBytes: Uint8Array): number;
25
26
  /**
26
27
  * One-pass validate + extract: validate `input` against the schema and
27
28
  * capture scalar values / array lengths at `paths` during the same native
@@ -74,12 +75,13 @@ export interface MediaTypeResult {
74
75
  /** The native `MediaTypeParser` class instance. */
75
76
  export interface MediaTypeParserInstance {
76
77
  parse(input: Uint8Array): MediaTypeResult;
77
- /** Wildcard match: any/any, type/any, or exact type/subtype. */
78
- matches(actual: Uint8Array, expected: Uint8Array): boolean;
79
78
  }
80
79
  /** The native `ConditionalRequest` class instance (per-resource 304 checks). */
81
80
  export interface ConditionalRequestInstance {
82
81
  isNotModified(ifNoneMatch: Uint8Array | null, ifModifiedSince: Uint8Array | null): boolean;
82
+ /** Opaque handle to the precompiled state (present when the bun:ffi fast path
83
+ * is active) — `castrum_conditional_is_not_modified` in rust/ffi.rs. */
84
+ innerPtr?(): bigint;
83
85
  }
84
86
  /** One parsed Accept-Encoding preference. */
85
87
  export interface EncodingPrefResult {
@@ -87,10 +89,15 @@ export interface EncodingPrefResult {
87
89
  q: number;
88
90
  order: number;
89
91
  }
90
- /** The native `AcceptNegotiator` class instance. */
92
+ /**
93
+ * The native `AcceptNegotiator` class instance (supported encodings compiled
94
+ * once). Best supported encoding for a header, or `null` for identity.
95
+ */
91
96
  export interface AcceptNegotiatorInstance {
92
97
  /** Best supported encoding for `header`, or null for identity. */
93
98
  negotiate(header: Uint8Array): string | null;
99
+ /** Opaque handle (bun:ffi fast path) — `castrum_accept_negotiator_negotiate`. */
100
+ innerPtr?(): bigint;
94
101
  }
95
102
  /** The native `Base64Codec` class instance (config compiled once). */
96
103
  export interface Base64CodecInstance {
@@ -107,6 +114,8 @@ export interface RateCheckResult {
107
114
  export interface RateLimiterInstance {
108
115
  check(key: string, nowMs: number): RateCheckResult;
109
116
  checkKey(key: number, nowMs: number): RateCheckResult;
117
+ /** Opaque handle (bun:ffi fast path) — `castrum_rate_limiter_check*`. */
118
+ innerPtr?(): bigint;
110
119
  }
111
120
  /** The native `CookieSigner` class instance (HMAC key compiled once). */
112
121
  export interface CookieSignerInstance {
@@ -122,6 +131,9 @@ export interface CsrfProtectorInstance {
122
131
  /** The native `UrlBuilder` class instance (base parsed once). */
123
132
  export interface UrlBuilderInstance {
124
133
  resolve(reference: Uint8Array): Uint8Array;
134
+ /** Opaque handle to the precompiled base (present when the bun:ffi fast path
135
+ * is active) — `castrum_url_builder_resolve` in rust/ffi.rs. */
136
+ innerPtr?(): bigint;
125
137
  }
126
138
  /** Options for `passwordHash` (argon2id). */
127
139
  export interface PasswordHashOptions {
@@ -150,11 +162,15 @@ export interface TemplateRendererInstance {
150
162
  renderBytes(contextJson: Uint8Array): Uint8Array;
151
163
  /** Parallel batch render: packed contexts in → packed rendered out. */
152
164
  renderBatchPacked(data: Uint8Array): Uint8Array;
165
+ /** Opaque handle (bun:ffi fast path) — `castrum_template_render`. */
166
+ innerPtr?(): bigint;
153
167
  }
154
168
  /** The native `MediaTypeMatcher` class instance (expected precompiled once). */
155
169
  export interface MediaTypeMatcherInstance {
156
170
  /** Wildcard match against the precompiled expected type. */
157
171
  matches(actual: Uint8Array): boolean;
172
+ /** Opaque handle (bun:ffi fast path) — `castrum_media_type_matcher_matches`. */
173
+ innerPtr?(): bigint;
158
174
  }
159
175
  /** The native `JwtSigner` class instance (HS256 key + ttl compiled once). */
160
176
  export interface JwtSignerInstance {
@@ -162,6 +178,8 @@ export interface JwtSignerInstance {
162
178
  /** Sign from pre-serialized claim JSON bytes (no napi Value marshal). */
163
179
  signBytes(claimsJson: Uint8Array, nowSeconds: number): Uint8Array;
164
180
  verify(token: Uint8Array, nowSeconds: number): unknown;
181
+ /** Opaque handle (bun:ffi fast path) — `castrum_jwt_signer_*`. */
182
+ innerPtr?(): bigint;
165
183
  }
166
184
  /** The native `AeadCipher` class instance (algorithm + key compiled once). */
167
185
  export interface AeadCipherInstance {
@@ -173,63 +191,13 @@ export interface Argon2HasherInstance {
173
191
  hash(password: Uint8Array, salt: Uint8Array): Uint8Array;
174
192
  verify(password: Uint8Array, phc: Uint8Array): boolean;
175
193
  }
176
- /** Options accepted by `createRust` / `rust.configure`. */
177
- export interface RustOptions {
178
- /**
179
- * Rayon thread pool size.
180
- *
181
- * The rayon pool is process-wide and initialized **once** (native
182
- * `OnceLock`) — the first initialization wins. Importing this module
183
- * initializes the pool with defaults, so this option only takes effect when
184
- * the pool has not yet been created. For reliable control set
185
- * `CASTRUM_RAYON_THREADS` / `RUST_RAYON_THREADS` before import.
186
- * Default: max(1, hardwareConcurrency - 1).
187
- */
188
- rayonThreads?: number;
189
- /** Cache MIME lookups keyed by normalized extension. Default: true. */
190
- mimeCache?: boolean;
191
- /** Reuse HMAC signers keyed by key-buffer identity. Default: true. */
192
- hmacCache?: boolean;
193
- }
194
- /** String-oriented FFI namespace. */
195
- export interface RustText {
196
- /**
197
- * Resolve a lowercase file extension to a MIME type string (e.g. `"html"` →
198
- * `"text/html"`). Unknown extensions return `"application/octet-stream"`.
199
- * @param ext the file extension WITHOUT a leading dot, case-insensitive.
200
- * @returns the MIME type for `ext`.
201
- */
202
- mimeFromExtension(ext: string): string;
203
- /**
204
- * RFC 3986 percent-encode a string (the `encodeURIComponent` unreserved
205
- * set). Under Bun this delegates to the native `encodeURIComponent` for
206
- * ~4x speed with byte-for-byte parity.
207
- * @param input the string to encode.
208
- * @returns the percent-encoded string.
209
- */
210
- urlEncode(input: string): string;
211
- /**
212
- * Percent-decode a string. Throws on malformed `%XX` or invalid UTF-8
213
- * output (parity with `decodeURIComponent`, which is used under Bun).
214
- * @param input the percent-encoded string to decode.
215
- * @returns the decoded string.
216
- */
217
- urlDecode(input: string): string;
218
- /**
219
- * Compute the RFC 6455 `Sec-WebSocket-Accept` value for a client key.
220
- * @param key the base64 `Sec-WebSocket-Key` header value.
221
- * @returns the 28-byte base64 accept value.
222
- */
223
- wsAcceptKey(key: string): string;
224
- /** @param input an email address. @returns whether it is RFC-valid. */
225
- validateEmail(input: string): boolean;
226
- /** @param input a UUID string. @returns whether it is a valid (v1-v8) UUID. */
227
- validateUuid(input: string): boolean;
228
- /** @param input an IPv4 address. @returns whether it is valid. */
229
- validateIpv4(input: string): boolean;
230
- /** @param input an IPv6 address. @returns whether it is valid. */
231
- validateIpv6(input: string): boolean;
232
- }
194
+ /** Parse a query string (`a=1&b=2`) into an object via the native parser. */
195
+ export declare function parseQueryString(query: string): Record<string, string | string[]>;
196
+ /** Parse a cookie header (`a=1; b=2`) into an object via the native parser. */
197
+ export declare function parseCookieHeader(header: string): Record<string, string | string[]>;
198
+ /** Parse an application/x-www-form-urlencoded body into a key/value object. */
199
+ export declare function parseFormBody(body: Uint8Array): Record<string, string | string[]>;
200
+ /** Native JSON-Schema validator handle (see `createSchemaValidator`). */
233
201
  export type SchemaValidator = SchemaValidatorInstance;
234
202
  /**
235
203
  * Unpack a packed u32 array: `[u32 count]{[u32 value]}` → `Uint32Array`.
@@ -252,18 +220,32 @@ export declare function unpackI64ArrayAsBigInt(bytes: Uint8Array): BigInt64Array
252
220
  * (zero-copy) — copy them if held beyond the buffer's lifetime.
253
221
  */
254
222
  export declare function unpackByteResults(bytes: Uint8Array): Uint8Array[];
223
+ /** A decoded `[name, value]` pair from a packed buffer. */
255
224
  export type Pair = [
256
225
  string,
257
226
  string
258
227
  ];
228
+ /**
229
+ * Decode a packed `[u32 count][u32 keyLen][key][u32 valLen][val]...` buffer
230
+ * into `[name, value]` string pairs (see `packPairs` for the layout).
231
+ */
259
232
  export declare function readPairsPacked(bytes: Uint8Array): Pair[];
233
+ /**
234
+ * Fold `[name, value]` pairs into an object; repeated names collect into a
235
+ * string array (query-string/cookie semantics).
236
+ */
260
237
  export declare function pairsToObject(pairs: Pair[]): Record<string, string | string[]>;
238
+ /** A decoded HTTP request from the native packed parser. */
261
239
  export interface ParsedHttpRequestPacked {
262
240
  method: string;
263
241
  path: string;
264
242
  version: string;
265
243
  headers: Record<string, string>;
266
244
  }
245
+ /**
246
+ * Decode a native `httpParseRequestPacked` buffer into a plain request object
247
+ * (zero-alloc on the Rust side; this builds the JS strings once).
248
+ */
267
249
  export declare function readHttpPacked(bytes: Uint8Array): ParsedHttpRequestPacked;
268
250
  /**
269
251
  * Build a packed batch buffer. Returns an OWNED buffer (safe to hold across
@@ -271,410 +253,841 @@ export declare function readHttpPacked(bytes: Uint8Array): ParsedHttpRequestPack
271
253
  * guarantee synchronous consumption should use `withPackScratch` instead.
272
254
  */
273
255
  export declare function packBatch(items: Uint8Array[]): Uint8Array;
256
+ /**
257
+ * Pack `[name, value]` string pairs into the native `[u32 count]...` layout
258
+ * that `readPairsPacked` / the batch validators consume.
259
+ */
274
260
  export declare function packPairs(pairs: Array<[
275
261
  string,
276
262
  string
277
263
  ]>): Uint8Array;
278
- export declare function parseQueryString(query: string): Record<string, string | string[]>;
279
- export declare function parseCookieHeader(header: string): Record<string, string | string[]>;
280
- /** Parse an application/x-www-form-urlencoded body into a key/value object. */
281
- export declare function parseFormBody(body: Uint8Array): Record<string, string | string[]>;
282
- /** Array-of-bytes FFI namespace. */
283
- export interface RustBatch {
284
- jsonValid(items: Uint8Array[]): Uint8Array;
285
- crc32(items: Uint8Array[]): Uint32Array;
286
- validateEmail(items: Uint8Array[]): Uint8Array;
287
- validateUuid(items: Uint8Array[]): Uint8Array;
288
- validateIpv4(items: Uint8Array[]): Uint8Array;
289
- validateIpv6(items: Uint8Array[]): Uint8Array;
290
- jsonSumIds(items: Uint8Array[]): BigInt64Array;
291
- queryParse(items: Uint8Array[]): Uint8Array[];
292
- cookieParse(items: Uint8Array[]): Uint8Array[];
293
- httpParseRequest(items: Uint8Array[]): Uint8Array[];
294
- /** Apply N RFC 6902 patches (docs and patches zipped). Fail-fast on error. */
295
- jsonPatch(docs: Uint8Array[], patches: Uint8Array[]): Uint8Array[];
296
- /** Encode N items to lowercase hex (packed in → byte results). */
297
- hexEncode(items: Uint8Array[]): Uint8Array[];
298
- /** Decode N lowercase/uppercase hex strings to bytes. */
299
- hexDecode(items: Uint8Array[]): Uint8Array[];
300
- /** Base64-encode N items (standard by default; url-safe/padding configurable). */
301
- base64Encode(items: Uint8Array[], urlSafe?: boolean, padding?: boolean): Uint8Array[];
302
- /** Base64-decode N items (standard by default; url-safe/padding configurable). */
303
- base64Decode(items: Uint8Array[], urlSafe?: boolean, padding?: boolean): Uint8Array[];
304
- formParse(items: Uint8Array[]): Uint8Array[];
305
- /** Sign N cookie values (packed → byte results). */
306
- signCookie(items: Uint8Array[], secret: Uint8Array): Uint8Array[];
307
- /** Verify N signed cookies (bitset of valid). */
308
- verifyCookie(items: Uint8Array[], secret: Uint8Array): Uint8Array;
309
- /** Verify N CSRF tokens (bitset of valid). */
310
- csrfVerify(items: Uint8Array[], secret: Uint8Array): Uint8Array;
311
- schemaValidate(validator: SchemaValidator, items: Uint8Array[]): Uint8Array;
312
- schemaValidateCount(validator: SchemaValidator, items: Uint8Array[]): number;
313
- /** Hash N items with FNV-1a 64 (packed → unsigned u64 array). */
314
- fnv1a64(items: Uint8Array[]): BigUint64Array;
315
- /** Generate N ETags (strong by default; weak flag applies to all items). */
316
- etag(items: Uint8Array[], weak?: boolean | null): Uint8Array[];
317
- urlEncode(items: Uint8Array[]): Uint8Array[];
318
- /** Percent-decode N strings (UTF-8 validated; malformed items → empty). */
319
- urlDecode(items: Uint8Array[]): Uint8Array[];
320
- /** Strict percent-decode N strings (no UTF-8 validation). */
321
- urlDecodeBytes(items: Uint8Array[]): Uint8Array[];
322
- mimeFromExtension(items: Uint8Array[]): Uint8Array[];
323
- wsAcceptKey(items: Uint8Array[]): Uint8Array[];
324
- /** Base64url-encode N items (URL-safe, no padding). */
325
- base64UrlEncode(items: Uint8Array[]): Uint8Array[];
326
- /** Base64url-decode N items (URL-safe, no padding). */
327
- base64UrlDecode(items: Uint8Array[]): Uint8Array[];
328
- passwordHash(passwords: Uint8Array[], salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array[];
329
- aeadEncrypt(key: Uint8Array, nonce: Uint8Array, items: Uint8Array[], algorithm?: string | null): Uint8Array[];
330
- aeadDecrypt(key: Uint8Array, nonce: Uint8Array, items: Uint8Array[], algorithm?: string | null): Uint8Array[];
331
- gzipCompress(items: Uint8Array[], level?: number | null): Uint8Array[];
332
- gzipDecompress(items: Uint8Array[], maxDecompressed?: number | null): Uint8Array[];
333
- brotliCompress(items: Uint8Array[], quality?: number | null): Uint8Array[];
334
- brotliDecompress(items: Uint8Array[], maxDecompressed?: number | null): Uint8Array[];
335
- jwtVerify(tokens: Uint8Array[], secret: Uint8Array, nowSeconds: number): Uint8Array;
336
- /** Sign N messages to lowercase-hex HMAC-SHA256 signatures (packed → byte results). */
337
- hmacSha256(items: Uint8Array[], key: Uint8Array): Uint8Array[];
338
- /** Verify N message + hex-signature pairs (two packed lists, zipped) → bitset of valid. */
339
- hmacSha256Verify(items: Uint8Array[], sigs: Uint8Array[], key: Uint8Array): Uint8Array;
340
- /** Verify N password+PHC pairs (two packed lists, zipped) → bitset of valid. */
341
- passwordVerify(items: Uint8Array[], phcs: Uint8Array[]): Uint8Array;
342
- /** Resolve N references against N bases (two packed lists, zipped). */
343
- urlResolve(bases: Uint8Array[], references: Uint8Array[]): Uint8Array[];
344
- /** Sign N JSON claim documents (packed → signed tokens). */
345
- jwtSign(items: Uint8Array[], secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array[];
346
- /** Encode N SSE events with shared event/id/retry. */
347
- sseEncode(items: Uint8Array[], event?: string | null, id?: string | null, retry?: number | null): Uint8Array[];
348
- /** Encode N frames (same opcode/mask/fin) from payloads. */
349
- wsFrameEncode(items: Uint8Array[], opcode: number, mask: boolean, fin: boolean): Uint8Array[];
350
- /** Decode N frames → payloads (opcodes/flags dropped; failed items → empty). */
351
- wsFrameDecode(items: Uint8Array[]): Uint8Array[];
352
- /** Parse N multipart bodies → array of parts per item (same boundary). */
353
- multipartParse(items: Uint8Array[], boundary: Uint8Array): MultipartPart[][];
354
- /**
355
- * @performance Template render: ~1.7x slower than the JS baseline (1/3 tasks failed) [check:annotate]
356
- * @deprecated Slower than the native JS baseline (~1.7x) — prefer the JS/Bun baseline. [check:annotate]
357
- * @remarks Promotion candidate: 2/3 benchmarks won in the latest run (static: not-competitive). [check:annotate]
358
- * @remarks The allocating render marshals the context via napi DOM (~1.5x loss). Use TemplateRenderer.renderBytes (JSON-bytes context) which avoids it and wins ~1.37x. [check:annotate]
359
- */
360
- templateRender(source: string, contexts: Uint8Array[]): Uint8Array[];
361
- }
362
- /** Raw packed-wire FFI namespace. */
363
- export interface RustPacked {
364
- crc32BatchPacked(input: Uint8Array): Uint8Array;
365
- jsonValidBatchPacked(input: Uint8Array): Uint8Array;
366
- validateEmailBatchPacked(input: Uint8Array): Uint8Array;
367
- validateUuidBatchPacked(input: Uint8Array): Uint8Array;
368
- validateIpv4BatchPacked(input: Uint8Array): Uint8Array;
369
- validateIpv6BatchPacked(input: Uint8Array): Uint8Array;
370
- jsonSumBatchPacked(input: Uint8Array): Uint8Array;
371
- queryParseBatchPacked(input: Uint8Array): Uint8Array;
372
- cookieParseBatchPacked(input: Uint8Array): Uint8Array;
373
- httpParseRequestBatchPacked(input: Uint8Array): Uint8Array;
374
- /** Batch RFC 6902 JSON Patch (two packed lists, zipped) → packed results. */
375
- jsonPatchBatchPacked(docs: Uint8Array, patches: Uint8Array): Uint8Array;
376
- /** Packed FNV-1a 64 batch (i64 per item). */
377
- fnv1A64BatchPacked(input: Uint8Array): Uint8Array;
378
- /** Packed ETag batch (10 strong / 12 weak bytes per item). */
379
- etagBatchPacked(input: Uint8Array, weak?: boolean | null): Uint8Array;
380
- urlEncodeBatchPacked(input: Uint8Array): Uint8Array;
381
- urlDecodeBatchPacked(input: Uint8Array): Uint8Array;
382
- urlDecodeBytesBatchPacked(input: Uint8Array): Uint8Array;
383
- mimeFromExtensionBatchPacked(input: Uint8Array): Uint8Array;
384
- wsAcceptKeyBatchPacked(input: Uint8Array): Uint8Array;
385
- jsonValidBatchCountPacked(input: Uint8Array): number;
386
- validateEmailBatchCountPacked(input: Uint8Array): number;
387
- validateUuidBatchCountPacked(input: Uint8Array): number;
388
- validateIpv4BatchCountPacked(input: Uint8Array): number;
389
- validateIpv6BatchCountPacked(input: Uint8Array): number;
390
- jsonSumBatchTotalPacked(input: Uint8Array): number;
391
- queryParseBatchTotalLenPacked(input: Uint8Array): number;
392
- cookieParseBatchTotalLenPacked(input: Uint8Array): number;
393
- httpParseRequestBatchTotalLenPacked(input: Uint8Array): number;
394
- passwordHashBatchPacked(input: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array;
395
- /** Packed password-verify batch (two packed lists, zipped) → bitset. */
396
- passwordVerifyBatchPacked(passwords: Uint8Array, phcs: Uint8Array): Uint8Array;
397
- /** Packed URL-resolve batch (two packed lists, zipped) → packed results. */
398
- urlResolveBatchPacked(bases: Uint8Array, references: Uint8Array): Uint8Array;
399
- aeadEncryptBatchPacked(input: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null): Uint8Array;
400
- aeadDecryptBatchPacked(input: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null): Uint8Array;
401
- gzipCompressBatchPacked(input: Uint8Array, level?: number | null): Uint8Array;
402
- gzipDecompressBatchPacked(input: Uint8Array): Uint8Array;
403
- brotliCompressBatchPacked(input: Uint8Array, quality?: number | null): Uint8Array;
404
- brotliDecompressBatchPacked(input: Uint8Array): Uint8Array;
405
- jwtSignBatchPacked(input: Uint8Array, secret: Uint8Array, ttlSeconds: number | null, nowSeconds: number): Uint8Array;
406
- jwtVerifyBatchPacked(input: Uint8Array, secret: Uint8Array, nowSeconds: number): Uint8Array;
407
- /** Batch HMAC-SHA256 sign (packed in → hex-signature byte results). */
408
- hmacSha256BatchPacked(input: Uint8Array, key: Uint8Array): Uint8Array;
409
- /** Batch HMAC-SHA256 verify (two packed lists: data + hex sigs, zipped) → bitset. */
410
- hmacSha256VerifyBatchPacked(input: Uint8Array, sigs: Uint8Array, key: Uint8Array): Uint8Array;
411
- multipartParseBatchPacked(input: Uint8Array, boundary: Uint8Array): Uint8Array;
412
- templateRenderBatchPacked(input: Uint8Array, source: string): Uint8Array;
413
- sseEncodeBatchPacked(input: Uint8Array, event: string | null, id: string | null, retry: number | null): Uint8Array;
414
- wsFrameEncodeBatchPacked(input: Uint8Array, opcode: number, mask: boolean, fin: boolean): Uint8Array;
415
- wsFrameDecodeBatchPacked(input: Uint8Array): Uint8Array;
264
+ /** Bounds-checked section offsets for one ingress output buffer. */
265
+ export interface PackedSectionLayout {
266
+ /** Cookie-JSON length clamped to the buffer (0 if none / out of range). */
267
+ safeCookiesLen: number;
268
+ /** Byte offset where the query-JSON section begins. */
269
+ queryStart: number;
270
+ /** Query-JSON length clamped to the buffer (0 if none / out of range). */
271
+ safeQueryLen: number;
272
+ /** Byte offset where the body-JSON section begins. */
273
+ bodyJsonStart: number;
274
+ /** Body-JSON length clamped to the buffer (0 if none / out of range). */
275
+ safeBodyJsonLen: number;
276
+ /** Whether any declared section length overran the buffer. */
277
+ truncated: boolean;
416
278
  }
417
- /** Scalar + factory + runtime methods of the Rust client. */
418
- export interface RustScalar {
279
+ declare abstract class IngressResultBase {
280
+ /** Raw native verdict byte (0 = accepted). */
281
+ verdict: number;
282
+ /** Raw native error-code byte. */
283
+ errorCode: number;
284
+ /** Normalized HTTP status. */
285
+ status: number;
286
+ /** Header template variant byte emitted by the native core. */
287
+ headerVariant: number;
288
+ /** Remaining rate-limit budget (count). */
289
+ rateRemaining: number;
290
+ /** Rate-limit window reset (ms epoch). */
291
+ rateResetMs: number;
292
+ /** Retry-After value (ms). */
293
+ retryAfterMs: number;
294
+ /** True when the pipeline returned a terminal (error) verdict. */
295
+ terminal: boolean;
296
+ /** True when the pipeline accepted the request (verdict 0 + 2xx/3xx). */
297
+ ok: boolean;
298
+ /** True when the request was a CORS preflight. */
299
+ isPreflight: boolean;
300
+ /** True when the CORS engine allowed the request origin. */
301
+ corsAllowed: boolean;
302
+ /** True when the request was rate-limited. */
303
+ rateLimited: boolean;
304
+ /** True when the request came from a trusted proxy. */
305
+ trustedProxy: boolean;
306
+ /** True when the request body parsed as valid JSON. */
307
+ bodyValidJson: boolean;
308
+ /** True when the request body validated against the ingress schema. */
309
+ schemaValid: boolean;
310
+ /** True when a declared output section overran the buffer. */
311
+ bodyTruncated: boolean;
312
+ /** Request body bytes (may be an empty view). */
313
+ body: Uint8Array;
314
+ protected _buf: Uint8Array;
315
+ protected _bodyJsonStart: number;
316
+ protected _bodyJsonLen: number;
317
+ private _cookiesBuf;
318
+ private _queryBuf;
319
+ private _cookiesDecoded;
320
+ private _queryDecoded;
321
+ /** Reset the shared fields to their empty state (call from subclass `invalidate`). */
322
+ protected resetShared(): void;
323
+ /** Recompute `terminal`/`ok` from the (subclass-set) verdict + status. */
324
+ protected updateOkTerminal(): void;
419
325
  /**
420
- * @performance CRC32: ~3.7x slower than the JS baseline (2/3 tasks failed) [check:annotate]
421
- * @deprecated Slower than the native JS baseline (~3.7x) — prefer the JS/Bun baseline. [check:annotate]
422
- * @remarks Sub-µs FFI-crossing bound vs the same-engine JS crc-32 loop (~0.23-0.44x across runs); use the packed crc32BatchPacked path which wins on larger inputs. [check:annotate]
326
+ * Store the rate-limit window fields. Both decoders read the same OUT_*
327
+ * slots and gate them on the same conditions (a positive budget OR the
328
+ * rate-limited flag), so the read cannot drift between paths.
423
329
  */
424
- crc32(input: Uint8Array): number;
330
+ protected setRateWindow(rateLimit: number, rateLimited: boolean, view: DataView): void;
425
331
  /**
426
- * @performance FNV-1a 64: ~6.6x faster than the JS baseline [check:annotate]
332
+ * Store the bounds-checked cookie/query/body JSON sections from `layout`.
333
+ *
334
+ * `bodyJsonLen` is the body-JSON length to trust for `bodyJson()`: the fast
335
+ * path passes the RAW declared length (it re-checks bounds on read), the
336
+ * baked path passes the already-clamped `layout.safeBodyJsonLen`. Sections
337
+ * are stored as slices and decoded lazily by `cookiesJson()`/`queryJson()`.
427
338
  */
428
- fnv1a64(input: Uint8Array): bigint;
429
- /**
430
- * XXH3-64 over raw bytes (high-throughput non-cryptographic hash).
431
- * Compare against `Bun.hash.xxHash3` — see docs/bun-builtins-decision-matrix.md.
432
- */
433
- xxh3(input: Uint8Array): bigint;
434
- /**
435
- * @performance HMAC sign: ~1.1x faster than the JS baseline (2/3 tasks won) [check:annotate]
436
- */
437
- hmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array;
339
+ protected setSections(buf: Uint8Array, layout: PackedSectionLayout, bodyJsonLen: number): void;
340
+ /** Decoded cookies-JSON section, or `"{}"` when absent. */
341
+ cookiesJson(): string;
342
+ /** Decoded query-JSON section, or `"{}"` when absent. */
343
+ queryJson(): string;
344
+ /** Bounds-checked body-JSON slice (empty when absent / out of range). */
345
+ protected bodyJsonSlice(): Uint8Array;
346
+ }
347
+ /** Zero-alloc, reusable result decoder for the pre-baked handler path. */
348
+ export declare class BakedIngressResult extends IngressResultBase {
349
+ refresh(buf: Uint8Array, body: Uint8Array, view: DataView): void;
350
+ invalidate(): void;
351
+ setInternalError(): void;
352
+ bodyJson(copy: boolean): Uint8Array;
353
+ }
354
+ /** User-facing CORS configuration. */
355
+ export interface CorsOptions {
356
+ allowOrigin?: string[];
357
+ allowMethods?: string[];
358
+ allowHeaders?: string[];
359
+ exposeHeaders?: string[];
360
+ allowCredentials?: boolean;
361
+ maxAge?: number;
362
+ }
363
+ /** Precomputed, immutable CORS policy strings. */
364
+ export interface CorsStaticStrings {
365
+ readonly allowMethodsJoined: string;
366
+ readonly allowHeadersJoined: string;
367
+ readonly exposeHeadersJoined: string;
368
+ readonly maxAgeString: string | null;
369
+ readonly isWildcard: boolean;
370
+ readonly credentials: boolean;
371
+ }
372
+ /** User-facing security-headers configuration. */
373
+ export interface SecurityHeadersOptions {
374
+ contentSecurityPolicy?: string;
375
+ hsts?: boolean;
376
+ hstsMaxAge?: number;
377
+ hstsIncludeSubdomains?: boolean;
378
+ hstsPreload?: boolean;
379
+ frameOptions?: string;
380
+ nosniff?: boolean;
381
+ referrerPolicy?: string;
382
+ coep?: string;
383
+ coop?: string;
384
+ corp?: string;
385
+ xssProtection?: string;
386
+ }
387
+ /** Zero-alloc, lazy-decoding view over a native Ingress output buffer. */
388
+ export declare class FastIngressResult extends IngressResultBase {
389
+ status: number;
390
+ verdict: number;
391
+ errorCode: number;
392
+ flags: number;
393
+ https: boolean;
394
+ hasCookies: boolean;
395
+ hasQuery: boolean;
396
+ rateLimit: number;
397
+ requestId: string;
398
+ refresh(buf: Uint8Array, body: Uint8Array, requestId: string): void;
399
+ invalidate(): void;
400
+ setInternalError(requestId: string): void;
401
+ /** Bounds-checked body-JSON section, or an empty view when absent. */
402
+ bodyJson(): Uint8Array;
403
+ }
404
+ /** Options accepted by `createIngressFast` / `createIngress`. */
405
+ export interface IngressFastOptions {
406
+ trustProxy?: boolean;
407
+ trustedProxies?: {
408
+ enabled?: boolean;
409
+ networks?: string[];
410
+ };
411
+ parseCookies?: boolean;
412
+ parseQuery?: boolean;
413
+ requireJsonBody?: boolean;
414
+ schema?: Uint8Array;
415
+ cors?: CorsOptions;
416
+ rateLimit?: {
417
+ limit?: number;
418
+ windowMs?: number;
419
+ maxEntries?: number;
420
+ };
438
421
  /**
439
- * @performance HMAC verify: ~2.5x faster than the JS baseline [check:annotate]
422
+ * Structured security-header options (CSP/HSTS) — honored by the fast/async
423
+ * paths (`createIngressFast` throws on it; `createIngress` applies it via
424
+ * `buildResponseContext`). The PRE-BAKED path (`createIngressHandler`)
425
+ * instead takes raw `securityHeaders: [name, value][]` pairs. The two paths
426
+ * intentionally use different option shapes (see docs/INGRESS.md).
440
427
  */
441
- hmacSha256Verify(key: Uint8Array, data: Uint8Array, sig: Uint8Array): boolean;
428
+ security?: SecurityHeadersOptions;
429
+ https?: boolean;
430
+ maxBodyBytes?: number;
431
+ enableSecurityHeaders?: boolean;
432
+ enableRequestIds?: boolean;
433
+ enableBodySizeGuard?: boolean;
434
+ emitMetadataJson?: boolean;
435
+ readBody?: boolean;
436
+ outputBufferSize?: number;
442
437
  /**
443
- * @performance JSON valid: ~3.2x faster than the JS baseline (8/8 tasks won) [check:annotate]
438
+ * Overall deadline (ms) for reading a request body in the async
439
+ * `createIngress` path. 0 disables. Default: `DEFAULT_BODY_TIMEOUT_MS` (30s).
440
+ * Ignored by the sync `createIngressFast` (it does not read bodies).
444
441
  */
445
- jsonValid(input: Uint8Array): boolean;
442
+ bodyTimeoutMs?: number;
446
443
  /**
447
- * Parse JSON to a JS value (native sonic-rs DOM → napi). Throws on invalid JSON.
448
- * @performance JSON parse: ~5.0x slower than the JS baseline [check:annotate]
449
- * @deprecated Slower than the native JS baseline (~5.0x) — prefer the JS/Bun baseline. [check:annotate]
450
- * @remarks Bun's JSON.parse beats the native DOM + napi marshaling path (~5x). [check:annotate]
444
+ * Invoked when the native pipeline throws (the request becomes a 500).
445
+ * Native failures are otherwise silent in the fast path. Never throws.
451
446
  */
452
- jsonParse(input: Uint8Array): unknown;
447
+ onError?: (error: Error) => void;
453
448
  /**
454
- * @performance JSON sum: ~2.9x faster than the JS baseline (4/4 tasks won) [check:annotate]
449
+ * When true, run one probe GET at construction so the `run()` closure,
450
+ * packed pipeline and FFI ingress call are JIT-warmed before the first real
451
+ * request (cuts cold-invocation tail latency in serverless-style
452
+ * deployments). Opt-in; default false. Not forwarded to the native addon.
455
453
  */
456
- jsonSumIds(input: Uint8Array): bigint;
454
+ warmOnCreate?: boolean;
455
+ limits?: {
456
+ maxUrlBytes?: number;
457
+ maxQueryBytes?: number;
458
+ maxCookieBytes?: number;
459
+ maxHeadersBytes?: number;
460
+ maxHeaders?: number;
461
+ maxPairs?: number;
462
+ };
463
+ }
464
+ /** The zero-alloc sync handler returned by `createIngressFast`. */
465
+ export interface IngressFastHandler {
466
+ run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, requestId: string, fn: (result: FastIngressResult) => T): T;
467
+ }
468
+ /**
469
+ * Options accepted by `createIngressHandler` (path 2).
470
+ *
471
+ * Same native option surface as the fast path, minus `onError` — path 2
472
+ * reports native failures through `BakedIngressRuntime.onError` instead of the
473
+ * options bag.
474
+ */
475
+ export type IngressHandlerOptions = Omit<IngressFastOptions, "onError">;
476
+ /** Public ingress options (extends the fast-path options). */
477
+ export interface IngressOptions extends IngressFastOptions {
478
+ enableRequestIds?: boolean;
457
479
  /**
458
- * @performance JSON Patch: ~1.2x faster than the JS baseline [check:annotate]
459
- * @remarks Modest but real win; swings ~0.9-1.5x run-to-run (DOM marshal dominated). [check:annotate]
480
+ * Invoked before a request is processed (for tracing/context hooks).
481
+ * Only used by the async `createIngress` path.
460
482
  */
461
- jsonPatch(doc: Uint8Array, patch: Uint8Array): Uint8Array;
483
+ onRequest?: (req: Request, requestId: string, ip: string | undefined) => void;
462
484
  /**
463
- * @performance MIME lookup: ≈ parity with the JS baseline [check:annotate]
464
- * @remarks Noisy sub-µs op: wins ~1.6x on good runs, loses on bad runs; phf table lookup. [check:annotate]
485
+ * Invoked after a terminal context (and its `Response`) is produced, for
486
+ * metrics/logging hooks. Only used by the async `createIngress` path.
465
487
  */
466
- mimeFromExtension(ext: Uint8Array): Uint8Array;
488
+ onResponse?: (req: Request, result: IngressContext, status: number, requestId: string) => void;
489
+ }
490
+ /**
491
+ * Readonly structural view of a decoded ingress result.
492
+ *
493
+ * Note: the exported `FastIngressResult` class is the zero-alloc implementation;
494
+ * this interface is the readonly view used by the public sync/async handlers.
495
+ */
496
+ export interface IngressResult {
497
+ readonly status: number;
498
+ readonly verdict: number;
499
+ readonly flags: number;
500
+ readonly errorCode: number;
501
+ readonly terminal: boolean;
502
+ readonly ok: boolean;
503
+ readonly https: boolean;
504
+ readonly trustedProxy: boolean;
505
+ readonly hasCookies: boolean;
506
+ readonly hasQuery: boolean;
507
+ readonly bodyValidJson: boolean;
508
+ readonly schemaValid: boolean;
509
+ readonly corsAllowed: boolean;
510
+ readonly isPreflight: boolean;
511
+ readonly rateLimited: boolean;
512
+ readonly rateLimit: number;
513
+ readonly rateRemaining: number;
514
+ readonly rateResetMs: number;
515
+ readonly retryAfterMs: number;
516
+ readonly body: Uint8Array;
517
+ readonly headerVariant: number;
518
+ readonly requestId: string;
519
+ readonly bodyTruncated: boolean;
520
+ cookiesJson(): string;
521
+ queryJson(): string;
522
+ bodyJson(): Uint8Array;
523
+ }
524
+ /** A result plus the terminal Response computed for it. */
525
+ export interface IngressContext extends IngressResult {
526
+ response: Response | null;
527
+ }
528
+ /**
529
+ * Synchronous ingress handler.
530
+ *
531
+ * The callback runs on the zero-alloc result object and MUST be synchronous:
532
+ * returning a Promise (or any thenable) throws. The result is invalidated after
533
+ * `run()` returns, so capture the fields you need inside the callback (or use
534
+ * the async {@link IngressHandler} which snapshots for you).
535
+ */
536
+ export interface SyncIngressHandler {
537
+ run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, requestId: string, fn: (result: IngressResult) => T): T;
538
+ }
539
+ /** Async ingress handler (wraps {@link SyncIngressHandler} with body reading). */
540
+ export type IngressHandler = (req: Request, ip?: string) => Promise<IngressContext>;
541
+ /** Mutable per-request context threaded through the pre-baked handler run. */
542
+ export interface BakedContext {
543
+ /** The request-id string (null when `emitRequestIdHeader` is off). */
544
+ requestIdHeader: string | null;
545
+ /** The `Origin` request header when CORS extraction is enabled. */
546
+ origin: string | null;
547
+ }
548
+ /**
549
+ * An optimized ingress handler. `run()` is the zero-alloc pipeline entry
550
+ * point; the response-builder methods are pre-baked and bound to this
551
+ * handler's configuration, so consumers can build custom routes without
552
+ * touching header templates or error bodies.
553
+ */
554
+ export interface OptimizedIngressHandler {
555
+ run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, fn: (result: BakedIngressResult, ctx: BakedContext) => T): T;
556
+ responseHeaders(variant: number, requestIdHeader: string | null, origin: string | null, rateRemaining?: number, rateResetSecs?: number, retryAfterSecs?: number): [
557
+ string,
558
+ string
559
+ ][];
560
+ terminalHeaders(variant: number, ctx: BakedContext, result: BakedIngressResult | null): [
561
+ string,
562
+ string
563
+ ][];
564
+ /** `req` is accepted for back-compat but unused by the baked terminal path. */
565
+ terminalResponse(req: Request | undefined, result: BakedIngressResult, ctx: BakedContext): Response | null;
566
+ /** `req` is accepted for back-compat but unused by the baked error path. */
567
+ errorResponse(req: Request | undefined, result: BakedIngressResult | null, status: number, code: string, message: string, ctx: BakedContext): Response;
568
+ internalErrorResponse(ctx: BakedContext, result?: BakedIngressResult): Response;
569
+ withContentType(headers: ReadonlyArray<[
570
+ string,
571
+ string
572
+ ]>, contentType: string): [
573
+ string,
574
+ string
575
+ ][];
467
576
  /**
468
- * @performance Random token: ≈ parity with the JS baseline [check:annotate]
577
+ * Build a zero-copy `Response` whose body is the request's pooled output
578
+ * slice. The pooled buffer is returned to its pool once the body has been
579
+ * consumed (stream closed) or the request aborted. Use when `copyBody` is
580
+ * `false`; otherwise a copied body is released eagerly at the end of `run()`.
469
581
  */
470
- randomToken(byteLen: number): Uint8Array;
582
+ zeroCopyResponse(result: BakedIngressResult, ctx: BakedContext, init: ResponseInit): Response;
583
+ }
584
+ /** Terminal (rejection) response envelope style for responder routes.
585
+ * `"castrum"` (default) emits the pre-baked `ok:false`/`ratelimit-*` wire;
586
+ * `"ignex"` emits the ignex framework envelope (`{error,status,code}` +
587
+ * `x-frame-options`/`nosniff`/`referrer-policy` security headers). Additive —
588
+ * castrum's own wire formats are untouched. */
589
+ export type TerminalStyle = "castrum" | "ignex";
590
+ /**
591
+ * Decoded request context handed to a {@link NativeResponder} after the native
592
+ * pipeline succeeded (non-terminal). The native pipeline owns parse/validate/
593
+ * CORS/rate-limit + terminal rejections; the responder builds the 2xx body
594
+ * (async OK). Fields are captured INSIDE the sync `run()` callback, so the
595
+ * pooled output buffer is never aliased after it is released.
596
+ */
597
+ export interface NativeRequestContext {
598
+ readonly requestId: string;
599
+ readonly status: number;
600
+ readonly rateLimited: boolean;
601
+ readonly retryAfterMs: number;
602
+ /** Parsed query object (last-wins per key) — `{}` when `parseQuery` is off. */
603
+ readonly query: Record<string, string | string[]>;
604
+ /** Parsed cookie object (last-wins per key) — `{}` when `parseCookies` is off. */
605
+ readonly cookies: Record<string, string>;
606
+ /** Request body bytes when read for native validation, else empty. */
607
+ readonly body: Uint8Array;
608
+ readonly ip: string | undefined;
609
+ readonly req: Request;
610
+ }
611
+ /** A JS 2xx builder invoked after the native pipeline succeeds (async OK). */
612
+ export type NativeResponder = (snap: NativeRequestContext) => Response | Promise<Response>;
613
+ /** Options accepted by the pre-baked route factories. */
614
+ export interface BakedHandlerOptions {
615
+ /** Resolve the client IP from the server object (e.g. `srv.requestIP`). */
616
+ getIp?: (req: Request, srv: unknown) => string | undefined;
617
+ /** Copy body slices instead of sharing the native buffer. Default: true (safe). */
618
+ copyBody?: boolean;
619
+ /** Maximum request body bytes for write/echo handlers. Default: 1 MiB. */
620
+ maxBodyBytes?: number;
471
621
  /**
472
- * @performance URL encode: ~2.2x slower than the JS baseline (2/3 tasks failed) [check:annotate]
473
- * @deprecated Slower than the native JS baseline (~2.2x) — prefer the JS/Bun baseline. [check:annotate]
474
- * @remarks Loses ~2.8x on the shipped baseline release build (only wins in the LOCAL SIMD perf build). [check:annotate]
475
- */
476
- urlEncode(input: Uint8Array): Uint8Array;
477
- /**
478
- * @performance URL decode: ~2.2x slower than the JS baseline (2/3 tasks failed) [check:annotate]
479
- * @deprecated Slower than the native JS baseline (~2.2x) — prefer the JS/Bun baseline. [check:annotate]
480
- * @remarks Loses ~2.8x on the shipped baseline release build (only wins in the LOCAL SIMD perf build). [check:annotate]
481
- */
482
- urlDecode(input: Uint8Array): Uint8Array;
483
- /** Strict percent-decode without UTF-8 validation. */
484
- urlDecodeBytes(input: Uint8Array): Uint8Array;
485
- /** Reusable-output percent-encode; returns bytes written. */
486
- urlEncodeInto(input: Uint8Array, output: Uint8Array): number;
487
- /** Reusable-output percent-decode; returns bytes written. */
488
- urlDecodeInto(input: Uint8Array, output: Uint8Array): number;
489
- /**
490
- * @performance Email validation: ~3.1x faster than the JS baseline (4/4 tasks won) [check:annotate]
491
- */
492
- validateEmail(input: Uint8Array): boolean;
493
- /**
494
- * @performance UUID validation: ≈ parity with the JS baseline (2/4 tasks won) [check:annotate]
495
- */
496
- validateUuid(input: Uint8Array): boolean;
497
- /**
498
- * @performance IPv4 validation: ≈ parity with the JS baseline (2/2 tasks won) [check:annotate]
499
- */
500
- validateIpv4(input: Uint8Array): boolean;
501
- /**
502
- * @performance IPv6 validation: ~1.9x faster than the JS baseline [check:annotate]
503
- */
504
- validateIpv6(input: Uint8Array): boolean;
505
- /**
506
- * @performance WebSocket accept: ~1.9x faster than the JS baseline (1/2 tasks won) [check:annotate]
507
- */
508
- wsAcceptKey(key: Uint8Array): Uint8Array;
509
- /**
510
- * @performance HTTP parse: ~5.3x faster than the JS baseline (6/6 tasks won) [check:annotate]
511
- */
512
- httpParseRequestPacked(input: Uint8Array): Uint8Array;
513
- /**
514
- * @performance Query parse: ~3.8x faster than the JS baseline (6/6 tasks won) [check:annotate]
515
- */
516
- queryParsePacked(input: Uint8Array): Uint8Array;
517
- /**
518
- * @performance Cookie parse: ~2.6x faster than the JS baseline (5/5 tasks won) [check:annotate]
519
- */
520
- cookieParsePacked(input: Uint8Array): Uint8Array;
521
- /** Reusable-output packed HTTP parse; returns bytes written. */
522
- httpParseRequestPackedInto(input: Uint8Array, output: Uint8Array): number;
523
- /** Reusable-output packed query parse; returns bytes written. */
524
- queryParsePackedInto(input: Uint8Array, output: Uint8Array): number;
525
- /** Reusable-output packed cookie parse; returns bytes written. */
526
- cookieParsePackedInto(input: Uint8Array, output: Uint8Array): number;
527
- /**
528
- * Parse an application/x-www-form-urlencoded body into packed pairs.
529
- * @performance Form parse: ~4.7x faster than the JS baseline (2/2 tasks won) [check:annotate]
530
- * @remarks Benchmarked via the FormParser instance (same parser core). [check:annotate]
531
- */
532
- formParsePacked(input: Uint8Array): Uint8Array;
533
- /**
534
- * Parse a Content-Type header into a structured media type.
535
- * @performance Media type parse: ~1.3x slower than the JS baseline [check:annotate]
536
- * @deprecated Slower than the native JS baseline (~1.3x) — prefer the JS/Bun baseline. [check:annotate]
537
- * @remarks Consistent ~0.71-0.81x (sub-µs FFI crossing vs the JS baseline); use MediaTypeMatcher (precompiled expected) for the zero-alloc match path. [check:annotate]
538
- */
539
- parseMediaType(input: Uint8Array): MediaTypeResult;
540
- /**
541
- * Generate a strong/weak ETag (crc32-based).
542
- * @performance ETag: ≈ parity with the JS baseline [check:annotate]
543
- */
544
- etag(data: Uint8Array, weak?: boolean): Uint8Array;
545
- /** Reusable-output etag; returns bytes written (10 strong / 12 weak). */
546
- etagInto(data: Uint8Array, output: Uint8Array, weak?: boolean): number;
547
- /**
548
- * Format a unix timestamp as an IMF-fixdate HTTP-date.
549
- * @performance HTTP date: ~1.5x slower than the JS baseline (2/2 tasks failed) [check:annotate]
550
- * @deprecated Slower than the native JS baseline (~1.5x) — prefer the JS/Bun baseline. [check:annotate]
551
- * @remarks Date.toUTCString() is native (~1.5-1.7x loss); pooled httpDateInto cuts it to ~1.3x. [check:annotate]
552
- */
553
- httpDate(secs?: number): Uint8Array;
554
- /** Reusable-output http-date; returns bytes written (29). Throws if `output` is too small or the year is out of the fixed-width range. */
555
- httpDateInto(secs: number | undefined, output: Uint8Array): number;
556
- /** Parse an IMF-fixdate HTTP-date back to unix seconds. */
557
- parseHttpDate(input: Uint8Array): bigint | null;
558
- /** Parse an Accept-Encoding header into ordered preferences. */
559
- parseAcceptEncoding(input: Uint8Array): EncodingPrefResult[];
560
- /**
561
- * Base64 encode (standard by default; url-safe/padding configurable).
562
- * @performance Base64 encode: ~1.6x slower than the JS baseline [check:annotate]
563
- * @deprecated Slower than the native JS baseline (~1.6x) — prefer the JS/Bun baseline. [check:annotate]
564
- * @remarks Bun Buffer base64 is SIMD; loses ~1.5x. [check:annotate]
565
- */
566
- base64Encode(input: Uint8Array, urlSafe?: boolean, padding?: boolean): Uint8Array;
567
- /**
568
- * Base64 decode (standard); throws on invalid input.
569
- * @performance Base64 decode: ≈ parity with the JS baseline [check:annotate]
622
+ * Overall deadline (ms) for reading the request body. Default: 30s
623
+ * (`DEFAULT_BODY_TIMEOUT_MS`). Set `0` to disable. Protects against
624
+ * slowloris / trickling bodies.
570
625
  */
571
- base64Decode(input: Uint8Array, urlSafe?: boolean, padding?: boolean): Uint8Array;
572
- /** Reusable-output base64 encode; returns bytes written. */
573
- base64EncodeInto(input: Uint8Array, output: Uint8Array, urlSafe?: boolean, padding?: boolean): number;
574
- /** Reusable-output base64 decode; returns bytes written. Throws on invalid input. */
575
- base64DecodeInto(input: Uint8Array, output: Uint8Array, urlSafe?: boolean, padding?: boolean): number;
576
- base64UrlEncode(input: Uint8Array): Uint8Array;
577
- base64UrlDecode(input: Uint8Array): Uint8Array;
626
+ bodyTimeoutMs?: number;
627
+ /** Fallback handler used for write error paths. Defaults to the write ingress. */
628
+ fallback?: OptimizedIngressHandler;
578
629
  /**
579
- * Lowercase hex encode.
580
- * @performance Hex encode: ~1.4x slower than the JS baseline (1/2 tasks failed) [check:annotate]
581
- * @deprecated Slower than the native JS baseline (~1.4x) — prefer the JS/Bun baseline. [check:annotate]
582
- * @remarks Buffer.toString('hex') is native SIMD; pooled hexEncodeInto cuts the loss from ~2.2x to ~1.35x. [check:annotate]
630
+ * When true, route the JSON-validity fallback check through the higher-order
631
+ * loader (`loader("jsonValid")`) instead of the direct native call —
632
+ * exercising the loader's dispatch + counters on the real request path.
633
+ * Default: false (the direct call is marginally faster for a single request;
634
+ * the loader pays off for same-tick bursts / bulk work, see src/integration/batch.ts).
583
635
  */
584
- hexEncode(input: Uint8Array): Uint8Array;
636
+ enableLoader?: boolean;
637
+ }
638
+ /** A raw web-standard route handler (`Request` → `Response`), e.g. the
639
+ * health/metrics probes (`livenessHandler`, `readinessHandler`,
640
+ * `healthHandler`, `metricsHandler`). Accepted as `BakedRoute.read` and
641
+ * served for GET directly, outside the ingress pipeline. The optional third
642
+ * arg carries the matched dynamic path params (`:param`/`*`) on the Node
643
+ * adapter (Bun's native router handles matching; the ingress pipeline does
644
+ * not echo params in its response). */
645
+ type RouteHandler = (req: Request, srv?: unknown, params?: Record<string, string>) => Response | Promise<Response>;
646
+ /** Route spec for the Bun.serve builder. */
647
+ export interface BakedRoute {
585
648
  /**
586
- * Hex decode; throws on odd length or invalid digits.
587
- * @performance Hex decode: ≈ parity with the JS baseline [check:annotate]
588
- * @remarks Slightly slower than Buffer hex decode (~1.3x). [check:annotate]
649
+ * Wires GET + HEAD read handlers. Accepts an optimized ingress handler OR a
650
+ * raw `RouteHandler` function (health/metrics probes are raw — see
651
+ * src/ingress/health.ts). A raw handler is served for GET only.
589
652
  */
590
- hexDecode(input: Uint8Array): Uint8Array;
591
- /** Reusable-output lowercase-hex encode; returns bytes written. */
592
- hexEncodeInto(input: Uint8Array, output: Uint8Array): number;
593
- /** Reusable-output hex decode; returns bytes written. Throws on bad input. */
594
- hexDecodeInto(input: Uint8Array, output: Uint8Array): number;
595
- /** Reusable-output HMAC-SHA256 hex (64 bytes); returns bytes written. Throws on too-small buffer. */
596
- hmacSha256Into(key: Uint8Array, data: Uint8Array, output: Uint8Array): number;
597
- /** Reusable-output cookie sign (`value.<64-hex>`); returns bytes written. Throws on too-small buffer. */
598
- signCookieInto(value: Uint8Array, secret: Uint8Array, output: Uint8Array): number;
599
- /** Reusable-output AEAD encrypt (ct + 16-byte tag); returns bytes written. Throws on too-small buffer. */
600
- aeadEncryptInto(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, output: Uint8Array, algorithm?: string | null): number;
601
- /** Reusable-output WS frame encode; returns bytes written. Throws on too-small buffer. */
602
- wsFrameEncodeInto(opcode: number, payload: Uint8Array, mask: boolean, fin: boolean, output: Uint8Array): number;
603
- /** Reusable-output gzip compress; returns bytes written. Throws on too-small buffer. */
604
- gzipCompressInto(data: Uint8Array, output: Uint8Array, level?: number | null): number;
605
- /** Reusable-output brotli compress; returns bytes written. Throws on too-small buffer. */
606
- brotliCompressInto(data: Uint8Array, output: Uint8Array, quality?: number | null): number;
653
+ read?: OptimizedIngressHandler | RouteHandler;
654
+ /** Wires POST/PUT/PATCH JSON-write handlers (and OPTIONS fallback). */
655
+ write?: OptimizedIngressHandler;
656
+ /** Wires a POST echo handler. */
657
+ echo?: OptimizedIngressHandler;
658
+ /** Wires a GET read handler (cookies-style route). */
659
+ cookies?: OptimizedIngressHandler;
660
+ /** Wires a DELETE read-style handler. */
661
+ delete?: OptimizedIngressHandler;
607
662
  /**
608
- * Sign a cookie value as `value.signature` (HMAC-SHA256 hex).
609
- * @performance Cookie sign: ~1.0x faster than the JS baseline [check:annotate]
610
- */
611
- signCookie(value: Uint8Array, secret: Uint8Array): Uint8Array;
663
+ * A JS responder route: the native pipeline owns parse/validate/CORS/
664
+ * rate-limit + terminal rejections; the responder builds the 2xx body
665
+ * (async OK). Wired for `methods` (default GET). Built by
666
+ * `nativeResponderRoute` (src/ingress/routes/responder.ts).
667
+ */
668
+ responder?: {
669
+ /** The route's compiled native `IngressInner`. */
670
+ ingress: OptimizedIngressHandler;
671
+ /** The JS 2xx builder. */
672
+ handler: NativeResponder;
673
+ /** HTTP methods to wire (default `['GET']`). */
674
+ methods?: ReadonlyArray<string>;
675
+ /** Terminal envelope style (`'castrum'` default / `'ignex'`). */
676
+ terminalStyle?: TerminalStyle;
677
+ /** Read the body for native validation (default false — framework owns it). */
678
+ readBody?: boolean;
679
+ };
680
+ /** Overrides `maxBodyBytes` for this route's write/echo handlers. */
681
+ maxBodyBytes?: number;
612
682
  /**
613
- * Verify a signed cookie; returns the value or null.
614
- * @performance Cookie verify: ~9.5x faster than the JS baseline [check:annotate]
683
+ * Overall deadline (ms) for reading the request body on this route's
684
+ * write/echo handlers. Default: 30_000 (`DEFAULT_BODY_TIMEOUT_MS`).
685
+ * Set 0 to disable.
615
686
  */
616
- verifyCookie(signed: Uint8Array, secret: Uint8Array): Uint8Array | null;
687
+ bodyTimeoutMs?: number;
688
+ }
689
+ /** RFC 6455 handshake values returned by `CreateIngressServerOptions.upgrade`. */
690
+ export interface NodeUpgradeHandshake {
691
+ /** `Sec-WebSocket-Accept` value (compute via `rust.text.wsAcceptKey`). */
692
+ accept: string;
693
+ /** Optional negotiated subprotocol (`Sec-WebSocket-Protocol`). */
694
+ protocol?: string;
695
+ }
696
+ /** Options for {@link createIngressServer}. */
697
+ export interface CreateIngressServerOptions {
698
+ port: number;
699
+ hostname?: string;
700
+ idleTimeout?: number;
701
+ maxRequestBodySize?: number;
702
+ reusePort?: boolean;
703
+ copyBody?: boolean;
704
+ getIp?: (req: Request, srv: unknown) => string | undefined;
705
+ routes: Record<string, BakedRoute>;
706
+ fallback?: OptimizedIngressHandler;
617
707
  /**
618
- * Create a CSRF token (32-byte random hex + HMAC signature).
619
- * @performance CSRF create: ~13.7x faster than the JS baseline [check:annotate]
708
+ * Invoked when an unhandled error escapes a request handler (currently wired
709
+ * on the Node adapter; the Bun path uses runtime.onResponse). Never throws —
710
+ * hook failures are swallowed.
620
711
  */
621
- csrfToken(secret: Uint8Array): Uint8Array;
712
+ onError?: (info: {
713
+ error: Error;
714
+ request?: Request;
715
+ }) => void;
716
+ /** Node adapter only: ms to receive the complete request (headers + body).
717
+ * Guards slowloris/trickling requests. Default: 30_000. */
718
+ requestTimeoutMs?: number;
719
+ /** Node adapter only: ms to receive the request headers. Default: 30_000. */
720
+ headersTimeoutMs?: number;
721
+ /** Node adapter only: max requests per keep-alive socket before Node forces
722
+ * a fresh connection (bounds long-lived socket reuse). Default: 1000. */
723
+ maxRequestsPerSocket?: number;
724
+ /** Node adapter only: optional WebSocket upgrade handler. Return the RFC 6455
725
+ * handshake values (see {@link NodeUpgradeHandshake}) to complete the
726
+ * handshake on the hijacked socket; return null/undefined to decline the
727
+ * upgrade. Ignored by the Bun server. (`createWebSocketUpgrade` is Bun-only
728
+ * — Node's Response cannot carry a 101.) */
729
+ upgrade?: (req: Request) => NodeUpgradeHandshake | null | undefined;
730
+ /** Node adapter only: called after a WebSocket upgrade handshake completes
731
+ * (the 101 response was accepted), with the hijacked socket so the caller
732
+ * can attach a frame codec/message loop (e.g. the `ws` library). Ignored by
733
+ * the Bun server. */
734
+ onUpgrade?: (socket: import("node:stream").Duplex, req: unknown, head: Buffer) => void;
735
+ }
736
+ /**
737
+ * Minimal surface of the running server that castrum relies on.
738
+ *
739
+ * This is intentionally NOT `ReturnType<typeof Bun.serve>` so that the public
740
+ * types stay runtime-agnostic — Node.js TypeScript consumers don't need
741
+ * `@types/bun` just to import castrum's types. Bun's server exposes far more
742
+ * fields; treat the handle as opaque.
743
+ */
744
+ export interface ServerHandle {
745
+ /** The port the server is bound to, when known (Bun exposes it; Node's
746
+ * http.Server does not — use `BakedServer.port` instead). */
747
+ port?: number;
748
+ /** Force-stop the server. Bun semantics: `true` drops active connections. */
749
+ stop(force?: boolean): void;
750
+ }
751
+ /** A running server instance plus a stop helper. */
752
+ export interface BakedServer {
753
+ server: ServerHandle;
754
+ stop(): void;
755
+ port: number;
756
+ }
757
+ /** Options for `gracefulShutdown` (drain grace period + signals). */
758
+ export interface GracefulShutdownOptions {
759
+ /** Grace period (ms) to drain in-flight requests before force-closing. */
760
+ timeoutMs?: number;
761
+ /** Signals to listen for. Default: SIGTERM + SIGINT. */
762
+ signals?: NodeJS.Signals[];
763
+ }
764
+ /**
765
+ * Wire SIGTERM/SIGINT to a graceful shutdown: soft-stop (drain in-flight
766
+ * requests) then force-close after `timeoutMs`. Works with both the Bun and
767
+ * Node server handles (both expose `stop(force?)`).
768
+ *
769
+ * Returns a cleanup function that removes the signal listeners. Call it (or
770
+ * `process.exit`) to tear down without hanging.
771
+ */
772
+ export declare function gracefulShutdown(handles: ReadonlyArray<ServerHandle>, options?: GracefulShutdownOptions): () => void;
773
+ /** A matched dynamic route: the handler map + the extracted path params. */
774
+ export interface PathMatch {
775
+ methods: Record<string, unknown>;
776
+ params: Record<string, string>;
777
+ }
778
+ /** Options for `createWebSocketUpgrade` (supported subprotocols). */ export interface WebSocketUpgradeOptions {
779
+ /** Subprotocols this server supports; the first client-requested match wins. */
780
+ protocols?: ReadonlyArray<string>;
781
+ }
782
+ /** The WebSocket upgrade handshake result (101 response + negotiation info). */
783
+ export interface WebSocketUpgradeResult {
784
+ /** The 101 Switching Protocols response — return it from your fetch handler. */
785
+ readonly response: Response;
786
+ /** The client's `Sec-WebSocket-Key` (handy for connection logging). */
787
+ readonly key: string;
788
+ /** The negotiated subprotocol, if any. */
789
+ readonly protocol: string | null;
790
+ }
791
+ /**
792
+ * Build a WebSocket 101 upgrade handshake response for a request.
793
+ *
794
+ * Validates `Sec-WebSocket-Key` presence and computes the RFC 6455 accept key
795
+ * via the native `rust.wsAcceptKey`, optionally negotiates a subprotocol, and
796
+ * returns a ready-to-serve `Response`. Returns `null` when the request is not a
797
+ * valid upgrade (missing/empty key).
798
+ *
799
+ * This only produces the handshake — pair it with your framework's own
800
+ * WebSocket server (Bun.serve's `websocket` handler, or a WS library), which
801
+ * owns the subsequent frames:
802
+ *
803
+ * @example
804
+ * ```ts
805
+ * const srv = Bun.serve({
806
+ * port: 3000,
807
+ * fetch(req, server) {
808
+ * const up = createWebSocketUpgrade(req, { protocols: ["chat"] });
809
+ * if (up && server.upgrade(req, { data: { protocol: up.protocol } })) {
810
+ * return up.response;
811
+ * }
812
+ * return new Response("Not a websocket", { status: 400 });
813
+ * },
814
+ * websocket: {
815
+ * message(ws, msg) { ws.send(msg); },
816
+ * },
817
+ * });
818
+ * ```
819
+ */
820
+ export declare function createWebSocketUpgrade(req: Request, opts?: WebSocketUpgradeOptions): WebSocketUpgradeResult | null;
821
+ /** Options accepted by `createRust` / `rust.configure`. */
822
+ export interface RustOptions {
622
823
  /**
623
- * Constant-time verify a CSRF token.
624
- * @performance CSRF verify: ~3.3x faster than the JS baseline [check:annotate]
824
+ * Rayon thread pool size.
825
+ *
826
+ * The rayon pool is process-wide and initialized **once** (native
827
+ * `OnceLock`) — the first initialization wins. Importing this module
828
+ * initializes the pool with defaults, so this option only takes effect when
829
+ * the pool has not yet been created. For reliable control set
830
+ * `CASTRUM_RAYON_THREADS` / `RUST_RAYON_THREADS` before import.
831
+ * Default: max(1, hardwareConcurrency - 1).
625
832
  */
626
- csrfVerify(token: Uint8Array, secret: Uint8Array): boolean;
627
- /**
628
- * Resolve a URL reference against a base (RFC 3986).
629
- * @performance URL resolve: ~1.8x slower than the JS baseline [check:annotate]
630
- * @deprecated Slower than the native JS baseline (~1.8x) — prefer the JS/Bun baseline. [check:annotate]
631
- * @remarks Auto-deprecated: 1/1 benchmarks failed in the latest run (static classification was parity). [check:annotate]
632
- * @remarks Noisy ~1.5µs op; swings 0.74-1.03x run-to-run. UrlBuilder reuses the parsed base. [check:annotate]
833
+ rayonThreads?: number;
834
+ /** Cache MIME lookups keyed by normalized extension. Default: true. */
835
+ mimeCache?: boolean;
836
+ /** Reuse HMAC signers keyed by key-buffer identity. Default: true. */
837
+ hmacCache?: boolean;
838
+ }
839
+ /**
840
+ * The `rust.batch.*` array-of-bytes batch surface: N items in → one packed
841
+ * native call → bitsets / typed arrays / byte arrays out. Separated from the
842
+ * implementation (`./build.ts`) so type-only consumers don't pull the native
843
+ * resolver.
844
+ */
845
+ export interface RustBatch {
846
+ jsonValid(items: Uint8Array[]): Uint8Array;
847
+ crc32(items: Uint8Array[]): Uint32Array;
848
+ validateEmail(items: Uint8Array[]): Uint8Array;
849
+ validateUuid(items: Uint8Array[]): Uint8Array;
850
+ validateIpv4(items: Uint8Array[]): Uint8Array;
851
+ validateIpv6(items: Uint8Array[]): Uint8Array;
852
+ jsonSumIds(items: Uint8Array[]): BigInt64Array;
853
+ queryParse(items: Uint8Array[]): Uint8Array[];
854
+ cookieParse(items: Uint8Array[]): Uint8Array[];
855
+ httpParseRequest(items: Uint8Array[]): Uint8Array[];
856
+ jsonPatch(docs: Uint8Array[], patches: Uint8Array[]): Uint8Array[];
857
+ hexEncode(items: Uint8Array[]): Uint8Array[];
858
+ hexDecode(items: Uint8Array[]): Uint8Array[];
859
+ base64Encode(items: Uint8Array[], urlSafe?: boolean, padding?: boolean): Uint8Array[];
860
+ base64Decode(items: Uint8Array[], urlSafe?: boolean, padding?: boolean): Uint8Array[];
861
+ formParse(items: Uint8Array[]): Uint8Array[];
862
+ signCookie(items: Uint8Array[], secret: Uint8Array): Uint8Array[];
863
+ verifyCookie(items: Uint8Array[], secret: Uint8Array): Uint8Array;
864
+ csrfVerify(items: Uint8Array[], secret: Uint8Array): Uint8Array;
865
+ schemaValidate(validator: SchemaValidator, items: Uint8Array[]): Uint8Array;
866
+ schemaValidateCount(validator: SchemaValidator, items: Uint8Array[]): number;
867
+ fnv1a64(items: Uint8Array[]): BigUint64Array;
868
+ etag(items: Uint8Array[], weak?: boolean | null): Uint8Array[];
869
+ urlEncode(items: Uint8Array[]): Uint8Array[];
870
+ urlDecode(items: Uint8Array[]): Uint8Array[];
871
+ urlDecodeBytes(items: Uint8Array[]): Uint8Array[];
872
+ mimeFromExtension(items: Uint8Array[]): Uint8Array[];
873
+ wsAcceptKey(items: Uint8Array[]): Uint8Array[];
874
+ base64UrlEncode(items: Uint8Array[]): Uint8Array[];
875
+ base64UrlDecode(items: Uint8Array[]): Uint8Array[];
876
+ passwordHash(passwords: Uint8Array[], salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array[];
877
+ aeadEncrypt(key: Uint8Array, nonce: Uint8Array, items: Uint8Array[], algorithm?: string | null): Uint8Array[];
878
+ aeadDecrypt(key: Uint8Array, nonce: Uint8Array, items: Uint8Array[], algorithm?: string | null): Uint8Array[];
879
+ gzipCompress(items: Uint8Array[], level?: number | null): Uint8Array[];
880
+ gzipDecompress(items: Uint8Array[], maxDecompressed?: number | null): Uint8Array[];
881
+ brotliCompress(items: Uint8Array[], quality?: number | null): Uint8Array[];
882
+ brotliDecompress(items: Uint8Array[], maxDecompressed?: number | null): Uint8Array[];
883
+ jwtVerify(tokens: Uint8Array[], secret: Uint8Array, nowSeconds: number): Uint8Array;
884
+ hmacSha256(items: Uint8Array[], key: Uint8Array): Uint8Array[];
885
+ hmacSha256Verify(items: Uint8Array[], sigs: Uint8Array[], key: Uint8Array): Uint8Array;
886
+ passwordVerify(items: Uint8Array[], phcs: Uint8Array[]): Uint8Array;
887
+ urlResolve(bases: Uint8Array[], references: Uint8Array[]): Uint8Array[];
888
+ jwtSign(items: Uint8Array[], secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array[];
889
+ sseEncode(items: Uint8Array[], event?: string | null, id?: string | null, retry?: number | null): Uint8Array[];
890
+ wsFrameEncode(items: Uint8Array[], opcode: number, mask: boolean, fin: boolean): Uint8Array[];
891
+ wsFrameDecode(items: Uint8Array[]): Uint8Array[];
892
+ multipartParse(items: Uint8Array[], boundary: Uint8Array): MultipartPart[][];
893
+ templateRender(source: string, contexts: Uint8Array[]): Uint8Array[];
894
+ }
895
+ /** Raw packed-wire FFI namespace. */
896
+ export interface RustPacked {
897
+ crc32BatchPacked(input: Uint8Array): Uint8Array;
898
+ jsonValidBatchPacked(input: Uint8Array): Uint8Array;
899
+ validateEmailBatchPacked(input: Uint8Array): Uint8Array;
900
+ validateUuidBatchPacked(input: Uint8Array): Uint8Array;
901
+ validateIpv4BatchPacked(input: Uint8Array): Uint8Array;
902
+ validateIpv6BatchPacked(input: Uint8Array): Uint8Array;
903
+ jsonSumBatchPacked(input: Uint8Array): Uint8Array;
904
+ queryParseBatchPacked(input: Uint8Array): Uint8Array;
905
+ cookieParseBatchPacked(input: Uint8Array): Uint8Array;
906
+ httpParseRequestBatchPacked(input: Uint8Array): Uint8Array;
907
+ /** Batch RFC 6902 JSON Patch (two packed lists, zipped) → packed results. */
908
+ jsonPatchBatchPacked(docs: Uint8Array, patches: Uint8Array): Uint8Array;
909
+ /** Packed FNV-1a 64 batch (i64 per item). */
910
+ fnv1A64BatchPacked(input: Uint8Array): Uint8Array;
911
+ /** Packed ETag batch (10 strong / 12 weak bytes per item). */
912
+ etagBatchPacked(input: Uint8Array, weak?: boolean | null): Uint8Array;
913
+ urlEncodeBatchPacked(input: Uint8Array): Uint8Array;
914
+ urlDecodeBatchPacked(input: Uint8Array): Uint8Array;
915
+ urlDecodeBytesBatchPacked(input: Uint8Array): Uint8Array;
916
+ mimeFromExtensionBatchPacked(input: Uint8Array): Uint8Array;
917
+ wsAcceptKeyBatchPacked(input: Uint8Array): Uint8Array;
918
+ jsonValidBatchCountPacked(input: Uint8Array): number;
919
+ validateEmailBatchCountPacked(input: Uint8Array): number;
920
+ validateUuidBatchCountPacked(input: Uint8Array): number;
921
+ validateIpv4BatchCountPacked(input: Uint8Array): number;
922
+ validateIpv6BatchCountPacked(input: Uint8Array): number;
923
+ jsonSumBatchTotalPacked(input: Uint8Array): number;
924
+ queryParseBatchTotalLenPacked(input: Uint8Array): number;
925
+ cookieParseBatchTotalLenPacked(input: Uint8Array): number;
926
+ httpParseRequestBatchTotalLenPacked(input: Uint8Array): number;
927
+ passwordHashBatchPacked(input: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array;
928
+ /** Packed password-verify batch (two packed lists, zipped) → bitset. */
929
+ passwordVerifyBatchPacked(passwords: Uint8Array, phcs: Uint8Array): Uint8Array;
930
+ /** Packed URL-resolve batch (two packed lists, zipped) → packed results. */
931
+ urlResolveBatchPacked(bases: Uint8Array, references: Uint8Array): Uint8Array;
932
+ aeadEncryptBatchPacked(input: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null): Uint8Array;
933
+ aeadDecryptBatchPacked(input: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null): Uint8Array;
934
+ gzipCompressBatchPacked(input: Uint8Array, level?: number | null): Uint8Array;
935
+ gzipDecompressBatchPacked(input: Uint8Array): Uint8Array;
936
+ brotliCompressBatchPacked(input: Uint8Array, quality?: number | null): Uint8Array;
937
+ brotliDecompressBatchPacked(input: Uint8Array): Uint8Array;
938
+ jwtSignBatchPacked(input: Uint8Array, secret: Uint8Array, ttlSeconds: number | null, nowSeconds: number): Uint8Array;
939
+ jwtVerifyBatchPacked(input: Uint8Array, secret: Uint8Array, nowSeconds: number): Uint8Array;
940
+ /** Batch HMAC-SHA256 sign (packed in → hex-signature byte results). */
941
+ hmacSha256BatchPacked(input: Uint8Array, key: Uint8Array): Uint8Array;
942
+ /** Batch HMAC-SHA256 verify (two packed lists: data + hex sigs, zipped) → bitset. */
943
+ hmacSha256VerifyBatchPacked(input: Uint8Array, sigs: Uint8Array, key: Uint8Array): Uint8Array;
944
+ multipartParseBatchPacked(input: Uint8Array, boundary: Uint8Array): Uint8Array;
945
+ templateRenderBatchPacked(input: Uint8Array, source: string): Uint8Array;
946
+ sseEncodeBatchPacked(input: Uint8Array, event: string | null, id: string | null, retry: number | null): Uint8Array;
947
+ wsFrameEncodeBatchPacked(input: Uint8Array, opcode: number, mask: boolean, fin: boolean): Uint8Array;
948
+ wsFrameDecodeBatchPacked(input: Uint8Array): Uint8Array;
949
+ }
950
+ /**
951
+ * The flat `rust.*` scalar method surface: bytes in → normalized out. Built by
952
+ * the scalar builders from the native addon + Bun built-in delegations.
953
+ */
954
+ export interface RustScalar {
955
+ crc32(input: Uint8Array): number;
956
+ fnv1a64(input: Uint8Array): bigint;
957
+ /**
958
+ * XXH3-64 over raw bytes (high-throughput non-cryptographic hash).
959
+ * Compare against `Bun.hash.xxHash3` — see docs/bun-builtins-decision-matrix.md.
633
960
  */
634
- urlResolve(base: Uint8Array, reference: Uint8Array): Uint8Array;
961
+ xxh3(input: Uint8Array): bigint;
962
+ hmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array | string;
963
+ hmacSha256Verify(key: Uint8Array, data: Uint8Array, sig: Uint8Array | string): boolean;
964
+ jsonValid(input: Uint8Array): boolean;
635
965
  /**
636
- * Build a percent-encoded query string from params (sorted keys).
637
- * @performance URL query build: ~1.4x slower than the JS baseline [check:annotate]
638
- * @deprecated Slower than the native JS baseline (~1.4x) — prefer the JS/Bun baseline. [check:annotate]
639
- * @remarks encodeURIComponent baseline wins (~1.2-1.35x). [check:annotate]
966
+ * Parse JSON to a JS value (FFI packed structural parse on Bun — sonic-rs
967
+ * parses ONCE, JS assembles from a token stream with no re-parse; napi
968
+ * sonic-rs DOM fallback). Throws on invalid JSON.
969
+ */
970
+ jsonParse(input: Uint8Array): unknown;
971
+ jsonSumIds(input: Uint8Array): bigint;
972
+ jsonPatch(doc: Uint8Array, patch: Uint8Array): Uint8Array | string;
973
+ mimeFromExtension(ext: Uint8Array): Uint8Array | string;
974
+ randomToken(byteLen: number): Uint8Array | string;
975
+ randomTokenInto(byteLen: number, output: Uint8Array): number;
976
+ urlEncode(input: Uint8Array): Uint8Array | string;
977
+ urlDecode(input: Uint8Array): Uint8Array;
978
+ /**
979
+ * Strict percent-decode without UTF-8 validation.
980
+ */
981
+ urlDecodeBytes(input: Uint8Array): Uint8Array;
982
+ urlEncodeInto(input: Uint8Array, output: Uint8Array): number;
983
+ urlDecodeInto(input: Uint8Array, output: Uint8Array): number;
984
+ validateEmail(input: Uint8Array): boolean;
985
+ validateUuid(input: Uint8Array): boolean;
986
+ validateIpv4(input: Uint8Array): boolean;
987
+ validateIpv6(input: Uint8Array): boolean;
988
+ wsAcceptKey(key: Uint8Array): Uint8Array | string;
989
+ wsAcceptKeyInto(key: Uint8Array, output: Uint8Array): number;
990
+ httpParseRequestPacked(input: Uint8Array): Uint8Array;
991
+ queryParsePacked(input: Uint8Array): Uint8Array;
992
+ cookieParsePacked(input: Uint8Array): Uint8Array;
993
+ httpParseRequestPackedInto(input: Uint8Array, output: Uint8Array): number;
994
+ queryParsePackedInto(input: Uint8Array, output: Uint8Array): number;
995
+ cookieParsePackedInto(input: Uint8Array, output: Uint8Array): number;
996
+ /**
997
+ * Parse an application/x-www-form-urlencoded body into packed pairs.
998
+ */
999
+ formParsePacked(input: Uint8Array): Uint8Array;
1000
+ formParsePackedInto(input: Uint8Array, output: Uint8Array): number;
1001
+ /**
1002
+ * Parse a Content-Type header into a structured media type.
1003
+ */
1004
+ parseMediaType(input: Uint8Array): MediaTypeResult;
1005
+ /**
1006
+ * Generate a strong/weak ETag (crc32-based).
1007
+ */
1008
+ etag(data: Uint8Array, weak?: boolean): Uint8Array | string;
1009
+ etagInto(data: Uint8Array, output: Uint8Array, weak?: boolean): number;
1010
+ /**
1011
+ * Format a unix timestamp as an IMF-fixdate HTTP-date.
1012
+ */
1013
+ httpDate(secs?: number): Uint8Array | string;
1014
+ httpDateInto(secs: number | undefined, output: Uint8Array): number;
1015
+ parseHttpDate(input: Uint8Array): bigint | null;
1016
+ parseAcceptEncoding(input: Uint8Array): EncodingPrefResult[];
1017
+ /**
1018
+ * Base64 encode (standard by default; url-safe/padding configurable).
1019
+ */
1020
+ base64Encode(input: Uint8Array, urlSafe?: boolean, padding?: boolean): Uint8Array | string;
1021
+ /**
1022
+ * Base64 decode (standard); throws on invalid input.
1023
+ */
1024
+ base64Decode(input: Uint8Array, urlSafe?: boolean, padding?: boolean): Uint8Array;
1025
+ base64EncodeInto(input: Uint8Array, output: Uint8Array, urlSafe?: boolean, padding?: boolean): number;
1026
+ base64DecodeInto(input: Uint8Array, output: Uint8Array, urlSafe?: boolean, padding?: boolean): number;
1027
+ base64UrlEncode(input: Uint8Array): Uint8Array | string;
1028
+ base64UrlDecode(input: Uint8Array): Uint8Array;
1029
+ /**
1030
+ * Lowercase hex encode.
1031
+ */
1032
+ hexEncode(input: Uint8Array): Uint8Array | string;
1033
+ /**
1034
+ * Hex decode; throws on odd length or invalid digits.
1035
+ */
1036
+ hexDecode(input: Uint8Array): Uint8Array;
1037
+ hexEncodeInto(input: Uint8Array, output: Uint8Array): number;
1038
+ hexDecodeInto(input: Uint8Array, output: Uint8Array): number;
1039
+ hmacSha256Into(key: Uint8Array, data: Uint8Array, output: Uint8Array): number;
1040
+ signCookieInto(value: Uint8Array, secret: Uint8Array, output: Uint8Array): number;
1041
+ verifyCookieInto(signed: Uint8Array, secret: Uint8Array, output: Uint8Array): number | null;
1042
+ csrfTokenInto(secret: Uint8Array, output: Uint8Array): number;
1043
+ aeadEncryptInto(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, output: Uint8Array, algorithm?: string | null): number;
1044
+ wsFrameEncodeInto(opcode: number, payload: Uint8Array, mask: boolean, fin: boolean, output: Uint8Array): number;
1045
+ gzipCompressInto(data: Uint8Array, output: Uint8Array, level?: number | null): number;
1046
+ brotliCompressInto(data: Uint8Array, output: Uint8Array, quality?: number | null): number;
1047
+ /**
1048
+ * Sign a cookie value as `value.signature` (HMAC-SHA256 hex).
1049
+ */
1050
+ signCookie(value: Uint8Array, secret: Uint8Array): Uint8Array | string;
1051
+ /**
1052
+ * Verify a signed cookie; returns the value or null.
1053
+ */
1054
+ verifyCookie(signed: Uint8Array, secret: Uint8Array): Uint8Array | string | null;
1055
+ /**
1056
+ * Create a CSRF token (32-byte random hex + HMAC signature).
1057
+ */
1058
+ csrfToken(secret: Uint8Array): Uint8Array | string;
1059
+ /**
1060
+ * Constant-time verify a CSRF token.
1061
+ */
1062
+ csrfVerify(token: Uint8Array, secret: Uint8Array): boolean;
1063
+ /**
1064
+ * Resolve a URL reference against a base (RFC 3986).
640
1065
  */
641
- urlEncodeQuery(params: Record<string, string>): Uint8Array;
1066
+ urlResolve(base: Uint8Array, reference: Uint8Array): Uint8Array | string;
642
1067
  /**
643
- * @performance JSON schema validate: ~1.7x faster than the JS baseline (2/2 tasks won) [check:annotate]
644
- * @remarks Zero-DOM fast path validates raw bytes for the common keyword subset (scalar ~1.2-2.4x, batch ~1.0-1.56x vs ajv); unsupported keywords fall back to the jsonschema crate. [check:annotate]
1068
+ * Build a percent-encoded query string from params (sorted keys).
645
1069
  */
1070
+ urlEncodeQuery(params: Record<string, string>): Uint8Array | string;
646
1071
  createSchemaValidator(schema: Uint8Array): SchemaValidatorInstance;
647
1072
  createHmacSigner(key: Uint8Array): HmacSignerInstance;
648
1073
  createTemplateRenderer(source: string): TemplateRendererInstance;
649
- /** Higher-order form parser: owns a reusable output buffer (setup once). */
650
1074
  createFormParser(capacity?: number): FormParserInstance;
651
- /** Higher-order media-type parser: reusable wildcard matcher. */
652
1075
  createMediaTypeParser(): MediaTypeParserInstance;
653
1076
  /**
654
1077
  * Higher-order conditional-request check: per-resource 304 decision (setup once).
655
- * @performance Conditional request: ~1.7x faster than the JS baseline [check:annotate]
656
1078
  */
657
1079
  createConditionalRequest(etagValue: Uint8Array, lastModifiedSecs?: number): ConditionalRequestInstance;
658
1080
  /**
659
1081
  * Higher-order negotiator: precompiles supported encodings once.
660
- * @performance Accept-Encoding negotiate: ~4.2x faster than the JS baseline [check:annotate]
661
1082
  */
662
1083
  createAcceptNegotiator(supported: string[]): AcceptNegotiatorInstance;
663
- /** Higher-order codec: base64 config compiled once. */
664
1084
  createBase64Codec(urlSafe?: boolean, padding?: boolean): Base64CodecInstance;
665
- /** Higher-order cookie signer: HMAC key compiled once. */
666
1085
  createCookieSigner(secret: Uint8Array): CookieSignerInstance;
667
- /** Higher-order CSRF protector: HMAC key compiled once. */
668
1086
  createCsrfProtector(secret: Uint8Array): CsrfProtectorInstance;
669
- /** Higher-order URL builder: base parsed once, reused. */
670
1087
  createUrlBuilder(base: Uint8Array): UrlBuilderInstance;
671
- /** Higher-order JWT signer: HS256 key + ttl compiled once. */
672
1088
  createJwtSigner(secret: Uint8Array, ttlSeconds?: number): JwtSignerInstance;
673
- /** Higher-order AEAD cipher: algorithm + key compiled once. */
674
1089
  createAeadCipher(key: Uint8Array, algorithm?: string): AeadCipherInstance;
675
- /** Higher-order argon2id hasher: params compiled once. */
676
1090
  createArgon2Hasher(options?: PasswordHashOptions | null): Argon2HasherInstance;
677
- /** Higher-order media-type matcher: expected precompiled once. */
678
1091
  createMediaTypeMatcher(expected: Uint8Array): MediaTypeMatcherInstance;
679
1092
  /**
680
1093
  * Sharded fixed-window per-key rate limiter. `maxEntries` clamps internally
@@ -686,1106 +1099,364 @@ export interface RustScalar {
686
1099
  createRateLimiter(limit: number, windowMs: number, maxEntries?: number | null): RateLimiterInstance;
687
1100
  initThreadPool(rayonThreads?: number): void;
688
1101
  rayonNumThreads(): number;
689
- /**
690
- * @performance JWT sign: ~1.1x slower than the JS baseline [check:annotate]
691
- * @deprecated Slower than the native JS baseline (~1.1x) — prefer the JS/Bun baseline. [check:annotate]
692
- * @remarks Base64 + claims DOM marshal overhead. Use jwtSignBytes (claims as JSON bytes) which skips the napi Value marshal and flips to a ~1.07x win. [check:annotate]
693
- */
694
1102
  jwtSign(claims: Record<string, unknown>, secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array;
695
1103
  /**
696
1104
  * Sign a JWT from pre-serialized claim JSON bytes — skips the napi
697
1105
  * `serde_json::Value` marshal of `jwtSign` for callers that already hold the
698
1106
  * bytes (same injection semantics).
699
- * @performance JWT sign (bytes): ≈ parity with the JS baseline [check:annotate]
700
- * @remarks Byte-JSON claims overload avoids the napi serde_json::Value DOM marshal; flips jwtSign from a ~1.3x loss to ~1.07x (parity). [check:annotate]
701
- */
702
- jwtSignBytes(claimsJson: Uint8Array, secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array;
703
- /**
704
- * @performance JWT verify: ~1.7x faster than the JS baseline (2/2 tasks won) [check:annotate]
705
1107
  */
1108
+ jwtSignBytes(claimsJson: Uint8Array, secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array | string;
1109
+ jwtSignBytesInto(claimsJson: Uint8Array, secret: Uint8Array, output: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): number;
706
1110
  jwtVerify(token: Uint8Array, secret: Uint8Array, nowSeconds?: number): unknown;
1111
+ passwordHash(password: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array | string;
1112
+ passwordVerify(password: Uint8Array, phc: Uint8Array): boolean;
707
1113
  /**
708
- * @performance Password hash: ~18.2x faster than the JS baseline (2/2 tasks won) [check:annotate]
709
- * @remarks argon2id vs node:crypto scrypt. [check:annotate]
1114
+ * bcrypt password hash → `$2b$` PHC string (cost clamped 4..=31).
710
1115
  */
711
- passwordHash(password: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array;
712
- passwordVerify(password: Uint8Array, phc: Uint8Array): boolean;
713
- /** bcrypt password hash → `$2b$` PHC string (cost clamped 4..=31). */
714
1116
  passwordHashBcrypt(password: Uint8Array, cost: number): string;
715
- /** Verify a password against a bcrypt `$2b$` PHC string. */
716
- passwordVerifyBcrypt(password: Uint8Array, hash: string): boolean;
717
- /** PBKDF2-HMAC-SHA256 key derivation (dkLen clamped to 1 MiB). */
718
- pbkdf2Sha256(password: Uint8Array, salt: Uint8Array, rounds: number, dkLen: number): Uint8Array;
719
1117
  /**
720
- * @performance AEAD encrypt: ~1.3x faster than the JS baseline [check:annotate]
1118
+ * Verify a password against a bcrypt `$2b$` PHC string.
721
1119
  */
722
- aeadEncrypt(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, algorithm?: string | null): Uint8Array;
1120
+ passwordVerifyBcrypt(password: Uint8Array, hash: string): boolean;
723
1121
  /**
724
- * @performance AEAD decrypt: ~1.4x faster than the JS baseline [check:annotate]
1122
+ * PBKDF2-HMAC-SHA256 key derivation (dkLen clamped to 1 MiB).
725
1123
  */
1124
+ pbkdf2Sha256(password: Uint8Array, salt: Uint8Array, rounds: number, dkLen: number): Uint8Array;
1125
+ aeadEncrypt(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, algorithm?: string | null): Uint8Array;
726
1126
  aeadDecrypt(key: Uint8Array, nonce: Uint8Array, ciphertext: Uint8Array, algorithm?: string | null): Uint8Array | null;
727
- /**
728
- * @performance Gzip compress: ≈ parity with the JS baseline (1/2 tasks won) [check:annotate]
729
- */
730
1127
  gzipCompress(data: Uint8Array, level?: number | null): Uint8Array;
731
1128
  /**
732
- * @performance Gzip decompress: ~1.0x faster than the JS baseline [check:annotate]
733
- * @remarks zlib-rs vs node zlib; swings 1.0-1.4x run-to-run. [check:annotate]
734
1129
  * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
735
1130
  * decompression-bomb guard; a larger value errors.
736
1131
  */
737
1132
  gzipDecompress(data: Uint8Array, maxDecompressed?: number | null): Uint8Array;
738
1133
  /**
739
- * @performance Brotli compress: ~1.7x slower than the JS baseline [check:annotate]
740
- * @deprecated Slower than the native JS baseline (~1.7x) — prefer the JS/Bun baseline. [check:annotate]
741
- * @remarks The native brotli baseline wins for small inputs. [check:annotate]
1134
+ * gzip-decompress into `output` (pooled — caller-owned buffer); returns bytes
1135
+ * written. Throws when `output` is too small (the exact required size is
1136
+ * reported) or the input is invalid / exceeds `maxDecompressed`.
1137
+ * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
1138
+ * decompression-bomb guard; a larger value errors.
742
1139
  */
1140
+ gzipDecompressInto(data: Uint8Array, output: Uint8Array, maxDecompressed?: number | null): number;
743
1141
  brotliCompress(data: Uint8Array, quality?: number | null): Uint8Array;
744
1142
  /**
745
- * @performance Brotli decompress: ~1.4x slower than the JS baseline [check:annotate]
746
- * @deprecated Slower than the native JS baseline (~1.4x) — prefer the JS/Bun baseline. [check:annotate]
747
- * @remarks Auto-deprecated: 1/1 benchmarks failed in the latest run (static classification was proven). [check:annotate]
748
1143
  * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
749
1144
  * decompression-bomb guard; a larger value errors.
750
1145
  */
751
1146
  brotliDecompress(data: Uint8Array, maxDecompressed?: number | null): Uint8Array;
752
1147
  /**
753
- * @performance Multipart parse: ~1.9x faster than the JS baseline [check:annotate]
1148
+ * brotli-decompress into `output` (pooled — caller-owned buffer); returns
1149
+ * bytes written. Throws when `output` is too small (the exact required size
1150
+ * is reported) or the input is invalid / exceeds `maxDecompressed`.
1151
+ * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
1152
+ * decompression-bomb guard; a larger value errors.
754
1153
  */
1154
+ brotliDecompressInto(data: Uint8Array, output: Uint8Array, maxDecompressed?: number | null): number;
755
1155
  multipartParse(body: Uint8Array, boundary: Uint8Array): MultipartPart[];
756
- /** Zero-copy packed sibling of `multipartParse` (packed parts layout). */
757
1156
  multipartParsePacked(body: Uint8Array, boundary: Uint8Array): Uint8Array;
758
- /**
759
- * @performance WS frame encode: ~2.0x faster than the JS baseline [check:annotate]
760
- */
1157
+ multipartParsePackedInto(body: Uint8Array, boundary: Uint8Array, output: Uint8Array): number;
761
1158
  wsFrameEncode(opcode: number, payload: Uint8Array, mask: boolean, fin: boolean): Uint8Array;
762
- /**
763
- * @performance WS frame decode: ~2.3x faster than the JS baseline [check:annotate]
764
- */
765
1159
  wsFrameDecode(data: Uint8Array): WsFrame | null;
766
- /**
767
- * @performance SSE encode: ≈ parity with the JS baseline [check:annotate]
768
- */
1160
+ wsFrameDecodePackedInto(data: Uint8Array, output: Uint8Array): number | null;
769
1161
  sseEncodeEvent(event: string | null, data: Uint8Array, id: string | null, retry: number | null): Uint8Array;
1162
+ sseEncodeEventInto(event: string | null, data: Uint8Array, id: string | null, retry: number | null, output: Uint8Array): number;
770
1163
  }
771
- /** The full Rust FFI client (scalar methods + namespaces + configuration). */
772
- export interface RustClient extends RustScalar {
773
- text: RustText;
774
- batch: RustBatch;
775
- packed: RustPacked;
1164
+ /** String-oriented FFI namespace. */
1165
+ export interface RustText {
776
1166
  /**
777
- * Resolve the native transport in use on this runtime: `"ffi"` (bun:ffi —
778
- * the PRIMARY transport under Bun) or `"napi"` (Node, forced
779
- * `CASTRUM_FFI_MODE=napi`, or a failed ffi bind-time self-test).
1167
+ * Resolve a lowercase file extension to a MIME type string (e.g. `"html"` →
1168
+ * `"text/html"`). Unknown extensions return `"application/octet-stream"`.
1169
+ * @param ext the file extension WITHOUT a leading dot, case-insensitive.
1170
+ * @returns the MIME type for `ext`.
780
1171
  */
781
- transport(): "ffi" | "napi";
782
- /** Whether the bun:ffi transport is live (equivalent to `transport() === "ffi"`). */
783
- ffiActive(): boolean;
1172
+ mimeFromExtension(ext: string): string;
784
1173
  /**
785
- * Update defaults on this instance. `mimeCache` / `hmacCache` apply
786
- * immediately (per-instance). `rayonThreads` is applied only if the
787
- * process-wide pool is not yet initialized (see {@link RustOptions}).
1174
+ * RFC 3986 percent-encode a string (the `encodeURIComponent` unreserved
1175
+ * set). Under Bun this delegates to the native `encodeURIComponent` for
1176
+ * ~4x speed with byte-for-byte parity.
1177
+ * @param input the string to encode.
1178
+ * @returns the percent-encoded string.
788
1179
  */
789
- configure(options: RustOptions): void;
790
- }
791
- /**
792
- * Create an isolated Rust client with the given defaults.
793
- *
794
- * `mimeCache` / `hmacCache` are per-instance. `rayonThreads` only applies
795
- * before the process-wide rayon pool is initialized (once per process — see
796
- * {@link RustOptions.rayonThreads}); the pool defaults to the env var or
797
- * `max(1, hardwareConcurrency - 1)` otherwise.
798
- */
799
- export declare function createRust(options?: RustOptions): RustClient;
800
- /**
801
- * The default, ready-to-use `RustClient` created with no options (resolves
802
- * rayon threads from the host automatically). Most consumers just do
803
- * `import { rust } from "castrum"` and call `rust.<fn>(...)` directly.
804
- */
805
- export declare const rust: RustClient;
806
- /** Recommended implementation for an operation. */
807
- export type OpImpl = "native" | "js";
808
- export interface OpDecision {
809
- /** The recommended implementation when the addon is available. */
810
- readonly impl: OpImpl;
811
- /** Why this decision (measured ratio / rationale). */
812
- readonly note?: string;
813
- }
814
- /**
815
- * The benchmark-driven native-vs-JS decision for `op` — runtime-aware.
816
- *
817
- * Returns `"native"` when the Rust addon is the recommended implementation,
818
- * `"js"` when a pure-JS (or Bun built-in) implementation wins, or `null` for
819
- * unknown ops (or when the addon is unavailable — with no addon there is no
820
- * "native" choice). Under Bun, ops in {@link BUN_WINS} resolve to `"js"` so the
821
- * consumer's JS path delegates to the faster Bun built-in.
822
- */
823
- export declare const opImpl: (op: string) => OpImpl | null;
824
- /** `true` when the Rust addon is the recommended impl for `op`. */
825
- export declare const isNativeOp: (op: string) => boolean;
826
- /** The decision record for `op`, or `null` when unknown. */
827
- export declare const opDecision: (op: string) => OpDecision | null;
828
- export type PerformanceStatus = "proven" | "parity" | "not-competitive" | "unmeasured";
829
- export interface ProvenEntry {
830
- /** Public `rust.<name>` method key. */
831
- name: string;
832
- /** Benchmark comparison label (see src/bench/comparisons.ts). */
833
- label: string;
834
- /** Baseline task name in the CPU report. */
835
- nativeTask: string;
836
- /** Rust task name in the CPU report. */
837
- rustTask: string;
838
- status: PerformanceStatus;
839
- /** Typical rust-vs-baseline ratio from release/perf builds (rust faster = >1). */
840
- typicalRatio?: number;
841
- /** Why this classification. */
842
- note?: string;
843
- }
844
- /**
845
- * Curated registry. Classifications are based on release/perf-build results
846
- * (docs + prior runs); the audit script re-checks them against the latest
847
- * report. Borderline wins are kept as "parity" so the `proven` surface stays
848
- * honest.
849
- *
850
- * `as const satisfies` keeps the literal `name`/`status` types so the
851
- * `ProvenKey` type (below) can be derived at the type level.
852
- */
853
- export declare const PROVEN_SURFACE: readonly [
854
- {
855
- readonly name: "fnv1a64";
856
- readonly label: "FNV-1a 64";
857
- readonly nativeTask: "native:fnv1a64";
858
- readonly rustTask: "rust:fnv1a64";
859
- readonly status: "proven";
860
- readonly typicalRatio: 11;
861
- },
862
- {
863
- readonly name: "jsonValid";
864
- readonly label: "JSON valid";
865
- readonly nativeTask: "native:json_valid";
866
- readonly rustTask: "rust:json_valid";
867
- readonly status: "proven";
868
- readonly typicalRatio: 3;
869
- },
870
- {
871
- readonly name: "jsonSumIds";
872
- readonly label: "JSON sum";
873
- readonly nativeTask: "native:json_sum";
874
- readonly rustTask: "rust:json_sum";
875
- readonly status: "proven";
876
- readonly typicalRatio: 3;
877
- },
878
- {
879
- readonly name: "httpParseRequestPacked";
880
- readonly label: "HTTP parse";
881
- readonly nativeTask: "native:http_parse";
882
- readonly rustTask: "rust:http_parse";
883
- readonly status: "proven";
884
- readonly typicalRatio: 4;
885
- },
886
- {
887
- readonly name: "queryParsePacked";
888
- readonly label: "Query parse";
889
- readonly nativeTask: "native:query_parse";
890
- readonly rustTask: "rust:query_parse";
891
- readonly status: "proven";
892
- readonly typicalRatio: 4;
893
- },
894
- {
895
- readonly name: "cookieParsePacked";
896
- readonly label: "Cookie parse";
897
- readonly nativeTask: "native:cookie_parse";
898
- readonly rustTask: "rust:cookie_parse";
899
- readonly status: "proven";
900
- readonly typicalRatio: 2.5;
901
- },
902
- {
903
- readonly name: "wsAcceptKey";
904
- readonly label: "WebSocket accept";
905
- readonly nativeTask: "native:ws_accept_key";
906
- readonly rustTask: "rust:ws_accept_key";
907
- readonly status: "proven";
908
- readonly typicalRatio: 1.6;
909
- },
910
- {
911
- readonly name: "jsonPatch";
912
- readonly label: "JSON Patch";
913
- readonly nativeTask: "native:json_patch";
914
- readonly rustTask: "rust:json_patch";
915
- readonly status: "proven";
916
- readonly typicalRatio: 1.2;
917
- readonly note: "Modest but real win; swings ~0.9-1.5x run-to-run (DOM marshal dominated).";
918
- },
919
- {
920
- readonly name: "hmacSha256";
921
- readonly label: "HMAC sign";
922
- readonly nativeTask: "native:hmac_sha256";
923
- readonly rustTask: "rust:hmac_sha256";
924
- readonly status: "proven";
925
- readonly typicalRatio: 1.5;
926
- readonly note: "Classification vs the node:crypto baseline. Under Bun the public rust.hmacSha256 delegates to Bun.CryptoHasher (BUN_WINS \u2014 hex re-encoded to the same contract); this row measures the raw addon (see src/bench/raw-native.ts).";
927
- },
928
- {
929
- readonly name: "hmacSha256Verify";
930
- readonly label: "HMAC verify";
931
- readonly nativeTask: "native:hmac_verify";
932
- readonly rustTask: "rust:hmac_verify";
933
- readonly status: "proven";
934
- readonly typicalRatio: 2.4;
935
- },
936
- {
937
- readonly name: "validateEmail";
938
- readonly label: "Email validation";
939
- readonly nativeTask: "native:validate_email";
940
- readonly rustTask: "rust:validate_email";
941
- readonly status: "proven";
942
- readonly typicalRatio: 3;
943
- },
944
- {
945
- readonly name: "validateIpv6";
946
- readonly label: "IPv6 validation";
947
- readonly nativeTask: "native:validate_ipv6";
948
- readonly rustTask: "rust:validate_ipv6";
949
- readonly status: "proven";
950
- readonly typicalRatio: 1.3;
951
- },
952
- {
953
- readonly name: "urlEncode";
954
- readonly label: "URL encode";
955
- readonly nativeTask: "native:url_encode";
956
- readonly rustTask: "rust:url_encode";
957
- readonly status: "not-competitive";
958
- readonly note: "Public rust.urlEncode delegates to encodeURIComponent under Bun (BUN_WINS \u2014 ~3-4x faster than the FFI crossing; skips the C-ABI call). The rust: column measures the RAW addon (src/bench/raw-native.ts): the small-input FFI crossing loses (~0.58x), but LARGE inputs win (rust:url_encode_large ~1.45x) \u2014 the honest report no longer self-compares the built-in. Rust addon remains the Node path. Byte parity pinned by test/unit/features/url.test.ts + test/unit/features/wiring.test.ts.";
959
- },
960
- {
961
- readonly name: "urlDecode";
962
- readonly label: "URL decode";
963
- readonly nativeTask: "native:url_decode";
964
- readonly rustTask: "rust:url_decode";
965
- readonly status: "not-competitive";
966
- readonly note: "Public rust.urlDecode delegates to decodeURIComponent under Bun (BUN_WINS \u2014 ~4-8x faster than the FFI crossing; strict UTF-8 semantics match: both throw on malformed/invalid). The rust: column measures the RAW addon (src/bench/raw-native.ts): the small-input FFI crossing loses (~0.55x), but LARGE inputs win (rust:url_decode_large ~3.45x) \u2014 the honest report no longer self-compares the built-in. Rust addon remains the Node path and the raw-bytes urlDecodeBytes stays native. Parity pinned by test/unit/features/url.test.ts + test/unit/features/wiring.test.ts.";
967
- },
968
- {
969
- readonly name: "jwtVerify";
970
- readonly label: "JWT verify";
971
- readonly nativeTask: "native:jwt_verify";
972
- readonly rustTask: "rust:jwt_verify";
973
- readonly status: "proven";
974
- readonly typicalRatio: 1.4;
975
- },
976
- {
977
- readonly name: "passwordHash";
978
- readonly label: "Password hash";
979
- readonly nativeTask: "native:password_hash";
980
- readonly rustTask: "rust:password_hash";
981
- readonly status: "proven";
982
- readonly typicalRatio: 19;
983
- readonly note: "argon2id vs node:crypto scrypt.";
984
- },
985
- {
986
- readonly name: "aeadEncrypt";
987
- readonly label: "AEAD encrypt";
988
- readonly nativeTask: "native:aead_encrypt";
989
- readonly rustTask: "rust:aead_encrypt";
990
- readonly status: "proven";
991
- readonly typicalRatio: 1.6;
992
- },
993
- {
994
- readonly name: "aeadDecrypt";
995
- readonly label: "AEAD decrypt";
996
- readonly nativeTask: "native:aead_decrypt";
997
- readonly rustTask: "rust:aead_decrypt";
998
- readonly status: "proven";
999
- readonly typicalRatio: 2;
1000
- },
1001
- {
1002
- readonly name: "gzipDecompress";
1003
- readonly label: "Gzip decompress";
1004
- readonly nativeTask: "native:gzip_decompress";
1005
- readonly rustTask: "rust:gzip_decompress";
1006
- readonly status: "proven";
1007
- readonly typicalRatio: 1.4;
1008
- readonly note: "zlib-rs vs node zlib; swings 1.0-1.4x run-to-run. Deliberately NOT delegated to Bun.gunzipSync under Bun (NOT in BUN_WINS): Bun's decompressor has no output-size bound, and the native path keeps the 64 MiB decompression-bomb cap.";
1009
- },
1010
- {
1011
- readonly name: "brotliDecompress";
1012
- readonly label: "Brotli decompress";
1013
- readonly nativeTask: "native:brotli_decompress";
1014
- readonly rustTask: "rust:brotli_decompress";
1015
- readonly status: "proven";
1016
- readonly typicalRatio: 1.9;
1017
- },
1018
- {
1019
- readonly name: "multipartParse";
1020
- readonly label: "Multipart parse";
1021
- readonly nativeTask: "native:multipart_parse";
1022
- readonly rustTask: "rust:multipart_parse";
1023
- readonly status: "proven";
1024
- readonly typicalRatio: 2.3;
1025
- },
1026
- {
1027
- readonly name: "wsFrameEncode";
1028
- readonly label: "WS frame encode";
1029
- readonly nativeTask: "native:ws_frame_encode";
1030
- readonly rustTask: "rust:ws_frame_encode";
1031
- readonly status: "proven";
1032
- readonly typicalRatio: 1.8;
1033
- },
1034
- {
1035
- readonly name: "wsFrameDecode";
1036
- readonly label: "WS frame decode";
1037
- readonly nativeTask: "native:ws_frame_decode";
1038
- readonly rustTask: "rust:ws_frame_decode";
1039
- readonly status: "proven";
1040
- readonly typicalRatio: 2;
1041
- },
1042
- {
1043
- readonly name: "createSchemaValidator";
1044
- readonly label: "JSON schema validate";
1045
- readonly nativeTask: "native:json_schema_validate";
1046
- readonly rustTask: "rust:json_schema_validate";
1047
- readonly status: "proven";
1048
- readonly note: "Zero-DOM fast path validates raw bytes for the common keyword subset (scalar ~1.2-2.4x, batch ~1.0-1.56x vs ajv); unsupported keywords fall back to the jsonschema crate.";
1049
- },
1050
- {
1051
- readonly name: "crc32";
1052
- readonly label: "CRC32";
1053
- readonly nativeTask: "native:crc32";
1054
- readonly rustTask: "rust:crc32";
1055
- readonly status: "not-competitive";
1056
- readonly note: "Raw addon vs the same-engine JS crc-32 loop (~0.23-0.44x across runs). Under Bun the public rust.crc32 delegates to Bun.hash.crc32 (BUN_WINS, ~2.8-8.4x) \u2014 this row measures the raw addon (src/bench/raw-native.ts).";
1057
- },
1058
- {
1059
- readonly name: "xxh3";
1060
- readonly label: "XXH3-64";
1061
- readonly nativeTask: "diag:bun_hash_xxh3";
1062
- readonly rustTask: "diag:xxh3";
1063
- readonly status: "not-competitive";
1064
- readonly note: "Bun.hash.xxHash3 wins ~4x (in-process C++ beats the FFI crossing). The public rust.xxh3 now DELEGATES to Bun.hash.xxHash3 under Bun (BUN_WINS); the addon remains the Node/non-Bun fast path. See docs/bun-builtins-decision-matrix.md.";
1065
- },
1066
- {
1067
- readonly name: "randomToken";
1068
- readonly label: "Random token";
1069
- readonly nativeTask: "native:random_token";
1070
- readonly rustTask: "rust:random_token";
1071
- readonly status: "parity";
1072
- readonly typicalRatio: 1.1;
1073
- readonly note: "Raw addon vs crypto.getRandomValues baseline. Under Bun the public rust.randomToken delegates to crypto.getRandomValues + native hex (BUN_WINS, same 2n-hex format + 16 MiB guard) \u2014 this row measures the raw addon (src/bench/raw-native.ts).";
1074
- },
1075
- {
1076
- readonly name: "validateUuid";
1077
- readonly label: "UUID validation";
1078
- readonly nativeTask: "native:validate_uuid";
1079
- readonly rustTask: "rust:validate_uuid";
1080
- readonly status: "parity";
1081
- readonly typicalRatio: 1;
1082
- },
1083
- {
1084
- readonly name: "validateIpv4";
1085
- readonly label: "IPv4 validation";
1086
- readonly nativeTask: "native:validate_ipv4";
1087
- readonly rustTask: "rust:validate_ipv4";
1088
- readonly status: "parity";
1089
- readonly typicalRatio: 1.05;
1090
- },
1091
- {
1092
- readonly name: "mimeFromExtension";
1093
- readonly label: "MIME lookup";
1094
- readonly nativeTask: "native:mime";
1095
- readonly rustTask: "rust:mime";
1096
- readonly status: "parity";
1097
- readonly typicalRatio: 1.4;
1098
- readonly note: "Consistently ~1.38-1.44x rust after the 2026-08-12 marshal reduction (cachedMime no longer per-call slices; text.mimeFromExtension memoizes the decoded string). phf table lookup.";
1099
- },
1100
- {
1101
- readonly name: "gzipCompress";
1102
- readonly label: "Gzip compress";
1103
- readonly nativeTask: "native:gzip_compress";
1104
- readonly rustTask: "rust:gzip_compress";
1105
- readonly status: "parity";
1106
- readonly typicalRatio: 1;
1107
- readonly note: "Raw addon vs node zlib baseline. Under Bun the public rust.gzipCompress delegates to Bun.gzipSync (BUN_WINS, ~2x; decompression-parity with the addon \u2014 only the header OS byte differs) \u2014 this row measures the raw addon (src/bench/raw-native.ts).";
1108
- },
1109
- {
1110
- readonly name: "sseEncodeEvent";
1111
- readonly label: "SSE encode";
1112
- readonly nativeTask: "native:sse_encode";
1113
- readonly rustTask: "rust:sse_encode";
1114
- readonly status: "parity";
1115
- readonly typicalRatio: 1.1;
1116
- },
1117
- {
1118
- readonly name: "passwordHashBcrypt";
1119
- readonly label: "Password hash (bcrypt)";
1120
- readonly nativeTask: "diag:bun_password_bcrypt_hash";
1121
- readonly rustTask: "diag:bcrypt_hash";
1122
- readonly status: "parity";
1123
- readonly note: "Bun.password.bcrypt ~1.24x faster at cost 10 (noisy KDF); rust is self-contained and non-Bun. See docs/bun-builtins-decision-matrix.md.";
1124
- },
1125
- {
1126
- readonly name: "passwordVerifyBcrypt";
1127
- readonly label: "Password verify (bcrypt)";
1128
- readonly nativeTask: "diag:bun_password_bcrypt_verify";
1129
- readonly rustTask: "diag:bcrypt_verify";
1130
- readonly status: "parity";
1131
- readonly note: "Rust ~1.49x vs Bun.password.verify at cost 10; KDF timings noisy \u2014 parity for gate stability.";
1132
- },
1133
- {
1134
- readonly name: "pbkdf2Sha256";
1135
- readonly label: "PBKDF2-HMAC-SHA256";
1136
- readonly nativeTask: "diag:pbkdf2_sha256";
1137
- readonly rustTask: "diag:pbkdf2_sha256_rust";
1138
- readonly status: "parity";
1139
- readonly note: "~1.08x vs node:crypto pbkdf2Sync at 100k rounds (parity); Bun has no synchronous PBKDF2.";
1140
- },
1141
- {
1142
- readonly name: "jsonParse";
1143
- readonly label: "JSON parse";
1144
- readonly nativeTask: "native:json_parse";
1145
- readonly rustTask: "rust:json_parse";
1146
- readonly status: "not-competitive";
1147
- readonly note: "Bun's JSON.parse beats the native DOM + napi marshaling path (~5x).";
1148
- },
1149
- {
1150
- readonly name: "jwtSign";
1151
- readonly label: "JWT sign";
1152
- readonly nativeTask: "native:jwt_sign";
1153
- readonly rustTask: "rust:jwt_sign";
1154
- readonly status: "not-competitive";
1155
- readonly note: "Base64 + claims DOM marshal overhead. Use jwtSignBytes (claims as JSON bytes) which skips the napi Value marshal and flips to a ~1.07x win.";
1156
- },
1157
- {
1158
- readonly name: "jwtSignBytes";
1159
- readonly label: "JWT sign (bytes)";
1160
- readonly nativeTask: "native:jwt_sign";
1161
- readonly rustTask: "rust:jwt_sign_bytes";
1162
- readonly status: "parity";
1163
- readonly note: "Byte-JSON claims overload avoids the napi serde_json::Value DOM marshal; flips jwtSign from a ~1.3x loss to ~1.07x (parity).";
1164
- },
1165
- {
1166
- readonly name: "brotliCompress";
1167
- readonly label: "Brotli compress";
1168
- readonly nativeTask: "native:brotli_compress";
1169
- readonly rustTask: "rust:brotli_compress";
1170
- readonly status: "not-competitive";
1171
- readonly note: "The native brotli baseline wins for small inputs.";
1172
- },
1173
- {
1174
- readonly name: "templateRender";
1175
- readonly label: "Template render";
1176
- readonly nativeTask: "native:template_render";
1177
- readonly rustTask: "rust:template_render";
1178
- readonly status: "not-competitive";
1179
- readonly note: "The allocating render marshals the context via napi DOM (~1.5x loss). Use TemplateRenderer.renderBytes (JSON-bytes context) which avoids it and wins ~1.37x.";
1180
- },
1181
- {
1182
- readonly name: "formParsePacked";
1183
- readonly label: "Form parse";
1184
- readonly nativeTask: "native:form_parse";
1185
- readonly rustTask: "rust:form_parse";
1186
- readonly status: "proven";
1187
- readonly typicalRatio: 5.8;
1188
- readonly note: "Benchmarked via the FormParser instance (same parser core).";
1189
- },
1190
- {
1191
- readonly name: "parseMediaType";
1192
- readonly label: "Media type parse";
1193
- readonly nativeTask: "native:media_type_parse";
1194
- readonly rustTask: "rust:media_type_parse";
1195
- readonly status: "not-competitive";
1196
- readonly note: "Consistent ~0.71-0.81x (sub-\u00B5s FFI crossing vs the JS baseline); use MediaTypeMatcher (precompiled expected) for the zero-alloc match path.";
1197
- },
1198
- {
1199
- readonly name: "etag";
1200
- readonly label: "ETag";
1201
- readonly nativeTask: "native:etag";
1202
- readonly rustTask: "rust:etag";
1203
- readonly status: "parity";
1204
- readonly typicalRatio: 1.06;
1205
- },
1206
- {
1207
- readonly name: "httpDate";
1208
- readonly label: "HTTP date";
1209
- readonly nativeTask: "native:http_date";
1210
- readonly rustTask: "rust:http_date";
1211
- readonly status: "not-competitive";
1212
- readonly note: "Delegates to Date.toUTCString() under Bun (BUN_WINS \u2014 ~3.7x faster than the FFI crossing; byte-identical RFC 1123 for HTTP timestamps, incl. leap years/epoch). Rust addon remains the Node path; pooled httpDateInto stays native.";
1213
- },
1214
- {
1215
- readonly name: "createConditionalRequest";
1216
- readonly label: "Conditional request";
1217
- readonly nativeTask: "native:conditional";
1218
- readonly rustTask: "rust:conditional";
1219
- readonly status: "proven";
1220
- readonly typicalRatio: 1.4;
1221
- },
1222
- {
1223
- readonly name: "createAcceptNegotiator";
1224
- readonly label: "Accept-Encoding negotiate";
1225
- readonly nativeTask: "native:accept_negotiate";
1226
- readonly rustTask: "rust:accept_negotiate";
1227
- readonly status: "proven";
1228
- readonly typicalRatio: 4;
1229
- },
1230
- {
1231
- readonly name: "base64Encode";
1232
- readonly label: "Base64 encode";
1233
- readonly nativeTask: "native:base64_encode";
1234
- readonly rustTask: "rust:base64_encode";
1235
- readonly status: "not-competitive";
1236
- readonly note: "Delegates to Buffer base64 under Bun for the standard padded, non-url-safe case (BUN_WINS \u2014 ~2x faster than the FFI crossing); url-safe/unpadded falls through to native. Rust addon remains the Node path. Parity pinned by test/unit/features/encoding.test.ts.";
1237
- },
1238
- {
1239
- readonly name: "base64Decode";
1240
- readonly label: "Base64 decode";
1241
- readonly nativeTask: "native:base64_decode";
1242
- readonly rustTask: "rust:base64_decode";
1243
- readonly status: "parity";
1244
- readonly typicalRatio: 1.17;
1245
- },
1246
- {
1247
- readonly name: "hexEncode";
1248
- readonly label: "Hex encode";
1249
- readonly nativeTask: "native:hex_encode";
1250
- readonly rustTask: "rust:hex_encode";
1251
- readonly status: "not-competitive";
1252
- readonly note: "Buffer.toString('hex') is native SIMD; pooled hexEncodeInto cuts the loss from ~2.2x to ~1.35x.";
1253
- },
1254
- {
1255
- readonly name: "hexDecode";
1256
- readonly label: "Hex decode";
1257
- readonly nativeTask: "native:hex_decode";
1258
- readonly rustTask: "rust:hex_decode";
1259
- readonly status: "parity";
1260
- readonly typicalRatio: 0.78;
1261
- readonly note: "Slightly slower than Buffer hex decode (~1.3x).";
1262
- },
1263
- {
1264
- readonly name: "signCookie";
1265
- readonly label: "Cookie sign";
1266
- readonly nativeTask: "native:cookie_sign";
1267
- readonly rustTask: "rust:cookie_sign";
1268
- readonly status: "proven";
1269
- readonly typicalRatio: 9;
1270
- },
1271
- {
1272
- readonly name: "verifyCookie";
1273
- readonly label: "Cookie verify";
1274
- readonly nativeTask: "native:cookie_verify";
1275
- readonly rustTask: "rust:cookie_verify";
1276
- readonly status: "proven";
1277
- readonly typicalRatio: 2.1;
1278
- },
1279
- {
1280
- readonly name: "csrfToken";
1281
- readonly label: "CSRF create";
1282
- readonly nativeTask: "native:csrf_create";
1283
- readonly rustTask: "rust:csrf_create";
1284
- readonly status: "proven";
1285
- readonly typicalRatio: 13.8;
1286
- },
1287
- {
1288
- readonly name: "csrfVerify";
1289
- readonly label: "CSRF verify";
1290
- readonly nativeTask: "native:csrf_verify";
1291
- readonly rustTask: "rust:csrf_verify";
1292
- readonly status: "proven";
1293
- readonly typicalRatio: 2.7;
1294
- },
1295
- {
1296
- readonly name: "urlResolve";
1297
- readonly label: "URL resolve";
1298
- readonly nativeTask: "native:url_resolve";
1299
- readonly rustTask: "rust:url_resolve";
1300
- readonly status: "parity";
1301
- readonly typicalRatio: 1.11;
1302
- readonly note: "Noisy ~1.5\u00B5s op; swings 0.74-1.03x run-to-run. UrlBuilder reuses the parsed base.";
1303
- },
1304
- {
1305
- readonly name: "urlEncodeQuery";
1306
- readonly label: "URL query build";
1307
- readonly nativeTask: "native:url_encode_query";
1308
- readonly rustTask: "rust:url_encode_query";
1309
- readonly status: "not-competitive";
1310
- readonly note: "encodeURIComponent baseline wins (~1.2-1.35x).";
1311
- },
1312
- {
1313
- readonly name: "passwordVerify";
1314
- readonly label: "Password verify";
1315
- readonly nativeTask: "";
1316
- readonly rustTask: "";
1317
- readonly status: "unmeasured";
1318
- readonly note: "Depends on the hash cost; no standalone comparison.";
1319
- },
1320
- {
1321
- readonly name: "urlDecodeBytes";
1322
- readonly label: "URL decode (bytes)";
1323
- readonly nativeTask: "";
1324
- readonly rustTask: "";
1325
- readonly status: "unmeasured";
1326
- },
1327
- {
1328
- readonly name: "configure";
1329
- readonly label: "configure";
1330
- readonly nativeTask: "";
1331
- readonly rustTask: "";
1332
- readonly status: "unmeasured";
1333
- readonly note: "Config only.";
1334
- },
1335
- {
1336
- readonly name: "initThreadPool";
1337
- readonly label: "initThreadPool";
1338
- readonly nativeTask: "";
1339
- readonly rustTask: "";
1340
- readonly status: "unmeasured";
1341
- readonly note: "Runtime setup only.";
1342
- },
1343
- {
1344
- readonly name: "rayonNumThreads";
1345
- readonly label: "rayonNumThreads";
1346
- readonly nativeTask: "";
1347
- readonly rustTask: "";
1348
- readonly status: "unmeasured";
1349
- readonly note: "Introspection only.";
1350
- }
1351
- ];
1352
- /** An entry of the registry with a specific status (type-level). */
1353
- export type ProvenEntryOf<S extends PerformanceStatus> = Extract<(typeof PROVEN_SURFACE)[number], {
1354
- status: S;
1355
- }>;
1356
- /**
1357
- * The `rust.<name>` keys whose status is "proven" — the only keys exposed on
1358
- * the `proven` surface. Derived from the registry so the type can never drift
1359
- * from the data.
1360
- */
1361
- export type ProvenKey = ProvenEntryOf<"proven">["name"];
1362
- /** Look up the status of a public function by its `rust.<name>` key. */
1363
- export declare function provenStatus(name: string): PerformanceStatus | undefined;
1364
- /** Whether a function is part of the performance-proven surface. */
1365
- export declare function isProven(name: string): boolean;
1366
- /** The entries that are performance-proven (Rust clearly wins). */
1367
- export declare function provenSurface(): ProvenEntry[];
1368
- /** Aggregate summary of the registry (status → count). */
1369
- export declare function provenSummary(): Record<PerformanceStatus, number>;
1370
- /**
1371
- * The performance-annotated client: the full {@link RustClient} surface.
1372
- * Each exported function's JSDoc notes its measured performance vs the JS
1373
- * baseline; functions slower than the baseline carry `@deprecated`.
1374
- */
1375
- export type ProvenClient = RustClient;
1376
- /**
1377
- * The full `rust.*` surface with benchmark-annotated JSDoc. Identical to
1378
- * `rust` — the annotations and `@deprecated` markers are what communicate
1379
- * performance now, not a curated subset.
1380
- */
1381
- export declare const proven: ProvenClient;
1382
- /**
1383
- * Shared TextEncoder instance for encoding strings to UTF-8 bytes.
1384
- *
1385
- * Reusing a single encoder avoids allocation overhead in hot paths.
1386
- */
1387
- export declare const encoder: TextEncoder;
1388
- /**
1389
- * Shared TextDecoder instance for decoding UTF-8 bytes to strings.
1390
- *
1391
- * Reusing a single decoder avoids allocation overhead in hot paths.
1392
- */
1393
- export declare const decoder: TextDecoder;
1394
- export interface AdaptiveEstimateOptions {
1395
- /**
1396
- * EWMA smoothing factor in (0, 1]. Higher reacts faster to new samples;
1397
- * lower smooths more. Default: 0.25.
1398
- */
1399
- alpha?: number;
1400
- /** Starting estimate. Default 0 (the first sample wins). */
1401
- initial?: number;
1402
- /** Clamp the estimate to at least this. Default 0. */
1403
- min?: number;
1404
- /** Clamp the estimate to at most this (bounds memory / resources). Default Infinity. */
1405
- max?: number;
1406
- }
1407
- /**
1408
- * A bounded exponential-moving-average estimate of an observed quantity.
1409
- *
1410
- * `sample(x)` folds a new observation into the running estimate; `estimate`
1411
- * reads the current value. The estimate is clamped to `[min, max]`, so it is
1412
- * safe to drive resource sizing (buffer pools, batch thresholds) with it —
1413
- * a single outlier cannot blow up the estimate, and it decays toward recent
1414
- * observations.
1415
- */
1416
- export declare class AdaptiveEstimate {
1417
- private readonly alpha;
1418
- private readonly min;
1419
- private readonly max;
1420
- private readonly initial;
1421
- private value;
1422
- constructor(options?: AdaptiveEstimateOptions);
1423
- /** Fold a new observation into the running estimate. */
1424
- sample(x: number): void;
1425
- /** Current estimate (clamped to `[min, max]`). */
1426
- get estimate(): number;
1427
- /** Reset the estimate (back to `initial`). */
1428
- reset(): void;
1429
- }
1430
- /** Generate a UUIDv7 (time-ordered) string, preferring Bun's native built-in. */
1431
- export declare function uuidv7(): string;
1432
- /** Default histogram buckets (Prometheus-style, seconds). */
1433
- export declare const DEFAULT_BUCKETS: readonly number[];
1434
- export type Labels = Readonly<Record<string, string>>;
1435
- /** A single labelled counter value. */
1436
- export interface Counter {
1437
- /** Increment by 1 (or `by`). `labels` must match the label names exactly. */
1438
- inc(labels?: Labels, by?: number): void;
1439
- }
1440
- /** A single labelled gauge value (can go up and down). */
1441
- export interface Gauge {
1442
- inc(labels?: Labels, by?: number): void;
1443
- dec(labels?: Labels, by?: number): void;
1444
- set(labels: Labels | undefined, value: number): void;
1445
- }
1446
- /** A single labelled histogram. */
1447
- export interface Histogram {
1448
- /** Record one observation. `labels` must match the label names exactly. */
1449
- observe(value: number, labels?: Labels): void;
1450
- }
1451
- /** The metrics registry factory. */
1452
- export interface MetricsRegistry {
1453
- /** Create (or fetch) a counter. `help` is only used on first creation. */
1454
- counter(name: string, help: string, labelNames?: readonly string[]): Counter;
1455
- /** Create (or fetch) a gauge. */
1456
- gauge(name: string, help: string, labelNames?: readonly string[]): Gauge;
1457
- /**
1458
- * Create (or fetch) a histogram. `buckets`/`help` only apply on first
1459
- * creation; later calls with the same name return the existing histogram.
1460
- */
1461
- histogram(name: string, help: string, buckets?: readonly number[], labelNames?: readonly string[]): Histogram;
1462
- /** Render the Prometheus text exposition format. */
1463
- render(): string;
1464
- /** Reset all metrics (for tests / interval rotation). */
1465
- reset(): void;
1466
- }
1467
- /** Create a fresh metrics registry. */
1468
- export declare function createMetrics(): MetricsRegistry;
1469
- /** User-facing CORS configuration. */
1470
- export interface CorsOptions {
1471
- allowOrigin?: string[];
1472
- allowMethods?: string[];
1473
- allowHeaders?: string[];
1474
- exposeHeaders?: string[];
1475
- allowCredentials?: boolean;
1476
- maxAge?: number;
1477
- }
1478
- /** Precomputed, immutable CORS policy strings. */
1479
- export interface CorsStaticStrings {
1480
- readonly allowMethodsJoined: string;
1481
- readonly allowHeadersJoined: string;
1482
- readonly exposeHeadersJoined: string;
1483
- readonly maxAgeString: string | null;
1484
- readonly isWildcard: boolean;
1485
- readonly credentials: boolean;
1486
- }
1487
- /** User-facing security-headers configuration. */
1488
- export interface SecurityHeadersOptions {
1489
- contentSecurityPolicy?: string;
1490
- hsts?: boolean;
1491
- hstsMaxAge?: number;
1492
- hstsIncludeSubdomains?: boolean;
1493
- hstsPreload?: boolean;
1494
- frameOptions?: string;
1495
- nosniff?: boolean;
1496
- referrerPolicy?: string;
1497
- coep?: string;
1498
- coop?: string;
1499
- corp?: string;
1500
- xssProtection?: string;
1501
- }
1502
- /** Bounds-checked section offsets for one ingress output buffer. */
1503
- export interface PackedSectionLayout {
1504
- /** Cookie-JSON length clamped to the buffer (0 if none / out of range). */
1505
- safeCookiesLen: number;
1506
- /** Byte offset where the query-JSON section begins. */
1507
- queryStart: number;
1508
- /** Query-JSON length clamped to the buffer (0 if none / out of range). */
1509
- safeQueryLen: number;
1510
- /** Byte offset where the body-JSON section begins. */
1511
- bodyJsonStart: number;
1512
- /** Body-JSON length clamped to the buffer (0 if none / out of range). */
1513
- safeBodyJsonLen: number;
1514
- /** Whether any declared section length overran the buffer. */
1515
- truncated: boolean;
1516
- }
1517
- declare abstract class IngressResultBase {
1518
- /** Raw native verdict byte (0 = accepted). */
1519
- verdict: number;
1520
- /** Raw native error-code byte. */
1521
- errorCode: number;
1522
- /** Normalized HTTP status. */
1523
- status: number;
1524
- /** Header template variant byte emitted by the native core. */
1525
- headerVariant: number;
1526
- /** Remaining rate-limit budget (count). */
1527
- rateRemaining: number;
1528
- /** Rate-limit window reset (ms epoch). */
1529
- rateResetMs: number;
1530
- /** Retry-After value (ms). */
1531
- retryAfterMs: number;
1532
- /** True when the pipeline returned a terminal (error) verdict. */
1533
- terminal: boolean;
1534
- /** True when the pipeline accepted the request (verdict 0 + 2xx/3xx). */
1535
- ok: boolean;
1536
- /** True when the request was a CORS preflight. */
1537
- isPreflight: boolean;
1538
- /** True when the CORS engine allowed the request origin. */
1539
- corsAllowed: boolean;
1540
- /** True when the request was rate-limited. */
1541
- rateLimited: boolean;
1542
- /** True when the request came from a trusted proxy. */
1543
- trustedProxy: boolean;
1544
- /** True when the request body parsed as valid JSON. */
1545
- bodyValidJson: boolean;
1546
- /** True when the request body validated against the ingress schema. */
1547
- schemaValid: boolean;
1548
- /** True when a declared output section overran the buffer. */
1549
- bodyTruncated: boolean;
1550
- /** Request body bytes (may be an empty view). */
1551
- body: Uint8Array;
1552
- protected _buf: Uint8Array;
1553
- protected _bodyJsonStart: number;
1554
- protected _bodyJsonLen: number;
1555
- private _cookiesBuf;
1556
- private _queryBuf;
1557
- private _cookiesDecoded;
1558
- private _queryDecoded;
1559
- /** Reset the shared fields to their empty state (call from subclass `invalidate`). */
1560
- protected resetShared(): void;
1561
- /** Recompute `terminal`/`ok` from the (subclass-set) verdict + status. */
1562
- protected updateOkTerminal(): void;
1563
- /**
1564
- * Store the rate-limit window fields. Both decoders read the same OUT_*
1565
- * slots and gate them on the same conditions (a positive budget OR the
1566
- * rate-limited flag), so the read cannot drift between paths.
1567
- */
1568
- protected setRateWindow(rateLimit: number, rateLimited: boolean, view: DataView): void;
1569
- /**
1570
- * Store the bounds-checked cookie/query/body JSON sections from `layout`.
1571
- *
1572
- * `bodyJsonLen` is the body-JSON length to trust for `bodyJson()`: the fast
1573
- * path passes the RAW declared length (it re-checks bounds on read), the
1574
- * baked path passes the already-clamped `layout.safeBodyJsonLen`. Sections
1575
- * are stored as slices and decoded lazily by `cookiesJson()`/`queryJson()`.
1576
- */
1577
- protected setSections(buf: Uint8Array, layout: PackedSectionLayout, bodyJsonLen: number): void;
1578
- /** Decoded cookies-JSON section, or `"{}"` when absent. */
1579
- cookiesJson(): string;
1580
- /** Decoded query-JSON section, or `"{}"` when absent. */
1581
- queryJson(): string;
1582
- /** Bounds-checked body-JSON slice (empty when absent / out of range). */
1583
- protected bodyJsonSlice(): Uint8Array;
1584
- }
1585
- /** Zero-alloc, lazy-decoding view over a native Ingress output buffer. */
1586
- export declare class FastIngressResult extends IngressResultBase {
1587
- status: number;
1588
- verdict: number;
1589
- errorCode: number;
1590
- flags: number;
1591
- https: boolean;
1592
- hasCookies: boolean;
1593
- hasQuery: boolean;
1594
- rateLimit: number;
1595
- requestId: string;
1596
- refresh(buf: Uint8Array, body: Uint8Array, requestId: string): void;
1597
- invalidate(): void;
1598
- setInternalError(requestId: string): void;
1599
- /** Bounds-checked body-JSON section, or an empty view when absent. */
1600
- bodyJson(): Uint8Array;
1601
- }
1602
- /** Options accepted by `createIngressFast` / `createIngress`. */
1603
- export interface IngressFastOptions {
1604
- trustProxy?: boolean;
1605
- trustedProxies?: {
1606
- enabled?: boolean;
1607
- networks?: string[];
1608
- };
1609
- parseCookies?: boolean;
1610
- parseQuery?: boolean;
1611
- requireJsonBody?: boolean;
1612
- schema?: Uint8Array;
1613
- cors?: CorsOptions;
1614
- rateLimit?: {
1615
- limit?: number;
1616
- windowMs?: number;
1617
- maxEntries?: number;
1618
- };
1180
+ urlEncode(input: string): string;
1619
1181
  /**
1620
- * Structured security-header options (CSP/HSTS) — honored by the fast/async
1621
- * paths (`createIngressFast` throws on it; `createIngress` applies it via
1622
- * `buildResponseContext`). The PRE-BAKED path (`createIngressHandler`)
1623
- * instead takes raw `securityHeaders: [name, value][]` pairs. The two paths
1624
- * intentionally use different option shapes (see docs/INGRESS.md).
1182
+ * Percent-decode a string. Throws on malformed `%XX` or invalid UTF-8
1183
+ * output (parity with `decodeURIComponent`, which is used under Bun).
1184
+ * @param input the percent-encoded string to decode.
1185
+ * @returns the decoded string.
1625
1186
  */
1626
- security?: SecurityHeadersOptions;
1627
- https?: boolean;
1628
- maxBodyBytes?: number;
1629
- enableSecurityHeaders?: boolean;
1630
- enableRequestIds?: boolean;
1631
- enableBodySizeGuard?: boolean;
1632
- emitMetadataJson?: boolean;
1633
- readBody?: boolean;
1634
- outputBufferSize?: number;
1187
+ urlDecode(input: string): string;
1635
1188
  /**
1636
- * Overall deadline (ms) for reading a request body in the async
1637
- * `createIngress` path. 0 disables. Default: `DEFAULT_BODY_TIMEOUT_MS` (30s).
1638
- * Ignored by the sync `createIngressFast` (it does not read bodies).
1189
+ * Compute the RFC 6455 `Sec-WebSocket-Accept` value for a client key.
1190
+ * @param key the base64 `Sec-WebSocket-Key` header value.
1191
+ * @returns the 28-byte base64 accept value.
1639
1192
  */
1640
- bodyTimeoutMs?: number;
1193
+ wsAcceptKey(key: string): string;
1194
+ /** @param input an email address. @returns whether it is RFC-valid. */
1195
+ validateEmail(input: string): boolean;
1196
+ /** @param input a UUID string. @returns whether it is a valid (v1-v8) UUID. */
1197
+ validateUuid(input: string): boolean;
1198
+ /** @param input an IPv4 address. @returns whether it is valid. */
1199
+ validateIpv4(input: string): boolean;
1200
+ /** @param input an IPv6 address. @returns whether it is valid. */
1201
+ validateIpv6(input: string): boolean;
1202
+ }
1203
+ /** The full Rust FFI client (scalar methods + namespaces + configuration). */
1204
+ export interface RustClient extends RustScalar {
1205
+ text: RustText;
1206
+ batch: RustBatch;
1207
+ packed: RustPacked;
1641
1208
  /**
1642
- * Invoked when the native pipeline throws (the request becomes a 500).
1643
- * Native failures are otherwise silent in the fast path. Never throws.
1209
+ * Resolve the native transport in use on this runtime: `"ffi"` (bun:ffi —
1210
+ * the PRIMARY transport under Bun) or `"napi"` (Node, forced
1211
+ * `CASTRUM_FFI_MODE=napi`, or a failed ffi bind-time self-test).
1644
1212
  */
1645
- onError?: (error: Error) => void;
1213
+ transport(): "ffi" | "napi";
1214
+ /** Whether the bun:ffi transport is live (equivalent to `transport() === "ffi"`). */
1215
+ ffiActive(): boolean;
1646
1216
  /**
1647
- * When true, run one probe GET at construction so the `run()` closure,
1648
- * packed pipeline and FFI ingress call are JIT-warmed before the first real
1649
- * request (cuts cold-invocation tail latency in serverless-style
1650
- * deployments). Opt-in; default false. Not forwarded to the native addon.
1217
+ * Update defaults on this instance. `mimeCache` / `hmacCache` apply
1218
+ * immediately (per-instance). `rayonThreads` is applied only if the
1219
+ * process-wide pool is not yet initialized (see {@link RustOptions}).
1651
1220
  */
1652
- warmOnCreate?: boolean;
1653
- limits?: {
1654
- maxUrlBytes?: number;
1655
- maxQueryBytes?: number;
1656
- maxCookieBytes?: number;
1657
- maxHeadersBytes?: number;
1658
- maxHeaders?: number;
1659
- maxPairs?: number;
1660
- };
1661
- }
1662
- /** The zero-alloc sync handler returned by `createIngressFast`. */
1663
- export interface IngressFastHandler {
1664
- run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, requestId: string, fn: (result: FastIngressResult) => T): T;
1221
+ configure(options: RustOptions): void;
1665
1222
  }
1666
1223
  /**
1667
- * Options accepted by `createIngressHandler` (path 2).
1224
+ * Create an isolated Rust client with the given defaults.
1668
1225
  *
1669
- * Same native option surface as the fast path, minus `onError` — path 2
1670
- * reports native failures through `BakedIngressRuntime.onError` instead of the
1671
- * options bag.
1226
+ * `mimeCache` / `hmacCache` are per-instance. `rayonThreads` only applies
1227
+ * before the process-wide rayon pool is initialized (once per process — see
1228
+ * {@link RustOptions.rayonThreads}); the pool defaults to the env var or
1229
+ * `max(1, hardwareConcurrency - 1)` otherwise.
1672
1230
  */
1673
- export type IngressHandlerOptions = Omit<IngressFastOptions, "onError">;
1674
- /** Zero-alloc, reusable result decoder for the pre-baked handler path. */
1675
- export declare class BakedIngressResult extends IngressResultBase {
1676
- refresh(buf: Uint8Array, body: Uint8Array, view: DataView): void;
1677
- invalidate(): void;
1678
- setInternalError(): void;
1679
- bodyJson(copy: boolean): Uint8Array;
1231
+ export declare function createRust(options?: RustOptions): RustClient;
1232
+ /**
1233
+ * The default, ready-to-use `RustClient` created with no options (resolves
1234
+ * rayon threads from the host automatically). Most consumers just do
1235
+ * `import { rust } from "castrum"` and call `rust.<fn>(...)` directly.
1236
+ */
1237
+ export declare const rust: RustClient;
1238
+ /** The benchmark-proven default implementation for an op. */
1239
+ export type ProvenImpl = "native" | "js" | "bun";
1240
+ /** How decisive the baked winner is. */
1241
+ export type ProvenStatus = "proven" | "parity" | "unmeasured";
1242
+ /** One entry in the baked proven-selection registry. */
1243
+ export interface ProvenEntry {
1244
+ /** Selection op name (matches `opImpl(op)` / `src/selection.json` keys). */
1245
+ name: string;
1246
+ /** The baked default implementation: the benchmark-proven winner. */
1247
+ impl: ProvenImpl;
1248
+ /** `proven` = decisive win, `parity` = borderline, `unmeasured` = pinned by policy. */
1249
+ status: ProvenStatus;
1250
+ /** Measured ratio behind the decision (see module doc for the axis). */
1251
+ typicalRatio?: number;
1252
+ /** Why this classification. */
1253
+ note?: string;
1680
1254
  }
1681
- /** Public ingress options (extends the fast-path options). */
1682
- export interface IngressOptions extends IngressFastOptions {
1683
- enableRequestIds?: boolean;
1684
- /**
1685
- * Invoked before a request is processed (for tracing/context hooks).
1686
- * Only used by the async `createIngress` path.
1687
- */
1688
- onRequest?: (req: Request, requestId: string, ip: string | undefined) => void;
1255
+ /**
1256
+ * Baked proven-winner registry. Covering the FULL selection surface
1257
+ * (`src/selection.json` ops + every Bun built-in delegation) so nothing can be
1258
+ * silently dropped. Classifications are based on release/perf-build results;
1259
+ * `test/unit/shared/proven.test.ts` re-checks them against the LIVE wiring.
1260
+ */
1261
+ export declare const PROVEN_SELECTION: readonly ProvenEntry[];
1262
+ /**
1263
+ * The baked {@link ProvenEntry} for `op`, or `undefined` for unknown ops.
1264
+ * Pure data — never dlopens the addon.
1265
+ */
1266
+ export declare function provenEntry(op: string): ProvenEntry | undefined;
1267
+ /** The baked default implementation for `op` (`native` / `js` / `bun`), or `null`. */
1268
+ export declare function provenImpl(op: string): ProvenImpl | null;
1269
+ /** The baked status for `op`, or `null` for unknown ops. */
1270
+ export declare function provenStatus(op: string): ProvenStatus | null;
1271
+ /** Whether the op's baked winner is a decisive (`proven`) win. */
1272
+ export declare function isProven(op: string): boolean;
1273
+ /** The full baked registry (same array as {@link PROVEN_SELECTION}). */
1274
+ export declare function provenSurface(): readonly ProvenEntry[];
1275
+ /** A one-line summary of the baked selection (counts per implementation). */
1276
+ export declare function provenSummary(): string;
1277
+ /** The full `rust.*` surface — identical to `rust`; the proven wiring is baked (see {@link ../shared/proven}). */
1278
+ export type ProvenClient = RustClient;
1279
+ /** The full `rust.*` surface, exposed for audit. Same object as `rust`. */
1280
+ export declare const proven: ProvenClient;
1281
+ /** Recommended implementation for an operation. */
1282
+ export type OpImpl = "native" | "js";
1283
+ /** A selection decision: recommended implementation + rationale note. */
1284
+ export interface OpDecision {
1285
+ /** The recommended implementation when the addon is available. */
1286
+ readonly impl: OpImpl;
1287
+ /** Why this decision (measured ratio / rationale). */
1288
+ readonly note?: string;
1289
+ }
1290
+ /**
1291
+ * The benchmark-driven native-vs-JS decision for `op` — runtime-aware.
1292
+ *
1293
+ * Returns `"native"` when the Rust addon is the recommended implementation,
1294
+ * `"js"` when a pure-JS (or Bun built-in) implementation wins, or `null` for
1295
+ * unknown ops (or when the addon is unavailable — with no addon there is no
1296
+ * "native" choice). Under Bun, ops in the adapter's builtins registry resolve
1297
+ * to `"js"` so the consumer's JS path delegates to the faster Bun built-in.
1298
+ *
1299
+ * The default is the BAKED proven selection (`src/shared/proven.ts`):
1300
+ * `native` / `js` directly, `bun` resolves to `"js"` via the builtins check
1301
+ * above. Unknown ops (and `bun` entries on a non-Bun runtime, where no
1302
+ * built-in exists) fall back to the addon's embedded decision
1303
+ * (`rust/selection.rs` ← `src/selection.json`).
1304
+ */
1305
+ export declare const opImpl: (op: string) => OpImpl | null;
1306
+ /** `true` when the Rust addon is the recommended impl for `op`. */
1307
+ export declare const isNativeOp: (op: string) => boolean;
1308
+ /** The decision record for `op`, or `null` when unknown. */
1309
+ export declare const opDecision: (op: string) => OpDecision | null;
1310
+ /**
1311
+ * Shared UTF-8 encoder (encode / encodeInto), backed by the runtime-native
1312
+ * codec (`src/shared/codec.ts`): on Bun the work is done by Bun's native
1313
+ * transfer machinery (`Bun.ArrayBufferSink` / a zero-copy `Buffer` view
1314
+ * write); under Node it falls back to `TextEncoder`. Reusing a single object
1315
+ * avoids allocation overhead in hot paths.
1316
+ *
1317
+ * `encode` accepts the string-or-bytes union the text-returning `rust.*` ops
1318
+ * surface (Bun returns strings, Node returns bytes) and normalizes to bytes —
1319
+ * a string is UTF-8 encoded, bytes pass through unchanged.
1320
+ */
1321
+ export declare const encoder: {
1322
+ encode(s: Uint8Array | string): Uint8Array;
1323
+ encodeInto(s: string, dest: Uint8Array): {
1324
+ read: number;
1325
+ written: number;
1326
+ };
1327
+ };
1328
+ /**
1329
+ * Shared UTF-8 decoder, backed by the runtime-native codec
1330
+ * (`src/shared/codec.ts`): on Bun it uses `new CString(ptr, 0, len)` from
1331
+ * `bun:ffi` (JSC-native, exact-length clone); under Node it falls back to
1332
+ * `TextDecoder`. Reusing a single object avoids allocation overhead in hot
1333
+ * paths.
1334
+ *
1335
+ * `decode` accepts the string-or-bytes union the text-returning `rust.*` ops
1336
+ * surface and normalizes to a string — bytes are UTF-8 decoded, strings pass
1337
+ * through unchanged.
1338
+ */
1339
+ export declare const decoder: {
1340
+ decode(bytes: Uint8Array | string): string;
1341
+ };
1342
+ /** Options for an `AdaptiveEstimate`: EWMA smoothing, bounds, starting value. */ export interface AdaptiveEstimateOptions {
1689
1343
  /**
1690
- * Invoked after a terminal context (and its `Response`) is produced, for
1691
- * metrics/logging hooks. Only used by the async `createIngress` path.
1344
+ * EWMA smoothing factor in (0, 1]. Higher reacts faster to new samples;
1345
+ * lower smooths more. Default: 0.25.
1692
1346
  */
1693
- onResponse?: (req: Request, result: IngressContext, status: number, requestId: string) => void;
1347
+ alpha?: number;
1348
+ /** Starting estimate. Default 0 (the first sample wins). */
1349
+ initial?: number;
1350
+ /** Clamp the estimate to at least this. Default 0. */
1351
+ min?: number;
1352
+ /** Clamp the estimate to at most this (bounds memory / resources). Default Infinity. */
1353
+ max?: number;
1694
1354
  }
1695
1355
  /**
1696
- * Readonly structural view of a decoded ingress result.
1356
+ * A bounded exponential-moving-average estimate of an observed quantity.
1697
1357
  *
1698
- * Note: the exported `FastIngressResult` class is the zero-alloc implementation;
1699
- * this interface is the readonly view used by the public sync/async handlers.
1358
+ * `sample(x)` folds a new observation into the running estimate; `estimate`
1359
+ * reads the current value. The estimate is clamped to `[min, max]`, so it is
1360
+ * safe to drive resource sizing (buffer pools, batch thresholds) with it —
1361
+ * a single outlier cannot blow up the estimate, and it decays toward recent
1362
+ * observations.
1700
1363
  */
1701
- export interface IngressResult {
1702
- readonly status: number;
1703
- readonly verdict: number;
1704
- readonly flags: number;
1705
- readonly errorCode: number;
1706
- readonly terminal: boolean;
1707
- readonly ok: boolean;
1708
- readonly https: boolean;
1709
- readonly trustedProxy: boolean;
1710
- readonly hasCookies: boolean;
1711
- readonly hasQuery: boolean;
1712
- readonly bodyValidJson: boolean;
1713
- readonly schemaValid: boolean;
1714
- readonly corsAllowed: boolean;
1715
- readonly isPreflight: boolean;
1716
- readonly rateLimited: boolean;
1717
- readonly rateLimit: number;
1718
- readonly rateRemaining: number;
1719
- readonly rateResetMs: number;
1720
- readonly retryAfterMs: number;
1721
- readonly body: Uint8Array;
1722
- readonly headerVariant: number;
1723
- readonly requestId: string;
1724
- readonly bodyTruncated: boolean;
1725
- cookiesJson(): string;
1726
- queryJson(): string;
1727
- bodyJson(): Uint8Array;
1728
- }
1729
- /** A result plus the terminal Response computed for it. */
1730
- export interface IngressContext extends IngressResult {
1731
- response: Response | null;
1364
+ export declare class AdaptiveEstimate {
1365
+ private readonly alpha;
1366
+ private readonly min;
1367
+ private readonly max;
1368
+ private readonly initial;
1369
+ private value;
1370
+ constructor(options?: AdaptiveEstimateOptions);
1371
+ /** Fold a new observation into the running estimate. */
1372
+ sample(x: number): void;
1373
+ /** Current estimate (clamped to `[min, max]`). */
1374
+ get estimate(): number;
1375
+ /** Reset the estimate (back to `initial`). */
1376
+ reset(): void;
1732
1377
  }
1733
1378
  /**
1734
- * Synchronous ingress handler.
1379
+ * Generate a UUIDv7 (time-ordered) string, preferring Bun's native built-in.
1380
+ * Under Node this falls back to `crypto.randomUUID` (v4).
1735
1381
  *
1736
- * The callback runs on the zero-alloc result object and MUST be synchronous:
1737
- * returning a Promise (or any thenable) throws. The result is invalidated after
1738
- * `run()` returns, so capture the fields you need inside the callback (or use
1739
- * the async {@link IngressHandler} which snapshots for you).
1382
+ * @returns A UUID string.
1740
1383
  */
1741
- export interface SyncIngressHandler {
1742
- run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, requestId: string, fn: (result: IngressResult) => T): T;
1384
+ export declare const uuidv7: () => string;
1385
+ /** Default histogram buckets (Prometheus-style, seconds). */
1386
+ export declare const DEFAULT_BUCKETS: readonly number[];
1387
+ export type Labels = Readonly<Record<string, string>>;
1388
+ /** A single labelled counter value. */
1389
+ export interface Counter {
1390
+ /** Increment by 1 (or `by`). `labels` must match the label names exactly. */
1391
+ inc(labels?: Labels, by?: number): void;
1743
1392
  }
1744
- /** Async ingress handler (wraps {@link SyncIngressHandler} with body reading). */
1745
- export type IngressHandler = (req: Request, ip?: string) => Promise<IngressContext>;
1746
- /** Mutable per-request context threaded through the pre-baked handler run. */
1747
- export interface BakedContext {
1748
- /** The request-id string (null when `emitRequestIdHeader` is off). */
1749
- requestIdHeader: string | null;
1750
- /** The `Origin` request header when CORS extraction is enabled. */
1751
- origin: string | null;
1393
+ /** A single labelled gauge value (can go up and down). */
1394
+ export interface Gauge {
1395
+ inc(labels?: Labels, by?: number): void;
1396
+ dec(labels?: Labels, by?: number): void;
1397
+ set(labels: Labels | undefined, value: number): void;
1752
1398
  }
1753
- /**
1754
- * An optimized ingress handler. `run()` is the zero-alloc pipeline entry
1755
- * point; the response-builder methods are pre-baked and bound to this
1756
- * handler's configuration, so consumers can build custom routes without
1757
- * touching header templates or error bodies.
1758
- */
1759
- export interface OptimizedIngressHandler {
1760
- run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, fn: (result: BakedIngressResult, ctx: BakedContext) => T): T;
1761
- responseHeaders(variant: number, requestIdHeader: string | null, origin: string | null, rateRemaining?: number, rateResetSecs?: number, retryAfterSecs?: number): [
1762
- string,
1763
- string
1764
- ][];
1765
- terminalHeaders(variant: number, ctx: BakedContext, result: BakedIngressResult | null): [
1766
- string,
1767
- string
1768
- ][];
1769
- /** `req` is accepted for back-compat but unused by the baked terminal path. */
1770
- terminalResponse(req: Request | undefined, result: BakedIngressResult, ctx: BakedContext): Response | null;
1771
- /** `req` is accepted for back-compat but unused by the baked error path. */
1772
- errorResponse(req: Request | undefined, result: BakedIngressResult | null, status: number, code: string, message: string, ctx: BakedContext): Response;
1773
- internalErrorResponse(ctx: BakedContext, result?: BakedIngressResult): Response;
1774
- withContentType(headers: ReadonlyArray<[
1775
- string,
1776
- string
1777
- ]>, contentType: string): [
1778
- string,
1779
- string
1780
- ][];
1399
+ /** A single labelled histogram. */
1400
+ export interface Histogram {
1401
+ /** Record one observation. `labels` must match the label names exactly. */
1402
+ observe(value: number, labels?: Labels): void;
1403
+ }
1404
+ /** The metrics registry factory. */
1405
+ export interface MetricsRegistry {
1406
+ /** Create (or fetch) a counter. `help` is only used on first creation. */
1407
+ counter(name: string, help: string, labelNames?: readonly string[]): Counter;
1408
+ /** Create (or fetch) a gauge. */
1409
+ gauge(name: string, help: string, labelNames?: readonly string[]): Gauge;
1781
1410
  /**
1782
- * Build a zero-copy `Response` whose body is the request's pooled output
1783
- * slice. The pooled buffer is returned to its pool once the body has been
1784
- * consumed (stream closed) or the request aborted. Use when `copyBody` is
1785
- * `false`; otherwise a copied body is released eagerly at the end of `run()`.
1411
+ * Create (or fetch) a histogram. `buckets`/`help` only apply on first
1412
+ * creation; later calls with the same name return the existing histogram.
1786
1413
  */
1787
- zeroCopyResponse(result: BakedIngressResult, ctx: BakedContext, init: ResponseInit): Response;
1414
+ histogram(name: string, help: string, buckets?: readonly number[], labelNames?: readonly string[]): Histogram;
1415
+ /** Render the Prometheus text exposition format. */
1416
+ render(): string;
1417
+ /** Reset all metrics (for tests / interval rotation). */
1418
+ reset(): void;
1419
+ }
1420
+ /** Create a fresh metrics registry. */
1421
+ export declare function createMetrics(): MetricsRegistry;
1422
+ /**
1423
+ * Create the runtime-appropriate ingress server: `Bun.serve` on Bun, the
1424
+ * `node:http` adapter on Node. Selected ONCE at module load — the branch
1425
+ * never runs in the hot path.
1426
+ */
1427
+ export declare function createIngressServer(options: CreateIngressServerOptions): BakedServer;
1428
+ /**
1429
+ * Generate the next request ID as 16 lowercase hex bytes (zero-alloc).
1430
+ *
1431
+ * @returns A shared buffer aliased across calls — decode/copy before the next
1432
+ * `generateRequestId()` invocation.
1433
+ */
1434
+ export declare function generateRequestId(): Uint8Array;
1435
+ /** A parsed W3C trace context (valid per the spec's length/hex rules). */
1436
+ export interface TraceContext {
1437
+ /** Version, always `"00"` for accepted headers. */
1438
+ version: string;
1439
+ /** 32 hex chars — the trace id (shared across the whole trace). */
1440
+ traceId: string;
1441
+ /** 16 hex chars — the current span id. */
1442
+ spanId: string;
1443
+ /** The flags byte (bit 0 = sampled). */
1444
+ flags: number;
1445
+ /** True when the `sampled` (bit 0) flag is set. */
1446
+ sampled: boolean;
1788
1447
  }
1448
+ /**
1449
+ * Parse a `traceparent` header value into a {@link TraceContext}, or `null`
1450
+ * when malformed (wrong version / length / non-hex). Invalid contexts are
1451
+ * ignored per the spec — callers should generate a fresh trace then.
1452
+ */
1453
+ export declare function parseTraceParent(header: string | null | undefined): TraceContext | null;
1454
+ /** Random 32-hex trace id (crypto-backed where available). */
1455
+ export declare function createTraceId(): string;
1456
+ /** Random 16-hex span id. */
1457
+ export declare function createSpanId(): string;
1458
+ /** Serialize a trace context back to a `traceparent` header value. */
1459
+ export declare function serializeTraceParent(ctx: TraceContext): string;
1789
1460
  /** Offset of the verdict byte (0 = accepted, nonzero = terminal error). */
1790
1461
  export declare const OUT_VERDICT: number;
1791
1462
  /** Offset of the error-code byte (see ERR_CODE_* below). */
@@ -1873,6 +1544,86 @@ export declare const ERR_CODE_INTERNAL: number;
1873
1544
  * numeric layout values come from the addon; this one is a JS-level error).
1874
1545
  */
1875
1546
  export declare const ERR_CODE_REQUEST_TIMEOUT: number;
1547
+ /** Map a native error code to its stable string name. */
1548
+ export declare function errorCodeName(code: number): string;
1549
+ /** Map a native error code (plus status context) to a human message. */
1550
+ export declare function errorMessage(status: number, code: number): string;
1551
+ /** A single precomputed header-variant template. */
1552
+ export interface HeaderTemplate {
1553
+ readonly entries: ReadonlyArray<readonly [
1554
+ string,
1555
+ string
1556
+ ]>;
1557
+ readonly needsOriginEcho: boolean;
1558
+ readonly needsRateDynamic: boolean;
1559
+ readonly needsRetryAfter: boolean;
1560
+ readonly needsDynamicHsts: boolean;
1561
+ }
1562
+ /** Precomputed per-handler response context. */
1563
+ export interface ResponseBuildContext {
1564
+ readonly templates: HeaderTemplate[];
1565
+ readonly corsStatic: CorsStaticStrings | null;
1566
+ readonly hstsValue: string | null;
1567
+ }
1568
+ /**
1569
+ * Build the full response context (header templates + static CORS strings +
1570
+ * HSTS value) for a handler configuration.
1571
+ */
1572
+ export declare function buildResponseContext(options: {
1573
+ cors?: CorsOptions;
1574
+ security?: SecurityHeadersOptions;
1575
+ https?: boolean;
1576
+ enableSecurityHeaders?: boolean;
1577
+ rateLimit?: {
1578
+ limit?: number;
1579
+ };
1580
+ }): ResponseBuildContext;
1581
+ /**
1582
+ * Build the response headers for a decoded result, applying the dynamic parts
1583
+ * (request-id, origin echo, rate-limit counters, retry-after, dynamic HSTS).
1584
+ */
1585
+ export declare function headersForResult(ctx: ResponseBuildContext, r: {
1586
+ readonly headerVariant: number;
1587
+ readonly corsAllowed: boolean;
1588
+ readonly rateRemaining: number;
1589
+ readonly rateResetMs: number;
1590
+ readonly retryAfterMs: number;
1591
+ readonly https: boolean;
1592
+ }, req: Request, requestId: string): Headers;
1593
+ /**
1594
+ * Build a terminal response for a result, or `null` when the result is not
1595
+ * terminal (the caller should serve the body instead).
1596
+ */
1597
+ export declare function buildTerminalResponse(ctx: ResponseBuildContext, r: {
1598
+ readonly terminal: boolean;
1599
+ readonly isPreflight: boolean;
1600
+ readonly corsAllowed: boolean;
1601
+ readonly errorCode: number;
1602
+ readonly status: number;
1603
+ readonly headerVariant: number;
1604
+ readonly https: boolean;
1605
+ readonly rateLimit: number;
1606
+ readonly rateRemaining: number;
1607
+ readonly rateResetMs: number;
1608
+ readonly retryAfterMs: number;
1609
+ }, req: Request, requestId: string): Response | null;
1610
+ /** Default maximum request body size in bytes. */
1611
+ export declare const DEFAULT_MAX_BODY_BYTES = 1048576;
1612
+ /**
1613
+ * Default overall deadline (ms) for reading a request body. Non-zero so the
1614
+ * async `createIngress` / route handlers are protected against slowloris and
1615
+ * trickling bodies by default. Set `bodyTimeoutMs: 0` to disable.
1616
+ */
1617
+ export declare const DEFAULT_BODY_TIMEOUT_MS = 30000;
1618
+ /** Maps HTTP methods to the native Ingress method-kind enum. */
1619
+ export declare const METHOD_KIND: Record<string, number>;
1620
+ /** Which request headers to extract into the packed input. */
1621
+ export interface HeaderPlan {
1622
+ cookie: boolean;
1623
+ cors: boolean;
1624
+ proxy: boolean;
1625
+ proto: boolean;
1626
+ }
1876
1627
  /**
1877
1628
  * Whether a raw status is a legal HTTP response status for the ingress
1878
1629
  * pipeline (101 switch-protocol or any 2xx–5xx).
@@ -1898,10 +1649,18 @@ export declare function safeTerminalStatus(r: {
1898
1649
  readonly isPreflight: boolean;
1899
1650
  readonly corsAllowed: boolean;
1900
1651
  }): number;
1901
- /** Map a native error code to its stable string name. */
1902
- export declare function errorCodeName(code: number): string;
1903
- /** Map a native error code (plus status context) to a human message. */
1904
- export declare function errorMessage(status: number, code: number): string;
1652
+ /**
1653
+ * Create a fast packed-input ingress handler (path 1).
1654
+ *
1655
+ * JS packs the request headers into a binary buffer (`IngressInputPacker`) and
1656
+ * the native `Ingress.handleRequestPacked` decodes them. Responses use the
1657
+ * `{"error":{...}}` wire format with `x-ratelimit-*` headers.
1658
+ *
1659
+ * Prefer this when you want the lowest-overhead pipeline and will call `run()`
1660
+ * yourself with a **synchronous** callback. For ready-made route handlers and a
1661
+ * server builder, use `createIngressHandler` (path 2).
1662
+ */
1663
+ export declare function createIngressFast(options?: IngressFastOptions): IngressFastHandler;
1905
1664
  declare function createStructuredLogger(stream?: Pick<NodeJS.WritableStream, "write">, env?: NodeJS.ProcessEnv): {
1906
1665
  /** Record one completed request. */
1907
1666
  request(info: {
@@ -1922,172 +1681,67 @@ declare function createStructuredLogger(stream?: Pick<NodeJS.WritableStream, "wr
1922
1681
  };
1923
1682
  /** Pre-encoded static error bodies, keyed by error-code string name. */
1924
1683
  export declare const ERROR_BODIES: Record<string, Uint8Array>;
1925
- /** Options accepted by the pre-baked route factories. */
1926
- export interface BakedHandlerOptions {
1927
- /** Resolve the client IP from the server object (e.g. `srv.requestIP`). */
1928
- getIp?: (req: Request, srv: unknown) => string | undefined;
1929
- /** Copy body slices instead of sharing the native buffer. Default: true (safe). */
1930
- copyBody?: boolean;
1931
- /** Maximum request body bytes for write/echo handlers. Default: 1 MiB. */
1932
- maxBodyBytes?: number;
1933
- /**
1934
- * Overall deadline (ms) for reading the request body. Default: 30s
1935
- * (`DEFAULT_BODY_TIMEOUT_MS`). Set `0` to disable. Protects against
1936
- * slowloris / trickling bodies.
1937
- */
1938
- bodyTimeoutMs?: number;
1939
- /** Fallback handler used for write error paths. Defaults to the write ingress. */
1940
- fallback?: OptimizedIngressHandler;
1941
- /**
1942
- * When true, route the JSON-validity fallback check through the higher-order
1943
- * loader (`loader("jsonValid")`) instead of the direct native call —
1944
- * exercising the loader's dispatch + counters on the real request path.
1945
- * Default: false (the direct call is marginally faster for a single request;
1946
- * the loader pays off for same-tick bursts / bulk work, see src/integration/batch.ts).
1947
- */
1948
- enableLoader?: boolean;
1949
- }
1950
1684
  /**
1951
1685
  * Pre-baked GET read handler: returns the ingress body JSON on success.
1952
1686
  */
1953
1687
  export declare function readHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1954
1688
  /**
1955
- * Pre-baked HEAD read handler: headers only, no body.
1956
- */
1957
- export declare function headHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1958
- /**
1959
- * Pre-baked JSON-write handler (POST/PUT/PATCH): enforces Content-Type,
1960
- * content-length/body-size limits, JSON validity and (optionally) schema
1961
- * validation, then returns the ingress body JSON on success.
1689
+ * Pre-baked DELETE handler: DELETE is a read-style method (no request body is
1690
+ * read), so it shares the exact pipeline flow of {@link readHandler} — it
1691
+ * returns the ingress body JSON on success and the terminal/error responses
1692
+ * otherwise. Reusing the read factory keeps the two handlers byte-identical
1693
+ * and avoids a copy-pasted variant.
1694
+ *
1695
+ * Wire it via the `delete` key of a `BakedRoute` (see `createIngressServer`).
1962
1696
  */
1963
- export declare function jsonWriteHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Promise<Response>;
1697
+ export declare const deleteHandler: typeof readHandler;
1964
1698
  /**
1965
1699
  * Pre-baked echo handler: streams the request body back with the client's
1966
1700
  * Content-Type, bounded by `maxBodyBytes`.
1967
1701
  */
1968
- export declare function echoHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Promise<Response>;
1969
- /**
1970
- * Pre-baked fallback handler: 404 for unmatched routes / OPTIONS.
1971
- */
1972
- export declare function fallbackHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1973
- /** A raw web-standard route handler (`Request` → `Response`), e.g. the
1974
- * health/metrics probes (`livenessHandler`, `readinessHandler`,
1975
- * `healthHandler`, `metricsHandler`). Accepted as `BakedRoute.read` and
1976
- * served for GET directly, outside the ingress pipeline. The optional third
1977
- * arg carries the matched dynamic path params (`:param`/`*`) on the Node
1978
- * adapter (Bun's native router handles matching; the ingress pipeline does
1979
- * not echo params in its response). */
1980
- type RouteHandler = (req: Request, srv?: unknown, params?: Record<string, string>) => Response | Promise<Response>;
1981
- /** Route spec for the Bun.serve builder. */
1982
- export interface BakedRoute {
1983
- /**
1984
- * Wires GET + HEAD read handlers. Accepts an optimized ingress handler OR a
1985
- * raw `RouteHandler` function (health/metrics probes are raw — see
1986
- * src/ingress/health.ts). A raw handler is served for GET only.
1987
- */
1988
- read?: OptimizedIngressHandler | RouteHandler;
1989
- /** Wires POST/PUT/PATCH JSON-write handlers (and OPTIONS fallback). */
1990
- write?: OptimizedIngressHandler;
1991
- /** Wires a POST echo handler. */
1992
- echo?: OptimizedIngressHandler;
1993
- /** Wires a GET read handler (cookies-style route). */
1994
- cookies?: OptimizedIngressHandler;
1995
- /** Wires a DELETE read-style handler. */
1996
- delete?: OptimizedIngressHandler;
1997
- /** Overrides `maxBodyBytes` for this route's write/echo handlers. */
1998
- maxBodyBytes?: number;
1999
- /**
2000
- * Overall deadline (ms) for reading the request body on this route's
2001
- * write/echo handlers. Default: 30_000 (`DEFAULT_BODY_TIMEOUT_MS`).
2002
- * Set 0 to disable.
2003
- */
2004
- bodyTimeoutMs?: number;
2005
- }
2006
- /** RFC 6455 handshake values returned by `CreateIngressServerOptions.upgrade`. */
2007
- export interface NodeUpgradeHandshake {
2008
- /** `Sec-WebSocket-Accept` value (compute via `rust.text.wsAcceptKey`). */
2009
- accept: string;
2010
- /** Optional negotiated subprotocol (`Sec-WebSocket-Protocol`). */
2011
- protocol?: string;
2012
- }
2013
- /** Options for {@link createIngressServer}. */
2014
- export interface CreateIngressServerOptions {
2015
- port: number;
2016
- hostname?: string;
2017
- idleTimeout?: number;
2018
- maxRequestBodySize?: number;
2019
- reusePort?: boolean;
2020
- copyBody?: boolean;
2021
- getIp?: (req: Request, srv: unknown) => string | undefined;
2022
- routes: Record<string, BakedRoute>;
2023
- fallback?: OptimizedIngressHandler;
2024
- /**
2025
- * Invoked when an unhandled error escapes a request handler (currently wired
2026
- * on the Node adapter; the Bun path uses runtime.onResponse). Never throws —
2027
- * hook failures are swallowed.
2028
- */
2029
- onError?: (info: {
2030
- error: Error;
2031
- request?: Request;
2032
- }) => void;
2033
- /** Node adapter only: ms to receive the complete request (headers + body).
2034
- * Guards slowloris/trickling requests. Default: 30_000. */
2035
- requestTimeoutMs?: number;
2036
- /** Node adapter only: ms to receive the request headers. Default: 30_000. */
2037
- headersTimeoutMs?: number;
2038
- /** Node adapter only: max requests per keep-alive socket before Node forces
2039
- * a fresh connection (bounds long-lived socket reuse). Default: 1000. */
2040
- maxRequestsPerSocket?: number;
2041
- /** Node adapter only: optional WebSocket upgrade handler. Return the RFC 6455
2042
- * handshake values (see {@link NodeUpgradeHandshake}) to complete the
2043
- * handshake on the hijacked socket; return null/undefined to decline the
2044
- * upgrade. Ignored by the Bun server. (`createWebSocketUpgrade` is Bun-only
2045
- * — Node's Response cannot carry a 101.) */
2046
- upgrade?: (req: Request) => NodeUpgradeHandshake | null | undefined;
2047
- /** Node adapter only: called after a WebSocket upgrade handshake completes
2048
- * (the 101 response was accepted), with the hijacked socket so the caller
2049
- * can attach a frame codec/message loop (e.g. the `ws` library). Ignored by
2050
- * the Bun server. */
2051
- onUpgrade?: (socket: import("node:stream").Duplex, req: unknown, head: Buffer) => void;
2052
- }
1702
+ export declare function echoHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Promise<Response>;
2053
1703
  /**
2054
- * Minimal surface of the running server that castrum relies on.
1704
+ * Pre-baked fallback handler: 404 for unmatched routes / OPTIONS.
1705
+ */
1706
+ export declare function fallbackHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1707
+ /**
1708
+ * Pre-baked HEAD read handler: headers only, no body.
1709
+ */
1710
+ export declare function headHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1711
+ /**
1712
+ * Pre-baked JSON-write handler (POST/PUT/PATCH): enforces Content-Type,
1713
+ * content-length/body-size limits, JSON validity and (optionally) schema
1714
+ * validation, then returns the ingress body JSON on success.
1715
+ */
1716
+ export declare function jsonWriteHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Promise<Response>;
1717
+ /**
1718
+ * Pre-baked OPTIONS handler: serves the native pipeline's CORS preflight
1719
+ * decision — 204 when the preflight is allowed, 403 (terminal) when denied —
1720
+ * and a plain 204 for non-preflight OPTIONS.
2055
1721
  *
2056
- * This is intentionally NOT `ReturnType<typeof Bun.serve>` so that the public
2057
- * types stay runtime-agnostic — Node.js TypeScript consumers don't need
2058
- * `@types/bun` just to import castrum's types. Bun's server exposes far more
2059
- * fields; treat the handle as opaque.
1722
+ * `createIngressServer` wires this for EVERY route that has a handler, so
1723
+ * read-only routes also answer preflights (previously OPTIONS only reached the
1724
+ * pipeline on write routes that also configured a fallback).
2060
1725
  */
2061
- export interface ServerHandle {
2062
- /** The port the server is bound to, when known (Bun exposes it; Node's
2063
- * http.Server does not — use `BakedServer.port` instead). */
2064
- port?: number;
2065
- /** Force-stop the server. Bun semantics: `true` drops active connections. */
2066
- stop(force?: boolean): void;
2067
- }
2068
- /** A running server instance plus a stop helper. */
2069
- export interface BakedServer {
2070
- server: ServerHandle;
2071
- stop(): void;
2072
- port: number;
2073
- }
2074
- export interface GracefulShutdownOptions {
2075
- /** Grace period (ms) to drain in-flight requests before force-closing. */
2076
- timeoutMs?: number;
2077
- /** Signals to listen for. Default: SIGTERM + SIGINT. */
2078
- signals?: NodeJS.Signals[];
1726
+ export declare function optionsHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1727
+ /** Options for {@link nativeResponderRoute}. */
1728
+ export interface ResponderRouteOptions extends BakedHandlerOptions {
1729
+ /** Terminal envelope style. Default: `'castrum'` (the pre-baked wire). */
1730
+ terminalStyle?: TerminalStyle;
1731
+ /**
1732
+ * Read the request body and pass it to the native pipeline for validation
1733
+ * (`requireJsonBody`/schema). Default `false` — the framework owns the body
1734
+ * (the responder reads it via `ctx.body`); native only needs the bytes when
1735
+ * a body stage is enabled in the route's `IngressHandlerOptions`.
1736
+ */
1737
+ readBody?: boolean;
2079
1738
  }
2080
1739
  /**
2081
- * Wire SIGTERM/SIGINT to a graceful shutdown: soft-stop (drain in-flight
2082
- * requests) then force-close after `timeoutMs`. Works with both the Bun and
2083
- * Node server handles (both expose `stop(force?)`).
2084
- *
2085
- * Returns a cleanup function that removes the signal listeners. Call it (or
2086
- * `process.exit`) to tear down without hanging.
1740
+ * Build a responder route: native pipeline decides + rejects (terminal
1741
+ * response in the chosen style); on success the JS `responder` builds the 2xx.
1742
+ * Returns an async `RouteHandler` (`(req, srv?, params?) => Promise<Response>`).
2087
1743
  */
2088
- export declare function gracefulShutdown(handles: ReadonlyArray<ServerHandle>, options?: GracefulShutdownOptions): () => void;
2089
- /** Build a Bun.serve config from pre-baked route handlers. */
2090
- export declare function createIngressServer(options: CreateIngressServerOptions): BakedServer;
1744
+ export declare function nativeResponderRoute(ingress: OptimizedIngressHandler, responder: NativeResponder, opts?: ResponderRouteOptions): RouteHandler;
2091
1745
  /** A Node.js ingress server: {@link BakedServer} plus an async ready signal. */
2092
1746
  export interface NodeIngressServer extends BakedServer {
2093
1747
  /**
@@ -2108,6 +1762,7 @@ export interface NodeIngressServer extends BakedServer {
2108
1762
  export declare function createIngressServerNode(options: CreateIngressServerOptions): NodeIngressServer;
2109
1763
  /** Sentinel value used by Rust to mean "rate limiting disabled". */
2110
1764
  export declare const RATE_LIMIT_U32_MAX = 4294967295;
1765
+ /** Runtime configuration for the pre-baked handler path (`createIngressHandler`). */
2111
1766
  export interface BakedIngressRuntime {
2112
1767
  /** Emit an `x-request-id` header on responses. Default: false. */
2113
1768
  emitRequestIdHeader?: boolean;
@@ -2179,100 +1834,22 @@ export interface BakedIngressRuntime {
2179
1834
  */
2180
1835
  export declare function createIngressHandler(options?: IngressHandlerOptions, runtime?: BakedIngressRuntime): OptimizedIngressHandler;
2181
1836
  /**
2182
- * Generate the next request ID as 16 lowercase hex bytes (zero-alloc).
2183
- *
2184
- * @returns A shared buffer aliased across calls — decode/copy before the next
2185
- * `generateRequestId()` invocation.
2186
- */
2187
- export declare function generateRequestId(): Uint8Array;
2188
- /** A single precomputed header-variant template. */
2189
- export interface HeaderTemplate {
2190
- readonly entries: ReadonlyArray<readonly [
2191
- string,
2192
- string
2193
- ]>;
2194
- readonly needsOriginEcho: boolean;
2195
- readonly needsRateDynamic: boolean;
2196
- readonly needsRetryAfter: boolean;
2197
- readonly needsDynamicHsts: boolean;
2198
- }
2199
- /** Precomputed per-handler response context. */
2200
- export interface ResponseBuildContext {
2201
- readonly templates: HeaderTemplate[];
2202
- readonly corsStatic: CorsStaticStrings | null;
2203
- readonly hstsValue: string | null;
2204
- }
2205
- /**
2206
- * Build the full response context (header templates + static CORS strings +
2207
- * HSTS value) for a handler configuration.
2208
- */
2209
- export declare function buildResponseContext(options: {
2210
- cors?: CorsOptions;
2211
- security?: SecurityHeadersOptions;
2212
- https?: boolean;
2213
- enableSecurityHeaders?: boolean;
2214
- rateLimit?: {
2215
- limit?: number;
2216
- };
2217
- }): ResponseBuildContext;
2218
- /**
2219
- * Build the response headers for a decoded result, applying the dynamic parts
2220
- * (request-id, origin echo, rate-limit counters, retry-after, dynamic HSTS).
2221
- */
2222
- export declare function headersForResult(ctx: ResponseBuildContext, r: {
2223
- readonly headerVariant: number;
2224
- readonly corsAllowed: boolean;
2225
- readonly rateRemaining: number;
2226
- readonly rateResetMs: number;
2227
- readonly retryAfterMs: number;
2228
- readonly https: boolean;
2229
- }, req: Request, requestId: string): Headers;
2230
- /**
2231
- * Build a terminal response for a result, or `null` when the result is not
2232
- * terminal (the caller should serve the body instead).
1837
+ * Liveness probe: `200 {"status":"ok"}` as long as the process is alive.
1838
+ * Never touches dependencies.
2233
1839
  */
2234
- export declare function buildTerminalResponse(ctx: ResponseBuildContext, r: {
2235
- readonly terminal: boolean;
2236
- readonly isPreflight: boolean;
2237
- readonly corsAllowed: boolean;
2238
- readonly errorCode: number;
2239
- readonly status: number;
2240
- readonly headerVariant: number;
2241
- readonly https: boolean;
2242
- readonly rateLimit: number;
2243
- readonly rateRemaining: number;
2244
- readonly rateResetMs: number;
2245
- readonly retryAfterMs: number;
2246
- }, req: Request, requestId: string): Response | null;
2247
- /** Default maximum request body size in bytes. */
2248
- export declare const DEFAULT_MAX_BODY_BYTES = 1048576;
1840
+ export declare function livenessHandler(): (_req: Request) => Response;
2249
1841
  /**
2250
- * Default overall deadline (ms) for reading a request body. Non-zero so the
2251
- * async `createIngress` / route handlers are protected against slowloris and
2252
- * trickling bodies by default. Set `bodyTimeoutMs: 0` to disable.
1842
+ * Readiness probe: runs the optional async `check` (dependency readiness).
1843
+ * Returns `200 {"status":"ready"}` when the check passes (or no check is
1844
+ * given), `503 {"status":"not_ready"}` when it throws or returns false.
2253
1845
  */
2254
- export declare const DEFAULT_BODY_TIMEOUT_MS = 30000;
2255
- /** Maps HTTP methods to the native Ingress method-kind enum. */
2256
- export declare const METHOD_KIND: Record<string, number>;
2257
- /** Which request headers to extract into the packed input. */
2258
- export interface HeaderPlan {
2259
- cookie: boolean;
2260
- cors: boolean;
2261
- proxy: boolean;
2262
- proto: boolean;
2263
- }
1846
+ export declare function readinessHandler(check?: () => boolean | Promise<boolean>): (_req: Request) => Promise<Response>;
2264
1847
  /**
2265
- * Create a fast packed-input ingress handler (path 1).
2266
- *
2267
- * JS packs the request headers into a binary buffer (`IngressInputPacker`) and
2268
- * the native `Ingress.handleRequestPacked` decodes them. Responses use the
2269
- * `{"error":{...}}` wire format with `x-ratelimit-*` headers.
2270
- *
2271
- * Prefer this when you want the lowest-overhead pipeline and will call `run()`
2272
- * yourself with a **synchronous** callback. For ready-made route handlers and a
2273
- * server builder, use `createIngressHandler` (path 2).
1848
+ * Combined health probe: liveness by default, plus an optional readiness
1849
+ * `check`. When a `check` is provided the response is 503 on failure
1850
+ * (readiness semantics), otherwise always 200.
2274
1851
  */
2275
- export declare function createIngressFast(options?: IngressFastOptions): IngressFastHandler;
1852
+ export declare function healthHandler(check?: () => boolean | Promise<boolean>): ((_req: Request) => Response) | ((_req: Request) => Promise<Response>);
2276
1853
  /** The runtime hooks + registry for ingress metrics. */
2277
1854
  export interface IngressMetrics {
2278
1855
  registry: MetricsRegistry;
@@ -2293,48 +1870,112 @@ export declare function createIngressMetrics(): IngressMetrics;
2293
1870
  * createIngressServer({ routes: { "/metrics": { read: metricsHandler(m) } } })
2294
1871
  */
2295
1872
  export declare function metricsHandler(metrics: IngressMetrics): (_req: Request) => Response;
2296
- /**
2297
- * Liveness probe: `200 {"status":"ok"}` as long as the process is alive.
2298
- * Never touches dependencies.
2299
- */
2300
- export declare function livenessHandler(): (_req: Request) => Response;
2301
- /**
2302
- * Readiness probe: runs the optional async `check` (dependency readiness).
2303
- * Returns `200 {"status":"ready"}` when the check passes (or no check is
2304
- * given), `503 {"status":"not_ready"}` when it throws or returns false.
2305
- */
2306
- export declare function readinessHandler(check?: () => boolean | Promise<boolean>): (_req: Request) => Promise<Response>;
2307
- /**
2308
- * Combined health probe: liveness by default, plus an optional readiness
2309
- * `check`. When a `check` is provided the response is 503 on failure
2310
- * (readiness semantics), otherwise always 200.
2311
- */
2312
- export declare function healthHandler(check?: () => boolean | Promise<boolean>): ((_req: Request) => Response) | ((_req: Request) => Promise<Response>);
2313
- /** A parsed W3C trace context (valid per the spec's length/hex rules). */
2314
- export interface TraceContext {
2315
- /** Version, always `"00"` for accepted headers. */
2316
- version: string;
2317
- /** 32 hex chars — the trace id (shared across the whole trace). */
2318
- traceId: string;
2319
- /** 16 hex chars — the current span id. */
2320
- spanId: string;
2321
- /** The flags byte (bit 0 = sampled). */
2322
- flags: number;
2323
- /** True when the `sampled` (bit 0) flag is set. */
2324
- sampled: boolean;
1873
+ /** Per-route spec for {@link createIngressRouter}. */
1874
+ export interface RouterRouteSpec {
1875
+ /**
1876
+ * Per-route ingress options — compiled into a DEDICATED native `IngressInner`
1877
+ * for this route (parseCookies, parseQuery, schema, cors, rateLimit, limits,
1878
+ * requireJsonBody, ...). This is what makes the pipeline prune per route.
1879
+ */
1880
+ options?: IngressHandlerOptions;
1881
+ /** Wire GET + HEAD read handlers over this route's compiled handler. */
1882
+ read?: boolean;
1883
+ /** Wire POST/PUT/PATCH JSON-write handlers over this route's compiled handler. */
1884
+ write?: boolean;
1885
+ /** Wire a POST echo handler over this route's compiled handler. */
1886
+ echo?: boolean;
1887
+ /** Wire a GET read handler (cookies-style) over this route's compiled handler. */
1888
+ cookies?: boolean;
1889
+ /** Wire a DELETE read-style handler over this route's compiled handler. */
1890
+ delete?: boolean;
1891
+ /**
1892
+ * A JS responder route: the native pipeline decides + rejects (terminal
1893
+ * response in {@link terminalStyle}); on success the responder builds the
1894
+ * 2xx body (async OK) from a decoded snapshot. Wired for `methods`
1895
+ * (default `['GET']`). When set, the standard `read`/`write`/etc. flags for
1896
+ * this route are ignored.
1897
+ */
1898
+ responder?: {
1899
+ handler: NativeResponder;
1900
+ /** HTTP methods to wire (default `['GET']`). */
1901
+ methods?: ReadonlyArray<string>;
1902
+ /** Read the body for native validation (default false — framework owns it). */
1903
+ readBody?: boolean;
1904
+ };
1905
+ /** Terminal envelope style for this route's responder (default: router-level
1906
+ * `terminalStyle` or `'castrum'`). */
1907
+ terminalStyle?: TerminalStyle;
1908
+ /**
1909
+ * A raw request→Response handler served directly for GET, OUTSIDE the
1910
+ * ingress pipeline (health/metrics probes, /metrics). When set, `read`/
1911
+ * `write`/etc. for this route are ignored.
1912
+ */
1913
+ raw?: RouteHandler;
1914
+ /** Overrides `maxBodyBytes` for this route's write/echo handlers. */
1915
+ maxBodyBytes?: number;
1916
+ /** Overrides `bodyTimeoutMs` for this route's write/echo handlers. */
1917
+ bodyTimeoutMs?: number;
1918
+ }
1919
+ /** Options for {@link createIngressRouter}. */
1920
+ export interface CreateIngressRouterOptions {
1921
+ /** Route table: path → per-route spec. */
1922
+ routes: Record<string, RouterRouteSpec>;
1923
+ /** Shared runtime hooks (onRequest/onResponse/onError, security headers,
1924
+ * output buffer size) applied to EVERY compiled route handler. */
1925
+ runtime?: BakedIngressRuntime;
1926
+ /** Shared `getIp` resolver for route handlers. */
1927
+ getIp?: (req: Request, srv: unknown) => string | undefined;
1928
+ /** Shared `copyBody` default for route handlers. */
1929
+ copyBody?: boolean;
1930
+ /** Default terminal envelope style for responder routes (`'castrum'`). */
1931
+ terminalStyle?: TerminalStyle;
1932
+ /** Pre-warm every compiled route at construction (JIT the packed pipeline +
1933
+ * the FFI ingress call before the first real request). Default: false. */
1934
+ warmOnCreate?: boolean;
1935
+ }
1936
+ /** A compiled per-route router. */
1937
+ export interface IngressRouter {
1938
+ /** The per-route compiled handlers keyed by path (for custom route wiring). */
1939
+ routeHandlers: Record<string, OptimizedIngressHandler>;
1940
+ /** The route → method → handler map (compatible with Bun.serve `routes` and
1941
+ * `createIngressServerNode`). */
1942
+ routes: Record<string, Record<string, unknown>>;
1943
+ /** The path matcher (`:param`/`*` dynamic routes). */
1944
+ match: (pathname: string) => PathMatch | undefined;
1945
+ /** A fetch-style dispatcher: match path + method → the route's handler. */
1946
+ fetch: (req: Request, srv?: unknown) => Response | Promise<Response>;
1947
+ /** Pre-warm every compiled route (JIT the packed pipeline + FFI call). */
1948
+ prewarm: () => void;
2325
1949
  }
2326
1950
  /**
2327
- * Parse a `traceparent` header value into a {@link TraceContext}, or `null`
2328
- * when malformed (wrong version / length / non-hex). Invalid contexts are
2329
- * ignored per the spec — callers should generate a fresh trace then.
1951
+ * Compile a route table into per-route native ingress instances.
1952
+ *
1953
+ * Each route with a pipeline-backed spec (`read`/`write`/`echo`/`cookies`/
1954
+ * `delete`) compiles its OWN `createIngressHandler(options)` — a dedicated
1955
+ * `IngressInner` pruned to that route's stages + a per-route header plan.
1956
+ * Routes that need nothing (a bare `read` with no cookies/query/cors) therefore
1957
+ * gather zero headers and run a near-empty native pipeline. All routes share
1958
+ * the same wire format and the shared process-wide rate-limiter budgets.
1959
+ *
1960
+ * @example
1961
+ * ```ts
1962
+ * const router = createIngressRouter({
1963
+ * warmOnCreate: true,
1964
+ * runtime: ingressMetrics?.runtime,
1965
+ * routes: {
1966
+ * '/health': { read: true, options: { parseCookies: false, parseQuery: false } },
1967
+ * '/api/users': {
1968
+ * read: true,
1969
+ * write: true,
1970
+ * options: { parseCookies: true, parseQuery: true, schema: USER_SCHEMA_BYTES },
1971
+ * },
1972
+ * '/metrics': { raw: metricsHandler(ingressMetrics) },
1973
+ * },
1974
+ * })
1975
+ * const server = Bun.serve({ routes: router.routes }) // or router.fetch
1976
+ * ```
2330
1977
  */
2331
- export declare function parseTraceParent(header: string | null | undefined): TraceContext | null;
2332
- /** Random 32-hex trace id (crypto-backed where available). */
2333
- export declare function createTraceId(): string;
2334
- /** Random 16-hex span id. */
2335
- export declare function createSpanId(): string;
2336
- /** Serialize a trace context back to a `traceparent` header value. */
2337
- export declare function serializeTraceParent(ctx: TraceContext): string;
1978
+ export declare function createIngressRouter(options: CreateIngressRouterOptions): IngressRouter;
2338
1979
  /**
2339
1980
  * Synchronous convenience wrapper over `createIngressFast` (path 1).
2340
1981
  *
@@ -2373,6 +2014,7 @@ export interface PipelineContext {
2373
2014
  /** Mutable per-request storage for middleware/user state. */
2374
2015
  readonly locals: Map<string, unknown>;
2375
2016
  }
2017
+ /** Result of running `preprocess`: terminal short-circuit or pass-through. */
2376
2018
  export interface PreprocessOutcome {
2377
2019
  /** True when the pipeline short-circuited (error/denied) — serve `response`. */
2378
2020
  readonly terminal: boolean;
@@ -2380,6 +2022,7 @@ export interface PreprocessOutcome {
2380
2022
  readonly result: PipelineResult | null;
2381
2023
  readonly ctx: PipelineContext;
2382
2024
  }
2025
+ /** Options for `createPipeline`. */
2383
2026
  export interface CreatePipelineOptions {
2384
2027
  /** Ingress options (same surface as `createIngressHandler`). */
2385
2028
  options?: IngressHandlerOptions;
@@ -2400,6 +2043,7 @@ export interface CreatePipelineOptions {
2400
2043
  */
2401
2044
  render?: (result: PipelineResult, ctx: PipelineContext) => Response | Promise<Response>;
2402
2045
  }
2046
+ /** The composed ingress pipeline: preprocess / handleRequest / readBody. */
2403
2047
  export interface IngressPipeline {
2404
2048
  /** The underlying pre-baked handler (custom route factories / responses). */
2405
2049
  readonly ingress: OptimizedIngressHandler;
@@ -2429,49 +2073,7 @@ export interface IngressPipeline {
2429
2073
  * ```
2430
2074
  */
2431
2075
  export declare function createPipeline(opts?: CreatePipelineOptions): IngressPipeline;
2432
- export interface WebSocketUpgradeOptions {
2433
- /** Subprotocols this server supports; the first client-requested match wins. */
2434
- protocols?: ReadonlyArray<string>;
2435
- }
2436
- export interface WebSocketUpgradeResult {
2437
- /** The 101 Switching Protocols response — return it from your fetch handler. */
2438
- readonly response: Response;
2439
- /** The client's `Sec-WebSocket-Key` (handy for connection logging). */
2440
- readonly key: string;
2441
- /** The negotiated subprotocol, if any. */
2442
- readonly protocol: string | null;
2443
- }
2444
- /**
2445
- * Build a WebSocket 101 upgrade handshake response for a request.
2446
- *
2447
- * Validates `Sec-WebSocket-Key` presence and computes the RFC 6455 accept key
2448
- * via the native `rust.wsAcceptKey`, optionally negotiates a subprotocol, and
2449
- * returns a ready-to-serve `Response`. Returns `null` when the request is not a
2450
- * valid upgrade (missing/empty key).
2451
- *
2452
- * This only produces the handshake — pair it with your framework's own
2453
- * WebSocket server (Bun.serve's `websocket` handler, or a WS library), which
2454
- * owns the subsequent frames:
2455
- *
2456
- * @example
2457
- * ```ts
2458
- * const srv = Bun.serve({
2459
- * port: 3000,
2460
- * fetch(req, server) {
2461
- * const up = createWebSocketUpgrade(req, { protocols: ["chat"] });
2462
- * if (up && server.upgrade(req, { data: { protocol: up.protocol } })) {
2463
- * return up.response;
2464
- * }
2465
- * return new Response("Not a websocket", { status: 400 });
2466
- * },
2467
- * websocket: {
2468
- * message(ws, msg) { ws.send(msg); },
2469
- * },
2470
- * });
2471
- * ```
2472
- */
2473
- export declare function createWebSocketUpgrade(req: Request, opts?: WebSocketUpgradeOptions): WebSocketUpgradeResult | null;
2474
- export interface SseEvent {
2076
+ /** One SSE event to frame via `sseResponse` (event/id/retry/data). */ export interface SseEvent {
2475
2077
  /** Optional `event:` field. */
2476
2078
  event?: string | null;
2477
2079
  /** Optional `id:` field. */
@@ -2802,7 +2404,7 @@ export declare const LOADER_OPS: {
2802
2404
  };
2803
2405
  readonly hexEncode: {
2804
2406
  readonly kind: "bytes";
2805
- readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2407
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2806
2408
  readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2807
2409
  readonly element: typeof byteElem;
2808
2410
  };
@@ -2814,7 +2416,7 @@ export declare const LOADER_OPS: {
2814
2416
  };
2815
2417
  readonly base64Encode: {
2816
2418
  readonly kind: "bytes";
2817
- readonly scalar: (i: Uint8Array, urlSafe?: boolean, padding?: boolean) => Uint8Array<ArrayBufferLike>;
2419
+ readonly scalar: (i: Uint8Array, urlSafe?: boolean, padding?: boolean) => string | Uint8Array<ArrayBufferLike>;
2818
2420
  readonly batch: (items: Uint8Array[], urlSafe?: boolean, padding?: boolean) => Uint8Array<ArrayBufferLike>[];
2819
2421
  readonly element: typeof byteElem;
2820
2422
  };
@@ -2826,7 +2428,7 @@ export declare const LOADER_OPS: {
2826
2428
  };
2827
2429
  readonly base64UrlEncode: {
2828
2430
  readonly kind: "bytes";
2829
- readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2431
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2830
2432
  readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2831
2433
  readonly element: typeof byteElem;
2832
2434
  };
@@ -2862,13 +2464,13 @@ export declare const LOADER_OPS: {
2862
2464
  };
2863
2465
  readonly etag: {
2864
2466
  readonly kind: "bytes";
2865
- readonly scalar: (i: Uint8Array, weak?: boolean | null) => Uint8Array<ArrayBufferLike>;
2467
+ readonly scalar: (i: Uint8Array, weak?: boolean | null) => string | Uint8Array<ArrayBufferLike>;
2866
2468
  readonly batch: (items: Uint8Array[], weak?: boolean | null) => Uint8Array<ArrayBufferLike>[];
2867
2469
  readonly element: typeof byteElem;
2868
2470
  };
2869
2471
  readonly urlEncode: {
2870
2472
  readonly kind: "bytes";
2871
- readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2473
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2872
2474
  readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2873
2475
  readonly element: typeof byteElem;
2874
2476
  };
@@ -2886,19 +2488,19 @@ export declare const LOADER_OPS: {
2886
2488
  };
2887
2489
  readonly wsAcceptKey: {
2888
2490
  readonly kind: "bytes";
2889
- readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2491
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2890
2492
  readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2891
2493
  readonly element: typeof byteElem;
2892
2494
  };
2893
2495
  readonly mimeFromExtension: {
2894
2496
  readonly kind: "bytes";
2895
- readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2497
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2896
2498
  readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2897
2499
  readonly element: typeof byteElem;
2898
2500
  };
2899
2501
  readonly signCookie: {
2900
2502
  readonly kind: "bytes";
2901
- readonly scalar: (i: Uint8Array, secret: Uint8Array) => Uint8Array<ArrayBufferLike>;
2503
+ readonly scalar: (i: Uint8Array, secret: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2902
2504
  readonly batch: (items: Uint8Array[], secret: Uint8Array) => Uint8Array<ArrayBufferLike>[];
2903
2505
  readonly element: typeof byteElem;
2904
2506
  };
@@ -2916,7 +2518,7 @@ export declare const LOADER_OPS: {
2916
2518
  };
2917
2519
  readonly passwordHash: {
2918
2520
  readonly kind: "bytes";
2919
- readonly scalar: (i: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null) => Uint8Array<ArrayBufferLike>;
2521
+ readonly scalar: (i: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null) => string | Uint8Array<ArrayBufferLike>;
2920
2522
  readonly batch: (items: Uint8Array[], salt: Uint8Array, options?: PasswordHashOptions | null) => Uint8Array<ArrayBufferLike>[];
2921
2523
  readonly element: typeof byteElem;
2922
2524
  };
@@ -2958,7 +2560,7 @@ export declare const LOADER_OPS: {
2958
2560
  readonly pairedRest: [
2959
2561
  0
2960
2562
  ];
2961
- readonly scalar: (i: Uint8Array, patch: Uint8Array) => Uint8Array<ArrayBufferLike>;
2563
+ readonly scalar: (i: Uint8Array, patch: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2962
2564
  readonly batch: (items: Uint8Array[], patches: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2963
2565
  readonly element: typeof byteElem;
2964
2566
  };
@@ -2967,7 +2569,7 @@ export declare const LOADER_OPS: {
2967
2569
  readonly pairedRest: [
2968
2570
  0
2969
2571
  ];
2970
- readonly scalar: (i: Uint8Array, base: Uint8Array) => Uint8Array<ArrayBufferLike>;
2572
+ readonly scalar: (i: Uint8Array, base: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2971
2573
  readonly batch: (items: Uint8Array[], bases: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2972
2574
  readonly element: typeof byteElem;
2973
2575
  };
@@ -2991,7 +2593,7 @@ export declare const LOADER_OPS: {
2991
2593
  };
2992
2594
  readonly hmacSha256: {
2993
2595
  readonly kind: "bytes";
2994
- readonly scalar: (i: Uint8Array, key: Uint8Array) => Uint8Array<ArrayBufferLike>;
2596
+ readonly scalar: (i: Uint8Array, key: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2995
2597
  readonly batch: (items: Uint8Array[], key: Uint8Array) => Uint8Array<ArrayBufferLike>[];
2996
2598
  readonly element: typeof byteElem;
2997
2599
  };