@forinda/kickjs 10.10.0 → 10.11.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-DLjn8q0c.d.mts → adapter-DiJfCKXU.d.mts} +27 -8
- package/dist/adapter-DiJfCKXU.d.mts.map +1 -0
- package/dist/{application-DLRHEOeg.mjs → application-BCXdtJd1.mjs} +3 -3
- package/dist/{application-DLRHEOeg.mjs.map → application-BCXdtJd1.mjs.map} +1 -1
- package/dist/{application-CdUI5E_3.d.mts → application-EinAcKLu.d.mts} +6 -6
- package/dist/{application-CdUI5E_3.d.mts.map → application-EinAcKLu.d.mts.map} +1 -1
- package/dist/{body-policy-DIgqprai.mjs → body-policy-DccDxmmR.mjs} +2 -2
- package/dist/{body-policy-DIgqprai.mjs.map → body-policy-DccDxmmR.mjs.map} +1 -1
- package/dist/bootstrap-C5op763j.mjs +12 -0
- package/dist/{bootstrap-6ltjueRe.mjs.map → bootstrap-C5op763j.mjs.map} +1 -1
- package/dist/{bounded-counters-Dxi2jekd.mjs → bounded-counters-CmmPOr2v.mjs} +2 -2
- package/dist/{bounded-counters-Dxi2jekd.mjs.map → bounded-counters-CmmPOr2v.mjs.map} +1 -1
- package/dist/{client-ip-dLKJKDZL.mjs → client-ip-STshfERA.mjs} +2 -2
- package/dist/{client-ip-dLKJKDZL.mjs.map → client-ip-STshfERA.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-BEoFtveu.mjs → config-DZd8tqGC.mjs} +3 -3
- package/dist/{config-BEoFtveu.mjs.map → config-DZd8tqGC.mjs.map} +1 -1
- package/dist/context-BJ6HVq4W.mjs +12 -0
- package/dist/context-BJ6HVq4W.mjs.map +1 -0
- package/dist/{context-errors-B2uJdmkX.mjs → context-errors-s1zG7eax.mjs} +2 -2
- package/dist/{context-errors-B2uJdmkX.mjs.map → context-errors-s1zG7eax.mjs.map} +1 -1
- package/dist/{contributor-runner-CaZkoZOK.mjs → contributor-runner-B5pv7_R-.mjs} +3 -3
- package/dist/{contributor-runner-CaZkoZOK.mjs.map → contributor-runner-B5pv7_R-.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.mjs +2 -2
- 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 +2 -2
- package/dist/{core-MyOlkejk.mjs → core-Cf6gPv9R.mjs} +3 -3
- package/dist/{core-MyOlkejk.mjs.map → core-Cf6gPv9R.mjs.map} +1 -1
- package/dist/{decorate-CU19-7Fw.mjs → decorate-BQA6M9jq.mjs} +3 -3
- package/dist/{decorate-CU19-7Fw.mjs.map → decorate-BQA6M9jq.mjs.map} +1 -1
- package/dist/{define-adapter-1FfgX1AQ.mjs → define-adapter-B9DcBJKt.mjs} +2 -2
- package/dist/{define-adapter-1FfgX1AQ.mjs.map → define-adapter-B9DcBJKt.mjs.map} +1 -1
- package/dist/{di-hooks-DX9rJX_0.mjs → di-hooks-DGmtRWDI.mjs} +2 -2
- package/dist/{di-hooks-DX9rJX_0.mjs.map → di-hooks-DGmtRWDI.mjs.map} +1 -1
- package/dist/{disposables-Bq6gIO7N.mjs → disposables-C1xhXyD6.mjs} +1 -1
- package/dist/{error-handler-BrihKETE.d.mts → error-handler-OfxVJX3s.d.mts} +2 -2
- package/dist/{error-handler-BrihKETE.d.mts.map → error-handler-OfxVJX3s.d.mts.map} +1 -1
- package/dist/{express-BBhisCna.mjs → express-DqWsJylQ.mjs} +3 -3
- package/dist/{express-BBhisCna.mjs.map → express-DqWsJylQ.mjs.map} +1 -1
- package/dist/{express-lazy-Pua2eR0n.mjs → express-lazy-CdPN1krb.mjs} +3 -3
- package/dist/{express-lazy-Pua2eR0n.mjs.map → express-lazy-CdPN1krb.mjs.map} +1 -1
- package/dist/handler-Ce16qhGr.mjs +12 -0
- package/dist/{handler-C_mWEafU.mjs.map → handler-Ce16qhGr.mjs.map} +1 -1
- package/dist/{host-d9X0p13s.mjs → host-BZcjkJ-A.mjs} +2 -2
- package/dist/{host-d9X0p13s.mjs.map → host-BZcjkJ-A.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- 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.mjs +2 -2
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- 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 +2 -2
- 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.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +2 -2
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.d.mts.map +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/index.d.mts +7 -7
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{is-production-BYwEumHI.mjs → is-production-et6gyyxF.mjs} +2 -2
- package/dist/{is-production-BYwEumHI.mjs.map → is-production-et6gyyxF.mjs.map} +1 -1
- package/dist/{jobs-bGtYcSgo.mjs → jobs-B4wle0iS.mjs} +3 -3
- package/dist/{jobs-bGtYcSgo.mjs.map → jobs-B4wle0iS.mjs.map} +1 -1
- package/dist/{kv-stores-DJBnGQsJ.d.mts → kv-stores-BN7c9bt9.d.mts} +2 -2
- package/dist/{kv-stores-DJBnGQsJ.d.mts.map → kv-stores-BN7c9bt9.d.mts.map} +1 -1
- package/dist/{kv-stores-DbM-V83V.mjs → kv-stores-CLR0N5im.mjs} +3 -3
- package/dist/{kv-stores-DbM-V83V.mjs.map → kv-stores-CLR0N5im.mjs.map} +1 -1
- package/dist/{lazy-serve-static-Dp3lqSlT.mjs → lazy-serve-static-CKaL8clq.mjs} +3 -3
- package/dist/{lazy-serve-static-Dp3lqSlT.mjs.map → lazy-serve-static-CKaL8clq.mjs.map} +1 -1
- package/dist/{metadata-BvNkZphr.mjs → metadata-CsfVw6pp.mjs} +1 -1
- package/dist/{observers-Bjs-1F1Z.mjs → observers-BbNYzGfC.mjs} +2 -2
- package/dist/{observers-Bjs-1F1Z.mjs.map → observers-BbNYzGfC.mjs.map} +1 -1
- package/dist/{precompressed-Cydk_Bpr.mjs → precompressed-BTEVCjT_.mjs} +2 -2
- package/dist/{precompressed-Cydk_Bpr.mjs.map → precompressed-BTEVCjT_.mjs.map} +1 -1
- package/dist/{query-BEnIVY7Q.mjs → query-EQM3lEr_.mjs} +2 -2
- package/dist/{query-BEnIVY7Q.mjs.map → query-EQM3lEr_.mjs.map} +1 -1
- package/dist/reply-Detphot1.mjs +12 -0
- package/dist/reply-Detphot1.mjs.map +1 -0
- package/dist/request-scope-D5ggZdvq.mjs +12 -0
- package/dist/{request-scope-u_VhYe4-.mjs.map → request-scope-D5ggZdvq.mjs.map} +1 -1
- package/dist/{respond-C0NoT3br.mjs → respond-B_5BPAJp.mjs} +2 -2
- package/dist/{respond-C0NoT3br.mjs.map → respond-B_5BPAJp.mjs.map} +1 -1
- package/dist/{rolldown-runtime-D2dh8WuU.mjs → rolldown-runtime-BgeRdaSa.mjs} +1 -1
- package/dist/{route-flag-xPz2wbyz.mjs → route-flag-CO7wkxhn.mjs} +3 -3
- package/dist/{route-flag-xPz2wbyz.mjs.map → route-flag-CO7wkxhn.mjs.map} +1 -1
- package/dist/{route-policy-weZwvZYs.mjs → route-policy-DJd0iddt.mjs} +2 -2
- package/dist/{route-policy-weZwvZYs.mjs.map → route-policy-DJd0iddt.mjs.map} +1 -1
- package/dist/{router-builder-CPJHwoL1.d.mts → router-builder-DtGrng_X.d.mts} +2 -2
- package/dist/{router-builder-CPJHwoL1.d.mts.map → router-builder-DtGrng_X.d.mts.map} +1 -1
- package/dist/{router-builder-CnCNsI87.mjs → router-builder-DtjsnD0b.mjs} +3 -3
- package/dist/{router-builder-CnCNsI87.mjs.map → router-builder-DtjsnD0b.mjs.map} +1 -1
- package/dist/{settings-Ciut2k76.mjs → settings-CJWJPERr.mjs} +3 -3
- package/dist/{settings-Ciut2k76.mjs.map → settings-CJWJPERr.mjs.map} +1 -1
- package/dist/{token-CBe6OMQK.mjs → token-kfP7I0D6.mjs} +1 -1
- package/dist/{upload-DtQ1pdQw.d.mts → upload-C9IfY1aQ.d.mts} +2 -2
- package/dist/{upload-DtQ1pdQw.d.mts.map → upload-C9IfY1aQ.d.mts.map} +1 -1
- package/dist/{upload-config-d_LW2u9b.mjs → upload-config-DldXNOHe.mjs} +2 -2
- package/dist/{upload-config-d_LW2u9b.mjs.map → upload-config-DldXNOHe.mjs.map} +1 -1
- package/dist/{url-for-Df_ts-iM.mjs → url-for-O-DQnRvH.mjs} +3 -3
- package/dist/{url-for-Df_ts-iM.mjs.map → url-for-O-DQnRvH.mjs.map} +1 -1
- package/dist/{background-CiKEgaD2.mjs → view-renderer-NbkTobFF.mjs} +3 -3
- package/dist/view-renderer-NbkTobFF.mjs.map +1 -0
- package/dist/{web-crypto-BNF60ZAh.mjs → web-crypto-BNP8o7BF.mjs} +2 -2
- package/dist/{web-crypto-BNF60ZAh.mjs.map → web-crypto-BNP8o7BF.mjs.map} +1 -1
- package/dist/web.d.mts +2 -2
- 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/adapter-DLjn8q0c.d.mts.map +0 -1
- package/dist/background-CiKEgaD2.mjs.map +0 -1
- package/dist/bootstrap-6ltjueRe.mjs +0 -12
- package/dist/context-BPszif4a.mjs +0 -12
- package/dist/context-BPszif4a.mjs.map +0 -1
- package/dist/handler-C_mWEafU.mjs +0 -12
- package/dist/reply-CGn9BmYj.mjs +0 -12
- package/dist/reply-CGn9BmYj.mjs.map +0 -1
- package/dist/request-scope-u_VhYe4-.mjs +0 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler-C_mWEafU.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 formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n readBodyBytes,\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 {\n applyUploadConfig,\n tooManyFiles,\n uploadLimits,\n type RawUploadPart,\n} 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 // Bounded before anything is parsed: the route's file budget plus room\n // for fields. Past it is a 413, held like a parse failure below.\n const limits = uploadLimits(upload)\n let form: FormData | undefined\n try {\n const bytes = await readBodyBytes(request, limits.total)\n const type = request.headers.get('content-type') ?? ''\n form = await new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], {\n headers: { 'content-type': type },\n })\n .formData()\n .catch(() => undefined)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields.push([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 req.body = formFields(fields)\n // A refused type (415), an oversized file or too many (413) is held like\n // a parse failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n if (rawParts.length > limits.files) {\n bodyError = tooManyFiles(limits.files)\n } else {\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\n }\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 // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (!bodyError && hasPrototypeKey(req.body)) bodyError = prototypeKeyError()\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 // Inside the request's store: an error page renders with the same\n // context and REQUEST-scoped services the route had.\n if (!driver.settled) {\n await requestStore.run(store, async () => {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n })\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":";;;;;;;;;;wyBAgBA,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,EACvC,MAAM,KAAO,IAAI,OAAS,EAAI,IAAM,IAAI,EAC1C,CACA,KAAK,MAAQ,KACf,CAGA,KAAK,MAAe,SAA4B,CAE9C,OADI,QAAU,SAAS,KAAK,OAAO,iBAAiB,QAAS,SAAU,CAAE,KAAM,EAAK,CAAC,EAC9E,IACT,CAGA,GAAG,MAAe,SAA4B,CAC5C,OAAO,KAAK,KAAK,MAAO,QAAQ,CAClC,CACF,EAEA,MAAM,QAAU,IAAI,YAEpB,SAAS,QAAQ,MAA4B,CAE3C,OADI,iBAAiB,WAAmB,MACjC,QAAQ,OAAO,OAAO,KAAK,CA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P,IAAK,OAAO,GAAG,EACd,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,CAGP,OAAO,SACV,MAAM,aAAa,IAAI,MAAO,SAAY,CACpC,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAK,IAAK,MAAM,EACnD,OAAO,SAAS,MAAM,aAAa,IAAK,IAAK,OAAQ,SAAS,CACrE,CAAC,CAEL,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-Ce16qhGr.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 formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n readBodyBytes,\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 {\n applyUploadConfig,\n tooManyFiles,\n uploadLimits,\n type RawUploadPart,\n} 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 // Bounded before anything is parsed: the route's file budget plus room\n // for fields. Past it is a 413, held like a parse failure below.\n const limits = uploadLimits(upload)\n let form: FormData | undefined\n try {\n const bytes = await readBodyBytes(request, limits.total)\n const type = request.headers.get('content-type') ?? ''\n form = await new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], {\n headers: { 'content-type': type },\n })\n .formData()\n .catch(() => undefined)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields.push([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 req.body = formFields(fields)\n // A refused type (415), an oversized file or too many (413) is held like\n // a parse failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n if (rawParts.length > limits.files) {\n bodyError = tooManyFiles(limits.files)\n } else {\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\n }\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 // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (!bodyError && hasPrototypeKey(req.body)) bodyError = prototypeKeyError()\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 // Inside the request's store: an error page renders with the same\n // context and REQUEST-scoped services the route had.\n if (!driver.settled) {\n await requestStore.run(store, async () => {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n })\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\n/**\n * HEAD for a GET route: run the route and answer with its status and\n * headers, without the body — what Express and Fastify do for every GET.\n */\nexport async function headFromGet(response: Promise<Response> | Response): Promise<Response> {\n const res = await response\n // A streamed GET (SSE) would otherwise keep producing for nobody.\n res.body?.cancel().catch(() => {})\n return new Response(null, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n })\n}\n"],"mappings":";;;;;;;;;;2yBAgBA,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,EACvC,MAAM,KAAO,IAAI,OAAS,EAAI,IAAM,IAAI,EAC1C,CACA,KAAK,MAAQ,KACf,CAGA,KAAK,MAAe,SAA4B,CAE9C,OADI,QAAU,SAAS,KAAK,OAAO,iBAAiB,QAAS,SAAU,CAAE,KAAM,EAAK,CAAC,E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/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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-BZcjkJ-A.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-
|
|
1
|
+
{"version":3,"file":"host-BZcjkJ-A.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 ConfigDescription, c as MiddlewareEntry, d as ShutdownOptions, f as describeRoutes, i as ApplicationOptions, l as MountedRouteInfo, n as AppStatus, o as ConfigOrigins, r as Application, s as ManagementOptions, t as APPLICATION, u as ServerOptions } from "../application-
|
|
2
|
+
import { a as ConfigDescription, c as MiddlewareEntry, d as ShutdownOptions, f as describeRoutes, i as ApplicationOptions, l as MountedRouteInfo, n as AppStatus, o as ConfigOrigins, r as Application, s as ManagementOptions, t as APPLICATION, u as ServerOptions } from "../application-EinAcKLu.mjs";
|
|
3
3
|
export { APPLICATION, AppStatus, Application, ApplicationOptions, ConfigDescription, ConfigOrigins, ManagementOptions, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions, describeRoutes };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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,n as Application,r as describeRoutes}from"../application-
|
|
11
|
+
export{t as APPLICATION,n as Application,r as describeRoutes}from"../application-BCXdtJd1.mjs";
|
package/dist/http/bootstrap.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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 bootstrap}from"../bootstrap-
|
|
11
|
+
export{t as bootstrap}from"../bootstrap-C5op763j.mjs";
|
package/dist/http/context.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
import { D as RouteShape, E as RequestContext, O as SseHandler, T as DeepReadonly, k as contentDisposition, w as Ctx } from "../adapter-
|
|
2
|
+
import { D as RouteShape, E as RequestContext, O as SseHandler, T as DeepReadonly, k as contentDisposition, w as Ctx } from "../adapter-DiJfCKXU.mjs";
|
|
3
3
|
import { b as ContextMeta } from "../app-module-Bk3glnPP.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.11.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-BJ6HVq4W.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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-BZcjkJ-A.mjs";import{n as resolvePathname}from"../../client-ip-STshfERA.mjs";import{i as sendJson}from"../../respond-B_5BPAJp.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,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-
|
|
11
|
+
import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-CO7wkxhn.mjs";import{t as isProduction}from"../../is-production-et6gyyxF.mjs";import{n as randomHex,r as safeEqual}from"../../web-crypto-BNP8o7BF.mjs";import{n as canonicalHost,r as parseHttpUrl}from"../../host-BZcjkJ-A.mjs";import{n as resolvePathname}from"../../client-ip-STshfERA.mjs";import{a as setCookie,i as sendJson,n as readCookies}from"../../respond-B_5BPAJp.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
12
|
//# sourceMappingURL=csrf.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as errorHandler, r as notFoundHandler, t as MountedRoute } from "../../error-handler-
|
|
2
|
+
import { n as errorHandler, r as notFoundHandler, t as MountedRoute } from "../../error-handler-OfxVJX3s.mjs";
|
|
3
3
|
export { MountedRoute, errorHandler, notFoundHandler };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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-et6gyyxF.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,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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-C1xhXyD6.mjs";import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-CO7wkxhn.mjs";import{n as bindRoutePolicy}from"../../route-policy-DJd0iddt.mjs";import{n as resolvePathname,t as resolveClientIp}from"../../client-ip-STshfERA.mjs";import{i as sendJson}from"../../respond-B_5BPAJp.mjs";import{t as BoundedCounters}from"../../bounded-counters-CmmPOr2v.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.11.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-Cf6gPv9R.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.11.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-C1xhXyD6.mjs";import{t as isProduction}from"../../is-production-et6gyyxF.mjs";import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-B_5BPAJp.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 { b as SpaAdapterOptions, x as resolveClientDir, y as SpaAdapter } from "../../application-
|
|
2
|
+
import { b as SpaAdapterOptions, x as resolveClientDir, y as SpaAdapter } from "../../application-EinAcKLu.mjs";
|
|
3
3
|
export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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-Cf6gPv9R.mjs";import{t as defineAdapter}from"../../define-adapter-B9DcBJKt.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,4 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as RawUploadPart, F as buildFileTypeFilter, I as resolveMimeTypes, M as UploadedFile, N as UploadedFileLike, P as applyUploadConfig, j as UploadStorageEngine } from "../../adapter-
|
|
3
|
-
import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "../../upload-
|
|
2
|
+
import { A as RawUploadPart, F as buildFileTypeFilter, I as resolveMimeTypes, M as UploadedFile, N as UploadedFileLike, P as applyUploadConfig, j as UploadStorageEngine } from "../../adapter-DiJfCKXU.mjs";
|
|
3
|
+
import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "../../upload-C9IfY1aQ.mjs";
|
|
4
4
|
export { type RawUploadPart, UploadOptions, type UploadStorageEngine, type UploadedFile, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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{HttpException,HttpStatus}from"../../core/errors.mjs";import{f as tooLarge}from"../../body-policy-
|
|
11
|
+
import{HttpException,HttpStatus}from"../../core/errors.mjs";import{f as tooLarge}from"../../body-policy-DccDxmmR.mjs";import{a as normalizeOriginalName,c as tooManyFiles,i as buildFileTypeFilter,l as uploadLimits,n as UPLOAD_FIELDS_ALLOWANCE,o as resolveMimeTypes,r as applyUploadConfig,s as serverFileName,t as MAX_UPLOAD_FIELDS}from"../../upload-config-DldXNOHe.mjs";import{unlink}from"node:fs/promises";import{Transform}from"node:stream";let _multer;function loadMulter(){return _multer??=import(`multer`).then(mod=>mod.default??mod,()=>{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed. Add it to your dependencies.`)})}function translateMulterErrors(mw,options,files){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(files&&err?.code===`LIMIT_UNEXPECTED_FILE`&&err.field===files.field)return next(tooManyFiles(files.max));if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}if(!err)try{nameUploads(req,options)}catch(error){return next(error)}next(err)})}}function nameUploads(req,options){let files=[req.file,...Array.isArray(req.files)?req.files:[]];for(let file of files)file&&(file.originalname=normalizeOriginalName(file.originalname),file.filename??=serverFileName(file,options))}function createMulter(options){let limits={fileSize:options.maxSize??5242880,fields:MAX_UPLOAD_FIELDS,fieldSize:UPLOAD_FIELDS_ALLOWANCE},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,defParamCharset:`utf8`,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}},built,lazy=pick=>{let handler;return(req,res,next)=>{handler??=(built??=loadMulter().then(multer=>multer(multerOptions))).then(pick),handler.then(run=>run(req,res,next),err=>{handler=built=_multer=void 0,next(err)})}};return{single:field=>lazy(m=>m.single(field)),array:(field,maxCount)=>lazy(m=>m.array(field,maxCount)),none:()=>lazy(m=>m.none())}}function bothConventions(handler){return((first,second,third)=>third===void 0&&typeof second==`function`&&typeof first==`object`&&first&&`req`in first&&`res`in first?new Promise((resolve,reject)=>{handler(first.req,first.res,err=>{if(err)return reject(err);resolve(),second()})}):handler(first,second,third))}function capBody(mw,limit){return(req,res,next)=>{if(Number(req.headers[`content-length`])>limit)return next(tooLarge(limit));if(typeof req.pipe!=`function`)return mw(req,res,next);let pipe=req.pipe.bind(req);req.pipe=(destination=>{let received=0,counter=new Transform({transform(chunk,_encoding,done){if(received+=chunk.length,received<=limit)return done(null,chunk);received-chunk.length<=limit&&destination.destroy(tooLarge(limit)),done()}});return pipe(counter),counter.pipe(destination)}),mw(req,res,next)}}function single(fieldName,options={}){let m=createMulter(options),{total}=uploadLimits({mode:`single`,maxSize:options.maxSize});return bothConventions(capBody(translateMulterErrors(m.single(fieldName),options,{field:fieldName,max:1}),total))}function array(fieldName,maxCount=10,options={}){let m=createMulter(options),{total}=uploadLimits({mode:`array`,maxSize:options.maxSize,maxCount});return bothConventions(capBody(translateMulterErrors(m.array(fieldName,maxCount),options,{field:fieldName,max:maxCount}),total))}function none(options={}){let m=createMulter(options),{total}=uploadLimits({mode:`none`});return bothConventions(capBody(translateMulterErrors(m.none(),options),total))}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap),config.rename&&(options.rename=config.rename);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
|
|
12
12
|
//# sourceMappingURL=upload.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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-Cf6gPv9R.mjs";import{t as defineAdapter}from"../../define-adapter-B9DcBJKt.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app:engineApp}){let app=engineApp,{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
|
|
12
12
|
//# sourceMappingURL=views.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-
|
|
11
|
+
export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-EQM3lEr_.mjs";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-
|
|
2
|
+
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-DtGrng_X.mjs";
|
|
3
3
|
export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.11.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 _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-
|
|
11
|
+
export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-DtjsnD0b.mjs";
|