@forinda/kickjs 10.3.1 → 10.4.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/{adapter-6fjmVVc2.d.mts → adapter-BZ1WzN1z.d.mts} +35 -5
- package/dist/{adapter-6fjmVVc2.d.mts.map → adapter-BZ1WzN1z.d.mts.map} +1 -1
- package/dist/{application-CYCvctQx.mjs → application-Bs30gJF1.mjs} +4 -4
- package/dist/application-Bs30gJF1.mjs.map +1 -0
- package/dist/{application-BuUWvaqp.d.mts → application-D5Iiy7rt.d.mts} +22 -11
- package/dist/{application-BuUWvaqp.d.mts.map → application-D5Iiy7rt.d.mts.map} +1 -1
- package/dist/{bootstrap-CfaYHbmd.mjs → bootstrap-B_sGJNSz.mjs} +3 -3
- package/dist/{bootstrap-CfaYHbmd.mjs.map → bootstrap-B_sGJNSz.mjs.map} +1 -1
- package/dist/{bounded-counters-BcA0f0bV.mjs → bounded-counters-DS-IbDW9.mjs} +2 -2
- package/dist/{bounded-counters-BcA0f0bV.mjs.map → bounded-counters-DS-IbDW9.mjs.map} +1 -1
- package/dist/{client-ip-BpauuVN_.mjs → client-ip-BLkoQTIR.mjs} +2 -2
- package/dist/{client-ip-BpauuVN_.mjs.map → client-ip-BLkoQTIR.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-DgMxtfcW.mjs → config-B6EeAw4P.mjs} +3 -3
- package/dist/{config-DgMxtfcW.mjs.map → config-B6EeAw4P.mjs.map} +1 -1
- package/dist/context-CRJzl_Mj.mjs +12 -0
- package/dist/context-CRJzl_Mj.mjs.map +1 -0
- package/dist/{context-errors-BGIOYMV5.mjs → context-errors-CR5NCXfl.mjs} +2 -2
- package/dist/{context-errors-BGIOYMV5.mjs.map → context-errors-CR5NCXfl.mjs.map} +1 -1
- package/dist/{contributor-runner-CJn1gZ8h.mjs → contributor-runner--ofCRZ0d.mjs} +3 -3
- package/dist/{contributor-runner-CJn1gZ8h.mjs.map → contributor-runner--ofCRZ0d.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/{core-YE-k8IrU.mjs → core-CsMDdzNE.mjs} +3 -3
- package/dist/{core-YE-k8IrU.mjs.map → core-CsMDdzNE.mjs.map} +1 -1
- package/dist/{csrf-ahBjt1ay.d.mts → csrf-BDAZK2mm.d.mts} +2 -2
- package/dist/{csrf-ahBjt1ay.d.mts.map → csrf-BDAZK2mm.d.mts.map} +1 -1
- package/dist/{decorate-CaEYam5J.mjs → decorate-CLeX6hbL.mjs} +3 -3
- package/dist/{decorate-CaEYam5J.mjs.map → decorate-CLeX6hbL.mjs.map} +1 -1
- package/dist/{decorators-deGmthGc.d.mts → decorators-Dvy0JZ5L.d.mts} +6 -2
- package/dist/{decorators-deGmthGc.d.mts.map → decorators-Dvy0JZ5L.d.mts.map} +1 -1
- package/dist/{define-adapter-C6H-I1og.mjs → define-adapter-RbKRSG3i.mjs} +2 -2
- package/dist/{define-adapter-C6H-I1og.mjs.map → define-adapter-RbKRSG3i.mjs.map} +1 -1
- package/dist/{di-hooks-BE0IOQk-.mjs → di-hooks-CiNaIu12.mjs} +2 -2
- package/dist/{di-hooks-BE0IOQk-.mjs.map → di-hooks-CiNaIu12.mjs.map} +1 -1
- package/dist/{disposables-Cste73oY.mjs → disposables-DYTkgNiG.mjs} +1 -1
- package/dist/{error-handler-C6JJJct_.d.mts → error-handler-CbP7hKdJ.d.mts} +7 -7
- package/dist/{error-handler-C6JJJct_.d.mts.map → error-handler-CbP7hKdJ.d.mts.map} +1 -1
- package/dist/{handler-DUyRCpPw.mjs → handler-Cw4mr3ls.mjs} +3 -3
- package/dist/{handler-DUyRCpPw.mjs.map → handler-Cw4mr3ls.mjs.map} +1 -1
- package/dist/{host-fc-YQZnN.mjs → host-H7CIkHNB.mjs} +2 -2
- package/dist/{host-fc-YQZnN.mjs.map → host-H7CIkHNB.mjs.map} +1 -1
- package/dist/http/application.d.mts +2 -2
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +1 -1
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +3 -2
- package/dist/http/middleware/csrf.mjs.map +1 -0
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.d.mts +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/{index-Dms8LzHG.d.mts → index-B4aOLoId.d.mts} +3 -3
- package/dist/{index-Dms8LzHG.d.mts.map → index-B4aOLoId.d.mts.map} +1 -1
- package/dist/{index-BfT5KZ-M.d.mts → index-Blgka75E.d.mts} +63 -4
- package/dist/index-Blgka75E.d.mts.map +1 -0
- package/dist/index.d.mts +11 -11
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/is-production-BTroGhp5.mjs +12 -0
- package/dist/is-production-BTroGhp5.mjs.map +1 -0
- package/dist/{jobs-DWi_Lwbe.mjs → jobs-xqoMmdr4.mjs} +3 -3
- package/dist/{jobs-DWi_Lwbe.mjs.map → jobs-xqoMmdr4.mjs.map} +1 -1
- package/dist/{kv-stores-BGXeNEDK.mjs → kv-stores-0-6blGzh.mjs} +3 -3
- package/dist/{kv-stores-BGXeNEDK.mjs.map → kv-stores-0-6blGzh.mjs.map} +1 -1
- package/dist/{kv-stores-BGXPKv15.d.mts → kv-stores-DXFBEYYu.d.mts} +30 -6
- package/dist/kv-stores-DXFBEYYu.d.mts.map +1 -0
- package/dist/{lazy-serve-static-Barg3__1.mjs → lazy-serve-static-D94xvah5.mjs} +2 -2
- package/dist/{lazy-serve-static-Barg3__1.mjs.map → lazy-serve-static-D94xvah5.mjs.map} +1 -1
- package/dist/{metadata-CnL9sQFa.mjs → metadata-Bm65Y-5O.mjs} +1 -1
- package/dist/{observers-BNMQ7VLb.mjs → observers-BAXkwMx0.mjs} +2 -2
- package/dist/{observers-BNMQ7VLb.mjs.map → observers-BAXkwMx0.mjs.map} +1 -1
- package/dist/query-CGyw7vNi.mjs +12 -0
- package/dist/query-CGyw7vNi.mjs.map +1 -0
- package/dist/{reply-CMRk-Jp3.mjs → reply-tlUaowib.mjs} +3 -3
- package/dist/{reply-CMRk-Jp3.mjs.map → reply-tlUaowib.mjs.map} +1 -1
- package/dist/{respond-gPELdOSi.mjs → respond-BOlh-baJ.mjs} +2 -2
- package/dist/{respond-gPELdOSi.mjs.map → respond-BOlh-baJ.mjs.map} +1 -1
- package/dist/{route-flag-8Pi83-uw.mjs → route-flag-BPSq2JCs.mjs} +3 -3
- package/dist/{route-flag-8Pi83-uw.mjs.map → route-flag-BPSq2JCs.mjs.map} +1 -1
- package/dist/{route-policy-0LAfSzo-.mjs → route-policy-DDszB6dQ.mjs} +2 -2
- package/dist/{route-policy-0LAfSzo-.mjs.map → route-policy-DDszB6dQ.mjs.map} +1 -1
- package/dist/{router-builder-obSpg-Ub.d.mts → router-builder-BewIsj7V.d.mts} +2 -2
- package/dist/{router-builder-obSpg-Ub.d.mts.map → router-builder-BewIsj7V.d.mts.map} +1 -1
- package/dist/{router-builder-D0SDqFTr.mjs → router-builder-DoaDAmK8.mjs} +3 -3
- package/dist/{router-builder-D0SDqFTr.mjs.map → router-builder-DoaDAmK8.mjs.map} +1 -1
- package/dist/{settings-BW5gVm6c.mjs → settings-CRkMOwcz.mjs} +3 -3
- package/dist/{settings-BW5gVm6c.mjs.map → settings-CRkMOwcz.mjs.map} +1 -1
- package/dist/{token-Q2c8xwJE.mjs → token-2CJq89za.mjs} +1 -1
- package/dist/{upload-CyBSlnH_.d.mts → upload-DkT2p1gd.d.mts} +3 -3
- package/dist/{upload-CyBSlnH_.d.mts.map → upload-DkT2p1gd.d.mts.map} +1 -1
- package/dist/{upload-config-D22qKth8.mjs → upload-config-Be7w0Dfx.mjs} +2 -2
- package/dist/{upload-config-D22qKth8.mjs.map → upload-config-Be7w0Dfx.mjs.map} +1 -1
- package/dist/url-for-EQsmb3yi.mjs +12 -0
- package/dist/url-for-EQsmb3yi.mjs.map +1 -0
- package/dist/web-crypto-G-m6c6w2.mjs +12 -0
- package/dist/web-crypto-G-m6c6w2.mjs.map +1 -0
- package/dist/web.d.mts +4 -4
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/application-CYCvctQx.mjs.map +0 -1
- package/dist/context-DJvuLfrx.mjs +0 -12
- package/dist/context-DJvuLfrx.mjs.map +0 -1
- package/dist/csrf-C6Em76kH.mjs +0 -12
- package/dist/csrf-C6Em76kH.mjs.map +0 -1
- package/dist/index-BfT5KZ-M.d.mts.map +0 -1
- package/dist/is-production-0lB5MU1j.mjs +0 -12
- package/dist/is-production-0lB5MU1j.mjs.map +0 -1
- package/dist/kv-stores-BGXPKv15.d.mts.map +0 -1
- package/dist/query-mXPZYtQw.mjs +0 -12
- package/dist/query-mXPZYtQw.mjs.map +0 -1
- package/dist/url-for-UZ5kJjsG.mjs +0 -12
- package/dist/url-for-UZ5kJjsG.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler-DUyRCpPw.mjs","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, type RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\n/** Edge-safe byte length — no `Buffer` on Workers. */\nconst utf8 = new TextEncoder()\n\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(stringifyJson(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n /** What `setHeader` recorded — `Set-Cookie` as its list, like node's `res.getHeader`. */\n getHeader(name: string): string | string[] | undefined {\n if (name.toLowerCase() === 'set-cookie') {\n const cookies = this.headers.getSetCookie()\n return cookies.length > 0 ? cookies : undefined\n }\n return this.headers.get(name) ?? undefined\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n // A buffered body has a known length: say so, as the node runtimes do —\n // no chunked encoding for a small reply, and middleware that decides by\n // size (compression's threshold) can see it.\n if (bodyAllowed && body != null && !this.headers.has('content-length')) {\n const length = typeof body === 'string' ? utf8.encode(body).byteLength : body.byteLength\n this.headers.set('content-length', String(length))\n }\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n","// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n parseForm,\n readBodyText,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n const form = await request.formData().catch(() => undefined)\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields[name] = value\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n req.body = fields\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n if (!driver.settled) {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n"],"mappings":";;;;;;;;;;4jBAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,aAAa,KAAK,EAAG,CACzC,IAAM,IAAM,IAAI,aAAa,OAAO,GAAG,E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M,CAC7C,CAAC,EACG,CAAC,UAAY,OAAO,QAAS,MACnC,CAGA,GADI,MAAM,mBAAmB,MAAM,MAAM,kBAAkB,GAAG,EAC1D,OAAO,QAAS,OACpB,IAAM,OAAS,MAAM,MAAM,QAAQ,GAAG,EAGjC,OAAO,SAAS,MAAM,mBAAmB,IAAK,MAAM,CAC3D,CAAC,EAED,GAAI,CAGF,GAAI,CACF,MAAM,QAAQ,KAAK,CAAC,SAAU,OAAO,KAAK,CAAC,CAC7C,OAAS,IAAK,CACP,OAAO,UACN,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAK,IAAK,MAAM,EACnD,OAAO,SAAS,MAAM,aAAa,IAAK,IAAK,OAAQ,SAAS,EAEvE,CAKA,OAJK,OAAO,SAEV,gBAAgB,IAAK,OAAQ,SAAS,EAEjC,MAAM,OAAO,KACtB,QAAU,CAIR,QAAa,QAAQ,QAAQ,CAAC,CAC3B,UAAY,CAAC,CAAC,CAAC,CACf,SAAW,oBAAoB,KAAK,CAAC,CAC1C,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"handler-Cw4mr3ls.mjs","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, type RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\n/** Edge-safe byte length — no `Buffer` on Workers. */\nconst utf8 = new TextEncoder()\n\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(stringifyJson(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n /** What `setHeader` recorded — `Set-Cookie` as its list, like node's `res.getHeader`. */\n getHeader(name: string): string | string[] | undefined {\n if (name.toLowerCase() === 'set-cookie') {\n const cookies = this.headers.getSetCookie()\n return cookies.length > 0 ? cookies : undefined\n }\n return this.headers.get(name) ?? undefined\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n // A buffered body has a known length: say so, as the node runtimes do —\n // no chunked encoding for a small reply, and middleware that decides by\n // size (compression's threshold) can see it.\n if (bodyAllowed && body != null && !this.headers.has('content-length')) {\n const length = typeof body === 'string' ? utf8.encode(body).byteLength : body.byteLength\n this.headers.set('content-length', String(length))\n }\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n","// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n parseForm,\n readBodyText,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n const form = await request.formData().catch(() => undefined)\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields[name] = value\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n req.body = fields\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n if (!driver.settled) {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n"],"mappings":";;;;;;;;;;4jBAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,aAAa,KAAK,E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,QAAQ,CACf,CAC4B,CAAC,CAAC,CAAC,MAAM,MAAM,CAC7C,CAAC,EACG,CAAC,UAAY,OAAO,QAAS,MACnC,CAGA,GADI,MAAM,mBAAmB,MAAM,MAAM,kBAAkB,GAAG,EAC1D,OAAO,QAAS,OACpB,IAAM,OAAS,MAAM,MAAM,QAAQ,GAAG,EAGjC,OAAO,SAAS,MAAM,mBAAmB,IAAK,MAAM,CAC3D,CAAC,EAED,GAAI,CAGF,GAAI,CACF,MAAM,QAAQ,KAAK,CAAC,SAAU,OAAO,KAAK,CAAC,CAC7C,OAAS,IAAK,CACP,OAAO,UACN,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAK,IAAK,MAAM,EACnD,OAAO,SAAS,MAAM,aAAa,IAAK,IAAK,OAAQ,SAAS,EAEvE,CAKA,OAJK,OAAO,SAEV,gBAAgB,IAAK,OAAQ,SAAS,EAEjC,MAAM,OAAO,KACtB,QAAU,CAIR,QAAa,QAAQ,QAAQ,CAAC,CAC3B,UAAY,CAAC,CAAC,CAAC,CACf,SAAW,oBAAoB,KAAK,CAAC,CAC1C,CACF,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function parseHttpUrl(value){try{let url=new URL(value);return url.protocol===`http:`||url.protocol===`https:`?url:void 0}catch{return}}const HOST_GRAMMAR=/^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::\d{1,5})?$/;function canonicalHost(host,protocol){if(host&&HOST_GRAMMAR.test(host))return parseHttpUrl(`${protocol}//${host}`)?.host}export{canonicalHost as n,parseHttpUrl as r,HOST_GRAMMAR as t};
|
|
12
|
-
//# sourceMappingURL=host-
|
|
12
|
+
//# sourceMappingURL=host-H7CIkHNB.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-
|
|
1
|
+
{"version":3,"file":"host-H7CIkHNB.mjs","names":[],"sources":["../src/http/host.ts"],"sourcesContent":["/**\n * Host header parsing shared by the middleware that trusts it (CSRF origin\n * check, allowed hosts). One grammar and one canonical form, so two checks\n * never disagree about what host a request named.\n *\n * @module @forinda/kickjs/http/host\n */\n\n/** An http(s) URL, or undefined for anything else (`null`, `file:`, garbage). */\nexport function parseHttpUrl(value: string): URL | undefined {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * RFC 9110 `Host`: a hostname or bracketed IPv6 literal, optional port. Checked\n * before parsing, so the URL parser never sees userinfo, a path or whitespace —\n * `x@a.test` would otherwise parse to the host `a.test`.\n */\nexport const HOST_GRAMMAR = /^(?:[A-Za-z0-9.-]+|\\[[0-9A-Fa-f:.]+\\])(?::\\d{1,5})?$/\n\n/**\n * The request's host, canonicalized the way `URL` canonicalizes the origin it\n * is compared with (case, IDN, default port for that scheme) — comparing two\n * strings parsed by different rules is how checks like this get bypassed.\n */\nexport function canonicalHost(host: string | undefined, protocol: string): string | undefined {\n if (!host || !HOST_GRAMMAR.test(host)) return undefined\n return parseHttpUrl(`${protocol}//${host}`)?.host\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,aAAa,MAAgC,CAC3D,GAAI,CACF,IAAM,IAAM,IAAI,IAAI,KAAK,EACzB,OAAO,IAAI,WAAa,SAAW,IAAI,WAAa,SAAW,IAAM,IAAA,EACvE,MAAQ,CACN,MACF,CACF,CAOA,MAAa,aAAe,uDAO5B,SAAgB,cAAc,KAA0B,SAAsC,CAC5F,GAAK,MAAS,aAAa,KAAK,IAAI,EACpC,OAAO,aAAa,GAAG,SAAS,IAAI,MAAM,CAAC,EAAE,IAC/C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as
|
|
3
|
-
export { Application, ApplicationOptions, ConfigDescription, ConfigOrigins, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions };
|
|
2
|
+
import { a as ConfigOrigins, c as ServerOptions, i as ConfigDescription, l as ShutdownOptions, n as Application, o as MiddlewareEntry, r as ApplicationOptions, s as MountedRouteInfo, t as APPLICATION } from "../application-D5Iiy7rt.mjs";
|
|
3
|
+
export { APPLICATION, Application, ApplicationOptions, ConfigDescription, ConfigOrigins, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
export{t as Application}from"../application-
|
|
11
|
+
export{t as APPLICATION,n as Application}from"../application-Bs30gJF1.mjs";
|
package/dist/http/bootstrap.mjs
CHANGED
package/dist/http/context.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as SseHandler, D as DeepReadonly, E as Ctx, O as RequestContext, j as contentDisposition, k as RouteShape } from "../adapter-
|
|
2
|
+
import { A as SseHandler, D as DeepReadonly, E as Ctx, O as RequestContext, j as contentDisposition, k as RouteShape } from "../adapter-BZ1WzN1z.mjs";
|
|
3
3
|
import { b as ContextMeta } from "../app-module-Cuu-Ma_E.mjs";
|
|
4
4
|
export { type ContextMeta, Ctx, DeepReadonly, RequestContext, RouteShape, SseHandler, contentDisposition };
|
package/dist/http/context.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
export{t as RequestContext,n as contentDisposition}from"../context-
|
|
11
|
+
export{t as RequestContext,n as contentDisposition}from"../context-CRJzl_Mj.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{r as parseHttpUrl,t as HOST_GRAMMAR}from"../../host-
|
|
11
|
+
import{r as parseHttpUrl,t as HOST_GRAMMAR}from"../../host-H7CIkHNB.mjs";import{n as resolvePathname}from"../../client-ip-BLkoQTIR.mjs";import{i as sendJson}from"../../respond-BOlh-baJ.mjs";function headerOf(headers,name){let value=headers[name];return Array.isArray(value)?value[0]:value}function hostnameOf(host){if(host&&HOST_GRAMMAR.test(host))return parseHttpUrl(`http://${host}`)?.hostname}function compile(patterns){if(patterns.length===0)throw Error(`allowedHosts(): list at least one host`);if(patterns.includes(`*`))return()=>!0;let exact=/* @__PURE__ */ new Set,suffixes=[];for(let pattern of patterns){let wildcard=pattern.startsWith(`.`),hostname=hostnameOf(wildcard?pattern.slice(1):pattern);if(!hostname)throw Error(`allowedHosts(): '${pattern}' is not a host name`);wildcard?suffixes.push(hostname):exact.add(hostname)}return hostname=>exact.has(hostname)||suffixes.some(s=>hostname===s||hostname.endsWith(`.${s}`))}const REJECTED={type:`about:blank`,title:`Bad Request`,status:400,detail:`This host is not served here.`};function allowedHosts(options){let{hosts,trustForwardedHost=!1,ignorePaths=[]}=Array.isArray(options)?{hosts:options}:options,allowed=compile(hosts),ignored=new Set(ignorePaths);return(req,res,next)=>{let headers=req.headers,forwardedHeader=headerOf(headers,`x-forwarded-host`),candidates;if(trustForwardedHost&&forwardedHeader!==void 0?candidates=forwardedHeader.split(`,`).map(h=>h.trim()):(forwardedHeader!==void 0&&delete headers[`x-forwarded-host`],candidates=[headerOf(headers,`host`)??headerOf(headers,`:authority`)]),candidates.every(host=>{let hostname=hostnameOf(host);return hostname!==void 0&&allowed(hostname)}))return next();let method=req.method?.toUpperCase();if(ignored.size>0&&(method===`GET`||method===`HEAD`)&&ignored.has(resolvePathname(req)))return next();res.setHeader(`content-type`,`application/problem+json`),sendJson(res,400,REJECTED)}}export{allowedHosts};
|
|
12
12
|
//# sourceMappingURL=allowed-hosts.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as isAllowedOrigin, i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "../../csrf-
|
|
2
|
+
import { a as isAllowedOrigin, i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "../../csrf-BDAZK2mm.mjs";
|
|
3
3
|
export { CsrfGuardOptions, CsrfOptions, csrf, csrfGuard, isAllowedOrigin };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
|
|
11
|
+
import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-BPSq2JCs.mjs";import{t as isProduction}from"../../is-production-BTroGhp5.mjs";import{n as randomHex,r as safeEqual}from"../../web-crypto-G-m6c6w2.mjs";import{n as canonicalHost,r as parseHttpUrl}from"../../host-H7CIkHNB.mjs";import{n as resolvePathname}from"../../client-ip-BLkoQTIR.mjs";import{a as setCookie,i as sendJson,n as readCookies}from"../../respond-BOlh-baJ.mjs";function headerOf(headers,name){let value=headers[name];return Array.isArray(value)?value[0]:value}function originOfUrl(url){if(url)try{return new URL(url).origin}catch{return}}function isAllowedOrigin(headers,trusted){let site=headerOf(headers,`sec-fetch-site`);if(site===`same-origin`)return!0;let declared=headerOf(headers,`origin`)??originOfUrl(headerOf(headers,`referer`));if(declared===void 0)return site===void 0||site===`none`;let origin=parseHttpUrl(declared);if(!origin)return!1;if(trusted.has(origin.origin))return!0;let host=canonicalHost(headerOf(headers,`host`)??headerOf(headers,`:authority`),origin.protocol);return host!==void 0&&host===origin.host}function trustedSet(origins){return new Set((origins??[]).map(o=>{let url=parseHttpUrl(o);if(!url||url.pathname!==`/`||url.search||url.hash||url.username||url.password)throw Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`);return url.origin}))}const ORIGIN_REJECTED={message:`CSRF origin not allowed`};function csrf(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(req,res,next)=>{let token=readCookies(req)[cookieName];if(token||(token=randomHex(tokenLength),setCookie(res,cookieName,token,cookieOpts)),!protectedMethods.has(req.method.toUpperCase())||ignorePaths.has(resolvePathname(req)))return next();if(checkOrigin&&!isAllowedOrigin(req.headers,trusted))return sendJson(res,403,ORIGIN_REJECTED);let headerToken=req.headers[headerName];if(typeof headerToken!=`string`||!safeEqual(headerToken,token))return sendJson(res,403,{message:`CSRF token mismatch`});next()}}function csrfGuard(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`csrfGuard({ exemptWhen })`);let checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(ctx,next)=>{let token=readCookies(ctx.req)[cookieName];token||(token=randomHex(tokenLength),setCookie(ctx.res,cookieName,token,cookieOpts));let method=ctx.route?.method??ctx.req.method??`GET`;if(!protectedMethods.has(method.toUpperCase())||exemptWhen!==void 0&&matchesFlagTest(exemptWhen,ctx.route?.flags,ctx.route)||ignorePaths.has(resolvePathname(ctx.req)))return next();if(checkOrigin&&!isAllowedOrigin(ctx.headers,trusted)){ctx.json(ORIGIN_REJECTED,403);return}let headerToken=ctx.headers[headerName];typeof headerToken!=`string`||!safeEqual(headerToken,token)?ctx.json({message:`CSRF token mismatch`},403):next()}}export{csrf,csrfGuard,isAllowedOrigin};
|
|
12
|
+
//# sourceMappingURL=csrf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csrf.mjs","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"sourcesContent":["import { readCookies, sendJson, setCookie } from './respond'\nimport type { Request, Response, NextFunction } from 'express'\nimport { resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { randomHex, safeEqual } from '../../core/web-crypto'\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport { isProduction } from '../../core/is-production'\nimport { canonicalHost, parseHttpUrl } from '../host'\n\nexport interface CsrfOptions {\n /** Cookie name for the CSRF token (default: '_csrf') */\n cookie?: string\n /** Header name to check for the token (default: 'x-csrf-token') */\n header?: string\n /** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */\n methods?: string[]\n /** Paths to exclude from CSRF checks (e.g. webhooks) */\n ignorePaths?: string[]\n /** Token byte length before hex encoding (default: 32 = 64 hex chars) */\n tokenLength?: number\n /**\n * Origins, besides the request's own host, allowed to send state-changing\n * requests — e.g. `['https://app.example.com']` when the frontend lives on\n * another subdomain. Compared against the `Origin` (or `Referer`) header.\n */\n trustedOrigins?: string[]\n /**\n * Check where an unsafe request came from before the token (default `true`).\n * `Sec-Fetch-Site: same-origin` passes; otherwise the `Origin` (or `Referer`)\n * must match the request's `Host` or a {@link trustedOrigins} entry, and a\n * browser request that says it is cross-site with neither is refused. A\n * request with no such headers at all (a server, curl) goes on to the token\n * check. Turn off only behind a proxy that rewrites `Host` and when you\n * cannot list the origins.\n */\n checkOrigin?: boolean\n /** Cookie options */\n cookieOptions?: {\n /**\n * Default `false`, because double-submit CSRF needs the page to read the\n * token and echo it in a header. Set `true` only if the client receives\n * the token another way — server-rendered, or from your own endpoint.\n */\n httpOnly?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n secure?: boolean\n path?: string\n }\n}\n\ntype HeaderBag = Record<string, string | string[] | undefined>\n\nfunction headerOf(headers: HeaderBag, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value[0] : value\n}\n\n/** `scheme://host[:port]` of a URL, or undefined when it doesn't parse. */\nfunction originOfUrl(url: string | undefined): string | undefined {\n if (!url) return undefined\n try {\n return new URL(url).origin\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether an unsafe request came from somewhere allowed to send it — the\n * origin half of CSRF protection, ahead of the token. The token alone (double\n * submit) can be planted by a sibling subdomain that sets cookies on the\n * parent domain; the browser's own origin headers cannot.\n */\nexport function isAllowedOrigin(headers: HeaderBag, trusted: ReadonlySet<string>): boolean {\n const site = headerOf(headers, 'sec-fetch-site')\n if (site === 'same-origin') return true\n\n const declared = headerOf(headers, 'origin') ?? originOfUrl(headerOf(headers, 'referer'))\n if (declared === undefined) {\n // No browser origin headers: not a browser cross-site request (or a very\n // old browser). Left to the token. A browser that says cross-site or\n // same-site but sends no origin is refused.\n return site === undefined || site === 'none'\n }\n // `Origin: null` (sandboxed frames, some redirects) and non-http schemes\n // don't parse: refused.\n const origin = parseHttpUrl(declared)\n if (!origin) return false\n if (trusted.has(origin.origin)) return true\n // The scheme is not compared: behind a TLS-terminating proxy the app cannot\n // know it reliably. The host (with port) is what an attacker cannot match.\n // HTTP/2 carries it as `:authority`.\n const host = canonicalHost(\n headerOf(headers, 'host') ?? headerOf(headers, ':authority'),\n origin.protocol,\n )\n return host !== undefined && host === origin.host\n}\n\nfunction trustedSet(origins: string[] | undefined): Set<string> {\n return new Set(\n (origins ?? []).map((o) => {\n const url = parseHttpUrl(o)\n // An origin is scheme + host + port: a path, query or credentials here\n // means the entry was meant as something else.\n if (!url || url.pathname !== '/' || url.search || url.hash || url.username || url.password) {\n throw new Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`)\n }\n return url.origin\n }),\n )\n}\n\nconst ORIGIN_REJECTED = { message: 'CSRF origin not allowed' }\n\n/**\n * Double-submit cookie CSRF protection middleware.\n *\n * On every request, sets a CSRF token cookie. For state-changing methods\n * (POST, PUT, PATCH, DELETE), validates that the request header matches\n * the cookie value.\n *\n * @example\n * ```ts\n * import { csrf } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * cookieParser(),\n * csrf(),\n * // ... other middleware\n * ],\n * })\n * ```\n *\n * Client usage:\n * 1. Read the `_csrf` cookie value\n * 2. Send it in the `x-csrf-token` header on every mutating request\n */\nexport function csrf(options: CsrfOptions = {}) {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // `false`, not `true`: double-submit CSRF requires the PAGE to read this\n // cookie and echo it in a header. Under `httpOnly: true` `document.cookie`\n // returns nothing, no header is sent, and every mutating request answers\n // 403 — the documented client flow could not work. The token is not a\n // credential; a token an attacker cannot read is also one your own page\n // cannot send. Set `cookieOptions: { httpOnly: true }` only when the token\n // reaches the client some other way (server-rendered, or your own endpoint).\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Generate or reuse CSRF token\n // NOT `req.cookies` alone: that is populated only by an upstream parser,\n // which Fastify and h3 never have and Express only has if the app mounts\n // one. Without this the middleware never saw the token it had just issued.\n const cookies = readCookies(req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(res, cookieName, token, cookieOpts)\n }\n\n // Skip validation for safe methods and ignored paths\n if (!protectedMethods.has(req.method.toUpperCase())) {\n return next()\n }\n\n // `req.path` is Express-only, so `has(undefined)` never matched and\n // configured exemptions were silently ignored on Fastify / h3.\n if (ignorePaths.has(resolvePathname(req as ClientRequestLike))) {\n return next()\n }\n\n if (checkOrigin && !isAllowedOrigin(req.headers as HeaderBag, trusted)) {\n return sendJson(res, 403, ORIGIN_REJECTED)\n }\n\n // Validate: header token must match cookie token\n const headerToken = req.headers[headerName] as string | undefined\n\n if (typeof headerToken !== 'string' || !safeEqual(headerToken, token)) {\n return sendJson(res, 403, {\n message: 'CSRF token mismatch',\n })\n }\n\n next()\n }\n}\n\nexport interface CsrfGuardOptions extends CsrfOptions {\n /**\n * Skip the token check on routes carrying a route flag — a name, a list of\n * names (any-of), or a predicate.\n *\n * This is the reason the guard exists. `csrf()` runs before route matching,\n * so its only handle on \"not this endpoint\" is {@link CsrfOptions.ignorePaths}\n * — an exact pathname string that cannot express `/webhooks/:provider` and\n * keeps parsing after an `apiPrefix` change that voids it. A flag is declared\n * on the route itself:\n *\n * ```ts\n * const CsrfExempt = defineRouteFlag('csrf.exempt')\n *\n * @CsrfExempt\n * @Controller()\n * class WebhooksController {\n * @Post('/:provider') receive(ctx: RequestContext) {}\n * }\n * ```\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Double-submit cookie CSRF protection as a `(ctx, next)` middleware.\n *\n * The ctx-style counterpart of {@link csrf}: it runs inside the matched route,\n * so it can read `ctx.route.flags` and be exempted per route, and it works on\n * every runtime including the `@forinda/kickjs/web` fetch entry.\n *\n * ```ts\n * // per controller — the flag-aware form\n * @Middleware(csrfGuard({ exemptWhen: 'csrf.exempt' }))\n * @Controller()\n * class BillingController {}\n *\n * // edge, app-wide\n * createWebApp({ h3, modules, middleware: [csrfGuard()] })\n * ```\n *\n * Mount `csrf()` instead when you want one app-wide connect middleware that\n * also covers requests matching no route — nothing to exempt, nothing to read.\n */\nexport function csrfGuard(options: CsrfGuardOptions = {}): MiddlewareHandler {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'csrfGuard({ exemptWhen })')\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // Same default as `csrf()` above, and for the same reason.\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (ctx: RequestContext, next: () => void): void => {\n const cookies = readCookies(ctx.req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(ctx.res, cookieName, token, cookieOpts)\n }\n\n // Safe methods only ever issue the token.\n const method = ctx.route?.method ?? (ctx.req as { method?: string }).method ?? 'GET'\n if (!protectedMethods.has(method.toUpperCase())) return next()\n\n // Flag first: it is the declared exemption, and cheaper than the path set.\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n if (ignorePaths.has(resolvePathname(ctx.req as unknown as ClientRequestLike))) return next()\n\n if (checkOrigin && !isAllowedOrigin(ctx.headers as HeaderBag, trusted)) {\n ctx.json(ORIGIN_REJECTED, 403)\n return\n }\n\n const headerToken = ctx.headers[headerName] as string | undefined\n if (typeof headerToken !== 'string' || !safeEqual(headerToken, token)) {\n ctx.json({ message: 'CSRF token mismatch' }, 403)\n return\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;4bAsDA,SAAS,SAAS,QAAoB,KAAkC,CACtE,IAAM,MAAQ,QAAQ,MACtB,OAAO,MAAM,QAAQ,KAAK,EAAI,MAAM,GAAK,KAC3C,CAGA,SAAS,YAAY,IAA6C,CAChE,GAAK,IACL,GAAI,CACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC,MACtB,MAAQ,CACN,MACF,CACF,CAQA,SAAgB,gBAAgB,QAAoB,QAAuC,CACzF,IAAM,KAAO,SAAS,QAAS,gBAAgB,EAC/C,GAAI,OAAS,cAAe,MAAO,GAEnC,IAAM,SAAW,SAAS,QAAS,QAAQ,GAAK,YAAY,SAAS,QAAS,SAAS,CAAC,EACxF,GAAI,WAAa,IAAA,GAIf,OAAO,OAAS,IAAA,IAAa,OAAS,OAIxC,IAAM,OAAS,aAAa,QAAQ,EACpC,GAAI,CAAC,OAAQ,MAAO,GACpB,GAAI,QAAQ,IAAI,OAAO,MAAM,EAAG,MAAO,GAIvC,IAAM,KAAO,cACX,SAAS,QAAS,MAAM,GAAK,SAAS,QAAS,YAAY,EAC3D,OAAO,QACT,EACA,OAAO,OAAS,IAAA,IAAa,OAAS,OAAO,IAC/C,CAEA,SAAS,WAAW,QAA4C,CAC9D,OAAO,IAAI,KACR,SAAW,CAAC,EAAA,CAAG,IAAK,GAAM,CACzB,IAAM,IA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andler, r as notFoundHandler, t as MountedRoute } from "../../error-handler-CbP7hKdJ.mjs";
|
|
3
3
|
export { MountedRoute, errorHandler, notFoundHandler };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger,describeError}from"../../core/logger.mjs";import{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{t as isProduction}from"../../is-production-
|
|
11
|
+
import{createLogger,describeError}from"../../core/logger.mjs";import{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{t as isProduction}from"../../is-production-BTroGhp5.mjs";const log=createLogger(`ErrorHandler`);function patternToRegExp(pattern){let source=pattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\/:[^/]+/g,`/[^/]+`).replace(/\*/g,`.*`);return RegExp(`^${source}/?$`)}function pathOf(req){let url=req.originalUrl??req.url??`/`,cut=url.search(/[?#]/);return cut===-1?url:url.slice(0,cut)}function notFoundHandler(routes=[]){let matchers=routes.map(route=>({method:route.method.toUpperCase(),matches:patternToRegExp(route.path)}));return(req,res,_next)=>{let path=pathOf(req),method=(req.method??`GET`).toUpperCase(),allowed=[...new Set(matchers.filter(m=>m.matches.test(path)).map(m=>m.method))];if(allowed.length>0&&!allowed.includes(method)){let verbs=allowed.toSorted().join(`, `);return res.setHeader(`Allow`,verbs),res.setHeader(`Content-Type`,`application/problem+json`),res.status(405).json(normalizeProblem({status:405,detail:`${method} is not supported for this resource. Allowed: ${verbs}.`}))}return res.setHeader(`Content-Type`,`application/problem+json`),res.status(404).json(normalizeProblem({status:404}))}}function fieldErrors(details){if(Array.isArray(details)&&details.length!==0)return details.every(d=>typeof d?.field==`string`&&typeof d?.message==`string`)?details.map(d=>({field:d.field,message:d.message})):void 0}function errorHandler(){return(err,req,res,_next)=>{let isProduction$1=isProduction();if(res.headersSent){log.warn(`Error after headers sent: ${err?.message||`Unknown`}`);return}if(err instanceof ProblemException){if(err.problem.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let body=normalizeProblem(err.problem);return res.setHeader(`Content-Type`,`application/problem+json`),res.status(body.status).json(body)}if(err?.name===`ZodError`){let firstIssue=err.issues?.[0];return res.status(422).json({message:firstIssue?.message||`Validation failed`,...isProduction$1?{}:{errors:err.issues}})}if(err instanceof HttpException){if(err.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let errors=isProduction$1?err.status===422?fieldErrors(err.details):void 0:err.details;return res.setHeader(`Content-Type`,`application/problem+json`),res.status(err.status).json(normalizeProblem({status:err.status,detail:err.message,...errors===void 0?{}:{errors}}))}let requestId=req.requestId??req.headers[`x-request-id`],declared=Number(err.status??err.statusCode);if(Number.isInteger(declared)&&declared>=400&&declared<500)return log.warn(`${req.method} ${req.originalUrl??req.url} — ${declared} ${describeError(err)}`),res.setHeader(`Content-Type`,`application/problem+json`),res.status(declared).json(normalizeProblem({status:declared,detail:err.message||void 0,...requestId?{requestId}:{}}));let status=Number.isInteger(declared)&&declared>=500&&declared<600?declared:500;log.error(err,`${req.method} ${req.originalUrl??req.url} — ${describeError(err)}${requestId?` [${requestId}]`:``}`),res.status(status).json({message:`Internal Server Error`,...requestId?{requestId}:{},...isProduction$1?{}:{error:describeError(err),...typeof err?.stack==`string`?{stack:err.stack.split(`
|
|
12
12
|
`)}:{}}})}}export{errorHandler,notFoundHandler};
|
|
13
13
|
//# sourceMappingURL=error-handler.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.mjs","names":["isProduction","isProductionEnv"],"sources":["../../../src/http/middleware/error-handler.ts"],"sourcesContent":["import type { RuntimeResponse } from '../runtime'\n\n/**\n * The slice of the request this handler reads, spelled from node's\n * `IncomingMessage` rather than Express's `Request`.\n *\n * Fastify and h3 hand the error handler `request.raw` — a plain\n * `IncomingMessage` — so anything Express-only is `undefined` there. This is\n * the default handler for EVERY runtime, so it must not assume Express.\n */\ninterface ErrorRequest {\n method?: string\n url?: string\n /** Express-only; absent on the raw node request the other runtimes pass. */\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n}\n// Module paths, not the core barrel: the web entry (edge runtimes) uses these\n// handlers too, and the barrel reaches node-only modules.\nimport { HttpException, ProblemException, normalizeProblem } from '../../core/errors'\nimport { createLogger, describeError } from '../../core/logger'\nimport { isProduction as isProductionEnv } from '../../core/is-production'\n\nconst log = createLogger('ErrorHandler')\n\n/** A mounted route, as the catch-all needs to see it. */\nexport interface MountedRoute {\n method: string\n /** Full path as mounted, `:param` segments included. */\n path: string\n}\n\n/** `/things/:id` → `^/things/[^/]+$`, so a concrete path can be matched. */\nfunction patternToRegExp(pattern: string): RegExp {\n const source = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/[^/]+')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\n/** Path without query string or hash. */\nfunction pathOf(req: ErrorRequest): string {\n const url = req.originalUrl ?? req.url ?? '/'\n const cut = url.search(/[?#]/)\n return cut === -1 ? url : url.slice(0, cut)\n}\n\n/**\n * Catch-all for unmatched routes.\n *\n * Answers RFC 9457 problem details, like every other error the framework\n * produces — the catch-all was the one path still emitting a bare\n * `{ message }`, so a client parsing `application/problem+json` had to special\n * case it.\n *\n * Distinguishes a path that does not exist from a path that does not accept\n * this method. `DELETE /things/1` where only `GET` is mounted is a **405** with\n * an `Allow` header, not a 404: the resource is there, the verb is not, and\n * 404 tells a client to stop looking for something that exists. Requires the\n * mounted route table, so an app that does not pass one keeps answering 404.\n */\nexport function notFoundHandler(routes: readonly MountedRoute[] = []) {\n const matchers = routes.map((route) => ({\n method: route.method.toUpperCase(),\n matches: patternToRegExp(route.path),\n }))\n\n return (req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const path = pathOf(req)\n const method = (req.method ?? 'GET').toUpperCase()\n const allowed = [...new Set(matchers.filter((m) => m.matches.test(path)).map((m) => m.method))]\n\n if (allowed.length > 0 && !allowed.includes(method)) {\n // Sorted once: the header and the detail must list the same verbs in the\n // same order, and `sort()` would mutate `allowed` under the second read.\n const verbs = allowed.toSorted().join(', ')\n // RFC 9110 §15.5.6 requires Allow on a 405.\n res.setHeader('Allow', verbs)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(405).json(\n normalizeProblem({\n status: 405,\n detail: `${method} is not supported for this resource. Allowed: ${verbs}.`,\n }),\n )\n }\n\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(404).json(normalizeProblem({ status: 404 }))\n }\n}\n\n/**\n * Global error handler.\n *\n * Default behavior strips error `details` from the response in production\n * (NODE_ENV === 'production') so internal context (DB errors, validation\n * issues, custom payloads) does not leak to clients. Apps that want to\n * expose details in production — for client-facing field-level validation,\n * for example — should pass their own `onError` to `bootstrap()` and decide\n * the policy explicitly.\n *\n * Unexpected 500s carry `requestId` in every environment (the correlation\n * handle back to the log line) and, outside production, the error summary\n * plus stack. Production bodies stay opaque.\n *\n * {@link ProblemException} and plain {@link HttpException} both emit\n * `application/problem+json` per RFC 9457. `ProblemException` carries a\n * caller-supplied `type` / `title` / extensions; an `HttpException`'s message\n * becomes `detail`, with `title` and `type` defaulted from the status. One\n * shape, so a client never has to branch on which one the app threw.\n */\nexport function errorHandler() {\n return (err: any, req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const isProduction = isProductionEnv()\n // Don't write after headers are already sent\n if (res.headersSent) {\n log.warn(`Error after headers sent: ${err?.message || 'Unknown'}`)\n return\n }\n\n // RFC 9457 Problem Details — checked before HttpException because\n // ProblemException extends HttpException; instanceof on the base\n // would otherwise swallow it.\n if (err instanceof ProblemException) {\n if (err.problem.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const body = normalizeProblem(err.problem)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(body.status).json(body)\n }\n\n // Zod validation errors\n if (err?.name === 'ZodError') {\n const firstIssue = err.issues?.[0]\n return res.status(422).json({\n message: firstIssue?.message || 'Validation failed',\n ...(isProduction ? {} : { errors: err.issues }),\n })\n }\n\n // HttpException (expected application errors) — RFC 9457, same as\n // ProblemException. It used to answer a bare `{ message }`, which made it\n // THE path a client parsing `application/problem+json` had to special-case\n // (#611) — the exact situation #587 removed from the catch-all. The\n // message becomes `detail`; `title` and `type` default from the status.\n if (err instanceof HttpException) {\n if (err.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const exposeDetails = !isProduction && err.details !== undefined\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(err.status).json(\n normalizeProblem({\n status: err.status,\n detail: err.message,\n // Extension member, permitted by RFC 9457 §3.2. Held back in\n // production for the same reason as before: `details` can carry the\n // shape of the request that failed.\n ...(exposeDetails ? { errors: err.details } : {}),\n }),\n )\n }\n\n const requestId = (req as any).requestId ?? req.headers['x-request-id']\n const declared = Number(err.status ?? err.statusCode)\n\n // Any error that says it's a client error — a database UniqueViolationError\n // (409), a BYO auth check's 401 — is answered like an HttpException: RFC\n // 9457, its message as `detail`, and a warning rather than an error log.\n // It used to fall through to the catch-all: logged at ERROR with a stack,\n // answered with a bare `{ message }` no problem+json client could parse.\n if (Number.isInteger(declared) && declared >= 400 && declared < 500) {\n log.warn(`${req.method} ${req.originalUrl ?? req.url} — ${declared} ${describeError(err)}`)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(declared).json(\n normalizeProblem({\n status: declared,\n detail: err.message || undefined,\n ...(requestId ? { requestId } : {}),\n }),\n )\n }\n\n // Unexpected errors — always log. A declared 5xx keeps its status but\n // gets the same guarded body as a 500.\n const status = Number.isInteger(declared) && declared >= 500 && declared < 600 ? declared : 500\n log.error(\n err,\n // `originalUrl` is Express-only. Fastify and h3 pass `request.raw`, so\n // this logged `GET undefined — <error>` on every error under those\n // runtimes — the path silently dropped from the one line meant to\n // identify the failing request.\n `${req.method} ${req.originalUrl ?? req.url} — ${describeError(err)}${\n requestId ? ` [${requestId}]` : ''\n }`,\n )\n\n // A 500 body must never carry the raw error in production — it can\n // contain table names, SQL, connection strings, or user data. But\n // returning a bare `{ message: 'Internal Server Error' }` in\n // development means the one place a developer is looking tells them\n // nothing, and the failure has to be re-diagnosed from the database.\n //\n // Development gets the full picture. Production gets the requestId,\n // which is the correlation handle back to the (now stack-carrying)\n // log line — without it an opaque 500 can't even be tied to its own\n // log entry.\n res.status(status).json({\n message: 'Internal Server Error',\n ...(requestId ? { requestId } : {}),\n ...(isProduction\n ? {}\n : {\n error: describeError(err),\n ...(typeof err?.stack === 'string' ? { stack: err.stack.split('\\n') } : {}),\n }),\n })\n }\n}\n"],"mappings":";;;;;;;;;;iNAuBA,MAAM,IAAM,aAAa,cAAc,EAUvC,SAAS,gBAAgB,QAAyB,CAChD,IAAM,OAAS,QACZ,QAAQ,qBAAsB,MAAM,CAAC,CACrC,QAAQ,YAAa,QAAQ,CAAC,CAC9B,QAAQ,MAAO,IAAI,EACtB,OAAW,OAAO,IAAI,OAAO,IAAI,CACnC,CAGA,SAAS,OAAO,IAA2B,CACzC,IAAM,IAAM,IAAI,aAAe,IAAI,KAAO,IACpC,IAAM,IAAI,OAAO,MAAM,EAC7B,OAAO,MAAQ,GAAK,IAAM,IAAI,MAAM,EAAG,GAAG,CAC5C,CAgBA,SAAgB,gBAAgB,OAAkC,CAAC,EAAG,CACpE,IAAM,SAAW,OAAO,IAAK,QAAW,CACtC,OAAQ,MAAM,OAAO,YAAY,EACjC,QAAS,gBAAgB,MAAM,IAAI,CACrC,EAAE,EAEF,OA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,IAChE,UAAY,KAAK,UAAU,GAAK,IAEpC,EAYA,IAAI,OAAO,MAAM,CAAC,CAAC,KAAK,CACtB,QAAS,wBACT,GAAI,UAAY,CAAE,SAAU,EAAI,CAAC,EACjC,GAAIA,eACA,CAAC,EACD,CACE,MAAO,cAAc,GAAG,EACxB,GAAI,OAAO,KAAK,OAAU,SAAW,CAAE,MAAO,IAAI,MAAM,MAAM;CAAI,CAAE,EAAI,CAAC,CAC3E,CACN,CAAC,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"error-handler.mjs","names":["isProduction","isProductionEnv"],"sources":["../../../src/http/middleware/error-handler.ts"],"sourcesContent":["import type { RuntimeResponse } from '../runtime'\n\n/**\n * The slice of the request this handler reads, spelled from node's\n * `IncomingMessage` rather than Express's `Request`.\n *\n * Fastify and h3 hand the error handler `request.raw` — a plain\n * `IncomingMessage` — so anything Express-only is `undefined` there. This is\n * the default handler for EVERY runtime, so it must not assume Express.\n */\ninterface ErrorRequest {\n method?: string\n url?: string\n /** Express-only; absent on the raw node request the other runtimes pass. */\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n}\n// Module paths, not the core barrel: the web entry (edge runtimes) uses these\n// handlers too, and the barrel reaches node-only modules.\nimport { HttpException, ProblemException, normalizeProblem } from '../../core/errors'\nimport { createLogger, describeError } from '../../core/logger'\nimport { isProduction as isProductionEnv } from '../../core/is-production'\n\nconst log = createLogger('ErrorHandler')\n\n/** A mounted route, as the catch-all needs to see it. */\nexport interface MountedRoute {\n method: string\n /** Full path as mounted, `:param` segments included. */\n path: string\n}\n\n/** `/things/:id` → `^/things/[^/]+$`, so a concrete path can be matched. */\nfunction patternToRegExp(pattern: string): RegExp {\n const source = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/[^/]+')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\n/** Path without query string or hash. */\nfunction pathOf(req: ErrorRequest): string {\n const url = req.originalUrl ?? req.url ?? '/'\n const cut = url.search(/[?#]/)\n return cut === -1 ? url : url.slice(0, cut)\n}\n\n/**\n * Catch-all for unmatched routes.\n *\n * Answers RFC 9457 problem details, like every other error the framework\n * produces — the catch-all was the one path still emitting a bare\n * `{ message }`, so a client parsing `application/problem+json` had to special\n * case it.\n *\n * Distinguishes a path that does not exist from a path that does not accept\n * this method. `DELETE /things/1` where only `GET` is mounted is a **405** with\n * an `Allow` header, not a 404: the resource is there, the verb is not, and\n * 404 tells a client to stop looking for something that exists. Requires the\n * mounted route table, so an app that does not pass one keeps answering 404.\n */\nexport function notFoundHandler(routes: readonly MountedRoute[] = []) {\n const matchers = routes.map((route) => ({\n method: route.method.toUpperCase(),\n matches: patternToRegExp(route.path),\n }))\n\n return (req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const path = pathOf(req)\n const method = (req.method ?? 'GET').toUpperCase()\n const allowed = [...new Set(matchers.filter((m) => m.matches.test(path)).map((m) => m.method))]\n\n if (allowed.length > 0 && !allowed.includes(method)) {\n // Sorted once: the header and the detail must list the same verbs in the\n // same order, and `sort()` would mutate `allowed` under the second read.\n const verbs = allowed.toSorted().join(', ')\n // RFC 9110 §15.5.6 requires Allow on a 405.\n res.setHeader('Allow', verbs)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(405).json(\n normalizeProblem({\n status: 405,\n detail: `${method} is not supported for this resource. Allowed: ${verbs}.`,\n }),\n )\n }\n\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(404).json(normalizeProblem({ status: 404 }))\n }\n}\n\n/**\n * A validation failure's `[{ field, message }]` with every other member\n * dropped — or `undefined` when `details` isn't that shape.\n */\nfunction fieldErrors(details: unknown): Array<{ field: string; message: string }> | undefined {\n if (!Array.isArray(details) || details.length === 0) return undefined\n const ok = details.every((d) => typeof d?.field === 'string' && typeof d?.message === 'string')\n return ok ? details.map((d) => ({ field: d.field, message: d.message })) : undefined\n}\n\n/**\n * Global error handler.\n *\n * Default behavior strips error `details` from the response in production\n * (any `NODE_ENV` but `development` / `test`, unset included) so internal\n * context (DB errors, custom payloads) does not leak to clients. A 422's\n * per-field `{ field, message }` list is kept — field names and messages are\n * what a form shows — with every other member dropped. Apps that want a\n * different policy pass their own `onError` to `bootstrap()`.\n *\n * Unexpected 500s carry `requestId` in every environment (the correlation\n * handle back to the log line) and, outside production, the error summary\n * plus stack. Production bodies stay opaque.\n *\n * {@link ProblemException} and plain {@link HttpException} both emit\n * `application/problem+json` per RFC 9457. `ProblemException` carries a\n * caller-supplied `type` / `title` / extensions; an `HttpException`'s message\n * becomes `detail`, with `title` and `type` defaulted from the status. One\n * shape, so a client never has to branch on which one the app threw.\n */\nexport function errorHandler() {\n return (err: any, req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const isProduction = isProductionEnv()\n // Don't write after headers are already sent\n if (res.headersSent) {\n log.warn(`Error after headers sent: ${err?.message || 'Unknown'}`)\n return\n }\n\n // RFC 9457 Problem Details — checked before HttpException because\n // ProblemException extends HttpException; instanceof on the base\n // would otherwise swallow it.\n if (err instanceof ProblemException) {\n if (err.problem.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const body = normalizeProblem(err.problem)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(body.status).json(body)\n }\n\n // A raw ZodError never comes from the framework's own validation (that\n // raises an HttpException 422 with `[{ field, message }]`). It is the app\n // parsing something — possibly internal data — so production shows no\n // field paths; route validation (`@Post('/', { body })`) or an explicit\n // `HttpException` is how a form gets its field errors.\n if (err?.name === 'ZodError') {\n const firstIssue = err.issues?.[0]\n return res.status(422).json({\n message: firstIssue?.message || 'Validation failed',\n ...(isProduction ? {} : { errors: err.issues }),\n })\n }\n\n // HttpException (expected application errors) — RFC 9457, same as\n // ProblemException. It used to answer a bare `{ message }`, which made it\n // THE path a client parsing `application/problem+json` had to special-case\n // (#611) — the exact situation #587 removed from the catch-all. The\n // message becomes `detail`; `title` and `type` default from the status.\n if (err instanceof HttpException) {\n if (err.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n // Extension member, permitted by RFC 9457 §3.2. Held back in production:\n // `details` can carry the shape of the request that failed. A 422's\n // per-field `{ field, message }` list is the exception — a form needs\n // it to say which field is wrong — so production keeps just those two.\n const errors = isProduction\n ? err.status === 422\n ? fieldErrors(err.details)\n : undefined\n : err.details\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(err.status).json(\n normalizeProblem({\n status: err.status,\n detail: err.message,\n ...(errors !== undefined ? { errors } : {}),\n }),\n )\n }\n\n const requestId = (req as any).requestId ?? req.headers['x-request-id']\n const declared = Number(err.status ?? err.statusCode)\n\n // Any error that says it's a client error — a database UniqueViolationError\n // (409), a BYO auth check's 401 — is answered like an HttpException: RFC\n // 9457, its message as `detail`, and a warning rather than an error log.\n // It used to fall through to the catch-all: logged at ERROR with a stack,\n // answered with a bare `{ message }` no problem+json client could parse.\n if (Number.isInteger(declared) && declared >= 400 && declared < 500) {\n log.warn(`${req.method} ${req.originalUrl ?? req.url} — ${declared} ${describeError(err)}`)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(declared).json(\n normalizeProblem({\n status: declared,\n detail: err.message || undefined,\n ...(requestId ? { requestId } : {}),\n }),\n )\n }\n\n // Unexpected errors — always log. A declared 5xx keeps its status but\n // gets the same guarded body as a 500.\n const status = Number.isInteger(declared) && declared >= 500 && declared < 600 ? declared : 500\n log.error(\n err,\n // `originalUrl` is Express-only. Fastify and h3 pass `request.raw`, so\n // this logged `GET undefined — <error>` on every error under those\n // runtimes — the path silently dropped from the one line meant to\n // identify the failing request.\n `${req.method} ${req.originalUrl ?? req.url} — ${describeError(err)}${\n requestId ? ` [${requestId}]` : ''\n }`,\n )\n\n // A 500 body must never carry the raw error in production — it can\n // contain table names, SQL, connection strings, or user data. But\n // returning a bare `{ message: 'Internal Server Error' }` in\n // development means the one place a developer is looking tells them\n // nothing, and the failure has to be re-diagnosed from the database.\n //\n // Development gets the full picture. Production gets the requestId,\n // which is the correlation handle back to the (now stack-carrying)\n // log line — without it an opaque 500 can't even be tied to its own\n // log entry.\n res.status(status).json({\n message: 'Internal Server Error',\n ...(requestId ? { requestId } : {}),\n ...(isProduction\n ? {}\n : {\n error: describeError(err),\n ...(typeof err?.stack === 'string' ? { stack: err.stack.split('\\n') } : {}),\n }),\n })\n }\n}\n"],"mappings":";;;;;;;;;;iNAuBA,MAAM,IAAM,aAAa,cAAc,EAUvC,SAAS,gBAAgB,QAAyB,CAChD,IAAM,OAAS,QACZ,QAAQ,qBAAsB,MAAM,CAAC,CACrC,QAAQ,YAAa,QAAQ,CAAC,CAC9B,QAAQ,MAAO,IAAI,EACtB,OAAW,OAAO,IAAI,OAAO,IAAI,CACnC,CAGA,SAAS,OAAO,IAA2B,CACzC,IAAM,IAAM,IAAI,aAAe,IAAI,KAAO,IACpC,IAAM,IAAI,OAAO,MAAM,EAC7B,OAAO,MAAQ,GAAK,IAAM,IAAI,MAAM,EAAG,GAAG,CAC5C,CAgBA,SAAgB,gBAAgB,OAAkC,CAAC,EAAG,CACpE,IAAM,SAAW,OAAO,IAAK,QAAW,CACtC,OAAQ,MAAM,OAAO,YAAY,EACjC,QAAS,gBAAgB,MAAM,IAAI,CACrC,EAAE,EAEF,OAAQ,IAAmB,IAAsB,QAAsB,CACrE,IAAM,KAAO,OAAO,GAAG,EACjB,QAAU,IAAI,QAAU,MAAA,CAAO,YAAY,EAC3C,QAAU,CAAC,GAAG,IAAI,IAAI,SAAS,OAAQ,GAAM,EAAE,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,IAAK,GAAM,EAAE,MAAM,CAAC,CAAC,EAE9F,GAAI,QAAQ,OAAS,GAAK,CAAC,QAAQ,SAAS,MAAM,EAAG,CAGnD,IAAM,MAAQ,QAAQ,SAAS,CAAC,CAAC,KAAK,IAAI,EA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,QAAS,wBACT,GAAI,UAAY,CAAE,SAAU,EAAI,CAAC,EACjC,GAAIA,eACA,CAAC,EACD,CACE,MAAO,cAAc,GAAG,EACxB,GAAI,OAAO,KAAK,OAAU,SAAW,CAAE,MAAO,IAAI,MAAM,MAAM;CAAI,CAAE,EAAI,CAAC,CAC3E,CACN,CAAC,CACH,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{r as registerDisposable}from"../../disposables-
|
|
11
|
+
import{r as registerDisposable}from"../../disposables-DYTkgNiG.mjs";import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-BPSq2JCs.mjs";import{n as bindRoutePolicy}from"../../route-policy-DDszB6dQ.mjs";import{n as resolvePathname,t as resolveClientIp}from"../../client-ip-BLkoQTIR.mjs";import{i as sendJson}from"../../respond-BOlh-baJ.mjs";import{t as BoundedCounters}from"../../bounded-counters-DS-IbDW9.mjs";var MemoryStore=class{counters;cleanupTimer;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit),this.cleanupTimer=setInterval(()=>this.counters.sweep(),windowMs),this.cleanupTimer.unref&&this.cleanupTimer.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupTimer),this.counters.clear()}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function rateLimit(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??(req=>resolveClientIp(req)??`global`),sendHeaders=options.headers??!0,store=options.store??new MemoryStore(windowMs,max),skip=options.skip,skipPaths=new Set(options.skipPaths??[]),exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimit({ exemptWhen })`);let policy;return bindRoutePolicy(async(req,res,next)=>{let pathname=resolvePathname(req);if(skipPaths.has(pathname))return next();if(exemptWhen!==void 0&&policy){let{originalUrl}=req,routePath=originalUrl?resolvePathname({url:originalUrl}):pathname,flags=policy.lookup(String(req.method??`GET`),routePath);if(matchesFlagTest(exemptWhen,flags))return next()}if(skip&&skip(req))return next();let key=keyGenerator(req),{totalHits,resetTime}=await store.increment(key),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(res.setHeader(`RateLimit-Limit`,max),res.setHeader(`RateLimit-Remaining`,remaining),res.setHeader(`RateLimit-Reset`,Math.ceil(resetTime.getTime()/1e3))),totalHits>max)return sendJson(res,statusCode,{message});next()},table=>{policy=table})}export{MemoryStore,rateLimit};
|
|
12
12
|
//# sourceMappingURL=rate-limit.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import"../../core-CsMDdzNE.mjs";function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}function requestLogger(options={}){let log=createLogger(options.name??`HTTP`),level=options.level??`info`,skip=options.skip??[];return(req,res,next)=>{let pathname=req.path??pathnameOf(req.url);if(skip.some(prefix=>pathname.startsWith(prefix)))return next();let start=Date.now();res.on(`finish`,()=>{let duration=Date.now()-start,requestId=req.requestId||req.headers[`x-request-id`]||`-`,status=res.statusCode,path=req.originalUrl??req.url??`/`;log.child({method:req.method,path,status,ms:duration,requestId})[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)}),next()}}export{requestLogger};
|
|
12
12
|
//# sourceMappingURL=request-logger.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"../../core/logger.mjs";import{r as registerDisposable}from"../../disposables-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import{r as registerDisposable}from"../../disposables-DYTkgNiG.mjs";import{t as isProduction}from"../../is-production-BTroGhp5.mjs";import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-BOlh-baJ.mjs";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=/* @__PURE__ */ new Map;empty=/* @__PURE__ */ new Set;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear(),this.empty.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),this.empty.delete(sid),null):entry.data:null}async set(sid,data,maxAge){for(this.sessions.delete(sid),this.sessions.set(sid,{data,expires:Date.now()+maxAge}),this.empty.delete(sid),Object.keys(data).length===0&&this.empty.add(sid);this.sessions.size>1e4;){let victim=this.empty.values().next().value??this.sessions.keys().next().value;this.sessions.delete(victim),this.empty.delete(victim)}}async destroy(sid){this.sessions.delete(sid),this.empty.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge,this.sessions.delete(sid),this.sessions.set(sid,entry))}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&(this.sessions.delete(sid),this.empty.delete(sid))}};function secretList(secret){let list=Array.isArray(secret)?secret:[secret];if(list.length===0||list.some(s=>typeof s!=`string`||s.length===0))throw Error("session(): `secret` must be a non-empty string or list of strings");return list}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secrets){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),provided=Buffer.from(raw.slice(dotIndex+1));for(let[index,secret]of secrets.entries()){let expected=Buffer.from(createHmac(`sha256`,secret).update(value).digest(`base64url`));if(provided.length===expected.length&&timingSafeEqual(provided,expected))return{value,stale:index>0}}return!1}function session(options){if(options.store===`cookie`)return cookieSession(options);let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,secrets=secretList(options.secret),secret=secrets[0],store=options.store??new MemoryStore,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1,staleSignature=!1;if(signedCookie){let unsigned=unsign(signedCookie,secrets);unsigned&&(sid=unsigned.value,staleSignature=unsigned.stale,sessionData=await store.get(sid))}(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,setCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||(!isNew||saveUninitialized||Object.keys(currentData).length!==0)&&(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),!isNew&&(rolling||staleSignature)&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}const cookieLog=createLogger(`Session`);function sealer(secrets,cookieName){let keys=secrets.map(secret=>Buffer.from(hkdfSync(`sha256`,secret,`kick.session`,`cookie-store-v1`,32))),key=keys[0],aad=Buffer.from(cookieName);return{seal(payload){let iv=randomBytes(12),cipher=createCipheriv(`aes-256-gcm`,key,iv).setAAD(aad),body=Buffer.concat([cipher.update(JSON.stringify(payload),`utf8`),cipher.final()]);return`v1.${Buffer.concat([iv,cipher.getAuthTag(),body]).toString(`base64url`)}`},open(value){if(!value.startsWith(`v1.`))return null;let raw;try{raw=Buffer.from(value.slice(3),`base64url`)}catch{return null}if(raw.length<29)return null;for(let[index,k]of keys.entries())try{let decipher=createDecipheriv(`aes-256-gcm`,k,raw.subarray(0,12)).setAAD(aad).setAuthTag(raw.subarray(12,28)),json=Buffer.concat([decipher.update(raw.subarray(28)),decipher.final()]),payload=JSON.parse(json.toString(`utf8`));return typeof payload?.i!=`string`||typeof payload.e!=`number`||!payload.d||typeof payload.d!=`object`?null:payload.e>Date.now()?{payload,stale:index>0}:null}catch{}return null}}}function cookieSession(options){let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,{seal,open}=sealer(secretList(options.secret),cookieName),cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{}},warnedSize=!1;return(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let opened=cookies[cookieName]?open(cookies[cookieName]):null,existing=opened?.payload??null,isNew=!existing,id=existing?.i??randomUUID(),destroyed=!1,written=existing&&!opened?.stale?JSON.stringify(existing.d):void 0,write=(force=!1)=>{if(res.headersSent)return;if(destroyed){replaceCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)});return}let json=JSON.stringify(sessionObj.data);if(json===written&&!force&&(!rolling||isNew)||written===void 0&&json===`{}`&&!saveUninitialized&&!force)return;let value=seal({i:id,d:sessionObj.data,e:Date.now()+maxAge});value.length+cookieName.length>4e3&&!warnedSize&&(warnedSize=!0,cookieLog.warn(`session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, so this session will not be kept. Store less in it, or use a shared store.`)),replaceCookie(res,cookieName,value,{...cookieDefaults,maxAge}),written=json};for(let method of[`writeHead`,`flushHeaders`,`write`,`end`]){let original=res[method];typeof original==`function`&&(res[method]=function(...args){return write(),original.apply(this,args)})}res.on?.(`finish`,()=>write());let sessionObj={get id(){return id},data:existing?{...existing.d}:{},async regenerate(){id=randomUUID(),sessionObj.data={},written=void 0,write(!0)},async destroy(){destroyed=!0,sessionObj.data={},write()},async save(){write()}};req.session=sessionObj,next()}}export{MemoryStore,session};
|
|
12
12
|
//# sourceMappingURL=session.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { _ as
|
|
2
|
+
import { _ as SpaAdapterOptions, g as SpaAdapter, v as resolveClientDir } from "../../application-D5Iiy7rt.mjs";
|
|
3
3
|
export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{Logger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import"../../core-CsMDdzNE.mjs";import{t as defineAdapter}from"../../define-adapter-RbKRSG3i.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=/* @__PURE__ */ new Set;function snapshotClientDir(){let paths=/* @__PURE__ */ new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return/* @__PURE__ */ new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);existsSync(indexPath)?(indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)):log.warn(`index.html not found in ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
|
|
12
12
|
//# sourceMappingURL=spa.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-
|
|
2
|
+
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-DkT2p1gd.mjs";
|
|
3
3
|
export { type RawUploadPart, UploadOptions, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|