@dunx/http 2.1.1 → 2.2.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/index.js.map CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/route/marker.ts", "../src/route/decorators.ts", "../src/route/discover.ts", "../src/route/metadata.ts", "../src/inspect.ts", "../src/ws/discover.ts", "../src/ws/marker.ts", "../src/server/client-address.ts", "../src/server/context.ts", "../src/server/cors.ts", "../src/server/errors.ts", "../src/server/factory.ts", "../src/ws/envelope.ts", "../src/ws/runtime.ts", "../src/ws/adapter.ts", "../src/ws/pubsub.ts", "../src/ws/relay.ts", "../src/server/application.ts", "../src/server/request-logging.ts", "../src/server/routes.ts", "../src/server/input.ts", "../src/server/middleware.ts", "../src/server/settings.ts", "../src/static/files.ts", "../src/static/options.ts", "../src/static/module.ts", "../src/ws/decorators.ts", "../src/ws/redis-relay.ts", "../src/health/contracts.ts", "../src/health/controller.ts", "../src/health/registry.ts", "../src/health/indicators.ts", "../src/health/module.ts", "../src/health/readiness.ts"],
3
+ "sources": ["../src/route/marker.ts", "../src/route/decorators.ts", "../src/route/discover.ts", "../src/route/metadata.ts", "../src/inspect.ts", "../src/ws/discover.ts", "../src/ws/marker.ts", "../src/server/client-address.ts", "../src/server/context.ts", "../src/server/cors.ts", "../src/server/errors.ts", "../src/server/factory.ts", "../src/ws/envelope.ts", "../src/ws/middleware.ts", "../src/ws/runtime.ts", "../src/ws/adapter.ts", "../src/ws/logging.ts", "../src/ws/pubsub.ts", "../src/ws/relay.ts", "../src/server/application.ts", "../src/server/request-logging.ts", "../src/server/routes.ts", "../src/server/input.ts", "../src/server/middleware.ts", "../src/server/settings.ts", "../src/static/files.ts", "../src/static/options.ts", "../src/static/module.ts", "../src/throttle/decorators.ts", "../src/throttle/guard.ts", "../src/throttle/options.ts", "../src/throttle/store.ts", "../src/throttle/module.ts", "../src/ws/decorators.ts", "../src/ws/redis-relay.ts", "../src/health/contracts.ts", "../src/health/controller.ts", "../src/health/registry.ts", "../src/health/indicators.ts", "../src/health/module.ts", "../src/health/readiness.ts"],
4
4
  "sourcesContent": [
5
5
  "// Symbol.for, so two copies of @dunx/http in a tree still agree on the key. The\n// marker goes on the method function itself - nothing accumulates at class\n// definition time, so there is no ordering dependence and no cross-file leak.\n// See docs/architecture/http.md, \"Route discovery\".\nimport type { RouteSchemas } from './schema.js';\n\nconst ROUTE = Symbol.for('dunx.route');\nconst CONTROLLER = Symbol.for('dunx.controller');\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * A literal path, or a thunk read at **discovery** rather than at decoration.\n *\n * Discovery runs after every provider has settled, which is the whole point: a\n * path that came out of validated configuration is knowable by then even though\n * a decorator's arguments were evaluated long before the container existed.\n * `OpenApiModule.forRootAsync` is what needs it - it mounts its page and its\n * document where `ConfigService` says. The thunk is called once per discovery,\n * so it has to answer the same thing every time.\n */\nexport type RoutePath = string | (() => string);\n\nexport interface RouteMeta {\n readonly method: HttpMethod;\n readonly path: RoutePath;\n /** The decorator's second argument. `buildRoutes` resolves it once, at boot. */\n readonly options?: RouteSchemas | undefined;\n}\n\nexport const resolvePath = (path: RoutePath): string =>\n typeof path === 'function' ? path() : path;\n\ninterface RouteMarked {\n readonly [ROUTE]?: RouteMeta;\n}\n\ninterface ControllerMarked {\n readonly [CONTROLLER]?: string;\n}\n\nexport const markRoute = (target: object, meta: RouteMeta): void => {\n Object.defineProperty(target, ROUTE, { value: meta, configurable: true });\n};\n\nexport const routeMetaOf = (value: unknown): RouteMeta | undefined =>\n typeof value === 'function' ? (value as RouteMarked)[ROUTE] : undefined;\n\nexport const markController = (target: object, prefix: string): void => {\n Object.defineProperty(target, CONTROLLER, {\n value: prefix,\n configurable: true,\n });\n};\n\n// Plain lookup, not Object.hasOwn: a subclass inherits its base's prefix, so two\n// subclasses of one decorated base collide loudly instead of silently mounting at\n// the root.\nexport const prefixOf = (target: object): string =>\n (target as ControllerMarked)[CONTROLLER] ?? '';\n",
6
6
  "import {\n markController,\n markRoute,\n type HttpMethod,\n type RoutePath,\n} from './marker.js';\nimport type { Input, RouteSchemas } from './schema.js';\n\ntype ControllerTarget = abstract new (...args: never[]) => object;\n\nexport const Controller =\n (prefix = '') =>\n <T extends ControllerTarget>(target: T): T => {\n markController(target, prefix);\n return target;\n };\n\n/**\n * `const O` is load-bearing: without it `{ body: CreateNote, status: 201 }` widens\n * to `RouteSchemas` and `Input<typeof opts>` degrades to bare `{ req }`, taking the\n * type check with it.\n *\n * The `M` constraint is the guarantee. A wrongly annotated `input` is a\n * `TS1241` + `TS1270` naming the mismatched property; an unannotated one is\n * `TS7006`. Inference is impossible here - see docs/architecture/constraints.md, \"A route\n * decorator can *check* a handler's input type but cannot *infer* it\".\n */\nconst verb =\n (method: HttpMethod) =>\n <const O extends RouteSchemas>(path: RoutePath = '/', options?: O) =>\n <M extends (input: Input<O>) => unknown>(\n value: M,\n _context: ClassMethodDecoratorContext,\n ): M => {\n markRoute(value, { method, path, options });\n return value;\n };\n\nexport const Get = verb('GET');\nexport const Post = verb('POST');\nexport const Put = verb('PUT');\nexport const Patch = verb('PATCH');\nexport const Delete = verb('DELETE');\n",
@@ -12,22 +12,29 @@
12
12
  "import type { BunRequest, Server } from 'bun';\nimport { AppError } from '@dunx/core';\n\nexport interface AddressSource {\n readonly server: Server<unknown>;\n readonly trustProxy: boolean | number;\n}\n\n/**\n * How many entries at the right-hand end of `X-Forwarded-For` were written by a\n * proxy under our control. `true` is one, which is the single-proxy deployment.\n */\nconst trustedHops = (setting: boolean | number): number => {\n if (setting === true) return 1;\n if (setting === false) return 0;\n return Number.isFinite(setting) ? Math.max(0, Math.trunc(setting)) : 0;\n};\n\n// Kept off the class so `ClientAddress`'s public shape stays `of(req)`. Per\n// instance rather than module-level, because two apps in one process (every test\n// file) must not share a server.\nconst sources = new WeakMap<ClientAddress, AddressSource>();\n\n/**\n * The client's address, honouring the `'trust proxy'` setting.\n *\n * With the setting on, the address is read from `X-Forwarded-For` counting from\n * the right by the number of trusted hops, never from the left. A client can put\n * anything in the header it sends; only the entries a proxy appended carry any\n * weight, and there are exactly as many of those as there are proxies in front of\n * this server.\n *\n * Bound and exported by `HttpFactory`'s global wrapper module, so injecting it in a\n * middleware or controller needs no registration and `app.clientIp(req)` is the same\n * instance. That binding is not optional under module scoping: an unbound class\n * self-binds into whichever scope asks first, so a second module injecting it was a\n * boot error naming the first, and `listen()` could attach the server to an instance\n * nothing else held.\n */\nexport class ClientAddress {\n of(req: BunRequest): string | undefined {\n const source = sources.get(this);\n if (!source) {\n throw new AppError(\n 'ClientAddress has no server yet. The address comes from the live Bun ' +\n 'server, so it is only available once listen() has run.',\n );\n }\n\n const hops = trustedHops(source.trustProxy);\n if (hops > 0) {\n const entries = (req.headers.get('x-forwarded-for') ?? '')\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n // Each proxy appends the peer it saw, so the last entry is the only one a\n // single trusted proxy wrote. Reading `[0]` returned whatever the caller\n // sent, which a caller may invent. A count longer than the header clamps\n // to the leftmost entry rather than reaching past it.\n const entry = entries[Math.max(0, entries.length - hops)];\n if (entry) return entry;\n }\n return source.server.requestIP(req)?.address;\n }\n}\n\n/** Internal: `listen()` hands the bound server to the resolved singleton. */\nexport const attachAddressSource = (\n target: ClientAddress,\n source: AddressSource,\n): void => {\n sources.set(target, source);\n};\n",
13
13
  "import type { DiscoveredRoute } from '../route/discover.js';\nimport type { HttpMethod } from '../route/marker.js';\nimport type { MetaKey, MetaRecord } from '../route/metadata.js';\n\n/**\n * Which route the middleware is running for, and what that route's decorators\n * declared. `get` resolves the handler's metadata first and the controller class's\n * second - the usual override direction for handler-over-class metadata.\n */\nexport interface RouteContext {\n readonly controller: string;\n readonly handler: string;\n readonly method: HttpMethod;\n readonly path: string;\n get<T>(key: MetaKey<T>): T | undefined;\n}\n\nconst EMPTY: MetaRecord = new Map();\n\n/**\n * One frozen context per route, built when the table is built and closed over by\n * the chain. The merge already happened at discovery, so `get` is a Map lookup -\n * not a prototype walk, and nothing is read per request.\n */\nexport const buildContext = (route: DiscoveredRoute): RouteContext => {\n const record = route.meta ?? EMPTY;\n return Object.freeze({\n controller: route.controller,\n handler: route.handlerName,\n method: route.method,\n path: route.path,\n get: <T>(key: MetaKey<T>): T | undefined =>\n record.get(key.id) as T | undefined,\n });\n};\n",
14
14
  "import type { RouteHandler } from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\nexport type CorsOrigin =\n | string\n | readonly string[]\n | ((origin: string) => boolean);\n\nexport interface CorsOptions {\n /**\n * `'*'` by default. A concrete string, a list, or a predicate all answer with the\n * caller's own origin only when it is allowed - a request from anywhere else gets\n * no CORS headers at all, which is what makes the browser block it.\n */\n readonly origin?: CorsOrigin;\n /** Defaults to the methods actually declared on the path. */\n readonly methods?: readonly string[];\n /** Echoes `Access-Control-Request-Headers` when omitted. */\n readonly allowedHeaders?: readonly string[];\n readonly exposedHeaders?: readonly string[];\n readonly credentials?: boolean;\n /** Seconds a browser may cache the preflight for. */\n readonly maxAge?: number;\n}\n\nconst ORIGIN = 'access-control-allow-origin';\n\n/**\n * `*` is illegal alongside credentials - a browser rejects the pair - so a\n * credentialed wildcard reflects the caller instead.\n */\nconst allowedOrigin = (\n options: CorsOptions,\n requested: string | null,\n): string | undefined => {\n const origin = options.origin ?? '*';\n\n if (typeof origin === 'string') {\n if (origin !== '*') return origin === requested ? origin : undefined;\n if (!options.credentials) return '*';\n return requested ?? undefined;\n }\n if (requested === null) return undefined;\n\n const allowed =\n typeof origin === 'function'\n ? origin(requested)\n : origin.includes(requested);\n return allowed ? requested : undefined;\n};\n\nconst applyCors = (\n options: CorsOptions,\n req: Request,\n response: Response,\n): Response => {\n const origin = allowedOrigin(options, req.headers.get('origin'));\n if (origin === undefined) return response;\n\n response.headers.set(ORIGIN, origin);\n // The response body varies by request origin unless every origin gets the same\n // wildcard, so a shared cache must not serve one origin's copy to another.\n if (origin !== '*') response.headers.append('vary', 'Origin');\n if (options.credentials) {\n response.headers.set('access-control-allow-credentials', 'true');\n }\n if (options.exposedHeaders?.length) {\n response.headers.set(\n 'access-control-expose-headers',\n options.exposedHeaders.join(', '),\n );\n }\n return response;\n};\n\n/** Adds the response-side CORS headers. One extra closure per route, at boot. */\nexport const withCors = (\n options: CorsOptions,\n handler: RouteHandler,\n): RouteHandler => {\n return async (req) => applyCors(options, req, await handler(req));\n};\n\n/**\n * `Bun.serve({ routes })` answers a method miss with 404, so a preflight cannot be\n * inferred - every CORS-enabled path gets its own `OPTIONS` handler, built at boot\n * from the methods that path actually declares.\n */\nexport const preflight = (\n options: CorsOptions,\n methods: readonly string[],\n): RouteHandler => {\n const allowMethods = (options.methods ?? methods).join(', ');\n\n return async (req) => {\n const response = applyCors(\n options,\n req,\n new Response(null, { status: HttpStatusCode.NO_CONTENT }),\n );\n // Origin not allowed: 204 with no CORS headers, which fails the preflight.\n if (!response.headers.has(ORIGIN)) return response;\n\n response.headers.set('access-control-allow-methods', allowMethods);\n\n const allowHeaders =\n options.allowedHeaders ??\n (req.headers.get('access-control-request-headers') ?? '')\n .split(',')\n .map((header) => header.trim())\n .filter((header) => header.length > 0);\n if (allowHeaders.length > 0) {\n response.headers.set(\n 'access-control-allow-headers',\n allowHeaders.join(', '),\n );\n }\n if (options.maxAge !== undefined) {\n response.headers.set('access-control-max-age', String(options.maxAge));\n }\n return response;\n };\n};\n",
15
- "import { AppError, ConsoleLogger, type Ctor, type Logger } from '@dunx/core';\nimport { HttpStatusCode } from './status.js';\n\nexport class HttpError extends AppError {\n override name = 'HttpError';\n\n constructor(\n readonly status: number,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n }\n}\nObject.defineProperty(HttpError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly status: number\" }, { unresolved: \"message: string\" }, ErrorOptions],\n});\n\n/** Which declared schema rejected the request. */\nexport type InputSource = 'body' | 'query' | 'params';\n\n/** A Standard Schema issue, flattened: `path` is dotted, or absent at the root. */\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: string;\n}\n\n/**\n * A declared schema rejected the input. Always a 400, and the issues survive into\n * the response body - a caller cannot fix what it cannot see.\n */\nexport class ValidationError extends HttpError {\n override name = 'ValidationError';\n\n constructor(\n readonly source: InputSource,\n readonly issues: readonly ValidationIssue[],\n ) {\n super(HttpStatusCode.BAD_REQUEST, `Invalid ${source}`);\n }\n}\nObject.defineProperty(ValidationError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly source: InputSource\" }, { unresolved: \"readonly issues: readonly ValidationIssue[]\" }],\n});\n\nexport type ErrorMapper = (error: unknown, req: Request) => Response;\n\n/**\n * The class form of {@link ErrorMapper}, and the one to reach for in an app.\n *\n * A mapper is a function, which means it cannot inject: the interesting ones need\n * the app's config to decide how much of an error to reveal, or its `Logger` to\n * record the ones that became a 500. dunx's own default proves the point - it is\n * `errorMapper(logger)`, a curried factory, because currying was the only way to\n * hand a function a dependency.\n *\n * A filter is resolved **from the container**, exactly as `HttpOptions.middleware`\n * entries are, so it takes whatever it needs as constructor parameters:\n *\n * ```ts\n * export class AppErrorFilter extends ErrorFilter {\n * constructor(\n * private readonly logger: Logger,\n * private readonly config: AppConfigService,\n * ) {}\n *\n * catch(error: unknown, req: Request): Response {\n * ...\n * }\n * }\n *\n * // It is a provider like any other, so it goes in a module:\n * @Module({ providers: [AppErrorFilter] })\n * // and then:\n * HttpFactory.create(root, { onError: AppErrorFilter });\n * ```\n *\n * `abstract class` rather than an interface, so it is a runtime value and therefore\n * usable as an injection token - an app that wants to swap filters by binding one\n * can. Extending it is optional: `onError` accepts any class with a matching\n * `catch`, because the check is structural.\n *\n * The method is `catch` to match the vocabulary of the thing it replaces, NestJS's\n * `ExceptionFilter.catch`. A filter that cannot handle an error should rethrow it,\n * or delegate to `defaultErrorMapper`.\n */\nexport abstract class ErrorFilter {\n abstract catch(error: unknown, req: Request): Response;\n}\n\n/**\n * What `onError` accepts. A bare mapper still works and is the cheaper thing for a\n * filter with no dependencies; a class is what an app that needs one uses.\n */\nexport type ErrorHandler = ErrorMapper | Ctor<ErrorFilter>;\n\n/**\n * Whether `onError` was given a class rather than a mapper.\n *\n * Both are `typeof === 'function'`, so the discriminator is the prototype carrying\n * a `catch`: a class declaration always has one, and neither an arrow function nor\n * a `function` expression ever does. Checking `prototype` alone would be wrong -\n * `function mapper() {}` has an empty one.\n */\nexport const isErrorFilter = (\n handler: ErrorHandler,\n): handler is Ctor<ErrorFilter> =>\n typeof handler === 'function' &&\n // Narrowed through a structural shape rather than `Ctor`: a construct signature\n // has no `prototype` in the type system, so `Partial<Ctor<T>>` cannot see it.\n typeof (handler as { prototype?: { catch?: unknown } }).prototype?.catch ===\n 'function';\n\n/**\n * Narrows an `ErrorHandler` to the mapper the request path actually calls.\n *\n * `resolve` is typed for this one token rather than generically: the only thing ever\n * looked up here is the filter, and a `<T>(token: Ctor<T>) => T` signature makes\n * every caller - a test included - satisfy a polymorphic contract it does not need.\n */\nexport const toErrorMapper = (\n handler: ErrorHandler,\n resolve: (token: Ctor<ErrorFilter>) => ErrorFilter,\n): ErrorMapper =>\n isErrorFilter(handler)\n ? (error, req) => resolve(handler).catch(error, req)\n : handler;\n\n/**\n * The mapper `HttpFactory` installs unless `onError` replaces it, built from the\n * app's **bound** `Logger` - so a service that imported `@dunx/infra/logger` gets\n * the stack as one `@arkv/logger` entry, sanitized and shaped like every other.\n *\n * An `HttpError` is not logged here at all: the status is the whole record, and\n * `RequestLoggingMiddleware` already writes the 4xx line. Only an error nothing\n * declared - the one that becomes a 500 - is worth a stack.\n *\n * The error goes in as its own argument rather than as a field of an object.\n * `JSON.stringify(new Error('x'))` is `{}`, so `{ err: error }` would drop the\n * stack; every `Logger` implementation picks an `Error` argument out and\n * serialises it.\n */\nexport const errorMapper =\n (logger: Logger): ErrorMapper =>\n (error) => {\n if (error instanceof ValidationError) {\n return Response.json(\n { error: error.message, status: error.status, issues: error.issues },\n { status: error.status },\n );\n }\n if (error instanceof HttpError) {\n return Response.json(\n { error: error.message, status: error.status },\n { status: error.status },\n );\n }\n logger.error('Unhandled error', error);\n return Response.json(\n {\n error: 'Internal Server Error',\n status: HttpStatusCode.INTERNAL_SERVER_ERROR,\n },\n { status: HttpStatusCode.INTERNAL_SERVER_ERROR },\n );\n };\n\n/**\n * The same mapper with no container behind it, for `buildRoutes` and\n * `buildFallback` called directly. It writes through core's `ConsoleLogger`, which\n * is one JSON line - the point being that nothing in this package ever reaches for\n * `console.error` and emits a multi-line dump a collector reads as several broken\n * records. An app gets {@link errorMapper} over its own bound logger instead.\n */\nexport const defaultErrorMapper: ErrorMapper = errorMapper(new ConsoleLogger());\n",
16
- "import {\n collectModules,\n AppError,\n AppFactory,\n Logger,\n provide,\n readControllers,\n RequestContext,\n type Ctor,\n type DynamicModule,\n type ModuleRef,\n} from '@dunx/core';\nimport { discoverRoutes, type DiscoveredRoute } from '../route/discover.js';\nimport { ClientAddress } from './client-address.js';\nimport { buildWebSocket } from '../ws/adapter.js';\nimport { discoverGateways } from '../ws/discover.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport {\n HttpApplication,\n type HttpApp,\n type HttpOptions,\n} from './application.js';\nimport type { Middleware } from './middleware.js';\nimport { RequestLoggingMiddleware } from './request-logging.js';\nimport { assertNoCollisions } from './routes.js';\n\nexport type { HttpApp, HttpOptions } from './application.js';\n\n// Bound around the user's root so `PubSub` is injectable without importing\n// anything. Its name is what a duplicate binding of PubSub would be reported\n// against, which is why it is a named class and not an object literal.\n//\n// `global: true` is what makes that \"without importing anything\" true under module\n// scoping. This module *imports* the root rather than being imported by it, and\n// visibility only flows from an import's exports to its importer - so without global\n// these bindings would be invisible to every module in the app, which is the opposite\n// of the intent. They are framework services with no module for an app to import.\nclass HttpModule {}\n\nexport class HttpFactory {\n /**\n * Boots the container, discovers every controller's routes and every gateway's\n * handlers, and rejects a collision in either. The `Bun.serve` route table itself\n * is built by `listen()`, so `setGlobalPrefix`, `use`, `set` and `enableCors` can\n * still affect it.\n */\n static async create(\n root: ModuleRef,\n options: HttpOptions = {},\n ): Promise<HttpApp> {\n // Bound here rather than left to self-binding, because its constructor takes\n // the options object as well as two injectables. `Logger` and\n // `RequestContext` always resolve: @dunx/core binds a default for each.\n const logging = provide(RequestLoggingMiddleware, {\n useFactory: (logger: Logger, context: RequestContext) =>\n new RequestLoggingMiddleware(\n logger,\n context,\n typeof options.requestLogging === 'object'\n ? options.requestLogging\n : {},\n ),\n inject: [Logger, RequestContext] as const,\n });\n\n // `ClientAddress` belongs here for the same reason `PubSub` does: `listen()`\n // hands one instance the live server, and `app.clientIp(req)` is documented as\n // that instance. Left to self-binding it landed in whichever scope asked first,\n // so a second module injecting it was a boot error naming the first - and the\n // app's own `app.get(ClientAddress)` could then reach an instance no server was\n // ever attached to.\n const services = [PubSub, ClientAddress];\n const providers =\n options.requestLogging === false ? services : [...services, logging];\n const scope: DynamicModule = {\n module: HttpModule,\n global: true,\n imports: [root],\n providers,\n exports: providers.map((entry) =>\n typeof entry === 'function' ? entry : entry.token,\n ),\n };\n // Spread rather than passed through, because `exactOptionalPropertyTypes`\n // separates an absent `overrides` from one explicitly set to undefined.\n const app = await AppFactory.create(\n scope,\n options.overrides ? { overrides: options.overrides } : {},\n );\n const modules = collectModules(scope);\n\n const discovered: DiscoveredRoute[] = [];\n for (const module of modules) {\n // The module's own middleware, applied to the routes its controllers declare\n // and to nothing else. Carried on each route with the module it came from, so it\n // resolves from that module's scope rather than the app's root.\n const moduleMiddleware = module.options.middleware ?? [];\n for (const controller of readControllers(module)) {\n const routes = discoverRoutes(\n app.get(controller, module.ref) as object,\n );\n if (routes.length === 0) {\n throw new AppError(\n `${controller.name} is registered as a controller but declares no routes. ` +\n 'Add a @Get/@Post/... method, or move it to providers.',\n );\n }\n discovered.push(\n ...routes.map((route) => ({\n ...route,\n module: module.ref,\n ...(moduleMiddleware.length === 0\n ? {}\n : {\n moduleMiddleware:\n moduleMiddleware as readonly Ctor<Middleware>[],\n }),\n })),\n );\n }\n }\n // Eagerly, so a wiring error still surfaces from create() rather than waiting\n // for listen(). A uniform global prefix cannot introduce a new one.\n assertNoCollisions(discovered);\n\n const gateways = discoverGateways(modules, (token) => app.get(token));\n // Handler collisions and two gateways on one path are boot errors too, and the\n // websocket object is built once here rather than per connection.\n const websocket =\n gateways.length > 0\n ? buildWebSocket(gateways, options.websocket)\n : undefined;\n\n // `root` is the app's own module, so global middleware and the error filter\n // resolve as the app sees them rather than as this wrapper does.\n return new HttpApplication(app, discovered, options, root, websocket);\n }\n}\n",
15
+ "import { AppError, ConsoleLogger, type Ctor, type Logger } from '@dunx/core';\nimport { HttpStatusCode } from './status.js';\n\nexport interface HttpErrorOptions extends ErrorOptions {\n /**\n * Headers the error response carries. `Retry-After` on a 429,\n * `WWW-Authenticate` on a 401, `Allow` on a 405 - each of them part of the\n * status rather than an extra, and none of them expressible by a throw before\n * this existed.\n *\n * {@link errorMapper} copies them onto the response. An app that replaces the\n * mapper has to read them itself, which is the same contract `status` and\n * `message` already have.\n */\n readonly headers?: Readonly<Record<string, string>>;\n}\n\nexport class HttpError extends AppError {\n override name = 'HttpError';\n readonly headers: Readonly<Record<string, string>> | undefined;\n\n constructor(\n readonly status: number,\n message: string,\n options?: HttpErrorOptions,\n ) {\n super(message, options);\n this.headers = options?.headers;\n }\n}\nObject.defineProperty(HttpError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly status: number\" }, { unresolved: \"message: string\" }, { unresolved: \"options?: HttpErrorOptions\" }],\n});\n\n/** Which declared schema rejected the request. */\nexport type InputSource = 'body' | 'query' | 'params';\n\n/** A Standard Schema issue, flattened: `path` is dotted, or absent at the root. */\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: string;\n}\n\n/**\n * A declared schema rejected the input. Always a 400, and the issues survive into\n * the response body - a caller cannot fix what it cannot see.\n */\nexport class ValidationError extends HttpError {\n override name = 'ValidationError';\n\n constructor(\n readonly source: InputSource,\n readonly issues: readonly ValidationIssue[],\n ) {\n super(HttpStatusCode.BAD_REQUEST, `Invalid ${source}`);\n }\n}\nObject.defineProperty(ValidationError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly source: InputSource\" }, { unresolved: \"readonly issues: readonly ValidationIssue[]\" }],\n});\n\nexport type ErrorMapper = (error: unknown, req: Request) => Response;\n\n/**\n * The class form of {@link ErrorMapper}, and the one to reach for in an app.\n *\n * A mapper is a function, which means it cannot inject: the interesting ones need\n * the app's config to decide how much of an error to reveal, or its `Logger` to\n * record the ones that became a 500. dunx's own default proves the point - it is\n * `errorMapper(logger)`, a curried factory, because currying was the only way to\n * hand a function a dependency.\n *\n * A filter is resolved **from the container**, exactly as `HttpOptions.middleware`\n * entries are, so it takes whatever it needs as constructor parameters:\n *\n * ```ts\n * export class AppErrorFilter extends ErrorFilter {\n * constructor(\n * private readonly logger: Logger,\n * private readonly config: AppConfigService,\n * ) {}\n *\n * catch(error: unknown, req: Request): Response {\n * ...\n * }\n * }\n *\n * // It is a provider like any other, so it goes in a module:\n * @Module({ providers: [AppErrorFilter] })\n * // and then:\n * HttpFactory.create(root, { onError: AppErrorFilter });\n * ```\n *\n * `abstract class` rather than an interface, so it is a runtime value and therefore\n * usable as an injection token - an app that wants to swap filters by binding one\n * can. Extending it is optional: `onError` accepts any class with a matching\n * `catch`, because the check is structural.\n *\n * The method is `catch` to match the vocabulary of the thing it replaces, NestJS's\n * `ExceptionFilter.catch`. A filter that cannot handle an error should rethrow it,\n * or delegate to `defaultErrorMapper`.\n */\nexport abstract class ErrorFilter {\n abstract catch(error: unknown, req: Request): Response;\n}\n\n/**\n * What `onError` accepts. A bare mapper still works and is the cheaper thing for a\n * filter with no dependencies; a class is what an app that needs one uses.\n */\nexport type ErrorHandler = ErrorMapper | Ctor<ErrorFilter>;\n\n/**\n * Whether `onError` was given a class rather than a mapper.\n *\n * Both are `typeof === 'function'`, so the discriminator is the prototype carrying\n * a `catch`: a class declaration always has one, and neither an arrow function nor\n * a `function` expression ever does. Checking `prototype` alone would be wrong -\n * `function mapper() {}` has an empty one.\n */\nexport const isErrorFilter = (\n handler: ErrorHandler,\n): handler is Ctor<ErrorFilter> =>\n typeof handler === 'function' &&\n // Narrowed through a structural shape rather than `Ctor`: a construct signature\n // has no `prototype` in the type system, so `Partial<Ctor<T>>` cannot see it.\n typeof (handler as { prototype?: { catch?: unknown } }).prototype?.catch ===\n 'function';\n\n/**\n * Narrows an `ErrorHandler` to the mapper the request path actually calls.\n *\n * `resolve` is typed for this one token rather than generically: the only thing ever\n * looked up here is the filter, and a `<T>(token: Ctor<T>) => T` signature makes\n * every caller - a test included - satisfy a polymorphic contract it does not need.\n */\nexport const toErrorMapper = (\n handler: ErrorHandler,\n resolve: (token: Ctor<ErrorFilter>) => ErrorFilter,\n): ErrorMapper =>\n isErrorFilter(handler)\n ? (error, req) => resolve(handler).catch(error, req)\n : handler;\n\n/**\n * The mapper `HttpFactory` installs unless `onError` replaces it, built from the\n * app's **bound** `Logger` - so a service that imported `@dunx/infra/logger` gets\n * the stack as one `@arkv/logger` entry, sanitized and shaped like every other.\n *\n * An `HttpError` is not logged here at all: the status is the whole record, and\n * `RequestLoggingMiddleware` already writes the 4xx line. Only an error nothing\n * declared - the one that becomes a 500 - is worth a stack.\n *\n * The error goes in as its own argument rather than as a field of an object.\n * `JSON.stringify(new Error('x'))` is `{}`, so `{ err: error }` would drop the\n * stack; every `Logger` implementation picks an `Error` argument out and\n * serialises it.\n */\nexport const errorMapper =\n (logger: Logger): ErrorMapper =>\n (error) => {\n if (error instanceof ValidationError) {\n return Response.json(\n { error: error.message, status: error.status, issues: error.issues },\n {\n status: error.status,\n ...(error.headers && { headers: error.headers }),\n },\n );\n }\n if (error instanceof HttpError) {\n return Response.json(\n { error: error.message, status: error.status },\n {\n status: error.status,\n ...(error.headers && { headers: error.headers }),\n },\n );\n }\n logger.error('Unhandled error', error);\n return Response.json(\n {\n error: 'Internal Server Error',\n status: HttpStatusCode.INTERNAL_SERVER_ERROR,\n },\n { status: HttpStatusCode.INTERNAL_SERVER_ERROR },\n );\n };\n\n/**\n * The same mapper with no container behind it, for `buildRoutes` and\n * `buildFallback` called directly. It writes through core's `ConsoleLogger`, which\n * is one JSON line - the point being that nothing in this package ever reaches for\n * `console.error` and emits a multi-line dump a collector reads as several broken\n * records. An app gets {@link errorMapper} over its own bound logger instead.\n */\nexport const defaultErrorMapper: ErrorMapper = errorMapper(new ConsoleLogger());\n",
16
+ "import {\n collectModules,\n AppError,\n AppFactory,\n Logger,\n provide,\n readControllers,\n RequestContext,\n type Ctor,\n type DynamicModule,\n type ModuleRef,\n} from '@dunx/core';\nimport { discoverRoutes, type DiscoveredRoute } from '../route/discover.js';\nimport { ClientAddress } from './client-address.js';\nimport { buildWebSocket } from '../ws/adapter.js';\nimport { discoverGateways } from '../ws/discover.js';\nimport { SocketLoggingMiddleware } from '../ws/logging.js';\nimport type { SocketMiddleware } from '../ws/middleware.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport {\n HttpApplication,\n type HttpApp,\n type HttpOptions,\n} from './application.js';\nimport type { Middleware } from './middleware.js';\nimport { RequestLoggingMiddleware } from './request-logging.js';\nimport { assertNoCollisions } from './routes.js';\n\nexport type { HttpApp, HttpOptions } from './application.js';\n\n// Bound around the user's root so `PubSub` is injectable without importing\n// anything. Its name is what a duplicate binding of PubSub would be reported\n// against, which is why it is a named class and not an object literal.\n//\n// `global: true` is what makes that \"without importing anything\" true under module\n// scoping. This module *imports* the root rather than being imported by it, and\n// visibility only flows from an import's exports to its importer - so without global\n// these bindings would be invisible to every module in the app, which is the opposite\n// of the intent. They are framework services with no module for an app to import.\nclass HttpModule {}\n\nexport class HttpFactory {\n /**\n * Boots the container, discovers every controller's routes and every gateway's\n * handlers, and rejects a collision in either. The `Bun.serve` route table itself\n * is built by `listen()`, so `setGlobalPrefix`, `use`, `set` and `enableCors` can\n * still affect it.\n */\n static async create(\n root: ModuleRef,\n options: HttpOptions = {},\n ): Promise<HttpApp> {\n // Bound here rather than left to self-binding, because its constructor takes\n // the options object as well as two injectables. `Logger` and\n // `RequestContext` always resolve: @dunx/core binds a default for each.\n const logging = provide(RequestLoggingMiddleware, {\n useFactory: (logger: Logger, context: RequestContext) =>\n new RequestLoggingMiddleware(\n logger,\n context,\n typeof options.requestLogging === 'object'\n ? options.requestLogging\n : {},\n ),\n inject: [Logger, RequestContext] as const,\n });\n\n // `ClientAddress` belongs here for the same reason `PubSub` does: `listen()`\n // hands one instance the live server, and `app.clientIp(req)` is documented as\n // that instance. Left to self-binding it landed in whichever scope asked first,\n // so a second module injecting it was a boot error naming the first - and the\n // app's own `app.get(ClientAddress)` could then reach an instance no server was\n // ever attached to.\n // Bound for the same reason: its constructor takes an options object as well\n // as two injectables, so it cannot self-bind.\n const socketLogging = provide(SocketLoggingMiddleware, {\n useFactory: (logger: Logger, context: RequestContext) =>\n new SocketLoggingMiddleware(\n logger,\n context,\n typeof options.socketLogging === 'object'\n ? options.socketLogging\n : {},\n ),\n inject: [Logger, RequestContext] as const,\n });\n\n const services = [PubSub, ClientAddress];\n const providers = [\n ...services,\n ...(options.requestLogging === false ? [] : [logging]),\n ...(options.socketLogging === false ? [] : [socketLogging]),\n ];\n const scope: DynamicModule = {\n module: HttpModule,\n global: true,\n imports: [root],\n providers,\n exports: providers.map((entry) =>\n typeof entry === 'function' ? entry : entry.token,\n ),\n };\n // Spread rather than passed through, because `exactOptionalPropertyTypes`\n // separates an absent `overrides` from one explicitly set to undefined.\n const app = await AppFactory.create(\n scope,\n options.overrides ? { overrides: options.overrides } : {},\n );\n const modules = collectModules(scope);\n\n const discovered: DiscoveredRoute[] = [];\n for (const module of modules) {\n // The module's own middleware, applied to the routes its controllers declare\n // and to nothing else. Carried on each route with the module it came from, so it\n // resolves from that module's scope rather than the app's root.\n const moduleMiddleware = module.options.middleware ?? [];\n for (const controller of readControllers(module)) {\n const routes = discoverRoutes(\n app.get(controller, module.ref) as object,\n );\n if (routes.length === 0) {\n throw new AppError(\n `${controller.name} is registered as a controller but declares no routes. ` +\n 'Add a @Get/@Post/... method, or move it to providers.',\n );\n }\n discovered.push(\n ...routes.map((route) => ({\n ...route,\n module: module.ref,\n ...(moduleMiddleware.length === 0\n ? {}\n : {\n moduleMiddleware:\n moduleMiddleware as readonly Ctor<Middleware>[],\n }),\n })),\n );\n }\n }\n // Eagerly, so a wiring error still surfaces from create() rather than waiting\n // for listen(). A uniform global prefix cannot introduce a new one.\n assertNoCollisions(discovered);\n\n const gateways = discoverGateways(modules, (token) => app.get(token));\n // Handler collisions and two gateways on one path are boot errors too, and the\n // websocket object is built once here rather than per connection.\n //\n // The socket middleware chain is resolved here and not at `listen()`, because\n // `buildWebSocket` folds it into one closure per slot - the same trade the HTTP\n // route table makes, moved a phase earlier because the handler object is.\n const websocket =\n gateways.length > 0\n ? buildWebSocket(\n gateways,\n options.websocket,\n HttpFactory.#socketMiddleware(app, root, options),\n )\n : undefined;\n\n // `root` is the app's own module, so global middleware and the error filter\n // resolve as the app sees them rather than as this wrapper does.\n return new HttpApplication(app, discovered, options, root, websocket);\n }\n\n /**\n * Logging outermost, then whatever the app declared - the order the HTTP chain\n * already uses, so a frame a guard refuses is still logged with the failure.\n *\n * Resolved permissively, like global HTTP middleware: the class is usually\n * declared by whichever feature module owns it, and pinning the lookup to the\n * root would make the app re-export every observer it lists.\n */\n static #socketMiddleware(\n app: { get<T>(token: Ctor<T>, from?: ModuleRef): T },\n root: ModuleRef,\n options: HttpOptions,\n ): readonly SocketMiddleware[] {\n const declared = options.socketMiddleware ?? [];\n const entries: readonly Ctor<SocketMiddleware>[] =\n options.socketLogging === false\n ? declared\n : [SocketLoggingMiddleware, ...declared];\n return entries.map((entry) => app.get(entry, root));\n }\n}\n",
17
17
  "/**\n * The whole wire protocol: one JSON object, an event name, and a payload. It is\n * only ever read for a gateway that declares at least one `@OnMessage(event)`\n * handler - a gateway with only a raw `@OnMessage()` never parses anything.\n */\nexport interface Envelope {\n readonly event: string;\n readonly data?: unknown;\n}\n\nexport const encode = (event: string, data: unknown): string =>\n JSON.stringify({ event, data });\n\n/**\n * `undefined` for anything that is not an envelope - binary frames, invalid JSON,\n * a non-object, or a missing `event`. Those fall through to the raw handler\n * instead of being rejected here.\n */\nexport const decode = (message: string | Buffer): Envelope | undefined => {\n if (typeof message !== 'string') return undefined;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch {\n return undefined;\n }\n\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const { event, data } = parsed as { event?: unknown; data?: unknown };\n return typeof event === 'string' ? { event, data } : undefined;\n};\n",
18
+ "import type { HandlerKind } from './marker.js';\nimport type { Socket } from './socket.js';\n\n/**\n * Which handler a frame is on its way to, resolved at boot.\n *\n * The websocket half of {@link RouteContext}: it names the gateway rather than the\n * controller, and the envelope event rather than the method and path. One object\n * per slot, built once, so a middleware costs no allocation per frame beyond the\n * frame itself.\n */\nexport interface SocketContext {\n /** The gateway class's name. */\n readonly gateway: string;\n /** The path it upgraded on, exactly as mounted. */\n readonly path: string;\n readonly kind: HandlerKind;\n /**\n * The `@OnMessage(event)` name. `undefined` for a lifecycle hook and for the raw\n * `@OnMessage()` catch-all, which claims every frame no named handler took.\n */\n readonly event: string | undefined;\n}\n\n/**\n * The frame itself: the socket it arrived on, and the argument the handler is\n * about to be given.\n *\n * `data` is the envelope's `data` for a named message, the whole frame for the raw\n * catch-all, `{ code, reason }` for a close, the buffer for a ping or a pong, and\n * `undefined` for an open or a drain.\n */\nexport interface SocketFrame {\n readonly socket: Socket;\n readonly data: unknown;\n}\n\n/**\n * Runs the rest of the chain and finally the gateway handler, returning whatever\n * it returned - which for a named message is the value dunx sends back.\n *\n * It is **not** `Promise<unknown>`, unlike the HTTP `Next`. A gateway handler may\n * be synchronous and the dispatcher does not allocate a promise to hide that, so a\n * middleware that needs the outcome handles both channels. {@link observe} is that\n * dance, written once.\n */\nexport type SocketNext = () => unknown;\n\n/**\n * The single extension point on the socket side, shaped like {@link Middleware} on\n * the HTTP side: one method, wrapping `next()`.\n *\n * It sees every dispatched handler - open, each named message, the catch-all,\n * close, drain, ping and pong - and open and close arrive even for a gateway that\n * declares no `@OnOpen`/`@OnClose`, so a connection is never invisible to it.\n *\n * A throwing or rejecting handler passes through here, which is where a guard\n * refuses and where an observer records the failure. Rethrow to leave the outcome\n * to `SocketOptions.onError`; return a value instead to answer the frame.\n *\n * Three things it cannot see, because they never reach the dispatcher: a\n * `socket.send` a handler makes itself, a `PubSub` broadcast, and the upgrade -\n * which is an HTTP request answered by the gateway's own route.\n */\nexport interface SocketMiddleware {\n handle(frame: SocketFrame, ctx: SocketContext, next: SocketNext): unknown;\n}\n\n/** One slot's folded chain. The handler's own arguments ride in `run`. */\nexport type SocketDispatch = (frame: SocketFrame, run: SocketNext) => unknown;\n\n/**\n * Folded into one closure per slot at boot, the same shape `compose` gives an HTTP\n * route - so dispatch stays a property read and a call, with no array iteration\n * per frame.\n */\nexport const composeSocket = (\n middleware: readonly SocketMiddleware[],\n ctx: SocketContext,\n): SocketDispatch =>\n middleware.reduceRight<SocketDispatch>(\n (next, current) => (frame, run) =>\n current.handle(frame, ctx, () => next(frame, run)),\n (_frame, run) => run(),\n );\n\n/**\n * Calls `next()` and reports how it went, on whichever channel it went out on,\n * leaving the result untouched.\n *\n * `error` is `undefined` on success. A synchronous throw and a rejection both\n * reach `done` and are then rethrown, so a middleware that only observes cannot\n * accidentally swallow a failure.\n */\nexport const observe = (\n next: SocketNext,\n done: (error: unknown, value: unknown) => void,\n): unknown => {\n let result: unknown;\n try {\n result = next();\n } catch (error) {\n done(error, undefined);\n throw error;\n }\n\n if (result instanceof Promise) {\n return result.then(\n (value: unknown) => {\n done(undefined, value);\n return value;\n },\n (error: unknown) => {\n done(error, undefined);\n throw error;\n },\n );\n }\n done(undefined, result);\n return result;\n};\n",
18
19
  "import { AppError } from '@dunx/core';\nimport type {\n DiscoveredGateway,\n DiscoveredHandler,\n Invoke,\n} from './discover.js';\nimport { HandlerKind } from './marker.js';\n\n/**\n * One gateway reduced to direct references, built once at boot. Dispatch reads\n * these fields and nothing else - no lookup, no metadata, no DI per message.\n */\nexport interface GatewayRuntime {\n readonly name: string;\n readonly path: string;\n readonly upgrade: Invoke | undefined;\n readonly open: Invoke | undefined;\n readonly close: Invoke | undefined;\n readonly drain: Invoke | undefined;\n readonly ping: Invoke | undefined;\n readonly pong: Invoke | undefined;\n /** The raw `@OnMessage()` catch-all: every frame no named event claimed. */\n readonly raw: Invoke | undefined;\n readonly events: ReadonlyMap<string, Invoke>;\n}\n\n/** What two handlers would have to share to be a collision. */\nconst slotOf = (handler: DiscoveredHandler): string =>\n handler.kind === HandlerKind.MESSAGE && handler.event !== undefined\n ? `message ${JSON.stringify(handler.event)}`\n : handler.kind;\n\nexport const buildRuntime = (gateway: DiscoveredGateway): GatewayRuntime => {\n if (gateway.handlers.length === 0) {\n throw new AppError(\n `${gateway.name} is registered as a gateway but declares no handlers. ` +\n 'Add an @OnMessage/@OnOpen/... method, or drop the @Gateway decorator.',\n );\n }\n\n const owners = new Map<string, DiscoveredHandler>();\n const events = new Map<string, Invoke>();\n\n for (const handler of gateway.handlers) {\n const slot = slotOf(handler);\n const existing = owners.get(slot);\n if (existing) {\n throw new AppError(\n `Handler collision in ${gateway.name}: ${slot} is claimed by ` +\n `${existing.method}() and by ${handler.method}(). One handler per event.`,\n );\n }\n owners.set(slot, handler);\n if (handler.kind === HandlerKind.MESSAGE && handler.event !== undefined) {\n events.set(handler.event, handler.invoke);\n }\n }\n\n const at = (slot: string): Invoke | undefined => owners.get(slot)?.invoke;\n\n return {\n name: gateway.name,\n path: gateway.path,\n upgrade: at(HandlerKind.UPGRADE),\n open: at(HandlerKind.OPEN),\n close: at(HandlerKind.CLOSE),\n drain: at(HandlerKind.DRAIN),\n ping: at(HandlerKind.PING),\n pong: at(HandlerKind.PONG),\n raw: at(HandlerKind.MESSAGE),\n events,\n };\n};\n\n/**\n * One route per gateway path, so two gateways on one path would mean one of them\n * could never receive a connection. That is a boot error naming both.\n */\nexport const buildGateways = (\n discovered: readonly DiscoveredGateway[],\n): ReadonlyMap<string, GatewayRuntime> => {\n const byPath = new Map<string, GatewayRuntime>();\n\n for (const gateway of discovered) {\n const existing = byPath.get(gateway.path);\n if (existing) {\n throw new AppError(\n `Gateway path collision: ${gateway.path} is served by ${existing.name} ` +\n `and by ${gateway.name}. One gateway per path.`,\n );\n }\n byPath.set(gateway.path, buildRuntime(gateway));\n }\n\n return byPath;\n};\n\nexport const someHandler = (\n gateways: Iterable<GatewayRuntime>,\n pick: (gateway: GatewayRuntime) => Invoke | undefined,\n): boolean => {\n for (const gateway of gateways) if (pick(gateway) !== undefined) return true;\n return false;\n};\n",
19
- "import type { BunRequest, Server, WebSocketHandler } from 'bun';\nimport type { DiscoveredGateway, Invoke } from './discover.js';\nimport { decode, encode } from './envelope.js';\nimport { buildGateways, someHandler, type GatewayRuntime } from './runtime.js';\nimport type {\n Socket,\n SocketData,\n SocketErrorHandler,\n SocketOptions,\n} from './socket.js';\n\n// The gateway a socket belongs to travels with the socket, so dispatch is a\n// property read rather than a path lookup. Symbol-keyed, so it stays out of\n// anything that enumerates `socket.data`.\nconst RUNTIME: unique symbol = Symbol.for('dunx.ws.runtime');\n\ninterface Routed extends SocketData<unknown> {\n readonly [RUNTIME]: GatewayRuntime;\n}\n\n/**\n * A gateway's entry in the server's route table. Returning `undefined` is how Bun\n * is told the socket was upgraded; a `Response` is `426` for a request that was not\n * an upgrade, or whatever `@OnUpgrade` refused with.\n */\nexport type UpgradeHandler = (\n req: BunRequest,\n server: Server<SocketData>,\n) => Response | undefined | Promise<Response | undefined>;\n\n/**\n * Everything the one `Bun.serve` call needs from the websocket side, built once at\n * boot: the handler object, and one native route per gateway path. Nothing here\n * calls `Bun.serve` itself.\n */\nexport interface WebSocketRuntime {\n readonly websocket: WebSocketHandler<SocketData>;\n /** Merged into the HTTP route table by `listen()`, keyed by gateway path. */\n readonly routes: ReadonlyMap<string, UpgradeHandler>;\n readonly paths: readonly string[];\n /**\n * What `listen()` reports at boot: which gateway serves each path and which named\n * messages it claims. Nest logs one line per subscription; this is the same\n * information in one structured field, which is the shape the queue worker's\n * \"Consuming N job(s)\" entry already set.\n */\n readonly gateways: readonly GatewaySummary[];\n}\n\nexport interface GatewaySummary {\n readonly name: string;\n readonly path: string;\n /** `@OnMessage('name')` events. A raw catch-all has no name to report. */\n readonly events: readonly string[];\n}\n\nconst defaultOnError: SocketErrorHandler = (error, socket) => {\n console.error(`[dunx/http] ${socket.data.path} handler failed:`, error);\n};\n\nconst runtimeOf = (socket: Socket): GatewayRuntime =>\n (socket.data as Routed)[RUNTIME];\n\nconst isBinary = (value: unknown): value is Bun.BufferSource =>\n value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n\nconst replyRaw = (socket: Socket, value: unknown): void => {\n if (value === undefined) return;\n socket.send(\n typeof value === 'string' || isBinary(value)\n ? value\n : JSON.stringify(value),\n );\n};\n\n/**\n * A handler may be sync or async. `then` is what turns a returned value into a\n * frame, and it runs inside the same error path either way.\n */\nconst settle = (\n result: unknown,\n socket: Socket,\n onError: SocketErrorHandler,\n then: ((value: unknown) => void) | undefined,\n): void => {\n if (result instanceof Promise) {\n void result.then(\n (value: unknown) => {\n if (!then) return;\n try {\n then(value);\n } catch (error) {\n onError(error, socket);\n }\n },\n (error: unknown) => onError(error, socket),\n );\n return;\n }\n if (then) then(result);\n};\n\nexport const buildWebSocket = (\n discovered: readonly DiscoveredGateway[],\n options: SocketOptions = {},\n): WebSocketRuntime => {\n const byPath = buildGateways(discovered);\n const gateways = [...byPath.values()];\n const onError = options.onError ?? defaultOnError;\n // The rest is exactly the set of keys Bun's WebSocketHandler accepts.\n const { onError: _onError, ...socketOptions } = options;\n\n const run = (\n invoke: Invoke,\n args: readonly unknown[],\n ws: Socket,\n then: ((value: unknown) => void) | undefined,\n ): void => {\n try {\n settle(invoke(...args), ws, onError, then);\n } catch (error) {\n onError(error, ws);\n }\n };\n\n const websocket: WebSocketHandler<SocketData> = {\n ...socketOptions,\n\n message(ws, message) {\n const gateway = runtimeOf(ws);\n if (gateway.events.size > 0) {\n const envelope = decode(message);\n const handler = envelope && gateway.events.get(envelope.event);\n if (envelope && handler) {\n run(handler, [envelope.data, ws], ws, (value) => {\n if (value !== undefined) ws.send(encode(envelope.event, value));\n });\n return;\n }\n }\n if (gateway.raw) {\n run(gateway.raw, [message, ws], ws, (value) => replyRaw(ws, value));\n }\n },\n\n ...(someHandler(gateways, (g) => g.open) && {\n open(ws: Socket) {\n const { open } = runtimeOf(ws);\n if (open) run(open, [ws], ws, undefined);\n },\n }),\n\n ...(someHandler(gateways, (g) => g.close) && {\n close(ws: Socket, code: number, reason: string) {\n const { close } = runtimeOf(ws);\n if (close) run(close, [ws, code, reason], ws, undefined);\n },\n }),\n\n ...(someHandler(gateways, (g) => g.drain) && {\n drain(ws: Socket) {\n const { drain } = runtimeOf(ws);\n if (drain) run(drain, [ws], ws, undefined);\n },\n }),\n\n // Only installed when a gateway asks for them: Bun answers a ping with a pong\n // on its own, and overriding the handler with a no-op would take that away.\n ...(someHandler(gateways, (g) => g.ping) && {\n ping(ws: Socket, data: Buffer) {\n const { ping } = runtimeOf(ws);\n if (ping) run(ping, [data, ws], ws, undefined);\n },\n }),\n\n ...(someHandler(gateways, (g) => g.pong) && {\n pong(ws: Socket, data: Buffer) {\n const { pong } = runtimeOf(ws);\n if (pong) run(pong, [data, ws], ws, undefined);\n },\n }),\n };\n\n const accept = (\n req: Request,\n server: Server<SocketData>,\n gateway: GatewayRuntime,\n context: unknown,\n ): Response | undefined => {\n const data: Routed = { path: gateway.path, context, [RUNTIME]: gateway };\n return server.upgrade(req, { data })\n ? undefined\n : new Response('Expected a WebSocket upgrade', { status: 426 });\n };\n\n // One closure per gateway, built here rather than per request. `@OnUpgrade` is\n // handed the BunRequest, so a path pattern's `req.params` is readable.\n const upgradeHandler =\n (gateway: GatewayRuntime): UpgradeHandler =>\n (req, server) => {\n if (!gateway.upgrade) return accept(req, server, gateway, undefined);\n\n const result = gateway.upgrade(req);\n if (result instanceof Promise) {\n return result.then((value: unknown) =>\n value instanceof Response\n ? value\n : accept(req, server, gateway, value),\n );\n }\n return result instanceof Response\n ? result\n : accept(req, server, gateway, result);\n };\n\n return {\n websocket,\n routes: new Map(\n gateways.map((gateway) => [gateway.path, upgradeHandler(gateway)]),\n ),\n paths: [...byPath.keys()],\n gateways: gateways.map((gateway) => ({\n name: gateway.name,\n path: gateway.path,\n events: [...gateway.events.keys()],\n })),\n };\n};\n",
20
+ "import type { BunRequest, Server, WebSocketHandler } from 'bun';\nimport type { DiscoveredGateway, Invoke } from './discover.js';\nimport { decode, encode } from './envelope.js';\nimport { HandlerKind } from './marker.js';\nimport {\n composeSocket,\n type SocketContext,\n type SocketFrame,\n type SocketMiddleware,\n} from './middleware.js';\nimport { buildGateways, someHandler, type GatewayRuntime } from './runtime.js';\nimport type {\n Socket,\n SocketData,\n SocketErrorHandler,\n SocketOptions,\n} from './socket.js';\n\n// The gateway a socket belongs to travels with the socket, so dispatch is a\n// property read rather than a path lookup. Symbol-keyed, so it stays out of\n// anything that enumerates `socket.data`.\nconst RUNTIME: unique symbol = Symbol.for('dunx.ws.runtime');\n// The chain for a frame no named handler claimed, built per gateway at boot. Only\n// present when there is middleware to run.\nconst UNCLAIMED: unique symbol = Symbol.for('dunx.ws.unclaimed');\n\ninterface Routed extends SocketData<unknown> {\n readonly [RUNTIME]: GatewayRuntime;\n readonly [UNCLAIMED]?: UnclaimedDispatch;\n}\n\n/**\n * A gateway's entry in the server's route table. Returning `undefined` is how Bun\n * is told the socket was upgraded; a `Response` is `426` for a request that was not\n * an upgrade, or whatever `@OnUpgrade` refused with.\n */\nexport type UpgradeHandler = (\n req: BunRequest,\n server: Server<SocketData>,\n) => Response | undefined | Promise<Response | undefined>;\n\n/**\n * Everything the one `Bun.serve` call needs from the websocket side, built once at\n * boot: the handler object, and one native route per gateway path. Nothing here\n * calls `Bun.serve` itself.\n */\nexport interface WebSocketRuntime {\n readonly websocket: WebSocketHandler<SocketData>;\n /** Merged into the HTTP route table by `listen()`, keyed by gateway path. */\n readonly routes: ReadonlyMap<string, UpgradeHandler>;\n readonly paths: readonly string[];\n /**\n * What `listen()` reports at boot: which gateway serves each path and which named\n * messages it claims. Nest logs one line per subscription; this is the same\n * information in one structured field, which is the shape the queue worker's\n * \"Consuming N job(s)\" entry already set.\n */\n readonly gateways: readonly GatewaySummary[];\n}\n\nexport interface GatewaySummary {\n readonly name: string;\n readonly path: string;\n /** `@OnMessage('name')` events. A raw catch-all has no name to report. */\n readonly events: readonly string[];\n}\n\nconst defaultOnError: SocketErrorHandler = (error, socket) => {\n console.error(`[dunx/http] ${socket.data.path} handler failed:`, error);\n};\n\n/** The failure already went through the chain, which is where it was recorded. */\nconst reportedByMiddleware: SocketErrorHandler = () => undefined;\n\nconst runtimeOf = (socket: Socket): GatewayRuntime =>\n (socket.data as Routed)[RUNTIME];\n\nconst isBinary = (value: unknown): value is Bun.BufferSource =>\n value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n\nconst replyRaw = (socket: Socket, value: unknown): void => {\n if (value === undefined) return;\n socket.send(\n typeof value === 'string' || isBinary(value)\n ? value\n : JSON.stringify(value),\n );\n};\n\n/**\n * A handler may be sync or async. `then` is what turns a returned value into a\n * frame, and it runs inside the same error path either way.\n */\nconst settle = (\n result: unknown,\n socket: Socket,\n onError: SocketErrorHandler,\n then: ((value: unknown) => void) | undefined,\n): void => {\n if (result instanceof Promise) {\n void result.then(\n (value: unknown) => {\n if (!then) return;\n try {\n then(value);\n } catch (error) {\n onError(error, socket);\n }\n },\n (error: unknown) => onError(error, socket),\n );\n return;\n }\n if (then) then(result);\n};\n\n/**\n * Where the socket and the payload sit in a handler's own arguments, which differ\n * by kind: `open`, `close` and `drain` take the socket first, while a message, a\n * ping and a pong take their data first. Resolved once per slot at boot, so no\n * frame is built by branching on the kind.\n */\nconst framing = (\n kind: HandlerKind,\n): ((args: readonly unknown[]) => SocketFrame) => {\n if (kind === HandlerKind.CLOSE) {\n return (args) => ({\n socket: args[0] as Socket,\n data: { code: args[1], reason: args[2] },\n });\n }\n if (kind === HandlerKind.OPEN || kind === HandlerKind.DRAIN) {\n return (args) => ({ socket: args[0] as Socket, data: undefined });\n }\n return (args) => ({ socket: args[1] as Socket, data: args[0] });\n};\n\nconst NOTHING: Invoke = () => undefined;\n\n/**\n * One slot's handler with the middleware chain folded in front of it.\n *\n * `invoke` may be absent: `open` and `close` are wrapped even for a gateway that\n * declares neither, so a connection and its end are never invisible to an\n * observer. The inner call is then a no-op and the chain still runs.\n */\nconst through = (\n gateway: GatewayRuntime,\n middleware: readonly SocketMiddleware[],\n kind: HandlerKind,\n event: string | undefined,\n invoke: Invoke | undefined,\n): Invoke => {\n const ctx: SocketContext = {\n gateway: gateway.name,\n path: gateway.path,\n kind,\n event,\n };\n const dispatch = composeSocket(middleware, ctx);\n const frameOf = framing(kind);\n const run = invoke ?? NOTHING;\n return (...args) => dispatch(frameOf(args), () => run(...args));\n};\n\nconst withMiddleware = (\n gateway: GatewayRuntime,\n middleware: readonly SocketMiddleware[],\n): GatewayRuntime => {\n const wrap = (\n kind: HandlerKind,\n event: string | undefined,\n invoke: Invoke | undefined,\n ) => through(gateway, middleware, kind, event, invoke);\n const optional = (kind: HandlerKind, invoke: Invoke | undefined) =>\n invoke === undefined ? undefined : wrap(kind, undefined, invoke);\n\n return {\n ...gateway,\n open: wrap(HandlerKind.OPEN, undefined, gateway.open),\n close: wrap(HandlerKind.CLOSE, undefined, gateway.close),\n // Left alone when the gateway declares none. Bun answers a ping with a pong\n // itself, and installing a handler to observe one would take that away.\n drain: optional(HandlerKind.DRAIN, gateway.drain),\n ping: optional(HandlerKind.PING, gateway.ping),\n pong: optional(HandlerKind.PONG, gateway.pong),\n raw: optional(HandlerKind.MESSAGE, gateway.raw),\n events: new Map(\n [...gateway.events].map(([event, invoke]) => [\n event,\n wrap(HandlerKind.MESSAGE, event, invoke),\n ]),\n ),\n };\n};\n\n/**\n * The chain for a frame nothing claimed - an event no `@OnMessage` declares, on a\n * gateway with no raw catch-all. The socket analogue of the HTTP not-found\n * fallback: without it an unknown event is silently dropped, which is the one thing\n * a client debugging its own wire format cannot see.\n *\n * The context is built per frame because the event name is the frame's, and that\n * allocation is on this path only.\n */\ntype UnclaimedDispatch = (\n frame: SocketFrame,\n event: string | undefined,\n) => unknown;\n\nconst unclaimedDispatch =\n (\n gateway: GatewayRuntime,\n middleware: readonly SocketMiddleware[],\n ): UnclaimedDispatch =>\n (frame, event) =>\n composeSocket(middleware, {\n gateway: gateway.name,\n path: gateway.path,\n kind: HandlerKind.MESSAGE,\n event,\n })(frame, () => undefined);\n\nexport const buildWebSocket = (\n discovered: readonly DiscoveredGateway[],\n options: SocketOptions = {},\n middleware: readonly SocketMiddleware[] = [],\n): WebSocketRuntime => {\n const byPath = buildGateways(discovered);\n const wrapped =\n middleware.length === 0\n ? byPath\n : new Map(\n [...byPath].map(([path, gateway]) => [\n path,\n withMiddleware(gateway, middleware),\n ]),\n );\n const gateways = [...wrapped.values()];\n // A middleware wraps the handler, so it has already seen a failure by the time\n // one escapes - and the console fallback would be a second report of it.\n const onError =\n options.onError ??\n (middleware.length === 0 ? defaultOnError : reportedByMiddleware);\n // The rest is exactly the set of keys Bun's WebSocketHandler accepts.\n const { onError: _onError, ...socketOptions } = options;\n\n const run = (\n invoke: Invoke,\n args: readonly unknown[],\n ws: Socket,\n then: ((value: unknown) => void) | undefined,\n ): void => {\n try {\n settle(invoke(...args), ws, onError, then);\n } catch (error) {\n onError(error, ws);\n }\n };\n\n const websocket: WebSocketHandler<SocketData> = {\n ...socketOptions,\n\n message(ws, message) {\n const gateway = runtimeOf(ws);\n let event: string | undefined;\n if (gateway.events.size > 0) {\n const envelope = decode(message);\n const handler = envelope && gateway.events.get(envelope.event);\n if (envelope && handler) {\n run(handler, [envelope.data, ws], ws, (value) => {\n if (value !== undefined) ws.send(encode(envelope.event, value));\n });\n return;\n }\n event = envelope?.event;\n }\n if (gateway.raw) {\n run(gateway.raw, [message, ws], ws, (value) => replyRaw(ws, value));\n return;\n }\n const unclaimed = (ws.data as Routed)[UNCLAIMED];\n if (!unclaimed) return;\n try {\n settle(\n unclaimed({ socket: ws, data: message }, event),\n ws,\n onError,\n undefined,\n );\n } catch (error) {\n onError(error, ws);\n }\n },\n\n ...(someHandler(gateways, (g) => g.open) && {\n open(ws: Socket) {\n const { open } = runtimeOf(ws);\n if (open) run(open, [ws], ws, undefined);\n },\n }),\n\n ...(someHandler(gateways, (g) => g.close) && {\n close(ws: Socket, code: number, reason: string) {\n const { close } = runtimeOf(ws);\n if (close) run(close, [ws, code, reason], ws, undefined);\n },\n }),\n\n ...(someHandler(gateways, (g) => g.drain) && {\n drain(ws: Socket) {\n const { drain } = runtimeOf(ws);\n if (drain) run(drain, [ws], ws, undefined);\n },\n }),\n\n // Only installed when a gateway asks for them: Bun answers a ping with a pong\n // on its own, and overriding the handler with a no-op would take that away.\n ...(someHandler(gateways, (g) => g.ping) && {\n ping(ws: Socket, data: Buffer) {\n const { ping } = runtimeOf(ws);\n if (ping) run(ping, [data, ws], ws, undefined);\n },\n }),\n\n ...(someHandler(gateways, (g) => g.pong) && {\n pong(ws: Socket, data: Buffer) {\n const { pong } = runtimeOf(ws);\n if (pong) run(pong, [data, ws], ws, undefined);\n },\n }),\n };\n\n const unclaimed = new Map<GatewayRuntime, UnclaimedDispatch>(\n middleware.length === 0\n ? []\n : gateways.map((gateway) => [\n gateway,\n unclaimedDispatch(gateway, middleware),\n ]),\n );\n\n const accept = (\n req: Request,\n server: Server<SocketData>,\n gateway: GatewayRuntime,\n context: unknown,\n ): Response | undefined => {\n const fallback = unclaimed.get(gateway);\n const data: Routed = {\n path: gateway.path,\n context,\n id: crypto.randomUUID(),\n [RUNTIME]: gateway,\n ...(fallback === undefined ? {} : { [UNCLAIMED]: fallback }),\n };\n return server.upgrade(req, { data })\n ? undefined\n : new Response('Expected a WebSocket upgrade', { status: 426 });\n };\n\n // One closure per gateway, built here rather than per request. `@OnUpgrade` is\n // handed the BunRequest, so a path pattern's `req.params` is readable.\n const upgradeHandler =\n (gateway: GatewayRuntime): UpgradeHandler =>\n (req, server) => {\n if (!gateway.upgrade) return accept(req, server, gateway, undefined);\n\n const result = gateway.upgrade(req);\n if (result instanceof Promise) {\n return result.then((value: unknown) =>\n value instanceof Response\n ? value\n : accept(req, server, gateway, value),\n );\n }\n return result instanceof Response\n ? result\n : accept(req, server, gateway, result);\n };\n\n return {\n websocket,\n routes: new Map(\n gateways.map((gateway) => [gateway.path, upgradeHandler(gateway)]),\n ),\n paths: [...byPath.keys()],\n gateways: gateways.map((gateway) => ({\n name: gateway.name,\n path: gateway.path,\n events: [...gateway.events.keys()],\n })),\n };\n};\n",
21
+ "import { Logger, LogLevel, RequestContext } from '@dunx/core';\nimport { HandlerKind } from './marker.js';\nimport {\n observe,\n type SocketContext,\n type SocketFrame,\n type SocketMiddleware,\n type SocketNext,\n} from './middleware.js';\n\nexport interface SocketLoggingOptions {\n /**\n * The level every message frame is logged at. Default **`'debug'`**.\n *\n * `'debug'`, not `'info'`, because a socket is not a request: a gateway can take\n * a frame per player per tick, and one `info` line each would bury everything\n * else the process writes. The default `ConsoleLogger` threshold is `'info'`, so\n * this is off until an app lowers its level or names a louder one here.\n */\n readonly level?: LogLevel;\n /** What a throwing or rejecting handler is logged at. @default 'error' */\n readonly errorLevel?: LogLevel;\n /**\n * Per-event level, keyed by the `@OnMessage(event)` name. `false` skips the\n * event entirely, and skipping is complete: no entry, no timing, no scope.\n *\n * ```ts\n * socketLogging: { events: { placeBet: 'info', cursorMove: false } }\n * ```\n */\n readonly events?: Readonly<Record<string, LogLevel | false>>;\n /**\n * Open, close, drain, ping and pong. Defaults to `level`; `false` drops them.\n *\n * Separate from `level` because the two answer different questions - how much\n * traffic a socket carries, against how many sockets there are - and an app that\n * silences the first usually still wants the second.\n */\n readonly lifecycle?: LogLevel | false;\n /**\n * Log the frame's payload. Default **`false`**.\n *\n * A payload is caller-supplied and arrives without validation, so it is both the\n * field most likely to carry a credential and the one most likely to be large.\n */\n readonly payload?: boolean;\n /** Payloads past this many characters are logged as a size. @default 512 */\n readonly maxPayloadLength?: number;\n /**\n * Wrap each dispatch in an `AsyncRequestContext` scope. Default **`true`**.\n *\n * The scope is what makes a line a service logs four frames down carry\n * `connectionId` and `event` without being handed the socket.\n */\n readonly correlate?: boolean;\n}\n\nconst LIFECYCLE_LABEL: Readonly<Record<string, string>> = {\n [HandlerKind.OPEN]: 'connect',\n [HandlerKind.CLOSE]: 'disconnect',\n};\n\nconst elapsedMs = (started: number): number =>\n Math.round((Bun.nanoseconds() - started) / 1e6);\n\n/**\n * One structured entry per dispatched frame, carrying the frame and its outcome.\n *\n * The socket counterpart of `RequestLoggingMiddleware`, and the same single-entry\n * shape: the middleware wraps the handler, so the frame and what it answered are\n * one line rather than an inbound line to correlate with an outbound one.\n *\n * It also replaces what a gateway would otherwise hand-write. A throwing handler\n * reaches the `Logger` here with the gateway, the path and the event on it -\n * `SocketOptions.onError`'s default is a bare `console.error` off the logging\n * pipeline entirely, and installing this takes that fallback out of the way.\n */\nexport class SocketLoggingMiddleware implements SocketMiddleware {\n readonly #level: LogLevel;\n readonly #errorLevel: LogLevel;\n readonly #events: Readonly<Record<string, LogLevel | false>>;\n readonly #lifecycle: LogLevel | false;\n readonly #payload: boolean;\n readonly #limit: number;\n readonly #correlate: boolean;\n\n constructor(\n private readonly logger: Logger,\n private readonly context: RequestContext,\n options: SocketLoggingOptions = {},\n ) {\n this.#level = options.level ?? LogLevel.DEBUG;\n this.#errorLevel = options.errorLevel ?? LogLevel.ERROR;\n this.#events = options.events ?? {};\n this.#lifecycle = options.lifecycle ?? this.#level;\n this.#payload = options.payload ?? false;\n this.#limit = options.maxPayloadLength ?? 512;\n this.#correlate = options.correlate ?? true;\n }\n\n /** `false` means this frame is not logged at all. */\n #levelFor(ctx: SocketContext): LogLevel | false {\n if (ctx.kind !== HandlerKind.MESSAGE) return this.#lifecycle;\n if (ctx.event === undefined) return this.#level;\n return this.#events[ctx.event] ?? this.#level;\n }\n\n handle(frame: SocketFrame, ctx: SocketContext, next: SocketNext): unknown {\n const level = this.#levelFor(ctx);\n if (level === false) return next();\n\n const label = ctx.event ?? LIFECYCLE_LABEL[ctx.kind] ?? ctx.kind;\n const connectionId = frame.socket.data.id;\n const started = Bun.nanoseconds();\n const write = (error: unknown, value: unknown): void => {\n const entry = {\n gateway: ctx.gateway,\n path: ctx.path,\n event: label,\n connectionId,\n elapsedMs: elapsedMs(started),\n ...(this.#payload ? { payload: this.#brief(frame.data) } : {}),\n ...(error === undefined\n ? { replied: value !== undefined }\n : { err: error }),\n };\n const line = `${ctx.path} ${label}`;\n this.#emit(error === undefined ? level : this.#errorLevel, line, entry);\n };\n\n if (!this.#correlate) return observe(next, write);\n return this.context.runWithContext(\n { connectionId, event: label, flow: 'ws', context: ctx.gateway },\n () => observe(next, write),\n );\n }\n\n /**\n * A `switch` rather than `this.logger[level](...)`. The indexed call needs a\n * `bind` to keep its receiver, which would be one closure allocated per frame -\n * and a gateway taking a frame per tick is exactly where that shows up.\n */\n #emit(level: LogLevel, line: string, entry: Record<string, unknown>): void {\n switch (level) {\n case LogLevel.VERBOSE:\n this.logger.verbose(line, entry);\n return;\n case LogLevel.DEBUG:\n this.logger.debug(line, entry);\n return;\n case LogLevel.INFO:\n this.logger.info(line, entry);\n return;\n case LogLevel.WARN:\n this.logger.warn(line, entry);\n return;\n case LogLevel.ERROR:\n this.logger.error(line, entry);\n return;\n default:\n this.logger.fatal(line, entry);\n }\n }\n\n /**\n * A payload as one loggable value: an object as itself, anything longer than the\n * limit as its size. Serialising to measure it is the cost `payload: false`\n * avoids.\n */\n #brief(data: unknown): unknown {\n if (data === undefined || this.#limit === 0) return undefined;\n if (typeof data === 'string') {\n return data.length > this.#limit ? `[${data.length} chars]` : data;\n }\n if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n return `[${data.byteLength} bytes]`;\n }\n const text = JSON.stringify(data) ?? '';\n return text.length > this.#limit ? `[${text.length} chars]` : data;\n }\n}\nObject.defineProperty(SocketLoggingMiddleware, Symbol.for('dunx.deps'), {\n value: () => [Logger, RequestContext, { unresolved: \"options: SocketLoggingOptions = {}\" }],\n});\n",
20
22
  "import { AppError } from '@dunx/core';\nimport type { Server } from 'bun';\nimport { encode } from './envelope.js';\nimport {\n decodeRelay,\n DEFAULT_RELAY_CHANNEL,\n defaultRelayError,\n encodeRelay,\n type PubSubRelay,\n type RelayOptions,\n type RelayPhase,\n} from './relay.js';\nimport type { SocketData } from './socket.js';\n\n/**\n * Server-wide publish, delegating to Bun's own pub/sub. Topics live in the\n * runtime, not in a JavaScript registry: `socket.subscribe(topic)` is what joins\n * one, and Bun does the fan-out.\n *\n * Injectable - `HttpFactory` binds it, so a service can publish without holding a\n * socket and without registering anything.\n *\n * With a {@link PubSubRelay} attached the same publish also reaches the other\n * nodes. Without one - the default - nothing here touches a broker and the cost is\n * exactly Bun's.\n */\nexport class PubSub {\n /**\n * Identifies this process on the wire, so a frame this node published and the\n * broker echoed back is recognised and dropped instead of being fanned out\n * locally a second time. `Bun.randomUUIDv7` rather than a counter: two nodes\n * booted in the same millisecond must not collide.\n */\n readonly #origin = Bun.randomUUIDv7();\n #server: Server<SocketData> | undefined;\n #relay: PubSubRelay | undefined;\n #channel = DEFAULT_RELAY_CHANNEL;\n #onRelayError = defaultRelayError;\n /** So a broker that is down is reported once, not once per publish. */\n #relayFailing = false;\n #resubscribeTimer: ReturnType<typeof setTimeout> | undefined;\n #resubscribeLeft = 0;\n #resubscribeDelay = 0;\n\n /** Called with the live server by `listen()`; also usable directly. */\n attach(server: Server<SocketData>): void {\n this.#server = server;\n }\n\n get attached(): boolean {\n return this.#server !== undefined;\n }\n\n /** This process's id on the relay channel. Stable for the process's lifetime. */\n get origin(): string {\n return this.#origin;\n }\n\n get relaying(): boolean {\n return this.#relay !== undefined;\n }\n\n /**\n * Opt into multi-node fan-out: every `publish` from here on also goes to\n * `relay`, and everything other nodes put on the channel is fanned out locally.\n *\n * `HttpFactory.create(root, { relay })` is the shorthand - `listen()` calls this.\n * Call it directly when the relay has to come out of the container, which is the\n * case for an app reusing its own `@dunx/infra/redis` connection:\n * `app.get(PubSub).relayThrough(app.get(RedisConnection))` before `listen()`.\n *\n * A broker that cannot be reached is reported through `onError` and left alone -\n * local fan-out is unaffected, and the app boots either way.\n */\n async relayThrough(\n relay: PubSubRelay,\n options: RelayOptions = {},\n ): Promise<void> {\n if (this.#relay) {\n throw new AppError(\n 'PubSub already relays. Two subscriptions on one channel would deliver ' +\n 'every relayed message twice - pass HttpOptions.relay or call ' +\n 'relayThrough(), not both.',\n );\n }\n this.#relay = relay;\n this.#channel = options.channel ?? DEFAULT_RELAY_CHANNEL;\n this.#onRelayError = options.onError ?? defaultRelayError;\n this.#resubscribeLeft = options.resubscribe?.attempts ?? 5;\n this.#resubscribeDelay = options.resubscribe?.delayMs ?? 500;\n\n await this.#trySubscribe();\n }\n\n /**\n * One subscribe attempt, scheduling the next on failure. Separate from\n * `relayThrough` because a retry has to run the identical path - including the\n * synchronous-throw handling, which Bun's client needs.\n */\n async #trySubscribe(): Promise<void> {\n const relay = this.#relay;\n if (!relay) return;\n\n try {\n // Bun's client throws synchronously for some states, so the call is inside\n // the try rather than only the await.\n await relay.subscribe(this.#channel, (message) => {\n this.#inbound(message);\n });\n this.#relayFailing = false;\n this.#resubscribeLeft = 0;\n } catch (error) {\n this.#degrade(error, 'subscribe');\n this.#scheduleResubscribe();\n }\n }\n\n #scheduleResubscribe(): void {\n if (this.#resubscribeLeft <= 0 || this.#relay === undefined) return;\n this.#resubscribeLeft -= 1;\n const delay = this.#resubscribeDelay;\n // Capped so a long-dead broker settles into a slow poll instead of growing\n // unboundedly; unref'd so it can never be the reason a process stays up.\n this.#resubscribeDelay = Math.min(delay * 2, 30_000);\n this.#resubscribeTimer = setTimeout(() => {\n void this.#trySubscribe();\n }, delay);\n this.#resubscribeTimer.unref?.();\n }\n\n /** Bytes sent locally, `0` if the message was dropped, `-1` under backpressure. */\n publish(\n topic: string,\n data: string | Bun.BufferSource,\n compress?: boolean,\n ): number {\n const sent = this.#live().publish(topic, data, compress);\n // Unconditional, and after the local fan-out: a topic with no subscriber on\n // this node may have thousands on another.\n this.#outbound(topic, data);\n return sent;\n }\n\n /** The same envelope `@OnMessage(event)` reads, published to a topic. */\n publishEvent(topic: string, event: string, data?: unknown): number {\n return this.publish(topic, encode(event, data));\n }\n\n /** Subscribers on **this** node. Bun counts its own sockets and nothing else. */\n subscriberCount(topic: string): number {\n return this.#live().subscriberCount(topic);\n }\n\n /**\n * Releases a relay this `PubSub` was given, if the relay owns connections.\n *\n * The server reference goes too, which is what makes a relay the *app* owns safe\n * to leave subscribed: `PubSubRelay` has no unsubscribe, so a frame may still\n * arrive on a shared connection after this node stopped, and with no server\n * there is nothing for it to fan out to.\n */\n async close(): Promise<void> {\n const relay = this.#relay;\n this.#relay = undefined;\n // Before anything can await: a pending retry must not fire against a relay\n // this call is closing.\n this.#resubscribeLeft = 0;\n if (this.#resubscribeTimer !== undefined) {\n clearTimeout(this.#resubscribeTimer);\n this.#resubscribeTimer = undefined;\n }\n this.#server = undefined;\n if (!relay?.close) return;\n try {\n await relay.close();\n } catch (error) {\n this.#degrade(error, 'close');\n }\n }\n\n #outbound(topic: string, data: string | Bun.BufferSource): void {\n const relay = this.#relay;\n if (!relay) return;\n try {\n const result = relay.publish(\n this.#channel,\n encodeRelay(this.#origin, topic, data),\n );\n if (result instanceof Promise) {\n void result.then(\n () => {\n this.#relayFailing = false;\n },\n (error: unknown) => {\n this.#degrade(error, 'publish');\n },\n );\n return;\n }\n this.#relayFailing = false;\n } catch (error) {\n this.#degrade(error, 'publish');\n }\n }\n\n /**\n * Local fan-out only, and that is the whole rule: republishing to the relay here\n * would put the frame back on the channel that delivered it and loop forever.\n */\n #inbound(message: string): void {\n const frame = decodeRelay(message);\n if (!frame || frame.origin === this.#origin) return;\n this.#server?.publish(frame.topic, frame.data);\n }\n\n #degrade(error: unknown, phase: RelayPhase): void {\n if (this.#relayFailing) return;\n this.#relayFailing = true;\n this.#onRelayError(error, phase);\n }\n\n #live(): Server<SocketData> {\n if (!this.#server) {\n throw new AppError(\n 'PubSub has no server yet. Publish once the server is listening: ' +\n 'HttpApp.listen() is what attaches it.',\n );\n }\n return this.#server;\n }\n}\n",
21
23
  "/**\n * What `PubSub` needs from something that carries a message to the other nodes:\n * publish, and subscribe. Nothing else, so anything that already talks to a\n * broker satisfies it - `@dunx/infra/redis`'s `RedisConnection` does, structurally\n * and with no adapter, and so does a bare `Bun.RedisClient` pair.\n *\n * The return types are `unknown` rather than `Promise<void>` deliberately: Bun's\n * `publish` resolves the subscriber count, `@dunx/infra`'s resolves nothing, and a\n * synchronous in-memory bus resolves at all. A returned promise is awaited by\n * `subscribe` and watched for rejection by `publish`; anything else is taken as\n * having succeeded.\n */\nexport interface PubSubRelay {\n /** Hand `message` to every node subscribed to `channel`, this one included. */\n publish(channel: string, message: string): unknown;\n /**\n * Deliver every message published to `channel` to `listener`. Called once, with\n * one channel - pattern subscription is not used, because Bun's `psubscribe`\n * does not work (see docs/bun-apis.md).\n */\n subscribe(channel: string, listener: (message: string) => void): unknown;\n /**\n * Release whatever this relay opened. Implement it only for connections the\n * relay itself owns: a relay that is the application's own shared\n * `RedisConnection` must leave closing to the container, and simply omitting\n * this method is how it says so.\n */\n close?(): unknown;\n}\n\n/** Which relay call failed, so one message can say what degraded. */\nexport type RelayPhase = 'publish' | 'subscribe' | 'close';\n\nexport interface RelayOptions {\n /**\n * The one broker channel every topic's frames travel on.\n *\n * One channel rather than one per topic, because a node cannot know which\n * topics its sockets joined - `socket.subscribe()` goes straight into Bun - and\n * `psubscribe` is unusable. The cost is that every node reads every relayed\n * frame and drops the ones for topics it has no local subscriber on, which is a\n * `server.publish` returning `0`. Two apps sharing a Redis need two channels.\n *\n * @default 'dunx:ws'\n */\n readonly channel?: string;\n /**\n * Where a relay failure goes. Called once when the relay starts failing and not\n * again until it works, so an unreachable broker cannot flood the log.\n *\n * @default console.warn\n */\n readonly onError?: (error: unknown, phase: RelayPhase) => void;\n /**\n * What to do when the **boot** subscribe fails. Publishing recovers on its own -\n * every publish retries the broker - but a failed subscribe used to be retried\n * by nothing, so the node stayed permanently deaf to other nodes while still\n * looking healthy.\n *\n * Bounded rather than infinite, and the timer is unref'd, so a broker that never\n * comes back cannot hold the process open or spin forever.\n */\n readonly resubscribe?: {\n /** Retries after the first failure. `0` disables them. @default 5 */\n readonly attempts?: number;\n /** First delay; doubles each attempt, capped at 30s. @default 500 */\n readonly delayMs?: number;\n };\n}\n\nexport const DEFAULT_RELAY_CHANNEL = 'dunx:ws';\n\nexport const defaultRelayError = (error: unknown, phase: RelayPhase): void => {\n console.warn(\n `[dunx/http] the websocket relay could not ${phase}. Fan-out is local to ` +\n 'this process until it recovers:',\n error,\n );\n};\n\n/**\n * One relayed publish: which process published it, which topic it belongs to, and\n * the frame itself. `origin` is the whole duplicate-delivery defence - the broker\n * echoes a publish back to the publisher, and fanning that out locally a second\n * time would give every client on the originating node the message twice.\n */\nexport interface RelayFrame {\n readonly origin: string;\n readonly topic: string;\n readonly data: string | Uint8Array<ArrayBufferLike>;\n}\n\nconst toBytes = (data: Bun.BufferSource): Uint8Array<ArrayBufferLike> =>\n ArrayBuffer.isView(data)\n ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n : new Uint8Array(data);\n\nexport const encodeRelay = (\n origin: string,\n topic: string,\n data: string | Bun.BufferSource,\n): string =>\n typeof data === 'string'\n ? JSON.stringify({ o: origin, t: topic, d: data })\n : // Base64 through Buffer, which Bun implements natively. A binary frame has\n // to survive a text channel, and Redis pub/sub payloads are text here\n // because Bun's buffer-mode subscription is not implemented.\n JSON.stringify({\n o: origin,\n t: topic,\n d: Buffer.from(toBytes(data)).toString('base64'),\n b: 1,\n });\n\n/** `undefined` for anything that is not one of our frames, which is then ignored. */\nexport const decodeRelay = (message: string): RelayFrame | undefined => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n\n const { o, t, d, b } = parsed as {\n o?: unknown;\n t?: unknown;\n d?: unknown;\n b?: unknown;\n };\n if (typeof o !== 'string' || typeof t !== 'string' || typeof d !== 'string') {\n return undefined;\n }\n return { origin: o, topic: t, data: b ? Buffer.from(d, 'base64') : d };\n};\n",
22
- "import type { BunRequest, Server } from 'bun';\nimport {\n AppError,\n Logger,\n runtimeInfo,\n ShutdownHooks,\n type App,\n type AppOptions,\n type Ctor,\n type InjectionToken,\n type ModuleRef,\n type ShutdownHookOptions,\n type ShutdownSignal,\n} from '@dunx/core';\nimport { joinPath, type DiscoveredRoute } from '../route/discover.js';\nimport type { WebSocketRuntime } from '../ws/adapter.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport type { PubSubRelay, RelayOptions, RelayPhase } from '../ws/relay.js';\nimport type { SocketData, SocketOptions } from '../ws/socket.js';\nimport { attachAddressSource, ClientAddress } from './client-address.js';\nimport type { CorsOptions } from './cors.js';\nimport {\n errorMapper,\n toErrorMapper,\n type ErrorHandler,\n type ErrorMapper,\n} from './errors.js';\nimport type { Middleware } from './middleware.js';\nimport {\n RequestLoggingMiddleware,\n type RequestLoggingOptions,\n} from './request-logging.js';\nimport {\n assertNoGatewayCollisions,\n buildFallback,\n buildRoutes,\n withUpgradeRoutes,\n} from './routes.js';\nimport { defaultSettings, type AppSettings } from './settings.js';\n\nexport interface HttpOptions extends AppOptions {\n readonly port?: number;\n /** Resolved from the container, so middleware can inject(). */\n readonly middleware?: readonly Ctor<Middleware>[];\n /**\n * Replaces the default mapper.\n *\n * A bare `ErrorMapper` function, or an `ErrorFilter` **class** - which is the one\n * to prefer, because a class is resolved from the container and can therefore\n * inject the `Logger` or the config a real filter needs. A mapper cannot; dunx's\n * own default has to be curried over its logger for exactly that reason.\n *\n * A filter with dependencies needs them bindable, the same rule `middleware`\n * entries follow; one with none self-binds and needs no `providers` entry.\n */\n readonly onError?: ErrorHandler;\n /**\n * One structured entry per request, on by default. `false` removes it; an\n * options object tunes what it records. See {@link RequestLoggingMiddleware}.\n *\n * It is the **outermost** middleware, ahead of anything `middleware` declares,\n * so a request rejected by a guard is still logged with the status it got.\n */\n readonly requestLogging?: boolean | RequestLoggingOptions;\n /**\n * One entry at `listen()` naming every route and gateway the process serves. On\n * by default, because it is the answer to \"is my route registered\" and a service\n * that logs nothing at boot cannot answer it from production.\n *\n * `false` removes it. Separate from `requestLogging` rather than sharing its\n * switch: one is per request and one is per process, and silencing the noisy one\n * is not a reason to lose the quiet one. `@dunx/testing` defaults it off, for the\n * same reason it defaults request logging off.\n */\n readonly bootLogging?: boolean;\n /**\n * Bun's `websocket` options, plus where a throwing handler goes. Server-wide, so\n * they live here next to `middleware` rather than on a module: gateways\n * themselves are declared in `@Module({ providers })`.\n */\n readonly websocket?: SocketOptions;\n /**\n * Multi-node websocket fan-out. Absent - the default - means `PubSub` publishes\n * to this process only, which is exactly Bun's native pub/sub and costs nothing.\n *\n * `new RedisRelay({ url })` is the batteries-included one. Anything with a\n * `publish` and a `subscribe` fits, including `@dunx/infra`'s `RedisConnection`,\n * which has to come out of the container and so goes through\n * `app.get(PubSub).relayThrough(...)` instead of this option.\n */\n readonly relay?: PubSubRelay;\n /** The broker channel the relay carries frames on. @default 'dunx:ws' */\n readonly relayChannel?: string;\n /**\n * How hard to retry a subscribe that failed. Same shape as\n * `RelayOptions.resubscribe`: bounded, doubling, and on an unref'd timer, so a\n * broker that never comes back cannot hold the process open.\n *\n * Here rather than only on `relayThrough` because reaching for that to set one\n * option means giving up `relay` above entirely - the two conflict, and the\n * second to run throws `PubSub already relays`.\n */\n readonly relayResubscribe?: RelayOptions['resubscribe'];\n /**\n * What an unmatched path looks like to global middleware.\n *\n * `'guarded'`, the default, gives the miss no route metadata, so a global guard\n * refuses it and an anonymous caller gets that guard's status rather than a 404.\n * That is deliberate: a 404 on a miss while every real path answers 401 tells a\n * prober which paths exist.\n *\n * `'public'` reports the miss as `@Public()`, so a guard honouring that flag\n * passes it through to the conventional 404. The request is still logged and\n * still gets a request id either way, which is the whole reason the fallback\n * runs the middleware at all.\n *\n * A guard can discriminate under either setting: `UNMATCHED` is set on the miss\n * and no real route ever sets it.\n *\n * @default 'guarded'\n */\n readonly notFound?: 'guarded' | 'public';\n}\n\n/**\n * Everything below `listen()` configures the route table, which is built exactly\n * once - when the server binds. Calling any of them afterwards throws rather than\n * being quietly dropped.\n */\nexport interface HttpApp extends App {\n /** Prefixes every discovered route. Last call wins. */\n setGlobalPrefix(prefix: string): this;\n /** Appends middleware, after anything `HttpOptions.middleware` declared. */\n use(...middleware: readonly Ctor<Middleware>[]): this;\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this;\n setting<K extends keyof AppSettings>(key: K): AppSettings[K];\n /** Mounts an `OPTIONS` preflight per path. Last call wins. */\n enableCors(options?: CorsOptions): this;\n /** The same `inject(ClientAddress)` singleton - honours `'trust proxy'`. */\n clientIp(req: BunRequest): string | undefined;\n /** Every gateway path this app upgrades on, exactly as mounted. */\n readonly gatewayPaths: readonly string[];\n listen(port?: number): Promise<string>;\n}\n\nexport class HttpApplication implements HttpApp {\n /** Forwarded from the container so an app can log scope warnings at boot. */\n readonly warnings: readonly string[];\n /**\n * The app's own root module, not this package's wrapper around it.\n *\n * Global middleware, guards and an error filter are all listed by the app, so they\n * resolve as the app's root sees them. Resolving them from the wrapper would mean a\n * guard could only inject what the app happened to *export*, which is a boundary the\n * app never asked for - it wrote the list.\n */\n readonly #root: ModuleRef;\n readonly closed: Promise<void>;\n readonly gatewayPaths: readonly string[];\n readonly #app: App;\n readonly #discovered: readonly DiscoveredRoute[];\n readonly #middleware: Ctor<Middleware>[];\n readonly #settings: AppSettings = defaultSettings();\n readonly #onError: ErrorMapper;\n readonly #port: number;\n readonly #websocket: WebSocketRuntime | undefined;\n readonly #relay: PubSubRelay | undefined;\n readonly #relayChannel: string | undefined;\n readonly #relayResubscribe: RelayOptions['resubscribe'];\n readonly #notFound: 'guarded' | 'public';\n readonly #bootLogging: boolean;\n #globalPrefix = '';\n #cors: CorsOptions | undefined;\n #started = false;\n #server: Server<SocketData> | undefined;\n #resolveClosed: (() => void) | undefined;\n #shuttingDown: Promise<void> | undefined;\n readonly #hooks = new ShutdownHooks();\n\n constructor(\n app: App,\n discovered: readonly DiscoveredRoute[],\n options: HttpOptions,\n root: ModuleRef,\n websocket?: WebSocketRuntime,\n ) {\n this.#app = app;\n this.#root = root;\n this.warnings = app.warnings;\n this.#discovered = discovered;\n this.#middleware = [\n ...(options.requestLogging === false ? [] : [RequestLoggingMiddleware]),\n ...(options.middleware ?? []),\n ];\n // The bound Logger, resolved only when the app did not bring its own handler:\n // a 500's stack belongs in the same stream as everything else.\n //\n // A filter class is resolved from the container here rather than per request, so\n // a missing binding is a boot error like any other and the request path stays a\n // method call. Its `catch` is looked up per call, which is what lets a filter be\n // rebound in a test.\n this.#onError =\n options.onError === undefined\n ? errorMapper(app.get(Logger))\n : toErrorMapper(options.onError, (token) => app.get(token, root));\n this.#port = options.port ?? 3000;\n this.#websocket = websocket;\n this.#relay = options.relay;\n this.#relayChannel = options.relayChannel;\n this.#relayResubscribe = options.relayResubscribe;\n this.#notFound = options.notFound ?? 'guarded';\n this.#bootLogging = options.bootLogging ?? true;\n this.gatewayPaths = websocket?.paths ?? [];\n this.closed = new Promise<void>((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n get<T>(token: InjectionToken<T>): T {\n return this.#app.get(token);\n }\n\n setGlobalPrefix(prefix: string): this {\n this.#assertNotStarted('setGlobalPrefix()');\n this.#globalPrefix = prefix;\n return this;\n }\n\n use(...middleware: readonly Ctor<Middleware>[]): this {\n this.#assertNotStarted('use()');\n this.#middleware.push(...middleware);\n return this;\n }\n\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this {\n this.#assertNotStarted('set()');\n this.#settings[key] = value;\n return this;\n }\n\n setting<K extends keyof AppSettings>(key: K): AppSettings[K] {\n return this.#settings[key];\n }\n\n enableCors(options: CorsOptions = {}): this {\n this.#assertNotStarted('enableCors()');\n this.#cors = options;\n return this;\n }\n\n clientIp(req: BunRequest): string | undefined {\n return this.#app.get(ClientAddress).of(req);\n }\n\n /**\n * The one `Bun.serve` call. A gateway's upgrade is a native `GET` route in the\n * same table, so Bun's router - not a hand-written `fetch` fallback - is what\n * matches an upgrade, and no `fetch` handler is needed at all.\n */\n async listen(port = this.#port): Promise<string> {\n this.#assertNotStarted('listen()');\n this.#started = true;\n\n /**\n * Global middleware resolves **permissively**, not from a named scope.\n *\n * It is the app's own list, and the class it names is usually declared by whichever\n * feature module owns it - so the right instance is the one that module built, with\n * that module's dependencies. Pinning the lookup to the app's root would instead\n * demand the root re-export every guard it lists, which is a boundary nobody asked\n * for. `app.get` finds the single module that declares it, and errors if two do.\n */\n const middleware = this.#middleware.map((entry) =>\n this.#app.get(entry, this.#root),\n );\n const prefixed = this.#prefixed();\n // A `@UseGuards` class comes from the container too, so a guard injects exactly\n // like global middleware does.\n const routes = buildRoutes(\n prefixed,\n middleware,\n this.#onError,\n this.#cors,\n // A module's own middleware resolves from that module, which `from` carries. A\n // `@UseGuards` guard without one takes the same permissive lookup as global\n // middleware.\n (guard, from) =>\n from === undefined ? this.#app.get(guard) : this.#app.get(guard, from),\n );\n\n const ws = this.#websocket;\n if (ws) assertNoGatewayCollisions(prefixed, ws.paths);\n\n // Bun's own 404 never reaches the middleware chain, so an unmatched path is\n // invisible to request logging. This runs only after Bun has matched nothing,\n // so Bun is still the router - it just puts the global middleware in front of\n // the 404 and returns it in the framework's error shape.\n const fetch = buildFallback(\n middleware,\n this.#onError,\n this.#cors,\n this.#notFound,\n );\n\n // Two literals, one call: a route that may answer `undefined` because it\n // upgraded is only a valid route table when `websocket` is there to receive it,\n // and Bun's own types say so.\n const options: Bun.Serve.Options<SocketData> = ws\n ? {\n port,\n fetch,\n routes: withUpgradeRoutes(routes, ws.routes),\n websocket: ws.websocket,\n }\n : { port, fetch, routes };\n this.#server = Bun.serve(options);\n\n attachAddressSource(this.#app.get(ClientAddress), {\n server: this.#server,\n trustProxy: this.#settings['trust proxy'],\n });\n const pubsub = this.#app.get(PubSub);\n pubsub.attach(this.#server);\n // After attach, so a frame that arrives during the subscribe already has a\n // server to fan out on. Awaited so a two-node deployment is subscribed by the\n // time listen() resolves; an unreachable broker fails fast and degrades.\n if (this.#relay) {\n const logger = this.#app.get(Logger);\n await pubsub.relayThrough(this.#relay, {\n ...(this.#relayChannel !== undefined && {\n channel: this.#relayChannel,\n }),\n ...(this.#relayResubscribe !== undefined && {\n resubscribe: this.#relayResubscribe,\n }),\n onError: (error: unknown, phase: RelayPhase) => {\n logger.warn(\n `the websocket relay could not ${phase}. Fan-out is local to this ` +\n 'process until it recovers.',\n { error },\n );\n },\n });\n }\n this.#logServed(prefixed, ws);\n return this.#server.url.href;\n }\n\n /**\n * What the process serves, in one entry, once the table is final.\n *\n * Nest emits a line per controller and a line per route through `RoutesResolver`\n * and `RouterExplorer`, plus one per websocket subscription. That is the useful\n * information and the wrong shape: 30 lines a collector reads as 30 records, for\n * one fact. This is the same content as one structured entry, which is what\n * `WorkerFactory`'s \"Consuming N job(s) on M queue(s)\" already does for the\n * consuming side.\n *\n * At `info`, deliberately. It is one line per process, it is the answer to \"is my\n * route registered\", and a service that logs nothing at boot cannot answer that\n * from production. `logLevel: 'warn'` silences it with everything else.\n *\n * Here rather than at `create()` because `setGlobalPrefix` runs in between, and a\n * table listing unprefixed paths would name routes that do not exist.\n */\n #logServed(\n routes: readonly DiscoveredRoute[],\n ws: WebSocketRuntime | undefined,\n ): void {\n if (!this.#bootLogging) return;\n const gateways = ws?.gateways ?? [];\n const subject = [\n `${routes.length} route(s)`,\n ...(gateways.length === 0 ? [] : [`${gateways.length} gateway(s)`]),\n ].join(' and ');\n\n this.#app.get(Logger).info(`Serving ${subject}`, {\n // The first entry this process writes, so it names what is running it.\n // Under `bun test` `main` is the test file rather than the app entry.\n ...runtimeInfo(),\n routes: routes.map((route) => `${route.method} ${route.path}`),\n ...(gateways.length === 0\n ? {}\n : {\n gateways: gateways.map((gateway) => ({\n path: gateway.path,\n gateway: gateway.name,\n events: gateway.events,\n })),\n }),\n });\n }\n\n // Not delegated to the core app: the server has to stop before providers tear\n // down, so the signal handler must land here. With a gateway the stop is forced -\n // a graceful stop waits for open connections and a WebSocket does not close on\n // its own, so it would hang. Those clients see a 1006 close.\n /**\n * Delegated unchanged: the drain is the container's phase, and `shutdown()`\n * runs it. Public so an operator can start draining without committing to a\n * shutdown, which is what a readiness probe wants during a rolling deploy.\n */\n drain(): Promise<void> {\n return this.#app.drain();\n }\n\n async shutdown(): Promise<void> {\n this.#shuttingDown ??= (async () => {\n // While the port is still open and the routes still answer: a readiness\n // probe has to start failing *before* the server stops, or a load balancer\n // is still routing when the socket closes. `App.shutdown()` below calls\n // this too and it is memoized, so nothing drains twice.\n await this.#app.drain();\n await this.#server?.stop(this.#websocket !== undefined);\n this.#server = undefined;\n // Before the container: a relay this app owns holds two Redis sockets, and\n // `maxRetries: 0` means nothing else will ever close them.\n await this.#app.get(PubSub).close();\n await this.#app.shutdown();\n this.#resolveClosed?.();\n })();\n return this.#shuttingDown;\n }\n\n enableShutdownHooks(\n signals: readonly ShutdownSignal[] = ['SIGTERM', 'SIGINT'],\n options: ShutdownHookOptions = {},\n ): this {\n this.#hooks.install(() => this.shutdown(), signals, options);\n return this;\n }\n\n // Collision detection re-runs inside buildRoutes on these final paths.\n #prefixed(): readonly DiscoveredRoute[] {\n if (this.#globalPrefix === '') return this.#discovered;\n return this.#discovered.map((route) => ({\n ...route,\n path: joinPath(this.#globalPrefix, route.path),\n }));\n }\n\n // #started rather than #server, which shutdown() clears - a hook called after\n // the server stopped is just as ineffective as one called while it ran.\n #assertNotStarted(hook: string): void {\n if (!this.#started) return;\n throw new AppError(\n `${hook} must be called before listen(). The route table and the middleware ` +\n 'chain are folded into one closure per route when the server binds, so ' +\n 'this call could not take effect.',\n );\n }\n}\nObject.defineProperty(HttpApplication, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"app: App\", typeOnly: \"App\" }, { unresolved: \"discovered: readonly DiscoveredRoute[]\" }, { unresolved: \"options: HttpOptions\" }, { unresolved: \"root: ModuleRef\", typeOnly: \"ModuleRef\" }, { unresolved: \"websocket?: WebSocketRuntime\", typeOnly: \"WebSocketRuntime\" }],\n});\n",
24
+ "import type { BunRequest, Server } from 'bun';\nimport {\n AppError,\n Logger,\n runtimeInfo,\n ShutdownHooks,\n teardownError,\n teardownFailures as toFailures,\n type App,\n type AppOptions,\n type Ctor,\n type InjectionToken,\n type ModuleRef,\n type ShutdownHookOptions,\n type ShutdownSignal,\n} from '@dunx/core';\nimport { joinPath, type DiscoveredRoute } from '../route/discover.js';\nimport type { WebSocketRuntime } from '../ws/adapter.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport type { SocketLoggingOptions } from '../ws/logging.js';\nimport type { SocketMiddleware } from '../ws/middleware.js';\nimport type { PubSubRelay, RelayOptions, RelayPhase } from '../ws/relay.js';\nimport type { SocketData, SocketOptions } from '../ws/socket.js';\nimport { attachAddressSource, ClientAddress } from './client-address.js';\nimport type { CorsOptions } from './cors.js';\nimport {\n errorMapper,\n toErrorMapper,\n type ErrorHandler,\n type ErrorMapper,\n} from './errors.js';\nimport type { Middleware } from './middleware.js';\nimport {\n RequestLoggingMiddleware,\n type RequestLoggingOptions,\n} from './request-logging.js';\nimport {\n assertNoGatewayCollisions,\n buildFallback,\n buildRoutes,\n withUpgradeRoutes,\n} from './routes.js';\nimport { defaultSettings, type AppSettings } from './settings.js';\n\nexport interface HttpOptions extends AppOptions {\n readonly port?: number;\n /** Resolved from the container, so middleware can inject(). */\n readonly middleware?: readonly Ctor<Middleware>[];\n /**\n * Replaces the default mapper.\n *\n * A bare `ErrorMapper` function, or an `ErrorFilter` **class** - which is the one\n * to prefer, because a class is resolved from the container and can therefore\n * inject the `Logger` or the config a real filter needs. A mapper cannot; dunx's\n * own default has to be curried over its logger for exactly that reason.\n *\n * A filter with dependencies needs them bindable, the same rule `middleware`\n * entries follow; one with none self-binds and needs no `providers` entry.\n */\n readonly onError?: ErrorHandler;\n /**\n * One structured entry per request, on by default. `false` removes it; an\n * options object tunes what it records. See {@link RequestLoggingMiddleware}.\n *\n * It is the **outermost** middleware, ahead of anything `middleware` declares,\n * so a request rejected by a guard is still logged with the status it got.\n */\n readonly requestLogging?: boolean | RequestLoggingOptions;\n /**\n * One entry at `listen()` naming every route and gateway the process serves. On\n * by default, because it is the answer to \"is my route registered\" and a service\n * that logs nothing at boot cannot answer it from production.\n *\n * `false` removes it. Separate from `requestLogging` rather than sharing its\n * switch: one is per request and one is per process, and silencing the noisy one\n * is not a reason to lose the quiet one. `@dunx/testing` defaults it off, for the\n * same reason it defaults request logging off.\n */\n readonly bootLogging?: boolean;\n /**\n * Bun's `websocket` options, plus where a throwing handler goes. Server-wide, so\n * they live here next to `middleware` rather than on a module: gateways\n * themselves are declared in `@Module({ providers })`.\n */\n readonly websocket?: SocketOptions;\n /**\n * The socket half of `middleware`, resolved from the container the same way.\n *\n * Each entry wraps every dispatched gateway handler - open, each named message,\n * the catch-all, close, drain, ping and pong - the way an HTTP middleware wraps a\n * route. `socketLogging`'s middleware runs outermost, ahead of anything here.\n */\n readonly socketMiddleware?: readonly Ctor<SocketMiddleware>[];\n /**\n * One structured entry per socket frame, on by default at **`debug`**. `false`\n * removes it; an options object tunes the level per event. See\n * {@link SocketLoggingMiddleware}.\n *\n * `debug` rather than request logging's `info`, because a gateway can take a\n * frame per connection per tick. The default `ConsoleLogger` threshold is\n * `info`, so this writes nothing until an app lowers its level or names a louder\n * one here.\n *\n * Installing it also takes `SocketOptions.onError`'s `console.error` default out\n * of the way: a middleware wraps the handler, so the failure is already reported\n * through the `Logger` with the gateway and the event on it.\n */\n readonly socketLogging?: boolean | SocketLoggingOptions;\n /**\n * Multi-node websocket fan-out. Absent - the default - means `PubSub` publishes\n * to this process only, which is exactly Bun's native pub/sub and costs nothing.\n *\n * `new RedisRelay({ url })` is the batteries-included one. Anything with a\n * `publish` and a `subscribe` fits, including `@dunx/infra`'s `RedisConnection`,\n * which has to come out of the container and so goes through\n * `app.get(PubSub).relayThrough(...)` instead of this option.\n */\n readonly relay?: PubSubRelay;\n /** The broker channel the relay carries frames on. @default 'dunx:ws' */\n readonly relayChannel?: string;\n /**\n * How hard to retry a subscribe that failed. Same shape as\n * `RelayOptions.resubscribe`: bounded, doubling, and on an unref'd timer, so a\n * broker that never comes back cannot hold the process open.\n *\n * Here rather than only on `relayThrough` because reaching for that to set one\n * option means giving up `relay` above entirely - the two conflict, and the\n * second to run throws `PubSub already relays`.\n */\n readonly relayResubscribe?: RelayOptions['resubscribe'];\n /**\n * What an unmatched path looks like to global middleware.\n *\n * `'guarded'`, the default, gives the miss no route metadata, so a global guard\n * refuses it and an anonymous caller gets that guard's status rather than a 404.\n * That is deliberate: a 404 on a miss while every real path answers 401 tells a\n * prober which paths exist.\n *\n * `'public'` reports the miss as `@Public()`, so a guard honouring that flag\n * passes it through to the conventional 404. The request is still logged and\n * still gets a request id either way, which is the whole reason the fallback\n * runs the middleware at all.\n *\n * A guard can discriminate under either setting: `UNMATCHED` is set on the miss\n * and no real route ever sets it.\n *\n * @default 'guarded'\n */\n readonly notFound?: 'guarded' | 'public';\n}\n\n/**\n * Everything below `listen()` configures the route table, which is built exactly\n * once - when the server binds. Calling any of them afterwards throws rather than\n * being quietly dropped.\n */\nexport interface HttpApp extends App {\n /** Prefixes every discovered route. Last call wins. */\n setGlobalPrefix(prefix: string): this;\n /** Appends middleware, after anything `HttpOptions.middleware` declared. */\n use(...middleware: readonly Ctor<Middleware>[]): this;\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this;\n setting<K extends keyof AppSettings>(key: K): AppSettings[K];\n /** Mounts an `OPTIONS` preflight per path. Last call wins. */\n enableCors(options?: CorsOptions): this;\n /** The same `inject(ClientAddress)` singleton - honours `'trust proxy'`. */\n clientIp(req: BunRequest): string | undefined;\n /** Every gateway path this app upgrades on, exactly as mounted. */\n readonly gatewayPaths: readonly string[];\n listen(port?: number): Promise<string>;\n}\n\nexport class HttpApplication implements HttpApp {\n /** Forwarded from the container so an app can log scope warnings at boot. */\n readonly warnings: readonly string[];\n /**\n * The app's own root module, not this package's wrapper around it.\n *\n * Global middleware, guards and an error filter are all listed by the app, so they\n * resolve as the app's root sees them. Resolving them from the wrapper would mean a\n * guard could only inject what the app happened to *export*, which is a boundary the\n * app never asked for - it wrote the list.\n */\n readonly #root: ModuleRef;\n readonly closed: Promise<void>;\n readonly gatewayPaths: readonly string[];\n readonly #app: App;\n readonly #discovered: readonly DiscoveredRoute[];\n readonly #middleware: Ctor<Middleware>[];\n readonly #settings: AppSettings = defaultSettings();\n readonly #onError: ErrorMapper;\n readonly #port: number;\n readonly #websocket: WebSocketRuntime | undefined;\n readonly #relay: PubSubRelay | undefined;\n readonly #relayChannel: string | undefined;\n readonly #relayResubscribe: RelayOptions['resubscribe'];\n readonly #notFound: 'guarded' | 'public';\n readonly #bootLogging: boolean;\n #globalPrefix = '';\n #cors: CorsOptions | undefined;\n #started = false;\n #server: Server<SocketData> | undefined;\n #resolveClosed: (() => void) | undefined;\n #shuttingDown: Promise<void> | undefined;\n readonly #hooks = new ShutdownHooks();\n\n constructor(\n app: App,\n discovered: readonly DiscoveredRoute[],\n options: HttpOptions,\n root: ModuleRef,\n websocket?: WebSocketRuntime,\n ) {\n this.#app = app;\n this.#root = root;\n this.warnings = app.warnings;\n this.#discovered = discovered;\n this.#middleware = [\n ...(options.requestLogging === false ? [] : [RequestLoggingMiddleware]),\n ...(options.middleware ?? []),\n ];\n // The bound Logger, resolved only when the app did not bring its own handler:\n // a 500's stack belongs in the same stream as everything else.\n //\n // A filter class is resolved from the container here rather than per request, so\n // a missing binding is a boot error like any other and the request path stays a\n // method call. Its `catch` is looked up per call, which is what lets a filter be\n // rebound in a test.\n this.#onError =\n options.onError === undefined\n ? errorMapper(app.get(Logger))\n : toErrorMapper(options.onError, (token) => app.get(token, root));\n this.#port = options.port ?? 3000;\n this.#websocket = websocket;\n this.#relay = options.relay;\n this.#relayChannel = options.relayChannel;\n this.#relayResubscribe = options.relayResubscribe;\n this.#notFound = options.notFound ?? 'guarded';\n this.#bootLogging = options.bootLogging ?? true;\n this.gatewayPaths = websocket?.paths ?? [];\n this.closed = new Promise<void>((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n get<T>(token: InjectionToken<T>): T {\n return this.#app.get(token);\n }\n\n setGlobalPrefix(prefix: string): this {\n this.#assertNotStarted('setGlobalPrefix()');\n this.#globalPrefix = prefix;\n return this;\n }\n\n use(...middleware: readonly Ctor<Middleware>[]): this {\n this.#assertNotStarted('use()');\n this.#middleware.push(...middleware);\n return this;\n }\n\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this {\n this.#assertNotStarted('set()');\n this.#settings[key] = value;\n return this;\n }\n\n setting<K extends keyof AppSettings>(key: K): AppSettings[K] {\n return this.#settings[key];\n }\n\n enableCors(options: CorsOptions = {}): this {\n this.#assertNotStarted('enableCors()');\n this.#cors = options;\n return this;\n }\n\n clientIp(req: BunRequest): string | undefined {\n return this.#app.get(ClientAddress).of(req);\n }\n\n /**\n * The one `Bun.serve` call. A gateway's upgrade is a native `GET` route in the\n * same table, so Bun's router - not a hand-written `fetch` fallback - is what\n * matches an upgrade, and no `fetch` handler is needed at all.\n */\n async listen(port = this.#port): Promise<string> {\n this.#assertNotStarted('listen()');\n this.#started = true;\n\n /**\n * Global middleware resolves **permissively**, not from a named scope.\n *\n * It is the app's own list, and the class it names is usually declared by whichever\n * feature module owns it - so the right instance is the one that module built, with\n * that module's dependencies. Pinning the lookup to the app's root would instead\n * demand the root re-export every guard it lists, which is a boundary nobody asked\n * for. `app.get` finds the single module that declares it, and errors if two do.\n */\n const middleware = this.#middleware.map((entry) =>\n this.#app.get(entry, this.#root),\n );\n const prefixed = this.#prefixed();\n // A `@UseGuards` class comes from the container too, so a guard injects exactly\n // like global middleware does.\n const routes = buildRoutes(\n prefixed,\n middleware,\n this.#onError,\n this.#cors,\n // A module's own middleware resolves from that module, which `from` carries. A\n // `@UseGuards` guard without one takes the same permissive lookup as global\n // middleware.\n (guard, from) =>\n from === undefined ? this.#app.get(guard) : this.#app.get(guard, from),\n );\n\n const ws = this.#websocket;\n if (ws) assertNoGatewayCollisions(prefixed, ws.paths);\n\n // Bun's own 404 never reaches the middleware chain, so an unmatched path is\n // invisible to request logging. This runs only after Bun has matched nothing,\n // so Bun is still the router - it just puts the global middleware in front of\n // the 404 and returns it in the framework's error shape.\n const fetch = buildFallback(\n middleware,\n this.#onError,\n this.#cors,\n this.#notFound,\n );\n\n // Two literals, one call: a route that may answer `undefined` because it\n // upgraded is only a valid route table when `websocket` is there to receive it,\n // and Bun's own types say so.\n const options: Bun.Serve.Options<SocketData> = ws\n ? {\n port,\n fetch,\n routes: withUpgradeRoutes(routes, ws.routes),\n websocket: ws.websocket,\n }\n : { port, fetch, routes };\n this.#server = Bun.serve(options);\n\n attachAddressSource(this.#app.get(ClientAddress), {\n server: this.#server,\n trustProxy: this.#settings['trust proxy'],\n });\n const pubsub = this.#app.get(PubSub);\n pubsub.attach(this.#server);\n // After attach, so a frame that arrives during the subscribe already has a\n // server to fan out on. Awaited so a two-node deployment is subscribed by the\n // time listen() resolves; an unreachable broker fails fast and degrades.\n if (this.#relay) {\n const logger = this.#app.get(Logger);\n await pubsub.relayThrough(this.#relay, {\n ...(this.#relayChannel !== undefined && {\n channel: this.#relayChannel,\n }),\n ...(this.#relayResubscribe !== undefined && {\n resubscribe: this.#relayResubscribe,\n }),\n onError: (error: unknown, phase: RelayPhase) => {\n logger.warn(\n `the websocket relay could not ${phase}. Fan-out is local to this ` +\n 'process until it recovers.',\n { error },\n );\n },\n });\n }\n this.#logServed(prefixed, ws);\n return this.#server.url.href;\n }\n\n /**\n * What the process serves, in one entry, once the table is final.\n *\n * Nest emits a line per controller and a line per route through `RoutesResolver`\n * and `RouterExplorer`, plus one per websocket subscription. That is the useful\n * information and the wrong shape: 30 lines a collector reads as 30 records, for\n * one fact. This is the same content as one structured entry, which is what\n * `WorkerFactory`'s \"Consuming N job(s) on M queue(s)\" already does for the\n * consuming side.\n *\n * At `info`, deliberately. It is one line per process, it is the answer to \"is my\n * route registered\", and a service that logs nothing at boot cannot answer that\n * from production. `logLevel: 'warn'` silences it with everything else.\n *\n * Here rather than at `create()` because `setGlobalPrefix` runs in between, and a\n * table listing unprefixed paths would name routes that do not exist.\n */\n #logServed(\n routes: readonly DiscoveredRoute[],\n ws: WebSocketRuntime | undefined,\n ): void {\n if (!this.#bootLogging) return;\n const gateways = ws?.gateways ?? [];\n const subject = [\n `${routes.length} route(s)`,\n ...(gateways.length === 0 ? [] : [`${gateways.length} gateway(s)`]),\n ].join(' and ');\n\n this.#app.get(Logger).info(`Serving ${subject}`, {\n // The first entry this process writes, so it names what is running it.\n // Under `bun test` `main` is the test file rather than the app entry.\n ...runtimeInfo(),\n routes: routes.map((route) => `${route.method} ${route.path}`),\n ...(gateways.length === 0\n ? {}\n : {\n gateways: gateways.map((gateway) => ({\n path: gateway.path,\n gateway: gateway.name,\n events: gateway.events,\n })),\n }),\n });\n }\n\n // Not delegated to the core app: the server has to stop before providers tear\n // down, so the signal handler must land here. With a gateway the stop is forced -\n // a graceful stop waits for open connections and a WebSocket does not close on\n // its own, so it would hang. Those clients see a 1006 close.\n /**\n * Delegated unchanged: the drain is the container's phase, and `shutdown()`\n * runs it. Public so an operator can start draining without committing to a\n * shutdown, which is what a readiness probe wants during a rolling deploy.\n */\n drain(): Promise<void> {\n return this.#app.drain();\n }\n\n /**\n * The four phases, in order, and **none of them is skipped because an earlier\n * one failed**. A drain hook that threw used to abort this before `server.stop()`\n * had run, so the port stayed open and `closed` never resolved; each failure is\n * collected now and thrown once the whole teardown is over.\n */\n async shutdown(): Promise<void> {\n this.#shuttingDown ??= (async () => {\n const failures: unknown[] = [];\n const step = async (run: () => Promise<unknown>): Promise<void> => {\n try {\n await run();\n } catch (error) {\n failures.push(...toFailures(error));\n }\n };\n\n // While the port is still open and the routes still answer: a readiness\n // probe has to start failing *before* the server stops, or a load balancer\n // is still routing when the socket closes. `App.shutdown()` below calls\n // this too and it is memoized, so nothing drains twice.\n await step(() => this.#app.drain());\n await step(async () => this.#server?.stop(this.#websocket !== undefined));\n this.#server = undefined;\n // Before the container: a relay this app owns holds two Redis sockets, and\n // `maxRetries: 0` means nothing else will ever close them.\n await step(() => this.#app.get(PubSub).close());\n try {\n await step(() => this.#app.shutdown());\n } finally {\n this.#resolveClosed?.();\n }\n if (failures.length > 0) throw teardownError(failures);\n })();\n return this.#shuttingDown;\n }\n\n enableShutdownHooks(\n signals: readonly ShutdownSignal[] = ['SIGTERM', 'SIGINT'],\n options: ShutdownHookOptions = {},\n ): this {\n this.#hooks.install(() => this.shutdown(), signals, options);\n return this;\n }\n\n // Collision detection re-runs inside buildRoutes on these final paths.\n #prefixed(): readonly DiscoveredRoute[] {\n if (this.#globalPrefix === '') return this.#discovered;\n return this.#discovered.map((route) => ({\n ...route,\n path: joinPath(this.#globalPrefix, route.path),\n }));\n }\n\n // #started rather than #server, which shutdown() clears - a hook called after\n // the server stopped is just as ineffective as one called while it ran.\n #assertNotStarted(hook: string): void {\n if (!this.#started) return;\n throw new AppError(\n `${hook} must be called before listen(). The route table and the middleware ` +\n 'chain are folded into one closure per route when the server binds, so ' +\n 'this call could not take effect.',\n );\n }\n}\nObject.defineProperty(HttpApplication, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"app: App\", typeOnly: \"App\" }, { unresolved: \"discovered: readonly DiscoveredRoute[]\" }, { unresolved: \"options: HttpOptions\" }, { unresolved: \"root: ModuleRef\", typeOnly: \"ModuleRef\" }, { unresolved: \"websocket?: WebSocketRuntime\", typeOnly: \"WebSocketRuntime\" }],\n});\n",
23
25
  "import {\n Logger,\n RequestContext,\n type RequestFields as ScopeFields,\n} from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport type { RouteContext } from './context.js';\nimport { HttpError } from './errors.js';\nimport type { Middleware, Next } from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\nexport const REQUEST_ID_HEADER = 'x-request-id';\n\nexport interface RequestLoggingOptions {\n /** Bodies past this many characters are logged as a size. Default 2048. `0` omits them. */\n readonly maxBodyLength?: number;\n /**\n * Log the request body. Default **`false`**.\n *\n * Reading it means `req.clone().text()` - a second copy of every payload,\n * buffered and parsed, on the hot path. Measured on the `validate` scenario in\n * `internal/bench`, turning both body options on costs roughly two thirds of the\n * throughput. It is also the field most likely to contain a password.\n *\n * Turn it on in development, where seeing the payload is the point.\n */\n readonly requestBody?: boolean;\n /** Log the response body. Default **`false`** - same clone-and-buffer cost. */\n readonly responseBody?: boolean;\n /**\n * Paths to skip entirely - a health check polled every second, say.\n *\n * **Entirely** is literal: no entry, no `x-request-id` on the response, and no\n * `AsyncLocalStorage` scope, so anything the handler logs is uncorrelated. That\n * is what makes it free. `correlateIgnored` buys the correlation back.\n */\n readonly ignore?: readonly string[];\n /**\n * Path **prefixes** to skip, for a whole mount rather than one path.\n *\n * `ignore` is an exact-match `Set` because that is one lookup on the hot path\n * and a health check is one path. A mount is not: `@dunx/dashboard` at\n * `/_dunx` polls four endpoints every five seconds and bull-board pulls a\n * dozen assets, and listing them is both tedious and wrong the moment either\n * grows an endpoint.\n *\n * Scanned only when non-empty, so an app that sets none pays nothing - the\n * same guard `ignore` has. Keep the list short; it is a loop.\n *\n * ```ts\n * requestLogging: { ignorePrefix: ['/_dunx'] }\n * ```\n */\n readonly ignorePrefix?: readonly string[];\n /**\n * Keep the request id and the async scope on an `ignore`d path. Default\n * **`false`**.\n *\n * \"Do not log the health check, but do keep its request id\" is this. The path\n * still writes no entry of its own; it gets an id - inbound or minted - on the\n * response, and everything the handler logs carries it.\n *\n * It is not the default because it is not free: the ignored path pays for\n * reading the header, `crypto.randomUUID()`, the `runWithContext` scope and the\n * response header. On the `bun run logging` decomposition those four rows are\n * ~2.2 µs, against ~5.4 µs for the whole default path - so it costs the half\n * that buys correlation and not the half that builds and serialises the entry.\n */\n readonly correlateIgnored?: boolean;\n /**\n * Wrap every request in an `AsyncLocalStorage` scope. Default **`true`**.\n *\n * The scope is what lets a service logging four frames down come out carrying\n * `requestId` without being handed a request object. It is measured: the\n * `runWithContext` row of `bun run logging` is **+0.91 µs**, 17% of the 5.38 µs\n * request logging costs over `requestLogging: false`.\n *\n * `correlate: false` skips it. **The request entry is unchanged** - the same\n * `requestId`, `method`, `event`, `flow` and `context` fields are written onto\n * it directly instead of being read back out of the store. What is lost is\n * everything *else* the request logs: those lines carry no `requestId`, and\n * `updateContext` from a handler has nothing to update.\n *\n * Worth it for an app whose handlers never log, or one that passes correlation\n * explicitly. Leave it on otherwise; correlation is most of what a request id\n * is for.\n */\n readonly correlate?: boolean;\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * An inbound id is honoured so a trace survives across services - but only if it\n * is a UUID, which is what this middleware would have minted. It is a\n * caller-supplied string that ends up in every line the request writes, so a\n * newline, a megabyte, or a deliberate collision with somebody else's trace is\n * replaced by a fresh one rather than trusted. A production template validated it the\n * same way.\n *\n * The length check first: it is what keeps garbage away from the regex, and the\n * common case has no header at all.\n */\nconst traceId = (inbound: string | null): string =>\n inbound !== null && inbound.length === 36 && UUID.test(inbound)\n ? inbound\n : crypto.randomUUID();\n\nconst parse = (text: string, limit: number): unknown => {\n if (limit === 0) return undefined;\n if (text.length === 0) return undefined;\n if (text.length > limit) return `[${text.length} bytes]`;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\nconst elapsedMs = (started: number): number =>\n Math.round((Bun.nanoseconds() - started) / 1e6);\n\n/** What the entry's `request` field carries, built in the order it is logged. */\ntype RequestFields = Record<string, unknown>;\n\n/**\n * One structured entry per request, carrying the request and its response.\n *\n * Installed by `HttpFactory.create` unless `requestLogging: false`. It injects\n * `Logger` and `RequestContext` - both `@dunx/core` contracts, both bound by\n * default - so it works with no logging module imported, and picks up\n * `@arkv/logger` automatically once `@dunx/infra/logger` is.\n *\n * **One entry, not two.** A framework whose middleware cannot see the response\n * needs a middleware for the inbound half and an\n * interceptor for the outbound one, because they are different classes and the\n * interceptor cannot see what the middleware saw. Here they are the same\n * closure, so there is no pair to correlate by `requestId` to find out how a\n * call ended. A 4xx is the same line at `warn`, a 5xx at `error`.\n *\n * Everything the handler logs in between carries `requestId`, `method`, `event`\n * and `context` without being passed anything, because the whole call runs\n * inside `runWithContext` - unless `correlate: false`, which drops the scope and\n * with it that guarantee, but not the fields on this middleware's own entry.\n *\n * **Nothing here is `async`.** Reading the request or the response body are the\n * only steps that can ever wait, both are off by default, and both are adopted\n * with `.then` rather than awaited - the same rule `input.ts` follows, for the\n * same measured reason. An `async` scope callback alone cost 0.44 µs/request\n * against a synchronous one on raw `Bun.serve`.\n */\nexport class RequestLoggingMiddleware implements Middleware {\n readonly #limit: number;\n readonly #requestBody: boolean;\n readonly #responseBody: boolean;\n readonly #ignore: ReadonlySet<string>;\n readonly #ignorePrefix: readonly string[];\n readonly #correlateIgnored: boolean;\n readonly #correlate: boolean;\n\n constructor(\n private readonly logger: Logger,\n private readonly context: RequestContext,\n options: RequestLoggingOptions = {},\n ) {\n this.#limit = options.maxBodyLength ?? 2048;\n this.#requestBody = options.requestBody ?? false;\n this.#responseBody = options.responseBody ?? false;\n this.#ignore = new Set(options.ignore ?? []);\n this.#ignorePrefix = options.ignorePrefix ?? [];\n this.#correlateIgnored = options.correlateIgnored ?? false;\n this.#correlate = options.correlate ?? true;\n }\n\n /**\n * Both guards check emptiness first, so an app configuring neither pays one\n * `size` read and one `length` read rather than a lookup and a loop.\n */\n #ignored(path: string): boolean {\n if (this.#ignore.size > 0 && this.#ignore.has(path)) return true;\n if (this.#ignorePrefix.length === 0) return false;\n return this.#ignorePrefix.some((prefix) => path.startsWith(prefix));\n }\n\n handle(req: BunRequest, ctx: RouteContext, next: Next): Promise<Response> {\n // `new URL(req.url)` parses the scheme, host, port, query and hash to reach one\n // string. This finds the same two offsets once and slices both the pathname and\n // the query out of them, which is what every request needs and all that most of\n // them need.\n const url = req.url;\n const from = url.indexOf('/', url.indexOf('://') + 3);\n const mark = from === -1 ? -1 : url.indexOf('?', from);\n const path =\n from === -1 ? '/' : mark === -1 ? url.slice(from) : url.slice(from, mark);\n if (this.#ignored(path)) {\n return this.#correlateIgnored\n ? this.#correlated(req, ctx, path, next)\n : next();\n }\n\n const started = Bun.nanoseconds();\n const requestId = traceId(req.headers.get(REQUEST_ID_HEADER));\n const scope: ScopeFields = {\n requestId,\n method: ctx.method,\n event: path,\n flow: 'http',\n context: `${ctx.controller}.${ctx.handler}`,\n };\n\n // The same five fields either way. Under `correlate` they go into the store,\n // which the logger reads back for every line the request writes; without it\n // they are merged straight onto this middleware's own entry, so the request\n // log is identical and only the lines in between lose their id.\n return this.#correlate\n ? this.context.runWithContext(scope, () =>\n this.#begin(\n req,\n url,\n mark,\n path,\n requestId,\n started,\n next,\n undefined,\n ),\n )\n : this.#begin(req, url, mark, path, requestId, started, next, scope);\n }\n\n #begin(\n req: BunRequest,\n url: string,\n mark: number,\n path: string,\n requestId: string,\n started: number,\n next: Next,\n scope: ScopeFields | undefined,\n ): Promise<Response> {\n const request: RequestFields = {};\n if (mark !== -1) {\n request['query'] = Object.fromEntries(\n new URLSearchParams(url.slice(mark + 1)),\n );\n }\n const body = this.#body(req);\n if (body === undefined) {\n request['userAgent'] = req.headers.get('user-agent');\n return this.#dispatch(\n req,\n path,\n requestId,\n started,\n request,\n next,\n scope,\n );\n }\n return body.then((value) => {\n if (value !== undefined) request['body'] = value;\n request['userAgent'] = req.headers.get('user-agent');\n return this.#dispatch(\n req,\n path,\n requestId,\n started,\n request,\n next,\n scope,\n );\n });\n }\n\n /**\n * An ignored path under `correlateIgnored`: the scope and the response header,\n * and no entry. Nothing is timed and no fields are collected, because nothing\n * here is ever logged. Under `correlate: false` there is no scope to open here\n * either - only the response header is left, which is all `correlateIgnored`\n * can still mean once nothing reads the store.\n */\n #correlated(\n req: BunRequest,\n ctx: RouteContext,\n path: string,\n next: Next,\n ): Promise<Response> {\n const requestId = traceId(req.headers.get(REQUEST_ID_HEADER));\n const stamp = (response: Response): Response => {\n response.headers.set(REQUEST_ID_HEADER, requestId);\n return response;\n };\n if (!this.#correlate) return next().then(stamp);\n return this.context.runWithContext(\n {\n requestId,\n method: ctx.method,\n event: path,\n flow: 'http',\n context: `${ctx.controller}.${ctx.handler}`,\n },\n () => next().then(stamp),\n );\n }\n\n #dispatch(\n req: BunRequest,\n path: string,\n requestId: string,\n started: number,\n request: RequestFields,\n next: Next,\n scope: ScopeFields | undefined,\n ): Promise<Response> {\n // `next()` is only ever a promise once the chain bottoms out in a route, but a\n // user middleware ahead of the route may throw out of `handle` synchronously,\n // and that request is still one this middleware promised to log.\n let settled: Promise<Response>;\n try {\n settled = next();\n } catch (error) {\n this.#failed(req, path, started, request, error, scope);\n throw error;\n }\n return settled.then(\n (response) =>\n this.#succeeded(\n req,\n path,\n requestId,\n started,\n request,\n response,\n scope,\n ),\n (error: unknown) => {\n this.#failed(req, path, started, request, error, scope);\n throw error;\n },\n );\n }\n\n /**\n * Logged and rethrown: the error mapper still owns the status and the response\n * shape. A 404 or a rejected body is the caller's fault, and logging every probe\n * at `error` would drown the ones that matter.\n */\n #failed(\n req: BunRequest,\n path: string,\n started: number,\n request: RequestFields,\n error: unknown,\n scope: ScopeFields | undefined,\n ): void {\n const status =\n error instanceof HttpError\n ? error.status\n : HttpStatusCode.INTERNAL_SERVER_ERROR;\n const entry = {\n ...scope,\n request,\n err: error,\n statusCode: status,\n elapsedMs: elapsedMs(started),\n };\n const line = `${req.method} ${path} ${status}`;\n if (status < HttpStatusCode.INTERNAL_SERVER_ERROR) {\n this.logger.warn(line, entry);\n } else {\n this.logger.error(line, entry);\n }\n }\n\n #succeeded(\n req: BunRequest,\n path: string,\n requestId: string,\n started: number,\n request: RequestFields,\n response: Response,\n scope: ScopeFields | undefined,\n ): Response | Promise<Response> {\n const body = this.#responseFields(response);\n if (body === undefined) {\n this.logger.info(`${req.method} ${path} ${response.status}`, {\n ...scope,\n request,\n statusCode: response.status,\n elapsedMs: elapsedMs(started),\n });\n response.headers.set(REQUEST_ID_HEADER, requestId);\n return response;\n }\n return body.then((value) => {\n this.logger.info(`${req.method} ${path} ${response.status}`, {\n ...scope,\n request,\n statusCode: response.status,\n ...(value === undefined ? {} : { responseBody: value }),\n elapsedMs: elapsedMs(started),\n });\n response.headers.set(REQUEST_ID_HEADER, requestId);\n return response;\n });\n }\n\n /**\n * `undefined` - the default - means there is nothing to read, and the caller\n * stays on the synchronous path. Clones when there is, so the handler's own\n * stream is never the one that was consumed.\n */\n #body(req: BunRequest): Promise<unknown> | undefined {\n if (!this.#requestBody) return undefined;\n if (req.method === 'GET' || req.method === 'HEAD') return undefined;\n if (!(req.headers.get('content-type') ?? '').includes('application/json')) {\n return undefined;\n }\n return req\n .clone()\n .text()\n .then((text) => parse(text, this.#limit));\n }\n\n #responseFields(response: Response): Promise<unknown> | undefined {\n if (!this.#responseBody) return undefined;\n if (\n !(response.headers.get('content-type') ?? '').includes('application/json')\n ) {\n return undefined;\n }\n return response\n .clone()\n .text()\n .then((text) => parse(text, this.#limit));\n }\n}\nObject.defineProperty(RequestLoggingMiddleware, Symbol.for('dunx.deps'), {\n value: () => [Logger, RequestContext, { unresolved: \"options: RequestLoggingOptions = {}\" }],\n});\n",
24
- "import { AppError, type Ctor, type ModuleRef } from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport type { DiscoveredRoute } from '../route/discover.js';\nimport type { HttpMethod } from '../route/marker.js';\nimport { PUBLIC, UNMATCHED, type MetaKey } from '../route/metadata.js';\nimport type { RouteInput } from '../route/schema.js';\nimport type { UpgradeHandler } from '../ws/adapter.js';\nimport { buildContext, type RouteContext } from './context.js';\nimport { preflight, withCors, type CorsOptions } from './cors.js';\nimport { defaultErrorMapper, HttpError, type ErrorMapper } from './errors.js';\nimport { buildInputReader, type InputReader } from './input.js';\nimport {\n compose,\n type Middleware,\n type RouteHandler,\n type ServedHandler,\n} from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\n/** How a `@UseGuards` class becomes an instance. `listen()` passes `app.get`. */\n/**\n * How a guard or a module's middleware becomes an instance.\n *\n * `from` names the module whose scope it resolves in - module middleware has to be\n * built from the module that declared it, or it could not inject that module's private\n * providers, which is the point of declaring it there.\n */\nexport type GuardResolver = (\n guard: Ctor<Middleware>,\n from?: ModuleRef,\n) => Middleware;\n\nconst construct: GuardResolver = (guard) =>\n new (guard as new () => Middleware)();\n\n/** `OPTIONS` is never a `@Get`-style route - only CORS mounts one. */\nexport type RouteMethod = HttpMethod | 'OPTIONS';\n\nexport type BunRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler>>\n>;\n\n/**\n * What `listen()` hands `Bun.serve`: the HTTP table plus one `GET` per gateway,\n * whose handler may answer `undefined` because the socket was upgraded.\n */\nexport type ServeRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler | UpgradeHandler>>\n>;\n\n/**\n * A `Response` passes through untouched - that is the escape hatch, and nothing\n * about it is worth second-guessing. Nothing at all is a 204: `Response.json(null)`\n * would be a body claiming to be no body.\n */\nconst toResponse = (value: unknown, status: number): Response => {\n if (value instanceof Response) return value;\n if (value === undefined || value === null) {\n return new Response(null, { status: HttpStatusCode.NO_CONTENT });\n }\n return Response.json(value, { status });\n};\n\n/** The usual rule: an explicit `status`, else 201 for POST, else 200. */\nconst statusFor = (route: DiscoveredRoute): number =>\n route.options?.status ??\n (route.method === 'POST' ? HttpStatusCode.CREATED : HttpStatusCode.OK);\n\n/**\n * Bun silently lets one route win on a collision, so a duplicate method+path is a\n * boot error naming both handlers. Run twice: once at `create()` on the discovered\n * paths, and again from `buildRoutes` at `listen()` on the final, prefixed ones.\n */\nexport const assertNoCollisions = (\n discovered: readonly DiscoveredRoute[],\n): void => {\n const owners = new Map<string, string>();\n\n for (const route of discovered) {\n const key = `${route.method} ${route.path}`;\n const owner = `${route.controller}.${route.handlerName}`;\n const existing = owners.get(key);\n\n if (existing !== undefined) {\n throw new AppError(\n `Route collision: ${key} is declared by ${existing} and by ${owner}. ` +\n 'Bun would keep only one of them.',\n );\n }\n owners.set(key, owner);\n }\n};\n\n/**\n * A gateway's upgrade is a native route like any other, so a path claimed by both a\n * controller and a gateway would lose one of them when the two tables merge.\n */\nexport const assertNoGatewayCollisions = (\n discovered: readonly DiscoveredRoute[],\n gatewayPaths: readonly string[],\n): void => {\n const gateways = new Set(gatewayPaths);\n\n for (const route of discovered) {\n if (gateways.has(route.path)) {\n throw new AppError(\n `Gateway path collision: ${route.path} is served by a gateway and by ` +\n `${route.controller}.${route.handlerName}(). The upgrade is a route too, ` +\n 'so one of them would be dropped.',\n );\n }\n }\n};\n\n/**\n * The two tables in one. A gateway's `GET` is what Bun's router matches on an\n * upgrade - the reason no `fetch` handler is needed for a socket to connect.\n */\nexport const withUpgradeRoutes = (\n routes: BunRoutes,\n gateways: ReadonlyMap<string, UpgradeHandler>,\n): ServeRoutes => {\n const merged: ServeRoutes = { ...routes };\n for (const [path, upgrade] of gateways) merged[path] = { GET: upgrade };\n return merged;\n};\n\n/**\n * The context an unmatched request gets. There is no controller and no handler,\n * and saying so is more useful to a log line than an empty string.\n *\n * A miss carries no route metadata, so a global guard reading none of it refuses,\n * which makes every 404 a 401 for an anonymous caller with no `@Public()`\n * anywhere to put. **That is deliberate and stays the default**: an unmatched\n * path answering 404 while every real path answers 401 tells a prober exactly\n * which paths exist.\n *\n * `notFound: 'public'` opts into the conventional 404 by reporting the miss as\n * public. Either way `UNMATCHED` is set, and no real route ever sets it, so a\n * guard can tell a genuinely public route from one that matched nothing.\n */\nconst unmatchedContext = (req: Request, isPublic: boolean): RouteContext =>\n Object.freeze({\n controller: '(unmatched)',\n handler: '(none)',\n method: req.method as HttpMethod,\n path: new URL(req.url).pathname,\n get: <T>(key: MetaKey<T>): T | undefined => {\n if (key.id === UNMATCHED.id) return true as T;\n if (key.id === PUBLIC.id && isPublic) return true as T;\n return undefined;\n },\n });\n\n/**\n * Bun answers an unmatched path itself, so nothing in the middleware chain ever\n * sees it - which makes a 404 invisible to request logging, metrics and tracing.\n *\n * This is the only `fetch` handler dunx installs, and it is not a router: Bun\n * still does all the matching, and this runs only once Bun has decided nothing\n * matched. It puts the global middleware in front of a 404 in the framework's\n * own error shape.\n *\n * Composed per request rather than at boot, because the context names the path\n * that missed. That allocation is on the 404 path only.\n */\nexport const buildFallback = (\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n notFound: 'guarded' | 'public' = 'guarded',\n): RouteHandler => {\n // The canonical status name, not a sentence naming the path back at the\n // caller: an unmatched path is the one place where echoing the request would\n // tell a prober something about the surface it just failed to find.\n const miss: RouteHandler = () => {\n throw new HttpError(HttpStatusCode.NOT_FOUND, 'NOT_FOUND');\n };\n\n const run: RouteHandler = async (req) => {\n try {\n return await compose(\n middleware,\n unmatchedContext(req, notFound === 'public'),\n miss,\n )(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return cors ? withCors(cors, run) : run;\n};\n\n/**\n * The direct path, taken when a route has no middleware and no CORS. Nothing here\n * is `async`: every step looks at what it got and only allocates a promise when\n * there is genuinely something to wait for.\n *\n * The general path is `async (req) => toResponse(await handler(await read(req)))`\n * inside an `async` try/catch - four `await`s across two async frames, on values\n * that are usually not thenable at all. A route with no declared schemas awaits\n * nothing; a route with only `query` or `params` awaits nothing either, because\n * every Standard Schema validator worth using is synchronous. Even a `body` route,\n * which really does have to wait for `req.json()`, pays one promise link instead of\n * six frames.\n *\n * Worth ~6 points of throughput against raw `Bun.serve` on the `params` scenario\n * when it covered only schema-less routes, and a further ~5 on `validate` when it\n * was extended to cover reading ones - which is most of what separated dunx from\n * Elysia, whose whole trick is compiling this shape ahead of time.\n *\n * A handler or a validator that *does* return a promise still works: it is adopted\n * here rather than awaited by a wrapper.\n */\nconst directOr = (\n guarded: RouteHandler,\n route: DiscoveredRoute,\n read: InputReader,\n status: number,\n onError: ErrorMapper,\n noMiddleware: boolean,\n): ServedHandler => {\n if (!noMiddleware) return guarded;\n\n // `toResponse` throws on a value `JSON.stringify` cannot take, so it is inside\n // the mapper's reach on every branch - including the `then` callbacks, where a\n // throw would otherwise escape as an unhandled rejection instead of a 500.\n const settle = (value: unknown, req: BunRequest): Response => {\n try {\n return toResponse(value, status);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const invoke = (\n input: RouteInput,\n req: BunRequest,\n ): Response | Promise<Response> => {\n try {\n const value = route.handler(input);\n return value instanceof Promise\n ? value.then(\n (resolved) => settle(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : settle(value, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return (req) => {\n try {\n const input = read(req);\n return input instanceof Promise\n ? input.then(\n (resolved) => invoke(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : invoke(input, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n};\n\nexport const buildRoutes = (\n discovered: readonly DiscoveredRoute[],\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n resolve: GuardResolver = construct,\n): BunRoutes => {\n assertNoCollisions(discovered);\n const routes: BunRoutes = {};\n // One instance per guard class for the whole table - what the container returns,\n // and what the default resolver has to match to be interchangeable with it.\n const instances = new Map<Ctor<Middleware>, Middleware>();\n const guardOf = (guard: Ctor<Middleware>, from?: ModuleRef): Middleware => {\n const existing = instances.get(guard);\n if (existing) return existing;\n const created = resolve(guard, from);\n instances.set(guard, created);\n return created;\n };\n\n for (const route of discovered) {\n // Schemas, parsers, the status and the route context resolve here, once. What\n // survives into the request path is one closure that reads no metadata.\n const read = buildInputReader(route.options);\n const status = statusFor(route);\n /**\n * Global outermost, then the declaring module's middleware, then the controller's\n * guards, then the method's.\n *\n * There is no ancestor layer: a module's middleware applies to its own\n * controllers, so importing a module never changes the request path of the\n * importer's routes.\n */\n const chain = [\n ...middleware,\n ...(route.moduleMiddleware ?? []).map((entry) =>\n guardOf(entry, route.module),\n ),\n ...(route.guards ?? []).map((guard) => guardOf(guard, route.module)),\n ];\n const chained = compose(chain, buildContext(route), async (req) =>\n toResponse(await route.handler(await read(req)), status),\n );\n const guarded: RouteHandler = async (req) => {\n try {\n return await chained(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const byMethod = (routes[route.path] ??= {});\n // Outside the error mapper, so a mapped 500 still carries the CORS headers the\n // browser needs in order to show it.\n byMethod[route.method] = cors\n ? withCors(cors, guarded)\n : directOr(guarded, route, read, status, onError, chain.length === 0);\n }\n\n if (cors) {\n for (const byMethod of Object.values(routes)) {\n byMethod.OPTIONS = preflight(cors, Object.keys(byMethod));\n }\n }\n\n return routes;\n};\n",
26
+ "import { AppError, type Ctor, type ModuleRef } from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport type { DiscoveredRoute } from '../route/discover.js';\nimport type { HttpMethod } from '../route/marker.js';\nimport { PUBLIC, UNMATCHED, type MetaKey } from '../route/metadata.js';\nimport type { RouteInput } from '../route/schema.js';\nimport type { UpgradeHandler } from '../ws/adapter.js';\nimport { buildContext, type RouteContext } from './context.js';\nimport { preflight, withCors, type CorsOptions } from './cors.js';\nimport { defaultErrorMapper, HttpError, type ErrorMapper } from './errors.js';\nimport { buildInputReader, type InputReader } from './input.js';\nimport {\n compose,\n type Middleware,\n type RouteHandler,\n type ServedHandler,\n} from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\n/** How a `@UseGuards` class becomes an instance. `listen()` passes `app.get`. */\n/**\n * How a guard or a module's middleware becomes an instance.\n *\n * `from` names the module whose scope it resolves in - module middleware has to be\n * built from the module that declared it, or it could not inject that module's private\n * providers, which is the point of declaring it there.\n */\nexport type GuardResolver = (\n guard: Ctor<Middleware>,\n from?: ModuleRef,\n) => Middleware;\n\nconst construct: GuardResolver = (guard) =>\n new (guard as new () => Middleware)();\n\n/** `OPTIONS` is never a `@Get`-style route - only CORS mounts one. */\nexport type RouteMethod = HttpMethod | 'OPTIONS';\n\nexport type BunRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler>>\n>;\n\n/**\n * What `listen()` hands `Bun.serve`: the HTTP table plus one `GET` per gateway,\n * whose handler may answer `undefined` because the socket was upgraded.\n */\nexport type ServeRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler | UpgradeHandler>>\n>;\n\n/**\n * A `Response` passes through untouched - that is the escape hatch, and nothing\n * about it is worth second-guessing. Nothing at all is a 204: `Response.json(null)`\n * would be a body claiming to be no body.\n */\nconst toResponse = (value: unknown, status: number): Response => {\n if (value instanceof Response) return value;\n if (value === undefined || value === null) {\n return new Response(null, { status: HttpStatusCode.NO_CONTENT });\n }\n return Response.json(value, { status });\n};\n\n/** The usual rule: an explicit `status`, else 201 for POST, else 200. */\nconst statusFor = (route: DiscoveredRoute): number =>\n route.options?.status ??\n (route.method === 'POST' ? HttpStatusCode.CREATED : HttpStatusCode.OK);\n\n/**\n * Bun silently lets one route win on a collision, so a duplicate method+path is a\n * boot error naming both handlers. Run twice: once at `create()` on the discovered\n * paths, and again from `buildRoutes` at `listen()` on the final, prefixed ones.\n */\nexport const assertNoCollisions = (\n discovered: readonly DiscoveredRoute[],\n): void => {\n const owners = new Map<string, string>();\n\n for (const route of discovered) {\n const key = `${route.method} ${route.path}`;\n const owner = `${route.controller}.${route.handlerName}`;\n const existing = owners.get(key);\n\n if (existing !== undefined) {\n throw new AppError(\n `Route collision: ${key} is declared by ${existing} and by ${owner}. ` +\n 'Bun would keep only one of them.',\n );\n }\n owners.set(key, owner);\n }\n};\n\n/**\n * A gateway's upgrade is a native route like any other, so a path claimed by both a\n * controller and a gateway would lose one of them when the two tables merge.\n */\nexport const assertNoGatewayCollisions = (\n discovered: readonly DiscoveredRoute[],\n gatewayPaths: readonly string[],\n): void => {\n const gateways = new Set(gatewayPaths);\n\n for (const route of discovered) {\n if (gateways.has(route.path)) {\n throw new AppError(\n `Gateway path collision: ${route.path} is served by a gateway and by ` +\n `${route.controller}.${route.handlerName}(). The upgrade is a route too, ` +\n 'so one of them would be dropped.',\n );\n }\n }\n};\n\n/**\n * The two tables in one. A gateway's `GET` is what Bun's router matches on an\n * upgrade - the reason no `fetch` handler is needed for a socket to connect.\n */\nexport const withUpgradeRoutes = (\n routes: BunRoutes,\n gateways: ReadonlyMap<string, UpgradeHandler>,\n): ServeRoutes => {\n const merged: ServeRoutes = { ...routes };\n for (const [path, upgrade] of gateways) merged[path] = { GET: upgrade };\n return merged;\n};\n\n/**\n * The context an unmatched request gets. There is no controller and no handler,\n * and saying so is more useful to a log line than an empty string.\n *\n * A miss carries no route metadata, so a global guard reading none of it refuses,\n * which makes every 404 a 401 for an anonymous caller with no `@Public()`\n * anywhere to put. **That is deliberate and stays the default**: an unmatched\n * path answering 404 while every real path answers 401 tells a prober exactly\n * which paths exist.\n *\n * `notFound: 'public'` opts into the conventional 404 by reporting the miss as\n * public. Either way `UNMATCHED` is set, and no real route ever sets it, so a\n * guard can tell a genuinely public route from one that matched nothing.\n */\nconst unmatchedContext = (req: Request, isPublic: boolean): RouteContext =>\n Object.freeze({\n controller: '(unmatched)',\n handler: '(none)',\n method: req.method as HttpMethod,\n path: new URL(req.url).pathname,\n get: <T>(key: MetaKey<T>): T | undefined => {\n if (key.id === UNMATCHED.id) return true as T;\n if (key.id === PUBLIC.id && isPublic) return true as T;\n return undefined;\n },\n });\n\n/**\n * Bun answers an unmatched path itself, so nothing in the middleware chain ever\n * sees it - which makes a 404 invisible to request logging, metrics and tracing.\n *\n * This is the only `fetch` handler dunx installs, and it is not a router: Bun\n * still does all the matching, and this runs only once Bun has decided nothing\n * matched. It puts the global middleware in front of a 404 in the framework's\n * own error shape.\n *\n * **The miss is a `throw`, not a returned `Response`.** `miss` raises\n * `HttpError(404)` and `compose` propagates it, so a middleware written as\n * `const response = await next(); if (response.status === 404) ...` never reaches\n * its own second line on an unmatched path - the rewrite it was written for is the\n * one case it cannot see. A middleware that means to act on a miss has to catch:\n *\n * ```ts\n * try {\n * return await next();\n * } catch (error) {\n * if (!(error instanceof HttpError) || error.status !== 404) throw error;\n * return rewritten();\n * }\n * ```\n *\n * `ctx.get(UNMATCHED)` is the other half, and the cheaper one: it is set here and\n * by no real route, so a middleware can tell \"nothing matched this path\" from \"a\n * handler answered 404 for a record that does not exist\" **before** calling\n * `next()` at all. Only the second of those is a `Response` to inspect.\n *\n * Composed per request rather than at boot, because the context names the path\n * that missed. That allocation is on the 404 path only.\n */\nexport const buildFallback = (\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n notFound: 'guarded' | 'public' = 'guarded',\n): RouteHandler => {\n // The canonical status name, not a sentence naming the path back at the\n // caller: an unmatched path is the one place where echoing the request would\n // tell a prober something about the surface it just failed to find.\n const miss: RouteHandler = () => {\n throw new HttpError(HttpStatusCode.NOT_FOUND, 'NOT_FOUND');\n };\n\n const run: RouteHandler = async (req) => {\n try {\n return await compose(\n middleware,\n unmatchedContext(req, notFound === 'public'),\n miss,\n )(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return cors ? withCors(cors, run) : run;\n};\n\n/**\n * The direct path, taken when a route has no middleware and no CORS. Nothing here\n * is `async`: every step looks at what it got and only allocates a promise when\n * there is genuinely something to wait for.\n *\n * The general path is `async (req) => toResponse(await handler(await read(req)))`\n * inside an `async` try/catch - four `await`s across two async frames, on values\n * that are usually not thenable at all. A route with no declared schemas awaits\n * nothing; a route with only `query` or `params` awaits nothing either, because\n * every Standard Schema validator worth using is synchronous. Even a `body` route,\n * which really does have to wait for `req.json()`, pays one promise link instead of\n * six frames.\n *\n * Worth ~6 points of throughput against raw `Bun.serve` on the `params` scenario\n * when it covered only schema-less routes, and a further ~5 on `validate` when it\n * was extended to cover reading ones - which is most of what separated dunx from\n * Elysia, whose whole trick is compiling this shape ahead of time.\n *\n * A handler or a validator that *does* return a promise still works: it is adopted\n * here rather than awaited by a wrapper.\n */\nconst directOr = (\n guarded: RouteHandler,\n route: DiscoveredRoute,\n read: InputReader,\n status: number,\n onError: ErrorMapper,\n noMiddleware: boolean,\n): ServedHandler => {\n if (!noMiddleware) return guarded;\n\n // `toResponse` throws on a value `JSON.stringify` cannot take, so it is inside\n // the mapper's reach on every branch - including the `then` callbacks, where a\n // throw would otherwise escape as an unhandled rejection instead of a 500.\n const settle = (value: unknown, req: BunRequest): Response => {\n try {\n return toResponse(value, status);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const invoke = (\n input: RouteInput,\n req: BunRequest,\n ): Response | Promise<Response> => {\n try {\n const value = route.handler(input);\n return value instanceof Promise\n ? value.then(\n (resolved) => settle(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : settle(value, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return (req) => {\n try {\n const input = read(req);\n return input instanceof Promise\n ? input.then(\n (resolved) => invoke(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : invoke(input, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n};\n\nexport const buildRoutes = (\n discovered: readonly DiscoveredRoute[],\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n resolve: GuardResolver = construct,\n): BunRoutes => {\n assertNoCollisions(discovered);\n const routes: BunRoutes = {};\n // One instance per guard class for the whole table - what the container returns,\n // and what the default resolver has to match to be interchangeable with it.\n const instances = new Map<Ctor<Middleware>, Middleware>();\n const guardOf = (guard: Ctor<Middleware>, from?: ModuleRef): Middleware => {\n const existing = instances.get(guard);\n if (existing) return existing;\n const created = resolve(guard, from);\n instances.set(guard, created);\n return created;\n };\n\n for (const route of discovered) {\n // Schemas, parsers, the status and the route context resolve here, once. What\n // survives into the request path is one closure that reads no metadata.\n const read = buildInputReader(route.options);\n const status = statusFor(route);\n /**\n * Global outermost, then the declaring module's middleware, then the controller's\n * guards, then the method's.\n *\n * There is no ancestor layer: a module's middleware applies to its own\n * controllers, so importing a module never changes the request path of the\n * importer's routes.\n */\n const chain = [\n ...middleware,\n ...(route.moduleMiddleware ?? []).map((entry) =>\n guardOf(entry, route.module),\n ),\n ...(route.guards ?? []).map((guard) => guardOf(guard, route.module)),\n ];\n const chained = compose(chain, buildContext(route), async (req) =>\n toResponse(await route.handler(await read(req)), status),\n );\n const guarded: RouteHandler = async (req) => {\n try {\n return await chained(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const byMethod = (routes[route.path] ??= {});\n // Outside the error mapper, so a mapped 500 still carries the CORS headers the\n // browser needs in order to show it.\n byMethod[route.method] = cors\n ? withCors(cors, guarded)\n : directOr(guarded, route, read, status, onError, chain.length === 0);\n }\n\n if (cors) {\n for (const byMethod of Object.values(routes)) {\n byMethod.OPTIONS = preflight(cors, Object.keys(byMethod));\n }\n }\n\n return routes;\n};\n",
25
27
  "import type { BunRequest } from 'bun';\nimport type {\n RouteInput,\n RouteSchemas,\n StandardSchemaIssue,\n StandardSchemaResult,\n StandardSchemaV1,\n} from '../route/schema.js';\nimport {\n HttpError,\n ValidationError,\n type InputSource,\n type ValidationIssue,\n} from './errors.js';\nimport { HttpStatusCode } from './status.js';\n\n/**\n * Built once per route at boot. A route that declares nothing gets the identity\n * reader - no parse, no validation, not even a promise.\n *\n * A reader **returns a promise only when it has something to wait for**. A `body`\n * schema always does; `query` and `params` against a synchronous validator - which\n * zod, Valibot and ArkType all are - resolve without one.\n */\nexport type InputReader = (req: BunRequest) => RouteInput | Promise<RouteInput>;\n\ninterface InputDraft {\n req: BunRequest;\n body?: unknown;\n query?: unknown;\n params?: unknown;\n}\n\n/**\n * One declared schema's contribution to the draft, returning the draft so the\n * steps chain without a wrapper. A bare `InputDraft` means it finished\n * synchronously, which is the common case and the reason this is not `async`:\n * Standard Schema *permits* a promise, so awaiting unconditionally costs an async\n * frame and a microtask tick per schema for a validator that never returns one.\n */\ntype Fill = (draft: InputDraft) => InputDraft | Promise<InputDraft>;\ntype BodyParser = (req: BunRequest) => Promise<unknown>;\n\n/** What `URLSearchParams` and `FormData` both offer, and all {@link grouped} needs. */\ninterface Enumerable {\n forEach(visit: (value: unknown, key: string) => void): void;\n}\n\n/**\n * A repeated key becomes an array, so `?tag=a&tag=b` reaches the schema whole\n * instead of silently losing `a`. Shared by query strings, urlencoded bodies and\n * multipart form data.\n *\n * `forEach` rather than `for…of`: both collections implement it natively, and\n * destructuring an iterator allocates a two-element array per entry. Measured at\n * ~150 ns/request cheaper on a three-pair query string.\n */\nconst grouped = (entries: Enumerable): Record<string, unknown> => {\n const collected: Record<string, unknown> = {};\n\n entries.forEach((value, key) => {\n const existing = collected[key];\n if (existing === undefined) collected[key] = value;\n else if (Array.isArray(existing)) (existing as unknown[]).push(value);\n else collected[key] = [existing, value];\n });\n\n return collected;\n};\n\nconst asJson: BodyParser = (req) => req.json();\nconst asUrlEncoded: BodyParser = async (req) =>\n grouped(new URLSearchParams(await req.text()));\nconst asMultipart: BodyParser = async (req) => grouped(await req.formData());\nconst asText: BodyParser = (req) => req.text();\n\n/** `application/vnd.api+json` and friends parse as JSON; `text/csv` as text. */\nconst parserFor = (media: string): BodyParser | undefined => {\n if (media === 'application/json' || media.endsWith('+json')) return asJson;\n if (media === 'application/x-www-form-urlencoded') return asUrlEncoded;\n if (media === 'multipart/form-data') return asMultipart;\n if (media.startsWith('text/')) return asText;\n return undefined;\n};\n\nconst JSON_MEDIA = 'application/json';\n\n// No content-type reads as JSON: fetch omits the header for a bodyless request and\n// a 415 there would be useless, since the schema is about to reject `undefined`.\nconst mediaTypeOf = (req: BunRequest): string => {\n const header = req.headers.get('content-type');\n // The header almost every JSON client sends, verbatim - worth not slicing,\n // trimming and lowercasing on the hot path.\n if (header === JSON_MEDIA || header === null) return JSON_MEDIA;\n const end = header.indexOf(';');\n const media = (end === -1 ? header : header.slice(0, end)).trim();\n return media === '' ? JSON_MEDIA : media.toLowerCase();\n};\n\nconst flatten = (issue: StandardSchemaIssue): ValidationIssue => {\n const path = issue.path\n ?.map((segment) =>\n String(typeof segment === 'object' ? segment.key : segment),\n )\n .join('.');\n\n return path === undefined || path === ''\n ? { message: issue.message }\n : { message: issue.message, path };\n};\n\n/** A rejected schema is a 400 carrying every issue, path flattened to dots. */\nconst accept = (source: InputSource, result: StandardSchemaResult<unknown>) => {\n if (result.issues !== undefined) {\n throw new ValidationError(source, result.issues.map(flatten));\n }\n return result.value;\n};\n\n/**\n * Validates, assigns, and hands the draft back. Returning the draft rather than\n * `void` is what lets the reader be `(req) => fill({ req })`: a body route then\n * costs one promise link in total, where threading the draft back through a second\n * `then` cost two - worth ~120 ns per request, measured.\n */\nconst fillWith = (\n draft: InputDraft,\n source: InputSource,\n schema: StandardSchemaV1,\n value: unknown,\n): InputDraft | Promise<InputDraft> => {\n const result = schema['~standard'].validate(value);\n\n if (result instanceof Promise) {\n return result.then((settled) => {\n draft[source] = accept(source, settled);\n return draft;\n });\n }\n draft[source] = accept(source, result);\n return draft;\n};\n\nconst bodyFill =\n (schema: StandardSchemaV1): Fill =>\n (draft) => {\n const media = mediaTypeOf(draft.req);\n const parse = parserFor(media);\n\n if (parse === undefined) {\n throw new HttpError(\n HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,\n `Unsupported content type \"${media}\". Declared bodies accept ` +\n 'application/json, application/x-www-form-urlencoded, multipart/form-data or text/*.',\n );\n }\n\n // Both handlers on one `then`, so the parse costs a single promise link. A\n // `ValidationError` from the success handler is deliberately not visible to the\n // rejection handler - only an unreadable or mangled body is a parse failure.\n return parse(draft.req).then(\n (value) => fillWith(draft, 'body', schema, value),\n (error: unknown) => {\n // A body the caller mangled is a 400. Only an unreadable stream would be ours.\n throw new HttpError(\n HttpStatusCode.BAD_REQUEST,\n `Malformed ${media} body`,\n { cause: error },\n );\n },\n );\n };\n\n/**\n * The query string, without parsing the whole URL to reach it. `new URL(req.url)`\n * resolves scheme, host, port, path and fragment to hand back a `searchParams`, and\n * measured **~1,000 ns of the ~1,500 ns** a `query` route used to cost - more than\n * the entire body reader. `RequestLoggingMiddleware` took the same slice for the\n * same reason.\n *\n * The fragment is stripped even though a client is not supposed to send one, because\n * `new URL` stripped it and a hostile request-target should not change what a schema\n * sees.\n */\nconst searchOf = (url: string): string => {\n const start = url.indexOf('?');\n if (start === -1) return '';\n const end = url.indexOf('#', start + 1);\n return end === -1 ? url.slice(start + 1) : url.slice(start + 1, end);\n};\n\nconst queryFill =\n (schema: StandardSchemaV1): Fill =>\n (draft) => {\n const params = new URLSearchParams(searchOf(draft.req.url));\n return fillWith(draft, 'query', schema, grouped(params));\n };\n\nconst paramsFill =\n (schema: StandardSchemaV1): Fill =>\n (draft) =>\n fillWith(draft, 'params', schema, draft.req.params);\n\n/** Sequential, and stays sequential without a promise unless one is produced. */\nconst then =\n (first: Fill, second: Fill): Fill =>\n (draft) => {\n const started = first(draft);\n return started instanceof Promise ? started.then(second) : second(started);\n };\n\n/**\n * Folds the declared schemas into a single closure, the way `compose` folds\n * middleware: which parsers and validators run is decided here, at boot, so per\n * request there is no metadata to read and no branch left to take.\n */\nexport const buildInputReader = (\n options: RouteSchemas | undefined,\n): InputReader => {\n const fills: Fill[] = [];\n if (options?.body !== undefined) fills.push(bodyFill(options.body));\n if (options?.query !== undefined) fills.push(queryFill(options.query));\n if (options?.params !== undefined) fills.push(paramsFill(options.params));\n\n if (fills.length === 0) return (req) => ({ req });\n\n const fill = fills.reduce(then);\n return (req) => fill({ req });\n};\n",
26
28
  "import type { BunRequest } from 'bun';\nimport type { RouteContext } from './context.js';\n\nexport type Next = () => Promise<Response>;\n\n/**\n * The single extension point. A guard is middleware that throws, an interceptor\n * wraps `next()`, a filter is the error mapper. `ctx` names the route and carries\n * what its decorators declared, resolved at boot - so a guard costs a Map lookup.\n */\nexport interface Middleware {\n handle(req: BunRequest, ctx: RouteContext, next: Next): Promise<Response>;\n}\n\nexport type RouteHandler = (req: BunRequest) => Promise<Response>;\n\n/**\n * What goes into the `Bun.serve` route table. Wider than `RouteHandler` because\n * Bun accepts a plain `Response`, which is what lets a route with nothing to\n * await skip promises altogether - see `buildRoutes`.\n */\nexport type ServedHandler = (req: BunRequest) => Response | Promise<Response>;\n\n/** Folded into one closure per route at boot - no per-request array iteration. */\nexport const compose = (\n middleware: readonly Middleware[],\n ctx: RouteContext,\n handler: RouteHandler,\n): RouteHandler =>\n middleware.reduceRight<RouteHandler>(\n (next, current) => (req) => current.handle(req, ctx, () => next(req)),\n handler,\n );\n",
27
29
  "/**\n * The settings `app.set()` accepts. A key has to be declared here to be settable,\n * so the map is checked at compile time instead of being a string bag - a typo is\n * a type error, not a setting that silently never applies.\n */\nexport interface AppSettings {\n /**\n * Resolve the client address from `X-Forwarded-For` rather than the socket.\n *\n * The value is how many proxies sit in front of this server: `true` means one,\n * a number means that many, `false` means read the socket. The address is taken\n * that many entries from the **right**, because a direct client can send\n * whatever it likes in the header and only a proxy under your control appends\n * to it. Setting a count higher than the number of proxies you actually run\n * hands the caller its own choice of address.\n */\n 'trust proxy': boolean | number;\n}\n\nexport const defaultSettings = (): AppSettings => ({ 'trust proxy': false });\n",
28
30
  "import { join, normalize, resolve } from 'node:path';\nimport type { BunRequest } from 'bun';\nimport type { Middleware, Next } from '../server/middleware.js';\nimport type { RouteContext } from '../server/context.js';\nimport { StaticOptions } from './options.js';\n\n/**\n * Static files, on `Bun.file`.\n *\n * Nest has `ServeStaticModule` over `serve-static`, which is Express middleware\n * doing its own `stat`, its own range parsing, its own ETag and its own MIME table.\n * None of that is needed here: `Bun.file(path)` handed to a `Response` already\n * streams, already sets `content-type` from the extension, already answers a\n * `Range` request, and does the whole thing with `sendfile(2)` rather than reading\n * into JavaScript. So this file is a **path check and a cache policy**, and that is\n * the entire justification for it existing.\n *\n * A middleware rather than routes, for the same reason the dashboard is one: the\n * file set is whatever is on disk at request time, and turning it into a\n * `Bun.serve` route table would mean walking a directory at boot and being wrong\n * the moment anything changed.\n */\nexport class StaticFiles implements Middleware {\n readonly #options: StaticOptions;\n readonly #root: string;\n readonly #prefix: string;\n\n constructor(options: StaticOptions) {\n this.#options = options;\n // Resolved once. Every request is compared against this, and re-resolving per\n // request would let a `cwd` change mid-process move the root.\n this.#root = resolve(options.root);\n this.#prefix = options.path === '/' ? '/' : `${options.path}/`;\n }\n\n /**\n * The file for a request path, or `undefined` if it escapes the root.\n *\n * **The traversal check is the point of this method.** `..` segments are removed\n * by `normalize`, but that alone is not enough: a root of `/srv/app` and a\n * request for `/srv/app-secrets` both start with the same string, so the guard\n * has to compare against the root **with a separator**. Both halves have to hold\n * or a caller reads the filesystem.\n */\n resolvePath(pathname: string): string | undefined {\n const relative = pathname.startsWith(this.#prefix)\n ? pathname.slice(this.#prefix.length)\n : pathname.slice(this.#options.path.length);\n\n // Percent-encoding first: `%2e%2e%2f` is `../` and would otherwise survive\n // normalisation as an opaque segment.\n let decoded: string;\n try {\n decoded = decodeURIComponent(relative);\n } catch {\n return undefined;\n }\n // A NUL truncates a path in some syscalls; nothing legitimate contains one.\n if (decoded.includes('\\0')) return undefined;\n\n const candidate = resolve(join(this.#root, normalize(decoded)));\n if (candidate !== this.#root && !candidate.startsWith(`${this.#root}/`)) {\n return undefined;\n }\n return candidate;\n }\n\n /**\n * `cache-control` is the whole reason to serve a file rather than inline it.\n *\n * `immutable` is only honest for a **content-addressed** name - `ui.a1b2c3.js` -\n * where a change produces a different URL. For anything else it is a promise the\n * server cannot keep, so the default is a short max-age and the caller opts into\n * the long one per asset.\n */\n #cacheControl(pathname: string): string {\n const { immutable, maxAge } = this.#options;\n return immutable(pathname)\n ? 'public, max-age=31536000, immutable'\n : `public, max-age=${maxAge}`;\n }\n\n async handle(\n req: BunRequest,\n _ctx: RouteContext,\n next: Next,\n ): Promise<Response> {\n const { pathname } = new URL(req.url);\n if (pathname !== this.#options.path && !pathname.startsWith(this.#prefix)) {\n return next();\n }\n if (req.method !== 'GET' && req.method !== 'HEAD') return next();\n\n const path = this.resolvePath(pathname);\n // A traversal attempt falls through rather than answering 403: the app's own\n // 404 is the correct answer to a path that does not exist, and a distinct\n // status would confirm the root's location.\n if (path === undefined) return next();\n\n const file = Bun.file(path);\n if (!(await file.exists())) return next();\n\n return new Response(file, {\n headers: {\n 'cache-control': this.#cacheControl(pathname),\n // Bun sets content-type from the extension. Stated for anything it does\n // not know, rather than left to the browser to sniff.\n ...(file.type === ''\n ? { 'content-type': 'application/octet-stream' }\n : {}),\n 'x-content-type-options': 'nosniff',\n },\n });\n }\n}\nObject.defineProperty(StaticFiles, Symbol.for('dunx.deps'), {\n value: () => [StaticOptions],\n});\n",
29
31
  "export interface StaticOptionsInit {\n /**\n * The directory served. Resolved once, at construction, and every request is\n * checked against it - see `StaticFiles.resolvePath`.\n */\n readonly root: string;\n /**\n * The URL prefix it is served under. `/` serves from the root of the app, which\n * is the usual case for a `public/` directory.\n *\n * @default '/'\n */\n readonly path?: string;\n /**\n * `max-age` in seconds for anything `immutable` does not claim.\n *\n * Deliberately short. A long max-age on a name that can change is a promise the\n * server cannot keep, and the fix - a content hash in the filename - is the\n * thing `immutable` is for.\n *\n * @default 60\n */\n readonly maxAge?: number;\n /**\n * Which paths may be cached forever.\n *\n * Only honest for a **content-addressed** name, where a change produces a\n * different URL: `(path) => /\\.[0-9a-f]{8}\\.(js|css)$/.test(path)`. The default\n * claims nothing, because guessing wrong here is a stale asset nobody can flush.\n */\n readonly immutable?: (pathname: string) => boolean;\n}\n\n/**\n * A class, not an interface, so it is a runtime value and can therefore be a\n * constructor parameter type that `@dunx/transform` records - the same reason\n * `QueueOptions` and `RedisOptions` are classes.\n */\nexport class StaticOptions {\n readonly root: string;\n readonly path: string;\n readonly maxAge: number;\n readonly immutable: (pathname: string) => boolean;\n\n constructor(init: StaticOptionsInit) {\n this.root = init.root;\n this.path = normalizePrefix(init.path ?? '/');\n this.maxAge = init.maxAge ?? 60;\n this.immutable = init.immutable ?? (() => false);\n }\n}\nObject.defineProperty(StaticOptions, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"init: StaticOptionsInit\" }],\n});\n\n/** A leading slash and no trailing one, so `${path}/x` is never `//x`. */\nexport const normalizePrefix = (path: string): string => {\n const trimmed = path.split('/').filter(Boolean).join('/');\n return trimmed === '' ? '/' : `/${trimmed}`;\n};\n",
30
- "import {\n Module,\n provide,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type Registration,\n} from '@dunx/core';\nimport { StaticFiles } from './files.js';\nimport { StaticOptions, type StaticOptionsInit } from './options.js';\n\nconst files = (): Registration =>\n provide(StaticFiles, {\n useFactory: (options: StaticOptions) => new StaticFiles(options),\n inject: [StaticOptions] as const,\n });\n\n/**\n * Serves a directory, the way Nest's `ServeStaticModule` does - and like the\n * dashboard, **it does not register itself**. The app does:\n *\n * ```ts\n * const app = await HttpFactory.create(AppModule);\n * app.use(StaticFiles);\n * ```\n *\n * Position in the chain is the decision being left to the app. Static assets\n * usually want to be *outside* an auth guard and *inside* request logging, and no\n * default can know which. Anything outside the mount falls through untouched, so\n * the app's own routes and its 404 behave exactly as before.\n *\n * There is no `index.html` fallback and no SPA rewrite. Both are one route in the\n * app - `@Get('/*')` returning `Bun.file(...)` - and building them in would mean\n * this middleware deciding what a 404 means for paths it does not own.\n */\n@Module({})\nexport class StaticModule {\n static forRoot(init: StaticOptionsInit): DynamicModule {\n return {\n module: StaticModule,\n exports: [StaticOptions, StaticFiles],\n providers: [\n provide(StaticOptions, { useValue: new StaticOptions(init) }),\n files(),\n ],\n };\n }\n\n /** `forRoot` with the root read off the container - a config value, usually. */\n static forRootAsync<const D extends Deps>(\n config: FactoryProvider<StaticOptionsInit, D> & {\n readonly imports?: DynamicModule['imports'];\n },\n ): DynamicModule {\n return {\n module: StaticModule,\n ...(config.imports && { imports: config.imports }),\n exports: [StaticOptions, StaticFiles],\n providers: [\n provide(StaticOptions, {\n useFactory: async (...deps: readonly unknown[]) =>\n new StaticOptions(\n await (\n config.useFactory as (\n ...args: readonly unknown[]\n ) => StaticOptionsInit | Promise<StaticOptionsInit>\n )(...deps),\n ),\n inject: config.inject ?? [],\n }),\n files(),\n ],\n };\n }\n}\n",
32
+ "import {\n Module,\n provide,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type Registration,\n} from '@dunx/core';\nimport { StaticFiles } from './files.js';\nimport { StaticOptions, type StaticOptionsInit } from './options.js';\n\nconst files = (): Registration =>\n provide(StaticFiles, {\n useFactory: (options: StaticOptions) => new StaticFiles(options),\n inject: [StaticOptions] as const,\n });\n\n/**\n * Serves a directory, the way Nest's `ServeStaticModule` does - and like the\n * dashboard, **it does not register itself**. The app does:\n *\n * ```ts\n * const app = await HttpFactory.create(AppModule);\n * app.use(StaticFiles);\n * ```\n *\n * Position in the chain is the decision being left to the app. Static assets\n * usually want to be *outside* an auth guard and *inside* request logging, and no\n * default can know which. Anything outside the mount falls through untouched, so\n * the app's own routes and its 404 behave exactly as before.\n *\n * There is no `index.html` fallback and no SPA rewrite: building them in would mean\n * this middleware deciding what a 404 means for paths it does not own.\n *\n * An app that wants one writes a middleware **outside** this one, and the shape\n * matters. An unmatched path is a **thrown** `HttpError(404)`, not a returned\n * `Response` - see `buildFallback` - so reading `(await next()).status` never sees a\n * miss, and `ctx.get(UNMATCHED)` is what does:\n *\n * ```ts\n * export class SpaFallback implements Middleware {\n * async handle(req: BunRequest, ctx: RouteContext, next: Next) {\n * const missed = ctx.get(UNMATCHED) === true;\n * if (\n * !missed ||\n * req.method !== 'GET' ||\n * new URL(req.url).pathname.startsWith('/api') ||\n * !(req.headers.get('accept') ?? '').includes('text/html')\n * ) {\n * return next();\n * }\n * const index = Bun.file(`${root}/index.html`);\n * if (!(await index.exists())) return next();\n * // The document carries the hashed asset names, so a stale one points at\n * // bundles that no longer exist.\n * return new Response(index, {\n * headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' },\n * });\n * }\n * }\n * ```\n *\n * Two more things that shape where it goes in the chain. `notFound: 'guarded'` -\n * the default - reports a miss with no route metadata, so a global session guard\n * refuses it and the status is a 401 rather than a 404; an app serving a SPA wants\n * `notFound: 'public'`. And the fallback answers **before** any middleware listed\n * after the guard, so the rewrite has to sit ahead of the guard to see the miss at\n * all.\n */\n@Module({})\nexport class StaticModule {\n static forRoot(init: StaticOptionsInit): DynamicModule {\n return {\n module: StaticModule,\n exports: [StaticOptions, StaticFiles],\n providers: [\n provide(StaticOptions, { useValue: new StaticOptions(init) }),\n files(),\n ],\n };\n }\n\n /** `forRoot` with the root read off the container - a config value, usually. */\n static forRootAsync<const D extends Deps>(\n config: FactoryProvider<StaticOptionsInit, D> & {\n readonly imports?: DynamicModule['imports'];\n },\n ): DynamicModule {\n return {\n module: StaticModule,\n ...(config.imports && { imports: config.imports }),\n exports: [StaticOptions, StaticFiles],\n providers: [\n provide(StaticOptions, {\n useFactory: async (...deps: readonly unknown[]) =>\n new StaticOptions(\n await (\n config.useFactory as (\n ...args: readonly unknown[]\n ) => StaticOptionsInit | Promise<StaticOptionsInit>\n )(...deps),\n ),\n inject: config.inject ?? [],\n }),\n files(),\n ],\n };\n }\n}\n",
33
+ "import { meta, metaKey, type MetaKey } from '../route/metadata.js';\n\nexport interface ThrottleLimit {\n /** Requests allowed per window, per subject. */\n readonly limit: number;\n readonly windowSeconds: number;\n}\n\n/**\n * Read off a `RouteContext` the way `ROLES` and `PUBLIC` are, so an app can build\n * its own guard on the same metadata rather than a parallel one.\n */\nexport const THROTTLE: MetaKey<ThrottleLimit> = metaKey('throttle');\nexport const SKIP_THROTTLE: MetaKey<boolean> = metaKey('skip-throttle');\n\n/**\n * A per-route limit, replacing the module's default for this handler.\n *\n * Valid on a method or on a class. A class-level limit covers every handler in the\n * controller and a handler's own wins over it, because the route's metadata is\n * `mergeMeta(klass, handler)` - the same precedence `@Roles` has.\n */\nexport const Throttle = (limit: ThrottleLimit) => meta(THROTTLE, limit);\n\n/** Exempts a handler, or a whole controller, from the limit entirely. */\nexport const SkipThrottle = () => meta(SKIP_THROTTLE, true);\n",
34
+ "import { Logger } from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport { UNMATCHED } from '../route/metadata.js';\nimport { ClientAddress } from '../server/client-address.js';\nimport type { RouteContext } from '../server/context.js';\nimport { HttpError } from '../server/errors.js';\nimport type { Middleware, Next } from '../server/middleware.js';\nimport { HttpStatusCode } from '../server/status.js';\nimport { SKIP_THROTTLE, THROTTLE, type ThrottleLimit } from './decorators.js';\nimport { ThrottleOptions } from './options.js';\nimport { ThrottleStore } from './store.js';\n\n/**\n * A fixed-window rate limit, one key per subject and handler.\n *\n * **Fails open.** A store that cannot be reached allows the request and warns\n * **once per process** - a line per request would be its own outage, and refusing\n * every request because the counter is down turns a degraded dependency into a\n * dead service.\n *\n * **List it after any session guard.** An authenticated caller should be limited by\n * user id and an anonymous one by address, and only the guard ahead of this one\n * knows which - which is what `ThrottleOptions.subject` reads.\n *\n * The 429 is thrown, never returned, so it goes through the app's own `onError` and\n * comes out in the app's error shape like every other status.\n */\nexport class ThrottleGuard implements Middleware {\n #warned = false;\n\n constructor(\n private readonly options: ThrottleOptions,\n private readonly store: ThrottleStore,\n private readonly address: ClientAddress,\n private readonly logger: Logger,\n ) {}\n\n async handle(\n req: BunRequest,\n ctx: RouteContext,\n next: Next,\n ): Promise<Response> {\n // A path that matched nothing has no handler to limit, and counting it would\n // let a burst of 404s spend a real caller's budget - one Redis round trip per\n // miss, on the cheapest request to generate.\n if (ctx.get(UNMATCHED) === true) return next();\n if (ctx.get(SKIP_THROTTLE) === true) return next();\n\n const limit: ThrottleLimit = ctx.get(THROTTLE) ?? this.options;\n const key = this.#key(req, ctx);\n const used = await this.#hit(key, limit.windowSeconds);\n if (used === undefined) return next();\n\n if (used > limit.limit) {\n const after = (await this.#ttl(key)) ?? limit.windowSeconds;\n throw new HttpError(\n HttpStatusCode.TOO_MANY_REQUESTS,\n `Rate limit exceeded: ${limit.limit} requests per ` +\n `${limit.windowSeconds}s`,\n this.options.headers\n ? {\n headers: {\n 'retry-after': String(after),\n 'ratelimit-limit': String(limit.limit),\n 'ratelimit-remaining': '0',\n 'ratelimit-reset': String(after),\n },\n }\n : undefined,\n );\n }\n\n const response = await next();\n if (this.options.headers) {\n response.headers.set('ratelimit-limit', String(limit.limit));\n response.headers.set(\n 'ratelimit-remaining',\n String(Math.max(0, limit.limit - used)),\n );\n }\n return response;\n }\n\n /**\n * Per **handler**, not per path: two verbs on one path get their own budgets,\n * and a parameterised path does not fragment into a key per id.\n */\n #key(req: BunRequest, ctx: RouteContext): string {\n const subject =\n (this.options.subject ?? ((request) => this.address.of(request)))(\n req,\n ctx,\n ) ?? 'anonymous';\n return `${this.options.prefix}:throttle:${ctx.controller}:${ctx.handler}:${subject}`;\n }\n\n async #hit(key: string, windowSeconds: number): Promise<number | undefined> {\n try {\n return await this.store.hit(key, windowSeconds);\n } catch (error) {\n this.#degraded(error);\n return undefined;\n }\n }\n\n async #ttl(key: string): Promise<number | undefined> {\n try {\n return await this.store.ttl(key);\n } catch (error) {\n this.#degraded(error);\n return undefined;\n }\n }\n\n #degraded(error: unknown): void {\n if (this.#warned) return;\n this.#warned = true;\n this.logger.warn(\n 'The rate limiter is unreachable, so requests are not being counted.',\n { reason: (error as Error).message },\n );\n }\n}\nObject.defineProperty(ThrottleGuard, Symbol.for('dunx.deps'), {\n value: () => [ThrottleOptions, ThrottleStore, ClientAddress, Logger],\n});\n",
35
+ "import { AppError } from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport type { RouteContext } from '../server/context.js';\nimport type { ThrottleLimit } from './decorators.js';\nimport type { ThrottleStore } from './store.js';\n\nexport interface ThrottleOptionsInit extends ThrottleLimit {\n /**\n * Namespaces every key this app writes. **Required, and an empty one throws.**\n *\n * There is no default on purpose. A scaffolded app that inherits the template's\n * prefix and ships with it puts two applications in one Redis on one throttle\n * namespace, each spending the other's budget - which is exactly what happened,\n * and a friendly fallback is what let it.\n */\n readonly prefix: string;\n /**\n * Who is being limited. Defaults to the client address, or `'anonymous'` when\n * even that is unknown.\n *\n * This is an option rather than an injected caller because the identity a limit\n * counts by belongs to the app: an authenticated request is limited by user id\n * and an anonymous one by address, and only the guard ahead of this one knows\n * which. It is also what keeps `@dunx/http` from depending on `@dunx/auth`.\n *\n * ```ts\n * subject: (req) => currentUser.optional()?.id ?? address.of(req)\n * ```\n */\n readonly subject?: (req: BunRequest, ctx: RouteContext) => string | undefined;\n /**\n * Send `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`, plus\n * `Retry-After` on a 429. @default true\n */\n readonly headers?: boolean;\n /**\n * The counter. Defaults to {@link MemoryThrottleStore}, which is per process -\n * so two replicas each allow the full budget until this names a shared one.\n */\n readonly store?: ThrottleStore;\n}\n\n/**\n * A class, not an interface, so it is a runtime value and can be a constructor\n * parameter type the transform records - the same reason `StaticOptions` is one.\n */\nexport class ThrottleOptions {\n readonly limit: number;\n readonly windowSeconds: number;\n readonly prefix: string;\n readonly headers: boolean;\n readonly subject:\n | ((req: BunRequest, ctx: RouteContext) => string | undefined)\n | undefined;\n readonly store: ThrottleStore | undefined;\n\n constructor(init: ThrottleOptionsInit) {\n if (init.prefix.trim() === '') {\n throw new AppError(\n 'ThrottleModule needs a prefix naming this application, and it has no ' +\n 'default: two apps sharing one Redis with one throttle namespace each ' +\n \"spend the other's budget. Pass something like { prefix: 'orders-api' }.\",\n );\n }\n if (!Number.isInteger(init.limit) || init.limit < 1) {\n throw new AppError(\n `ThrottleModule needs a limit of at least 1; got ${init.limit}.`,\n );\n }\n if (!Number.isInteger(init.windowSeconds) || init.windowSeconds < 1) {\n throw new AppError(\n 'ThrottleModule needs a windowSeconds of at least 1; got ' +\n `${init.windowSeconds}.`,\n );\n }\n this.limit = init.limit;\n this.windowSeconds = init.windowSeconds;\n this.prefix = init.prefix;\n this.headers = init.headers ?? true;\n this.subject = init.subject;\n this.store = init.store;\n }\n}\nObject.defineProperty(ThrottleOptions, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"init: ThrottleOptionsInit\" }],\n});\n",
36
+ "import { AppError } from '@dunx/core';\n\n/**\n * The counter behind the guard.\n *\n * An `abstract class` rather than an interface: `@dunx/transform` records\n * constructor parameter *types*, so an interface at an injection site is a boot\n * error. Same reason `RedisConnection` and `Logger` are classes.\n *\n * **A fixed window, not a sliding one.** `hit` increments and returns the count for\n * the window the key is already in; the window starts at the first hit and ends\n * when the key expires. A sliding window needs a sorted set per subject and a\n * range trim per request, which is a different cost for an accuracy a rate limit\n * does not need.\n */\nexport abstract class ThrottleStore {\n constructor() {\n if (new.target === ThrottleStore) {\n throw new AppError(\n 'ThrottleStore is a contract, not an implementation. Bind one with ' +\n 'ThrottleModule.forRoot({ store: new RedisThrottleStore(redis) }), or ' +\n 'leave it out for the in-process MemoryThrottleStore.',\n );\n }\n }\n\n /**\n * The count for this key in the current window.\n *\n * **`undefined` means the store could not be reached**, and the guard reads that\n * as \"allow\". A rate limiter that turns an unreachable Redis into a 503 has\n * turned a degraded route into an outage.\n */\n abstract hit(key: string, windowSeconds: number): Promise<number | undefined>;\n\n /** Seconds left in this key's window, for `Retry-After`. */\n abstract ttl(key: string): Promise<number | undefined>;\n}\n\n/**\n * The commands the Redis store needs, restated structurally so this package keeps\n * its zero dependencies - the same trick `PubSubRelay` uses.\n *\n * `@dunx/infra`'s `RedisConnection` satisfies it, and so does a bare\n * `Bun.RedisClient`, without either being named here.\n */\nexport interface ThrottleRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n ttl(key: string): Promise<number>;\n}\n\n/**\n * The multi-process counter: one key per subject and handler.\n *\n * `INCR` then `EXPIRE`, and the `EXPIRE` **only on the call that returned 1**. That\n * is what makes the window start at the first hit rather than being pushed forward\n * by every subsequent one, and it is two round trips rather than a Lua script\n * because `Bun.RedisClient` pipelines on its own.\n */\nexport class RedisThrottleStore extends ThrottleStore {\n constructor(private readonly redis: ThrottleRedis) {\n super();\n }\n\n async hit(key: string, windowSeconds: number): Promise<number | undefined> {\n const used = await this.redis.incr(key);\n if (used === 1) await this.redis.expire(key, windowSeconds);\n return used;\n }\n\n async ttl(key: string): Promise<number | undefined> {\n // Redis answers -1 for a key with no expiry and -2 for one that is gone.\n // Neither is a duration, and reporting one as a `Retry-After` would be a\n // negative wait.\n const left = await this.redis.ttl(key);\n return left > 0 ? left : undefined;\n }\n}\nObject.defineProperty(RedisThrottleStore, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"private readonly redis: ThrottleRedis\" }],\n});\n\ninterface Window {\n count: number;\n expiresAt: number;\n}\n\n/**\n * The single-process counter, and the default - so an app with no Redis still\n * limits something rather than nothing.\n *\n * It is per process, which is the whole caveat: two replicas each allow the full\n * budget. `RedisThrottleStore` is the answer for more than one.\n *\n * The map is bounded. An expired entry is dropped when its key is next touched,\n * and once the map passes `maxKeys` every expired entry is swept - so a burst\n * across many subjects cannot grow it without limit. Reaching the cap with nothing\n * expired clears it, which resets a window early rather than holding memory a\n * server does not have.\n */\nexport class MemoryThrottleStore extends ThrottleStore {\n readonly #windows = new Map<string, Window>();\n readonly #maxKeys: number;\n\n constructor(maxKeys = 10_000) {\n super();\n this.#maxKeys = maxKeys;\n }\n\n hit(key: string, windowSeconds: number): Promise<number | undefined> {\n const now = Date.now();\n const existing = this.#windows.get(key);\n if (existing !== undefined && existing.expiresAt > now) {\n existing.count += 1;\n return Promise.resolve(existing.count);\n }\n if (this.#windows.size >= this.#maxKeys) this.#sweep(now);\n this.#windows.set(key, { count: 1, expiresAt: now + windowSeconds * 1000 });\n return Promise.resolve(1);\n }\n\n ttl(key: string): Promise<number | undefined> {\n const window = this.#windows.get(key);\n if (window === undefined) return Promise.resolve(undefined);\n const left = Math.ceil((window.expiresAt - Date.now()) / 1000);\n return Promise.resolve(left > 0 ? left : undefined);\n }\n\n #sweep(now: number): void {\n for (const [key, window] of this.#windows) {\n if (window.expiresAt <= now) this.#windows.delete(key);\n }\n if (this.#windows.size >= this.#maxKeys) this.#windows.clear();\n }\n}\nObject.defineProperty(MemoryThrottleStore, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"maxKeys = 10_000\" }],\n});\n",
37
+ "import {\n Logger,\n Module,\n provide,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type Registration,\n} from '@dunx/core';\nimport { ClientAddress } from '../server/client-address.js';\nimport { ThrottleGuard } from './guard.js';\nimport { ThrottleOptions, type ThrottleOptionsInit } from './options.js';\nimport { MemoryThrottleStore, ThrottleStore } from './store.js';\n\nconst EXPORTS = [ThrottleOptions, ThrottleStore, ThrottleGuard];\n\n/**\n * Bound with its dependencies declared rather than left to `@dunx/transform`, the\n * same choice `RedisModule` makes for `Redis`: this package's own test run has no\n * preload, and a framework provider that only resolves in a transformed app is a\n * provider that cannot be tested here.\n */\nconst guard = (): Registration =>\n provide(ThrottleGuard, {\n useFactory: (\n options: ThrottleOptions,\n store: ThrottleStore,\n address: ClientAddress,\n logger: Logger,\n ) => new ThrottleGuard(options, store, address, logger),\n inject: [ThrottleOptions, ThrottleStore, ClientAddress, Logger] as const,\n });\n\n/**\n * The store the options named, or the in-process one. Bound as a factory so the\n * default is built at boot rather than at import, and so an app that never\n * registers the module never allocates a Map.\n */\nconst store = (): Registration =>\n provide(ThrottleStore, {\n useFactory: (options: ThrottleOptions) =>\n options.store ?? new MemoryThrottleStore(),\n inject: [ThrottleOptions] as const,\n });\n\n/**\n * A first-class rate limit: the decorator, the guard, the counter and its options.\n *\n * `global: true`, because the guard is listed in `HttpOptions.middleware` - which\n * is the app's own list, resolved from wherever the class is declared - and a\n * non-global module would make every consumer import this one to reach a guard it\n * never names.\n *\n * ```ts\n * ThrottleModule.forRootAsync({\n * useFactory: (config: AppConfig, redis: RedisConnection) => ({\n * ...config.throttle,\n * prefix: config.app.name,\n * store: new RedisThrottleStore(redis),\n * subject: (req) => caller.optional()?.id ?? address.of(req),\n * }),\n * inject: [AppConfig, RedisConnection] as const,\n * });\n *\n * HttpFactory.create(AppModule, { middleware: [SessionGuard, ThrottleGuard] });\n * ```\n *\n * Position in the chain is the app's, the same decision `StaticFiles` leaves open,\n * and for a sharper reason: ahead of a session guard the limit counts every caller\n * as an address.\n */\n@Module({})\nexport class ThrottleModule {\n static forRoot(init: ThrottleOptionsInit): DynamicModule {\n return {\n module: ThrottleModule,\n global: true,\n exports: EXPORTS,\n providers: [\n provide(ThrottleOptions, { useValue: new ThrottleOptions(init) }),\n store(),\n guard(),\n ],\n };\n }\n\n /** `forRoot` with the limit read off the container - a config value, usually. */\n static forRootAsync<const D extends Deps>(\n config: FactoryProvider<ThrottleOptionsInit, D> & {\n readonly imports?: DynamicModule['imports'];\n },\n ): DynamicModule {\n return {\n module: ThrottleModule,\n global: true,\n ...(config.imports && { imports: config.imports }),\n exports: EXPORTS,\n providers: [\n provide(ThrottleOptions, {\n useFactory: async (...deps: readonly unknown[]) =>\n new ThrottleOptions(\n await (\n config.useFactory as (\n ...args: readonly unknown[]\n ) => ThrottleOptionsInit | Promise<ThrottleOptionsInit>\n )(...deps),\n ),\n inject: config.inject ?? [],\n }),\n store(),\n guard(),\n ],\n };\n }\n}\n",
31
38
  "import { HandlerKind, markGateway, markHandler } from './marker.js';\n\ntype GatewayTarget = abstract new (...args: never[]) => object;\n// never[] is what makes an arbitrary method signature assignable, so a handler\n// may declare the payload type it expects. See the README, \"Typed payloads\".\ntype HandlerMethod = (...args: never[]) => unknown;\n\nexport const Gateway =\n (path = '/') =>\n <T extends GatewayTarget>(target: T): T => {\n markGateway(target, path);\n return target;\n };\n\nconst lifecycle =\n (kind: HandlerKind) =>\n () =>\n <T extends HandlerMethod>(value: T): T => {\n markHandler(value, { kind, event: undefined });\n return value;\n };\n\n/** Runs before the socket exists. Return a `Response` to refuse the upgrade. */\nexport const OnUpgrade = lifecycle(HandlerKind.UPGRADE);\nexport const OnOpen = lifecycle(HandlerKind.OPEN);\nexport const OnClose = lifecycle(HandlerKind.CLOSE);\nexport const OnDrain = lifecycle(HandlerKind.DRAIN);\nexport const OnPing = lifecycle(HandlerKind.PING);\nexport const OnPong = lifecycle(HandlerKind.PONG);\n\n/**\n * With an event name, the handler is routed the `data` of any\n * `{\"event\":\"<name>\",\"data\":...}` frame. With none, it is the raw catch-all and\n * receives every frame no named handler claimed.\n */\nexport const OnMessage =\n (event?: string) =>\n <T extends HandlerMethod>(value: T): T => {\n markHandler(value, { kind: HandlerKind.MESSAGE, event });\n return value;\n };\n",
32
39
  "import { AppError } from '@dunx/core';\nimport type { PubSubRelay } from './relay.js';\n\n/**\n * The schemes `Bun.RedisClient` accepts. Checked here because Bun takes any string\n * and only fails later, at connect time, as an opaque `Connection closed` - which\n * an absence-tolerant relay would swallow, turning a typo into silent single-node\n * fan-out.\n */\nconst PROTOCOLS: readonly string[] = [\n 'redis:',\n 'rediss:',\n 'valkey:',\n 'valkeys:',\n 'redis+tls:',\n 'redis+unix:',\n 'redis+tls+unix:',\n];\n\n/** The same fallback chain `Bun.RedisClient` uses when given no URL. */\nexport const defaultRelayUrl = (): string =>\n process.env['VALKEY_URL'] ??\n process.env['REDIS_URL'] ??\n 'redis://localhost:6379';\n\nexport interface RedisRelayOptions {\n /** @default `$VALKEY_URL`, `$REDIS_URL`, then `redis://localhost:6379` */\n readonly url?: string;\n /**\n * Bun's reconnection budget.\n *\n * `0` by default, and that default is not a preference: a `Bun.RedisClient` that\n * never connects keeps an internal retry timer alive past `close()`, and the\n * process then never exits. A relay is exactly the connection most likely to be\n * absent - a single-node deployment with `REDIS_URL` left over from staging -\n * so the default has to be the one that lets the app boot, degrade, and still\n * exit. Raise it when Redis is a hard requirement and you want Bun to reconnect\n * for you.\n *\n * @default 0\n */\n readonly maxRetries?: number;\n /** @default 10000 */\n readonly connectionTimeout?: number;\n readonly tls?: boolean | Bun.TLSOptions;\n}\n\nconst assertUrl = (url: string): string => {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new AppError(\n `${JSON.stringify(url)} is not a valid URL for the websocket relay. ` +\n 'Expected something like redis://localhost:6379.',\n );\n }\n if (!PROTOCOLS.includes(parsed.protocol)) {\n throw new AppError(\n `Unsupported protocol ${JSON.stringify(parsed.protocol)} in ` +\n `${JSON.stringify(url)}. Expected one of ${PROTOCOLS.join(', ')}.`,\n );\n }\n return url;\n};\n\n/**\n * A {@link PubSubRelay} on `Bun.RedisClient` - a Bun global, so this costs\n * `@dunx/http` no dependency at all.\n *\n * **Two connections, not one.** A client in subscriber mode rejects every data\n * command, and throws synchronously doing it, so the subscription cannot share the\n * socket that publishes. This is the same split the socket.io Redis adapter makes\n * with its `pubClient` / `subClient`.\n *\n * Both are opened lazily, on the first call that needs them, and a failed one is\n * discarded so the next call builds a fresh connection rather than reusing a dead\n * one.\n */\nexport class RedisRelay implements PubSubRelay {\n readonly #url: string;\n readonly #options: Bun.RedisOptions;\n #pub: Bun.RedisClient | undefined;\n #sub: Bun.RedisClient | undefined;\n /** Remembered only so `close()` can leave subscriber mode. See `close()`. */\n #channel: string | undefined;\n\n constructor(options: RedisRelayOptions = {}) {\n this.#url = assertUrl(options.url ?? defaultRelayUrl());\n this.#options = {\n maxRetries: options.maxRetries ?? 0,\n ...(options.connectionTimeout !== undefined && {\n connectionTimeout: options.connectionTimeout,\n }),\n ...(options.tls !== undefined && { tls: options.tls }),\n };\n }\n\n /** The URL with any password removed, for logs and error messages. */\n get url(): string {\n const parsed = new URL(this.#url);\n if (parsed.password) parsed.password = '***';\n return parsed.toString();\n }\n\n async publish(channel: string, message: string): Promise<number> {\n const client = (this.#pub ??= new Bun.RedisClient(\n this.#url,\n this.#options,\n ));\n try {\n return await client.publish(channel, message);\n } catch (error) {\n if (this.#pub === client) {\n this.#pub = undefined;\n client.close();\n }\n throw error;\n }\n }\n\n async subscribe(\n channel: string,\n listener: (message: string) => void,\n ): Promise<void> {\n const client = (this.#sub ??= new Bun.RedisClient(\n this.#url,\n this.#options,\n ));\n try {\n // `connect()` before `subscribe()`, and that order is load-bearing too:\n // measured on Bun 1.3.14, a `subscribe()` that cannot reach the server\n // leaves the client holding the event loop open even after `close()` and\n // even with `maxRetries: 0`, so an app pointed at an absent broker would\n // never exit. Failing at `connect()` instead releases cleanly, and says\n // `Connection closed` rather than `Max reconnection attempts reached`.\n await client.connect();\n await client.subscribe(channel, listener);\n this.#channel = channel;\n } catch (error) {\n if (this.#sub === client) {\n this.#sub = undefined;\n client.close();\n }\n throw error;\n }\n }\n\n /**\n * `UNSUBSCRIBE` before `close()`, and that order is load-bearing: measured on\n * Bun 1.3.14, a `Bun.RedisClient` left in subscriber mode keeps the process\n * alive after `close()`, so an app that shut down cleanly would never exit.\n * Leaving subscriber mode first fixes it. Recorded in docs/bun-apis.md.\n */\n async close(): Promise<void> {\n const sub = this.#sub;\n const channel = this.#channel;\n this.#pub?.close();\n this.#pub = undefined;\n this.#sub = undefined;\n this.#channel = undefined;\n if (!sub) return;\n if (channel !== undefined) {\n try {\n await sub.unsubscribe(channel);\n } catch {\n // A socket that is already gone is not in subscriber mode either, and\n // throwing here would leave the connection below unclosed.\n }\n }\n sub.close();\n }\n}\nObject.defineProperty(RedisRelay, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"options: RedisRelayOptions = {}\" }],\n});\n",
33
40
  "/**\n * The state a probe reports.\n *\n * `unknown` is not `down`. A probe that timed out has told you nothing, and the\n * difference decides whether traffic is shed: `unknown` on a critical check fails\n * readiness, on a non-critical one it does not. `@dunx/dashboard` had this rule\n * first and re-exports these two from here.\n */\nexport type ProbeState = 'up' | 'down' | 'unknown';\n\nexport interface ProbeResult {\n readonly state: ProbeState;\n /** One line for the operator: a latency, a version, a failure message. */\n readonly detail?: string;\n}\n\n/**\n * One thing worth checking.\n *\n * An abstract class rather than an interface because it is an injection site: the\n * container needs a runtime value to record, and an interface there is a boot\n * error. Subclass it, or hand `HealthOptions` any object with the three members.\n */\nexport abstract class HealthIndicator {\n abstract readonly name: string;\n /**\n * Whether a failure here should shed traffic. `true` by default.\n *\n * `false` reports without gating readiness, which is what memory and disk want: a\n * disk at 91 percent is worth seeing and is not worth pulling the pod out of\n * rotation for, since no other pod is any emptier.\n */\n readonly critical: boolean = true;\n abstract check(): Promise<ProbeResult> | ProbeResult;\n}\n\n/**\n * Enough of a client to answer \"is it up\". `RedisConnection` from\n * `@dunx/infra/redis` satisfies it as written, and so does a bare\n * `Bun.RedisClient`.\n *\n * Narrower than `@dunx/dashboard`'s `RedisProbe` on purpose, and they are not\n * merged. That one also needs `connected` and `send`, because it renders an `INFO`\n * panel; this needs a round trip and nothing else. Sharing one contract would\n * oblige an app to hand a health check two members it never calls.\n */\nexport abstract class PingProbe {\n abstract ping(message?: string): Promise<string>;\n}\n\n/**\n * A database that can be asked for a round trip. `DbConnection` from\n * `@dunx/infra/db` satisfies it once it grows `ping()`.\n *\n * Separate from {@link PingProbe} because the return types differ: a Redis `PING`\n * answers `PONG` and a database round trip answers nothing worth reading.\n */\nexport abstract class QueryProbe {\n abstract ping(): Promise<void>;\n}\n",
@@ -37,7 +44,7 @@
37
44
  "import {\n Module,\n provide,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type ProviderEntry,\n} from '@dunx/core';\nimport { HealthController } from './controller.js';\nimport { Readiness, ReadinessOptions } from './readiness.js';\nimport {\n HealthOptions,\n HealthRegistry,\n type HealthOptionsInit,\n} from './registry.js';\n\nconst wiring = (\n options: readonly ProviderEntry[],\n): readonly ProviderEntry[] => [\n ...options,\n provide(ReadinessOptions, {\n useFactory: (opts: HealthOptions) =>\n new ReadinessOptions({ drainDelayMs: opts.drainDelayMs }),\n inject: [HealthOptions] as const,\n }),\n provide(Readiness, {\n useFactory: (opts: ReadinessOptions) => new Readiness(opts),\n inject: [ReadinessOptions] as const,\n }),\n provide(HealthRegistry, {\n useFactory: (opts: HealthOptions, readiness: Readiness) =>\n new HealthRegistry(opts, readiness),\n inject: [HealthOptions, Readiness] as const,\n }),\n];\n\nconst surface = [HealthOptions, HealthRegistry, Readiness];\n\n/**\n * Liveness and readiness, and the drain that makes readiness worth having.\n *\n * `Readiness` implements `OnBeforeShutdown`, so readiness starts failing **before** the\n * server stops accepting. Without that phase the flip was unexpressible: every\n * `onShutdown` hook runs after `server.stop()` has resolved, so a probe answering\n * from there answers on a closed port and the load balancer is still routing when\n * the socket goes away.\n *\n * `routes: false` binds everything and mounts nothing, for an app that would rather\n * answer on its own paths or from a sidecar.\n */\n@Module({})\nexport class HealthModule {\n static forRoot(init: HealthOptionsInit = {}): DynamicModule {\n const options = new HealthOptions(init);\n return {\n module: HealthModule,\n ...(options.routes ? { controllers: [HealthController] } : {}),\n exports: surface,\n providers: wiring([provide(HealthOptions, { useValue: options })]),\n };\n }\n\n /**\n * The same, with the indicators built from the container, which is the usual case:\n * a database indicator needs the connection.\n *\n * ```ts\n * HealthModule.forRootAsync({\n * useFactory: (db: DbConnection, redis: RedisConnection) => ({\n * readiness: [new DatabaseIndicator(db), new RedisIndicator(redis)],\n * drainDelayMs: 15_000,\n * }),\n * inject: [DbConnection, RedisConnection],\n * });\n * ```\n *\n * `routes` is read from the init here too, but the controller is mounted from the\n * static shape rather than from the awaited options: a route table is folded into\n * one closure per route when the server binds, so it cannot wait on a factory.\n * Pass `routes: false` and mount your own if that matters.\n */\n static forRootAsync<const D extends Deps>(\n config: FactoryProvider<HealthOptionsInit, D> & {\n readonly imports?: DynamicModule['imports'];\n readonly routes?: boolean;\n },\n ): DynamicModule {\n return {\n module: HealthModule,\n ...(config.imports ? { imports: config.imports } : {}),\n ...((config.routes ?? true) ? { controllers: [HealthController] } : {}),\n exports: surface,\n providers: wiring([\n provide(HealthOptions, {\n // Same cast `StaticModule.forRootAsync` makes: `Resolved<D>` is what\n // types the caller's factory, and the container hands its providers\n // through as `unknown[]`.\n useFactory: async (...deps: readonly unknown[]) =>\n new HealthOptions(\n await (\n config.useFactory as (\n ...args: readonly unknown[]\n ) => HealthOptionsInit | Promise<HealthOptionsInit>\n )(...deps),\n ),\n inject: config.inject ?? [],\n }),\n ]),\n };\n }\n}\n",
38
45
  "import type { OnBeforeShutdown } from '@dunx/core';\n\nexport interface ReadinessOptionsInit {\n /**\n * How long to keep failing readiness after the drain starts, before the server\n * stops accepting. Default `0`.\n *\n * The window exists because a load balancer notices a failing probe on its own\n * schedule: with a 2 second probe interval and a 3 failure threshold, traffic can\n * arrive for 6 seconds after the pod has decided to go. Set it to a few probe\n * intervals and the pod stops receiving before the socket closes, which is the\n * whole reason this phase runs before `server.stop()`.\n */\n readonly drainDelayMs?: number;\n}\n\n/** A class, so it is a recordable constructor parameter type. */\nexport class ReadinessOptions {\n readonly drainDelayMs: number;\n\n constructor(init: ReadinessOptionsInit = {}) {\n this.drainDelayMs = Math.max(0, init.drainDelayMs ?? 0);\n }\n}\nObject.defineProperty(ReadinessOptions, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"init: ReadinessOptionsInit = {}\" }],\n});\n\n/**\n * Whether this process wants traffic.\n *\n * Injectable, so a handler can pull the pod out of rotation for a migration and put\n * it back. `hold` and `release` are for that; `onBeforeShutdown` is for shutdown and does not\n * release.\n *\n * This is what `OnBeforeShutdown` was added to `@dunx/core` for. `HttpApplication.shutdown()`\n * stopped the server before running any hook, so a readiness flip in `onShutdown`\n * answered on a closed port, which is the wrong order: a load balancer has to see\n * the probe fail while the port is still open.\n */\nexport class Readiness implements OnBeforeShutdown {\n #reason: string | undefined;\n #draining = false;\n\n constructor(private readonly options: ReadinessOptions) {}\n\n /** `true` once shutdown has begun, or while something holds the pod out. */\n get draining(): boolean {\n return this.#draining || this.#reason !== undefined;\n }\n\n /** Why readiness is failing, for the report. */\n get reason(): string | undefined {\n return this.#draining ? (this.#reason ?? 'shutting down') : this.#reason;\n }\n\n /** Fail readiness until `release()`. Idempotent; the last reason wins. */\n hold(reason: string): void {\n this.#reason = reason;\n }\n\n release(): void {\n this.#reason = undefined;\n }\n\n /**\n * Fails readiness, then waits, all before the server stops accepting.\n *\n * The wait is here rather than in the application because this is the thing that\n * knows why it is waiting. `App.drain()` runs every hook under one `Promise.all`,\n * so this window overlaps a queue worker's own drain instead of being added to it.\n */\n async onBeforeShutdown(): Promise<void> {\n this.#draining = true;\n if (this.options.drainDelayMs > 0) {\n await Bun.sleep(this.options.drainDelayMs);\n }\n }\n}\nObject.defineProperty(Readiness, Symb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