@nifrajs/cli 2.8.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/mcp-http.js +1 -1
- package/dist/scaffold.d.ts.map +1 -1
- package/dist/scaffold.js +34 -1
- package/dist/scaffold.js.map +1 -1
- package/docs/examples.json +9 -3
- package/docs/llms-full.txt +219 -45
- package/docs/types.json +177 -15
- package/package.json +9 -9
- package/src/cli.ts +1 -1
- package/src/mcp-http.ts +1 -1
- package/src/scaffold.ts +34 -1
package/docs/types.json
CHANGED
|
@@ -393,6 +393,13 @@
|
|
|
393
393
|
"signature": "export declare function assertStorageAdapterConformance(options: StorageAdapterConformanceOptions): Promise<void>;",
|
|
394
394
|
"doc": "/**\n * Execute the observable {@link StorageAdapter} contract without depending on a test runner.\n *\n * The adapter must be isolated because this writes deterministic conformance keys. The promise resolves\n * only after proving byte + metadata round-trips, overwrite, missing/delete semantics, prefix/limit listing,\n * and uniform unsafe-key rejection across every key-taking method. When the adapter also implements an\n * optional capability ({@link PagedStorageAdapter}, {@link PresignableStorageAdapter},\n * {@link MovableStorageAdapter}), that capability's contract is proven too - implementing a capability\n * partially or unsafely fails conformance rather than silently escaping it.\n */"
|
|
395
395
|
},
|
|
396
|
+
{
|
|
397
|
+
"name": "assertTransportTextBounded",
|
|
398
|
+
"kind": "function",
|
|
399
|
+
"package": "@nifrajs/core",
|
|
400
|
+
"signature": "export declare function assertTransportTextBounded(text: string, options: TransportDecodeOptions): void;",
|
|
401
|
+
"doc": "/**\n * Enforce the transport byte cap on already-read text - the same limit (and the same error) the\n * streaming reader applies during a bounded read. Exported for callers that read a body through a\n * native, non-streaming path (the typed client's in-process branch) and still owe the cap contract.\n */"
|
|
402
|
+
},
|
|
396
403
|
{
|
|
397
404
|
"name": "AssuranceConfig",
|
|
398
405
|
"kind": "interface",
|
|
@@ -1972,7 +1979,7 @@
|
|
|
1972
1979
|
"kind": "function",
|
|
1973
1980
|
"package": "@nifrajs/middleware",
|
|
1974
1981
|
"signature": "export declare function compression(options?: CompressionOptions): import(\"@nifrajs/core/server\").NifraPlugin<import(\"@nifrajs/core/server\").AnyServer, import(\"@nifrajs/core/server\").AnyServer>;",
|
|
1975
|
-
"doc": "/**\n * Transparently **gzip** responses when the client sends `Accept-Encoding: gzip` and the body is a\n * compressible type larger than `threshold`. Uses the Web-standard `CompressionStream
|
|
1982
|
+
"doc": "/**\n * Transparently **gzip** responses when the client sends `Accept-Encoding: gzip` and the body is a\n * compressible type larger than `threshold`. Uses the Web-standard `CompressionStream`, so it runs\n * on every nifra runtime including the edge; gzip is the one encoding `CompressionStream`\n * guarantees everywhere, so brotli isn't offered.\n *\n * Built on the portable `onResponseBody` tier for framework-serialized bytes, with a stream-safe raw\n * fallback for handler-returned/proxied Responses. The common JSON path stays on Node's direct\n * writer; raw streams are compressed incrementally without being fully buffered.\n *\n * Skips: clients that don't accept gzip, already-encoded responses, bodyless responses,\n * `Range` responses (206 / `Content-Range`), `Cache-Control: no-transform`, non-compressible\n * types, and bodies below `threshold` (gzip's ~20-byte overhead would enlarge them). Adds\n * `Vary: Accept-Encoding`.\n *\n * ```ts\n * app.use(compression())\n * ```\n */"
|
|
1976
1983
|
},
|
|
1977
1984
|
{
|
|
1978
1985
|
"name": "CompressionOptions",
|
|
@@ -2078,14 +2085,14 @@
|
|
|
2078
2085
|
"name": "Context",
|
|
2079
2086
|
"kind": "interface",
|
|
2080
2087
|
"package": "@nifrajs/core",
|
|
2081
|
-
"signature": "export interface Context<Path extends string = string, S extends RouteSchema = RouteSchema> {\n readonly req: Request;\n /**\n * Alias of {@link req} - the same `Request`. Page loaders/actions receive their request as `request`;\n * this alias lets route handlers and loaders share one name, so `c.request` and `ctx.req` both work\n * everywhere (no more `c.req` vs `ctx.request` mismatch).\n */\n readonly request: Request;\n readonly params: ParamsOf<S, Path>;\n readonly query: QueryOf<S>;\n readonly body: BodyOf<S>;\n /** The request's cookies, parsed from the `Cookie` header (values URL-decoded). Parsed lazily on\n * first access + cached. Signed cookies arrive as `value.signature` - verify with `unsignValue`. */\n readonly cookies: Readonly<Record<string, string>>;\n readonly set: ResponseControls;\n /**\n * Aborts when the server's `requestTimeoutMs` elapses (and never, when no timeout\n * is configured). Pass it to cancellation-aware work - DB drivers, `fetch` - so a\n * timed-out request stops doing work instead of running on after the 503.\n */\n readonly signal: AbortSignal;\n /**\n * Absolute request deadline plus monotonic remaining time. It shares {@link signal}; the server\n * clamps an inbound deadline to local policy when `acceptInboundDeadlines` is enabled.\n */\n readonly budget: RequestBudget;\n /**\n * Platform bindings from `app.fetch(request, { env })` - Workers `env` (KV/D1/secrets), etc.\n * `undefined` off-edge (Bun/Node/Deno). Declare the shape with `server<Env>()` to read it typed\n * (`c.env: Env`); otherwise `unknown`. Validate at the trust boundary before use either way.\n */\n readonly env: unknown;\n /**\n * The caller's IP. By default the raw socket peer the serving adapter observed (`listen()`,\n * `@nifrajs/node`, `@nifrajs/deno`) - the one address a client cannot forge - or `undefined` when the\n * runtime exposes no socket (Workers) and no trust is declared. Behind a proxy/CDN, set the\n * `clientIp` server option (`{ trustedHops }` or `{ header }`) to derive the real caller from the\n * forwarding chain as far as you trust it; unset, no forwarded header is ever believed. Safe to key\n * rate limits and audit logs on.\n */\n readonly clientIp: string | undefined;\n /**\n * Schedule background work. On edge runtimes it extends the response lifetime (Workers\n * `ctx.waitUntil`); off-edge it runs the promise fire-and-forget (a rejection is swallowed,\n * never an unhandled rejection).\n */\n readonly waitUntil: (promise: Promise<unknown>) => void;\n /**\n * Read the raw request body as bytes, **capped** at `maxBytes` (default: the server's\n * `maxBodyBytes`). For routes with **no body schema** - raw bodies, file uploads,\n * BYO-validation - where the automatic schema cap doesn't apply. An over-cap body (by\n * `Content-Length` or while streaming) throws a flat `413`; a malformed `Content-Length`\n * throws `400`. Consumes the body stream (call once). Pass a larger `maxBytes` for an\n * upload route, a smaller one to tighten a specific endpoint.\n */\n readonly boundedBody: (maxBytes?: number) => Promise<Uint8Array>;\n /**\n * `boundedBody` + `JSON.parse` (UTF-8). Same cap + `413`/`400` semantics; additionally\n * throws a flat `400` on invalid JSON. Use for a schema-less JSON endpoint that still\n * wants the body bounded.\n */\n readonly boundedJson: <T = unknown>(maxBytes?: number) => Promise<T>;\n /**\n * Build a JSON `Response`. Pass a status number or a full `ResponseInit` as the second arg. `return` it\n * from a handler, or `throw` it from `derive`/`beforeHandle` to short-circuit - both work:\n * `throw c.json({ error: \"unauthorized\" }, 401)`. A terser alternative to\n * `new Response(JSON.stringify(...), { status, headers: { \"content-type\": \"application/json\" } })`.\n */\n readonly json: (body: unknown, init?: ResponseInit | number) => Response;\n /** Build a `text/plain; charset=utf-8` `Response`. Like {@link json}, pass a status or `ResponseInit`. */\n readonly text: (body: string, init?: ResponseInit | number) => Response;\n}",
|
|
2088
|
+
"signature": "export interface Context<Path extends string = string, S extends RouteSchema = RouteSchema> {\n readonly req: Request;\n /**\n * Alias of {@link req} - the same `Request`. Page loaders/actions receive their request as `request`;\n * this alias lets route handlers and loaders share one name, so `c.request` and `ctx.req` both work\n * everywhere (no more `c.req` vs `ctx.request` mismatch).\n */\n readonly request: Request;\n /** Read one request header without materializing a Web `Request` on the Node adapter hot path. */\n readonly header: (name: string) => string | null;\n readonly params: ParamsOf<S, Path>;\n readonly query: QueryOf<S>;\n readonly body: BodyOf<S>;\n /** The request's cookies, parsed from the `Cookie` header (values URL-decoded). Parsed lazily on\n * first access + cached. Signed cookies arrive as `value.signature` - verify with `unsignValue`. */\n readonly cookies: Readonly<Record<string, string>>;\n readonly set: ResponseControls;\n /**\n * Aborts when the server's `requestTimeoutMs` elapses (and never, when no timeout\n * is configured). Pass it to cancellation-aware work - DB drivers, `fetch` - so a\n * timed-out request stops doing work instead of running on after the 503.\n */\n readonly signal: AbortSignal;\n /**\n * Absolute request deadline plus monotonic remaining time. It shares {@link signal}; the server\n * clamps an inbound deadline to local policy when `acceptInboundDeadlines` is enabled.\n */\n readonly budget: RequestBudget;\n /**\n * Platform bindings from `app.fetch(request, { env })` - Workers `env` (KV/D1/secrets), etc.\n * `undefined` off-edge (Bun/Node/Deno). Declare the shape with `server<Env>()` to read it typed\n * (`c.env: Env`); otherwise `unknown`. Validate at the trust boundary before use either way.\n */\n readonly env: unknown;\n /**\n * The caller's IP. By default the raw socket peer the serving adapter observed (`listen()`,\n * `@nifrajs/node`, `@nifrajs/deno`) - the one address a client cannot forge - or `undefined` when the\n * runtime exposes no socket (Workers) and no trust is declared. Behind a proxy/CDN, set the\n * `clientIp` server option (`{ trustedHops }` or `{ header }`) to derive the real caller from the\n * forwarding chain as far as you trust it; unset, no forwarded header is ever believed. Safe to key\n * rate limits and audit logs on.\n */\n readonly clientIp: string | undefined;\n /**\n * Schedule background work. On edge runtimes it extends the response lifetime (Workers\n * `ctx.waitUntil`); off-edge it runs the promise fire-and-forget (a rejection is swallowed,\n * never an unhandled rejection).\n */\n readonly waitUntil: (promise: Promise<unknown>) => void;\n /**\n * Read the raw request body as bytes, **capped** at `maxBytes` (default: the server's\n * `maxBodyBytes`). For routes with **no body schema** - raw bodies, file uploads,\n * BYO-validation - where the automatic schema cap doesn't apply. An over-cap body (by\n * `Content-Length` or while streaming) throws a flat `413`; a malformed `Content-Length`\n * throws `400`. Consumes the body stream (call once). Pass a larger `maxBytes` for an\n * upload route, a smaller one to tighten a specific endpoint.\n */\n readonly boundedBody: (maxBytes?: number) => Promise<Uint8Array>;\n /**\n * `boundedBody` + `JSON.parse` (UTF-8). Same cap + `413`/`400` semantics; additionally\n * throws a flat `400` on invalid JSON. Use for a schema-less JSON endpoint that still\n * wants the body bounded.\n */\n readonly boundedJson: <T = unknown>(maxBytes?: number) => Promise<T>;\n /**\n * Build a JSON `Response`. Pass a status number or a full `ResponseInit` as the second arg. `return` it\n * from a handler, or `throw` it from `derive`/`beforeHandle` to short-circuit - both work:\n * `throw c.json({ error: \"unauthorized\" }, 401)`. A terser alternative to\n * `new Response(JSON.stringify(...), { status, headers: { \"content-type\": \"application/json\" } })`.\n */\n readonly json: (body: unknown, init?: ResponseInit | number) => Response;\n /** Build a `text/plain; charset=utf-8` `Response`. Like {@link json}, pass a status or `ResponseInit`. */\n readonly text: (body: string, init?: ResponseInit | number) => Response;\n}",
|
|
2082
2089
|
"doc": "/**\n * Handler context. `params` are inferred from the path; `body` and `query` are\n * the validated outputs of their schemas when declared (else `undefined` /\n * raw `URLSearchParams`).\n */"
|
|
2083
2090
|
},
|
|
2084
2091
|
{
|
|
2085
2092
|
"name": "Context",
|
|
2086
2093
|
"kind": "interface",
|
|
2087
2094
|
"package": "nifra",
|
|
2088
|
-
"signature": "export interface Context<Path extends string = string, S extends RouteSchema = RouteSchema> {\n readonly req: Request;\n /**\n * Alias of {@link req} - the same `Request`. Page loaders/actions receive their request as `request`;\n * this alias lets route handlers and loaders share one name, so `c.request` and `ctx.req` both work\n * everywhere (no more `c.req` vs `ctx.request` mismatch).\n */\n readonly request: Request;\n readonly params: ParamsOf<S, Path>;\n readonly query: QueryOf<S>;\n readonly body: BodyOf<S>;\n /** The request's cookies, parsed from the `Cookie` header (values URL-decoded). Parsed lazily on\n * first access + cached. Signed cookies arrive as `value.signature` - verify with `unsignValue`. */\n readonly cookies: Readonly<Record<string, string>>;\n readonly set: ResponseControls;\n /**\n * Aborts when the server's `requestTimeoutMs` elapses (and never, when no timeout\n * is configured). Pass it to cancellation-aware work - DB drivers, `fetch` - so a\n * timed-out request stops doing work instead of running on after the 503.\n */\n readonly signal: AbortSignal;\n /**\n * Absolute request deadline plus monotonic remaining time. It shares {@link signal}; the server\n * clamps an inbound deadline to local policy when `acceptInboundDeadlines` is enabled.\n */\n readonly budget: RequestBudget;\n /**\n * Platform bindings from `app.fetch(request, { env })` - Workers `env` (KV/D1/secrets), etc.\n * `undefined` off-edge (Bun/Node/Deno). Declare the shape with `server<Env>()` to read it typed\n * (`c.env: Env`); otherwise `unknown`. Validate at the trust boundary before use either way.\n */\n readonly env: unknown;\n /**\n * The caller's IP. By default the raw socket peer the serving adapter observed (`listen()`,\n * `@nifrajs/node`, `@nifrajs/deno`) - the one address a client cannot forge - or `undefined` when the\n * runtime exposes no socket (Workers) and no trust is declared. Behind a proxy/CDN, set the\n * `clientIp` server option (`{ trustedHops }` or `{ header }`) to derive the real caller from the\n * forwarding chain as far as you trust it; unset, no forwarded header is ever believed. Safe to key\n * rate limits and audit logs on.\n */\n readonly clientIp: string | undefined;\n /**\n * Schedule background work. On edge runtimes it extends the response lifetime (Workers\n * `ctx.waitUntil`); off-edge it runs the promise fire-and-forget (a rejection is swallowed,\n * never an unhandled rejection).\n */\n readonly waitUntil: (promise: Promise<unknown>) => void;\n /**\n * Read the raw request body as bytes, **capped** at `maxBytes` (default: the server's\n * `maxBodyBytes`). For routes with **no body schema** - raw bodies, file uploads,\n * BYO-validation - where the automatic schema cap doesn't apply. An over-cap body (by\n * `Content-Length` or while streaming) throws a flat `413`; a malformed `Content-Length`\n * throws `400`. Consumes the body stream (call once). Pass a larger `maxBytes` for an\n * upload route, a smaller one to tighten a specific endpoint.\n */\n readonly boundedBody: (maxBytes?: number) => Promise<Uint8Array>;\n /**\n * `boundedBody` + `JSON.parse` (UTF-8). Same cap + `413`/`400` semantics; additionally\n * throws a flat `400` on invalid JSON. Use for a schema-less JSON endpoint that still\n * wants the body bounded.\n */\n readonly boundedJson: <T = unknown>(maxBytes?: number) => Promise<T>;\n /**\n * Build a JSON `Response`. Pass a status number or a full `ResponseInit` as the second arg. `return` it\n * from a handler, or `throw` it from `derive`/`beforeHandle` to short-circuit - both work:\n * `throw c.json({ error: \"unauthorized\" }, 401)`. A terser alternative to\n * `new Response(JSON.stringify(...), { status, headers: { \"content-type\": \"application/json\" } })`.\n */\n readonly json: (body: unknown, init?: ResponseInit | number) => Response;\n /** Build a `text/plain; charset=utf-8` `Response`. Like {@link json}, pass a status or `ResponseInit`. */\n readonly text: (body: string, init?: ResponseInit | number) => Response;\n}",
|
|
2095
|
+
"signature": "export interface Context<Path extends string = string, S extends RouteSchema = RouteSchema> {\n readonly req: Request;\n /**\n * Alias of {@link req} - the same `Request`. Page loaders/actions receive their request as `request`;\n * this alias lets route handlers and loaders share one name, so `c.request` and `ctx.req` both work\n * everywhere (no more `c.req` vs `ctx.request` mismatch).\n */\n readonly request: Request;\n /** Read one request header without materializing a Web `Request` on the Node adapter hot path. */\n readonly header: (name: string) => string | null;\n readonly params: ParamsOf<S, Path>;\n readonly query: QueryOf<S>;\n readonly body: BodyOf<S>;\n /** The request's cookies, parsed from the `Cookie` header (values URL-decoded). Parsed lazily on\n * first access + cached. Signed cookies arrive as `value.signature` - verify with `unsignValue`. */\n readonly cookies: Readonly<Record<string, string>>;\n readonly set: ResponseControls;\n /**\n * Aborts when the server's `requestTimeoutMs` elapses (and never, when no timeout\n * is configured). Pass it to cancellation-aware work - DB drivers, `fetch` - so a\n * timed-out request stops doing work instead of running on after the 503.\n */\n readonly signal: AbortSignal;\n /**\n * Absolute request deadline plus monotonic remaining time. It shares {@link signal}; the server\n * clamps an inbound deadline to local policy when `acceptInboundDeadlines` is enabled.\n */\n readonly budget: RequestBudget;\n /**\n * Platform bindings from `app.fetch(request, { env })` - Workers `env` (KV/D1/secrets), etc.\n * `undefined` off-edge (Bun/Node/Deno). Declare the shape with `server<Env>()` to read it typed\n * (`c.env: Env`); otherwise `unknown`. Validate at the trust boundary before use either way.\n */\n readonly env: unknown;\n /**\n * The caller's IP. By default the raw socket peer the serving adapter observed (`listen()`,\n * `@nifrajs/node`, `@nifrajs/deno`) - the one address a client cannot forge - or `undefined` when the\n * runtime exposes no socket (Workers) and no trust is declared. Behind a proxy/CDN, set the\n * `clientIp` server option (`{ trustedHops }` or `{ header }`) to derive the real caller from the\n * forwarding chain as far as you trust it; unset, no forwarded header is ever believed. Safe to key\n * rate limits and audit logs on.\n */\n readonly clientIp: string | undefined;\n /**\n * Schedule background work. On edge runtimes it extends the response lifetime (Workers\n * `ctx.waitUntil`); off-edge it runs the promise fire-and-forget (a rejection is swallowed,\n * never an unhandled rejection).\n */\n readonly waitUntil: (promise: Promise<unknown>) => void;\n /**\n * Read the raw request body as bytes, **capped** at `maxBytes` (default: the server's\n * `maxBodyBytes`). For routes with **no body schema** - raw bodies, file uploads,\n * BYO-validation - where the automatic schema cap doesn't apply. An over-cap body (by\n * `Content-Length` or while streaming) throws a flat `413`; a malformed `Content-Length`\n * throws `400`. Consumes the body stream (call once). Pass a larger `maxBytes` for an\n * upload route, a smaller one to tighten a specific endpoint.\n */\n readonly boundedBody: (maxBytes?: number) => Promise<Uint8Array>;\n /**\n * `boundedBody` + `JSON.parse` (UTF-8). Same cap + `413`/`400` semantics; additionally\n * throws a flat `400` on invalid JSON. Use for a schema-less JSON endpoint that still\n * wants the body bounded.\n */\n readonly boundedJson: <T = unknown>(maxBytes?: number) => Promise<T>;\n /**\n * Build a JSON `Response`. Pass a status number or a full `ResponseInit` as the second arg. `return` it\n * from a handler, or `throw` it from `derive`/`beforeHandle` to short-circuit - both work:\n * `throw c.json({ error: \"unauthorized\" }, 401)`. A terser alternative to\n * `new Response(JSON.stringify(...), { status, headers: { \"content-type\": \"application/json\" } })`.\n */\n readonly json: (body: unknown, init?: ResponseInit | number) => Response;\n /** Build a `text/plain; charset=utf-8` `Response`. Like {@link json}, pass a status or `ResponseInit`. */\n readonly text: (body: string, init?: ResponseInit | number) => Response;\n}",
|
|
2089
2096
|
"doc": "/**\n * Handler context. `params` are inferred from the path; `body` and `query` are\n * the validated outputs of their schemas when declared (else `undefined` /\n * raw `URLSearchParams`).\n */"
|
|
2090
2097
|
},
|
|
2091
2098
|
{
|
|
@@ -2720,6 +2727,13 @@
|
|
|
2720
2727
|
"package": "@nifrajs/core",
|
|
2721
2728
|
"signature": "export declare function decodeTransportResponse(response: Response, registry?: TransportCodecRegistry, options?: TransportDecodeOptions): Promise<unknown>;"
|
|
2722
2729
|
},
|
|
2730
|
+
{
|
|
2731
|
+
"name": "decodeTransportText",
|
|
2732
|
+
"kind": "function",
|
|
2733
|
+
"package": "@nifrajs/core",
|
|
2734
|
+
"signature": "export declare function decodeTransportText(text: string, contentType: string | null, registry?: TransportCodecRegistry, options?: TransportDecodeOptions): unknown;",
|
|
2735
|
+
"doc": "/**\n * Decode an ALREADY-READ transport body. The counterpart to {@link decodeTransportResponse} for a\n * caller that obtained the text through its own bounded read - notably the typed client's\n * in-process path, where the response body is same-process memory that was fully resident before\n * the read, so the native `Response.text()` is safe and the streaming byte-cap loop would protect\n * nothing while costing ~23x. The byte cap is still enforced here (identical error), just after\n * the read instead of during it.\n */"
|
|
2736
|
+
},
|
|
2723
2737
|
{
|
|
2724
2738
|
"name": "DEFAULT_DEV_PORT",
|
|
2725
2739
|
"kind": "const",
|
|
@@ -3534,7 +3548,7 @@
|
|
|
3534
3548
|
"kind": "function",
|
|
3535
3549
|
"package": "@nifrajs/middleware",
|
|
3536
3550
|
"signature": "export declare function etag(options?: ETagOptions): import(\"@nifrajs/core/server\").NifraPlugin<import(\"@nifrajs/core/server\").AnyServer, import(\"@nifrajs/core/server\").AnyServer>;",
|
|
3537
|
-
"doc": "/**\n * A {@link definePlugin} plugin that adds a content-hash `ETag` to `GET` `200` responses and returns\n * **`304 Not Modified`** when the client's `If-None-Match` matches - saving bandwidth on unchanged\n * responses.
|
|
3551
|
+
"doc": "/**\n * A {@link definePlugin} plugin that adds a content-hash `ETag` to `GET` `200` responses and returns\n * **`304 Not Modified`** when the client's `If-None-Match` matches - saving bandwidth on unchanged\n * responses. Built on the portable `onResponseBody` tier: the hook receives the final\n * framework-serialized bytes on every runtime with nothing drained, so the middleware stays on\n * Node's direct writer. Handler-returned raw `Response`s (streams, proxied fetches) use a capped,\n * replaying fallback so oversized bodies remain intact. Idempotent.\n */"
|
|
3538
3552
|
},
|
|
3539
3553
|
{
|
|
3540
3554
|
"name": "ETagOptions",
|
|
@@ -5900,14 +5914,14 @@
|
|
|
5900
5914
|
"name": "Middleware",
|
|
5901
5915
|
"kind": "interface",
|
|
5902
5916
|
"package": "@nifrajs/core",
|
|
5903
|
-
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
5917
|
+
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n /** Allocation-light Node equivalent of `onRequest` for header-only hooks. */\n readonly onNodeRequest?: NodeRequestHook;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n /**\n * Header-only equivalent of `onResponse` for the Node-direct serializer. It is used only when every\n * response hook in the app supplies this paired native implementation; arbitrary response transforms\n * continue through the Web Response path.\n */\n readonly onNodeResponse?: NodeResponseHook;\n /**\n * Response headers with NO per-request decision behind them. Declared here instead of written by a\n * hook, they are folded into response construction, so a bundle that only sets static headers does\n * not cost the app its fused/native lanes (see {@link Server.responseHeaders}). They are defaults:\n * anything the request produced wins. Reach for `onResponseHeaders` the moment a value depends on\n * the request, the route, or the response.\n */\n readonly responseHeaders?: Readonly<Record<string, string>>;\n /**\n * PORTABLE header-only response hook - the recommended shape when the middleware only reads or\n * writes headers. One implementation runs on every runtime: inside the Web `onResponse` walk\n * against the response's own `Headers`, and on Node as a self-paired native hook against the\n * outcome record - so it never forces the Node adapter off its direct writer. Use `onResponse` +\n * an optional `onNodeResponse` twin only when the hook must see a real `Response`.\n */\n readonly onResponseHeaders?: ResponseHeadersHook;\n /**\n * PORTABLE post-serialization body hook - the payload tier. Receives the final\n * framework-serialized bytes (already resident on every runtime; no stream is drained) plus the\n * header view and status, and may return replacement bytes. Raw handler-returned `Response`s\n * (proxies, SSE, streamed SSR) are skipped by contract - transforming those needs `onResponse`.\n */\n readonly onResponseBody?: ResponseBodyHook;\n /**\n * Response transform for untagged/raw responses (streams, proxied fetches, and framework errors).\n * Framework-serialized payloads use `onResponseBody` and remain on the Node direct lane.\n */\n readonly onResponseRaw?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
5904
5918
|
"doc": "/**\n * A bundle of lifecycle hooks applied together via {@link Server.use} - the unit\n * `@nifrajs/middleware` ships (cors, security headers, rate-limit). Every hook is\n * optional and wired to its lifecycle point. Middleware is context-agnostic (sees\n * the base `Context`); `use` does no context-type merging - the full type-merging\n * plugin system is deferred, and `.use` is reserved as its future entry point.\n */"
|
|
5905
5919
|
},
|
|
5906
5920
|
{
|
|
5907
5921
|
"name": "Middleware",
|
|
5908
5922
|
"kind": "interface",
|
|
5909
5923
|
"package": "nifra",
|
|
5910
|
-
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
5924
|
+
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n /** Allocation-light Node equivalent of `onRequest` for header-only hooks. */\n readonly onNodeRequest?: NodeRequestHook;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n /**\n * Header-only equivalent of `onResponse` for the Node-direct serializer. It is used only when every\n * response hook in the app supplies this paired native implementation; arbitrary response transforms\n * continue through the Web Response path.\n */\n readonly onNodeResponse?: NodeResponseHook;\n /**\n * Response headers with NO per-request decision behind them. Declared here instead of written by a\n * hook, they are folded into response construction, so a bundle that only sets static headers does\n * not cost the app its fused/native lanes (see {@link Server.responseHeaders}). They are defaults:\n * anything the request produced wins. Reach for `onResponseHeaders` the moment a value depends on\n * the request, the route, or the response.\n */\n readonly responseHeaders?: Readonly<Record<string, string>>;\n /**\n * PORTABLE header-only response hook - the recommended shape when the middleware only reads or\n * writes headers. One implementation runs on every runtime: inside the Web `onResponse` walk\n * against the response's own `Headers`, and on Node as a self-paired native hook against the\n * outcome record - so it never forces the Node adapter off its direct writer. Use `onResponse` +\n * an optional `onNodeResponse` twin only when the hook must see a real `Response`.\n */\n readonly onResponseHeaders?: ResponseHeadersHook;\n /**\n * PORTABLE post-serialization body hook - the payload tier. Receives the final\n * framework-serialized bytes (already resident on every runtime; no stream is drained) plus the\n * header view and status, and may return replacement bytes. Raw handler-returned `Response`s\n * (proxies, SSE, streamed SSR) are skipped by contract - transforming those needs `onResponse`.\n */\n readonly onResponseBody?: ResponseBodyHook;\n /**\n * Response transform for untagged/raw responses (streams, proxied fetches, and framework errors).\n * Framework-serialized payloads use `onResponseBody` and remain on the Node direct lane.\n */\n readonly onResponseRaw?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
5911
5925
|
"doc": "/**\n * A bundle of lifecycle hooks applied together via {@link Server.use} - the unit\n * `@nifrajs/middleware` ships (cors, security headers, rate-limit). Every hook is\n * optional and wired to its lifecycle point. Middleware is context-agnostic (sees\n * the base `Context`); `use` does no context-type merging - the full type-merging\n * plugin system is deferred, and `.use` is reserved as its future entry point.\n */"
|
|
5912
5926
|
},
|
|
5913
5927
|
{
|
|
@@ -6340,18 +6354,74 @@
|
|
|
6340
6354
|
"signature": "export declare function nodeDirect(): IdentityPlugin;",
|
|
6341
6355
|
"doc": "/** Enable `app.resolveNode()` for direct callers. Applying it twice is a no-op (named plugin dedupe). */"
|
|
6342
6356
|
},
|
|
6357
|
+
{
|
|
6358
|
+
"name": "NodeRequestContext",
|
|
6359
|
+
"kind": "interface",
|
|
6360
|
+
"package": "@nifrajs/core",
|
|
6361
|
+
"signature": "export interface NodeRequestContext {\n readonly method: string;\n readonly url: string;\n readonly header: (name: string) => string | null;\n}",
|
|
6362
|
+
"doc": "/**\n * Allocation-light request view used by Node-native header middleware.\n *\n * Identity contract: within one request, the SAME object is passed to every `onNodeRequest` hook\n * and every `onNodeResponse` hook (the native lanes engage together - see the server's gate), so a\n * middleware may use it as a `WeakMap` key to carry per-request state from its request twin to its\n * response twin.\n */"
|
|
6363
|
+
},
|
|
6364
|
+
{
|
|
6365
|
+
"name": "NodeRequestContext",
|
|
6366
|
+
"kind": "interface",
|
|
6367
|
+
"package": "nifra",
|
|
6368
|
+
"signature": "export interface NodeRequestContext {\n readonly method: string;\n readonly url: string;\n readonly header: (name: string) => string | null;\n}",
|
|
6369
|
+
"doc": "/**\n * Allocation-light request view used by Node-native header middleware.\n *\n * Identity contract: within one request, the SAME object is passed to every `onNodeRequest` hook\n * and every `onNodeResponse` hook (the native lanes engage together - see the server's gate), so a\n * middleware may use it as a `WeakMap` key to carry per-request state from its request twin to its\n * response twin.\n */"
|
|
6370
|
+
},
|
|
6371
|
+
{
|
|
6372
|
+
"name": "NodeRequestHook",
|
|
6373
|
+
"kind": "type",
|
|
6374
|
+
"package": "@nifrajs/core",
|
|
6375
|
+
"signature": "export type NodeRequestHook = (request: NodeRequestContext, platform?: Platform) => MaybePromise<Response | undefined>;",
|
|
6376
|
+
"doc": "/** Native equivalent of a paired `onRequest` hook. It may short-circuit, but cannot rewrite a request. */"
|
|
6377
|
+
},
|
|
6378
|
+
{
|
|
6379
|
+
"name": "NodeRequestHook",
|
|
6380
|
+
"kind": "type",
|
|
6381
|
+
"package": "nifra",
|
|
6382
|
+
"signature": "export type NodeRequestHook = (request: NodeRequestContext, platform?: Platform) => MaybePromise<Response | undefined>;",
|
|
6383
|
+
"doc": "/** Native equivalent of a paired `onRequest` hook. It may short-circuit, but cannot rewrite a request. */"
|
|
6384
|
+
},
|
|
6385
|
+
{
|
|
6386
|
+
"name": "NodeResponseContext",
|
|
6387
|
+
"kind": "interface",
|
|
6388
|
+
"package": "@nifrajs/core",
|
|
6389
|
+
"signature": "export interface NodeResponseContext {\n /** Mutable ONLY through a body hook's replacement object (e.g. an ETag 304); header hooks read. */\n status: number;\n headers: Record<string, string | readonly string[]> | undefined;\n readonly cookies: readonly string[] | undefined;\n /** The framework-serialized body bytes (`null` for a bodiless render). Replaceable by body hooks. */\n body: string | Uint8Array | null;\n}",
|
|
6390
|
+
"doc": "/**\n * Response view used by Node-direct middleware. Header hooks mutate `headers`; a BODY hook\n * (adapted from the portable `onResponseBody`) may replace `body` - the already-serialized bytes\n * the direct writer is about to send - and, through its structured replacement, the status\n * (an ETag 304 being the canonical case).\n */"
|
|
6391
|
+
},
|
|
6392
|
+
{
|
|
6393
|
+
"name": "NodeResponseContext",
|
|
6394
|
+
"kind": "interface",
|
|
6395
|
+
"package": "nifra",
|
|
6396
|
+
"signature": "export interface NodeResponseContext {\n /** Mutable ONLY through a body hook's replacement object (e.g. an ETag 304); header hooks read. */\n status: number;\n headers: Record<string, string | readonly string[]> | undefined;\n readonly cookies: readonly string[] | undefined;\n /** The framework-serialized body bytes (`null` for a bodiless render). Replaceable by body hooks. */\n body: string | Uint8Array | null;\n}",
|
|
6397
|
+
"doc": "/**\n * Response view used by Node-direct middleware. Header hooks mutate `headers`; a BODY hook\n * (adapted from the portable `onResponseBody`) may replace `body` - the already-serialized bytes\n * the direct writer is about to send - and, through its structured replacement, the status\n * (an ETag 304 being the canonical case).\n */"
|
|
6398
|
+
},
|
|
6399
|
+
{
|
|
6400
|
+
"name": "NodeResponseHook",
|
|
6401
|
+
"kind": "type",
|
|
6402
|
+
"package": "@nifrajs/core",
|
|
6403
|
+
"signature": "export type NodeResponseHook = (response: NodeResponseContext, req: NodeRequestContext) => MaybePromise<void>;",
|
|
6404
|
+
"doc": "/** Native equivalent of a paired `onResponse` hook. It must preserve the Web hook's header semantics. */"
|
|
6405
|
+
},
|
|
6406
|
+
{
|
|
6407
|
+
"name": "NodeResponseHook",
|
|
6408
|
+
"kind": "type",
|
|
6409
|
+
"package": "nifra",
|
|
6410
|
+
"signature": "export type NodeResponseHook = (response: NodeResponseContext, req: NodeRequestContext) => MaybePromise<void>;",
|
|
6411
|
+
"doc": "/** Native equivalent of a paired `onResponse` hook. It must preserve the Web hook's header semantics. */"
|
|
6412
|
+
},
|
|
6343
6413
|
{
|
|
6344
6414
|
"name": "NodeServeOutcome",
|
|
6345
6415
|
"kind": "type",
|
|
6346
6416
|
"package": "@nifrajs/core",
|
|
6347
|
-
"signature": "export type NodeServeOutcome = {\n readonly kind: \"response\";\n readonly response: Response;\n} | {\n readonly kind: \"json\";\n readonly status: number;\n /**
|
|
6417
|
+
"signature": "export type NodeServeOutcome = {\n readonly kind: \"response\";\n readonly response: Response;\n} | {\n readonly kind: \"json\";\n readonly status: number;\n /** Header record after native hooks; repeated values are retained as arrays. */\n readonly headers: Readonly<Record<string, string | readonly string[]>> | undefined;\n /** Queued `Set-Cookie` lines, or `undefined`; the adapter emits one header line each. */\n readonly cookies: readonly string[] | undefined;\n /** The JSON body already stringified, or `null` for an empty (204) response. */\n readonly body: string | null;\n} | {\n readonly kind: \"body\";\n readonly status: number;\n readonly headers: Readonly<Record<string, string | readonly string[]>> | undefined;\n readonly body: string | Uint8Array;\n};",
|
|
6348
6418
|
"doc": "/**\n * What {@link Server.resolveNode} returns: either a plain-data render the `@nifrajs/node` adapter writes\n * to the socket directly (`kind: \"json\"` - status + headers + cookies + a pre-stringified body, **no**\n * undici `Response` built or drained), a marked buffered response body (`kind: \"body\"` - e.g.\n * @nifrajs/web's non-deferred SSR HTML), or a `Response` (`kind: \"response\"`) for everything else\n * (redirects, 404/405/errors, unmarked or streaming bodies). Internal to the nifra<->node bridge.\n */"
|
|
6349
6419
|
},
|
|
6350
6420
|
{
|
|
6351
6421
|
"name": "NodeServeOutcome",
|
|
6352
6422
|
"kind": "type",
|
|
6353
6423
|
"package": "nifra",
|
|
6354
|
-
"signature": "export type NodeServeOutcome = {\n readonly kind: \"response\";\n readonly response: Response;\n} | {\n readonly kind: \"json\";\n readonly status: number;\n /**
|
|
6424
|
+
"signature": "export type NodeServeOutcome = {\n readonly kind: \"response\";\n readonly response: Response;\n} | {\n readonly kind: \"json\";\n readonly status: number;\n /** Header record after native hooks; repeated values are retained as arrays. */\n readonly headers: Readonly<Record<string, string | readonly string[]>> | undefined;\n /** Queued `Set-Cookie` lines, or `undefined`; the adapter emits one header line each. */\n readonly cookies: readonly string[] | undefined;\n /** The JSON body already stringified, or `null` for an empty (204) response. */\n readonly body: string | null;\n} | {\n readonly kind: \"body\";\n readonly status: number;\n readonly headers: Readonly<Record<string, string | readonly string[]>> | undefined;\n readonly body: string | Uint8Array;\n};",
|
|
6355
6425
|
"doc": "/**\n * What {@link Server.resolveNode} returns: either a plain-data render the `@nifrajs/node` adapter writes\n * to the socket directly (`kind: \"json\"` - status + headers + cookies + a pre-stringified body, **no**\n * undici `Response` built or drained), a marked buffered response body (`kind: \"body\"` - e.g.\n * @nifrajs/web's non-deferred SSR HTML), or a `Response` (`kind: \"response\"`) for everything else\n * (redirects, 404/405/errors, unmarked or streaming bodies). Internal to the nifra<->node bridge.\n */"
|
|
6356
6426
|
},
|
|
6357
6427
|
{
|
|
@@ -6750,6 +6820,18 @@
|
|
|
6750
6820
|
"signature": "export declare function parseTraceparent(header: string | null | undefined): ParsedTraceparent | null;",
|
|
6751
6821
|
"doc": "/**\n * Parse a `traceparent` header, or `null` if it's absent/malformed/version-unknown - per the spec,\n * a bad header means \"start a fresh trace\", never an error. Only version `00` is accepted.\n */"
|
|
6752
6822
|
},
|
|
6823
|
+
{
|
|
6824
|
+
"name": "pathnameOf",
|
|
6825
|
+
"kind": "function",
|
|
6826
|
+
"package": "@nifrajs/core",
|
|
6827
|
+
"signature": "export declare function pathnameOf(url: string): string;"
|
|
6828
|
+
},
|
|
6829
|
+
{
|
|
6830
|
+
"name": "pathnameOf",
|
|
6831
|
+
"kind": "function",
|
|
6832
|
+
"package": "nifra",
|
|
6833
|
+
"signature": "export declare function pathnameOf(url: string): string;"
|
|
6834
|
+
},
|
|
6753
6835
|
{
|
|
6754
6836
|
"name": "pickLanguage",
|
|
6755
6837
|
"kind": "function",
|
|
@@ -6953,7 +7035,7 @@
|
|
|
6953
7035
|
"name": "PrettyJsonOptions",
|
|
6954
7036
|
"kind": "interface",
|
|
6955
7037
|
"package": "@nifrajs/middleware",
|
|
6956
|
-
"signature": "export interface PrettyJsonOptions {\n /** JSON indentation spaces. Default `2`. */\n readonly spaces?: number;\n /** Maximum response bytes to inspect. Default `1_000_000`; larger responses pass through. */\n readonly maxBytes?: number;\n /** Append a final newline. Default `true`. */\n readonly newline?: boolean;\n /** Optional query toggle. When set, pretty printing runs only when the parameter is present. */\n readonly query?: string | false;\n /** Only pretty-print matching requests
|
|
7038
|
+
"signature": "export interface PrettyJsonOptions {\n /** JSON indentation spaces. Default `2`. */\n readonly spaces?: number;\n /** Maximum response bytes to inspect. Default `1_000_000`; larger responses pass through. */\n readonly maxBytes?: number;\n /** Append a final newline. Default `true`. */\n readonly newline?: boolean;\n /** Optional query toggle. When set, pretty printing runs only when the parameter is present. */\n readonly query?: string | false;\n /** Only pretty-print matching requests (the predicate receives the portable request view -\n * `{ method, url, header(name) }` - so the check runs without materializing a `Request`).\n * Default `true`. */\n readonly enabled?: boolean | ((request: NodeRequestContext) => boolean);\n}"
|
|
6957
7039
|
},
|
|
6958
7040
|
{
|
|
6959
7041
|
"name": "previewEndpoint",
|
|
@@ -7774,6 +7856,34 @@
|
|
|
7774
7856
|
"signature": "export declare function respondMcpHttp(request: Request, tools: McpTool[], serverInfo: {\n name: string;\n version: string;\n}, options?: McpHttpOptions): Promise<Response>;",
|
|
7775
7857
|
"doc": "/**\n * Handle one MCP request over HTTP against the given `tools`/`features`. POST a JSON-RPC body → JSON-RPC\n * response; GET → a plain-text health page; OPTIONS → CORS preflight. Never throws - a bad body becomes a\n * JSON-RPC parse error. Dual-era: a modern (2026-07-28) POST that mirrors its method/name/version into\n * headers is validated against the body before dispatch and gets spec HTTP statuses; legacy requests are\n * served unchanged. The dispatch is the shared, transport-agnostic {@link handleRpc}.\n */"
|
|
7776
7858
|
},
|
|
7859
|
+
{
|
|
7860
|
+
"name": "ResponseBodyHook",
|
|
7861
|
+
"kind": "type",
|
|
7862
|
+
"package": "@nifrajs/core",
|
|
7863
|
+
"signature": "export type ResponseBodyHook = (body: string | Uint8Array, headers: ResponseHeadersView, req: NodeRequestContext, status: number) => MaybePromise<string | Uint8Array | ResponseBodyReplacement | undefined>;",
|
|
7864
|
+
"doc": "/**\n * A portable post-serialization body hook - the Fastify-`onSend`-shaped tier. The hook receives\n * the FINAL framework-serialized bytes plus the header view, and may return replacement bytes\n * (`undefined` keeps the body unchanged). It runs at the framework's cheapest point on every\n * runtime: the bytes are already resident before any Web `Response` exists, so no body stream is\n * ever drained. A handler-returned raw `Response` (a proxied fetch, SSE, streamed SSR) is SKIPPED\n * by definition - transforming those is exactly what the full `onResponse` contract is for.\n */"
|
|
7865
|
+
},
|
|
7866
|
+
{
|
|
7867
|
+
"name": "ResponseBodyHook",
|
|
7868
|
+
"kind": "type",
|
|
7869
|
+
"package": "nifra",
|
|
7870
|
+
"signature": "export type ResponseBodyHook = (body: string | Uint8Array, headers: ResponseHeadersView, req: NodeRequestContext, status: number) => MaybePromise<string | Uint8Array | ResponseBodyReplacement | undefined>;",
|
|
7871
|
+
"doc": "/**\n * A portable post-serialization body hook - the Fastify-`onSend`-shaped tier. The hook receives\n * the FINAL framework-serialized bytes plus the header view, and may return replacement bytes\n * (`undefined` keeps the body unchanged). It runs at the framework's cheapest point on every\n * runtime: the bytes are already resident before any Web `Response` exists, so no body stream is\n * ever drained. A handler-returned raw `Response` (a proxied fetch, SSE, streamed SSR) is SKIPPED\n * by definition - transforming those is exactly what the full `onResponse` contract is for.\n */"
|
|
7872
|
+
},
|
|
7873
|
+
{
|
|
7874
|
+
"name": "ResponseBodyReplacement",
|
|
7875
|
+
"kind": "interface",
|
|
7876
|
+
"package": "@nifrajs/core",
|
|
7877
|
+
"signature": "export interface ResponseBodyReplacement {\n readonly body?: string | Uint8Array | null;\n readonly status?: number;\n}",
|
|
7878
|
+
"doc": "/** A body hook's structured replacement: new bytes (or `null` to drop the body) and/or a status. */"
|
|
7879
|
+
},
|
|
7880
|
+
{
|
|
7881
|
+
"name": "ResponseBodyReplacement",
|
|
7882
|
+
"kind": "interface",
|
|
7883
|
+
"package": "nifra",
|
|
7884
|
+
"signature": "export interface ResponseBodyReplacement {\n readonly body?: string | Uint8Array | null;\n readonly status?: number;\n}",
|
|
7885
|
+
"doc": "/** A body hook's structured replacement: new bytes (or `null` to drop the body) and/or a status. */"
|
|
7886
|
+
},
|
|
7777
7887
|
{
|
|
7778
7888
|
"name": "responseCache",
|
|
7779
7889
|
"kind": "const",
|
|
@@ -7798,7 +7908,7 @@
|
|
|
7798
7908
|
"kind": "function",
|
|
7799
7909
|
"package": "@nifrajs/core",
|
|
7800
7910
|
"signature": "export declare function responseContract(mode?: ResponseContractMode): IdentityPlugin;",
|
|
7801
|
-
"doc": "/**\n * Hold every route's declared `response` schema to what the handler actually returned.\n *\n * app.use(responseContract(\"enforce\"))\n *\n * Install it before the routes it should cover - like `idempotency()`, the decision is made per route\n * at registration, so routes registered earlier are not retroactively covered.\n *\n *
|
|
7911
|
+
"doc": "/**\n * Hold every route's declared `response` schema to what the handler actually returned.\n *\n * app.use(responseContract(\"enforce\"))\n *\n * Install it before the routes it should cover - like `idempotency()`, the decision is made per route\n * at registration, so routes registered earlier are not retroactively covered.\n *\n * The check itself is cheap - with a compiled validator it measures in the ~100ns-per-response\n * range, within benchmark noise of an uncontracted route on any route that carries middleware or a\n * derive. What a contracted route does give up is the bare-route fused lane (the check needs the\n * handler's value before it becomes bytes), which only a route with NO other lifecycle steps was\n * taking anyway. Opt-in because not installing the plugin keeps the lane out of the bundle, not\n * because enforcement is expensive.\n */"
|
|
7802
7912
|
},
|
|
7803
7913
|
{
|
|
7804
7914
|
"name": "ResponseContractMode",
|
|
@@ -7870,6 +7980,34 @@
|
|
|
7870
7980
|
"signature": "export declare function responseFromStored(stored: StoredResponse, options?: {\n readonly maxBytes?: number;\n}): Response;",
|
|
7871
7981
|
"doc": "/** Rebuild a live response from storage, stamping the replay marker header. */"
|
|
7872
7982
|
},
|
|
7983
|
+
{
|
|
7984
|
+
"name": "ResponseHeadersHook",
|
|
7985
|
+
"kind": "type",
|
|
7986
|
+
"package": "@nifrajs/core",
|
|
7987
|
+
"signature": "export type ResponseHeadersHook = (headers: ResponseHeadersView, req: NodeRequestContext, status: number) => MaybePromise<void>;",
|
|
7988
|
+
"doc": "/**\n * A portable header-only response hook - the recommended shape for response middleware that only\n * reads or writes headers (security headers, CORS reflection, cache directives, negotiation). It\n * runs on every runtime from one implementation: the server adapts it into the Web `onResponse`\n * walk AND the Node-native response lane, so registering one never forces the Node adapter off its\n * direct socket writer the way a full `onResponse(res: Response)` hook does. It cannot replace the\n * response or touch the body - middleware needing that keeps the full `onResponse` contract and\n * its cost.\n */"
|
|
7989
|
+
},
|
|
7990
|
+
{
|
|
7991
|
+
"name": "ResponseHeadersHook",
|
|
7992
|
+
"kind": "type",
|
|
7993
|
+
"package": "nifra",
|
|
7994
|
+
"signature": "export type ResponseHeadersHook = (headers: ResponseHeadersView, req: NodeRequestContext, status: number) => MaybePromise<void>;",
|
|
7995
|
+
"doc": "/**\n * A portable header-only response hook - the recommended shape for response middleware that only\n * reads or writes headers (security headers, CORS reflection, cache directives, negotiation). It\n * runs on every runtime from one implementation: the server adapts it into the Web `onResponse`\n * walk AND the Node-native response lane, so registering one never forces the Node adapter off its\n * direct socket writer the way a full `onResponse(res: Response)` hook does. It cannot replace the\n * response or touch the body - middleware needing that keeps the full `onResponse` contract and\n * its cost.\n */"
|
|
7996
|
+
},
|
|
7997
|
+
{
|
|
7998
|
+
"name": "ResponseHeadersView",
|
|
7999
|
+
"kind": "interface",
|
|
8000
|
+
"package": "@nifrajs/core",
|
|
8001
|
+
"signature": "export interface ResponseHeadersView {\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n append(name: string, value: string): void;\n delete(name: string): void;\n}",
|
|
8002
|
+
"doc": "/**\n * The mutable, case-insensitive header surface a portable {@link ResponseHeadersHook} writes\n * through. Deliberately the subset of the Web `Headers` interface every runtime can satisfy\n * natively: on the Web paths the hook receives the response's own `Headers` object directly (which\n * structurally implements this), and on the Node direct-writer path it receives a thin view over\n * the outcome's plain header record - so ONE hook implementation is fast everywhere.\n */"
|
|
8003
|
+
},
|
|
8004
|
+
{
|
|
8005
|
+
"name": "ResponseHeadersView",
|
|
8006
|
+
"kind": "interface",
|
|
8007
|
+
"package": "nifra",
|
|
8008
|
+
"signature": "export interface ResponseHeadersView {\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n append(name: string, value: string): void;\n delete(name: string): void;\n}",
|
|
8009
|
+
"doc": "/**\n * The mutable, case-insensitive header surface a portable {@link ResponseHeadersHook} writes\n * through. Deliberately the subset of the Web `Headers` interface every runtime can satisfy\n * natively: on the Web paths the hook receives the response's own `Headers` object directly (which\n * structurally implements this), and on the Node direct-writer path it receives a thin view over\n * the outcome's plain header record - so ONE hook implementation is fast everywhere.\n */"
|
|
8010
|
+
},
|
|
7873
8011
|
{
|
|
7874
8012
|
"name": "Result",
|
|
7875
8013
|
"kind": "type",
|
|
@@ -8587,7 +8725,7 @@
|
|
|
8587
8725
|
"kind": "function",
|
|
8588
8726
|
"package": "@nifrajs/middleware",
|
|
8589
8727
|
"signature": "export declare function securityHeaders(options?: SecurityHeadersOptions): Middleware;",
|
|
8590
|
-
"doc": "/**\n * A safe-by-default set of response security headers
|
|
8728
|
+
"doc": "/**\n * A safe-by-default set of response security headers, covering errors and 404s too:\n * `X-Content-Type-Options: nosniff`, `X-Frame-Options`, and `Referrer-Policy` always;\n * `Strict-Transport-Security` and `Content-Security-Policy` only when configured (both are\n * environment-/app-specific).\n *\n * Every value is fixed at construction, so these are declared statically rather than written by a\n * response hook: an app whose response middleware is only this keeps the fused native lanes. A route\n * that sets one of these names itself keeps its own value.\n */"
|
|
8591
8729
|
},
|
|
8592
8730
|
{
|
|
8593
8731
|
"name": "SecurityHeadersOptions",
|
|
@@ -8740,14 +8878,14 @@
|
|
|
8740
8878
|
"name": "Server",
|
|
8741
8879
|
"kind": "class",
|
|
8742
8880
|
"package": "@nifrajs/core",
|
|
8743
|
-
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext> {\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n private wsRouteCount;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n private readonly maxBodyBytes;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private sealed;\n private readonly derives;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onResponseHooks;\n private readonly onResponseFinalizedHooks;\n private readonly responseRequests;\n /** Names of plugins/middleware already applied via `use` - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Add a per-request, computed context extension for subsequent routes. */\n derive<D extends object>(fn: (context: Context & Ctx) => MaybePromise<D>): Server<R, Ctx & D>;\n /** Add a static context value for subsequent routes. */\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>>;\n /**\n * Run before routing on the raw request. Return a `Response` to short-circuit, or a replacement\n * `Request` to continue routing with a rewritten method/URL/headers. Global.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /** Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped. */\n beforeHandle(fn: (context: Context & Ctx) => MaybePromise<unknown>): this;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n */\n around(fn: <T>(context: Context & Ctx, next: () => MaybePromise<T>) => MaybePromise<T>): this;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped. */\n afterHandle(fn: (result: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500). Order-scoped. */\n onError(fn: (error: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a *named* identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use(plugin: IdentityPlugin): this;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe).\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A named bundle already\n * applied is skipped (idempotent).\n */\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Register a **typed SSE route** - a GET endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, extra headers). The\n * connection closes when the handler resolves, `stream.close()` runs, or the client disconnects\n * (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, Response>>, Ctx>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>>>, Ctx>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`; the optional `handler.upgrade(c)` runs in the request context first and may\n * reject (return a `Response`) or seed per-connection `ws.data`. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send>): string extends Path ? Server<R, Ctx> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: Method, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates. */\n registerBatch(routes: readonly {\n readonly method: Method;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n private prepareRoute;\n /** Collapse route-invariant lifecycle decisions into one runner at registration. The request path\n * performs no eligibility ladder: it supplies request state to this already-selected plan. */\n private compileExecutionPlan;\n /** The idempotency lane's bridge back into the normal matched lanes, resolved to a concrete Response\n * (the lane buffers the body, then replays it through the route's real validation + handler). */\n private idempotencyRunLanes;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The group's request-level\n * hooks (`onRequest`/`onResponse`/`onResponseFinalized`) are appended to this server's. This\n * server's route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like\n * routes registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes is refused (register\n * those on the parent).\n */\n merge<R2 extends Registry, Ctx2>(other: Server<R2, Ctx2>): Server<R & R2, Ctx>;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or any registered `onResponse` hook falls back to the\n * full Web path (`{ kind: \"response\" }`), so behavior is identical - only the common JSON-data case is\n * faster. Same lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final\n * render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private dispatch;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full async {@link runLifecycle}, unchanged.\n */\n private routeAndRun;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the bare slice of {@link runLifecycle} (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to {@link runLifecycle}'s catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n private bareError;\n private runWithAround;\n private runAround;\n private runBodyOnly;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n /**\n * The post-match lifecycle: validate → derive → beforeHandle → handler → afterHandle, with onError.\n * Generic over the render: a success value goes through `finalize(result, set)` (a Web `Response`, or\n * node-direct primitives); an early/error `Response` (validation, thrown, 500) through `wrapResponse`.\n */\n private runLifecycle;\n private handleLifecycleError;\n /** Log an unhandled request error to the (redacting) logger - shared by {@link runLifecycle} and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n /**\n * Read the body as text, capped at `maxBodyBytes`. Rejects (`null`) on a\n * `Content-Length` over the cap *before* buffering, and aborts mid-stream once the\n * running byte count exceeds it - so a lying or absent length can't force us to\n * buffer an oversized payload.\n *\n * Fast path: when a non-chunked request carries a `Content-Length` within the cap,\n * a native `req.json()` is already bounded - under HTTP/1.1 + HTTP/2 framing the\n * runtime delivers at most `Content-Length` bytes - so we skip the manual stream\n * loop and a separate text decode. It trusts the wire\n * *framing*, not the header value: nifra only ever receives framed Requests from the\n * runtime's HTTP server, never a hand-built one with a mismatched length. Chunked or\n * length-less bodies fall through to the streaming byte-cap guard below.\n */\n private readBoundedJson;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade. Named wildcards also stay on the fallback until Bun exposes their raw\n * capture semantics; static and `:param` routes take the native lane. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
8881
|
+
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext> {\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n private wsRouteCount;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n private readonly maxBodyBytes;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private sealed;\n private readonly derives;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onNodeRequestHooks;\n /** Registration-time eligibility for the Node request twin lane. */\n private nodeRequestHooksComplete;\n private readonly onResponseHooks;\n private readonly onNodeResponseHooks;\n /** Registration-time eligibility for the Node response twin lane. */\n private nodeResponseHooksComplete;\n private readonly onResponseFinalizedHooks;\n /**\n * Statically declared response headers, merged and prebuilt at registration; `undefined` (the\n * default) leaves every render path in its original shape. These are NOT response hooks - they are\n * folded into response construction - so declaring them keeps the fused native lanes an\n * `onResponse` hook would have disabled.\n */\n private staticResponseHeaders;\n /** `wrapResponse` for the Web lanes: identity until static headers exist to fold into the\n * framework's own error/404/timeout renders, which are built outside the header init. */\n private wrapWebResponse;\n private webResponseTimeout;\n /** Body/raw response hooks need a framework-payload marker; keep that decision per app. */\n private responseBodyTag;\n private readonly responseBodyOwners;\n private readonly finalizeResponse;\n private readonly responseRequests;\n /** Original source → request observed by generic request hooks, including in-place mutations. */\n private readonly responseSources;\n /** Memoized NodeRequestContext per plain-`Request` source - see {@link nodeRequestContextOf}. */\n private readonly nodeContexts;\n /** Names of plugins/middleware already applied via `use` - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Add a per-request, computed context extension for subsequent routes. */\n derive<D extends object>(fn: (context: Context & Ctx) => MaybePromise<D>): Server<R, Ctx & D>;\n /** Add a static context value for subsequent routes. */\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>>;\n /**\n * Run before routing on the raw request. Return a `Response` to short-circuit, or a replacement\n * `Request` to continue routing with a rewritten method/URL/headers. Global.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /** Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped. */\n beforeHandle(fn: (context: Context & Ctx) => MaybePromise<unknown>): this;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n */\n around(fn: <T>(context: Context & Ctx, next: () => MaybePromise<T>) => MaybePromise<T>): this;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped. */\n afterHandle(fn: (result: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500). Order-scoped. */\n onError(fn: (error: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Declare response headers with NO per-request decision behind them - and pay nothing for them on\n * the request path.\n *\n * These are not a hook. Because the values are known at wire-up, they are folded into response\n * construction (one prebuilt init for JSON renders, one record merge where the request set its own\n * headers), so an app whose only response middleware is static keeps every fused and native lane -\n * `onResponse`/`onResponseHeaders` disable Bun's fused native routes and, for a full `onResponse`,\n * the Node direct writer. They apply to EVERY response, exactly as a response hook would: success,\n * error, 404/405, timeout, and short-circuit alike.\n *\n * app.responseHeaders({ \"x-frame-options\": \"DENY\", \"referrer-policy\": \"no-referrer\" })\n *\n * They are DEFAULTS: a value the request itself produced (`c.set.headers`, or a response hook)\n * wins, whatever casing it used. Names are lowercased once here; a non-string value, an invalid\n * name, `__proto__`, or a name the render owns (`content-type`, `content-length`,\n * `transfer-encoding`, `set-cookie`) throws a `TypeError` at wire-up.\n *\n * ORDERING: declarations made before any response hook fold into one static record. One made AFTER\n * a response hook cannot - the hook may already have written that name and must keep winning - so\n * it registers as an ordinary `onResponseHeaders` hook instead, preserving registration order at\n * the cost of the static tier's speed. Declare static headers first.\n */\n responseHeaders(record: Readonly<Record<string, string>>): this;\n /** Wire an already-validated lowercase record into the static tier, or - once a dynamic response\n * hook owns part of the header state - into a hook that runs in the right order. */\n private addStaticResponseHeaders;\n private enableResponseBodyTagging;\n /**\n * Register a response transform for raw/streamed Responses. Framework-serialized payloads stay on\n * the body tier; this hook is only entered for untagged Responses (streams, proxied fetches, and\n * framework-generated error responses). A no-op native twin keeps buffered JSON on the direct lane.\n */\n onResponseRaw(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Register a PORTABLE header-only response hook - one implementation, fast on every runtime.\n *\n * The hook receives a mutable case-insensitive header view, a minimal request view, and the\n * status. On the Web serving paths it runs inside the normal `onResponse` walk against the\n * response's own `Headers` (mutating in place - no clone). On Node it self-pairs as a native\n * response hook against the outcome's plain header record, so registering one NEVER forces the\n * Node adapter off its direct socket writer the way a full `onResponse(res: Response)` hook does.\n * Prefer this over `onResponse` whenever the middleware only reads/writes headers.\n */\n onResponseHeaders(fn: ResponseHeadersHook): this;\n /**\n * Register a PORTABLE post-serialization body hook - the payload tier. The hook receives the\n * FINAL framework-serialized bytes (plus the mutable header view and status) and may return\n * replacement bytes; `undefined` keeps the body. On the Node direct writer the bytes come\n * straight off the outcome record; on the Web serving paths they ride the framework-built\n * Response as a tag, so no body stream is ever drained on any runtime. A handler-returned raw\n * `Response` (proxied fetch, SSE, streamed SSR) is skipped by contract - transforming those is\n * what the full `onResponse` hook is for.\n */\n onResponseBody(fn: ResponseBodyHook): this;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a *named* identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use(plugin: IdentityPlugin): this;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe).\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A named bundle already\n * applied is skipped (idempotent).\n */\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Register a **typed SSE route** - a GET endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, extra headers). The\n * connection closes when the handler resolves, `stream.close()` runs, or the client disconnects\n * (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, Response>>, Ctx>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>>>, Ctx>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`; the optional `handler.upgrade(c)` runs in the request context first and may\n * reject (return a `Response`) or seed per-connection `ws.data`. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send>): string extends Path ? Server<R, Ctx> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: Method, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates. */\n registerBatch(routes: readonly {\n readonly method: Method;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n private prepareRoute;\n /** Collapse route-invariant lifecycle decisions into one runner at registration. The request path\n * performs no eligibility ladder: it supplies request state to this already-selected plan. */\n private compileExecutionPlan;\n /** The idempotency lane's bridge back into the normal matched lanes, resolved to a concrete Response\n * (the lane buffers the body, then replays it through the route's real validation + handler). */\n private idempotencyRunLanes;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The group's request-level\n * hooks (`onRequest`/`onResponse`/`onResponseFinalized`) are appended to this server's. This\n * server's route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like\n * routes registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes is refused (register\n * those on the parent).\n */\n merge<R2 extends Registry, Ctx2>(other: Server<R2, Ctx2>): Server<R & R2, Ctx>;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or a response hook that replaces/consumes the buffered\n * body stays on the full Web path; an in-place response hook can still use the direct writer. Same\n * lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /** Run generic Web response middleware while retaining direct writes for untouched buffered bodies. */\n private finishNodeWebResponse;\n /** True only when every transforming Web response hook has a header-only Node equivalent. */\n private canUseNodeResponseHooks;\n /** Apply paired native hooks to data outcomes; preserve the complete Web hook pipeline for Response outcomes. */\n private finishNodeResponse;\n private withNodeResponseHeaders;\n /** Synchronous until a native response hook actually returns a Promise. */\n private applyNodeResponseHooks;\n private continueNodeResponseHooks;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private dispatch;\n /** Node-native request hook walk. A header-only hook can inspect the lazy source without forcing a\n * Web `Request`; arbitrary request rewrites and full Web hooks use {@link runWithOnRequest}. */\n private runWithNodeRequest;\n private continueNodeRequest;\n private canUseNodeRequestHooks;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * The NodeRequestContext for a source, MEMOIZED per source so the request twins and the response\n * twins receive the exact same object within one request - that identity is the documented\n * contract stateful twins key their WeakMaps on. An adapter source (which already speaks the\n * interface) is returned as-is; a plain `Request` source (a direct `resolveNode` caller) gets one\n * cached wrapper.\n */\n private nodeRequestContextOf;\n /** Preserve the request visible to generic onRequest hooks for paired native response hooks. */\n private takeNodeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full async {@link runLifecycle}, unchanged.\n */\n private routeAndRun;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the bare slice of {@link runLifecycle} (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to {@link runLifecycle}'s catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** Compile the eligible body-only route's parser → validator → handler continuation once. The\n * bounded parser remains shared with the generic lane; only the route-invariant entry lookups and\n * lifecycle dispatch disappear from the common synchronous-validator/synchronous-handler case. */\n private buildFusedBodyRunner;\n /** Web adapter wrapper for the shared body runner. Node passes its native finalizer directly through\n * the execution plan, while Web needs the live context to preserve lazy `c.set` controls. */\n private buildFusedBodyWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n private bareError;\n private runWithAround;\n private runAround;\n private runBodyOnly;\n /** Shared bounded body framing/parser. Both body lanes use the same trust-boundary checks; only\n * the validation + handler continuation differs. */\n private readBodyInput;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n /**\n * The post-match lifecycle: validate → derive → beforeHandle → handler → afterHandle, with onError.\n * Generic over the render: a success value goes through `finalize(result, set)` (a Web `Response`, or\n * node-direct primitives); an early/error `Response` (validation, thrown, 500) through `wrapResponse`.\n */\n /** Synchronous until a validator, lifecycle hook, handler, or contract check actually returns a Promise. */\n private runLifecycle;\n /** Registration-specialized query lifecycle: query validation (including recovery) → hooks. */\n private runLifecycleQuery;\n /** Registration-specialized body lifecycle: bounded body validation (including recovery) → hooks. */\n private runLifecycleBody;\n /** Registration-specialized body + query lifecycle: bounded body validation → query validation → hooks. */\n private runLifecycleBodyQuery;\n /** Registration-specialized no-body lifecycle: query validation (if present) → derives/hooks. */\n private runQueryAndLifecycle;\n private runQueryAndLifecycleResult;\n private runLifecycleAfterParamsResult;\n private runLifecycleAfterParams;\n private runLifecycleAfterParamsSettled;\n private runLifecycleAfterBody;\n private runLifecycleAfterQueryResult;\n private runLifecycleAfterQuery;\n private runLifecycleHooks;\n /** Registration-specialized derive → before → handler lifecycle. */\n private runLifecycleDeriveBefore;\n /** Finalize the specialized lane without rechecking its registration-proven invariants. */\n private finishSimpleLifecycleResult;\n private continueLifecycleAfterDerive;\n private runLifecycleHooksAsync;\n private continueLifecycleAfterBefore;\n private runLifecycleHandlerAsync;\n private finishLifecycleResult;\n private continueLifecycleAfterHandle;\n private finishLifecycleContract;\n private finishContractOutcome;\n private handleLifecycleError;\n /** Log an unhandled request error to the (redacting) logger - shared by {@link runLifecycle} and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n private finishLifecycleValidationRecovery;\n /**\n * Read the body as text, capped at `maxBodyBytes`. Rejects (`null`) on a\n * `Content-Length` over the cap *before* buffering, and aborts mid-stream once the\n * running byte count exceeds it - so a lying or absent length can't force us to\n * buffer an oversized payload.\n *\n * Fast path: when a non-chunked request carries a `Content-Length` within the cap,\n * a native `req.json()` is already bounded - under HTTP/1.1 + HTTP/2 framing the\n * runtime delivers at most `Content-Length` bytes - so we skip the manual stream\n * loop and a separate text decode. It trusts the wire\n * *framing*, not the header value: nifra only ever receives framed Requests from the\n * runtime's HTTP server, never a hand-built one with a mismatched length. Chunked or\n * length-less bodies fall through to the streaming byte-cap guard below.\n */\n private readBoundedJson;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade. Named wildcards also stay on the fallback until Bun exposes their raw\n * capture semantics; static and `:param` routes take the native lane. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
8744
8882
|
"doc": "/**\n * The inline server. Routes are chainable and fully type-inferred. `derive`/\n * `decorate` extend the handler context (`Ctx`) for routes defined *after* them,\n * with full types; `Ctx` is server-only and never touches the client registry.\n *\n * app.decorate(\"db\", db).derive((c) => ({ user: auth(c) }))\n * .get(\"/me\", (c) => c.user) // c.user + c.db are typed\n */"
|
|
8745
8883
|
},
|
|
8746
8884
|
{
|
|
8747
8885
|
"name": "Server",
|
|
8748
8886
|
"kind": "class",
|
|
8749
8887
|
"package": "nifra",
|
|
8750
|
-
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext> {\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n private wsRouteCount;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n private readonly maxBodyBytes;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private sealed;\n private readonly derives;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onResponseHooks;\n private readonly onResponseFinalizedHooks;\n private readonly responseRequests;\n /** Names of plugins/middleware already applied via `use` - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Add a per-request, computed context extension for subsequent routes. */\n derive<D extends object>(fn: (context: Context & Ctx) => MaybePromise<D>): Server<R, Ctx & D>;\n /** Add a static context value for subsequent routes. */\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>>;\n /**\n * Run before routing on the raw request. Return a `Response` to short-circuit, or a replacement\n * `Request` to continue routing with a rewritten method/URL/headers. Global.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /** Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped. */\n beforeHandle(fn: (context: Context & Ctx) => MaybePromise<unknown>): this;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n */\n around(fn: <T>(context: Context & Ctx, next: () => MaybePromise<T>) => MaybePromise<T>): this;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped. */\n afterHandle(fn: (result: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500). Order-scoped. */\n onError(fn: (error: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a *named* identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use(plugin: IdentityPlugin): this;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe).\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A named bundle already\n * applied is skipped (idempotent).\n */\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Register a **typed SSE route** - a GET endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, extra headers). The\n * connection closes when the handler resolves, `stream.close()` runs, or the client disconnects\n * (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, Response>>, Ctx>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>>>, Ctx>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`; the optional `handler.upgrade(c)` runs in the request context first and may\n * reject (return a `Response`) or seed per-connection `ws.data`. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send>): string extends Path ? Server<R, Ctx> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: Method, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates. */\n registerBatch(routes: readonly {\n readonly method: Method;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n private prepareRoute;\n /** Collapse route-invariant lifecycle decisions into one runner at registration. The request path\n * performs no eligibility ladder: it supplies request state to this already-selected plan. */\n private compileExecutionPlan;\n /** The idempotency lane's bridge back into the normal matched lanes, resolved to a concrete Response\n * (the lane buffers the body, then replays it through the route's real validation + handler). */\n private idempotencyRunLanes;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The group's request-level\n * hooks (`onRequest`/`onResponse`/`onResponseFinalized`) are appended to this server's. This\n * server's route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like\n * routes registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes is refused (register\n * those on the parent).\n */\n merge<R2 extends Registry, Ctx2>(other: Server<R2, Ctx2>): Server<R & R2, Ctx>;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or any registered `onResponse` hook falls back to the\n * full Web path (`{ kind: \"response\" }`), so behavior is identical - only the common JSON-data case is\n * faster. Same lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final\n * render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private dispatch;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full async {@link runLifecycle}, unchanged.\n */\n private routeAndRun;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the bare slice of {@link runLifecycle} (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to {@link runLifecycle}'s catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n private bareError;\n private runWithAround;\n private runAround;\n private runBodyOnly;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n /**\n * The post-match lifecycle: validate → derive → beforeHandle → handler → afterHandle, with onError.\n * Generic over the render: a success value goes through `finalize(result, set)` (a Web `Response`, or\n * node-direct primitives); an early/error `Response` (validation, thrown, 500) through `wrapResponse`.\n */\n private runLifecycle;\n private handleLifecycleError;\n /** Log an unhandled request error to the (redacting) logger - shared by {@link runLifecycle} and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n /**\n * Read the body as text, capped at `maxBodyBytes`. Rejects (`null`) on a\n * `Content-Length` over the cap *before* buffering, and aborts mid-stream once the\n * running byte count exceeds it - so a lying or absent length can't force us to\n * buffer an oversized payload.\n *\n * Fast path: when a non-chunked request carries a `Content-Length` within the cap,\n * a native `req.json()` is already bounded - under HTTP/1.1 + HTTP/2 framing the\n * runtime delivers at most `Content-Length` bytes - so we skip the manual stream\n * loop and a separate text decode. It trusts the wire\n * *framing*, not the header value: nifra only ever receives framed Requests from the\n * runtime's HTTP server, never a hand-built one with a mismatched length. Chunked or\n * length-less bodies fall through to the streaming byte-cap guard below.\n */\n private readBoundedJson;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade. Named wildcards also stay on the fallback until Bun exposes their raw\n * capture semantics; static and `:param` routes take the native lane. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
8888
|
+
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext> {\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n private wsRouteCount;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n private readonly maxBodyBytes;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private sealed;\n private readonly derives;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onNodeRequestHooks;\n /** Registration-time eligibility for the Node request twin lane. */\n private nodeRequestHooksComplete;\n private readonly onResponseHooks;\n private readonly onNodeResponseHooks;\n /** Registration-time eligibility for the Node response twin lane. */\n private nodeResponseHooksComplete;\n private readonly onResponseFinalizedHooks;\n /**\n * Statically declared response headers, merged and prebuilt at registration; `undefined` (the\n * default) leaves every render path in its original shape. These are NOT response hooks - they are\n * folded into response construction - so declaring them keeps the fused native lanes an\n * `onResponse` hook would have disabled.\n */\n private staticResponseHeaders;\n /** `wrapResponse` for the Web lanes: identity until static headers exist to fold into the\n * framework's own error/404/timeout renders, which are built outside the header init. */\n private wrapWebResponse;\n private webResponseTimeout;\n /** Body/raw response hooks need a framework-payload marker; keep that decision per app. */\n private responseBodyTag;\n private readonly responseBodyOwners;\n private readonly finalizeResponse;\n private readonly responseRequests;\n /** Original source → request observed by generic request hooks, including in-place mutations. */\n private readonly responseSources;\n /** Memoized NodeRequestContext per plain-`Request` source - see {@link nodeRequestContextOf}. */\n private readonly nodeContexts;\n /** Names of plugins/middleware already applied via `use` - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Add a per-request, computed context extension for subsequent routes. */\n derive<D extends object>(fn: (context: Context & Ctx) => MaybePromise<D>): Server<R, Ctx & D>;\n /** Add a static context value for subsequent routes. */\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>>;\n /**\n * Run before routing on the raw request. Return a `Response` to short-circuit, or a replacement\n * `Request` to continue routing with a rewritten method/URL/headers. Global.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /** Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped. */\n beforeHandle(fn: (context: Context & Ctx) => MaybePromise<unknown>): this;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n */\n around(fn: <T>(context: Context & Ctx, next: () => MaybePromise<T>) => MaybePromise<T>): this;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped. */\n afterHandle(fn: (result: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500). Order-scoped. */\n onError(fn: (error: unknown, context: Context & Ctx) => MaybePromise<unknown>): this;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Declare response headers with NO per-request decision behind them - and pay nothing for them on\n * the request path.\n *\n * These are not a hook. Because the values are known at wire-up, they are folded into response\n * construction (one prebuilt init for JSON renders, one record merge where the request set its own\n * headers), so an app whose only response middleware is static keeps every fused and native lane -\n * `onResponse`/`onResponseHeaders` disable Bun's fused native routes and, for a full `onResponse`,\n * the Node direct writer. They apply to EVERY response, exactly as a response hook would: success,\n * error, 404/405, timeout, and short-circuit alike.\n *\n * app.responseHeaders({ \"x-frame-options\": \"DENY\", \"referrer-policy\": \"no-referrer\" })\n *\n * They are DEFAULTS: a value the request itself produced (`c.set.headers`, or a response hook)\n * wins, whatever casing it used. Names are lowercased once here; a non-string value, an invalid\n * name, `__proto__`, or a name the render owns (`content-type`, `content-length`,\n * `transfer-encoding`, `set-cookie`) throws a `TypeError` at wire-up.\n *\n * ORDERING: declarations made before any response hook fold into one static record. One made AFTER\n * a response hook cannot - the hook may already have written that name and must keep winning - so\n * it registers as an ordinary `onResponseHeaders` hook instead, preserving registration order at\n * the cost of the static tier's speed. Declare static headers first.\n */\n responseHeaders(record: Readonly<Record<string, string>>): this;\n /** Wire an already-validated lowercase record into the static tier, or - once a dynamic response\n * hook owns part of the header state - into a hook that runs in the right order. */\n private addStaticResponseHeaders;\n private enableResponseBodyTagging;\n /**\n * Register a response transform for raw/streamed Responses. Framework-serialized payloads stay on\n * the body tier; this hook is only entered for untagged Responses (streams, proxied fetches, and\n * framework-generated error responses). A no-op native twin keeps buffered JSON on the direct lane.\n */\n onResponseRaw(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Register a PORTABLE header-only response hook - one implementation, fast on every runtime.\n *\n * The hook receives a mutable case-insensitive header view, a minimal request view, and the\n * status. On the Web serving paths it runs inside the normal `onResponse` walk against the\n * response's own `Headers` (mutating in place - no clone). On Node it self-pairs as a native\n * response hook against the outcome's plain header record, so registering one NEVER forces the\n * Node adapter off its direct socket writer the way a full `onResponse(res: Response)` hook does.\n * Prefer this over `onResponse` whenever the middleware only reads/writes headers.\n */\n onResponseHeaders(fn: ResponseHeadersHook): this;\n /**\n * Register a PORTABLE post-serialization body hook - the payload tier. The hook receives the\n * FINAL framework-serialized bytes (plus the mutable header view and status) and may return\n * replacement bytes; `undefined` keeps the body. On the Node direct writer the bytes come\n * straight off the outcome record; on the Web serving paths they ride the framework-built\n * Response as a tag, so no body stream is ever drained on any runtime. A handler-returned raw\n * `Response` (proxied fetch, SSE, streamed SSR) is skipped by contract - transforming those is\n * what the full `onResponse` hook is for.\n */\n onResponseBody(fn: ResponseBodyHook): this;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a *named* identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use(plugin: IdentityPlugin): this;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe).\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A named bundle already\n * applied is skipped (idempotent).\n */\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Register a **typed SSE route** - a GET endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, extra headers). The\n * connection closes when the handler resolves, `stream.close()` runs, or the client disconnects\n * (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, Response>>, Ctx>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>>>, Ctx>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>>>, Ctx>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>>>, Ctx>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`; the optional `handler.upgrade(c)` runs in the request context first and may\n * reject (return a `Response`) or seed per-connection `ws.data`. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send>): string extends Path ? Server<R, Ctx> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: Method, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates. */\n registerBatch(routes: readonly {\n readonly method: Method;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n private prepareRoute;\n /** Collapse route-invariant lifecycle decisions into one runner at registration. The request path\n * performs no eligibility ladder: it supplies request state to this already-selected plan. */\n private compileExecutionPlan;\n /** The idempotency lane's bridge back into the normal matched lanes, resolved to a concrete Response\n * (the lane buffers the body, then replays it through the route's real validation + handler). */\n private idempotencyRunLanes;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The group's request-level\n * hooks (`onRequest`/`onResponse`/`onResponseFinalized`) are appended to this server's. This\n * server's route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like\n * routes registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes is refused (register\n * those on the parent).\n */\n merge<R2 extends Registry, Ctx2>(other: Server<R2, Ctx2>): Server<R & R2, Ctx>;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or a response hook that replaces/consumes the buffered\n * body stays on the full Web path; an in-place response hook can still use the direct writer. Same\n * lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /** Run generic Web response middleware while retaining direct writes for untouched buffered bodies. */\n private finishNodeWebResponse;\n /** True only when every transforming Web response hook has a header-only Node equivalent. */\n private canUseNodeResponseHooks;\n /** Apply paired native hooks to data outcomes; preserve the complete Web hook pipeline for Response outcomes. */\n private finishNodeResponse;\n private withNodeResponseHeaders;\n /** Synchronous until a native response hook actually returns a Promise. */\n private applyNodeResponseHooks;\n private continueNodeResponseHooks;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private dispatch;\n /** Node-native request hook walk. A header-only hook can inspect the lazy source without forcing a\n * Web `Request`; arbitrary request rewrites and full Web hooks use {@link runWithOnRequest}. */\n private runWithNodeRequest;\n private continueNodeRequest;\n private canUseNodeRequestHooks;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * The NodeRequestContext for a source, MEMOIZED per source so the request twins and the response\n * twins receive the exact same object within one request - that identity is the documented\n * contract stateful twins key their WeakMaps on. An adapter source (which already speaks the\n * interface) is returned as-is; a plain `Request` source (a direct `resolveNode` caller) gets one\n * cached wrapper.\n */\n private nodeRequestContextOf;\n /** Preserve the request visible to generic onRequest hooks for paired native response hooks. */\n private takeNodeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full async {@link runLifecycle}, unchanged.\n */\n private routeAndRun;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the bare slice of {@link runLifecycle} (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to {@link runLifecycle}'s catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** Compile the eligible body-only route's parser → validator → handler continuation once. The\n * bounded parser remains shared with the generic lane; only the route-invariant entry lookups and\n * lifecycle dispatch disappear from the common synchronous-validator/synchronous-handler case. */\n private buildFusedBodyRunner;\n /** Web adapter wrapper for the shared body runner. Node passes its native finalizer directly through\n * the execution plan, while Web needs the live context to preserve lazy `c.set` controls. */\n private buildFusedBodyWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n private bareError;\n private runWithAround;\n private runAround;\n private runBodyOnly;\n /** Shared bounded body framing/parser. Both body lanes use the same trust-boundary checks; only\n * the validation + handler continuation differs. */\n private readBodyInput;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n /**\n * The post-match lifecycle: validate → derive → beforeHandle → handler → afterHandle, with onError.\n * Generic over the render: a success value goes through `finalize(result, set)` (a Web `Response`, or\n * node-direct primitives); an early/error `Response` (validation, thrown, 500) through `wrapResponse`.\n */\n /** Synchronous until a validator, lifecycle hook, handler, or contract check actually returns a Promise. */\n private runLifecycle;\n /** Registration-specialized query lifecycle: query validation (including recovery) → hooks. */\n private runLifecycleQuery;\n /** Registration-specialized body lifecycle: bounded body validation (including recovery) → hooks. */\n private runLifecycleBody;\n /** Registration-specialized body + query lifecycle: bounded body validation → query validation → hooks. */\n private runLifecycleBodyQuery;\n /** Registration-specialized no-body lifecycle: query validation (if present) → derives/hooks. */\n private runQueryAndLifecycle;\n private runQueryAndLifecycleResult;\n private runLifecycleAfterParamsResult;\n private runLifecycleAfterParams;\n private runLifecycleAfterParamsSettled;\n private runLifecycleAfterBody;\n private runLifecycleAfterQueryResult;\n private runLifecycleAfterQuery;\n private runLifecycleHooks;\n /** Registration-specialized derive → before → handler lifecycle. */\n private runLifecycleDeriveBefore;\n /** Finalize the specialized lane without rechecking its registration-proven invariants. */\n private finishSimpleLifecycleResult;\n private continueLifecycleAfterDerive;\n private runLifecycleHooksAsync;\n private continueLifecycleAfterBefore;\n private runLifecycleHandlerAsync;\n private finishLifecycleResult;\n private continueLifecycleAfterHandle;\n private finishLifecycleContract;\n private finishContractOutcome;\n private handleLifecycleError;\n /** Log an unhandled request error to the (redacting) logger - shared by {@link runLifecycle} and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n private finishLifecycleValidationRecovery;\n /**\n * Read the body as text, capped at `maxBodyBytes`. Rejects (`null`) on a\n * `Content-Length` over the cap *before* buffering, and aborts mid-stream once the\n * running byte count exceeds it - so a lying or absent length can't force us to\n * buffer an oversized payload.\n *\n * Fast path: when a non-chunked request carries a `Content-Length` within the cap,\n * a native `req.json()` is already bounded - under HTTP/1.1 + HTTP/2 framing the\n * runtime delivers at most `Content-Length` bytes - so we skip the manual stream\n * loop and a separate text decode. It trusts the wire\n * *framing*, not the header value: nifra only ever receives framed Requests from the\n * runtime's HTTP server, never a hand-built one with a mismatched length. Chunked or\n * length-less bodies fall through to the streaming byte-cap guard below.\n */\n private readBoundedJson;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade. Named wildcards also stay on the fallback until Bun exposes their raw\n * capture semantics; static and `:param` routes take the native lane. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
8751
8889
|
"doc": "/**\n * The inline server. Routes are chainable and fully type-inferred. `derive`/\n * `decorate` extend the handler context (`Ctx`) for routes defined *after* them,\n * with full types; `Ctx` is server-only and never touches the client registry.\n *\n * app.decorate(\"db\", db).derive((c) => ({ user: auth(c) }))\n * .get(\"/me\", (c) => c.user) // c.user + c.db are typed\n */"
|
|
8752
8890
|
},
|
|
8753
8891
|
{
|
|
@@ -10255,6 +10393,30 @@
|
|
|
10255
10393
|
"signature": "export declare function url(opts?: Base<string> & Optional): StandardSchemaV1<string | undefined>;",
|
|
10256
10394
|
"doc": "/** A valid absolute URL (parses with the WHATWG `URL`). Returns the normalized href string. */"
|
|
10257
10395
|
},
|
|
10396
|
+
{
|
|
10397
|
+
"name": "UrlParts",
|
|
10398
|
+
"kind": "interface",
|
|
10399
|
+
"package": "@nifrajs/core",
|
|
10400
|
+
"signature": "export interface UrlParts {\n readonly pathname: string;\n readonly search: string;\n}"
|
|
10401
|
+
},
|
|
10402
|
+
{
|
|
10403
|
+
"name": "UrlParts",
|
|
10404
|
+
"kind": "interface",
|
|
10405
|
+
"package": "nifra",
|
|
10406
|
+
"signature": "export interface UrlParts {\n readonly pathname: string;\n readonly search: string;\n}"
|
|
10407
|
+
},
|
|
10408
|
+
{
|
|
10409
|
+
"name": "urlPartsOf",
|
|
10410
|
+
"kind": "function",
|
|
10411
|
+
"package": "@nifrajs/core",
|
|
10412
|
+
"signature": "export declare function urlPartsOf(url: string): UrlParts;"
|
|
10413
|
+
},
|
|
10414
|
+
{
|
|
10415
|
+
"name": "urlPartsOf",
|
|
10416
|
+
"kind": "function",
|
|
10417
|
+
"package": "nifra",
|
|
10418
|
+
"signature": "export declare function urlPartsOf(url: string): UrlParts;"
|
|
10419
|
+
},
|
|
10258
10420
|
{
|
|
10259
10421
|
"name": "useBlocker",
|
|
10260
10422
|
"kind": "function",
|
|
@@ -10821,14 +10983,14 @@
|
|
|
10821
10983
|
"name": "VERSION",
|
|
10822
10984
|
"kind": "const",
|
|
10823
10985
|
"package": "@nifrajs/core",
|
|
10824
|
-
"signature": "export declare const VERSION: \"2.
|
|
10986
|
+
"signature": "export declare const VERSION: \"2.9.0\";",
|
|
10825
10987
|
"doc": "/**\n * Current package version. A hardcoded literal on purpose - core runs on the edge (no fs), so it can't\n * read its own package.json at runtime. `scripts/version.ts` rewrites it on every release bump and\n * `check:publish` asserts it equals `@nifrajs/core`'s package version.\n */"
|
|
10826
10988
|
},
|
|
10827
10989
|
{
|
|
10828
10990
|
"name": "VERSION",
|
|
10829
10991
|
"kind": "const",
|
|
10830
10992
|
"package": "nifra",
|
|
10831
|
-
"signature": "export declare const VERSION: \"2.
|
|
10993
|
+
"signature": "export declare const VERSION: \"2.9.0\";",
|
|
10832
10994
|
"doc": "/**\n * Current package version. A hardcoded literal on purpose - core runs on the edge (no fs), so it can't\n * read its own package.json at runtime. `scripts/version.ts` rewrites it on every release bump and\n * `check:publish` asserts it equals `@nifrajs/core`'s package version.\n */"
|
|
10833
10995
|
},
|
|
10834
10996
|
{
|