@forinda/kickjs 9.1.0 → 9.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-DhjoIYVI.d.mts → adapter-DjfRMob8.d.mts} +3 -13
- package/dist/{adapter-DhjoIYVI.d.mts.map → adapter-DjfRMob8.d.mts.map} +1 -1
- package/dist/application-BSJpaiSY.mjs +12 -0
- package/dist/{application-nDj-76EX.mjs.map → application-BSJpaiSY.mjs.map} +1 -1
- package/dist/{application-DqD58rhF.d.mts → application-CGxZCYl1.d.mts} +8 -8
- package/dist/{application-DqD58rhF.d.mts.map → application-CGxZCYl1.d.mts.map} +1 -1
- package/dist/{bootstrap-BqcT1h9H.mjs → bootstrap-CbTF6xvv.mjs} +3 -3
- package/dist/{bootstrap-BqcT1h9H.mjs.map → bootstrap-CbTF6xvv.mjs.map} +1 -1
- package/dist/{client-ip-DMKc-Trg.mjs → client-ip-pcINkkPr.mjs} +2 -2
- package/dist/{client-ip-DMKc-Trg.mjs.map → client-ip-pcINkkPr.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-DrgIbebd.mjs → config-DmGiAIuH.mjs} +3 -3
- package/dist/{config-DrgIbebd.mjs.map → config-DmGiAIuH.mjs.map} +1 -1
- package/dist/{container-ZnfelY_a.mjs → container-CAPN7pBG.mjs} +3 -3
- package/dist/{container-ZnfelY_a.mjs.map → container-CAPN7pBG.mjs.map} +1 -1
- package/dist/{context-errors-Cgtrrqfs.mjs → context-errors-DYJjhalQ.mjs} +2 -2
- package/dist/{context-errors-Cgtrrqfs.mjs.map → context-errors-DYJjhalQ.mjs.map} +1 -1
- package/dist/context-gpvcMlG5.mjs +12 -0
- package/dist/context-gpvcMlG5.mjs.map +1 -0
- package/dist/{contributor-runner-BSpshfPN.mjs → contributor-runner-vk9XlOED.mjs} +3 -3
- package/dist/{contributor-runner-BSpshfPN.mjs.map → contributor-runner-vk9XlOED.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/{core-_WNyghl_.mjs → core-DKrKVLfj.mjs} +3 -3
- package/dist/{core-_WNyghl_.mjs.map → core-DKrKVLfj.mjs.map} +1 -1
- package/dist/{csrf-COFjRrUz.d.mts → csrf-C73UkRgc.d.mts} +2 -2
- package/dist/{csrf-COFjRrUz.d.mts.map → csrf-C73UkRgc.d.mts.map} +1 -1
- package/dist/{csrf-BcxqzCZW.mjs → csrf-CxJItZVa.mjs} +3 -3
- package/dist/{csrf-BcxqzCZW.mjs.map → csrf-CxJItZVa.mjs.map} +1 -1
- package/dist/{decorate-BBwu7--P.mjs → decorate-DfH1NIqV.mjs} +1 -1
- package/dist/{decorators-DOcWsXci.d.mts → decorators-BxNSz9Qt.d.mts} +4 -4
- package/dist/{decorators-DOcWsXci.d.mts.map → decorators-BxNSz9Qt.d.mts.map} +1 -1
- package/dist/{define-adapter-CajLeMzM.mjs → define-adapter-C6lFhCL-.mjs} +2 -2
- package/dist/{define-adapter-CajLeMzM.mjs.map → define-adapter-C6lFhCL-.mjs.map} +1 -1
- package/dist/{disposables-DIXt8ze-.mjs → disposables-NlW6Mibk.mjs} +2 -2
- package/dist/{disposables-DIXt8ze-.mjs.map → disposables-NlW6Mibk.mjs.map} +1 -1
- package/dist/{env-DtJ-6gyL.mjs → env-__fzPsHD.mjs} +3 -3
- package/dist/{env-DtJ-6gyL.mjs.map → env-__fzPsHD.mjs.map} +1 -1
- package/dist/{error-handler-DiueQHes.d.mts → error-handler-itG65lj0.d.mts} +2 -2
- package/dist/{error-handler-DiueQHes.d.mts.map → error-handler-itG65lj0.d.mts.map} +1 -1
- package/dist/handler-DnZbcleS.mjs +13 -0
- package/dist/handler-DnZbcleS.mjs.map +1 -0
- 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/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +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 +1 -1
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +3 -1
- package/dist/http/runtimes/fastify.d.mts.map +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.d.mts +1 -1
- package/dist/http/runtimes/h3-web.mjs +2 -2
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-CDn-p3tq.d.mts → index-CNHSbZTE.d.mts} +4 -4
- package/dist/{index-CDn-p3tq.d.mts.map → index-CNHSbZTE.d.mts.map} +1 -1
- package/dist/index.d.mts +9 -9
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{jobs-dx-MTUUb.mjs → jobs-BmpeFvi0.mjs} +3 -3
- package/dist/{jobs-dx-MTUUb.mjs.map → jobs-BmpeFvi0.mjs.map} +1 -1
- package/dist/{kv-stores-CetFF9N_.d.mts → kv-stores-BZTe23Tw.d.mts} +3 -3
- package/dist/{kv-stores-CetFF9N_.d.mts.map → kv-stores-BZTe23Tw.d.mts.map} +1 -1
- package/dist/{kv-stores-Ba5_rcz-.mjs → kv-stores-DJwxntyw.mjs} +3 -3
- package/dist/{kv-stores-Ba5_rcz-.mjs.map → kv-stores-DJwxntyw.mjs.map} +1 -1
- package/dist/{metadata-CW4I35nN.mjs → metadata-CzzRUnAx.mjs} +2 -2
- package/dist/{metadata-CW4I35nN.mjs.map → metadata-CzzRUnAx.mjs.map} +1 -1
- package/dist/{module-registry-kqozOSo0.mjs → module-registry-BnmRNy-3.mjs} +2 -2
- package/dist/{module-registry-kqozOSo0.mjs.map → module-registry-BnmRNy-3.mjs.map} +1 -1
- package/dist/{observers-CC3sO1BM.mjs → observers-COlQfinD.mjs} +2 -2
- package/dist/{observers-CC3sO1BM.mjs.map → observers-COlQfinD.mjs.map} +1 -1
- package/dist/{query-DPlkWOw6.mjs → query-B5DTq_4W.mjs} +2 -2
- package/dist/{query-DPlkWOw6.mjs.map → query-B5DTq_4W.mjs.map} +1 -1
- package/dist/reply-CbTYIj_e.mjs +12 -0
- package/dist/reply-CbTYIj_e.mjs.map +1 -0
- package/dist/{respond-DjxNwGnN.mjs → respond-wbMSqHYo.mjs} +2 -2
- package/dist/{respond-DjxNwGnN.mjs.map → respond-wbMSqHYo.mjs.map} +1 -1
- package/dist/{route-flag-sIYXay3q.mjs → route-flag-Bb7n9Mnp.mjs} +3 -3
- package/dist/{route-flag-sIYXay3q.mjs.map → route-flag-Bb7n9Mnp.mjs.map} +1 -1
- package/dist/{route-policy-B6_toGJW.mjs → route-policy-C_Wsc-b1.mjs} +2 -2
- package/dist/{route-policy-B6_toGJW.mjs.map → route-policy-C_Wsc-b1.mjs.map} +1 -1
- package/dist/{router-builder-BSBSYgYW.d.mts → router-builder-CDkW88KQ.d.mts} +2 -2
- package/dist/{router-builder-BSBSYgYW.d.mts.map → router-builder-CDkW88KQ.d.mts.map} +1 -1
- package/dist/{router-builder-CzVjPs5y.mjs → router-builder-DawnRzlp.mjs} +3 -3
- package/dist/{router-builder-CzVjPs5y.mjs.map → router-builder-DawnRzlp.mjs.map} +1 -1
- package/dist/{upload-DjhnyHHm.d.mts → upload-Cy7qQy7M.d.mts} +3 -3
- package/dist/{upload-DjhnyHHm.d.mts.map → upload-Cy7qQy7M.d.mts.map} +1 -1
- package/dist/{upload-config-d0pisVsK.mjs → upload-config-D01Ty40f.mjs} +2 -2
- package/dist/{upload-config-d0pisVsK.mjs.map → upload-config-D01Ty40f.mjs.map} +1 -1
- package/dist/web.d.mts +3 -3
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/application-nDj-76EX.mjs +0 -12
- package/dist/context-BGPof8bs.mjs +0 -12
- package/dist/context-BGPof8bs.mjs.map +0 -1
- package/dist/handler-2OebsoPr.mjs +0 -13
- package/dist/handler-2OebsoPr.mjs.map +0 -1
- package/dist/runtime-CDz5ayBt.mjs +0 -12
- package/dist/runtime-CDz5ayBt.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metadata-
|
|
1
|
+
{"version":3,"file":"metadata-CzzRUnAx.mjs","names":[],"sources":["../src/core/metadata.ts"],"sourcesContent":["import 'reflect-metadata'\nimport type { InjectionToken } from './token'\n\n/**\n * Typed utilities for reflect-metadata operations.\n *\n * Replaces scattered Reflect.defineMetadata/getMetadata calls with a single\n * source of truth. If we later move to Stage 3 decorators or a WeakMap-based\n * store, only this file changes — all 24+ consumer files stay untouched.\n *\n * Keys may be symbols, strings, or `InjectionToken<T>` objects produced by\n * `createToken()`. Using `createToken` is the preferred pattern because the\n * token's phantom type flows through the helpers, enabling type-safe reads.\n */\n\ntype MetaKey = symbol | string | InjectionToken<unknown>\n\n// ── Setters ─────────────────────────────────────────────────────\n\n/** Set metadata on a class (or prototype for property decorators) */\nexport function setClassMeta<T>(key: MetaKey, value: T, target: object): void {\n Reflect.defineMetadata(key, value, target)\n}\n\n/** Set metadata on a specific method */\nexport function setMethodMeta<T>(key: MetaKey, value: T, target: object, method: string): void {\n Reflect.defineMetadata(key, value, target, method)\n}\n\n// ── Getters ─────────────────────────────────────────────────────\n\n/** Get metadata from a class, returning `fallback` if not set */\nexport function getClassMeta<T>(key: MetaKey, target: object, fallback: T): T {\n return (Reflect.getMetadata(key, target) as T) ?? fallback\n}\n\n/** Get metadata from a specific method, returning `fallback` if not set */\nexport function getMethodMeta<T>(key: MetaKey, target: object, method: string, fallback: T): T {\n return (Reflect.getMetadata(key, target, method) as T) ?? fallback\n}\n\n/** Check if metadata exists on a class */\nexport function hasClassMeta(key: MetaKey, target: object): boolean {\n return Reflect.hasMetadata(key, target)\n}\n\n/** Get metadata from a class with no default (returns undefined if absent) */\nexport function getClassMetaOrUndefined<T>(key: MetaKey, target: object): T | undefined {\n return Reflect.getMetadata(key, target) as T | undefined\n}\n\n/** Get metadata from a method with no default (returns undefined if absent) */\nexport function getMethodMetaOrUndefined<T>(\n key: MetaKey,\n target: object,\n method: string,\n): T | undefined {\n return Reflect.getMetadata(key, target, method) as T | undefined\n}\n\n// ── Accumulate: Arrays ──────────────────────────────────────────\n\n/** Append items to an array stored in class metadata */\nexport function pushClassMeta<T>(key: MetaKey, target: object, ...items: T[]): void {\n const existing: T[] = Reflect.getOwnMetadata(key, target) ?? []\n Reflect.defineMetadata(key, [...existing, ...items], target)\n}\n\n/** Append items to an array stored in method metadata */\nexport function pushMethodMeta<T>(\n key: MetaKey,\n target: object,\n method: string,\n ...items: T[]\n): void {\n const existing: T[] = Reflect.getOwnMetadata(key, target, method) ?? []\n Reflect.defineMetadata(key, [...existing, ...items], target, method)\n}\n\n// ── Accumulate: Maps ────────────────────────────────────────────\n\n/** Set a key/value in a Map stored in class metadata */\nexport function setInMetaMap<K, V>(key: MetaKey, target: object, mapKey: K, mapValue: V): void {\n const inherited: Map<K, V> | undefined = Reflect.getOwnMetadata(key, target)\n const map = inherited ? new Map(inherited) : new Map<K, V>()\n map.set(mapKey, mapValue)\n Reflect.defineMetadata(key, map, target)\n}\n\n/** Get a Map from class metadata (returns empty Map if absent) */\nexport function getMetaMap<K, V>(key: MetaKey, target: object): Map<K, V> {\n return Reflect.getMetadata(key, target) ?? new Map()\n}\n\n// ── Accumulate: Records ─────────────────────────────────────────\n\n/** Set a key/value in a Record stored in class metadata */\nexport function setInMetaRecord<V>(\n key: MetaKey,\n target: object,\n recKey: string | number,\n recValue: V,\n): void {\n const inherited: Record<string | number, V> | undefined = Reflect.getOwnMetadata(key, target)\n const rec = inherited ? { ...inherited } : {}\n rec[recKey] = recValue\n Reflect.defineMetadata(key, rec, target)\n}\n\n/** Get a Record from class metadata (returns empty object if absent) */\nexport function getMetaRecord<V>(key: MetaKey, target: object): Record<string | number, V> {\n return Reflect.getMetadata(key, target) ?? {}\n}\n"],"mappings":";;;;;;;;;;yBAoBA,SAAgB,aAAgB,IAAc,MAAU,OAAsB,CAC5E,QAAQ,eAAe,IAAK,MAAO,MAAM,CAC3C,CAGA,SAAgB,cAAiB,IAAc,MAAU,OAAgB,OAAsB,CAC7F,QAAQ,eAAe,IAAK,MAAO,OAAQ,MAAM,CACnD,CAKA,SAAgB,aAAgB,IAAc,OAAgB,SAAgB,CAC5E,OAAQ,QAAQ,YAAY,IAAK,MAAM,GAAW,QACpD,CAGA,SAAgB,cAAiB,IAAc,OA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YAAY,IAAK,MAAM,GAAK,CAAC,CAC9C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};export{MutableModuleRegistry as t};
|
|
12
|
-
//# sourceMappingURL=module-registry-
|
|
12
|
+
//# sourceMappingURL=module-registry-BnmRNy-3.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module-registry-
|
|
1
|
+
{"version":3,"file":"module-registry-BnmRNy-3.mjs","names":[],"sources":["../src/core/module-registry.ts"],"sourcesContent":["import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n"],"mappings":";;;;;;;;;;AAwDA,IAAa,sBAAb,KAA6D,CAC3D,QAAqC,CAAC,EAEtC,MAAM,OAA8B,CAClC,KAAK,QAAQ,KAAK,MAAM,CAC1B,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import{createLogger}from"./core/logger.mjs";const log=createLogger(`Observers`);let observers=[],publisher,publisherWantsResponses=()=>!1;function setObservers(list){return observers=list.filter(o=>o.onError||o.onResponse),observers}function releaseObservers(installed){observers===installed&&(observers=[])}function setObserverPublisher(next,wantsResponses=()=>!1){publisher=next,publisherWantsResponses=wantsResponses}function hasResponseObservers(){return observers.some(o=>o.onResponse)||publisherWantsResponses()}function notify(pick,what){for(let observer of publisher?[...observers,publisher]:observers)try{let result=pick(observer);result&&typeof result.catch==`function`&&result.catch(err=>failed(observer,what,err))}catch(err){failed(observer,what,err)}}function failed(observer,what,err){try{log.error({err},`${observer.name??`observer`}.${what} threw — skipped`)}catch{}}function reportError(error,info){notify(o=>o.onError?.(error,info),`onError`)}function reportResponse(info){notify(o=>o.onResponse?.(info),`onResponse`)}export{setObserverPublisher as a,reportResponse as i,releaseObservers as n,setObservers as o,reportError as r,hasResponseObservers as t};
|
|
12
|
-
//# sourceMappingURL=observers-
|
|
12
|
+
//# sourceMappingURL=observers-COlQfinD.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observers-
|
|
1
|
+
{"version":3,"file":"observers-COlQfinD.mjs","names":[],"sources":["../src/core/observers.ts"],"sourcesContent":["/**\n * One place every error and every response is reported to — so an error\n * tracker, a metrics exporter, or an APM integration hooks in once instead of\n * replacing the error handler and patching each source.\n *\n * Observers are adapters and plugins with `onError` / `onResponse`, plus\n * whatever the Node server's tracing channels publish (see `http/tracing.ts`).\n * Observe-only: they cannot change the response, and one that throws is\n * logged and skipped — it never breaks a request or another observer.\n *\n * Free of `node:` imports: `waitUntil` (shared with the web entry) reports\n * through here.\n *\n * @module @forinda/kickjs/core/observers\n */\nimport { createLogger } from './logger'\n\nconst log = createLogger('Observers')\n\n/** Where an error came from. Integrations may report their own sources. */\nexport type ErrorSource =\n | 'request'\n | 'uncaught'\n | 'unhandled-rejection'\n | 'background'\n | 'job'\n | (string & {})\n\nexport interface ErrorInfo {\n source: ErrorSource\n requestId?: string\n method?: string\n /** The request URL path, as received. */\n path?: string\n /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */\n route?: string\n /** The status the error was answered with, for request errors. */\n status?: number\n /** Anything else the reporter knows — a queue and job name, a cron schedule. */\n context?: Record<string, unknown>\n}\n\nexport interface ResponseInfo {\n method: string\n path: string\n /** The matched route pattern, or undefined when no route matched (404s). */\n route?: string\n status: number\n durationMs: number\n requestId?: string\n}\n\nexport interface Observer {\n name?: string\n onError?(error: unknown, info: ErrorInfo): void | Promise<void>\n onResponse?(info: ResponseInfo): void | Promise<void>\n}\n\nlet observers: readonly Observer[] = []\nlet publisher: Observer | undefined\nlet publisherWantsResponses: () => boolean = () => false\n\n/**\n * Replace the observer set — called by the Application from its adapters and\n * plugins. Returns the installed set, so its owner can later release exactly\n * that set (see {@link releaseObservers}).\n */\nexport function setObservers(list: readonly Observer[]): readonly Observer[] {\n observers = list.filter((o) => o.onError || o.onResponse)\n return observers\n}\n\n/**\n * Clear the observer set — but only if it is still the one `installed`. The\n * set is process-wide: a newer Application may have replaced it, and an older\n * one shutting down must not clear the newer one's observers.\n */\nexport function releaseObservers(installed: readonly Observer[]): void {\n if (observers === installed) observers = []\n}\n\n/**\n * The Node server's tracing channels, fed from the same reports. `wantsResponses`\n * is checked per request: a channel can gain a subscriber at any time.\n */\nexport function setObserverPublisher(\n next: Observer | undefined,\n wantsResponses: () => boolean = () => false,\n): void {\n publisher = next\n publisherWantsResponses = wantsResponses\n}\n\n/** Whether anything is listening for responses — lets the server skip timing work. */\nexport function hasResponseObservers(): boolean {\n return observers.some((o) => o.onResponse) || publisherWantsResponses()\n}\n\nfunction notify(pick: (o: Observer) => void | Promise<void> | undefined, what: string): void {\n for (const observer of publisher ? [...observers, publisher] : observers) {\n try {\n const result = pick(observer)\n if (result && typeof (result as Promise<void>).catch === 'function') {\n ;(result as Promise<void>).catch((err: unknown) => failed(observer, what, err))\n }\n } catch (err) {\n failed(observer, what, err)\n }\n }\n}\n\nfunction failed(observer: Observer, what: string, err: unknown): void {\n // Logged directly, never re-reported: an observer failing inside onError\n // must not loop back into onError. Guarded too: a custom LoggerProvider that\n // throws would otherwise escape reportError() — or, from an async\n // observer, become an unhandled rejection that bootstrap reports right back\n // here.\n try {\n log.error({ err }, `${observer.name ?? 'observer'}.${what} threw — skipped`)\n } catch {\n // Nothing left to tell; reportError's \"never throws\" contract wins.\n }\n}\n\n/**\n * Report an error to every observer. The framework calls this for request\n * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and\n * queue job failures; call it from your own integrations too (a cron runner,\n * a message consumer). Never throws.\n */\nexport function reportError(error: unknown, info: ErrorInfo): void {\n notify((o) => o.onError?.(error, info), 'onError')\n}\n\n/** Report a finished response to every observer. Never throws. */\nexport function reportResponse(info: ResponseInfo): void {\n notify((o) => o.onResponse?.(info), 'onResponse')\n}\n"],"mappings":";;;;;;;;;;4CAiBA,MAAM,IAAM,aAAa,WAAW,EAyCpC,IAAI,UAAiC,CAAC,EAClC,UACA,4BAA+C,GAOnD,SAAgB,aAAa,KAAgD,CAE3E,MADA,WAAY,KAAK,OAAQ,GAAM,EAAE,SAAW,EAAE,UAAU,EACjD,SACT,CAOA,SAAgB,iBAAiB,UAAsC,CACjE,YAAc,YAAW,UAAY,CAAC,EAC5C,CAMA,SAAgB,qBACd,KACA,mBAAsC,GAChC,CACN,UAAY,KACZ,wBAA0B,cAC5B,CAGA,SAAgB,sBAAgC,CAC9C,OAAO,UAAU,KAAM,GAAM,EAAE,UAAU,GAAK,wBAAwB,CACxE,CAEA,SAAS,OAAO,KAAyD,KAAoB,CAC3F,IAAK,IAAM,YAAY,UAAY,CAAC,GAAG,UAAW,SAAS,EAAI,UAC7D,GAAI,CACF,IAAM,OAAS,KAAK,QAAQ,EACxB,QAAU,OAAQ,OAAyB,OAAU,YACtD,OAA0B,MAAO,KAAiB,OAAO,SAAU,KAAM,GAAG,CAAC,CAElF,OAAS,IAAK,CACZ,OAAO,SAAU,KAAM,GAAG,CAC5B,CAEJ,CAEA,SAAS,OAAO,SAAoB,KAAc,IAAoB,CAMpE,GAAI,CACF,IAAI,MAAM,CAAE,GAAI,EAAG,GAAG,SAAS,MAAQ,WAAW,GAAG,KAAK,iBAAiB,CAC7E,MAAQ,CAER,CACF,CAQA,SAAgB,YAAY,MAAgB,KAAuB,CACjE,OAAQ,GAAM,EAAE,UAAU,MAAO,IAAI,EAAG,SAAS,CACnD,CAGA,SAAgB,eAAe,KAA0B,CACvD,OAAQ,GAAM,EAAE,aAAa,IAAI,EAAG,YAAY,CAClD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
const FILTER_OPERATORS=new Set([`eq`,`neq`,`gt`,`gte`,`lt`,`lte`,`between`,`in`,`contains`,`starts`,`ends`]),BUILTIN_DEFAULTS={maxLimit:100,defaultLimit:20,maxSearchLength:200,defaultPage:1},defaults={...BUILTIN_DEFAULTS};function setQueryParsingDefaults(partial){partial.maxLimit!==void 0&&(defaults.maxLimit=partial.maxLimit),partial.defaultLimit!==void 0&&(defaults.defaultLimit=partial.defaultLimit),partial.maxSearchLength!==void 0&&(defaults.maxSearchLength=partial.maxSearchLength)}function getQueryParsingDefaults(){return{...defaults}}function resetQueryParsingDefaults(){Object.assign(defaults,BUILTIN_DEFAULTS)}function parseFilters(filterParam,allowedFields,options){if(!filterParam)return[];let items=Array.isArray(filterParam)?filterParam:[filterParam],results=[],allowed=allowedFields?new Set(allowedFields):null,onReject=options?.onReject;for(let item of items){let firstColon=item.indexOf(`:`);if(firstColon===-1)continue;let secondColon=item.indexOf(`:`,firstColon+1);if(secondColon===-1)continue;let field=item.slice(0,firstColon),operator=item.slice(firstColon+1,secondColon),value=item.slice(secondColon+1);if(field&&value){if(!FILTER_OPERATORS.has(operator)){onReject?.({kind:`filter`,field,reason:`unknown-operator`});continue}if(allowed&&!allowed.has(field)){onReject?.({kind:`filter`,field,reason:`field-not-allowed`});continue}results.push({field,operator,value})}}return results}function parseSort(sortParam,allowedFields,options){if(!sortParam)return[];let items=Array.isArray(sortParam)?sortParam:[sortParam],results=[],allowed=allowedFields?new Set(allowedFields):null,onReject=options?.onReject;for(let item of items){let lastColon=item.lastIndexOf(`:`);if(lastColon===-1)continue;let field=item.slice(0,lastColon),dir=item.slice(lastColon+1).toLowerCase();if(field&&(dir===`asc`||dir===`desc`)){if(allowed&&!allowed.has(field)){onReject?.({kind:`sort`,field,reason:`field-not-allowed`});continue}results.push({field,direction:dir})}}return results}function parsePagination(params,options){let defaultLimit=options?.defaultLimit??defaults.defaultLimit,maxLimit=options?.maxLimit??defaults.maxLimit,page=typeof params.page==`string`?Number.parseInt(params.page,10):params.page??defaults.defaultPage,limit=typeof params.limit==`string`?Number.parseInt(params.limit,10):params.limit??defaultLimit;return(Number.isNaN(page)||page<1)&&(page=defaults.defaultPage),(Number.isNaN(limit)||limit<1)&&(limit=defaultLimit),limit>maxLimit&&(limit=maxLimit),{page,limit,offset:(page-1)*limit}}function parseSearchQuery(q,options){if(!q)return``;let maxLen=options?.maxSearchLength??defaults.maxSearchLength,trimmed=q.trim();return trimmed.length>maxLen?(options?.onReject?.({kind:`search`,field:`q`,reason:`truncated`}),trimmed.slice(0,maxLen)):trimmed}function normalizeFieldConfig(config){if(config)return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:void 0}:config}function parseQuery(query,fieldConfig,options){let normalized=normalizeFieldConfig(fieldConfig),rejectOpts=options?.onReject?{onReject:options.onReject}:void 0;return{filters:parseFilters(query.filter,normalized?.filterable,rejectOpts),sort:parseSort(query.sort,normalized?.sortable,rejectOpts),pagination:parsePagination({page:query.page,limit:query.limit},options),search:parseSearchQuery(query.q,options)}}function buildQueryParams(parsed){let params={};return parsed.filters?.length&&(params.filter=parsed.filters.map(f=>`${f.field}:${f.operator}:${f.value}`)),parsed.sort?.length&&(params.sort=parsed.sort.map(s=>`${s.field}:${s.direction}`)),parsed.pagination&&(params.page=parsed.pagination.page,params.limit=parsed.pagination.limit),parsed.search&&(params.q=parsed.search),params}export{parseQuery as a,resetQueryParsingDefaults as c,parsePagination as i,setQueryParsingDefaults as l,getQueryParsingDefaults as n,parseSearchQuery as o,parseFilters as r,parseSort as s,buildQueryParams as t,FILTER_OPERATORS as u};
|
|
12
|
-
//# sourceMappingURL=query-
|
|
12
|
+
//# sourceMappingURL=query-B5DTq_4W.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-DPlkWOw6.mjs","names":[],"sources":["../src/http/query/types.ts","../src/http/query/parse-query.ts"],"sourcesContent":["/** Supported filter operators for query string parsing */\nexport type FilterOperator =\n | 'eq'\n | 'neq'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'between'\n | 'in'\n | 'contains'\n | 'starts'\n | 'ends'\n\nexport const FILTER_OPERATORS = new Set<string>([\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'between',\n 'in',\n 'contains',\n 'starts',\n 'ends',\n])\n\nexport interface FilterItem {\n field: string\n operator: FilterOperator\n value: string\n}\n\nexport interface SortItem {\n field: string\n direction: 'asc' | 'desc'\n}\n\nexport interface PaginationParams {\n page: number\n limit: number\n offset: number\n}\n\n/**\n * The result of parsing a query string. ORM-agnostic — pass this to\n * a query builder adapter (Drizzle, Prisma, Sequelize, etc.) to produce\n * database-specific query objects.\n */\nexport interface ParsedQuery {\n filters: FilterItem[]\n sort: SortItem[]\n pagination: PaginationParams\n search: string\n}\n\n/**\n * Helper that extracts the literal field union from a `QueryFieldConfig`\n * key. When the user passes `{ filterable: ['status', 'category'] } as const`,\n * `FieldsOf<typeof config, 'filterable'>` resolves to `'status' | 'category'`.\n *\n * Without `as const`, the arrays widen to `string[]` and the union falls\n * back to `string`. This is the documented escape hatch.\n */\nexport type FieldsOf<\n TConfig extends QueryFieldConfig | undefined,\n K extends 'filterable' | 'sortable' | 'searchable',\n> = TConfig extends { readonly [P in K]: readonly (infer F)[] }\n ? F extends string\n ? F\n : string\n : TConfig extends { columns: infer C }\n ? K extends 'filterable'\n ? keyof C & string\n : string\n : string\n\n/**\n * Narrowed `ParsedQuery` whose `filters[].field` and `sort[].field`\n * unions are constrained to the literal whitelist passed to\n * `ctx.qs()` / `parseQuery()`. Extends `ParsedQuery`, so any function\n * accepting `ParsedQuery` accepts a `TypedParsedQuery<X>` automatically\n * (subtype assignment, no codegen, backward compatible).\n *\n * @example\n * ```ts\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt'],\n * } as const)\n * parsed.filters[0]?.field // 'status' | 'priority'\n * parsed.sort[0]?.field // 'createdAt'\n * ```\n */\nexport interface TypedParsedQuery<\n TConfig extends QueryFieldConfig | undefined,\n> extends ParsedQuery {\n filters: Array<FilterItem & { field: FieldsOf<TConfig, 'filterable'> }>\n sort: Array<SortItem & { field: FieldsOf<TConfig, 'sortable'> }>\n}\n\n/**\n * Restrict which fields can be filtered, sorted, or searched.\n * Fields not in the allow-list are silently ignored.\n *\n * Accepts two forms:\n * 1. **String arrays** (standard): `{ filterable: ['name', 'status'], sortable: ['createdAt'] }`\n * 2. **Column-object maps** (Drizzle-style): `{ columns: { name: col, status: col }, sortable: { createdAt: col } }`\n *\n * When column-object maps are provided, `Object.keys()` is used to derive the field names.\n */\nexport type QueryFieldConfig = StringQueryFieldConfig | ColumnQueryFieldConfig\n\nexport interface StringQueryFieldConfig {\n filterable?: string[]\n sortable?: string[]\n searchable?: string[]\n}\n\n/**\n * Column-object-based field config (e.g., from DrizzleQueryParamsConfig).\n * Keys are the field names used in query strings; values are ORM column references.\n */\nexport interface ColumnQueryFieldConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/** Standardized paginated response shape */\nexport interface PaginatedResponse<T = any> {\n data: T[]\n meta: {\n page: number\n limit: number\n total: number\n totalPages: number\n hasNext: boolean\n hasPrev: boolean\n }\n}\n\n/**\n * Interface for ORM-specific query builder adapters.\n * Implement this to translate a `ParsedQuery` into your ORM's query format.\n *\n * @example\n * ```ts\n * // Drizzle adapter\n * class DrizzleQueryAdapter implements QueryBuilderAdapter<DrizzleQueryResult> {\n * build(parsed: ParsedQuery, config: DrizzleConfig): DrizzleQueryResult {\n * // Convert filters → Drizzle SQL conditions\n * // Convert sort → Drizzle orderBy\n * return { where, orderBy, limit, offset }\n * }\n * }\n *\n * // Prisma adapter\n * class PrismaQueryAdapter implements QueryBuilderAdapter<PrismaQueryResult> {\n * build(parsed: ParsedQuery, config: PrismaConfig): PrismaQueryResult {\n * return { where, orderBy, skip, take }\n * }\n * }\n * ```\n */\nexport interface QueryBuilderAdapter<TResult = any, TConfig = any> {\n /** Human-readable name for debugging */\n readonly name: string\n\n /**\n * Convert a ParsedQuery into an ORM-specific query object.\n * @param parsed - The ORM-agnostic parsed query\n * @param config - ORM-specific configuration (column maps, search columns, etc.)\n */\n build(parsed: ParsedQuery, config: TConfig): TResult\n}\n","import {\n FILTER_OPERATORS,\n type FilterItem,\n type FilterOperator,\n type SortItem,\n type PaginationParams,\n type ParsedQuery,\n type QueryFieldConfig,\n type StringQueryFieldConfig,\n type TypedParsedQuery,\n} from './types'\n\n// ── Configurable defaults ───────────────────────────────────────────────\n\n/**\n * Why a rejected field/value was dropped. Surfaced through\n * {@link ParseQueryOptions.onReject} so a caller can warn, count, or\n * return a 400 instead of the historical silent drop.\n */\nexport type QueryRejectReason = 'field-not-allowed' | 'unknown-operator' | 'truncated'\n\nexport interface QueryRejection {\n kind: 'filter' | 'sort' | 'search'\n field: string\n reason: QueryRejectReason\n}\n\nexport interface ParseQueryOptions {\n /** Hard cap on `limit`. Default: global (100, override via {@link setQueryParsingDefaults}). */\n maxLimit?: number\n /** `limit` when the query omits one. Default: global (20). */\n defaultLimit?: number\n /** Max `q` length before truncation. Default: global (200). */\n maxSearchLength?: number\n /**\n * Called once per dropped filter/sort field or truncated search.\n * The historical behaviour is a silent drop; wire this to a logger or\n * a 400 to make over-broad / typo'd queries visible.\n */\n onReject?: (rejection: QueryRejection) => void\n}\n\ninterface QueryParsingDefaults {\n maxLimit: number\n defaultLimit: number\n maxSearchLength: number\n defaultPage: number\n}\n\nconst BUILTIN_DEFAULTS: QueryParsingDefaults = {\n maxLimit: 100,\n defaultLimit: 20,\n maxSearchLength: 200,\n defaultPage: 1,\n}\n\nconst defaults: QueryParsingDefaults = { ...BUILTIN_DEFAULTS }\n\n/**\n * Globally override the query-parsing limits — call once at bootstrap.\n * Per-call {@link ParseQueryOptions} still take precedence over these.\n */\nexport function setQueryParsingDefaults(\n partial: Partial<Omit<QueryParsingDefaults, 'defaultPage'>>,\n): void {\n if (partial.maxLimit !== undefined) defaults.maxLimit = partial.maxLimit\n if (partial.defaultLimit !== undefined) defaults.defaultLimit = partial.defaultLimit\n if (partial.maxSearchLength !== undefined) defaults.maxSearchLength = partial.maxSearchLength\n}\n\n/** Read the current global query-parsing defaults (a copy). */\nexport function getQueryParsingDefaults(): Readonly<QueryParsingDefaults> {\n return { ...defaults }\n}\n\n/**\n * Restore the built-in query-parsing defaults (maxLimit 100, defaultLimit\n * 20, maxSearchLength 200). Useful in test teardown after a\n * {@link setQueryParsingDefaults} override so global state can't leak\n * between tests.\n */\nexport function resetQueryParsingDefaults(): void {\n Object.assign(defaults, BUILTIN_DEFAULTS)\n}\n\n// ── Individual parsers ──────────────────────────────────────────────────\n\n/** Parse filter strings like \"status:eq:active\" into structured objects */\nexport function parseFilters(\n filterParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): FilterItem[] {\n if (!filterParam) return []\n\n const items = Array.isArray(filterParam) ? filterParam : [filterParam]\n const results: FilterItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on first two colons only — value may contain colons (e.g. timestamps)\n const firstColon = item.indexOf(':')\n if (firstColon === -1) continue\n\n const secondColon = item.indexOf(':', firstColon + 1)\n if (secondColon === -1) continue\n\n const field = item.slice(0, firstColon)\n const operator = item.slice(firstColon + 1, secondColon)\n const value = item.slice(secondColon + 1)\n\n if (!field || !value) continue\n if (!FILTER_OPERATORS.has(operator)) {\n onReject?.({ kind: 'filter', field, reason: 'unknown-operator' })\n continue\n }\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'filter', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, operator: operator as FilterOperator, value })\n }\n\n return results\n}\n\n/** Parse sort strings like \"firstName:asc\" into structured objects */\nexport function parseSort(\n sortParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): SortItem[] {\n if (!sortParam) return []\n\n const items = Array.isArray(sortParam) ? sortParam : [sortParam]\n const results: SortItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on last colon so field names with colons work\n const lastColon = item.lastIndexOf(':')\n if (lastColon === -1) continue\n\n const field = item.slice(0, lastColon)\n const dir = item.slice(lastColon + 1).toLowerCase()\n\n if (!field) continue\n if (dir !== 'asc' && dir !== 'desc') continue\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'sort', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, direction: dir })\n }\n\n return results\n}\n\n/** Parse page/limit into pagination with computed offset */\nexport function parsePagination(\n params: {\n page?: string | number\n limit?: string | number\n },\n options?: Pick<ParseQueryOptions, 'maxLimit' | 'defaultLimit'>,\n): PaginationParams {\n const defaultLimit = options?.defaultLimit ?? defaults.defaultLimit\n const maxLimit = options?.maxLimit ?? defaults.maxLimit\n\n let page =\n typeof params.page === 'string'\n ? Number.parseInt(params.page, 10)\n : (params.page ?? defaults.defaultPage)\n let limit =\n typeof params.limit === 'string'\n ? Number.parseInt(params.limit, 10)\n : (params.limit ?? defaultLimit)\n\n if (Number.isNaN(page) || page < 1) page = defaults.defaultPage\n if (Number.isNaN(limit) || limit < 1) limit = defaultLimit\n if (limit > maxLimit) limit = maxLimit\n\n return { page, limit, offset: (page - 1) * limit }\n}\n\n/** Sanitize and truncate search query */\nexport function parseSearchQuery(\n q: string | undefined,\n options?: Pick<ParseQueryOptions, 'maxSearchLength' | 'onReject'>,\n): string {\n if (!q) return ''\n const maxLen = options?.maxSearchLength ?? defaults.maxSearchLength\n const trimmed = q.trim()\n if (trimmed.length > maxLen) {\n options?.onReject?.({ kind: 'search', field: 'q', reason: 'truncated' })\n return trimmed.slice(0, maxLen)\n }\n return trimmed\n}\n\n// ── Config normalizer ───────────────────────────────────────────────────\n\n/**\n * Normalize a QueryFieldConfig into the string-based form.\n * Detects column-object-based configs (DrizzleQueryParamsConfig) by checking\n * for a `columns` property and extracts `Object.keys()`.\n */\nfunction normalizeFieldConfig(config?: QueryFieldConfig): StringQueryFieldConfig | undefined {\n if (!config) return undefined\n\n // Column-object-based config (e.g., DrizzleQueryParamsConfig)\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: undefined, // searchColumns are Column objects, not used for string filtering\n }\n }\n\n // Already string-based\n return config as StringQueryFieldConfig\n}\n\n// ── Combined parser ─────────────────────────────────────────────────────\n\n/**\n * Parse a raw Express query object into a structured, ORM-agnostic ParsedQuery.\n *\n * @param query - Raw query string object from `req.query` or Zod-validated object\n * @param fieldConfig - Optional field restrictions (whitelist filterable/sortable/searchable).\n * Accepts both string-based configs (`{ filterable, sortable, searchable }`) and\n * column-object configs (`{ columns, sortable, searchColumns }`).\n * @param options - Limits + an `onReject` hook for dropped/truncated input.\n *\n * @example\n * ```ts\n * // String-based config\n * const parsed = parseQuery(ctx.query, {\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * })\n *\n * // Column-object config (DrizzleQueryParamsConfig)\n * const parsed = parseQuery(ctx.query, TASK_QUERY_CONFIG)\n * ```\n *\n * Query string format:\n * - Filters: `?filter=field:operator:value` (repeatable)\n * - Sort: `?sort=field:asc|desc` (repeatable)\n * - Pagination: `?page=1&limit=20`\n * - Search: `?q=search+term`\n *\n * Filter operators: eq, neq, gt, gte, lt, lte, between, in, contains, starts, ends\n */\nexport function parseQuery<TConfig extends QueryFieldConfig | undefined = undefined>(\n query: Record<string, any>,\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n): TypedParsedQuery<TConfig> {\n const normalized = normalizeFieldConfig(fieldConfig)\n const rejectOpts = options?.onReject ? { onReject: options.onReject } : undefined\n return {\n filters: parseFilters(query.filter, normalized?.filterable, rejectOpts),\n sort: parseSort(query.sort, normalized?.sortable, rejectOpts),\n pagination: parsePagination({ page: query.page, limit: query.limit }, options),\n search: parseSearchQuery(query.q, options),\n } as TypedParsedQuery<TConfig>\n}\n\n// ── Query URL builder (for client-side or testing) ──────────────────────\n\n/** Convert ParsedQuery back into query string parameters */\nexport function buildQueryParams(\n parsed: Partial<ParsedQuery>,\n): Record<string, string | string[] | number> {\n const params: Record<string, string | string[] | number> = {}\n\n if (parsed.filters?.length) {\n params.filter = parsed.filters.map((f) => `${f.field}:${f.operator}:${f.value}`)\n }\n\n if (parsed.sort?.length) {\n params.sort = parsed.sort.map((s) => `${s.field}:${s.direction}`)\n }\n\n if (parsed.pagination) {\n params.page = parsed.pagination.page\n params.limit = parsed.pagination.limit\n }\n\n if (parsed.search) {\n params.q = parsed.search\n }\n\n return params\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAa,iBAAmB,IAAI,IAAY,CAC9C,KACA,MACA,KACA,MACA,KACA,MACA,UACA,KACA,WACA,SACA,MACF,CAAC,ECuBK,iBAAyC,CAC7C,SAAU,IACV,aAAc,GACd,gBAAiB,IACjB,YAAa,CACf,EAEM,SAAiC,CAAE,GAAG,gBAAiB,EAM7D,SAAgB,wBACd,QACM,CACF,QAAQ,WAAa,IAAA,KAAW,SAAS,SAAW,QAAQ,UAC5D,QAAQ,eAAiB,IAAA,KAAW,SAAS,aAAe,QAAQ,cACpE,QAAQ,kBAAoB,IAAA,KAAW,SAAS,gBAAkB,QAAQ,gBAChF,CAGA,SAAgB,yBAA0D,CACxE,MAAO,CAAE,GAAG,QAAS,CACvB,CAQA,SAAgB,2BAAkC,CAChD,OAAO,OAAO,SAAU,gBAAgB,CAC1C,C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AC3B,IAAM,WAAa,qBAAqB,WAAW,EAC7C,WAAa,SAAS,SAAW,CAAE,SAAU,QAAQ,QAAS,EAAI,IAAA,GACxE,MAAO,CACL,QAAS,aAAa,MAAM,OAAQ,YAAY,WAAY,UAAU,EACtE,KAAM,UAAU,MAAM,KAAM,YAAY,SAAU,UAAU,EAC5D,WAAY,gBAAgB,CAAE,KAAM,MAAM,KAAM,MAAO,MAAM,KAAM,EAAG,OAAO,EAC7E,OAAQ,iBAAiB,MAAM,EAAG,OAAO,CAC3C,CACF,CAKA,SAAgB,iBACd,OAC4C,CAC5C,IAAM,OAAqD,CAAC,EAmB5D,OAjBI,OAAO,SAAS,SAClB,OAAO,OAAS,OAAO,QAAQ,IAAK,GAAM,GAAG,EAAE,MAAM,GAAG,EAAE,SAAS,GAAG,EAAE,OAAO,GAG7E,OAAO,MAAM,SACf,OAAO,KAAO,OAAO,KAAK,IAAK,GAAM,GAAG,EAAE,MAAM,GAAG,EAAE,WAAW,GAG9D,OAAO,aACT,OAAO,KAAO,OAAO,WAAW,KAChC,OAAO,MAAQ,OAAO,WAAW,OAG/B,OAAO,SACT,OAAO,EAAI,OAAO,QAGb,MACT"}
|
|
1
|
+
{"version":3,"file":"query-B5DTq_4W.mjs","names":[],"sources":["../src/http/query/types.ts","../src/http/query/parse-query.ts"],"sourcesContent":["/** Supported filter operators for query string parsing */\nexport type FilterOperator =\n | 'eq'\n | 'neq'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'between'\n | 'in'\n | 'contains'\n | 'starts'\n | 'ends'\n\nexport const FILTER_OPERATORS = new Set<string>([\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'between',\n 'in',\n 'contains',\n 'starts',\n 'ends',\n])\n\nexport interface FilterItem {\n field: string\n operator: FilterOperator\n value: string\n}\n\nexport interface SortItem {\n field: string\n direction: 'asc' | 'desc'\n}\n\nexport interface PaginationParams {\n page: number\n limit: number\n offset: number\n}\n\n/**\n * The result of parsing a query string. ORM-agnostic — pass this to\n * a query builder adapter (Drizzle, Prisma, Sequelize, etc.) to produce\n * database-specific query objects.\n */\nexport interface ParsedQuery {\n filters: FilterItem[]\n sort: SortItem[]\n pagination: PaginationParams\n search: string\n}\n\n/**\n * Helper that extracts the literal field union from a `QueryFieldConfig`\n * key. When the user passes `{ filterable: ['status', 'category'] } as const`,\n * `FieldsOf<typeof config, 'filterable'>` resolves to `'status' | 'category'`.\n *\n * Without `as const`, the arrays widen to `string[]` and the union falls\n * back to `string`. This is the documented escape hatch.\n */\nexport type FieldsOf<\n TConfig extends QueryFieldConfig | undefined,\n K extends 'filterable' | 'sortable' | 'searchable',\n> = TConfig extends { readonly [P in K]: readonly (infer F)[] }\n ? F extends string\n ? F\n : string\n : TConfig extends { columns: infer C }\n ? K extends 'filterable'\n ? keyof C & string\n : string\n : string\n\n/**\n * Narrowed `ParsedQuery` whose `filters[].field` and `sort[].field`\n * unions are constrained to the literal whitelist passed to\n * `ctx.qs()` / `parseQuery()`. Extends `ParsedQuery`, so any function\n * accepting `ParsedQuery` accepts a `TypedParsedQuery<X>` automatically\n * (subtype assignment, no codegen, backward compatible).\n *\n * @example\n * ```ts\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt'],\n * } as const)\n * parsed.filters[0]?.field // 'status' | 'priority'\n * parsed.sort[0]?.field // 'createdAt'\n * ```\n */\nexport interface TypedParsedQuery<\n TConfig extends QueryFieldConfig | undefined,\n> extends ParsedQuery {\n filters: Array<FilterItem & { field: FieldsOf<TConfig, 'filterable'> }>\n sort: Array<SortItem & { field: FieldsOf<TConfig, 'sortable'> }>\n}\n\n/**\n * Restrict which fields can be filtered, sorted, or searched.\n * Fields not in the allow-list are silently ignored.\n *\n * Accepts two forms:\n * 1. **String arrays** (standard): `{ filterable: ['name', 'status'], sortable: ['createdAt'] }`\n * 2. **Column-object maps** (Drizzle-style): `{ columns: { name: col, status: col }, sortable: { createdAt: col } }`\n *\n * When column-object maps are provided, `Object.keys()` is used to derive the field names.\n */\nexport type QueryFieldConfig = StringQueryFieldConfig | ColumnQueryFieldConfig\n\nexport interface StringQueryFieldConfig {\n filterable?: string[]\n sortable?: string[]\n searchable?: string[]\n}\n\n/**\n * Column-object-based field config (e.g., from DrizzleQueryParamsConfig).\n * Keys are the field names used in query strings; values are ORM column references.\n */\nexport interface ColumnQueryFieldConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/** Standardized paginated response shape */\nexport interface PaginatedResponse<T = any> {\n data: T[]\n meta: {\n page: number\n limit: number\n total: number\n totalPages: number\n hasNext: boolean\n hasPrev: boolean\n }\n}\n\n/**\n * Interface for ORM-specific query builder adapters.\n * Implement this to translate a `ParsedQuery` into your ORM's query format.\n *\n * @example\n * ```ts\n * // Drizzle adapter\n * class DrizzleQueryAdapter implements QueryBuilderAdapter<DrizzleQueryResult> {\n * build(parsed: ParsedQuery, config: DrizzleConfig): DrizzleQueryResult {\n * // Convert filters → Drizzle SQL conditions\n * // Convert sort → Drizzle orderBy\n * return { where, orderBy, limit, offset }\n * }\n * }\n *\n * // Prisma adapter\n * class PrismaQueryAdapter implements QueryBuilderAdapter<PrismaQueryResult> {\n * build(parsed: ParsedQuery, config: PrismaConfig): PrismaQueryResult {\n * return { where, orderBy, skip, take }\n * }\n * }\n * ```\n */\nexport interface QueryBuilderAdapter<TResult = any, TConfig = any> {\n /** Human-readable name for debugging */\n readonly name: string\n\n /**\n * Convert a ParsedQuery into an ORM-specific query object.\n * @param parsed - The ORM-agnostic parsed query\n * @param config - ORM-specific configuration (column maps, search columns, etc.)\n */\n build(parsed: ParsedQuery, config: TConfig): TResult\n}\n","import {\n FILTER_OPERATORS,\n type FilterItem,\n type FilterOperator,\n type SortItem,\n type PaginationParams,\n type ParsedQuery,\n type QueryFieldConfig,\n type StringQueryFieldConfig,\n type TypedParsedQuery,\n} from './types'\n\n// ── Configurable defaults ───────────────────────────────────────────────\n\n/**\n * Why a rejected field/value was dropped. Surfaced through\n * {@link ParseQueryOptions.onReject} so a caller can warn, count, or\n * return a 400 instead of the historical silent drop.\n */\nexport type QueryRejectReason = 'field-not-allowed' | 'unknown-operator' | 'truncated'\n\nexport interface QueryRejection {\n kind: 'filter' | 'sort' | 'search'\n field: string\n reason: QueryRejectReason\n}\n\nexport interface ParseQueryOptions {\n /** Hard cap on `limit`. Default: global (100, override via {@link setQueryParsingDefaults}). */\n maxLimit?: number\n /** `limit` when the query omits one. Default: global (20). */\n defaultLimit?: number\n /** Max `q` length before truncation. Default: global (200). */\n maxSearchLength?: number\n /**\n * Called once per dropped filter/sort field or truncated search.\n * The historical behaviour is a silent drop; wire this to a logger or\n * a 400 to make over-broad / typo'd queries visible.\n */\n onReject?: (rejection: QueryRejection) => void\n}\n\ninterface QueryParsingDefaults {\n maxLimit: number\n defaultLimit: number\n maxSearchLength: number\n defaultPage: number\n}\n\nconst BUILTIN_DEFAULTS: QueryParsingDefaults = {\n maxLimit: 100,\n defaultLimit: 20,\n maxSearchLength: 200,\n defaultPage: 1,\n}\n\nconst defaults: QueryParsingDefaults = { ...BUILTIN_DEFAULTS }\n\n/**\n * Globally override the query-parsing limits — call once at bootstrap.\n * Per-call {@link ParseQueryOptions} still take precedence over these.\n */\nexport function setQueryParsingDefaults(\n partial: Partial<Omit<QueryParsingDefaults, 'defaultPage'>>,\n): void {\n if (partial.maxLimit !== undefined) defaults.maxLimit = partial.maxLimit\n if (partial.defaultLimit !== undefined) defaults.defaultLimit = partial.defaultLimit\n if (partial.maxSearchLength !== undefined) defaults.maxSearchLength = partial.maxSearchLength\n}\n\n/** Read the current global query-parsing defaults (a copy). */\nexport function getQueryParsingDefaults(): Readonly<QueryParsingDefaults> {\n return { ...defaults }\n}\n\n/**\n * Restore the built-in query-parsing defaults (maxLimit 100, defaultLimit\n * 20, maxSearchLength 200). Useful in test teardown after a\n * {@link setQueryParsingDefaults} override so global state can't leak\n * between tests.\n */\nexport function resetQueryParsingDefaults(): void {\n Object.assign(defaults, BUILTIN_DEFAULTS)\n}\n\n// ── Individual parsers ──────────────────────────────────────────────────\n\n/** Parse filter strings like \"status:eq:active\" into structured objects */\nexport function parseFilters(\n filterParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): FilterItem[] {\n if (!filterParam) return []\n\n const items = Array.isArray(filterParam) ? filterParam : [filterParam]\n const results: FilterItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on first two colons only — value may contain colons (e.g. timestamps)\n const firstColon = item.indexOf(':')\n if (firstColon === -1) continue\n\n const secondColon = item.indexOf(':', firstColon + 1)\n if (secondColon === -1) continue\n\n const field = item.slice(0, firstColon)\n const operator = item.slice(firstColon + 1, secondColon)\n const value = item.slice(secondColon + 1)\n\n if (!field || !value) continue\n if (!FILTER_OPERATORS.has(operator)) {\n onReject?.({ kind: 'filter', field, reason: 'unknown-operator' })\n continue\n }\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'filter', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, operator: operator as FilterOperator, value })\n }\n\n return results\n}\n\n/** Parse sort strings like \"firstName:asc\" into structured objects */\nexport function parseSort(\n sortParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): SortItem[] {\n if (!sortParam) return []\n\n const items = Array.isArray(sortParam) ? sortParam : [sortParam]\n const results: SortItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on last colon so field names with colons work\n const lastColon = item.lastIndexOf(':')\n if (lastColon === -1) continue\n\n const field = item.slice(0, lastColon)\n const dir = item.slice(lastColon + 1).toLowerCase()\n\n if (!field) continue\n if (dir !== 'asc' && dir !== 'desc') continue\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'sort', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, direction: dir })\n }\n\n return results\n}\n\n/** Parse page/limit into pagination with computed offset */\nexport function parsePagination(\n params: {\n page?: string | number\n limit?: string | number\n },\n options?: Pick<ParseQueryOptions, 'maxLimit' | 'defaultLimit'>,\n): PaginationParams {\n const defaultLimit = options?.defaultLimit ?? defaults.defaultLimit\n const maxLimit = options?.maxLimit ?? defaults.maxLimit\n\n let page =\n typeof params.page === 'string'\n ? Number.parseInt(params.page, 10)\n : (params.page ?? defaults.defaultPage)\n let limit =\n typeof params.limit === 'string'\n ? Number.parseInt(params.limit, 10)\n : (params.limit ?? defaultLimit)\n\n if (Number.isNaN(page) || page < 1) page = defaults.defaultPage\n if (Number.isNaN(limit) || limit < 1) limit = defaultLimit\n if (limit > maxLimit) limit = maxLimit\n\n return { page, limit, offset: (page - 1) * limit }\n}\n\n/** Sanitize and truncate search query */\nexport function parseSearchQuery(\n q: string | undefined,\n options?: Pick<ParseQueryOptions, 'maxSearchLength' | 'onReject'>,\n): string {\n if (!q) return ''\n const maxLen = options?.maxSearchLength ?? defaults.maxSearchLength\n const trimmed = q.trim()\n if (trimmed.length > maxLen) {\n options?.onReject?.({ kind: 'search', field: 'q', reason: 'truncated' })\n return trimmed.slice(0, maxLen)\n }\n return trimmed\n}\n\n// ── Config normalizer ───────────────────────────────────────────────────\n\n/**\n * Normalize a QueryFieldConfig into the string-based form.\n * Detects column-object-based configs (DrizzleQueryParamsConfig) by checking\n * for a `columns` property and extracts `Object.keys()`.\n */\nfunction normalizeFieldConfig(config?: QueryFieldConfig): StringQueryFieldConfig | undefined {\n if (!config) return undefined\n\n // Column-object-based config (e.g., DrizzleQueryParamsConfig)\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: undefined, // searchColumns are Column objects, not used for string filtering\n }\n }\n\n // Already string-based\n return config as StringQueryFieldConfig\n}\n\n// ── Combined parser ─────────────────────────────────────────────────────\n\n/**\n * Parse a raw Express query object into a structured, ORM-agnostic ParsedQuery.\n *\n * @param query - Raw query string object from `req.query` or Zod-validated object\n * @param fieldConfig - Optional field restrictions (whitelist filterable/sortable/searchable).\n * Accepts both string-based configs (`{ filterable, sortable, searchable }`) and\n * column-object configs (`{ columns, sortable, searchColumns }`).\n * @param options - Limits + an `onReject` hook for dropped/truncated input.\n *\n * @example\n * ```ts\n * // String-based config\n * const parsed = parseQuery(ctx.query, {\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * })\n *\n * // Column-object config (DrizzleQueryParamsConfig)\n * const parsed = parseQuery(ctx.query, TASK_QUERY_CONFIG)\n * ```\n *\n * Query string format:\n * - Filters: `?filter=field:operator:value` (repeatable)\n * - Sort: `?sort=field:asc|desc` (repeatable)\n * - Pagination: `?page=1&limit=20`\n * - Search: `?q=search+term`\n *\n * Filter operators: eq, neq, gt, gte, lt, lte, between, in, contains, starts, ends\n */\nexport function parseQuery<TConfig extends QueryFieldConfig | undefined = undefined>(\n query: Record<string, any>,\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n): TypedParsedQuery<TConfig> {\n const normalized = normalizeFieldConfig(fieldConfig)\n const rejectOpts = options?.onReject ? { onReject: options.onReject } : undefined\n return {\n filters: parseFilters(query.filter, normalized?.filterable, rejectOpts),\n sort: parseSort(query.sort, normalized?.sortable, rejectOpts),\n pagination: parsePagination({ page: query.page, limit: query.limit }, options),\n search: parseSearchQuery(query.q, options),\n } as TypedParsedQuery<TConfig>\n}\n\n// ── Query URL builder (for client-side or testing) ──────────────────────\n\n/** Convert ParsedQuery back into query string parameters */\nexport function buildQueryParams(\n parsed: Partial<ParsedQuery>,\n): Record<string, string | string[] | number> {\n const params: Record<string, string | string[] | number> = {}\n\n if (parsed.filters?.length) {\n params.filter = parsed.filters.map((f) => `${f.field}:${f.operator}:${f.value}`)\n }\n\n if (parsed.sort?.length) {\n params.sort = parsed.sort.map((s) => `${s.field}:${s.direction}`)\n }\n\n if (parsed.pagination) {\n params.page = parsed.pagination.page\n params.limit = parsed.pagination.limit\n }\n\n if (parsed.search) {\n params.q = parsed.search\n }\n\n return params\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAa,iBAAmB,IAAI,IAAY,CAC9C,KACA,MACA,KACA,MACA,KACA,MACA,UACA,KACA,WACA,SACA,MACF,CAAC,ECuBK,iBAAyC,CAC7C,SAAU,IACV,aAAc,GACd,gBAAiB,IACjB,YAAa,CACf,EAEM,SAAiC,CAAE,GAAG,gBAAiB,EAM7D,SAAgB,wBACd,QACM,CACF,QAAQ,WAAa,IAAA,KAAW,SAAS,SAAW,QAAQ,UAC5D,QAAQ,eAAiB,IAAA,KAAW,SAAS,aAAe,QAAQ,cACpE,QAAQ,kBAAoB,IAAA,KAAW,SAAS,gBAAkB,QAAQ,gBAChF,CAGA,SAAgB,yBAA0D,CACxE,MAAO,CAAE,GAAG,QAAS,CACvB,CAQA,SAAgB,2BAAkC,CAChD,OAAO,OAAO,SAAU,gBAAgB,CAC1C,CAKA,SAAgB,aACd,YACA,cACA,QACc,CACd,GAAI,CAAC,YAAa,MAAO,CAAC,EAE1B,IAAM,MAAQ,MAAM,QAAQ,WAAW,EAAI,YAAc,CAAC,WAAW,EAC/D,QAAwB,CAAC,EACzB,QAAU,cAAgB,IAAI,IAAI,aAAa,EAAI,KACnD,SAAW,SAAS,SAE1B,IAAK,IAAM,QAAQ,MAAO,CAExB,IAAM,WAAa,KAAK,QAAQ,GAAG,EACnC,GAAI,aAAe,GAAI,SAEvB,IAAM,YAAc,KAAK,QAAQ,IAAK,WAAa,CAAC,EACpD,GAAI,cAAgB,GAAI,SAExB,IAAM,MAAQ,KAAK,MAAM,EAAG,UAAU,EAChC,SAAW,KAAK,MAAM,WAAa,EAAG,WAAW,EACjD,MAAQ,KAAK,MAAM,YAAc,CAAC,EAEpC,GAAC,OAAU,MACf,IAAI,CAAC,iBAAiB,IAAI,QAAQ,EAAG,CACnC,WAAW,CAAE,KAAM,SAAU,MAA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AAW,GAG9D,OAAO,aACT,OAAO,KAAO,OAAO,WAAW,KAChC,OAAO,MAAQ,OAAO,WAAW,OAG/B,OAAO,SACT,OAAO,EAAI,OAAO,QAGb,MACT"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{METADATA}from"./core/interfaces.mjs";import{createLogger}from"./core/logger.mjs";import{n as getClassMetaOrUndefined}from"./metadata-CzzRUnAx.mjs";import{HttpException}from"./core/errors.mjs";import{d as requestStore}from"./context-gpvcMlG5.mjs";function normalizeMediaType(contentType){return((Array.isArray(contentType)?contentType[0]:contentType)??``).split(`;`)[0].trim().toLowerCase()}function isJsonMediaType(mediaType){return mediaType===`application/json`||/^application\/[\w.+-]+\+json$/.test(mediaType)}function classifyMediaType(contentType){let mediaType=normalizeMediaType(contentType);return mediaType?isJsonMediaType(mediaType)?`json`:mediaType===`application/x-www-form-urlencoded`?`urlencoded`:mediaType.startsWith(`multipart/`)?`multipart`:mediaType.startsWith(`text/`)?`text`:`unsupported`:`unsupported`}const EXPRESS_JSON_TYPES=[`application/json`,`application/*+json`],SUPPORTED_BODY_TYPES=[`application/json`,`application/*+json`,`application/x-www-form-urlencoded`,`text/*`,`multipart/form-data`];function unsupportedMediaTypeError(contentType){let mediaType=normalizeMediaType(contentType);return new HttpException(415,mediaType?`Unsupported Media Type: ${mediaType}`:`Unsupported Media Type: request has a body but no Content-Type`,void 0,{Accept:SUPPORTED_BODY_TYPES.join(`, `)})}const BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);function rejectUnsupportedBody(){return(req,_res,next)=>{if(!BODY_METHODS.has((req.method??`GET`).toUpperCase())||classifyMediaType(req.headers?.[`content-type`])!==`unsupported`)return next();let reject=()=>next(unsupportedMediaTypeError(req.headers?.[`content-type`])),length=req.headers?.[`content-length`];if(length!==void 0)return length===`0`?next():reject();if(req.headers?.[`transfer-encoding`]===void 0)return next();let decided=!1,settle=fn=>()=>{decided||(decided=!0,req.off?.(`data`,onData),req.off?.(`end`,onEnd),fn())},onData=settle(reject),onEnd=settle(()=>next());req.on?.(`data`,onData),req.on?.(`end`,onEnd)}}const log=createLogger(`RequestScope`),preDestroyCache=new Map;function preDestroyMethod(ctor){let method=preDestroyCache.get(ctor);return method===void 0&&(method=getClassMetaOrUndefined(METADATA.PRE_DESTROY,ctor.prototype)??null,preDestroyCache.set(ctor,method)),method}function disposeRequestStore(store){if(!store.disposed&&(store.disposed=!0,store.instances.size!==0)){for(let instance of store.instances.values()){if(typeof instance!=`object`||!instance)continue;let method=preDestroyMethod(instance.constructor);if(method&&typeof instance[method]==`function`)try{let result=instance[method]();result&&typeof result.then==`function`&&result.catch(err=>log.error(err,`@PreDestroy on ${instance.constructor.name} rejected`))}catch(err){log.error(err,`@PreDestroy on ${instance.constructor.name} threw`)}}store.instances.clear()}}const REQUEST_SCOPE_MIDDLEWARE_MARKER=Symbol.for(`@kickjs/requestScopeMiddleware`);function createRequestStore(requestId){return{requestId:requestId||crypto.randomUUID(),instances:new Map,values:new Map}}function requestScopeMiddleware(){let mw=(req,res,next)=>{let requestIdHeader=req.headers[`x-request-id`],requestId=(Array.isArray(requestIdHeader)?requestIdHeader[0]:requestIdHeader)||crypto.randomUUID(),store=createRequestStore(requestId);req.requestId=requestId,res.once(`close`,()=>disposeRequestStore(store)),requestStore.run(store,next)};return mw[REQUEST_SCOPE_MIDDLEWARE_MARKER]=!0,mw}function isRequestScopeMiddleware(value){return typeof value==`function`&&value[REQUEST_SCOPE_MIDDLEWARE_MARKER]===!0}const REPLY_BRAND=Symbol.for(`kickjs.reply`);function reply(status,body){return{[REPLY_BRAND]:!0,status,body}}reply.ok=body=>reply(200,body),reply.created=body=>reply(201,body),reply.accepted=body=>reply(202,body),reply.noContent=()=>reply(204,void 0);function isReply(value){return typeof value==`object`&&!!value&&value[REPLY_BRAND]===!0}function applyHandlerResult(ctx,result){return result===void 0?!1:isReply(result)?result.status===204?(ctx.noContent(),!0):(ctx.json(result.body,result.status),!0):(ctx.json(result),!0)}export{disposeRequestStore as a,EXPRESS_JSON_TYPES as c,unsupportedMediaTypeError as d,createRequestStore as i,classifyMediaType as l,isReply as n,isRequestScopeMiddleware as o,reply as r,requestScopeMiddleware as s,applyHandlerResult as t,rejectUnsupportedBody as u};
|
|
12
|
+
//# sourceMappingURL=reply-CbTYIj_e.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reply-CbTYIj_e.mjs","names":[],"sources":["../src/http/body-policy.ts","../src/http/middleware/request-scope.ts","../src/http/reply.ts"],"sourcesContent":["/**\n * How a request body is interpreted, decided in ONE place for every runtime.\n *\n * Before this, each engine brought its own library's opinion: Express parsed\n * only exact `application/json` and silently left everything else `undefined`,\n * Fastify answered 415 for anything it had no parser for, and h3 routed\n * unrecognised types through `destr` — so the same request produced a parsed\n * object, an empty body, or a 415 depending on which engine the app was\n * configured with. The runtime is meant to be swappable; that made it not\n * swappable for any app accepting a body outside `application/json` (#590).\n *\n * @module @forinda/kickjs/http/body-policy\n */\n\nimport { HttpException } from '../core/errors'\n\n/**\n * A header as the runtimes hand it over. Node's `IncomingHttpHeaders` and\n * Fastify's normalised map both allow `string[]`, so take the union here\n * rather than casting at every call site.\n */\nexport type HeaderValue = string | string[] | undefined\n\n/** What the framework does with a body of a given media type. */\nexport type BodyKind =\n /** Parse as JSON, strictly. */\n | 'json'\n /** Parse as `application/x-www-form-urlencoded` into an object. */\n | 'urlencoded'\n /** Hand the handler the raw string. Never JSON — see `classifyMediaType`. */\n | 'text'\n /** Left to the upload path, which consumes the stream itself. */\n | 'multipart'\n /** Not parsed. `ctx.body` stays undefined. */\n | 'unsupported'\n\n/**\n * Strip parameters and normalise: `Application/JSON; charset=utf-8` →\n * `application/json`. h3's own check is `===` against the bare type, which is\n * why `application/json; charset=utf-8` — what most clients actually send —\n * missed it and fell to a non-strict branch.\n */\nexport function normalizeMediaType(contentType: HeaderValue): string {\n const value = Array.isArray(contentType) ? contentType[0] : contentType\n return (value ?? '').split(';')[0].trim().toLowerCase()\n}\n\n/**\n * `application/*+json` is JSON, and this is not a judgement call: RFC 6838\n * §4.2.8 says a media type \"MUST NOT be given names incorporating suffixes for\n * structured syntaxes they do not actually employ\", and RFC 6839 §2 exists so\n * receivers can \"do generic processing of the underlying representation\".\n * Spring, ASP.NET Core and Hono's validator all match the suffix by default.\n *\n * So `application/merge-patch+json` (RFC 7396) and `application/problem+json`\n * (RFC 9457) parse as JSON — which the framework already emits for every\n * problem response, and previously could not read back.\n */\nfunction isJsonMediaType(mediaType: string): boolean {\n return mediaType === 'application/json' || /^application\\/[\\w.+-]+\\+json$/.test(mediaType)\n}\n\n/**\n * Decide how to treat a body, from its declared media type alone.\n *\n * `text/*` deliberately yields the raw string and is NEVER JSON-parsed.\n * `text/plain` is one of three CORS-safelisted content types, so it crosses\n * origins without a preflight; JSON-parsing it would re-open the simple-request\n * CSRF that requiring `application/json` closes. h3's own source carries this\n * warning, and h3 v2 pulled back from `destr` partly because of it.\n */\nexport function classifyMediaType(contentType: HeaderValue): BodyKind {\n const mediaType = normalizeMediaType(contentType)\n if (!mediaType) return 'unsupported'\n if (isJsonMediaType(mediaType)) return 'json'\n if (mediaType === 'application/x-www-form-urlencoded') return 'urlencoded'\n if (mediaType.startsWith('multipart/')) return 'multipart'\n if (mediaType.startsWith('text/')) return 'text'\n return 'unsupported'\n}\n\n/**\n * Media types Express should hand to its JSON body parser. `express.json()`\n * defaults to the exact string `application/json`, and `type-is` will not match\n * `application/json` against a bare wildcard-plus-json pattern (a length guard rejects\n * it), so BOTH entries are required — passing only the wildcard silently stops\n * parsing ordinary JSON.\n */\nexport const EXPRESS_JSON_TYPES = ['application/json', 'application/*+json'] as const\n\n/** Media types the framework claims to parse, for diagnostics and docs. */\nexport const SUPPORTED_BODY_TYPES = [\n 'application/json',\n 'application/*+json',\n 'application/x-www-form-urlencoded',\n 'text/*',\n 'multipart/form-data',\n] as const\n\n/**\n * The 415 for a body whose media type the framework does not parse.\n *\n * Only ever raised when a body was actually SENT. An absent or empty body is\n * treated as absent regardless of its declared type — the same call Spring's\n * `readWithMessageConverters` and ASP.NET's `BodyModelBinder` both make, and\n * the reason neither rejects a bodyless POST. A bare `POST` with no payload is\n * a legitimate request, not an unsupported one.\n *\n * Carries `Accept`, which RFC 9110 §15.5.16 says a 415 \"can\" use to indicate\n * which media types would have been accepted.\n */\nexport function unsupportedMediaTypeError(contentType: HeaderValue): HttpException {\n const mediaType = normalizeMediaType(contentType)\n return new HttpException(\n 415,\n mediaType\n ? `Unsupported Media Type: ${mediaType}`\n : 'Unsupported Media Type: request has a body but no Content-Type',\n undefined,\n { Accept: SUPPORTED_BODY_TYPES.join(', ') },\n )\n}\n\n/** Verbs whose body the framework reads. */\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Did this request actually carry a body? Decided from the framing headers\n * rather than from whether a parser produced anything — the distinction that\n * separates \"nothing was sent\" from \"something was sent that we could not\n * read\", which is the whole basis for answering 415 on one and 200 on the other.\n */\nexport function hasRequestBody(headers: Record<string, unknown>): boolean {\n const length = headers['content-length'] as string | undefined\n const encoding = headers['transfer-encoding'] as string | undefined\n return encoding !== undefined || (length !== undefined && length !== '0')\n}\n\n/**\n * Connect middleware that answers 415 for a body Express's parsers left\n * untouched.\n *\n * Express has no concept of an unsupported type: a parser whose `type` does not\n * match simply calls `next()` and leaves `req.body` undefined, indistinguishable\n * from a request that sent nothing. Mounted after the parsers, this restores the\n * distinction so Express agrees with the other runtimes.\n */\nexport function rejectUnsupportedBody() {\n return (req: any, _res: unknown, next: (err?: unknown) => void): void => {\n if (!BODY_METHODS.has((req.method ?? 'GET').toUpperCase())) return next()\n if (classifyMediaType(req.headers?.['content-type']) !== 'unsupported') return next()\n\n const reject = (): void => next(unsupportedMediaTypeError(req.headers?.['content-type']))\n const length = req.headers?.['content-length'] as string | undefined\n if (length !== undefined) return length === '0' ? next() : reject()\n if (req.headers?.['transfer-encoding'] === undefined) return next()\n\n // Chunked: the framing headers say a body MAY follow, but an empty chunked\n // post sends none. Deciding on the headers alone would 415 a request that\n // sent nothing, so wait to see whether a byte actually arrives — the same\n // distinction the other runtimes make by inspecting the read body.\n let decided = false\n const settle = (fn: () => void) => (): void => {\n if (decided) return\n decided = true\n req.off?.('data', onData)\n req.off?.('end', onEnd)\n fn()\n }\n const onData = settle(reject)\n const onEnd = settle(() => next())\n req.on?.('data', onData)\n req.on?.('end', onEnd)\n }\n}\n","// Web Crypto via globalThis.crypto (randomUUID) — portable across\n// node/bun/deno/workers; node:crypto deliberately NOT imported here so this\n// module stays on the edge-safe request path.\nimport type { Request, Response, NextFunction } from 'express'\nimport { requestStore, type RequestStore } from '../request-store'\nimport { METADATA } from '../../core/interfaces'\nimport { getClassMetaOrUndefined } from '../../core/metadata'\nimport { createLogger } from '../../core/logger'\n\nconst log = createLogger('RequestScope')\n\n// Per-class @PreDestroy method-name cache: the metadata is immutable after\n// class definition, so pay the Reflect read once per class, not once per\n// instance per request. `null` = \"checked, none declared\".\nconst preDestroyCache = new Map<Function, string | symbol | null>()\n\nfunction preDestroyMethod(ctor: Function): string | symbol | null {\n let method = preDestroyCache.get(ctor)\n if (method === undefined) {\n method =\n getClassMetaOrUndefined<string | symbol>(METADATA.PRE_DESTROY, (ctor as any).prototype) ??\n null\n preDestroyCache.set(ctor, method)\n }\n return method\n}\n\n/**\n * Run `@PreDestroy` hooks on every REQUEST-scoped instance the request\n * created, then drop them. Called when the response closes (finished or\n * aborted) — the counterpart to `@PostConstruct`, closing the lifecycle gap\n * where per-request services holding transactions/handles/subscriptions were\n * silently dropped with no cleanup callback.\n *\n * Idempotent (guarded by `store.disposed`); hook errors are logged and\n * swallowed so one failing teardown can't break request completion. Async\n * hooks are fired without being awaited — the response is already gone.\n */\nexport function disposeRequestStore(store: RequestStore): void {\n if (store.disposed) return\n store.disposed = true\n if (store.instances.size === 0) return\n for (const instance of store.instances.values()) {\n if (instance === null || typeof instance !== 'object') continue\n const method = preDestroyMethod(instance.constructor)\n if (!method || typeof instance[method] !== 'function') continue\n try {\n const result = instance[method]()\n if (result && typeof result.then === 'function') {\n ;(result as Promise<void>).catch((err) =>\n log.error(err, `@PreDestroy on ${instance.constructor.name} rejected`),\n )\n }\n } catch (err) {\n log.error(err, `@PreDestroy on ${instance.constructor.name} threw`)\n }\n }\n store.instances.clear()\n}\n\n/**\n * Marker symbol stamped on the function returned by {@link requestScopeMiddleware}.\n *\n * `Application.setup()` uses {@link isRequestScopeMiddleware} to detect whether\n * the user-supplied middleware list already contains the request-scope wrapper,\n * and skips its automatic auto-mount when one is found. Lets adopters control\n * the exact position of the ALS frame in their pipeline (e.g., after a custom\n * tracing wrapper) without ending up with two nested frames.\n */\n// `Symbol.for(...)` returns a plain `symbol` (not `unique symbol`), but the\n// runtime detection marker doesn't need the unique nominal property — it only\n// needs the interned-slot reference equality that `Symbol.for` already provides.\nconst REQUEST_SCOPE_MIDDLEWARE_MARKER = Symbol.for('@kickjs/requestScopeMiddleware')\n\n/**\n * Build a fresh per-request store. Shared by {@link requestScopeMiddleware}\n * (Express) and by runtimes whose handler runs outside the connect-middleware\n * chain (e.g. Fastify), so both establish an identical ALS frame.\n */\nexport function createRequestStore(requestId?: string): RequestStore {\n return {\n requestId: requestId || crypto.randomUUID(),\n instances: new Map(),\n // Explicit generic locks the \"string keys only\" decision.\n values: new Map<string, unknown>(),\n }\n}\n\n/**\n * Wraps each request in an AsyncLocalStorage context.\n * Enables REQUEST-scoped DI and automatic requestId propagation to logs.\n *\n * Should be mounted early in the middleware pipeline (before route handlers).\n * `Application` mounts this automatically unless `contextStore: 'manual'` is set\n * or the user already includes one in their middleware list.\n */\nexport function requestScopeMiddleware() {\n const mw = (req: Request, res: Response, next: NextFunction) => {\n const requestIdHeader = req.headers['x-request-id']\n const requestId =\n (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID()\n const store = createRequestStore(requestId)\n // Surface the requestId on req so the standalone requestId() middleware\n // (when also mounted) reuses this value instead of generating a divergent\n // second one. Without this, log lines that read from the ALS store would\n // disagree with the X-Request-Id response header for any request that\n // didn't carry an inbound x-request-id header.\n ;(req as Request & { requestId?: string }).requestId = requestId\n // 'close' fires once the response finished OR the client aborted — run\n // @PreDestroy teardown for the request's scoped instances either way.\n res.once('close', () => disposeRequestStore(store))\n // Pass `next` directly — `run` invokes it with no args, so the arrow\n // wrapper previously allocated per request added nothing.\n requestStore.run(store, next)\n }\n ;(mw as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] = true\n return mw\n}\n\n/**\n * Returns `true` when `value` is the function produced by {@link requestScopeMiddleware}.\n *\n * Detection uses a `Symbol.for(...)` marker so the check survives different\n * copies of `@forinda/kickjs` loaded under different module identities (e.g.,\n * a published package alongside a workspace-linked one during local dev).\n */\nexport function isRequestScopeMiddleware(value: unknown): boolean {\n if (typeof value !== 'function') return false\n return (value as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] === true\n}\n","// Return-value handler support.\n//\n// Handlers may RETURN their response payload instead of calling `ctx.json`:\n// the runtime auto-sends it when the pipeline finishes with nothing written.\n// `reply(status, body)` wraps a payload with a non-200 status while staying\n// transparent to type inference (`Reply<201, Task>` carries both statically).\n//\n// Edge-safe: no node imports — shared by all four runtimes including the\n// `@forinda/kickjs/web` entry.\n\nimport type { RequestContext } from './context'\nimport type { RuntimeResponse } from './runtime'\n\n// `Symbol.for` so the brand survives duplicate module copies (workspace-linked\n// + published package in one process — same rationale as the request-scope\n// middleware marker).\nconst REPLY_BRAND = Symbol.for('kickjs.reply')\n\n/**\n * A status-carrying response payload for return-value handlers. Create via\n * {@link reply} — the brand is what runtimes detect, and the generics are\n * what the `kick/routes` response typegen unwraps (`Reply<S, T>` → `T`).\n */\nexport interface Reply<S extends number = number, T = unknown> {\n readonly [REPLY_BRAND]: true\n readonly status: S\n readonly body: T\n}\n\n/**\n * Wrap a return-value handler's payload with an explicit status code:\n *\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * return reply(201, await this.tasks.create(ctx.body))\n * }\n * ```\n */\nexport function reply<S extends number, T>(status: S, body: T): Reply<S, T> {\n return { [REPLY_BRAND]: true, status, body }\n}\n\n/** `reply(200, body)` — explicit form of a bare `return body`. */\nreply.ok = <T>(body: T): Reply<200, T> => reply(200, body)\n/** `reply(201, body)` */\nreply.created = <T>(body: T): Reply<201, T> => reply(201, body)\n/** `reply(202, body)` */\nreply.accepted = <T>(body: T): Reply<202, T> => reply(202, body)\n/** Empty 204 — maps to `ctx.noContent()`. */\nreply.noContent = (): Reply<204, undefined> => reply(204, undefined)\n\n/**\n * The statically-inferred response type of a controller handler — what\n * `kick typegen` emits into `KickRoutes[...].response`:\n *\n * - `Awaited<ReturnType>` of the method\n * - `Reply<S, T>` unwraps to `T`\n * - `void`/`undefined` members are dropped (imperative `ctx.json` branches);\n * a handler that never returns a value stays `unknown`, matching the\n * pre-inference emission\n *\n * ```ts\n * type R = InferHandlerResponse<UsersController['get']> // → User\n * ```\n */\nexport type InferHandlerResponse<H> = H extends (...args: never[]) => infer R\n ? [Exclude<Awaited<R>, void | undefined>] extends [never]\n ? unknown\n : UnwrapReply<Exclude<Awaited<R>, void | undefined>>\n : unknown\n\ntype UnwrapReply<A> =\n A extends Reply<number, infer B>\n ? B\n : A extends RuntimeResponse\n ? // The engine's own response object says nothing about the body, so a\n // handler ending `return ctx.json(...)` degrades to `unknown` — which is\n // what the typegen comment always claimed happened. It did not: the bare\n // `RuntimeResponse` leaked into `KickRoutes[...].response`, offering\n // `.status()` / `.setHeader()` to a client expecting a payload.\n // Confidently wrong is worse than unknown.\n //\n // To carry a payload, return it (`return user`) or wrap it\n // (`return reply(201, user)`) — that is what `reply` is for.\n unknown\n : A\n\nexport function isReply(value: unknown): value is Reply {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[REPLY_BRAND] === true\n )\n}\n\n/**\n * Send a handler's RETURN value when the pipeline finished without anything\n * having written a response. Callers guard on \"driver/response unsettled\" —\n * this only decides how to send:\n *\n * - `undefined` → not handled (returns false; runtime keeps today's behavior)\n * - `Reply` wrapper → status + body (204 → `ctx.noContent()`)\n * - anything else → `ctx.json(value)` (200)\n *\n * Returns true when a response was produced.\n */\nexport function applyHandlerResult(ctx: RequestContext, result: unknown): boolean {\n if (result === undefined) return false\n if (isReply(result)) {\n // Only 204 maps to noContent — an undefined body must NOT coerce the\n // declared status (reply(304, undefined) keeps its 304; the json body\n // is simply empty).\n if (result.status === 204) {\n ctx.noContent()\n return true\n }\n ctx.json(result.body, result.status)\n return true\n }\n ctx.json(result)\n return true\n}\n"],"mappings":";;;;;;;;;;6PA0CA,SAAgB,mBAAmB,YAAkC,CAEnE,QADc,MAAM,QAAQ,WAAW,EAAI,YAAY,GAAK,cAC3C,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,YAAY,CACxD,CAaA,SAAS,gBAAgB,UAA4B,CACnD,OAAO,YAAc,oBAAsB,gCAAgC,KAAK,SAAS,CAC3F,CAWA,SAAgB,kBAAkB,YAAoC,CACpE,IAAM,UAAY,mBAAmB,WAAW,EAMhD,OALK,UACD,gBAAgB,SAAS,EAAU,OACnC,YAAc,oCAA4C,aAC1D,UAAU,WAAW,YAAY,EAAU,YAC3C,UAAU,WAAW,OAAO,EAAU,OACnC,cALgB,aAMzB,CASA,MAAa,mBAAqB,CAAC,mBAAoB,oBAAoB,EAG9D,qBAAuB,CAClC,mBACA,qBACA,oCACA,SACA,qBACF,EAcA,SAAgB,0BAA0B,YAAyC,CACjF,IAAM,UAAY,mBAAm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,IAAK,IAAA,EAAS,EAsCnE,SAAgB,QAAQ,MAAgC,CACtD,OACE,OAAO,OAAU,YACjB,OACC,MAAkC,eAAiB,EAExD,CAaA,SAAgB,mBAAmB,IAAqB,OAA0B,CAchF,OAbI,SAAW,IAAA,GAAkB,GAC7B,QAAQ,MAAM,EAIZ,OAAO,SAAW,KACpB,IAAI,UAAU,EACP,KAET,IAAI,KAAK,OAAO,KAAM,OAAO,MAAM,EAC5B,KAET,IAAI,KAAK,MAAM,EACR,GACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function readCookies(req){let source=req;if(source.cookies)return source.cookies;let header=source.headers?.cookie;return typeof header==`string`?parseCookieHeader(header):{}}function parseCookieHeader(header){let out={};for(let pair of header.split(`;`)){let eq=pair.indexOf(`=`);if(eq===-1)continue;let key=pair.slice(0,eq).trim();if(!key)continue;let value=pair.slice(eq+1).trim();value.startsWith(`"`)&&value.endsWith(`"`)&&(value=value.slice(1,-1));try{out[key]=decodeURIComponent(value)}catch{out[key]=value}}return out}function serializeCookie(name,value,options){let parts=[`${name}=${encodeURIComponent(value)}`];if(options.maxAge!==void 0&&parts.push(`Max-Age=${Math.floor(options.maxAge/1e3)}`),options.expires&&parts.push(`Expires=${options.expires.toUTCString()}`),options.domain&&parts.push(`Domain=${options.domain}`),parts.push(`Path=${options.path??`/`}`),options.httpOnly&&parts.push(`HttpOnly`),options.secure&&parts.push(`Secure`),options.sameSite){let value=options.sameSite===!0?`Strict`:options.sameSite;parts.push(`SameSite=${value.charAt(0).toUpperCase()}${value.slice(1)}`)}return parts.join(`; `)}function setCookie(res,name,value,options={}){let target=res;if(typeof target.cookie==`function`){target.cookie(name,value,options);return}let cookie=serializeCookie(name,value,options),prior=target.getHeader?.(`Set-Cookie`),all=prior===void 0?[cookie]:[...Array.isArray(prior)?prior:[prior],cookie];target.setHeader?.(`Set-Cookie`,all)}function sendJson(res,status,body){let target=res;if(typeof target.status==`function`){let chained=target.status(status);if(typeof chained?.json==`function`){chained.json(body);return}}target.statusCode=status,target.getHeader?.(`content-type`)||target.setHeader?.(`content-type`,`application/json; charset=utf-8`),target.end?.(JSON.stringify(body))}export{setCookie as i,readCookies as n,sendJson as r,parseCookieHeader as t};
|
|
12
|
-
//# sourceMappingURL=respond-
|
|
12
|
+
//# sourceMappingURL=respond-wbMSqHYo.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"respond-
|
|
1
|
+
{"version":3,"file":"respond-wbMSqHYo.mjs","names":[],"sources":["../src/http/middleware/respond.ts"],"sourcesContent":["/**\n * Response helpers that work on every runtime.\n *\n * Connect middleware receives an Express response under Express and a raw\n * `ServerResponse` under Fastify and h3. `res.cookie()` and `res.status().json()`\n * are Express conveniences that do not exist on the raw object, so a shipped\n * middleware reaching for them works on one engine and throws on the other two:\n *\n * csrf → `res.cookie()` threw before any check ran, so EVERY request\n * became a 500 — including safe methods the middleware is\n * supposed to wave through\n * rateLimit → `res.status()` threw only once the limit was hit, and the\n * throw left the request hanging rather than answering 429\n * session → `res.cookie()` threw on every response that issued a session\n *\n * These take the Express path when it is there — so behaviour under Express is\n * byte-identical to before — and fall back to the Node primitives otherwise.\n *\n * @module @forinda/kickjs/http/middleware/respond\n */\n\n/**\n * Cookies on the request, whoever parsed them.\n *\n * `req.cookies` exists only when an upstream cookie parser populated it —\n * `cookie-parser` under Express, nothing at all under Fastify and h3, which\n * pass a raw node request. A middleware that reads only `req.cookies` therefore\n * sees no cookies on those runtimes, and none under Express either unless the\n * app happens to mount a parser.\n *\n * For `csrf` that broke the double-submit flow outright: with no cookie visible\n * it minted a fresh token on every request and compared the submitted header\n * against that new value, so a client could never complete a protected request.\n */\nexport function readCookies(req: unknown): Record<string, string> {\n const source = req as { cookies?: Record<string, string>; headers?: Record<string, unknown> }\n if (source.cookies) return source.cookies\n const header = source.headers?.cookie\n return typeof header === 'string' ? parseCookieHeader(header) : {}\n}\n\n/** `a=1; b=2` → `{ a: '1', b: '2' }`. */\nexport function parseCookieHeader(header: string): Record<string, string> {\n const out: Record<string, string> = {}\n for (const pair of header.split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n const key = pair.slice(0, eq).trim()\n if (!key) continue\n let value = pair.slice(eq + 1).trim()\n if (value.startsWith('\"') && value.endsWith('\"')) {\n value = value.slice(1, -1)\n }\n try {\n out[key] = decodeURIComponent(value)\n } catch {\n // A malformed escape is not a reason to lose the whole cookie jar.\n out[key] = value\n }\n }\n return out\n}\n\n/** Cookie attributes, matching the subset of Express's `res.cookie` we use. */\nexport interface CookieOptions {\n maxAge?: number\n expires?: Date\n domain?: string\n path?: string\n httpOnly?: boolean\n secure?: boolean\n sameSite?: boolean | 'lax' | 'strict' | 'none'\n}\n\ninterface AnyResponse {\n cookie?: (name: string, value: string, options?: CookieOptions) => unknown\n status?: (code: number) => { json?: (body: unknown) => unknown }\n statusCode?: number\n getHeader?: (name: string) => unknown\n setHeader?: (name: string, value: unknown) => unknown\n end?: (chunk?: unknown) => unknown\n}\n\n/** `Set-Cookie` value for one cookie, per RFC 6265 §4.1. */\nfunction serializeCookie(name: string, value: string, options: CookieOptions): string {\n const parts = [`${name}=${encodeURIComponent(value)}`]\n // Express takes `maxAge` in milliseconds; `Max-Age` is seconds.\n if (options.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(options.maxAge / 1000)}`)\n if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`)\n if (options.domain) parts.push(`Domain=${options.domain}`)\n parts.push(`Path=${options.path ?? '/'}`)\n if (options.httpOnly) parts.push('HttpOnly')\n if (options.secure) parts.push('Secure')\n if (options.sameSite) {\n // `true` means Strict, matching Express.\n const value = options.sameSite === true ? 'Strict' : options.sameSite\n parts.push(`SameSite=${value.charAt(0).toUpperCase()}${value.slice(1)}`)\n }\n return parts.join('; ')\n}\n\n/** Set a cookie without assuming Express. Appends, never replaces. */\nexport function setCookie(\n res: unknown,\n name: string,\n value: string,\n options: CookieOptions = {},\n): void {\n const target = res as AnyResponse\n if (typeof target.cookie === 'function') {\n target.cookie(name, value, options)\n return\n }\n const cookie = serializeCookie(name, value, options)\n const prior = target.getHeader?.('Set-Cookie')\n const all = prior === undefined ? [cookie] : [...(Array.isArray(prior) ? prior : [prior]), cookie]\n target.setHeader?.('Set-Cookie', all)\n}\n\n/** Send a JSON body with a status, without assuming Express. */\nexport function sendJson(res: unknown, status: number, body: unknown): void {\n const target = res as AnyResponse\n if (typeof target.status === 'function') {\n const chained = target.status(status)\n if (typeof chained?.json === 'function') {\n chained.json(body)\n return\n }\n }\n target.statusCode = status\n if (!target.getHeader?.('content-type')) {\n target.setHeader?.('content-type', 'application/json; charset=utf-8')\n }\n target.end?.(JSON.stringify(body))\n}\n"],"mappings":";;;;;;;;;;AAkCA,SAAgB,YAAY,IAAsC,CAChE,IAAM,OAAS,IACf,GAAI,OAAO,QAAS,OAAO,OAAO,QAClC,IAAM,OAAS,OAAO,SAAS,OAC/B,OAAO,OAAO,QAAW,SAAW,kBAAkB,MAAM,EAAI,CAAC,CACnE,CAGA,SAAgB,kBAAkB,OAAwC,CACxE,IAAM,IAA8B,CAAC,EACrC,IAAK,IAAM,QAAQ,OAAO,MAAM,GAAG,EAAG,CACpC,IAAM,GAAK,KAAK,QAAQ,GAAG,EAC3B,GAAI,KAAO,GAAI,SACf,IAAM,IAAM,KAAK,MAAM,EAAG,EAAE,CAAC,CAAC,KAAK,EACnC,GAAI,CAAC,IAAK,SACV,IAAI,MAAQ,KAAK,MAAM,GAAK,CAAC,CAAC,CAAC,KAAK,EAChC,MAAM,WAAW,GAAG,GAAK,MAAM,SAAS,GAAG,IAC7C,MAAQ,MAAM,MAAM,EAAG,EAAE,GAE3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O,OAAO,MAAM,EACpC,GAAI,OAAO,SAAS,MAAS,WAAY,CACvC,QAAQ,KAAK,IAAI,EACjB,MACF,CACF,CACA,OAAO,WAAa,OACf,OAAO,YAAY,cAAc,GACpC,OAAO,YAAY,eAAgB,iCAAiC,EAEtE,OAAO,MAAM,KAAK,UAAU,IAAI,CAAC,CACnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.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{METADATA}from"./core/interfaces.mjs";import{a as getMethodMeta,c as pushClassMeta,l as pushMethodMeta,t as getClassMeta}from"./metadata-
|
|
12
|
-
//# sourceMappingURL=route-flag-
|
|
11
|
+
import{METADATA}from"./core/interfaces.mjs";import{a as getMethodMeta,c as pushClassMeta,l as pushMethodMeta,t as getClassMeta}from"./metadata-CzzRUnAx.mjs";const FLAG_UNSET=Symbol(`kick.flagUnset`);function isDecoratorApplication(args){let[target,propertyKey]=args;return typeof propertyKey==`string`||typeof propertyKey==`symbol`||args.length===1&&typeof target==`function`}function defineRouteFlag(name){if(name.startsWith(`!`))throw Error(`defineRouteFlag('${name}'): a flag name cannot start with '!' — that prefix is reserved for negated tests ('!${name.slice(1)}' means "does not carry ${name.slice(1)}"). Rename the flag.`);function apply(value,target,propertyKey){let declaration={name,value};if(propertyKey===void 0){pushClassMeta(METADATA.CLASS_FLAGS,target,declaration);return}pushMethodMeta(METADATA.METHOD_FLAGS,target.constructor,String(propertyKey),declaration)}let flag=(...args)=>{if(isDecoratorApplication(args)){apply(!0,args[0],args[1]);return}let value=args[0];return(target,propertyKey)=>{apply(value,target,propertyKey)}};return Object.defineProperty(flag,"flagName",{value:name,enumerable:!0}),Object.defineProperty(flag,"off",{value:(target,propertyKey)=>{apply(FLAG_UNSET,target,propertyKey)},enumerable:!0}),flag}function resolveRouteFlags(classDeclarations,methodDeclarations,mountDeclarations=[]){let resolved=new Map;for(let{name,value}of[...mountDeclarations,...classDeclarations,...methodDeclarations]){if(value===FLAG_UNSET){resolved.delete(name);continue}resolved.set(name,value)}return resolved}function matchesFlagTest(test,flags,route){let resolved=flags??EMPTY_FLAGS;if(typeof test==`function`)return test({flags:resolved,route});if(typeof test==`string`)return isNegated(test)?!resolved.has(stripNegation(test)):resolved.has(test);if(test.length===0)return!1;let negated=isNegated(test[0]);if(test.some(name=>isNegated(name)!==negated))throw Error(`Route flag test mixes polarities: [${test.map(n=>`'${n}'`).join(`, `)}]. A list is either all names ("carries any of these") or all negated ("carries none of these") — for anything else, pass a predicate.`);return negated?test.every(name=>!resolved.has(stripNegation(name))):test.some(name=>resolved.has(name))}function assertFlagTest(test,site){if(typeof test==`function`||typeof test==`string`||test.length===0)return;let negated=isNegated(test[0]);if(test.some(name=>isNegated(name)!==negated))throw Error(`${site}: route flag test mixes polarities: [${test.map(n=>`'${n}'`).join(`, `)}]. A list is either all names ("carries any of these") or all negated ("carries none of these") — for anything else, pass a predicate.`)}const isNegated=name=>name.startsWith(`!`),stripNegation=name=>name.slice(1),EMPTY_FLAGS=new Map,ROUTE_SLOT=Symbol.for(`kick.route`);function getRouteFlags(controllerClass,handlerName){return resolveRouteFlags(getClassFlagDeclarations(controllerClass),getMethodFlagDeclarations(controllerClass,handlerName),getMountFlagDeclarations(controllerClass))}function getClassFlagDeclarations(controllerClass){return getClassMeta(METADATA.CLASS_FLAGS,controllerClass,[])}function getMethodFlagDeclarations(controllerClass,handlerName){return getMethodMeta(METADATA.METHOD_FLAGS,controllerClass,handlerName,[])}function toFlagDeclarations(flags,site){return flags?(Array.isArray(flags)?flags.map(name=>[name,!0]):Object.entries(flags)).map(([name,value])=>{if(name.startsWith(`!`))throw Error(`${site}: a flag name cannot start with '!' — that prefix is reserved for negated tests, and a declaration has no negative form. Remove the flag instead of declaring '${name}'.`);return{name,value}}):[]}const MOUNT_FLAGS=new WeakMap;function registerMountFlags(controllerClass,declarations){if(declarations.length===0){MOUNT_FLAGS.delete(controllerClass);return}MOUNT_FLAGS.set(controllerClass,[...declarations])}function getMountFlagDeclarations(controllerClass){return MOUNT_FLAGS.get(controllerClass)??[]}export{getMethodFlagDeclarations as a,registerMountFlags as c,getClassFlagDeclarations as i,resolveRouteFlags as l,assertFlagTest as n,getRouteFlags as o,defineRouteFlag as r,matchesFlagTest as s,ROUTE_SLOT as t,toFlagDeclarations as u};
|
|
12
|
+
//# sourceMappingURL=route-flag-Bb7n9Mnp.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-flag-sIYXay3q.mjs","names":[],"sources":["../src/core/route-flag.ts"],"sourcesContent":["/**\n * Route flags — a named, inheritable fact about a route.\n *\n * A flag carries no behaviour. It records something about the route that any\n * consumer may read: `auth.public`, `csrf.exempt`, `rate.limit`. Auth reads it\n * to skip a contributor, a guard reads it to return early, Swagger reads it to\n * mark a security scheme — none of them needs to know about the others.\n *\n * The rule that makes presence checks safe: a flag resolves to **absent**, or\n * **present with a value**. `@Public.off` on a method removes what the class\n * set, rather than storing something falsy — so `flags.has(name)` is always the\n * right question for a boolean flag. Without that, `has('auth.public')` could\n * answer `true` for the route that just opted back IN, which is an\n * authorization bypass rather than a papercut.\n */\nimport { METADATA } from './interfaces'\nimport { getClassMeta, getMethodMeta, pushClassMeta, pushMethodMeta } from './metadata'\n\n/**\n * Augmentable route-flag registry — the flag counterpart of `ContextMeta`.\n *\n * Declare a project's flags here and every use of them narrows: a misspelt\n * name is a compile error rather than a flag that silently never matches, and\n * `flags.get('rate.limit')` comes back typed instead of `unknown`.\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'auth.public': true\n * 'rate.limit': { rpm: number }\n * }\n * }\n * ```\n *\n * The interface is empty by default, and everything below falls back to plain\n * `string` while it stays that way — a project that has not augmented anything\n * keeps compiling exactly as before. The narrowing switches on with the first\n * declaration.\n *\n * The framework itself declares nothing here: it ships the mechanism and names\n * no flags, so `auth.public` above is a name you chose.\n *\n * Two constraints on what you can declare:\n * - A name cannot start with `!` — that prefix means \"does not carry this flag\"\n * in a {@link RouteFlagTest}, and `defineRouteFlag` rejects it.\n * - Removal is `@Flag.off`, not `@Flag(false)` — so `false` stays usable as a\n * real value for a flag declared `boolean`.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface KickRouteFlags {}\n\n/**\n * A flag name. Narrows to the declared keys once {@link KickRouteFlags} is\n * augmented, and stays `string` until then — the same\n * `[Known] extends [never]` fallback `ContextMetaKey` uses, for the same\n * reason: first-day code must keep compiling.\n */\nexport type RouteFlagName = [keyof KickRouteFlags] extends [never]\n ? string\n : keyof KickRouteFlags & string\n\n/**\n * The value type declared for a flag, defaulting to `true` for a bare flag and\n * `unknown` for a name the registry does not know.\n */\nexport type RouteFlagValue<K extends string, Fallback = unknown> = K extends keyof KickRouteFlags\n ? KickRouteFlags[K]\n : Fallback\n\n/**\n * Marks a declaration as \"remove this flag\" during resolution.\n *\n * A dedicated sentinel rather than `false`: `false` is a perfectly good flag\n * VALUE (a registry entry typed `boolean`), and overloading it meant\n * `@Enabled(false)` deleted the flag while `flags.get('enabled')` could never\n * return `false`. With the sentinel, `false` stores like any other value and\n * removal is spelled `@Enabled.off`.\n *\n * Module-private and NOT `Symbol.for`: a registry-global symbol is reachable\n * by application code, so a flag declared with a `symbol` value could be handed\n * this exact sentinel and be deleted instead of stored. It is created and\n * consumed in this module, so it never needs to cross a realm.\n */\nconst FLAG_UNSET: unique symbol = Symbol('kick.flagUnset') as never\n\n/** One `@Flag` application, before precedence resolution. */\nexport interface RouteFlagDeclaration {\n readonly name: string\n /** `false` means \"remove whatever a lower-precedence site declared\". */\n readonly value: unknown\n}\n\n/**\n * A flag decorator. Usable bare (`@Public`) or called with a value\n * (`@Public(false)`, `@RateLimit({ rpm: 10 })`), on a class or a method.\n */\n/**\n * The bare application forms — `@Public` with no call.\n *\n * Split out so they can be withheld from a flag whose declared value is not\n * assignable from `true`: applying `@Limit` bare would store `true` while\n * `flags.get('rate.limit')` promises `{ rpm: number }`, and nothing would catch\n * the mismatch until a consumer read the wrong shape at runtime.\n */\nexport interface BareRouteFlag {\n /**\n * Bare on a class. Typed against `Function` rather than `object` so a flag\n * VALUE that happens to be an object (`@Limit({ rpm: 10 })`) cannot match\n * this signature: overload resolution would otherwise pick it, return\n * `void`, and fail with \"Type 'void' has no call signatures\".\n */\n (target: Function): void\n /**\n * Bare on a method. `propertyKey` is required for the same reason — it makes\n * a one-argument call unambiguous.\n */\n (target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor): void\n}\n\n/** The called form — `@Limit({ rpm: 10 })` — plus removal via `.off`. */\nexport interface ValuedRouteFlag<V> {\n (value: V): (target: object, propertyKey?: string | symbol) => void\n /**\n * Remove the flag on this route — `@Public.off` on a method drops what the\n * controller set.\n *\n * Applied bare, like the flag itself. Spelled as its own member rather than\n * `@Public(false)` so that `false` stays available as a real value: a flag\n * declared `boolean` can store it, and `flags.get()` can return it.\n */\n readonly off: BareRouteFlag\n readonly flagName: string\n}\n\n/**\n * A flag decorator.\n *\n * Bare application is available only when `true` is a valid value for the flag\n * — which is every flag until {@link KickRouteFlags} declares a value type for\n * it. Declare `'rate.limit': { rpm: number }` and `@RateLimit` on its own stops\n * compiling, because the value it would store is not the value the registry\n * promises readers.\n */\nexport type RouteFlag<V = true> = true extends V\n ? BareRouteFlag & ValuedRouteFlag<V>\n : ValuedRouteFlag<V>\n\n/**\n * True when the arguments look like a decorator application rather than a\n * value. The two forms are `@Public` (TS calls it for us) and `@Public(v)`\n * (we return the decorator).\n *\n * Discrimination has to be exact, because a value can be an object:\n * `@RateLimit({ rpm: 10 })` is a single object argument, and treating it as a\n * class-decorator target silently drops the flag.\n *\n * - method decorator → `(prototype, 'name', descriptor?)`, so arg 1 is a\n * string or symbol\n * - class decorator → `(constructor)`, a single *function* argument\n * - anything else → a value\n */\nfunction isDecoratorApplication(args: unknown[]): boolean {\n const [target, propertyKey] = args\n if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') return true\n return args.length === 1 && typeof target === 'function'\n}\n\n/**\n * Define a route flag.\n *\n * ```ts\n * export const Public = defineRouteFlag('auth.public')\n * export const RateLimit = defineRouteFlag<{ rpm: number }>('rate.limit')\n * ```\n *\n * Once {@link KickRouteFlags} declares the name, the value type comes from the\n * registry and the explicit generic is redundant:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'rate.limit': { rpm: number }\n * }\n * }\n *\n * const RateLimit = defineRouteFlag('rate.limit') // RouteFlag<{ rpm: number }>\n * ```\n */\nexport function defineRouteFlag<const N extends RouteFlagName>(\n name: N,\n): RouteFlag<RouteFlagValue<N, true>>\nexport function defineRouteFlag<V>(name: RouteFlagName): RouteFlag<V>\nexport function defineRouteFlag(name: string): RouteFlag<never> {\n // `!` is reserved: a test string starting with it means \"does NOT carry this\n // flag\", so a flag literally named '!x' would be indistinguishable from the\n // negation of 'x' — `exemptWhen: '!x'` would silently stop meaning what the\n // author wrote. Rejecting at definition is the only point where the two can\n // still be told apart.\n if (name.startsWith('!')) {\n throw new Error(\n `defineRouteFlag('${name}'): a flag name cannot start with '!' — that prefix is reserved ` +\n `for negated tests ('!${name.slice(1)}' means \"does not carry ${name.slice(1)}\"). ` +\n `Rename the flag.`,\n )\n }\n\n function apply(value: unknown, target: object, propertyKey?: string | symbol): void {\n const declaration: RouteFlagDeclaration = { name, value }\n if (propertyKey === undefined) {\n pushClassMeta<RouteFlagDeclaration>(METADATA.CLASS_FLAGS, target, declaration)\n return\n }\n // Method decorators receive the prototype; metadata helpers key off the\n // constructor so class + method lookups land in the same place.\n pushMethodMeta<RouteFlagDeclaration>(\n METADATA.METHOD_FLAGS,\n (target as { constructor: object }).constructor,\n String(propertyKey),\n declaration,\n )\n }\n\n const flag = (...args: unknown[]): unknown => {\n if (isDecoratorApplication(args)) {\n // Bare form: @Public\n apply(true, args[0] as object, args[1] as string | symbol | undefined)\n return undefined\n }\n // Called form: @Public(false) / @RateLimit({ rpm: 10 })\n const value = args[0]\n return (target: object, propertyKey?: string | symbol): void => {\n apply(value, target, propertyKey)\n }\n }\n\n Object.defineProperty(flag, 'flagName', { value: name, enumerable: true })\n // `.off` is the removal decorator: bare-applicable, and the only way to drop\n // an inherited flag now that `false` is an ordinary value.\n Object.defineProperty(flag, 'off', {\n value: (target: object, propertyKey?: string | symbol): void => {\n apply(FLAG_UNSET, target, propertyKey)\n },\n enumerable: true,\n })\n return flag as unknown as RouteFlag<never>\n}\n\n/**\n * Resolve the flags in force for one route.\n *\n * Precedence is method > class > mount, matching the contributor pipeline's top\n * three levels. Within a level the last declaration wins (decorators apply\n * bottom-up, so the one nearest the handler is applied last).\n *\n * A resolved `false` deletes the key rather than storing it — see the module\n * docblock.\n */\nexport function resolveRouteFlags(\n classDeclarations: readonly RouteFlagDeclaration[],\n methodDeclarations: readonly RouteFlagDeclaration[],\n mountDeclarations: readonly RouteFlagDeclaration[] = [],\n): RouteFlags {\n const resolved = new Map<string, unknown>()\n\n // Lowest precedence first, so higher levels overwrite. Mount comes first\n // despite being the last parameter — it was added after the other two, and\n // moving it to the front would break every existing caller for no gain.\n for (const { name, value } of [\n ...mountDeclarations,\n ...classDeclarations,\n ...methodDeclarations,\n ]) {\n if (value === FLAG_UNSET) {\n resolved.delete(name)\n continue\n }\n resolved.set(name, value)\n }\n\n // The map is built from declarations, so its value types are whatever the\n // registry says they are — this cast is the one place that knowledge crosses\n // from runtime data into the type system.\n return resolved as RouteFlags\n}\n\n/**\n * The resolved flags for a route.\n *\n * A `ReadonlyMap` whose `has` is narrowed to known names and whose `get`\n * returns the declared value type — so `flags.get('rate.limit')` is\n * `{ rpm: number } | undefined` rather than `unknown`, once the registry\n * declares it. Until then it behaves like `ReadonlyMap<string, unknown>`.\n */\nexport interface RouteFlags extends ReadonlyMap<string, unknown> {\n has(name: RouteFlagName): boolean\n get<K extends RouteFlagName>(name: K): RouteFlagValue<K> | undefined\n}\n\n/**\n * Argument handed to a flag predicate.\n *\n * `route` is undefined only where flags are consulted outside a matched route,\n * which today means a non-HTTP transport running the same contributor pipeline.\n */\nexport interface RouteFlagContext {\n readonly flags: RouteFlags\n readonly route?: {\n readonly method: string\n readonly path: string\n readonly controller?: unknown\n readonly handlerName?: string\n }\n}\n\n/**\n * A predicate form of a flag test, for conditions a single name cannot express:\n * two flags together, a flag's *value*, a path or controller check, an env\n * switch.\n *\n * ```ts\n * skipWhen: ({ flags }) => flags.has('auth.public') || flags.has('internal'),\n * skipWhen: ({ flags }) => (flags.get('rate.limit') as { rpm: number })?.rpm === 0,\n * skipWhen: ({ route }) => route?.path.startsWith('/webhooks') ?? false,\n * ```\n *\n * Keep predicates pure and cheap — they run per request, per contributor.\n */\nexport type RouteFlagPredicate = (ctx: RouteFlagContext) => boolean\n\n/**\n * How a consumer names the routes it cares about.\n *\n * A bare name for the common case, a list when several flags mean the same\n * thing (matched **any-of**), a predicate for everything else — all-of, a\n * flag's value, the route's path.\n *\n * ```ts\n * skipWhen: 'auth.public'\n * skipWhen: ['auth.public', 'health.probe'] // either one\n * skipWhen: ({ flags }) => flags.has('a') && flags.has('b') // both\n * ```\n */\n/**\n * A flag name with `!` in front — matches routes that do **not** carry it.\n *\n * Narrows with the registry like the positive form: once `KickRouteFlags`\n * declares `'auth.public'`, this is `'!auth.public' | …`, so a misspelt\n * negation is a compile error too.\n */\nexport type NegatedRouteFlagName = `!${RouteFlagName}`\n\n/**\n * How a consumer names the routes it cares about.\n *\n * - `'auth.public'` — carries the flag\n * - `'!auth.public'` — does **not** carry it\n * - `['a', 'b']` — carries **any** of them\n * - `['!a', '!b']` — carries **none** of them\n * - a predicate — anything else: all-of, a flag's value, the route's path\n *\n * Lists are single-polarity by construction: `['a', '!b']` matches neither\n * array member of this union, so it is a compile error. Mixed polarity has no\n * reading everyone agrees on — under any-of it means \"a present OR b absent\",\n * which most readers parse as \"and\" — and a predicate says it unambiguously.\n */\nexport type RouteFlagTest =\n | RouteFlagName\n | NegatedRouteFlagName\n | readonly RouteFlagName[]\n | readonly NegatedRouteFlagName[]\n | RouteFlagPredicate\n\n/**\n * Evaluate a {@link RouteFlagTest} against a route's resolved flags.\n *\n * Shared by every consumer that can be exempted per route — the contributor\n * runner, `csrfGuard`, `rateLimitGuard` — so \"which routes does this apply to\"\n * means the same thing everywhere, and a list is any-of in all of them.\n */\nexport function matchesFlagTest(\n test: RouteFlagTest,\n flags: RouteFlags | undefined,\n route?: RouteFlagContext['route'],\n): boolean {\n const resolved = flags ?? EMPTY_FLAGS\n if (typeof test === 'function') return test({ flags: resolved, route })\n\n if (typeof test === 'string') {\n return isNegated(test)\n ? !resolved.has(stripNegation(test))\n : resolved.has(test as RouteFlagName)\n }\n\n if (test.length === 0) return false\n\n // Single polarity per list — the type forbids mixing, and this guards the\n // untyped callers (plain JS, a value read from config) that the type cannot.\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `Route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n\n // Positive list is any-of; negated list is its complement, none-of. The two\n // read as opposites, which is what makes flipping every entry do what a\n // reader expects.\n return negated\n ? test.every((name) => !resolved.has(stripNegation(name)))\n : test.some((name) => resolved.has(name as RouteFlagName))\n}\n\n/**\n * Reject a mixed-polarity list at construction time.\n *\n * A list like `['auth.public', '!metered']` is a static mistake, so it fails\n * where it is written — when the contributor or guard is built — rather than\n * on the first request that reaches it. Same reasoning as the contributor\n * pipeline failing a dependency cycle at boot.\n *\n * Call from every factory that accepts a {@link RouteFlagTest}; the check in\n * {@link matchesFlagTest} stays as a backstop for direct callers.\n */\nexport function assertFlagTest(test: RouteFlagTest, site: string): void {\n if (typeof test === 'function' || typeof test === 'string' || test.length === 0) return\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `${site}: route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n}\n\nconst isNegated = (name: string): boolean => name.startsWith('!')\nconst stripNegation = (name: string): RouteFlagName => name.slice(1) as RouteFlagName\n\nconst EMPTY_FLAGS: RouteFlags = new Map()\n\n/**\n * Where the matched route is stashed for `ctx.route` to read.\n *\n * It lives on the **request object**, not on the RequestContext: the Express\n * runtime constructs a fresh `RequestContext` per middleware, so anything\n * written to one ctx is invisible to the next and to the handler. Fastify and\n * h3 build a single ctx per request and would not have shown the difference —\n * the cross-runtime test is what surfaced it.\n *\n * `Symbol.for` rather than a private symbol so a duplicated module instance\n * (pnpm hoisting, a bundled copy) still reads the same slot.\n */\nexport const ROUTE_SLOT: unique symbol = Symbol.for('kick.route') as never\n\n/**\n * Resolve the flags in force for one handler, straight from the controller\n * class — the same method-over-class result `buildRouteTable` computes.\n *\n * For consumers that see a controller and a method name rather than a live\n * request: an adapter's `onRouteMount`, an OpenAPI generator, a DevTools route\n * listing. Inside a request, read `ctx.route.flags` instead — it is already\n * resolved.\n *\n * ```ts\n * // Mark flagged routes public in the OpenAPI spec:\n * SwaggerAdapter({\n * bearerAuth: true,\n * securityResolver: ({ controllerClass, handlerName }) =>\n * getRouteFlags(controllerClass, handlerName).has('auth.public') ? null : undefined,\n * })\n * ```\n */\nexport function getRouteFlags(controllerClass: object, handlerName: string): RouteFlags {\n return resolveRouteFlags(\n getClassFlagDeclarations(controllerClass),\n getMethodFlagDeclarations(controllerClass, handlerName),\n getMountFlagDeclarations(controllerClass),\n )\n}\n\n/** Read the class-level declarations off a controller. */\nexport function getClassFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return getClassMeta<RouteFlagDeclaration[]>(METADATA.CLASS_FLAGS, controllerClass, [])\n}\n\n/** Read the method-level declarations off a controller method. */\nexport function getMethodFlagDeclarations(\n controllerClass: object,\n handlerName: string,\n): RouteFlagDeclaration[] {\n return getMethodMeta<RouteFlagDeclaration[]>(\n METADATA.METHOD_FLAGS,\n controllerClass,\n handlerName,\n [],\n )\n}\n\n/**\n * Flags declared as data rather than as a decorator, keyed by name.\n *\n * ```ts\n * { 'auth.public': true, 'rate.limit': { rpm: 10 } }\n * ```\n */\nexport type RouteFlagRecord = { [K in RouteFlagName]?: RouteFlagValue<K, true> }\n\n/**\n * What a non-decorator registration site accepts.\n *\n * A list is the common case — bare flags, each stored as `true`:\n * `flags: ['auth.public']`. The record form exists for flags that carry a\n * value. Both narrow against {@link KickRouteFlags} once it is augmented.\n */\nexport type RouteFlagDeclarations = readonly RouteFlagName[] | RouteFlagRecord\n\n/**\n * Normalise either input form into declarations.\n *\n * @param site Where the flags came from, for the error message — a name is\n * validated here rather than at read time so a typo'd `!` fails at boot.\n */\nexport function toFlagDeclarations(\n flags: RouteFlagDeclarations | undefined,\n site: string,\n): RouteFlagDeclaration[] {\n if (!flags) return []\n const entries: [string, unknown][] = Array.isArray(flags)\n ? flags.map((name) => [name as string, true])\n : Object.entries(flags as Record<string, unknown>)\n\n return entries.map(([name, value]) => {\n // Same reservation as `defineRouteFlag`: `!name` is a negated *test*, and a\n // flag named that way could never be tested for. Declaring one is always a\n // mistake — usually someone reaching for \"not public\" on the wrong side.\n if (name.startsWith('!')) {\n throw new Error(\n `${site}: a flag name cannot start with '!' — that prefix is reserved for negated ` +\n `tests, and a declaration has no negative form. Remove the flag instead of ` +\n `declaring '${name}'.`,\n )\n }\n return { name, value }\n })\n}\n\n/**\n * Mount-level declarations, keyed by controller class.\n *\n * A module declares flags for every route it mounts (`ModuleRoutes.flags`), so\n * unlike class and method declarations they are not written by a decorator and\n * have nowhere on the class to live. They are recorded here at mount time so\n * that {@link getRouteFlags} — which sees only a controller and a method name —\n * reports the same flags the runtime resolved. Without it an OpenAPI spec or a\n * DevTools route listing would disagree with `ctx.route.flags`.\n *\n * A `WeakMap`, so a controller from a torn-down app (a test, an HMR reload) is\n * collectable. Mounting the same controller twice replaces rather than appends:\n * a reload re-declares the same flags, and appending would grow without bound.\n */\nconst MOUNT_FLAGS = new WeakMap<object, RouteFlagDeclaration[]>()\n\n/**\n * Record the flags a mount declares for `controllerClass`.\n *\n * @internal Called by the route-table builder; not part of the app-facing API.\n */\nexport function registerMountFlags(\n controllerClass: object,\n declarations: readonly RouteFlagDeclaration[],\n): void {\n if (declarations.length === 0) {\n MOUNT_FLAGS.delete(controllerClass)\n return\n }\n MOUNT_FLAGS.set(controllerClass, [...declarations])\n}\n\n/** Read the mount-level declarations recorded for a controller. */\nexport function getMountFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return MOUNT_FLAGS.get(controllerClass) ?? []\n}\n"],"mappings":";;;;;;;;;;6JAmFA,MAAM,WAA4B,OAAO,gBAAgB,EA8EzD,SAAS,uBAAuB,KAA0B,CACxD,GAAM,CAAC,OAAQ,aAAe,KAE9B,OADI,OAAO,aAAgB,UAAY,OAAO,aAAgB,UACvD,KAAK,SAAW,GAAK,OAAO,QAAW,UAChD,CA2BA,SAAgB,gBAAgB,KAAgC,CAM9D,GAAI,KAAK,WAAW,GAAG,EACrB,MAAU,MACR,oBAAoB,KAAK,uFACC,KAAK,MAAM,CAAC,EAAE,0BAA0B,KAAK,MAAM,CAAC,EAAE,qBAElF,EAGF,SAAS,MAAM,MAAgB,OAAgB,YAAqC,CAClF,IAAM,YAAoC,CAAE,KAAM,KAAM,EACxD,GAAI,cAAgB,IAAA,GAAW,CAC7B,cAAoC,SAAS,YAAa,OAAQ,WAAW,EAC7E,MACF,CAGA,eACE,SAAS,aACR,OAAmC,YACpC,OAAO,WAAW,EAClB,WACF,CACF,CAEA,IAAM,MAAQ,GAAG,OAA6B,CAC5C,GAAI,uBAAuB,IAAI,EAAG,CAEhC,MAAM,GAAM,KAAK,GAAc,K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SAAgB,yBAAyB,gBAAiD,CACxF,OAAO,YAAY,IAAI,eAAe,GAAK,CAAC,CAC9C"}
|
|
1
|
+
{"version":3,"file":"route-flag-Bb7n9Mnp.mjs","names":[],"sources":["../src/core/route-flag.ts"],"sourcesContent":["/**\n * Route flags — a named, inheritable fact about a route.\n *\n * A flag carries no behaviour. It records something about the route that any\n * consumer may read: `auth.public`, `csrf.exempt`, `rate.limit`. Auth reads it\n * to skip a contributor, a guard reads it to return early, Swagger reads it to\n * mark a security scheme — none of them needs to know about the others.\n *\n * The rule that makes presence checks safe: a flag resolves to **absent**, or\n * **present with a value**. `@Public.off` on a method removes what the class\n * set, rather than storing something falsy — so `flags.has(name)` is always the\n * right question for a boolean flag. Without that, `has('auth.public')` could\n * answer `true` for the route that just opted back IN, which is an\n * authorization bypass rather than a papercut.\n */\nimport { METADATA } from './interfaces'\nimport { getClassMeta, getMethodMeta, pushClassMeta, pushMethodMeta } from './metadata'\n\n/**\n * Augmentable route-flag registry — the flag counterpart of `ContextMeta`.\n *\n * Declare a project's flags here and every use of them narrows: a misspelt\n * name is a compile error rather than a flag that silently never matches, and\n * `flags.get('rate.limit')` comes back typed instead of `unknown`.\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'auth.public': true\n * 'rate.limit': { rpm: number }\n * }\n * }\n * ```\n *\n * The interface is empty by default, and everything below falls back to plain\n * `string` while it stays that way — a project that has not augmented anything\n * keeps compiling exactly as before. The narrowing switches on with the first\n * declaration.\n *\n * The framework itself declares nothing here: it ships the mechanism and names\n * no flags, so `auth.public` above is a name you chose.\n *\n * Two constraints on what you can declare:\n * - A name cannot start with `!` — that prefix means \"does not carry this flag\"\n * in a {@link RouteFlagTest}, and `defineRouteFlag` rejects it.\n * - Removal is `@Flag.off`, not `@Flag(false)` — so `false` stays usable as a\n * real value for a flag declared `boolean`.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface KickRouteFlags {}\n\n/**\n * A flag name. Narrows to the declared keys once {@link KickRouteFlags} is\n * augmented, and stays `string` until then — the same\n * `[Known] extends [never]` fallback `ContextMetaKey` uses, for the same\n * reason: first-day code must keep compiling.\n */\nexport type RouteFlagName = [keyof KickRouteFlags] extends [never]\n ? string\n : keyof KickRouteFlags & string\n\n/**\n * The value type declared for a flag, defaulting to `true` for a bare flag and\n * `unknown` for a name the registry does not know.\n */\nexport type RouteFlagValue<K extends string, Fallback = unknown> = K extends keyof KickRouteFlags\n ? KickRouteFlags[K]\n : Fallback\n\n/**\n * Marks a declaration as \"remove this flag\" during resolution.\n *\n * A dedicated sentinel rather than `false`: `false` is a perfectly good flag\n * VALUE (a registry entry typed `boolean`), and overloading it meant\n * `@Enabled(false)` deleted the flag while `flags.get('enabled')` could never\n * return `false`. With the sentinel, `false` stores like any other value and\n * removal is spelled `@Enabled.off`.\n *\n * Module-private and NOT `Symbol.for`: a registry-global symbol is reachable\n * by application code, so a flag declared with a `symbol` value could be handed\n * this exact sentinel and be deleted instead of stored. It is created and\n * consumed in this module, so it never needs to cross a realm.\n */\nconst FLAG_UNSET: unique symbol = Symbol('kick.flagUnset') as never\n\n/** One `@Flag` application, before precedence resolution. */\nexport interface RouteFlagDeclaration {\n readonly name: string\n /** `false` means \"remove whatever a lower-precedence site declared\". */\n readonly value: unknown\n}\n\n/**\n * A flag decorator. Usable bare (`@Public`) or called with a value\n * (`@Public(false)`, `@RateLimit({ rpm: 10 })`), on a class or a method.\n */\n/**\n * The bare application forms — `@Public` with no call.\n *\n * Split out so they can be withheld from a flag whose declared value is not\n * assignable from `true`: applying `@Limit` bare would store `true` while\n * `flags.get('rate.limit')` promises `{ rpm: number }`, and nothing would catch\n * the mismatch until a consumer read the wrong shape at runtime.\n */\nexport interface BareRouteFlag {\n /**\n * Bare on a class. Typed against `Function` rather than `object` so a flag\n * VALUE that happens to be an object (`@Limit({ rpm: 10 })`) cannot match\n * this signature: overload resolution would otherwise pick it, return\n * `void`, and fail with \"Type 'void' has no call signatures\".\n */\n (target: Function): void\n /**\n * Bare on a method. `propertyKey` is required for the same reason — it makes\n * a one-argument call unambiguous.\n */\n (target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor): void\n}\n\n/** The called form — `@Limit({ rpm: 10 })` — plus removal via `.off`. */\nexport interface ValuedRouteFlag<V> {\n (value: V): (target: object, propertyKey?: string | symbol) => void\n /**\n * Remove the flag on this route — `@Public.off` on a method drops what the\n * controller set.\n *\n * Applied bare, like the flag itself. Spelled as its own member rather than\n * `@Public(false)` so that `false` stays available as a real value: a flag\n * declared `boolean` can store it, and `flags.get()` can return it.\n */\n readonly off: BareRouteFlag\n readonly flagName: string\n}\n\n/**\n * A flag decorator.\n *\n * Bare application is available only when `true` is a valid value for the flag\n * — which is every flag until {@link KickRouteFlags} declares a value type for\n * it. Declare `'rate.limit': { rpm: number }` and `@RateLimit` on its own stops\n * compiling, because the value it would store is not the value the registry\n * promises readers.\n */\nexport type RouteFlag<V = true> = true extends V\n ? BareRouteFlag & ValuedRouteFlag<V>\n : ValuedRouteFlag<V>\n\n/**\n * True when the arguments look like a decorator application rather than a\n * value. The two forms are `@Public` (TS calls it for us) and `@Public(v)`\n * (we return the decorator).\n *\n * Discrimination has to be exact, because a value can be an object:\n * `@RateLimit({ rpm: 10 })` is a single object argument, and treating it as a\n * class-decorator target silently drops the flag.\n *\n * - method decorator → `(prototype, 'name', descriptor?)`, so arg 1 is a\n * string or symbol\n * - class decorator → `(constructor)`, a single *function* argument\n * - anything else → a value\n */\nfunction isDecoratorApplication(args: unknown[]): boolean {\n const [target, propertyKey] = args\n if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') return true\n return args.length === 1 && typeof target === 'function'\n}\n\n/**\n * Define a route flag.\n *\n * ```ts\n * export const Public = defineRouteFlag('auth.public')\n * export const RateLimit = defineRouteFlag<{ rpm: number }>('rate.limit')\n * ```\n *\n * Once {@link KickRouteFlags} declares the name, the value type comes from the\n * registry and the explicit generic is redundant:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'rate.limit': { rpm: number }\n * }\n * }\n *\n * const RateLimit = defineRouteFlag('rate.limit') // RouteFlag<{ rpm: number }>\n * ```\n */\nexport function defineRouteFlag<const N extends RouteFlagName>(\n name: N,\n): RouteFlag<RouteFlagValue<N, true>>\nexport function defineRouteFlag<V>(name: RouteFlagName): RouteFlag<V>\nexport function defineRouteFlag(name: string): RouteFlag<never> {\n // `!` is reserved: a test string starting with it means \"does NOT carry this\n // flag\", so a flag literally named '!x' would be indistinguishable from the\n // negation of 'x' — `exemptWhen: '!x'` would silently stop meaning what the\n // author wrote. Rejecting at definition is the only point where the two can\n // still be told apart.\n if (name.startsWith('!')) {\n throw new Error(\n `defineRouteFlag('${name}'): a flag name cannot start with '!' — that prefix is reserved ` +\n `for negated tests ('!${name.slice(1)}' means \"does not carry ${name.slice(1)}\"). ` +\n `Rename the flag.`,\n )\n }\n\n function apply(value: unknown, target: object, propertyKey?: string | symbol): void {\n const declaration: RouteFlagDeclaration = { name, value }\n if (propertyKey === undefined) {\n pushClassMeta<RouteFlagDeclaration>(METADATA.CLASS_FLAGS, target, declaration)\n return\n }\n // Method decorators receive the prototype; metadata helpers key off the\n // constructor so class + method lookups land in the same place.\n pushMethodMeta<RouteFlagDeclaration>(\n METADATA.METHOD_FLAGS,\n (target as { constructor: object }).constructor,\n String(propertyKey),\n declaration,\n )\n }\n\n const flag = (...args: unknown[]): unknown => {\n if (isDecoratorApplication(args)) {\n // Bare form: @Public\n apply(true, args[0] as object, args[1] as string | symbol | undefined)\n return undefined\n }\n // Called form: @Public(false) / @RateLimit({ rpm: 10 })\n const value = args[0]\n return (target: object, propertyKey?: string | symbol): void => {\n apply(value, target, propertyKey)\n }\n }\n\n Object.defineProperty(flag, 'flagName', { value: name, enumerable: true })\n // `.off` is the removal decorator: bare-applicable, and the only way to drop\n // an inherited flag now that `false` is an ordinary value.\n Object.defineProperty(flag, 'off', {\n value: (target: object, propertyKey?: string | symbol): void => {\n apply(FLAG_UNSET, target, propertyKey)\n },\n enumerable: true,\n })\n return flag as unknown as RouteFlag<never>\n}\n\n/**\n * Resolve the flags in force for one route.\n *\n * Precedence is method > class > mount, matching the contributor pipeline's top\n * three levels. Within a level the last declaration wins (decorators apply\n * bottom-up, so the one nearest the handler is applied last).\n *\n * A resolved `false` deletes the key rather than storing it — see the module\n * docblock.\n */\nexport function resolveRouteFlags(\n classDeclarations: readonly RouteFlagDeclaration[],\n methodDeclarations: readonly RouteFlagDeclaration[],\n mountDeclarations: readonly RouteFlagDeclaration[] = [],\n): RouteFlags {\n const resolved = new Map<string, unknown>()\n\n // Lowest precedence first, so higher levels overwrite. Mount comes first\n // despite being the last parameter — it was added after the other two, and\n // moving it to the front would break every existing caller for no gain.\n for (const { name, value } of [\n ...mountDeclarations,\n ...classDeclarations,\n ...methodDeclarations,\n ]) {\n if (value === FLAG_UNSET) {\n resolved.delete(name)\n continue\n }\n resolved.set(name, value)\n }\n\n // The map is built from declarations, so its value types are whatever the\n // registry says they are — this cast is the one place that knowledge crosses\n // from runtime data into the type system.\n return resolved as RouteFlags\n}\n\n/**\n * The resolved flags for a route.\n *\n * A `ReadonlyMap` whose `has` is narrowed to known names and whose `get`\n * returns the declared value type — so `flags.get('rate.limit')` is\n * `{ rpm: number } | undefined` rather than `unknown`, once the registry\n * declares it. Until then it behaves like `ReadonlyMap<string, unknown>`.\n */\nexport interface RouteFlags extends ReadonlyMap<string, unknown> {\n has(name: RouteFlagName): boolean\n get<K extends RouteFlagName>(name: K): RouteFlagValue<K> | undefined\n}\n\n/**\n * Argument handed to a flag predicate.\n *\n * `route` is undefined only where flags are consulted outside a matched route,\n * which today means a non-HTTP transport running the same contributor pipeline.\n */\nexport interface RouteFlagContext {\n readonly flags: RouteFlags\n readonly route?: {\n readonly method: string\n readonly path: string\n readonly controller?: unknown\n readonly handlerName?: string\n }\n}\n\n/**\n * A predicate form of a flag test, for conditions a single name cannot express:\n * two flags together, a flag's *value*, a path or controller check, an env\n * switch.\n *\n * ```ts\n * skipWhen: ({ flags }) => flags.has('auth.public') || flags.has('internal'),\n * skipWhen: ({ flags }) => (flags.get('rate.limit') as { rpm: number })?.rpm === 0,\n * skipWhen: ({ route }) => route?.path.startsWith('/webhooks') ?? false,\n * ```\n *\n * Keep predicates pure and cheap — they run per request, per contributor.\n */\nexport type RouteFlagPredicate = (ctx: RouteFlagContext) => boolean\n\n/**\n * How a consumer names the routes it cares about.\n *\n * A bare name for the common case, a list when several flags mean the same\n * thing (matched **any-of**), a predicate for everything else — all-of, a\n * flag's value, the route's path.\n *\n * ```ts\n * skipWhen: 'auth.public'\n * skipWhen: ['auth.public', 'health.probe'] // either one\n * skipWhen: ({ flags }) => flags.has('a') && flags.has('b') // both\n * ```\n */\n/**\n * A flag name with `!` in front — matches routes that do **not** carry it.\n *\n * Narrows with the registry like the positive form: once `KickRouteFlags`\n * declares `'auth.public'`, this is `'!auth.public' | …`, so a misspelt\n * negation is a compile error too.\n */\nexport type NegatedRouteFlagName = `!${RouteFlagName}`\n\n/**\n * How a consumer names the routes it cares about.\n *\n * - `'auth.public'` — carries the flag\n * - `'!auth.public'` — does **not** carry it\n * - `['a', 'b']` — carries **any** of them\n * - `['!a', '!b']` — carries **none** of them\n * - a predicate — anything else: all-of, a flag's value, the route's path\n *\n * Lists are single-polarity by construction: `['a', '!b']` matches neither\n * array member of this union, so it is a compile error. Mixed polarity has no\n * reading everyone agrees on — under any-of it means \"a present OR b absent\",\n * which most readers parse as \"and\" — and a predicate says it unambiguously.\n */\nexport type RouteFlagTest =\n | RouteFlagName\n | NegatedRouteFlagName\n | readonly RouteFlagName[]\n | readonly NegatedRouteFlagName[]\n | RouteFlagPredicate\n\n/**\n * Evaluate a {@link RouteFlagTest} against a route's resolved flags.\n *\n * Shared by every consumer that can be exempted per route — the contributor\n * runner, `csrfGuard`, `rateLimitGuard` — so \"which routes does this apply to\"\n * means the same thing everywhere, and a list is any-of in all of them.\n */\nexport function matchesFlagTest(\n test: RouteFlagTest,\n flags: RouteFlags | undefined,\n route?: RouteFlagContext['route'],\n): boolean {\n const resolved = flags ?? EMPTY_FLAGS\n if (typeof test === 'function') return test({ flags: resolved, route })\n\n if (typeof test === 'string') {\n return isNegated(test)\n ? !resolved.has(stripNegation(test))\n : resolved.has(test as RouteFlagName)\n }\n\n if (test.length === 0) return false\n\n // Single polarity per list — the type forbids mixing, and this guards the\n // untyped callers (plain JS, a value read from config) that the type cannot.\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `Route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n\n // Positive list is any-of; negated list is its complement, none-of. The two\n // read as opposites, which is what makes flipping every entry do what a\n // reader expects.\n return negated\n ? test.every((name) => !resolved.has(stripNegation(name)))\n : test.some((name) => resolved.has(name as RouteFlagName))\n}\n\n/**\n * Reject a mixed-polarity list at construction time.\n *\n * A list like `['auth.public', '!metered']` is a static mistake, so it fails\n * where it is written — when the contributor or guard is built — rather than\n * on the first request that reaches it. Same reasoning as the contributor\n * pipeline failing a dependency cycle at boot.\n *\n * Call from every factory that accepts a {@link RouteFlagTest}; the check in\n * {@link matchesFlagTest} stays as a backstop for direct callers.\n */\nexport function assertFlagTest(test: RouteFlagTest, site: string): void {\n if (typeof test === 'function' || typeof test === 'string' || test.length === 0) return\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `${site}: route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n}\n\nconst isNegated = (name: string): boolean => name.startsWith('!')\nconst stripNegation = (name: string): RouteFlagName => name.slice(1) as RouteFlagName\n\nconst EMPTY_FLAGS: RouteFlags = new Map()\n\n/**\n * Where the matched route is stashed for `ctx.route` to read.\n *\n * It lives on the **request object**, not on the RequestContext: the Express\n * runtime constructs a fresh `RequestContext` per middleware, so anything\n * written to one ctx is invisible to the next and to the handler. Fastify and\n * h3 build a single ctx per request and would not have shown the difference —\n * the cross-runtime test is what surfaced it.\n *\n * `Symbol.for` rather than a private symbol so a duplicated module instance\n * (pnpm hoisting, a bundled copy) still reads the same slot.\n */\nexport const ROUTE_SLOT: unique symbol = Symbol.for('kick.route') as never\n\n/**\n * Resolve the flags in force for one handler, straight from the controller\n * class — the same method-over-class result `buildRouteTable` computes.\n *\n * For consumers that see a controller and a method name rather than a live\n * request: an adapter's `onRouteMount`, an OpenAPI generator, a DevTools route\n * listing. Inside a request, read `ctx.route.flags` instead — it is already\n * resolved.\n *\n * ```ts\n * // Mark flagged routes public in the OpenAPI spec:\n * SwaggerAdapter({\n * bearerAuth: true,\n * securityResolver: ({ controllerClass, handlerName }) =>\n * getRouteFlags(controllerClass, handlerName).has('auth.public') ? null : undefined,\n * })\n * ```\n */\nexport function getRouteFlags(controllerClass: object, handlerName: string): RouteFlags {\n return resolveRouteFlags(\n getClassFlagDeclarations(controllerClass),\n getMethodFlagDeclarations(controllerClass, handlerName),\n getMountFlagDeclarations(controllerClass),\n )\n}\n\n/** Read the class-level declarations off a controller. */\nexport function getClassFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return getClassMeta<RouteFlagDeclaration[]>(METADATA.CLASS_FLAGS, controllerClass, [])\n}\n\n/** Read the method-level declarations off a controller method. */\nexport function getMethodFlagDeclarations(\n controllerClass: object,\n handlerName: string,\n): RouteFlagDeclaration[] {\n return getMethodMeta<RouteFlagDeclaration[]>(\n METADATA.METHOD_FLAGS,\n controllerClass,\n handlerName,\n [],\n )\n}\n\n/**\n * Flags declared as data rather than as a decorator, keyed by name.\n *\n * ```ts\n * { 'auth.public': true, 'rate.limit': { rpm: 10 } }\n * ```\n */\nexport type RouteFlagRecord = { [K in RouteFlagName]?: RouteFlagValue<K, true> }\n\n/**\n * What a non-decorator registration site accepts.\n *\n * A list is the common case — bare flags, each stored as `true`:\n * `flags: ['auth.public']`. The record form exists for flags that carry a\n * value. Both narrow against {@link KickRouteFlags} once it is augmented.\n */\nexport type RouteFlagDeclarations = readonly RouteFlagName[] | RouteFlagRecord\n\n/**\n * Normalise either input form into declarations.\n *\n * @param site Where the flags came from, for the error message — a name is\n * validated here rather than at read time so a typo'd `!` fails at boot.\n */\nexport function toFlagDeclarations(\n flags: RouteFlagDeclarations | undefined,\n site: string,\n): RouteFlagDeclaration[] {\n if (!flags) return []\n const entries: [string, unknown][] = Array.isArray(flags)\n ? flags.map((name) => [name as string, true])\n : Object.entries(flags as Record<string, unknown>)\n\n return entries.map(([name, value]) => {\n // Same reservation as `defineRouteFlag`: `!name` is a negated *test*, and a\n // flag named that way could never be tested for. Declaring one is always a\n // mistake — usually someone reaching for \"not public\" on the wrong side.\n if (name.startsWith('!')) {\n throw new Error(\n `${site}: a flag name cannot start with '!' — that prefix is reserved for negated ` +\n `tests, and a declaration has no negative form. Remove the flag instead of ` +\n `declaring '${name}'.`,\n )\n }\n return { name, value }\n })\n}\n\n/**\n * Mount-level declarations, keyed by controller class.\n *\n * A module declares flags for every route it mounts (`ModuleRoutes.flags`), so\n * unlike class and method declarations they are not written by a decorator and\n * have nowhere on the class to live. They are recorded here at mount time so\n * that {@link getRouteFlags} — which sees only a controller and a method name —\n * reports the same flags the runtime resolved. Without it an OpenAPI spec or a\n * DevTools route listing would disagree with `ctx.route.flags`.\n *\n * A `WeakMap`, so a controller from a torn-down app (a test, an HMR reload) is\n * collectable. Mounting the same controller twice replaces rather than appends:\n * a reload re-declares the same flags, and appending would grow without bound.\n */\nconst MOUNT_FLAGS = new WeakMap<object, RouteFlagDeclaration[]>()\n\n/**\n * Record the flags a mount declares for `controllerClass`.\n *\n * @internal Called by the route-table builder; not part of the app-facing API.\n */\nexport function registerMountFlags(\n controllerClass: object,\n declarations: readonly RouteFlagDeclaration[],\n): void {\n if (declarations.length === 0) {\n MOUNT_FLAGS.delete(controllerClass)\n return\n }\n MOUNT_FLAGS.set(controllerClass, [...declarations])\n}\n\n/** Read the mount-level declarations recorded for a controller. */\nexport function getMountFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return MOUNT_FLAGS.get(controllerClass) ?? []\n}\n"],"mappings":";;;;;;;;;;6JAmFA,MAAM,WAA4B,OAAO,gBAAgB,EA8EzD,SAAS,uBAAuB,KAA0B,CACxD,GAAM,CAAC,OAAQ,aAAe,KAE9B,OADI,OAAO,aAAgB,UAAY,OAAO,aAAgB,UACvD,KAAK,SAAW,GAAK,OAAO,QAAW,UAChD,CA2BA,SAAgB,gBAAgB,KAAgC,CAM9D,GAAI,KAAK,WAAW,GAAG,EACrB,MAAU,MACR,oBAAoB,KAAK,uFACC,KAAK,MAAM,CAAC,EAAE,0BAA0B,KAAK,MAAM,CAAC,EAAE,qBAElF,EAGF,SAAS,MAAM,MAAgB,OAAgB,YAAqC,CAClF,IAAM,YAAoC,CAAE,KAAM,KAAM,EACxD,GAAI,cAAgB,IAAA,GAAW,CAC7B,cAAoC,SAAS,YAAa,OAAQ,WAAW,EAC7E,MACF,CAGA,eACE,SAAS,aACR,OAAmC,YACpC,OAAO,WAAW,EAClB,WACF,CACF,CAEA,IAAM,MAAQ,GAAG,OAA6B,CAC5C,GAAI,uBAAuB,IAAI,EAAG,CAEhC,MAAM,GAAM,KAAK,GAAc,KAAK,EAAiC,EACrE,MACF,CAEA,IAAM,MAAQ,KAAK,GACnB,OAAQ,OAAgB,cAAwC,CAC9D,MAAM,MAAO,OAAQ,WAAW,CAClC,CACF,EAWA,OATA,OAAO,eAAe,KAAM,WAAY,CAAE,MAAO,KAAM,WAAY,EAAK,CAAC,EAGzE,OAAO,eAAe,KAAM,MAAO,CACjC,OAAQ,OAAgB,cAAwC,CAC9D,MAAM,WAAY,OAAQ,WAAW,CACvC,EACA,WAAY,EACd,CAAC,EACM,IACT,CAYA,SAAgB,kBACd,kBACA,mBACA,kBAAqD,C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AC,EAE7D,YAA0B,IAAI,IAcvB,WAA4B,OAAO,IAAI,YAAY,EAoBhE,SAAgB,cAAc,gBAAyB,YAAiC,CACtF,OAAO,kBACL,yBAAyB,eAAe,EACxC,0BAA0B,gBAAiB,WAAW,EACtD,yBAAyB,eAAe,CAC1C,CACF,CAGA,SAAgB,yBAAyB,gBAAiD,CACxF,OAAO,aAAqC,SAAS,YAAa,gBAAiB,CAAC,CAAC,CACvF,CAGA,SAAgB,0BACd,gBACA,YACwB,CACxB,OAAO,cACL,SAAS,aACT,gBACA,YACA,CAAC,CACH,CACF,CA0BA,SAAgB,mBACd,MACA,KACwB,CAMxB,OALK,OACgC,MAAM,QAAQ,KAAK,EACpD,MAAM,IAAK,MAAS,CAAC,KAAgB,EAAI,CAAC,EAC1C,OAAO,QAAQ,KAAgC,EAAA,CAEpC,KAAK,CAAC,KAAM,SAAW,CAIpC,GAAI,KAAK,WAAW,GAAG,EACrB,MAAU,MACR,GAAG,KAAK,iKAEQ,KAAK,GACvB,EAEF,MAAO,CAAE,KAAM,KAAM,CACvB,CAAC,EAjBkB,CAAC,CAkBtB,CAgBA,MAAM,YAAc,IAAI,QAOxB,SAAgB,mBACd,gBACA,aACM,CACN,GAAI,aAAa,SAAW,EAAG,CAC7B,YAAY,OAAO,eAAe,EAClC,MACF,CACA,YAAY,IAAI,gBAAiB,CAAC,GAAG,YAAY,CAAC,CACpD,CAGA,SAAgB,yBAAyB,gBAAiD,CACxF,OAAO,YAAY,IAAI,eAAe,GAAK,CAAC,CAC9C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
const EMPTY=new Map;function compile(path){let source=path.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\/:[^/]+/g,`/([^/]+)`).replace(/\*/g,`.*`);return RegExp(`^${source}/?$`)}var RoutePolicyTable=class{byMethod=new Map;add(method,path,flags){if(!flags||flags.size===0)return;let verb=method.toUpperCase(),bucket=this.byMethod.get(verb)??[];bucket.push({pattern:compile(path),flags}),this.byMethod.set(verb,bucket)}lookup(method,pathname){let bucket=this.byMethod.get(method.toUpperCase());if(!bucket)return EMPTY;for(let entry of bucket)if(entry.pattern.test(pathname))return entry.flags;return EMPTY}clear(){this.byMethod.clear()}get size(){let total=0;for(let bucket of this.byMethod.values())total+=bucket.length;return total}};const ROUTE_POLICY_SLOT=Symbol.for(`kick.routePolicy`);function bindRoutePolicy(handler,receive){return Object.defineProperty(handler,ROUTE_POLICY_SLOT,{value:receive,enumerable:!1}),handler}function offerRoutePolicy(handler,table){let receive=handler?.[ROUTE_POLICY_SLOT];typeof receive==`function`&&receive(table)}export{bindRoutePolicy as n,offerRoutePolicy as r,RoutePolicyTable as t};
|
|
12
|
-
//# sourceMappingURL=route-policy-
|
|
12
|
+
//# sourceMappingURL=route-policy-C_Wsc-b1.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-policy-
|
|
1
|
+
{"version":3,"file":"route-policy-C_Wsc-b1.mjs","names":[],"sources":["../src/core/route-policy.ts"],"sourcesContent":["/**\n * The route policy table — route flags for pre-match middleware.\n *\n * Middleware mounted app-wide (the connect-style `rateLimit()`, `csrf()`) runs\n * *before* a route is matched, so it cannot read `ctx.route.flags`: there is no\n * route yet. That is also the reason to keep it there — an abuse control has to\n * see traffic that matches nothing, which a route-scoped guard never does.\n *\n * So the flags come to it instead. Every mounted route registers its method,\n * full path and resolved flags here at boot; a global middleware asks the table\n * what flags *would* apply to an incoming method + pathname.\n *\n * The table is per-Application, handed to middleware that opts in via\n * {@link bindRoutePolicy}. Nothing global: two apps in one process (a test file,\n * an embedded admin app) each get their own.\n */\n\nimport type { RouteFlags } from './route-flag'\n\n/** Flags for one mounted route, keyed for lookup by an incoming request. */\ninterface PolicyEntry {\n /** Compiled from the mounted path — `/users/:id` → `^/users/([^/]+)$`. */\n readonly pattern: RegExp\n readonly flags: RouteFlags\n}\n\nconst EMPTY: RouteFlags = new Map() as RouteFlags\n\n/**\n * Turn a mounted path into a matcher.\n *\n * Deliberately small: `:param` matches one segment, `*` matches the rest, and\n * everything else is literal. This is a *lookup* over paths the engine already\n * chose to mount, not a second router — if it ever disagrees with the engine,\n * the answer is fewer features here, not more.\n */\nfunction compile(path: string): RegExp {\n const source = path\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/([^/]+)')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\nexport class RoutePolicyTable {\n /** Bucketed by method: an incoming request only scans its own verb. */\n private readonly byMethod = new Map<string, PolicyEntry[]>()\n\n add(method: string, path: string, flags: RouteFlags | undefined): void {\n if (!flags || flags.size === 0) return // nothing to say about this route\n const verb = method.toUpperCase()\n const bucket = this.byMethod.get(verb) ?? []\n bucket.push({ pattern: compile(path), flags })\n this.byMethod.set(verb, bucket)\n }\n\n /**\n * Flags that apply to `method pathname`, or an empty map when the path\n * matches no flagged route — including when it matches no route at all,\n * which is exactly the traffic this exists to keep visible.\n */\n lookup(method: string, pathname: string): RouteFlags {\n const bucket = this.byMethod.get(method.toUpperCase())\n if (!bucket) return EMPTY\n for (const entry of bucket) {\n if (entry.pattern.test(pathname)) return entry.flags\n }\n return EMPTY\n }\n\n /** Drop everything — the Application rebuilds on every HMR reload. */\n clear(): void {\n this.byMethod.clear()\n }\n\n get size(): number {\n let total = 0\n for (const bucket of this.byMethod.values()) total += bucket.length\n return total\n }\n}\n\n/**\n * Slot a middleware exposes to say \"hand me the policy table once routes are\n * mounted\". The Application calls it during setup; middleware that never\n * declares it is untouched.\n */\nexport const ROUTE_POLICY_SLOT: unique symbol = Symbol.for('kick.routePolicy') as never\n\n/** A middleware that accepts the policy table. */\nexport interface RoutePolicyAware {\n [ROUTE_POLICY_SLOT]?: (table: RoutePolicyTable) => void\n}\n\n/**\n * Declare that `handler` wants the policy table.\n *\n * Explicit hand-off rather than a module-level singleton, so the table a\n * middleware reads is always the one belonging to the app that mounted it.\n */\nexport function bindRoutePolicy<T extends object>(\n handler: T,\n receive: (table: RoutePolicyTable) => void,\n): T {\n Object.defineProperty(handler, ROUTE_POLICY_SLOT, { value: receive, enumerable: false })\n return handler\n}\n\n/** Hand the table to a middleware if it declared the slot. */\nexport function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void {\n const receive = (handler as RoutePolicyAware | null)?.[ROUTE_POLICY_SLOT]\n if (typeof receive === 'function') receive(table)\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,MAAoB,IAAI,IAU9B,SAAS,QAAQ,KAAsB,CACrC,IAAM,OAAS,KACZ,QAAQ,qBAAsB,MAAM,CAAC,CACrC,QAAQ,YAAa,UAAU,CAAC,CAChC,QAAQ,MAAO,IAAI,EACtB,OAAW,OAAO,IAAI,OAAO,IAAI,CACnC,CAEA,IAAa,iBAAb,KAA8B,CAE5B,SAA4B,IAAI,IAEhC,IAAI,OAAgB,KAAc,MAAqC,CACrE,GAAI,CAAC,OAAS,MAAM,OAAS,EAAG,OAChC,IAAM,KAAO,OAAO,YAAY,EAC1B,OAAS,KAAK,SAAS,IAAI,IAAI,GAAK,CAAC,EAC3C,OAAO,KAAK,CAAE,QAAS,QAAQ,IAAI,EAAG,KAAM,CAAC,EAC7C,KAAK,SAAS,IAAI,KAAM,MAAM,CAChC,CAOA,OAAO,OAAgB,SAA8B,CACnD,IAAM,OAAS,KAAK,SAAS,IAAI,OAAO,YAAY,CAAC,EACrD,GAAI,CAAC,OAAQ,OAAO,MACpB,IAAK,IAAM,SAAS,OAClB,GAAI,MAAM,QAAQ,KAAK,QAAQ,EAAG,OAAO,MAAM,MAEjD,OAAO,KACT,CAGA,OAAc,CACZ,KAAK,SAAS,MAAM,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