@forinda/kickjs 10.13.1 → 10.13.3
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/application-Bq0CzA-N.mjs +14 -0
- package/dist/application-Bq0CzA-N.mjs.map +1 -0
- package/dist/{application-r0VMb-A5.d.mts → application-DsHdZoZK.d.mts} +4 -3
- package/dist/{application-r0VMb-A5.d.mts.map → application-DsHdZoZK.d.mts.map} +1 -1
- package/dist/{body-policy-DpzQ1sXo.mjs → body-policy-mOP2Y9X_.mjs} +2 -2
- package/dist/{body-policy-DpzQ1sXo.mjs.map → body-policy-mOP2Y9X_.mjs.map} +1 -1
- package/dist/{bootstrap-D8U1b1lN.mjs → bootstrap-CMwBEDZq.mjs} +3 -3
- package/dist/{bootstrap-D8U1b1lN.mjs.map → bootstrap-CMwBEDZq.mjs.map} +1 -1
- package/dist/{bounded-counters-W_iZ-6a-.mjs → bounded-counters-BMVTNLG4.mjs} +2 -2
- package/dist/{bounded-counters-W_iZ-6a-.mjs.map → bounded-counters-BMVTNLG4.mjs.map} +1 -1
- package/dist/{client-ip-B90_tMPE.mjs → client-ip-C4TZ7y05.mjs} +2 -2
- package/dist/{client-ip-B90_tMPE.mjs.map → client-ip-C4TZ7y05.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-CcwnmXAp.mjs → config-DzmeCXg4.mjs} +3 -3
- package/dist/{config-CcwnmXAp.mjs.map → config-DzmeCXg4.mjs.map} +1 -1
- package/dist/{context-DJh3UImF.mjs → context-CvicRipm.mjs} +3 -3
- package/dist/{context-DJh3UImF.mjs.map → context-CvicRipm.mjs.map} +1 -1
- package/dist/{context-errors-Bjmg2Idn.mjs → context-errors-CXGtzjTQ.mjs} +2 -2
- package/dist/{context-errors-Bjmg2Idn.mjs.map → context-errors-CXGtzjTQ.mjs.map} +1 -1
- package/dist/{contributor-runner-BDrfpkvN.mjs → contributor-runner-Dx-TDNgk.mjs} +3 -3
- package/dist/{contributor-runner-BDrfpkvN.mjs.map → contributor-runner-Dx-TDNgk.mjs.map} +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +2 -2
- package/dist/{core-fD81or3K.mjs → core-CXAMJq3w.mjs} +3 -3
- package/dist/{core-fD81or3K.mjs.map → core-CXAMJq3w.mjs.map} +1 -1
- package/dist/{decorate-xqpvUQBu.mjs → decorate-JtGrMqV1.mjs} +3 -3
- package/dist/{decorate-xqpvUQBu.mjs.map → decorate-JtGrMqV1.mjs.map} +1 -1
- package/dist/{define-adapter-DV0gX0Zc.mjs → define-adapter-C_97M6VW.mjs} +2 -2
- package/dist/{define-adapter-DV0gX0Zc.mjs.map → define-adapter-C_97M6VW.mjs.map} +1 -1
- package/dist/{di-hooks-BCQxqvPP.mjs → di-hooks-CBFaF0h-.mjs} +2 -2
- package/dist/{di-hooks-BCQxqvPP.mjs.map → di-hooks-CBFaF0h-.mjs.map} +1 -1
- package/dist/{disposables-CLELPWB2.mjs → disposables-BBiL1YqI.mjs} +1 -1
- package/dist/{driver-60Ojtg4A.mjs → driver-B8NPLeRC.mjs} +3 -3
- package/dist/{driver-60Ojtg4A.mjs.map → driver-B8NPLeRC.mjs.map} +1 -1
- package/dist/{express-cGEtQgNP.mjs → express-_PaI8hxC.mjs} +3 -3
- package/dist/{express-cGEtQgNP.mjs.map → express-_PaI8hxC.mjs.map} +1 -1
- package/dist/{express-lazy-A39r8_jk.mjs → express-lazy-DaYQBnt_.mjs} +3 -3
- package/dist/{express-lazy-A39r8_jk.mjs.map → express-lazy-DaYQBnt_.mjs.map} +1 -1
- package/dist/{handler-BDivc8AT.mjs → handler-B5jN9Wms.mjs} +3 -3
- package/dist/{handler-BDivc8AT.mjs.map → handler-B5jN9Wms.mjs.map} +1 -1
- package/dist/{host-DTmYT9lX.mjs → host-Ix7FHVzW.mjs} +2 -2
- package/dist/{host-DTmYT9lX.mjs.map → host-Ix7FHVzW.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.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.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.mjs +2 -2
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{is-production-CC5VwQUr.mjs → is-production-BiWSKvPw.mjs} +2 -2
- package/dist/{is-production-CC5VwQUr.mjs.map → is-production-BiWSKvPw.mjs.map} +1 -1
- package/dist/{jobs-Cv_MxBmp.mjs → jobs-CZeIt0gU.mjs} +3 -3
- package/dist/{jobs-Cv_MxBmp.mjs.map → jobs-CZeIt0gU.mjs.map} +1 -1
- package/dist/{kv-stores-IqwuxoUl.mjs → kv-stores-C10enmKH.mjs} +3 -3
- package/dist/{kv-stores-IqwuxoUl.mjs.map → kv-stores-C10enmKH.mjs.map} +1 -1
- package/dist/{lazy-serve-static-DA6yo1u9.mjs → lazy-serve-static-BYRJI_As.mjs} +3 -3
- package/dist/{lazy-serve-static-DA6yo1u9.mjs.map → lazy-serve-static-BYRJI_As.mjs.map} +1 -1
- package/dist/{metadata-BhcNTK8K.mjs → metadata-CVsp-IZS.mjs} +1 -1
- package/dist/{observers-ZGFBMx7P.mjs → observers-DBTDcQ62.mjs} +2 -2
- package/dist/{observers-ZGFBMx7P.mjs.map → observers-DBTDcQ62.mjs.map} +1 -1
- package/dist/{precompressed-D03hwjjz.mjs → precompressed-Cc2hpa1k.mjs} +2 -2
- package/dist/{precompressed-D03hwjjz.mjs.map → precompressed-Cc2hpa1k.mjs.map} +1 -1
- package/dist/{query-Bs-87jM-.mjs → query-sD0UtM2N.mjs} +2 -2
- package/dist/{query-Bs-87jM-.mjs.map → query-sD0UtM2N.mjs.map} +1 -1
- package/dist/{reply-GgkLk_oe.mjs → reply-CjA0lh5T.mjs} +3 -3
- package/dist/{reply-GgkLk_oe.mjs.map → reply-CjA0lh5T.mjs.map} +1 -1
- package/dist/{request-scope-mn1b63mA.mjs → request-scope-BjBvqXuj.mjs} +3 -3
- package/dist/{request-scope-mn1b63mA.mjs.map → request-scope-BjBvqXuj.mjs.map} +1 -1
- package/dist/{respond-BBYJsJ-G.mjs → respond--cbHjP4v.mjs} +2 -2
- package/dist/{respond-BBYJsJ-G.mjs.map → respond--cbHjP4v.mjs.map} +1 -1
- package/dist/{rolldown-runtime-C4ng-APQ.mjs → rolldown-runtime-Bdw01CLM.mjs} +1 -1
- package/dist/{route-flag-DjDiOO3H.mjs → route-flag-Bjnd8inS.mjs} +3 -3
- package/dist/{route-flag-DjDiOO3H.mjs.map → route-flag-Bjnd8inS.mjs.map} +1 -1
- package/dist/{route-policy-BSaFqylB.mjs → route-policy-CiSCSa16.mjs} +2 -2
- package/dist/{route-policy-BSaFqylB.mjs.map → route-policy-CiSCSa16.mjs.map} +1 -1
- package/dist/{router-builder-BRmu4LTG.mjs → router-builder-BgoS_JoM.mjs} +3 -3
- package/dist/{router-builder-BRmu4LTG.mjs.map → router-builder-BgoS_JoM.mjs.map} +1 -1
- package/dist/{runtime-CeZOPbkB.mjs → runtime-BMyg1FYH.mjs} +3 -3
- package/dist/{runtime-CeZOPbkB.mjs.map → runtime-BMyg1FYH.mjs.map} +1 -1
- package/dist/{settings-DdExbzhu.mjs → settings-Ck0vWbOD.mjs} +3 -3
- package/dist/{settings-DdExbzhu.mjs.map → settings-Ck0vWbOD.mjs.map} +1 -1
- package/dist/{token-SjtN7iMS.mjs → token-BRZwz7iz.mjs} +1 -1
- package/dist/{upload-config-D8OMmdY7.mjs → upload-config-C_SlwFq0.mjs} +2 -2
- package/dist/{upload-config-D8OMmdY7.mjs.map → upload-config-C_SlwFq0.mjs.map} +1 -1
- package/dist/{url-for-YPjjzRlH.mjs → url-for-C5R5ZrDW.mjs} +3 -3
- package/dist/{url-for-YPjjzRlH.mjs.map → url-for-C5R5ZrDW.mjs.map} +1 -1
- package/dist/{view-renderer-CA8eJU23.mjs → view-renderer-BvDWb7GV.mjs} +3 -3
- package/dist/{view-renderer-CA8eJU23.mjs.map → view-renderer-BvDWb7GV.mjs.map} +1 -1
- package/dist/{web-crypto-iLWDbH8H.mjs → web-crypto-Dm0fWL80.mjs} +2 -2
- package/dist/{web-crypto-iLWDbH8H.mjs.map → web-crypto-Dm0fWL80.mjs.map} +1 -1
- package/dist/web.mjs +2 -2
- package/package.json +2 -2
- package/dist/application-QBVum-rq.mjs +0 -14
- package/dist/application-QBVum-rq.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-builder-BRmu4LTG.mjs","names":[],"sources":["../src/core/contributor-pipeline.ts","../src/http/router-builder.ts"],"sourcesContent":["import type { AnyContributorRegistration } from './context-decorator'\nimport {\n ContributorCycleError,\n DuplicateContributorError,\n MissingContributorError,\n} from './context-errors'\n\n/**\n * Where a contributor was registered, ordered by precedence\n * (lower index wins). Mirrors `architecture.md` §20.4.\n *\n * Levels (highest → lowest precedence):\n * - `'method'` — `@LoadX` on a controller method.\n * - `'class'` — `@LoadX` on a controller class.\n * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.\n * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies\n * to every module's routes.\n * - `'global'` — `ApplicationOptions.contributors`. App-wide default.\n */\nexport type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global'\n\n/** Precedence-ranked source list. Index = precedence; method (0) wins ties. */\nconst PRECEDENCE_ORDER: readonly ContributorSource[] = [\n 'method',\n 'class',\n 'module',\n 'adapter',\n 'global',\n]\n\n/**\n * Input row to {@link buildPipeline}. Pairs a registration with its origin\n * so dedup can apply the precedence rule and diagnostic errors can name\n * the offending site.\n *\n * `registration` is the type-erased {@link AnyContributorRegistration}\n * — the runner doesn't care about each registration's narrow `D` /\n * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic\n * contributors in the same `externalSources` / `contributors()`\n * array. The narrow generics from `defineContextDecorator` survive\n * at the *definition* site (where `resolve` is typed); they're erased\n * here so collections compose without `as any` casts.\n */\nexport interface SourcedRegistration {\n registration: AnyContributorRegistration\n source: ContributorSource\n /** Human label surfaced in DuplicateContributorError messages. */\n label?: string\n}\n\n/**\n * Resolved, validated, topo-sorted pipeline ready for execution.\n *\n * `contributors` is in execution order — every entry's `dependsOn`\n * keys appear earlier. `keys` is the set of all keys this pipeline\n * produces; the runner uses it for fast existence checks and the\n * builder uses it for missing-dep validation.\n */\nexport interface ContributorPipeline {\n readonly contributors: readonly AnyContributorRegistration[]\n readonly keys: ReadonlySet<string>\n}\n\nexport interface BuildPipelineOptions {\n /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */\n route?: string\n}\n\n/**\n * Build, validate, and topo-sort a contributor pipeline.\n *\n * Pipeline:\n *\n * 1. Group sources by precedence (method > class > module > adapter > global).\n * 2. Within each precedence level, two contributors with the same `key`\n * raise {@link DuplicateContributorError}.\n * 3. Across levels, the highest-precedence contributor wins each key\n * (lower-precedence duplicates are silently dropped — that is the\n * documented override mechanism, not an error).\n * 4. Every key referenced by `dependsOn` must be produced by the\n * surviving set, otherwise {@link MissingContributorError}.\n * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after\n * the queue drains form a cycle → {@link ContributorCycleError}\n * with a reconstructed path.\n *\n * Pure function — no DI, no I/O. Safe to call once at startup per\n * route and cache the result.\n */\nexport function buildPipeline(\n sources: readonly SourcedRegistration[],\n options: BuildPipelineOptions = {},\n): ContributorPipeline {\n const route = options.route\n\n // Step 1: group by source.\n const bySource = new Map<ContributorSource, SourcedRegistration[]>()\n for (const src of PRECEDENCE_ORDER) bySource.set(src, [])\n for (const entry of sources) bySource.get(entry.source)!.push(entry)\n\n // Step 2 + 3: dedup with precedence. We walk highest precedence first,\n // claim its keys, and drop lower-precedence rows that conflict.\n const winners = new Map<string, SourcedRegistration>()\n for (const src of PRECEDENCE_ORDER) {\n const rows = bySource.get(src)!\n const keysAtThisLevel = new Map<string, SourcedRegistration[]>()\n for (const row of rows) {\n const key = row.registration.key\n const existing = keysAtThisLevel.get(key) ?? []\n existing.push(row)\n keysAtThisLevel.set(key, existing)\n }\n for (const [key, rowsForKey] of keysAtThisLevel) {\n if (rowsForKey.length > 1) {\n const labels = rowsForKey.map((r, i) => r.label ?? `${src}#${i}`)\n throw new DuplicateContributorError(key, labels)\n }\n if (!winners.has(key)) winners.set(key, rowsForKey[0])\n }\n }\n\n const survivors = [...winners.values()].map((r) => r.registration)\n const allKeys = new Set(survivors.map((r) => r.key))\n\n // Step 4: dependsOn validation.\n for (const reg of survivors) {\n for (const dep of reg.dependsOn) {\n if (!allKeys.has(dep)) {\n throw new MissingContributorError(dep, reg.key, route, reg.definedAt)\n }\n }\n }\n\n // Step 5: Kahn topo-sort.\n const sorted = topoSort(survivors, route)\n\n return Object.freeze({\n contributors: Object.freeze(sorted),\n keys: allKeys,\n })\n}\n\n/**\n * Split a built pipeline into the contributors that run before request\n * validation (`beforeValidation: true`) and the rest, which keep their place\n * after `@Middleware()`. Both halves stay in topo order.\n *\n * An early contributor can only depend on other early ones — its dependency\n * would not have run yet otherwise — so that fails here, at boot.\n */\nexport function splitBeforeValidation(\n pipeline: ContributorPipeline,\n route?: string,\n): { early: ContributorPipeline | null; late: ContributorPipeline | null } {\n const early = pipeline.contributors.filter((reg) => reg.beforeValidation)\n if (early.length === 0) return { early: null, late: pipeline }\n\n const earlyKeys = new Set(early.map((reg) => reg.key))\n for (const reg of early) {\n const lateDep = reg.dependsOn.find((dep) => !earlyKeys.has(dep))\n if (lateDep !== undefined) {\n throw new Error(\n `Contributor '${reg.key}'${route ? ` on ${route}` : ''} sets beforeValidation but ` +\n `depends on '${lateDep}', which runs after validation. Set beforeValidation on ` +\n `'${lateDep}' too, or remove it from '${reg.key}'.`,\n )\n }\n }\n\n const late = pipeline.contributors.filter((reg) => !reg.beforeValidation)\n return {\n early: Object.freeze({ contributors: Object.freeze(early), keys: earlyKeys }),\n late:\n late.length === 0\n ? null\n : Object.freeze({\n contributors: Object.freeze(late),\n keys: new Set(late.map((reg) => reg.key)),\n }),\n }\n}\n\n/**\n * Kahn's algorithm with deterministic ordering on ties.\n *\n * Nodes with no remaining incoming edges enter the queue in input\n * order. Cycles surface as nodes still present after the queue\n * drains; we reconstruct one cycle path for diagnostics.\n */\nfunction topoSort(\n registrations: readonly AnyContributorRegistration[],\n route: string | undefined,\n): AnyContributorRegistration[] {\n // indegree[key] = number of unresolved dependsOn entries for key\n const indegree = new Map<string, number>()\n // dependents[depKey] = list of registrations that depend on depKey\n const dependents = new Map<string, AnyContributorRegistration[]>()\n const byKey = new Map<string, AnyContributorRegistration>()\n\n for (const reg of registrations) {\n indegree.set(reg.key, reg.dependsOn.length)\n byKey.set(reg.key, reg)\n }\n for (const reg of registrations) {\n for (const dep of reg.dependsOn) {\n const list = dependents.get(dep) ?? []\n list.push(reg)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: registrations with zero indegree, preserving input order.\n const queue: AnyContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: AnyContributorRegistration[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.key) ?? []) {\n const next = (indegree.get(dependent.key) ?? 0) - 1\n indegree.set(dependent.key, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== registrations.length) {\n const remaining = registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0)\n throw new ContributorCycleError(reconstructCycle(remaining, byKey), route)\n }\n\n return sorted\n}\n\n/**\n * Reconstruct one cycle path from the residual graph.\n *\n * Walks from any remaining node, following its first dependency that's\n * still in the residual set, until we revisit a node. The path returned\n * starts and ends with the same key so the message reads naturally:\n * `tenant → project → tenant`.\n */\nfunction reconstructCycle(\n residual: readonly AnyContributorRegistration[],\n byKey: ReadonlyMap<string, AnyContributorRegistration>,\n): string[] {\n const residualKeys = new Set(residual.map((r) => r.key))\n const start = residual[0].key\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor: string = start\n\n while (true) {\n const reg = byKey.get(cursor)!\n const nextDep = reg.dependsOn.find((d) => residualKeys.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n // Trim the prefix that isn't part of the cycle.\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n // Fallback — couldn't reconstruct a strict cycle, return what we walked.\n return path\n}\n","// Concrete-module imports (NOT the `../core` barrel): the barrel re-exports\n// the asset manager, whose eager `node:fs` import would poison the edge-safe\n// `@forinda/kickjs/web` entry graph that flows through this file.\nimport {\n buildPipeline,\n splitBeforeValidation,\n type SourcedRegistration,\n} from '../core/contributor-pipeline'\nimport { runContributors } from '../core/contributor-runner'\nimport { Container } from '../core/container'\nimport { METADATA } from '../core/interfaces'\nimport type { ContributorRegistration } from '../core/context-decorator'\nimport type { FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core/decorators'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport {\n getClassFlagDeclarations,\n getMethodFlagDeclarations,\n registerMountFlags,\n resolveRouteFlags,\n toFlagDeclarations,\n type RouteFlagDeclarations,\n} from '../core/route-flag'\nimport { duplicateRouteError } from '../core/kick-errors'\nimport type { CtxHandler, RouteContributor, RouteEntry, RouteMethod } from './runtime'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRouteTable() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRouteTable()/buildRoutes() callers (mostly tests) see only\n * class + method contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container.requestStoreProvider`: an internal escape hatch for\n * cross-module wiring without inversion-of-control gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\n/**\n * Boot-time duplicate-route guard shared by the node and web mount loops.\n *\n * Registers `METHOD /mounted/path` into `registry` and throws\n * {@link duplicateRouteError} (KICK006) if another handler already claimed\n * it. Param *names* are ignored — `/tasks/:id` and `/tasks/:taskId` are the\n * same route at dispatch time, so they collide here too.\n *\n * @internal\n */\nexport function assertRouteUnique(\n registry: Map<string, string>,\n method: string,\n fullPath: string,\n owner: string,\n): void {\n const key = `${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g, ':*')}`\n const prior = registry.get(key)\n if (prior !== undefined) {\n throw duplicateRouteError(method.toUpperCase(), fullPath, owner, prior)\n }\n registry.set(key, owner)\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRouteTable/buildRoutes\n * outside the Application route-mount loop (typically in tests). When omitted,\n * falls back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n /**\n * Flags the mounting module declares for every route on this controller\n * (`ModuleRoutes.flags`). Lowest precedence — a class or method declaration\n * of the same name wins, and `@Flag.off` on a method removes it.\n */\n mountFlags?: RouteFlagDeclarations\n}\n\n/**\n * Turn a controller class decorated with @Get, @Post, etc. into a plain-data\n * {@link RouteEntry}[] — the engine-neutral route table an {@link HttpRuntime}\n * materializes.\n *\n * What used to be per-handler Express `(req, res, next)` closures is now\n * captured as data: `middlewares` keep their `(ctx, next)` shape, the contributor\n * pipeline is pre-built into a `contributorRunner` closure, validation / upload\n * stay as metadata, and the terminal `handler` resolves the controller per-request\n * (to respect DI scoping) and invokes it. The runtime owns how these get wrapped\n * onto its engine.\n *\n * Routes use only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked in — it is metadata for Swagger/introspection.\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the path.\n *\n * The contributor pipeline is built here, so a cycle or missing `dependsOn`\n * throws at table-build time (boot) rather than on first request.\n */\nexport function buildRouteTable(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): RouteEntry[] {\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n // Route flags declared on the controller — inherited by every method below\n // unless a method declares the same flag `false` (see core/route-flag.ts).\n const classFlagDeclarations = getClassFlagDeclarations(controllerClass)\n\n // Flags the module declared for this whole mount. Recorded against the class\n // so `getRouteFlags()` — the resolver Swagger and DevTools use, which sees no\n // mount — reports what the runtime actually resolved.\n const mountFlagDeclarations = toFlagDeclarations(\n options.mountFlags,\n `${controllerClass?.name ?? 'controller'} mount flags`,\n )\n registerMountFlags(controllerClass, mountFlagDeclarations)\n\n const entries: RouteEntry[] = []\n\n for (const route of routes) {\n const method = route.method.toUpperCase() as RouteMethod\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // @FileUpload decorator — runtime supplies the upload backend.\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Flags in force for THIS route: class declarations overridden by method\n // ones. Resolved at build time so the per-request cost is a map lookup.\n const flags = resolveRouteFlags(\n classFlagDeclarations,\n getMethodFlagDeclarations(controllerClass, route.handlerName),\n mountFlagDeclarations,\n )\n\n let contributorRunner: CtxHandler | null = null\n let earlyContributorRunner: CtxHandler | null = null\n let contributors: RouteContributor[] | undefined\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map((registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n })),\n ...classContributors.map((registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n })),\n ...externalSources,\n ]\n const routeLabel = `${method} ${fullPath}`\n const pipeline = buildPipeline(sources, { route: routeLabel })\n contributors = describePipeline(pipeline.contributors, sources)\n const { early, late } = splitBeforeValidation(pipeline, routeLabel)\n if (early) {\n earlyContributorRunner = (ctx) =>\n runContributors({ pipeline: early, ctx, container, flags })\n }\n if (late) {\n contributorRunner = (ctx) => runContributors({ pipeline: late, ctx, container, flags })\n }\n }\n\n // Terminal handler — resolve controller per-request to respect DI scoping.\n const handler: CtxHandler = (ctx) => container.resolve(controllerClass)[route.handlerName](ctx)\n\n entries.push({\n method,\n path: fullPath,\n middlewares: [...classMiddlewares, ...methodMiddlewares],\n contributorRunner,\n earlyContributorRunner,\n handler,\n meta: {\n controller: controllerClass,\n handlerName: route.handlerName,\n validation: route.validation,\n upload: fileUploadConfig,\n flags,\n ...(contributors ? { contributors } : {}),\n },\n })\n }\n\n return entries\n}\n\n/**\n * The pipeline as introspection shows it. The built pipeline keeps only the\n * registrations; their sources and labels are recovered from the inputs by\n * identity, along with the lower-precedence registrations each one replaced.\n */\nfunction describePipeline(\n ordered: readonly SourcedRegistration['registration'][],\n sources: readonly SourcedRegistration[],\n): RouteContributor[] {\n const bySource = new Map(sources.map((s) => [s.registration, s]))\n // Execution order: the pipeline is split at run time — `beforeValidation`\n // ones run first, ahead of middleware and validation, then the rest. Each\n // half keeps its dependency order.\n const runOrder = [\n ...ordered.filter((r) => r.beforeValidation === true),\n ...ordered.filter((r) => r.beforeValidation !== true),\n ]\n return runOrder.map((registration) => {\n const winner = bySource.get(registration)\n const described: RouteContributor = {\n key: registration.key,\n source: winner?.source ?? 'global',\n dependsOn: registration.dependsOn,\n beforeValidation: registration.beforeValidation === true,\n overrides: sources\n .filter((s) => s.registration !== registration && s.registration.key === registration.key)\n .map((s) => (s.label ? { source: s.source, label: s.label } : { source: s.source })),\n }\n if (winner?.label) described.label = winner.label\n return described\n })\n}\n"],"mappings":";;;;;;;;;;+mBAsBA,MAAM,iBAAiD,CACrD,SACA,QACA,SACA,UACA,QACF,EA4DA,SAAgB,cACd,QACA,QAAgC,CAAC,EACZ,CACrB,IAAM,MAAQ,QAAQ,MAGhB,yBAAW,IAAI,IACrB,IAAK,IAAM,OAAO,iBAAkB,SAAS,IAAI,IAAK,CAAC,CAAC,EACxD,IAAK,IAAM,SAAS,QAAS,SAAS,IAAI,MAAM,MAAM,CAAC,CAAE,KAAK,KAAK,EAInE,IAAM,wBAAU,IAAI,IACpB,IAAK,IAAM,OAAO,iBAAkB,CAClC,IAAM,KAAO,SAAS,IAAI,GAAG,EACvB,gCAAkB,IAAI,IAC5B,IAAK,IAAM,OAAO,KAAM,CACtB,IAAM,IAAM,IAAI,aAAa,IACvB,SAAW,gBAAgB,IAAI,GAAG,GAAK,CAAC,EAC9C,SAAS,KAAK,GAAG,EACjB,gBAAgB,IAAI,IAAK,QAAQ,CACnC,CACA,IAAK,GAAM,CAAC,IAAK,cAAe,gBAAiB,CAC/C,GAAI,WAAW,OAAS,EAAG,CACzB,IAAM,OAAS,WAAW,KAAK,EAAG,IAAM,EAAE,OAAS,GAAG,IAAI,GAAG,GAAG,EAChE,MAAM,IAAI,0BAA0B,IAAK,MAAM,CACjD,CACK,QAAQ,IAAI,GAAG,GAAG,QAAQ,IAAI,IAAK,WAAW,EAAE,CACvD,CACF,CAEA,IAAM,UAAY,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC,CAAC,IAAK,GAAM,EAAE,YAAY,EAC3D,QAAU,IAAI,IAAI,UAAU,IAAK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,CAAC,EAAE,aAAc,CAAC,CAAC,CAAC,EAQhE,MAAO,CAHL,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,EACpD,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,CAExC,CAAC,CAAC,IAAK,cAAiB,CACpC,IAAM,OAAS,SAAS,IAAI,YAAY,EAClC,UAA8B,CAClC,IAAK,aAAa,IAClB,OAAQ,QAAQ,QAAU,SAC1B,UAAW,aAAa,UACxB,iBAAkB,aAAa,mBAAqB,GACpD,UAAW,QACR,OAAQ,GAAM,EAAE,eAAiB,cAAgB,EAAE,aAAa,MAAQ,aAAa,GAAG,CAAC,CACzF,IAAK,GAAO,EAAE,MAAQ,CAAE,OAAQ,EAAE,OAAQ,MAAO,EAAE,KAAM,EAAI,CAAE,OAAQ,EAAE,MAAO,CAAE,CACvF,EAEA,OADI,QAAQ,QAAO,UAAU,MAAQ,OAAO,OACrC,SACT,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"router-builder-BgoS_JoM.mjs","names":[],"sources":["../src/core/contributor-pipeline.ts","../src/http/router-builder.ts"],"sourcesContent":["import type { AnyContributorRegistration } from './context-decorator'\nimport {\n ContributorCycleError,\n DuplicateContributorError,\n MissingContributorError,\n} from './context-errors'\n\n/**\n * Where a contributor was registered, ordered by precedence\n * (lower index wins). Mirrors `architecture.md` §20.4.\n *\n * Levels (highest → lowest precedence):\n * - `'method'` — `@LoadX` on a controller method.\n * - `'class'` — `@LoadX` on a controller class.\n * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.\n * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies\n * to every module's routes.\n * - `'global'` — `ApplicationOptions.contributors`. App-wide default.\n */\nexport type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global'\n\n/** Precedence-ranked source list. Index = precedence; method (0) wins ties. */\nconst PRECEDENCE_ORDER: readonly ContributorSource[] = [\n 'method',\n 'class',\n 'module',\n 'adapter',\n 'global',\n]\n\n/**\n * Input row to {@link buildPipeline}. Pairs a registration with its origin\n * so dedup can apply the precedence rule and diagnostic errors can name\n * the offending site.\n *\n * `registration` is the type-erased {@link AnyContributorRegistration}\n * — the runner doesn't care about each registration's narrow `D` /\n * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic\n * contributors in the same `externalSources` / `contributors()`\n * array. The narrow generics from `defineContextDecorator` survive\n * at the *definition* site (where `resolve` is typed); they're erased\n * here so collections compose without `as any` casts.\n */\nexport interface SourcedRegistration {\n registration: AnyContributorRegistration\n source: ContributorSource\n /** Human label surfaced in DuplicateContributorError messages. */\n label?: string\n}\n\n/**\n * Resolved, validated, topo-sorted pipeline ready for execution.\n *\n * `contributors` is in execution order — every entry's `dependsOn`\n * keys appear earlier. `keys` is the set of all keys this pipeline\n * produces; the runner uses it for fast existence checks and the\n * builder uses it for missing-dep validation.\n */\nexport interface ContributorPipeline {\n readonly contributors: readonly AnyContributorRegistration[]\n readonly keys: ReadonlySet<string>\n}\n\nexport interface BuildPipelineOptions {\n /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */\n route?: string\n}\n\n/**\n * Build, validate, and topo-sort a contributor pipeline.\n *\n * Pipeline:\n *\n * 1. Group sources by precedence (method > class > module > adapter > global).\n * 2. Within each precedence level, two contributors with the same `key`\n * raise {@link DuplicateContributorError}.\n * 3. Across levels, the highest-precedence contributor wins each key\n * (lower-precedence duplicates are silently dropped — that is the\n * documented override mechanism, not an error).\n * 4. Every key referenced by `dependsOn` must be produced by the\n * surviving set, otherwise {@link MissingContributorError}.\n * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after\n * the queue drains form a cycle → {@link ContributorCycleError}\n * with a reconstructed path.\n *\n * Pure function — no DI, no I/O. Safe to call once at startup per\n * route and cache the result.\n */\nexport function buildPipeline(\n sources: readonly SourcedRegistration[],\n options: BuildPipelineOptions = {},\n): ContributorPipeline {\n const route = options.route\n\n // Step 1: group by source.\n const bySource = new Map<ContributorSource, SourcedRegistration[]>()\n for (const src of PRECEDENCE_ORDER) bySource.set(src, [])\n for (const entry of sources) bySource.get(entry.source)!.push(entry)\n\n // Step 2 + 3: dedup with precedence. We walk highest precedence first,\n // claim its keys, and drop lower-precedence rows that conflict.\n const winners = new Map<string, SourcedRegistration>()\n for (const src of PRECEDENCE_ORDER) {\n const rows = bySource.get(src)!\n const keysAtThisLevel = new Map<string, SourcedRegistration[]>()\n for (const row of rows) {\n const key = row.registration.key\n const existing = keysAtThisLevel.get(key) ?? []\n existing.push(row)\n keysAtThisLevel.set(key, existing)\n }\n for (const [key, rowsForKey] of keysAtThisLevel) {\n if (rowsForKey.length > 1) {\n const labels = rowsForKey.map((r, i) => r.label ?? `${src}#${i}`)\n throw new DuplicateContributorError(key, labels)\n }\n if (!winners.has(key)) winners.set(key, rowsForKey[0])\n }\n }\n\n const survivors = [...winners.values()].map((r) => r.registration)\n const allKeys = new Set(survivors.map((r) => r.key))\n\n // Step 4: dependsOn validation.\n for (const reg of survivors) {\n for (const dep of reg.dependsOn) {\n if (!allKeys.has(dep)) {\n throw new MissingContributorError(dep, reg.key, route, reg.definedAt)\n }\n }\n }\n\n // Step 5: Kahn topo-sort.\n const sorted = topoSort(survivors, route)\n\n return Object.freeze({\n contributors: Object.freeze(sorted),\n keys: allKeys,\n })\n}\n\n/**\n * Split a built pipeline into the contributors that run before request\n * validation (`beforeValidation: true`) and the rest, which keep their place\n * after `@Middleware()`. Both halves stay in topo order.\n *\n * An early contributor can only depend on other early ones — its dependency\n * would not have run yet otherwise — so that fails here, at boot.\n */\nexport function splitBeforeValidation(\n pipeline: ContributorPipeline,\n route?: string,\n): { early: ContributorPipeline | null; late: ContributorPipeline | null } {\n const early = pipeline.contributors.filter((reg) => reg.beforeValidation)\n if (early.length === 0) return { early: null, late: pipeline }\n\n const earlyKeys = new Set(early.map((reg) => reg.key))\n for (const reg of early) {\n const lateDep = reg.dependsOn.find((dep) => !earlyKeys.has(dep))\n if (lateDep !== undefined) {\n throw new Error(\n `Contributor '${reg.key}'${route ? ` on ${route}` : ''} sets beforeValidation but ` +\n `depends on '${lateDep}', which runs after validation. Set beforeValidation on ` +\n `'${lateDep}' too, or remove it from '${reg.key}'.`,\n )\n }\n }\n\n const late = pipeline.contributors.filter((reg) => !reg.beforeValidation)\n return {\n early: Object.freeze({ contributors: Object.freeze(early), keys: earlyKeys }),\n late:\n late.length === 0\n ? null\n : Object.freeze({\n contributors: Object.freeze(late),\n keys: new Set(late.map((reg) => reg.key)),\n }),\n }\n}\n\n/**\n * Kahn's algorithm with deterministic ordering on ties.\n *\n * Nodes with no remaining incoming edges enter the queue in input\n * order. Cycles surface as nodes still present after the queue\n * drains; we reconstruct one cycle path for diagnostics.\n */\nfunction topoSort(\n registrations: readonly AnyContributorRegistration[],\n route: string | undefined,\n): AnyContributorRegistration[] {\n // indegree[key] = number of unresolved dependsOn entries for key\n const indegree = new Map<string, number>()\n // dependents[depKey] = list of registrations that depend on depKey\n const dependents = new Map<string, AnyContributorRegistration[]>()\n const byKey = new Map<string, AnyContributorRegistration>()\n\n for (const reg of registrations) {\n indegree.set(reg.key, reg.dependsOn.length)\n byKey.set(reg.key, reg)\n }\n for (const reg of registrations) {\n for (const dep of reg.dependsOn) {\n const list = dependents.get(dep) ?? []\n list.push(reg)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: registrations with zero indegree, preserving input order.\n const queue: AnyContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: AnyContributorRegistration[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.key) ?? []) {\n const next = (indegree.get(dependent.key) ?? 0) - 1\n indegree.set(dependent.key, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== registrations.length) {\n const remaining = registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0)\n throw new ContributorCycleError(reconstructCycle(remaining, byKey), route)\n }\n\n return sorted\n}\n\n/**\n * Reconstruct one cycle path from the residual graph.\n *\n * Walks from any remaining node, following its first dependency that's\n * still in the residual set, until we revisit a node. The path returned\n * starts and ends with the same key so the message reads naturally:\n * `tenant → project → tenant`.\n */\nfunction reconstructCycle(\n residual: readonly AnyContributorRegistration[],\n byKey: ReadonlyMap<string, AnyContributorRegistration>,\n): string[] {\n const residualKeys = new Set(residual.map((r) => r.key))\n const start = residual[0].key\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor: string = start\n\n while (true) {\n const reg = byKey.get(cursor)!\n const nextDep = reg.dependsOn.find((d) => residualKeys.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n // Trim the prefix that isn't part of the cycle.\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n // Fallback — couldn't reconstruct a strict cycle, return what we walked.\n return path\n}\n","// Concrete-module imports (NOT the `../core` barrel): the barrel re-exports\n// the asset manager, whose eager `node:fs` import would poison the edge-safe\n// `@forinda/kickjs/web` entry graph that flows through this file.\nimport {\n buildPipeline,\n splitBeforeValidation,\n type SourcedRegistration,\n} from '../core/contributor-pipeline'\nimport { runContributors } from '../core/contributor-runner'\nimport { Container } from '../core/container'\nimport { METADATA } from '../core/interfaces'\nimport type { ContributorRegistration } from '../core/context-decorator'\nimport type { FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core/decorators'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport {\n getClassFlagDeclarations,\n getMethodFlagDeclarations,\n registerMountFlags,\n resolveRouteFlags,\n toFlagDeclarations,\n type RouteFlagDeclarations,\n} from '../core/route-flag'\nimport { duplicateRouteError } from '../core/kick-errors'\nimport type { CtxHandler, RouteContributor, RouteEntry, RouteMethod } from './runtime'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRouteTable() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRouteTable()/buildRoutes() callers (mostly tests) see only\n * class + method contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container.requestStoreProvider`: an internal escape hatch for\n * cross-module wiring without inversion-of-control gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\n/**\n * Boot-time duplicate-route guard shared by the node and web mount loops.\n *\n * Registers `METHOD /mounted/path` into `registry` and throws\n * {@link duplicateRouteError} (KICK006) if another handler already claimed\n * it. Param *names* are ignored — `/tasks/:id` and `/tasks/:taskId` are the\n * same route at dispatch time, so they collide here too.\n *\n * @internal\n */\nexport function assertRouteUnique(\n registry: Map<string, string>,\n method: string,\n fullPath: string,\n owner: string,\n): void {\n const key = `${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g, ':*')}`\n const prior = registry.get(key)\n if (prior !== undefined) {\n throw duplicateRouteError(method.toUpperCase(), fullPath, owner, prior)\n }\n registry.set(key, owner)\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRouteTable/buildRoutes\n * outside the Application route-mount loop (typically in tests). When omitted,\n * falls back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n /**\n * Flags the mounting module declares for every route on this controller\n * (`ModuleRoutes.flags`). Lowest precedence — a class or method declaration\n * of the same name wins, and `@Flag.off` on a method removes it.\n */\n mountFlags?: RouteFlagDeclarations\n}\n\n/**\n * Turn a controller class decorated with @Get, @Post, etc. into a plain-data\n * {@link RouteEntry}[] — the engine-neutral route table an {@link HttpRuntime}\n * materializes.\n *\n * What used to be per-handler Express `(req, res, next)` closures is now\n * captured as data: `middlewares` keep their `(ctx, next)` shape, the contributor\n * pipeline is pre-built into a `contributorRunner` closure, validation / upload\n * stay as metadata, and the terminal `handler` resolves the controller per-request\n * (to respect DI scoping) and invokes it. The runtime owns how these get wrapped\n * onto its engine.\n *\n * Routes use only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked in — it is metadata for Swagger/introspection.\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the path.\n *\n * The contributor pipeline is built here, so a cycle or missing `dependsOn`\n * throws at table-build time (boot) rather than on first request.\n */\nexport function buildRouteTable(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): RouteEntry[] {\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n // Route flags declared on the controller — inherited by every method below\n // unless a method declares the same flag `false` (see core/route-flag.ts).\n const classFlagDeclarations = getClassFlagDeclarations(controllerClass)\n\n // Flags the module declared for this whole mount. Recorded against the class\n // so `getRouteFlags()` — the resolver Swagger and DevTools use, which sees no\n // mount — reports what the runtime actually resolved.\n const mountFlagDeclarations = toFlagDeclarations(\n options.mountFlags,\n `${controllerClass?.name ?? 'controller'} mount flags`,\n )\n registerMountFlags(controllerClass, mountFlagDeclarations)\n\n const entries: RouteEntry[] = []\n\n for (const route of routes) {\n const method = route.method.toUpperCase() as RouteMethod\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // @FileUpload decorator — runtime supplies the upload backend.\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Flags in force for THIS route: class declarations overridden by method\n // ones. Resolved at build time so the per-request cost is a map lookup.\n const flags = resolveRouteFlags(\n classFlagDeclarations,\n getMethodFlagDeclarations(controllerClass, route.handlerName),\n mountFlagDeclarations,\n )\n\n let contributorRunner: CtxHandler | null = null\n let earlyContributorRunner: CtxHandler | null = null\n let contributors: RouteContributor[] | undefined\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map((registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n })),\n ...classContributors.map((registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n })),\n ...externalSources,\n ]\n const routeLabel = `${method} ${fullPath}`\n const pipeline = buildPipeline(sources, { route: routeLabel })\n contributors = describePipeline(pipeline.contributors, sources)\n const { early, late } = splitBeforeValidation(pipeline, routeLabel)\n if (early) {\n earlyContributorRunner = (ctx) =>\n runContributors({ pipeline: early, ctx, container, flags })\n }\n if (late) {\n contributorRunner = (ctx) => runContributors({ pipeline: late, ctx, container, flags })\n }\n }\n\n // Terminal handler — resolve controller per-request to respect DI scoping.\n const handler: CtxHandler = (ctx) => container.resolve(controllerClass)[route.handlerName](ctx)\n\n entries.push({\n method,\n path: fullPath,\n middlewares: [...classMiddlewares, ...methodMiddlewares],\n contributorRunner,\n earlyContributorRunner,\n handler,\n meta: {\n controller: controllerClass,\n handlerName: route.handlerName,\n validation: route.validation,\n upload: fileUploadConfig,\n flags,\n ...(contributors ? { contributors } : {}),\n },\n })\n }\n\n return entries\n}\n\n/**\n * The pipeline as introspection shows it. The built pipeline keeps only the\n * registrations; their sources and labels are recovered from the inputs by\n * identity, along with the lower-precedence registrations each one replaced.\n */\nfunction describePipeline(\n ordered: readonly SourcedRegistration['registration'][],\n sources: readonly SourcedRegistration[],\n): RouteContributor[] {\n const bySource = new Map(sources.map((s) => [s.registration, s]))\n // Execution order: the pipeline is split at run time — `beforeValidation`\n // ones run first, ahead of middleware and validation, then the rest. Each\n // half keeps its dependency order.\n const runOrder = [\n ...ordered.filter((r) => r.beforeValidation === true),\n ...ordered.filter((r) => r.beforeValidation !== true),\n ]\n return runOrder.map((registration) => {\n const winner = bySource.get(registration)\n const described: RouteContributor = {\n key: registration.key,\n source: winner?.source ?? 'global',\n dependsOn: registration.dependsOn,\n beforeValidation: registration.beforeValidation === true,\n overrides: sources\n .filter((s) => s.registration !== registration && s.registration.key === registration.key)\n .map((s) => (s.label ? { source: s.source, label: s.label } : { source: s.source })),\n }\n if (winner?.label) described.label = winner.label\n return described\n })\n}\n"],"mappings":";;;;;;;;;;+mBAsBA,MAAM,iBAAiD,CACrD,SACA,QACA,SACA,UACA,QACF,EA4DA,SAAgB,cACd,QACA,QAAgC,CAAC,EACZ,CACrB,IAAM,MAAQ,QAAQ,MAGhB,yBAAW,IAAI,IACrB,IAAK,IAAM,OAAO,iBAAkB,SAAS,IAAI,IAAK,CAAC,CAAC,EACxD,IAAK,IAAM,SAAS,QAAS,SAAS,IAAI,MAAM,MAAM,CAAC,CAAE,KAAK,KAAK,EAInE,I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AU,MAAQ,OAAO,OACrC,SACT,CAAC,CACH"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.3
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as ROUTE_SLOT}from"./route-flag-
|
|
12
|
-
//# sourceMappingURL=runtime-
|
|
11
|
+
import{t as ROUTE_SLOT}from"./route-flag-Bjnd8inS.mjs";function publishMatchedRoute(req,entry){let route=matchedRoutes.get(entry);route||(route=Object.freeze({method:entry.method,path:entry.path,controller:entry.meta.controller,handlerName:entry.meta.handlerName,flags:entry.meta.flags??EMPTY_FLAGS,pattern:entry.meta.pattern??entry.path,urls:entry.urls}),matchedRoutes.set(entry,route)),req[ROUTE_SLOT]=route}const matchedRoutes=/* @__PURE__ */ new WeakMap,EMPTY_FLAGS=/* @__PURE__ */ new Map;function isBigIntJsonError(err){return err instanceof TypeError&&/BigInt/.test(err.message)}function stringifyJson(data){try{return JSON.stringify(data)}catch(err){if(!isBigIntJsonError(err))throw err;return JSON.stringify(data,(_key,value)=>typeof value==`bigint`?value.toString():value)}}export{publishMatchedRoute as n,stringifyJson as r,isBigIntJsonError as t};
|
|
12
|
+
//# sourceMappingURL=runtime-BMyg1FYH.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-CeZOPbkB.mjs","names":[],"sources":["../src/http/runtime.ts"],"sourcesContent":["// The HttpRuntime seam.\n//\n// Decorators no longer emit an `express.Router` directly. `buildRouteTable()`\n// turns controller metadata into a plain-data `RouteEntry[]`; an `HttpRuntime`\n// materializes that table onto whatever engine it owns. Express is the default\n// runtime and the only one shipped in M1 — its materializer reproduces the exact\n// handler chain the old `buildRoutes()` built, so behavior is unchanged.\n//\n// Fastify / h3 runtimes (later milestones) consume the SAME `RouteEntry` data\n// and the SAME `HttpRuntime` contract; the request/response driver abstraction\n// that lets `RequestContext` run engine-agnostically lands with them (M3), since\n// under Express the drivers ARE the Express request/response objects already.\n//\n// Why a seam: running Fastify / h3 behind an Express-compat layer\n// (`@fastify/express`, h3's node bridge) bypasses their router and\n// serialization, and rebuilding `ctx` over web-standard Request/Response\n// would break SSE / streaming, multer uploads and `ctx.res` for every adopter.\n// The seam keeps `ctx` and swaps only the engine underneath it.\n\nimport { ROUTE_SLOT, type RouteFlags } from '../core/route-flag'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ConnectMiddleware, ConnectRequest, ConnectResponse } from './connect'\n\nimport type { Constructor, FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core'\nimport type { RequestContext } from './context'\nimport type { ValidationErrorFactory } from './middleware/validate'\nimport type { RouteUrls } from './url-for'\nimport type { ContributorSource } from '../core/contributor-pipeline'\n\n/** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */\nexport type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n\n/**\n * A context-based handler: the runtime-neutral unit of the request pipeline.\n * Contributors, route middleware (via {@link MiddlewareHandler}), and the\n * terminal controller call all reduce to this shape. The runtime owns how a\n * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,\n * next)`; Fastify in its own handler).\n */\nexport type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>\n\n/**\n * Connect-style middleware — the portable middleware format. Built-in\n * middleware and adopter-supplied Express middleware are this shape. The\n * Express runtime hands them straight to `app.use`; the others bridge them\n * (Fastify via `@fastify/middie`, h3 via its node adapter). See `./connect`.\n */\nexport type { ConnectMiddleware }\n\n/**\n * One materialized route, as plain data. Produced by {@link buildRouteTable}\n * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.\n *\n * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`\n * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),\n * `contributorRunner` is a closure over the pre-built pipeline + container (the\n * pipeline is built — and any cycle / missing-dep error thrown — at table-build\n * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime\n * materializes its own way. Faithfully reproducing the legacy Express chain —\n * not collapsing it — is what keeps M1 behavior-neutral.\n */\nexport interface RouteEntry {\n method: RouteMethod\n /** Path with `:param` segments — the portable subset all engines accept. */\n path: string\n /** Class + method middleware, in execution order; each receives `(ctx, next)`. */\n middlewares: MiddlewareHandler[]\n /**\n * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),\n * or `null` when no contributors apply. Closes over the built pipeline and\n * the DI container so it stays engine-neutral; the runtime advances the\n * chain (Express: call `next()`) once it resolves.\n */\n contributorRunner: CtxHandler | null\n /**\n * Contributors registered with `beforeValidation: true`. Runtimes run this\n * right after publishing the matched route — before validation, upload and\n * middleware — so a rejection (401) lands before a malformed body's 422.\n * Absent or `null` when no contributor asks for it.\n */\n earlyContributorRunner?: CtxHandler | null\n /** The app's `validationError` — what this route's validation failure throws. */\n validationError?: ValidationErrorFactory\n /** The app's route names → paths, for `ctx.urlFor()`. */\n urls?: RouteUrls\n /** Terminal handler: resolves the controller per-request and invokes it. */\n handler: CtxHandler\n /** Introspection + runtime-materialized concerns (swagger/typegen read this). */\n meta: RouteMeta\n}\n\n/** Per-route metadata: introspection refs plus runtime-materialized concerns. */\n/**\n * One context contributor on a route, as introspection sees it: the\n * contributors a request runs, in execution order. Built with the route.\n */\nexport interface RouteContributor {\n /** The key it sets with `ctx.set(...)`. */\n key: string\n /** Where it was registered — `method` / `class` decorators, or a module, adapter or global list. */\n source: ContributorSource\n /** The registering site, e.g. `UsersController.show#0(tenant)` or a module name. */\n label?: string\n dependsOn: readonly string[]\n /** Runs before validation (`beforeValidation: true`). */\n beforeValidation: boolean\n /** Lower-precedence registrations of the same key this one replaced. */\n overrides: ReadonlyArray<{ source: ContributorSource; label?: string }>\n}\n\nexport interface RouteMeta {\n /**\n * Owning controller class — for DI resolution and adapter introspection.\n * Absent for ad-hoc routes registered through {@link AdapterHttp.route},\n * which have no controller class behind them.\n */\n controller?: Constructor\n /** Handler method name on the controller, when there is one. */\n handlerName?: string\n /** The route's context contributors, in execution order — for devtools / introspection. */\n contributors?: readonly RouteContributor[]\n /** Zod/JSON-schema validation config from the route decorator, if any. */\n validation?: RouteDefinition['validation']\n /** `@FileUpload` config, if present — the runtime supplies the backend. */\n upload?: FileUploadConfig\n /**\n * Route flags in force here, resolved at build time (method over class).\n * Enabled flags only: a flag declared `false` at a higher-precedence site is\n * absent rather than present-and-false, so `has()` is always the right\n * question. See `core/route-flag.ts`.\n */\n flags?: RouteFlags\n /**\n * The full mounted pattern (`/api/v1/users/:id`) — set by the Application\n * for controller routes. `path` is relative to the module mount.\n */\n pattern?: string\n}\n\n/**\n * The route a request matched, published on `ctx.route`.\n *\n * Everything that holds a {@link RequestContext} — handlers, `@Middleware()`,\n * guards, contributors — can read it, which is what lets one declaration on a\n * route serve every consumer.\n */\n/**\n * Publish the matched route on the request, for `ctx.route` to read.\n *\n * Called by each runtime once per dispatch, before it builds a RequestContext.\n * It lives on `req` rather than on the ctx because the Express runtime\n * constructs a fresh RequestContext per middleware step — anything written to\n * one ctx would be invisible to the next and to the handler.\n */\nexport function publishMatchedRoute(req: unknown, entry: RouteEntry): void {\n // One object per route, shared by its requests — every field comes from the\n // entry, which is final once mounted. Frozen, since it is shared.\n let route = matchedRoutes.get(entry)\n if (!route) {\n route = Object.freeze({\n method: entry.method,\n path: entry.path,\n controller: entry.meta.controller,\n handlerName: entry.meta.handlerName,\n flags: entry.meta.flags ?? EMPTY_FLAGS,\n pattern: entry.meta.pattern ?? entry.path,\n urls: entry.urls,\n })\n matchedRoutes.set(entry, route)\n }\n ;(req as Record<symbol, MatchedRoute>)[ROUTE_SLOT] = route\n}\n\nconst matchedRoutes = new WeakMap<RouteEntry, MatchedRoute>()\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\nexport interface MatchedRoute {\n readonly method: RouteMethod\n /** Path as declared on the handler, e.g. `/:id`. */\n readonly path: string\n /**\n * The full route pattern including the mount prefix and version, e.g.\n * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls\n * back to `path` for routes registered without a mount.\n */\n readonly pattern: string\n readonly controller?: Constructor\n readonly handlerName?: string\n /** Enabled flags only — see {@link RouteMeta.flags}. */\n readonly flags: RouteFlags\n /** @internal The app's route names, for `ctx.urlFor()`. */\n readonly urls?: RouteUrls\n}\n\n/** A controller's routes grouped under the module mount prefix. */\nexport type RouteTable = { mountPath: string; routes: RouteEntry[] }[]\n\n/**\n * The response surface {@link RequestContext}'s helpers (`json` / `html` /\n * `sse` / `download` / `render` / `problem`) drive, instead of calling Express\n * `res` methods directly (spec §4.3). Sized so `express.Response` satisfies it\n * structurally — under the Express runtime the driver IS the Express response,\n * so there is no wrapping and no behavior change. Other runtimes (Fastify / h3)\n * provide a thin object implementing this over their native reply.\n *\n * The terminal methods return `RuntimeResponse` for fluent chaining (Express's\n * `Response` is assignable, since it is a superset).\n */\n/** True for the TypeError `JSON.stringify` throws on a bigint. */\nexport function isBigIntJsonError(err: unknown): boolean {\n return err instanceof TypeError && /BigInt/.test(err.message)\n}\n\n/**\n * `JSON.stringify` that writes a bigint as its decimal string instead of\n * throwing — database counts and `bigint` columns reach responses as bigints.\n * Plain `JSON.stringify` runs first, so a body without one costs nothing extra.\n */\nexport function stringifyJson(data: unknown): string {\n try {\n return JSON.stringify(data)\n } catch (err) {\n if (!isBigIntJsonError(err)) throw err\n return JSON.stringify(data, (_key, value) =>\n typeof value === 'bigint' ? value.toString() : value,\n )\n }\n}\n\nexport interface RuntimeResponse {\n status(code: number): RuntimeResponse\n json(data: unknown): RuntimeResponse\n send(data: unknown): RuntimeResponse\n type(contentType: string): RuntimeResponse\n setHeader(name: string, value: string | number | readonly string[]): unknown\n render(view: string, data?: Record<string, unknown>): unknown\n writeHead(statusCode: number, headers?: Record<string, string>): unknown\n flushHeaders(): unknown\n write(chunk: string | Buffer): boolean\n end(data?: unknown): unknown\n once(event: 'close' | 'drain', listener: () => void): unknown\n readonly headersSent: boolean\n}\n\n// ── Runtime-typed escape hatches (spec §4.3b) ─────────────────────────────\n\n/**\n * Per-runtime type map: the engine-native request / response / app types an\n * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.\n */\nexport interface RuntimeTypeMap {\n request: unknown\n response: unknown\n app: unknown\n}\n\n/**\n * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen\n * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured\n * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,\n * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`\n * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is\n * uniform with `kick/db` and env typing.\n *\n * @example\n * ```ts\n * // .kickjs/types/kick__runtime.d.ts — generated by typegen\n * declare module '@forinda/kickjs' {\n * interface KickRuntimeRegister {\n * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes\n * }\n * }\n * ```\n */\n\nexport interface KickRuntimeRegister {}\n\n/**\n * The active runtime's type map — the augmented one, or the connect-style\n * {@link ConnectRuntimeTypes} when nothing is augmented. `kick typegen` augments it from kick.config's\n * `runtime`, Express included.\n */\nexport type ActiveRuntime = KickRuntimeRegister extends { runtime: infer R extends RuntimeTypeMap }\n ? R\n : ConnectRuntimeTypes\n\n/**\n * What the escape hatches are typed as with no augmentation: the connect-style\n * request and response every runtime's middleware sees, and an app of unknown\n * engine.\n */\nexport interface ConnectRuntimeTypes {\n request: ConnectRequest\n response: ConnectResponse\n app: unknown\n}\n\n/** Options passed to {@link HttpRuntime.createApp}. */\nexport interface RuntimeAppOptions {\n /**\n * Express `trust proxy` setting (and the equivalent on other engines). The\n * function form is Express-specific; other runtimes interpret the simpler\n * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).\n */\n trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean)\n /**\n * When the app is mounted inside another handler (`kick dev`'s Vite server,\n * `app.handle(req, res, next)` in a host server), hand requests no route\n * matched back to it — `true`, the default — or answer them here with the\n * app's not-found handling — `false`. Express always answers.\n */\n notFoundFallthrough?: boolean\n /** Largest request body the engine parses, in bytes — `jsonLimit`, resolved. */\n bodyLimit?: number\n}\n\n/** Where a connect middleware sits and what it scopes to. */\nexport interface UseConnectOptions {\n path?: string | RegExp | ReadonlyArray<string | RegExp>\n}\n\n/**\n * Optional engine capabilities. Absence means the corresponding `ctx` feature\n * raises a clear error on that runtime rather than failing obscurely.\n */\nexport interface RuntimeCapabilities {\n /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */\n render: boolean\n /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */\n uploads: boolean\n /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */\n connectMiddleware: boolean\n /**\n * The engine parses request bodies itself (Fastify, h3). When true, the\n * Application skips its default `express.json()` so the body stream isn't\n * consumed twice (which would deadlock the engine's own parser). Express:\n * false — it relies on the `express.json()` connect middleware.\n */\n nativeBodyParsing: boolean\n /**\n * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2\n * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:\n * true. Express: false — it does not run on that layer. Absent = false, so\n * custom runtimes opt in explicitly.\n */\n http2?: boolean\n}\n\n/**\n * The engine driver. KickJS owns decorators → {@link RouteTable}, the\n * contributor pipeline, the `RequestContext` surface, and error mapping. The\n * runtime owns app/server creation, route materialization, connect-middleware\n * registration, static serving, and the terminal not-found / error handlers.\n *\n * `expressRuntime()` is the default and the M1 reference implementation.\n */\nexport interface HttpRuntime<TApp = unknown> {\n readonly name: 'express' | 'fastify' | 'h3' | (string & {})\n\n /** Create the engine app. Called once per Application (and per HMR rebuild). */\n createApp(options?: RuntimeAppOptions): TApp\n\n /**\n * Node-compatible request listener — the transport contract.\n * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST\n * invoke `next` (when given) instead of 404-ing if no route matched — the\n * Vite dev chain depends on fall-through.\n */\n nodeHandler(\n app: TApp,\n ): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void\n\n /** Materialize the framework-built route table onto the engine. */\n mountRoutes(app: TApp, table: RouteTable): void\n\n /** Register a connect-style middleware (built-ins + adopter middleware). */\n useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void\n\n /** Serve a static directory (swagger-ui assets, devtools SPA). */\n serveStatic(app: TApp, prefix: string, dir: string): void\n\n /** Terminal not-found handler. */\n setNotFound(app: TApp, mw: ConnectMiddleware): void\n\n /** Terminal error handler. */\n setErrorHandler(app: TApp, mw: ConnectMiddleware): void\n\n /**\n * Load the engine before the first `createApp()` — for a runtime that\n * imports it lazily, as the root `expressRuntime()` does so that\n * `@forinda/kickjs` doesn't need `express` installed. Awaited at setup.\n */\n load?(): Promise<void>\n\n /**\n * Body parsers to mount among the default middleware, for an engine that\n * doesn't parse request bodies itself (`capabilities.nativeBodyParsing:\n * false`). `limit` is `bootstrap({ jsonLimit })`.\n */\n bodyParsers?(options: { limit: string | number }): ConnectMiddleware[]\n\n /** Release the engine app on shutdown (Fastify runs its `onClose` hooks). */\n close?(app: TApp): void | Promise<void>\n\n readonly capabilities: RuntimeCapabilities\n}\n\n/**\n * The supported surface adapters use to add HTTP routes, mounts, static dirs,\n * and middleware — engine-agnostic, in place of reaching for the raw Express\n * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the\n * Application over the active {@link HttpRuntime}, so an adapter written against\n * this works under any runtime; the raw `app` escape hatch stays available for\n * the rare engine-specific need.\n */\nexport interface AdapterHttp {\n /** Register a single context-handler route (e.g. a docs or transport endpoint). */\n route(method: RouteMethod, path: string, handler: CtxHandler): void\n /** Mount a pre-built route table under a path prefix. */\n mount(prefix: string, routes: RouteEntry[]): void\n /** Serve a static directory under a path prefix. */\n serveStatic(prefix: string, dir: string): void\n /** Register a connect-style middleware (optionally path-scoped). */\n use(mw: ConnectMiddleware, opts?: UseConnectOptions): void\n}\n"],"mappings":";;;;;;;;;;uDA0JA,SAAgB,oBAAoB,IAAc,MAAyB,CAGzE,IAAI,MAAQ,cAAc,IAAI,KAAK,EAC9B,QACH,MAAQ,OAAO,OAAO,CACpB,OAAQ,MAAM,OACd,KAAM,MAAM,KACZ,WAAY,MAAM,KAAK,WACvB,YAAa,MAAM,KAAK,YACxB,MAAO,MAAM,KAAK,OAAS,YAC3B,QAAS,MAAM,KAAK,SAAW,MAAM,KACrC,KAAM,MAAM,IACd,CAAC,EACD,cAAc,IAAI,MAAO,KAAK,GAE/B,IAAsC,YAAc,KACvD,CAEA,MAAM,8BAAgB,IAAI,QAEpB,4BAA0B,IAAI,IAmCpC,SAAgB,kBAAkB,IAAuB,CACvD,OAAO,eAAe,WAAa,SAAS,KAAK,IAAI,OAAO,CAC9D,CAOA,SAAgB,cAAc,KAAuB,CACnD,GAAI,CACF,OAAO,KAAK,UAAU,IAAI,CAC5B,OAAS,IAAK,CACZ,GAAI,CAAC,kBAAkB,GAAG,EAAG,MAAM,IACnC,OAAO,KAAK,UAAU,MAAO,KAAM,QACjC,OAAO,OAAU,SAAW,MAAM,SAAS,EAAI,KACjD,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"runtime-BMyg1FYH.mjs","names":[],"sources":["../src/http/runtime.ts"],"sourcesContent":["// The HttpRuntime seam.\n//\n// Decorators no longer emit an `express.Router` directly. `buildRouteTable()`\n// turns controller metadata into a plain-data `RouteEntry[]`; an `HttpRuntime`\n// materializes that table onto whatever engine it owns. Express is the default\n// runtime and the only one shipped in M1 — its materializer reproduces the exact\n// handler chain the old `buildRoutes()` built, so behavior is unchanged.\n//\n// Fastify / h3 runtimes (later milestones) consume the SAME `RouteEntry` data\n// and the SAME `HttpRuntime` contract; the request/response driver abstraction\n// that lets `RequestContext` run engine-agnostically lands with them (M3), since\n// under Express the drivers ARE the Express request/response objects already.\n//\n// Why a seam: running Fastify / h3 behind an Express-compat layer\n// (`@fastify/express`, h3's node bridge) bypasses their router and\n// serialization, and rebuilding `ctx` over web-standard Request/Response\n// would break SSE / streaming, multer uploads and `ctx.res` for every adopter.\n// The seam keeps `ctx` and swaps only the engine underneath it.\n\nimport { ROUTE_SLOT, type RouteFlags } from '../core/route-flag'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ConnectMiddleware, ConnectRequest, ConnectResponse } from './connect'\n\nimport type { Constructor, FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core'\nimport type { RequestContext } from './context'\nimport type { ValidationErrorFactory } from './middleware/validate'\nimport type { RouteUrls } from './url-for'\nimport type { ContributorSource } from '../core/contributor-pipeline'\n\n/** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */\nexport type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n\n/**\n * A context-based handler: the runtime-neutral unit of the request pipeline.\n * Contributors, route middleware (via {@link MiddlewareHandler}), and the\n * terminal controller call all reduce to this shape. The runtime owns how a\n * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,\n * next)`; Fastify in its own handler).\n */\nexport type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>\n\n/**\n * Connect-style middleware — the portable middleware format. Built-in\n * middleware and adopter-supplied Express middleware are this shape. The\n * Express runtime hands them straight to `app.use`; the others bridge them\n * (Fastify via `@fastify/middie`, h3 via its node adapter). See `./connect`.\n */\nexport type { ConnectMiddleware }\n\n/**\n * One materialized route, as plain data. Produced by {@link buildRouteTable}\n * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.\n *\n * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`\n * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),\n * `contributorRunner` is a closure over the pre-built pipeline + container (the\n * pipeline is built — and any cycle / missing-dep error thrown — at table-build\n * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime\n * materializes its own way. Faithfully reproducing the legacy Express chain —\n * not collapsing it — is what keeps M1 behavior-neutral.\n */\nexport interface RouteEntry {\n method: RouteMethod\n /** Path with `:param` segments — the portable subset all engines accept. */\n path: string\n /** Class + method middleware, in execution order; each receives `(ctx, next)`. */\n middlewares: MiddlewareHandler[]\n /**\n * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),\n * or `null` when no contributors apply. Closes over the built pipeline and\n * the DI container so it stays engine-neutral; the runtime advances the\n * chain (Express: call `next()`) once it resolves.\n */\n contributorRunner: CtxHandler | null\n /**\n * Contributors registered with `beforeValidation: true`. Runtimes run this\n * right after publishing the matched route — before validation, upload and\n * middleware — so a rejection (401) lands before a malformed body's 422.\n * Absent or `null` when no contributor asks for it.\n */\n earlyContributorRunner?: CtxHandler | null\n /** The app's `validationError` — what this route's validation failure throws. */\n validationError?: ValidationErrorFactory\n /** The app's route names → paths, for `ctx.urlFor()`. */\n urls?: RouteUrls\n /** Terminal handler: resolves the controller per-request and invokes it. */\n handler: CtxHandler\n /** Introspection + runtime-materialized concerns (swagger/typegen read this). */\n meta: RouteMeta\n}\n\n/** Per-route metadata: introspection refs plus runtime-materialized concerns. */\n/**\n * One context contributor on a route, as introspection sees it: the\n * contributors a request runs, in execution order. Built with the route.\n */\nexport interface RouteContributor {\n /** The key it sets with `ctx.set(...)`. */\n key: string\n /** Where it was registered — `method` / `class` decorators, or a module, adapter or global list. */\n source: ContributorSource\n /** The registering site, e.g. `UsersController.show#0(tenant)` or a module name. */\n label?: string\n dependsOn: readonly string[]\n /** Runs before validation (`beforeValidation: true`). */\n beforeValidation: boolean\n /** Lower-precedence registrations of the same key this one replaced. */\n overrides: ReadonlyArray<{ source: ContributorSource; label?: string }>\n}\n\nexport interface RouteMeta {\n /**\n * Owning controller class — for DI resolution and adapter introspection.\n * Absent for ad-hoc routes registered through {@link AdapterHttp.route},\n * which have no controller class behind them.\n */\n controller?: Constructor\n /** Handler method name on the controller, when there is one. */\n handlerName?: string\n /** The route's context contributors, in execution order — for devtools / introspection. */\n contributors?: readonly RouteContributor[]\n /** Zod/JSON-schema validation config from the route decorator, if any. */\n validation?: RouteDefinition['validation']\n /** `@FileUpload` config, if present — the runtime supplies the backend. */\n upload?: FileUploadConfig\n /**\n * Route flags in force here, resolved at build time (method over class).\n * Enabled flags only: a flag declared `false` at a higher-precedence site is\n * absent rather than present-and-false, so `has()` is always the right\n * question. See `core/route-flag.ts`.\n */\n flags?: RouteFlags\n /**\n * The full mounted pattern (`/api/v1/users/:id`) — set by the Application\n * for controller routes. `path` is relative to the module mount.\n */\n pattern?: string\n}\n\n/**\n * The route a request matched, published on `ctx.route`.\n *\n * Everything that holds a {@link RequestContext} — handlers, `@Middleware()`,\n * guards, contributors — can read it, which is what lets one declaration on a\n * route serve every consumer.\n */\n/**\n * Publish the matched route on the request, for `ctx.route` to read.\n *\n * Called by each runtime once per dispatch, before it builds a RequestContext.\n * It lives on `req` rather than on the ctx because the Express runtime\n * constructs a fresh RequestContext per middleware step — anything written to\n * one ctx would be invisible to the next and to the handler.\n */\nexport function publishMatchedRoute(req: unknown, entry: RouteEntry): void {\n // One object per route, shared by its requests — every field comes from the\n // entry, which is final once mounted. Frozen, since it is shared.\n let route = matchedRoutes.get(entry)\n if (!route) {\n route = Object.freeze({\n method: entry.method,\n path: entry.path,\n controller: entry.meta.controller,\n handlerName: entry.meta.handlerName,\n flags: entry.meta.flags ?? EMPTY_FLAGS,\n pattern: entry.meta.pattern ?? entry.path,\n urls: entry.urls,\n })\n matchedRoutes.set(entry, route)\n }\n ;(req as Record<symbol, MatchedRoute>)[ROUTE_SLOT] = route\n}\n\nconst matchedRoutes = new WeakMap<RouteEntry, MatchedRoute>()\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\nexport interface MatchedRoute {\n readonly method: RouteMethod\n /** Path as declared on the handler, e.g. `/:id`. */\n readonly path: string\n /**\n * The full route pattern including the mount prefix and version, e.g.\n * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls\n * back to `path` for routes registered without a mount.\n */\n readonly pattern: string\n readonly controller?: Constructor\n readonly handlerName?: string\n /** Enabled flags only — see {@link RouteMeta.flags}. */\n readonly flags: RouteFlags\n /** @internal The app's route names, for `ctx.urlFor()`. */\n readonly urls?: RouteUrls\n}\n\n/** A controller's routes grouped under the module mount prefix. */\nexport type RouteTable = { mountPath: string; routes: RouteEntry[] }[]\n\n/**\n * The response surface {@link RequestContext}'s helpers (`json` / `html` /\n * `sse` / `download` / `render` / `problem`) drive, instead of calling Express\n * `res` methods directly (spec §4.3). Sized so `express.Response` satisfies it\n * structurally — under the Express runtime the driver IS the Express response,\n * so there is no wrapping and no behavior change. Other runtimes (Fastify / h3)\n * provide a thin object implementing this over their native reply.\n *\n * The terminal methods return `RuntimeResponse` for fluent chaining (Express's\n * `Response` is assignable, since it is a superset).\n */\n/** True for the TypeError `JSON.stringify` throws on a bigint. */\nexport function isBigIntJsonError(err: unknown): boolean {\n return err instanceof TypeError && /BigInt/.test(err.message)\n}\n\n/**\n * `JSON.stringify` that writes a bigint as its decimal string instead of\n * throwing — database counts and `bigint` columns reach responses as bigints.\n * Plain `JSON.stringify` runs first, so a body without one costs nothing extra.\n */\nexport function stringifyJson(data: unknown): string {\n try {\n return JSON.stringify(data)\n } catch (err) {\n if (!isBigIntJsonError(err)) throw err\n return JSON.stringify(data, (_key, value) =>\n typeof value === 'bigint' ? value.toString() : value,\n )\n }\n}\n\nexport interface RuntimeResponse {\n status(code: number): RuntimeResponse\n json(data: unknown): RuntimeResponse\n send(data: unknown): RuntimeResponse\n type(contentType: string): RuntimeResponse\n setHeader(name: string, value: string | number | readonly string[]): unknown\n render(view: string, data?: Record<string, unknown>): unknown\n writeHead(statusCode: number, headers?: Record<string, string>): unknown\n flushHeaders(): unknown\n write(chunk: string | Buffer): boolean\n end(data?: unknown): unknown\n once(event: 'close' | 'drain', listener: () => void): unknown\n readonly headersSent: boolean\n}\n\n// ── Runtime-typed escape hatches (spec §4.3b) ─────────────────────────────\n\n/**\n * Per-runtime type map: the engine-native request / response / app types an\n * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.\n */\nexport interface RuntimeTypeMap {\n request: unknown\n response: unknown\n app: unknown\n}\n\n/**\n * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen\n * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured\n * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,\n * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`\n * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is\n * uniform with `kick/db` and env typing.\n *\n * @example\n * ```ts\n * // .kickjs/types/kick__runtime.d.ts — generated by typegen\n * declare module '@forinda/kickjs' {\n * interface KickRuntimeRegister {\n * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes\n * }\n * }\n * ```\n */\n\nexport interface KickRuntimeRegister {}\n\n/**\n * The active runtime's type map — the augmented one, or the connect-style\n * {@link ConnectRuntimeTypes} when nothing is augmented. `kick typegen` augments it from kick.config's\n * `runtime`, Express included.\n */\nexport type ActiveRuntime = KickRuntimeRegister extends { runtime: infer R extends RuntimeTypeMap }\n ? R\n : ConnectRuntimeTypes\n\n/**\n * What the escape hatches are typed as with no augmentation: the connect-style\n * request and response every runtime's middleware sees, and an app of unknown\n * engine.\n */\nexport interface ConnectRuntimeTypes {\n request: ConnectRequest\n response: ConnectResponse\n app: unknown\n}\n\n/** Options passed to {@link HttpRuntime.createApp}. */\nexport interface RuntimeAppOptions {\n /**\n * Express `trust proxy` setting (and the equivalent on other engines). The\n * function form is Express-specific; other runtimes interpret the simpler\n * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).\n */\n trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean)\n /**\n * When the app is mounted inside another handler (`kick dev`'s Vite server,\n * `app.handle(req, res, next)` in a host server), hand requests no route\n * matched back to it — `true`, the default — or answer them here with the\n * app's not-found handling — `false`. Express always answers.\n */\n notFoundFallthrough?: boolean\n /** Largest request body the engine parses, in bytes — `jsonLimit`, resolved. */\n bodyLimit?: number\n}\n\n/** Where a connect middleware sits and what it scopes to. */\nexport interface UseConnectOptions {\n path?: string | RegExp | ReadonlyArray<string | RegExp>\n}\n\n/**\n * Optional engine capabilities. Absence means the corresponding `ctx` feature\n * raises a clear error on that runtime rather than failing obscurely.\n */\nexport interface RuntimeCapabilities {\n /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */\n render: boolean\n /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */\n uploads: boolean\n /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */\n connectMiddleware: boolean\n /**\n * The engine parses request bodies itself (Fastify, h3). When true, the\n * Application skips its default `express.json()` so the body stream isn't\n * consumed twice (which would deadlock the engine's own parser). Express:\n * false — it relies on the `express.json()` connect middleware.\n */\n nativeBodyParsing: boolean\n /**\n * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2\n * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:\n * true. Express: false — it does not run on that layer. Absent = false, so\n * custom runtimes opt in explicitly.\n */\n http2?: boolean\n}\n\n/**\n * The engine driver. KickJS owns decorators → {@link RouteTable}, the\n * contributor pipeline, the `RequestContext` surface, and error mapping. The\n * runtime owns app/server creation, route materialization, connect-middleware\n * registration, static serving, and the terminal not-found / error handlers.\n *\n * `expressRuntime()` is the default and the M1 reference implementation.\n */\nexport interface HttpRuntime<TApp = unknown> {\n readonly name: 'express' | 'fastify' | 'h3' | (string & {})\n\n /** Create the engine app. Called once per Application (and per HMR rebuild). */\n createApp(options?: RuntimeAppOptions): TApp\n\n /**\n * Node-compatible request listener — the transport contract.\n * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST\n * invoke `next` (when given) instead of 404-ing if no route matched — the\n * Vite dev chain depends on fall-through.\n */\n nodeHandler(\n app: TApp,\n ): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void\n\n /** Materialize the framework-built route table onto the engine. */\n mountRoutes(app: TApp, table: RouteTable): void\n\n /** Register a connect-style middleware (built-ins + adopter middleware). */\n useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void\n\n /** Serve a static directory (swagger-ui assets, devtools SPA). */\n serveStatic(app: TApp, prefix: string, dir: string): void\n\n /** Terminal not-found handler. */\n setNotFound(app: TApp, mw: ConnectMiddleware): void\n\n /** Terminal error handler. */\n setErrorHandler(app: TApp, mw: ConnectMiddleware): void\n\n /**\n * Load the engine before the first `createApp()` — for a runtime that\n * imports it lazily, as the root `expressRuntime()` does so that\n * `@forinda/kickjs` doesn't need `express` installed. Awaited at setup.\n */\n load?(): Promise<void>\n\n /**\n * Body parsers to mount among the default middleware, for an engine that\n * doesn't parse request bodies itself (`capabilities.nativeBodyParsing:\n * false`). `limit` is `bootstrap({ jsonLimit })`.\n */\n bodyParsers?(options: { limit: string | number }): ConnectMiddleware[]\n\n /** Release the engine app on shutdown (Fastify runs its `onClose` hooks). */\n close?(app: TApp): void | Promise<void>\n\n readonly capabilities: RuntimeCapabilities\n}\n\n/**\n * The supported surface adapters use to add HTTP routes, mounts, static dirs,\n * and middleware — engine-agnostic, in place of reaching for the raw Express\n * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the\n * Application over the active {@link HttpRuntime}, so an adapter written against\n * this works under any runtime; the raw `app` escape hatch stays available for\n * the rare engine-specific need.\n */\nexport interface AdapterHttp {\n /** Register a single context-handler route (e.g. a docs or transport endpoint). */\n route(method: RouteMethod, path: string, handler: CtxHandler): void\n /** Mount a pre-built route table under a path prefix. */\n mount(prefix: string, routes: RouteEntry[]): void\n /** Serve a static directory under a path prefix. */\n serveStatic(prefix: string, dir: string): void\n /** Register a connect-style middleware (optionally path-scoped). */\n use(mw: ConnectMiddleware, opts?: UseConnectOptions): void\n}\n"],"mappings":";;;;;;;;;;uDA0JA,SAAgB,oBAAoB,IAAc,MAAyB,CAGzE,IAAI,MAAQ,cAAc,IAAI,KAAK,EAC9B,QACH,MAAQ,OAAO,OAAO,CACpB,OAAQ,MAAM,OACd,KAAM,MAAM,KACZ,WAAY,MAAM,KAAK,WACvB,YAAa,MAAM,KAAK,YACxB,MAAO,MAAM,KAAK,OAAS,YAC3B,QAAS,MAAM,KAAK,SAAW,MAAM,KACrC,KAAM,MAAM,IACd,CAAC,EACD,cAAc,IAAI,MAAO,KAAK,GAE/B,IAAsC,YAAc,KACvD,CAEA,MAAM,8BAAgB,IAAI,QAEpB,4BAA0B,IAAI,IAmCpC,SAAgB,kBAAkB,IAAuB,CACvD,OAAO,eAAe,WAAa,SAAS,KAAK,IAAI,OAAO,CAC9D,CAOA,SAAgB,cAAc,KAAuB,CACnD,GAAI,CACF,OAAO,KAAK,UAAU,IAAI,CAC5B,OAAS,IAAK,CACZ,GAAI,CAAC,kBAAkB,GAAG,EAAG,MAAM,IACnC,OAAO,KAAK,UAAU,MAAO,KAAM,QACjC,OAAO,OAAU,SAAW,MAAM,SAAS,EAAI,KACjD,CACF,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.3
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{Container}from"./core/container.mjs";import{t as INJECTION_TOKEN}from"./token-
|
|
11
|
+
import{Container}from"./core/container.mjs";import{t as INJECTION_TOKEN}from"./token-BRZwz7iz.mjs";import{detectSchema}from"@forinda/kickjs-schema";let readSecretFiles;function _useSecretFileReader(reader){readSecretFiles=reader}const PROVIDED=Symbol.for(`kickjs.settings.provided`);function isProvided(decl){return decl[PROVIDED]===!0}const envSegment=key=>key.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase();function leavesOf(shape,prefix,path=[],required=!0){if(shape.properties){let own=new Set(shape.required??[]),parentRequired=required&&shape.default===void 0;return Object.entries(shape.properties).flatMap(([key,child])=>leavesOf(child,prefix,[...path,key],parentRequired&&own.has(key)))}let types=Array.isArray(shape.type)?shape.type:[shape.type];return[{path,env:[prefix,...path.map(envSegment)].join(`_`),list:types.includes(`array`),required:required&&shape.default===void 0,...shape.default===void 0?{}:{default:shape.default},...shape.description?{description:shape.description}:{}}]}const toConfigVar=leaf=>({name:leaf.env,required:leaf.required,list:leaf.list,...leaf.default===void 0?{}:{default:leaf.default},...leaf.description?{description:leaf.description}:{}});function describeSchemaVars(schema){let shape=detectSchema(schema).toJsonSchema(),required=new Set(shape.required??[]);return Object.entries(shape.properties??{}).map(([key,child])=>{let described=toConfigVar(leavesOf(child,``,[key],required.has(key))[0]);return described.name=key,described})}function originsOf(vars,env=process.env){let has=name=>env[name]!==void 0&&env[name]!==``;return vars.map(v=>{let origin=`unset`;return has(v.name)?origin=`env`:readSecretFiles&&has(`${v.name}_FILE`)?origin=`file`:v.default!==void 0&&(origin=`default`),{name:v.name,origin}})}const cached=/* @__PURE__ */ new WeakMap;function defineSettings(prefix,schema){return createSection(prefix,schema)}function createSection(prefix,schema){if(!/^[A-Z][A-Z0-9_]*$/.test(prefix))throw Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`);let wrapped=detectSchema(schema),shape=wrapped.toJsonSchema();if(!shape.properties)throw Error(`defineSettings('${prefix}'): the schema must be an object whose keys can be read (Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.`);let leaves=leavesOf(shape,prefix),seenEnv=/* @__PURE__ */ new Map;for(let leaf of leaves){let path=leaf.path.join(`.`),other=seenEnv.get(leaf.env);if(other!==void 0)throw Error(`defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`);seenEnv.set(leaf.env,path)}let envNames=leaves.map(leaf=>leaf.env),byPath=new Map(leaves.map(leaf=>[leaf.path.join(`.`),leaf.env])),load=(env=process.env)=>{let source=readSecretFiles?readSecretFiles(env,envNames):env,input={};for(let leaf of leaves){let raw=source[leaf.env];if(raw===void 0)continue;let target=input;for(let key of leaf.path.slice(0,-1))target=target[key]??={};target[leaf.path.at(-1)]=leaf.list?raw.split(`,`).map(item=>item.trim()).filter(Boolean):raw}return validate(input)},validate=input=>{let result=wrapped.safeParse(input);if(result.success)return result.data;let problems=result.issues.map(issue=>{let key=issue.path.join(`.`);return` ${byPath.get(key)??[prefix,...issue.path.map(p=>envSegment(String(p)))].join(`_`)}: ${issue.message}`});throw Error(`Settings '${prefix}' are invalid:\n${problems.join(`
|
|
12
12
|
`)}`)},scopes=/* @__PURE__ */ new Map,settings=Object.freeze({[INJECTION_TOKEN]:!0,name:`Settings(${prefix})`,prefix,envNames,load,parse:value=>validate(value),provide:value=>Object.freeze({[PROVIDED]:!0,section:settings,value}),describe:()=>leaves.map(toConfigVar),get:()=>{let container=Container.getInstance();return container.has(settings)?container.resolve(settings):(cached.has(settings)||cached.set(settings,load()),cached.get(settings))},scoped:name=>{let scopePrefix=`${name}_${prefix}`,scoped=scopes.get(scopePrefix);return scoped||(scoped=createSection(scopePrefix,schema),scopes.set(scopePrefix,scoped)),scoped}});return settings}function loadSettings(declarations,env=process.env,byPrefix=/* @__PURE__ */ new Map,providedBefore=/* @__PURE__ */ new Map){let values=/* @__PURE__ */ new Map,failures=[],provided=/* @__PURE__ */ new Map,sections=[];for(let decl of declarations)if(isProvided(decl)){let earlier=provided.has(decl.section)?provided:providedBefore;if(earlier.has(decl.section)&&earlier.get(decl.section)!==decl.value){failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`);continue}provided.set(decl.section,decl.value),sections.push(decl.section)}else sections.push(decl);for(let section of sections){if(values.has(section))continue;let other=byPrefix.get(section.prefix);if(other!==section||provided.has(section)&&!providedBefore.has(section)){if(other&&other!==section)failures.push(`Two different settings sections use the prefix '${section.prefix}'.`);else{byPrefix.set(section.prefix,section);try{let value=provided.has(section)?section.parse(provided.get(section)):section.load(env);values.set(section,value),provided.has(section)&&providedBefore.set(section,provided.get(section)),cached.set(section,value)}catch(err){failures.push(err.message)}}}}if(failures.length>0)throw Error(failures.join(`
|
|
13
13
|
`));return values}export{originsOf as a,loadSettings as i,defineSettings as n,describeSchemaVars as r,_useSecretFileReader as t};
|
|
14
|
-
//# sourceMappingURL=settings-
|
|
14
|
+
//# sourceMappingURL=settings-Ck0vWbOD.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-DdExbzhu.mjs","names":[],"sources":["../src/config/settings.ts"],"sourcesContent":["/**\n * Typed configuration sections: one schema per concern (`DB`, `MAIL`,\n * `STORAGE`), each read from its own prefix of the environment and injected\n * where it's needed — instead of one flat env every service reaches into.\n * Spring's `@ConfigurationProperties`, for any schema `@forinda/kickjs-schema`\n * reads — Zod, Valibot, Yup.\n *\n * @module @forinda/kickjs/config/settings\n */\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { INJECTION_TOKEN, type InjectionToken } from '../core/token'\nimport { Container } from '../core/container'\n\n/**\n * Reads `<NAME>_FILE` secrets. Registered by `./env` (Node only) when it\n * loads — this module imports nothing node-only, so the web entry can use it;\n * there, `_FILE` variables are simply not read.\n */\ntype SecretFileReader = (\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n) => Record<string, string | undefined>\nlet readSecretFiles: SecretFileReader | undefined\n\n/** @internal */\nexport function _useSecretFileReader(reader: SecretFileReader): void {\n readSecretFiles = reader\n}\n\n/** A section: an injection token that also knows how to load itself. */\nexport interface Settings<T> extends InjectionToken<T> {\n /** The env prefix, e.g. `'DB'`. */\n readonly prefix: string\n /** Every env name the section reads, e.g. `['DB_URL', 'DB_POOL_MAX']`. */\n readonly envNames: readonly string[]\n /**\n * The section's value — validated at startup, then cached. Before startup\n * (a script, a CLI command) the first call loads and validates it.\n */\n get(): T\n /** Parse the section from `env` (default `process.env`) afresh; throws listing every problem. */\n load(env?: NodeJS.ProcessEnv): T\n /** Each variable the section reads — required or not, default, description. Reads no env. */\n describe(): ConfigVar[]\n /** Validate a value you supply against the schema — defaults applied — instead of reading env. */\n parse(value: unknown): T\n /**\n * Declare the section with a value you supply instead of the environment —\n * a test's container, a service you started, a secret manager's answer.\n * Validated against the schema like env values; bound under this section's\n * token, so everything injecting it gets the provided value.\n *\n * ```ts\n * const pg = await startService('postgres')\n * await createTestApp({ modules, settings: [DbSettings.provide({ url: pg.url })] })\n * ```\n */\n provide(value: unknown): ProvidedSettings<T>\n /**\n * The same schema under another prefix, for a second instance:\n * `DbSettings.scoped('ANALYTICS')` reads `ANALYTICS_DB_*` beside `DB_*`.\n * Returns the same token for the same name.\n */\n scoped(name: string): Settings<T>\n}\n\nconst PROVIDED = Symbol.for('kickjs.settings.provided')\n\n/** A section declared with a supplied value — see {@link Settings.provide}. */\nexport interface ProvidedSettings<T> {\n readonly [PROVIDED]: true\n readonly section: Settings<T>\n readonly value: unknown\n}\n\n/** What a `settings` list accepts: a section (read from env) or a provided one. */\nexport type SettingsDeclaration = Settings<unknown> | ProvidedSettings<unknown>\n\nfunction isProvided(decl: SettingsDeclaration): decl is ProvidedSettings<unknown> {\n return (decl as Partial<ProvidedSettings<unknown>>)[PROVIDED] === true\n}\n\n/** The value type of a section: `SettingsOf<typeof DbSettings>`. */\nexport type SettingsOf<S> = S extends Settings<infer T> ? T : never\n\ninterface Leaf {\n path: string[]\n env: string\n list: boolean\n required: boolean\n default?: unknown\n description?: string\n}\n\n/** One variable, as `describe()` and `app.describeConfig()` report it. */\nexport interface ConfigVar {\n name: string\n /** Startup fails without it: required by the schema, with no default. */\n required: boolean\n /** The schema's default, when it has one. */\n default?: unknown\n /** The schema's description (`.describe('…')` in Zod). */\n description?: string\n /** Read as a comma-separated list. */\n list: boolean\n}\n\n/** The part of a JSON schema the env mapping reads. */\ninterface JsonShape {\n type?: string | string[]\n properties?: Record<string, JsonShape>\n required?: string[]\n default?: unknown\n description?: string\n}\n\n/** `maxConnections` → `MAX_CONNECTIONS`. */\nconst envSegment = (key: string) => key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()\n\n/**\n * The variables a JSON-schema shape reads. A leaf is required when every\n * object on its path is required by its parent and none of them (nor the leaf)\n * has a default — a defaulted parent object supplies its children.\n */\nfunction leavesOf(shape: JsonShape, prefix: string, path: string[] = [], required = true): Leaf[] {\n if (shape.properties) {\n const own = new Set(shape.required ?? [])\n const parentRequired = required && shape.default === undefined\n return Object.entries(shape.properties).flatMap(([key, child]) =>\n leavesOf(child, prefix, [...path, key], parentRequired && own.has(key)),\n )\n }\n const types = Array.isArray(shape.type) ? shape.type : [shape.type]\n return [\n {\n path,\n env: [prefix, ...path.map(envSegment)].join('_'),\n list: types.includes('array'),\n required: required && shape.default === undefined,\n ...(shape.default !== undefined ? { default: shape.default } : {}),\n ...(shape.description ? { description: shape.description } : {}),\n },\n ]\n}\n\nconst toConfigVar = (leaf: Leaf): ConfigVar => ({\n name: leaf.env,\n required: leaf.required,\n list: leaf.list,\n ...(leaf.default !== undefined ? { default: leaf.default } : {}),\n ...(leaf.description ? { description: leaf.description } : {}),\n})\n\n/**\n * The variables of a flat schema (the app's env schema), described the same\n * way — no prefix, top-level keys only.\n */\nexport function describeSchemaVars(schema: unknown): ConfigVar[] {\n const shape = detectSchema(schema).toJsonSchema() as JsonShape\n const required = new Set(shape.required ?? [])\n // The keys of an env schema are the variable names themselves.\n return Object.entries(shape.properties ?? {}).map(([key, child]) => {\n // A fresh object from toConfigVar — safe to set the name on directly.\n const described = toConfigVar(leavesOf(child, '', [key], required.has(key))[0])\n described.name = key\n return described\n })\n}\n\n/** Where a variable's value comes from. */\nexport type ValueOrigin = 'env' | 'file' | 'provided' | 'default' | 'unset'\n\n/** A variable and where its value comes from — never the value itself. */\nexport interface VarOrigin {\n name: string\n origin: ValueOrigin\n}\n\n/**\n * Where each variable's value comes from in `env`: set directly, read from\n * `<NAME>_FILE`, the schema's default, or not set at all. Names only — safe\n * to show where the values themselves must not appear.\n */\nexport function originsOf(\n vars: readonly ConfigVar[],\n env: NodeJS.ProcessEnv = process.env,\n): VarOrigin[] {\n // Empty counts as unset, as the secret-file reader treats it.\n const has = (name: string) => env[name] !== undefined && env[name] !== ''\n return vars.map((v) => {\n let origin: ValueOrigin = 'unset'\n if (has(v.name)) origin = 'env'\n // `_FILE` is only read where a reader is registered (Node, not the web entry).\n else if (readSecretFiles && has(`${v.name}_FILE`)) origin = 'file'\n else if (v.default !== undefined) origin = 'default'\n return { name: v.name, origin }\n })\n}\n\n/** Values validated at startup (or on first `get()`), by prefix. */\nconst cached = new WeakMap<Settings<unknown>, unknown>()\n\n/**\n * Define a typed configuration section read from env variables with a prefix.\n * Each key path becomes one variable: `pool.max` under `'DB'` is `DB_POOL_MAX`,\n * `maxConnections` is `DB_MAX_CONNECTIONS`. A list reads a comma-separated\n * value. `<NAME>_FILE` secrets work for every variable.\n *\n * ```ts\n * export const DbSettings = defineSettings('DB', z.object({\n * url: z.string().url(),\n * pool: z.object({ max: z.coerce.number().default(10) }).default({ max: 10 }),\n * }))\n *\n * @Service()\n * class Database {\n * constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}\n * }\n * ```\n *\n * Declare it where it's used — `bootstrap({ settings })`, a module's, adapter's\n * or plugin's `settings()` — and it is validated when the app starts (a\n * missing or invalid value fails startup, naming the variable) and injectable\n * by its token. Undeclared, `get()` validates it on first use. Values\n * come from the schema's coercion: use `z.coerce.number()`, and\n * `z.stringbool()` for booleans (`z.coerce.boolean()` reads `'false'` as true).\n */\nexport function defineSettings<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n return createSection(prefix, schema)\n}\n\nfunction createSection<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n type T = InferSchemaOutput<S>\n if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) {\n throw new Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`)\n }\n const wrapped = detectSchema(schema)\n // The env names come from the schema's shape, read through its JSON schema —\n // the one view every adapter (Zod, Valibot, Yup) provides.\n const shape = wrapped.toJsonSchema() as JsonShape\n if (!shape.properties) {\n throw new Error(\n `defineSettings('${prefix}'): the schema must be an object whose keys can be read ` +\n '(Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.',\n )\n }\n const leaves = leavesOf(shape, prefix)\n // `fooBar` and `foo_bar` would both read `DB_FOO_BAR` — one variable for two\n // settings that could never differ. Refuse it here, naming both paths.\n const seenEnv = new Map<string, string>()\n for (const leaf of leaves) {\n const path = leaf.path.join('.')\n const other = seenEnv.get(leaf.env)\n if (other !== undefined) {\n throw new Error(\n `defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`,\n )\n }\n seenEnv.set(leaf.env, path)\n }\n const envNames = leaves.map((leaf) => leaf.env)\n const byPath = new Map(leaves.map((leaf) => [leaf.path.join('.'), leaf.env]))\n\n const load = (env: NodeJS.ProcessEnv = process.env): T => {\n const source = readSecretFiles ? readSecretFiles(env, envNames) : env\n const input: Record<string, unknown> = {}\n for (const leaf of leaves) {\n const raw = source[leaf.env]\n if (raw === undefined) continue\n let target = input\n for (const key of leaf.path.slice(0, -1)) {\n target = (target[key] ??= {}) as Record<string, unknown>\n }\n target[leaf.path.at(-1)!] = leaf.list\n ? raw\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean)\n : raw\n }\n return validate(input)\n }\n\n const validate = (input: unknown): T => {\n const result = wrapped.safeParse(input)\n if (result.success) return result.data as T\n const problems = result.issues.map((issue) => {\n const key = issue.path.join('.')\n // The variable to fix, not the schema path; a nested object that is\n // missing entirely names its prefix.\n const name =\n byPath.get(key) ?? [prefix, ...issue.path.map((p) => envSegment(String(p)))].join('_')\n return ` ${name}: ${issue.message}`\n })\n throw new Error(`Settings '${prefix}' are invalid:\\n${problems.join('\\n')}`)\n }\n\n const scopes = new Map<string, Settings<T>>()\n const settings: Settings<T> = Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name: `Settings(${prefix})`,\n prefix,\n envNames,\n load,\n parse: (value: unknown): T => validate(value),\n provide: (value: unknown): ProvidedSettings<T> =>\n Object.freeze({ [PROVIDED]: true as const, section: settings, value }),\n describe: () => leaves.map(toConfigVar),\n get: (): T => {\n // What injected code sees: the container's binding, which a module or a\n // test may have replaced. Before the app binds it, the validated env.\n const container = Container.getInstance()\n if (container.has(settings)) return container.resolve(settings) as T\n // Keyed by the section, not its prefix: two sections sharing a prefix\n // each parse their own schema.\n if (!cached.has(settings)) cached.set(settings, load())\n return cached.get(settings) as T\n },\n scoped: (name: string): Settings<T> => {\n const scopePrefix = `${name}_${prefix}`\n let scoped = scopes.get(scopePrefix)\n if (!scoped) {\n scoped = createSection(scopePrefix, schema) as Settings<T>\n scopes.set(scopePrefix, scoped)\n }\n return scoped\n },\n }) as Settings<T>\n return settings\n}\n\n/**\n * Validate the given sections — the ones the app declared — throwing once\n * with every problem, so a misconfigured deploy fails at startup with the\n * whole list. A section declared twice is loaded once; two different sections\n * with one prefix would read the same variables, and are refused.\n */\nexport function loadSettings(\n declarations: Iterable<SettingsDeclaration>,\n env: NodeJS.ProcessEnv = process.env,\n /**\n * Prefixes already taken, across calls — an app binds in two phases (app\n * sections, then modules') and a clash between them must still be refused.\n */\n byPrefix: Map<string, Settings<unknown>> = new Map(),\n /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */\n providedBefore: Map<Settings<unknown>, unknown> = new Map(),\n): Map<Settings<unknown>, unknown> {\n const values = new Map<Settings<unknown>, unknown>()\n const failures: string[] = []\n // A provided value wins over the same section read from env, wherever each\n // was declared — a test's provide() must not lose to a module's section.\n const provided = new Map<Settings<unknown>, unknown>()\n const sections: Settings<unknown>[] = []\n for (const decl of declarations) {\n if (isProvided(decl)) {\n // Two provides of one section would silently keep whichever came last.\n const earlier = provided.has(decl.section) ? provided : providedBefore\n if (earlier.has(decl.section) && earlier.get(decl.section) !== decl.value) {\n failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`)\n continue\n }\n provided.set(decl.section, decl.value)\n sections.push(decl.section)\n } else {\n sections.push(decl)\n }\n }\n for (const section of sections) {\n if (values.has(section)) continue\n const other = byPrefix.get(section.prefix)\n // Already bound in an earlier phase: nothing to do — unless that read env\n // and this phase provides a value, which wins.\n if (other === section && !(provided.has(section) && !providedBefore.has(section))) continue\n if (other && other !== section) {\n failures.push(`Two different settings sections use the prefix '${section.prefix}'.`)\n continue\n }\n byPrefix.set(section.prefix, section)\n try {\n const value = provided.has(section) ? section.parse(provided.get(section)) : section.load(env)\n values.set(section, value)\n if (provided.has(section)) providedBefore.set(section, provided.get(section))\n // `get()` returns what the app started with.\n cached.set(section, value)\n } catch (err) {\n failures.push((err as Error).message)\n }\n }\n if (failures.length > 0) throw new Error(failures.join('\\n'))\n return values\n}\n"],"mappings":";;;;;;;;;;oJAsBA,IAAI,gBAGJ,SAAgB,qBAAqB,OAAgC,CACnE,gBAAkB,MACpB,CAuCA,MAAM,SAAW,OAAO,IAAI,0BAA0B,EAYtD,SAAS,WAAW,KAA8D,CAChF,OAAQ,KAA4C,YAAc,EACpE,CAqCA,MAAM,WAAc,KAAgB,IAAI,QAAQ,qBAAsB,OAAO,CAAC,CAAC,YAAY,EAO3F,SAAS,SAAS,MAAkB,OAAgB,KAAiB,CAAC,EAAG,SAAW,GAAc,CAChG,GAAI,MAAM,WAAY,CACpB,IAAM,IAAM,IAAI,IAAI,MAAM,UAAY,CAAC,CAAC,EAClC,eAAiB,UAAY,MAAM,UAAY,IAAA,GACrD,OAAO,OAAO,QAAQ,MAAM,UAAU,CAAC,CAAC,SAAS,CAAC,IAAK,SACrD,SAAS,MAAO,OAAQ,CAAC,GAAG,KAAM,GAAG,EAAG,gBAAkB,IAAI,IAAI,GAAG,CAAC,CACxE,CACF,CACA,IAAM,MAAQ,MAAM,QAAQ,MAAM,IAAI,EAAI,MAAM,KAAO,CAAC,MAAM,IAAI,EAClE,MAAO,CACL,CACE,KACA,IAAK,CA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W,IAAI,IACf,SAAgC,CAAC,EACvC,IAAK,IAAM,QAAQ,aACjB,GAAI,WAAW,IAAI,EAAG,CAEpB,IAAM,QAAU,SAAS,IAAI,KAAK,OAAO,EAAI,SAAW,eACxD,GAAI,QAAQ,IAAI,KAAK,OAAO,GAAK,QAAQ,IAAI,KAAK,OAAO,IAAM,KAAK,MAAO,CACzE,SAAS,KAAK,aAAa,KAAK,QAAQ,OAAO,4CAA4C,EAC3F,QACF,CACA,SAAS,IAAI,KAAK,QAAS,KAAK,KAAK,EACrC,SAAS,KAAK,KAAK,OAAO,CAC5B,MACE,SAAS,KAAK,IAAI,EAGtB,IAAK,IAAM,WAAW,SAAU,CAC9B,GAAI,OAAO,IAAI,OAAO,EAAG,SACzB,IAAM,MAAQ,SAAS,IAAI,QAAQ,MAAM,EAGzC,GAAI,QAAU,SAAa,SAAS,IAAI,OAAO,GAAM,gBAAe,IAAI,OAAO,EAC/E,IAAI,OAAS,QAAU,QACrB,SAAS,KAAK,mDAAmD,QAAQ,OAAO,GAAG,MAGrF,UAAS,IAAI,QAAQ,OAAQ,OAAO,EACpC,GAAI,CACF,IAAM,MAAQ,SAAS,IAAI,OAAO,EAAI,QAAQ,MAAM,SAAS,IAAI,OAAO,CAAC,EAAI,QAAQ,KAAK,GAAG,EAC7F,OAAO,IAAI,QAAS,KAAK,EACrB,SAAS,IAAI,OAAO,GAAG,eAAe,IAAI,QAAS,SAAS,IAAI,OAAO,CAAC,EAE5E,OAAO,IAAI,QAAS,KAAK,CAC3B,OAAS,IAAK,CACZ,SAAS,KAAM,IAAc,OAAO,CACtC,CAToC,CADpC,CAWF,CACA,GAAI,SAAS,OAAS,EAAG,MAAU,MAAM,SAAS,KAAK;CAAI,CAAC,EAC5D,OAAO,MACT"}
|
|
1
|
+
{"version":3,"file":"settings-Ck0vWbOD.mjs","names":[],"sources":["../src/config/settings.ts"],"sourcesContent":["/**\n * Typed configuration sections: one schema per concern (`DB`, `MAIL`,\n * `STORAGE`), each read from its own prefix of the environment and injected\n * where it's needed — instead of one flat env every service reaches into.\n * Spring's `@ConfigurationProperties`, for any schema `@forinda/kickjs-schema`\n * reads — Zod, Valibot, Yup.\n *\n * @module @forinda/kickjs/config/settings\n */\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { INJECTION_TOKEN, type InjectionToken } from '../core/token'\nimport { Container } from '../core/container'\n\n/**\n * Reads `<NAME>_FILE` secrets. Registered by `./env` (Node only) when it\n * loads — this module imports nothing node-only, so the web entry can use it;\n * there, `_FILE` variables are simply not read.\n */\ntype SecretFileReader = (\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n) => Record<string, string | undefined>\nlet readSecretFiles: SecretFileReader | undefined\n\n/** @internal */\nexport function _useSecretFileReader(reader: SecretFileReader): void {\n readSecretFiles = reader\n}\n\n/** A section: an injection token that also knows how to load itself. */\nexport interface Settings<T> extends InjectionToken<T> {\n /** The env prefix, e.g. `'DB'`. */\n readonly prefix: string\n /** Every env name the section reads, e.g. `['DB_URL', 'DB_POOL_MAX']`. */\n readonly envNames: readonly string[]\n /**\n * The section's value — validated at startup, then cached. Before startup\n * (a script, a CLI command) the first call loads and validates it.\n */\n get(): T\n /** Parse the section from `env` (default `process.env`) afresh; throws listing every problem. */\n load(env?: NodeJS.ProcessEnv): T\n /** Each variable the section reads — required or not, default, description. Reads no env. */\n describe(): ConfigVar[]\n /** Validate a value you supply against the schema — defaults applied — instead of reading env. */\n parse(value: unknown): T\n /**\n * Declare the section with a value you supply instead of the environment —\n * a test's container, a service you started, a secret manager's answer.\n * Validated against the schema like env values; bound under this section's\n * token, so everything injecting it gets the provided value.\n *\n * ```ts\n * const pg = await startService('postgres')\n * await createTestApp({ modules, settings: [DbSettings.provide({ url: pg.url })] })\n * ```\n */\n provide(value: unknown): ProvidedSettings<T>\n /**\n * The same schema under another prefix, for a second instance:\n * `DbSettings.scoped('ANALYTICS')` reads `ANALYTICS_DB_*` beside `DB_*`.\n * Returns the same token for the same name.\n */\n scoped(name: string): Settings<T>\n}\n\nconst PROVIDED = Symbol.for('kickjs.settings.provided')\n\n/** A section declared with a supplied value — see {@link Settings.provide}. */\nexport interface ProvidedSettings<T> {\n readonly [PROVIDED]: true\n readonly section: Settings<T>\n readonly value: unknown\n}\n\n/** What a `settings` list accepts: a section (read from env) or a provided one. */\nexport type SettingsDeclaration = Settings<unknown> | ProvidedSettings<unknown>\n\nfunction isProvided(decl: SettingsDeclaration): decl is ProvidedSettings<unknown> {\n return (decl as Partial<ProvidedSettings<unknown>>)[PROVIDED] === true\n}\n\n/** The value type of a section: `SettingsOf<typeof DbSettings>`. */\nexport type SettingsOf<S> = S extends Settings<infer T> ? T : never\n\ninterface Leaf {\n path: string[]\n env: string\n list: boolean\n required: boolean\n default?: unknown\n description?: string\n}\n\n/** One variable, as `describe()` and `app.describeConfig()` report it. */\nexport interface ConfigVar {\n name: string\n /** Startup fails without it: required by the schema, with no default. */\n required: boolean\n /** The schema's default, when it has one. */\n default?: unknown\n /** The schema's description (`.describe('…')` in Zod). */\n description?: string\n /** Read as a comma-separated list. */\n list: boolean\n}\n\n/** The part of a JSON schema the env mapping reads. */\ninterface JsonShape {\n type?: string | string[]\n properties?: Record<string, JsonShape>\n required?: string[]\n default?: unknown\n description?: string\n}\n\n/** `maxConnections` → `MAX_CONNECTIONS`. */\nconst envSegment = (key: string) => key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()\n\n/**\n * The variables a JSON-schema shape reads. A leaf is required when every\n * object on its path is required by its parent and none of them (nor the leaf)\n * has a default — a defaulted parent object supplies its children.\n */\nfunction leavesOf(shape: JsonShape, prefix: string, path: string[] = [], required = true): Leaf[] {\n if (shape.properties) {\n const own = new Set(shape.required ?? [])\n const parentRequired = required && shape.default === undefined\n return Object.entries(shape.properties).flatMap(([key, child]) =>\n leavesOf(child, prefix, [...path, key], parentRequired && own.has(key)),\n )\n }\n const types = Array.isArray(shape.type) ? shape.type : [shape.type]\n return [\n {\n path,\n env: [prefix, ...path.map(envSegment)].join('_'),\n list: types.includes('array'),\n required: required && shape.default === undefined,\n ...(shape.default !== undefined ? { default: shape.default } : {}),\n ...(shape.description ? { description: shape.description } : {}),\n },\n ]\n}\n\nconst toConfigVar = (leaf: Leaf): ConfigVar => ({\n name: leaf.env,\n required: leaf.required,\n list: leaf.list,\n ...(leaf.default !== undefined ? { default: leaf.default } : {}),\n ...(leaf.description ? { description: leaf.description } : {}),\n})\n\n/**\n * The variables of a flat schema (the app's env schema), described the same\n * way — no prefix, top-level keys only.\n */\nexport function describeSchemaVars(schema: unknown): ConfigVar[] {\n const shape = detectSchema(schema).toJsonSchema() as JsonShape\n const required = new Set(shape.required ?? [])\n // The keys of an env schema are the variable names themselves.\n return Object.entries(shape.properties ?? {}).map(([key, child]) => {\n // A fresh object from toConfigVar — safe to set the name on directly.\n const described = toConfigVar(leavesOf(child, '', [key], required.has(key))[0])\n described.name = key\n return described\n })\n}\n\n/** Where a variable's value comes from. */\nexport type ValueOrigin = 'env' | 'file' | 'provided' | 'default' | 'unset'\n\n/** A variable and where its value comes from — never the value itself. */\nexport interface VarOrigin {\n name: string\n origin: ValueOrigin\n}\n\n/**\n * Where each variable's value comes from in `env`: set directly, read from\n * `<NAME>_FILE`, the schema's default, or not set at all. Names only — safe\n * to show where the values themselves must not appear.\n */\nexport function originsOf(\n vars: readonly ConfigVar[],\n env: NodeJS.ProcessEnv = process.env,\n): VarOrigin[] {\n // Empty counts as unset, as the secret-file reader treats it.\n const has = (name: string) => env[name] !== undefined && env[name] !== ''\n return vars.map((v) => {\n let origin: ValueOrigin = 'unset'\n if (has(v.name)) origin = 'env'\n // `_FILE` is only read where a reader is registered (Node, not the web entry).\n else if (readSecretFiles && has(`${v.name}_FILE`)) origin = 'file'\n else if (v.default !== undefined) origin = 'default'\n return { name: v.name, origin }\n })\n}\n\n/** Values validated at startup (or on first `get()`), by prefix. */\nconst cached = new WeakMap<Settings<unknown>, unknown>()\n\n/**\n * Define a typed configuration section read from env variables with a prefix.\n * Each key path becomes one variable: `pool.max` under `'DB'` is `DB_POOL_MAX`,\n * `maxConnections` is `DB_MAX_CONNECTIONS`. A list reads a comma-separated\n * value. `<NAME>_FILE` secrets work for every variable.\n *\n * ```ts\n * export const DbSettings = defineSettings('DB', z.object({\n * url: z.string().url(),\n * pool: z.object({ max: z.coerce.number().default(10) }).default({ max: 10 }),\n * }))\n *\n * @Service()\n * class Database {\n * constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}\n * }\n * ```\n *\n * Declare it where it's used — `bootstrap({ settings })`, a module's, adapter's\n * or plugin's `settings()` — and it is validated when the app starts (a\n * missing or invalid value fails startup, naming the variable) and injectable\n * by its token. Undeclared, `get()` validates it on first use. Values\n * come from the schema's coercion: use `z.coerce.number()`, and\n * `z.stringbool()` for booleans (`z.coerce.boolean()` reads `'false'` as true).\n */\nexport function defineSettings<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n return createSection(prefix, schema)\n}\n\nfunction createSection<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n type T = InferSchemaOutput<S>\n if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) {\n throw new Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`)\n }\n const wrapped = detectSchema(schema)\n // The env names come from the schema's shape, read through its JSON schema —\n // the one view every adapter (Zod, Valibot, Yup) provides.\n const shape = wrapped.toJsonSchema() as JsonShape\n if (!shape.properties) {\n throw new Error(\n `defineSettings('${prefix}'): the schema must be an object whose keys can be read ` +\n '(Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.',\n )\n }\n const leaves = leavesOf(shape, prefix)\n // `fooBar` and `foo_bar` would both read `DB_FOO_BAR` — one variable for two\n // settings that could never differ. Refuse it here, naming both paths.\n const seenEnv = new Map<string, string>()\n for (const leaf of leaves) {\n const path = leaf.path.join('.')\n const other = seenEnv.get(leaf.env)\n if (other !== undefined) {\n throw new Error(\n `defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`,\n )\n }\n seenEnv.set(leaf.env, path)\n }\n const envNames = leaves.map((leaf) => leaf.env)\n const byPath = new Map(leaves.map((leaf) => [leaf.path.join('.'), leaf.env]))\n\n const load = (env: NodeJS.ProcessEnv = process.env): T => {\n const source = readSecretFiles ? readSecretFiles(env, envNames) : env\n const input: Record<string, unknown> = {}\n for (const leaf of leaves) {\n const raw = source[leaf.env]\n if (raw === undefined) continue\n let target = input\n for (const key of leaf.path.slice(0, -1)) {\n target = (target[key] ??= {}) as Record<string, unknown>\n }\n target[leaf.path.at(-1)!] = leaf.list\n ? raw\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean)\n : raw\n }\n return validate(input)\n }\n\n const validate = (input: unknown): T => {\n const result = wrapped.safeParse(input)\n if (result.success) return result.data as T\n const problems = result.issues.map((issue) => {\n const key = issue.path.join('.')\n // The variable to fix, not the schema path; a nested object that is\n // missing entirely names its prefix.\n const name =\n byPath.get(key) ?? [prefix, ...issue.path.map((p) => envSegment(String(p)))].join('_')\n return ` ${name}: ${issue.message}`\n })\n throw new Error(`Settings '${prefix}' are invalid:\\n${problems.join('\\n')}`)\n }\n\n const scopes = new Map<string, Settings<T>>()\n const settings: Settings<T> = Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name: `Settings(${prefix})`,\n prefix,\n envNames,\n load,\n parse: (value: unknown): T => validate(value),\n provide: (value: unknown): ProvidedSettings<T> =>\n Object.freeze({ [PROVIDED]: true as const, section: settings, value }),\n describe: () => leaves.map(toConfigVar),\n get: (): T => {\n // What injected code sees: the container's binding, which a module or a\n // test may have replaced. Before the app binds it, the validated env.\n const container = Container.getInstance()\n if (container.has(settings)) return container.resolve(settings) as T\n // Keyed by the section, not its prefix: two sections sharing a prefix\n // each parse their own schema.\n if (!cached.has(settings)) cached.set(settings, load())\n return cached.get(settings) as T\n },\n scoped: (name: string): Settings<T> => {\n const scopePrefix = `${name}_${prefix}`\n let scoped = scopes.get(scopePrefix)\n if (!scoped) {\n scoped = createSection(scopePrefix, schema) as Settings<T>\n scopes.set(scopePrefix, scoped)\n }\n return scoped\n },\n }) as Settings<T>\n return settings\n}\n\n/**\n * Validate the given sections — the ones the app declared — throwing once\n * with every problem, so a misconfigured deploy fails at startup with the\n * whole list. A section declared twice is loaded once; two different sections\n * with one prefix would read the same variables, and are refused.\n */\nexport function loadSettings(\n declarations: Iterable<SettingsDeclaration>,\n env: NodeJS.ProcessEnv = process.env,\n /**\n * Prefixes already taken, across calls — an app binds in two phases (app\n * sections, then modules') and a clash between them must still be refused.\n */\n byPrefix: Map<string, Settings<unknown>> = new Map(),\n /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */\n providedBefore: Map<Settings<unknown>, unknown> = new Map(),\n): Map<Settings<unknown>, unknown> {\n const values = new Map<Settings<unknown>, unknown>()\n const failures: string[] = []\n // A provided value wins over the same section read from env, wherever each\n // was declared — a test's provide() must not lose to a module's section.\n const provided = new Map<Settings<unknown>, unknown>()\n const sections: Settings<unknown>[] = []\n for (const decl of declarations) {\n if (isProvided(decl)) {\n // Two provides of one section would silently keep whichever came last.\n const earlier = provided.has(decl.section) ? provided : providedBefore\n if (earlier.has(decl.section) && earlier.get(decl.section) !== decl.value) {\n failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`)\n continue\n }\n provided.set(decl.section, decl.value)\n sections.push(decl.section)\n } else {\n sections.push(decl)\n }\n }\n for (const section of sections) {\n if (values.has(section)) continue\n const other = byPrefix.get(section.prefix)\n // Already bound in an earlier phase: nothing to do — unless that read env\n // and this phase provides a value, which wins.\n if (other === section && !(provided.has(section) && !providedBefore.has(section))) continue\n if (other && other !== section) {\n failures.push(`Two different settings sections use the prefix '${section.prefix}'.`)\n continue\n }\n byPrefix.set(section.prefix, section)\n try {\n const value = provided.has(section) ? section.parse(provided.get(section)) : section.load(env)\n values.set(section, value)\n if (provided.has(section)) providedBefore.set(section, provided.get(section))\n // `get()` returns what the app started with.\n cached.set(section, value)\n } catch (err) {\n failures.push((err as Error).message)\n }\n }\n if (failures.length > 0) throw new Error(failures.join('\\n'))\n return values\n}\n"],"mappings":";;;;;;;;;;oJAsBA,IAAI,gBAGJ,SAAgB,qBAAqB,OAAgC,CACnE,gBAAkB,MACpB,CAuCA,MAAM,SAAW,OAAO,IAAI,0BAA0B,EAYtD,SAAS,WAAW,KAA8D,CAChF,OAAQ,KAA4C,YAAc,EACpE,CAqCA,MAAM,WAAc,KAAgB,IAAI,QAAQ,qBAAsB,OAAO,CAAC,CAAC,YAAY,EAO3F,SAAS,SAAS,MAAkB,OAAgB,KAAiB,CAAC,EAAG,SAAW,GAAc,CAChG,GAAI,MAAM,WAAY,CACpB,IAAM,IAAM,IAAI,IAAI,MAAM,UAAY,CAAC,CAAC,EAClC,eAAiB,UAAY,MAAM,UAAY,IAAA,GACrD,OAAO,OAAO,QAAQ,MAAM,UAAU,CAAC,CAAC,SAAS,CAAC,IAAK,SACrD,SAAS,MAAO,OAAQ,CAAC,GAAG,KAAM,GAAG,EAAG,gBAAkB,IAAI,IAAI,GAAG,CAAC,CACxE,CACF,CACA,IAAM,MAAQ,MAAM,QAAQ,MAAM,IAAI,EAAI,MAAM,KAAO,CAAC,MAAM,IAAI,EAClE,MAAO,CACL,CACE,KACA,IAAK,CAAC,OAAQ,GAAG,KAAK,IAAI,UAAU,CAAC,CAAC,CAAC,KAAK,GAAG,EAC/C,KAAM,MAAM,SAAS,OAAO,EAC5B,SAAU,UAAY,MAAM,UAAY,IAAA,GACxC,GAAI,MAAM,UAAY,IAAA,GAAyC,CAAC,EAA9B,CAAE,QAAS,MAAM,OAAQ,EAC3D,GAAI,MAAM,YAAc,CAAE,YAAa,MAAM,WAAY,EAAI,CAAC,CAChE,CACF,CACF,CAEA,MAAM,YAAe,OAA2B,CAC9C,KAAM,KAAK,IACX,SAAU,KAAK,SACf,KAAM,KAAK,KACX,GAAI,KAAK,UAAY,IAAA,GAAwC,CAAC,EAA7B,CAAE,QAAS,KAAK,OAAQ,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IAAI,OAAO,EAAG,SACzB,IAAM,MAAQ,SAAS,IAAI,QAAQ,MAAM,EAGzC,GAAI,QAAU,SAAa,SAAS,IAAI,OAAO,GAAM,gBAAe,IAAI,OAAO,EAC/E,IAAI,OAAS,QAAU,QACrB,SAAS,KAAK,mDAAmD,QAAQ,OAAO,GAAG,MAGrF,UAAS,IAAI,QAAQ,OAAQ,OAAO,EACpC,GAAI,CACF,IAAM,MAAQ,SAAS,IAAI,OAAO,EAAI,QAAQ,MAAM,SAAS,IAAI,OAAO,CAAC,EAAI,QAAQ,KAAK,GAAG,EAC7F,OAAO,IAAI,QAAS,KAAK,EACrB,SAAS,IAAI,OAAO,GAAG,eAAe,IAAI,QAAS,SAAS,IAAI,OAAO,CAAC,EAE5E,OAAO,IAAI,QAAS,KAAK,CAC3B,OAAS,IAAK,CACZ,SAAS,KAAM,IAAc,OAAO,CACtC,CAToC,CADpC,CAWF,CACA,GAAI,SAAS,OAAS,EAAG,MAAU,MAAM,SAAS,KAAK;CAAI,CAAC,EAC5D,OAAO,MACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.3
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import{HttpException,HttpStatus}from"./core/errors.mjs";const MIME_MAP={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,bmp:`image/bmp`,ico:`image/x-icon`,tiff:`image/tiff`,tif:`image/tiff`,avif:`image/avif`,pdf:`application/pdf`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,txt:`text/plain`,csv:`text/csv`,zip:`application/zip`,gz:`application/gzip`,tar:`application/x-tar`,rar:`application/vnd.rar`,"7z":`application/x-7z-compressed`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,flac:`audio/flac`,aac:`audio/aac`,mp4:`video/mp4`,webm:`video/webm`,avi:`video/x-msvideo`,mov:`video/quicktime`,mkv:`video/x-matroska`,json:`application/json`,xml:`application/xml`,html:`text/html`};function resolveMimeTypes(types){return types.map(t=>{let lower=t.toLowerCase().replace(/^\./,``);return MIME_MAP[lower]??t})}function buildFileTypeFilter(allowedTypes,customMimeMap){if(!allowedTypes)return()=>!0;if(typeof allowedTypes==`function`)return allowedTypes;let mimeMap=customMimeMap?{...MIME_MAP,...customMimeMap}:MIME_MAP,resolved=allowedTypes.map(t=>mimeMap[t.toLowerCase().replace(/^\./,``)]??t);return mimetype=>resolved.some(type=>type.endsWith(`/*`)?mimetype.startsWith(type.replace(`/*`,`/`)):mimetype===type)}const DEFAULT_MAX_SIZE=5242880;function normalizeOriginalName(name){return(name.normalize(`NFC`).split(/[\\/]/).pop()??``).replace(/[\u0000-\u001f\u007f]/g,``).trim()}function matchingExtension(name,mimetype,customMimeMap){let dot=name.lastIndexOf(`.`);if(dot<=0)return``;let ext=name.slice(dot+1).toLowerCase(),type=mimetype.split(`;`)[0].trim().toLowerCase();return(customMimeMap?.[ext]??MIME_MAP[ext])===type?`.${ext}`:``}function serverFileName(file,options={}){let{rename,customMimeMap}=options;if(!rename){let ext=matchingExtension(file.originalname,file.mimetype,customMimeMap);return`${globalThis.crypto.randomUUID()}${ext}`}let name=rename(file);if(typeof name!=`string`||name===``||name===`.`||name===`..`||name.length>255||/[\\/\0]/.test(name))throw Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`);return name}const UPLOAD_FIELDS_ALLOWANCE=1048576,MAX_UPLOAD_FIELDS=1e3;function uploadLimits(config){let fileSize=config.maxSize??DEFAULT_MAX_SIZE,files=config.mode===`none`?0:config.mode===`single`?1:config.maxCount??10;return{fileSize,files,total:fileSize*files+UPLOAD_FIELDS_ALLOWANCE}}function tooManyFiles(limit){return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`Too many files: at most ${limit}`)}function applyUploadConfig(parts,config){if(config.mode===`none`)return{};let field=config.fieldName??`file`,maxSize=config.maxSize??DEFAULT_MAX_SIZE,typeAllowed=buildFileTypeFilter(config.allowedTypes,config.customMimeMap),files=parts.filter(p=>p.fieldname===field).map(p=>{if(!typeAllowed(p.mimetype,p.filename))throw new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${p.mimetype} is not allowed`);if(p.buffer.length>maxSize)throw new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${p.filename} exceeds the ${maxSize}-byte limit`);let named={fieldname:p.fieldname,originalname:normalizeOriginalName(p.filename),mimetype:p.mimetype,size:p.buffer.length};return{...named,filename:serverFileName(named,config),encoding:`7bit`,buffer:p.buffer}});if(config.mode===`single`)return{file:files[0]};let maxCount=config.maxCount??10;return{files:files.slice(0,maxCount)}}export{normalizeOriginalName as a,tooManyFiles as c,buildFileTypeFilter as i,uploadLimits as l,UPLOAD_FIELDS_ALLOWANCE as n,resolveMimeTypes as o,applyUploadConfig as r,serverFileName as s,MAX_UPLOAD_FIELDS as t};
|
|
12
|
-
//# sourceMappingURL=upload-config-
|
|
12
|
+
//# sourceMappingURL=upload-config-C_SlwFq0.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload-config-D8OMmdY7.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;;;;;;;;;wDAUA,MAAa,SAAmC,CAE9C,IAAK,aACL,KAAM,aACN,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,gBACL,IAAK,YACL,IAAK,eACL,KAAM,aACN,IAAK,aACL,KAAM,aAEN,IAAK,kBACL,IAAK,qBACL,KAAM,0EACN,IAAK,2BACL,KAAM,oEACN,IAAK,gCACL,KAAM,4EACN,IAAK,0CACL,IAAK,iDACL,IAAK,kDACL,IAAK,kBACL,IAAK,aACL,IAAK,WAEL,IAAK,kBACL,GAAI,mBACJ,IAAK,oBACL,IAAK,sBACL,KAAM,8BAEN,IAAK,aACL,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,YAEL,IAAK,YACL,KAAM,aACN,IAAK,kBACL,IAAK,kBACL,IAAK,mBAEL,KAAM,mBACN,IAAK,kBACL,KAAM,WACR,EAYA,SAAgB,iBAAiB,MAA2B,CAC1D,OAAO,MAAM,IAAK,GAAM,CACtB,IAAM,MAAQ,EAAE,YAAY,CAAC,CAAC,QAAQ,MAAO,EAAE,EAC/C,OAAO,SAAS,QAAU,CAC5B,CAAC,CACH,CASA,SAAgB,oBACd,aACA,cACiD,CACjD,GAAI,CAAC,aAAc,UAAa,GAChC,GAAI,OAAO,cAAiB,WAAY,OAAO,aAC/C,IAAM,QAAU,cAAgB,CAAE,GAAG,SAAU,GAAG,aAAc,EAAI,SAC9D,SAAW,aAAa,IAAK,GAAM,QAAQ,EAAE,YAAY,CAAC,CAAC,QAAQ,MAAO,EAAE,IAAM,CA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AAW,MAAQ,uBAAwB,CAC9E,CAGA,SAAgB,aAAa,MAA8B,CACzD,OAAO,IAAI,cAAc,WAAW,kBAAmB,2BAA2B,OAAO,CAC3F,CASA,SAAgB,kBACd,MACA,OACyD,CACzD,GAAI,OAAO,OAAS,OAAQ,MAAO,CAAC,EAEpC,IAAM,MAAQ,OAAO,WAAa,OAC5B,QAAU,OAAO,SAAW,iBAC5B,YAAc,oBAAoB,OAAO,aAAc,OAAO,aAAa,EAG3E,MADU,MAAM,OAAQ,GAAM,EAAE,YAAc,KACZ,CAAC,CAAC,IAAK,GAAM,CACnD,GAAI,CAAC,YAAY,EAAE,SAAU,EAAE,QAAQ,EACrC,MAAM,IAAI,cACR,WAAW,uBACX,aAAa,EAAE,SAAS,gBAC1B,EAEF,GAAI,EAAE,OAAO,OAAS,QACpB,MAAM,IAAI,cACR,WAAW,kBACX,QAAQ,EAAE,SAAS,eAAe,QAAQ,YAC5C,EAEF,IAAM,MAAQ,CACZ,UAAW,EAAE,UACb,aAAc,sBAAsB,EAAE,QAAQ,EAC9C,SAAU,EAAE,SACZ,KAAM,EAAE,OAAO,MACjB,EACA,MAAO,CACL,GAAG,MACH,SAAU,eAAe,MAAO,MAAM,EACtC,SAAU,OACV,OAAQ,EAAE,MACZ,CACF,CAAC,EAED,GAAI,OAAO,OAAS,SAAU,MAAO,CAAE,KAAM,MAAM,EAAG,EACtD,IAAM,SAAW,OAAO,UAAY,GACpC,MAAO,CAAE,MAAO,MAAM,MAAM,EAAG,QAAQ,CAAE,CAC3C"}
|
|
1
|
+
{"version":3,"file":"upload-config-C_SlwFq0.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;;;;;;;;;wDAUA,MAAa,SAAmC,CAE9C,IAAK,aACL,KAAM,aACN,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,gBACL,IAAK,YACL,IAAK,eACL,KAAM,aACN,IAAK,aACL,KAAM,aAEN,IAAK,kBACL,IAAK,qBACL,KAAM,0EACN,IAAK,2BACL,KAAM,oEACN,IAAK,gCACL,KAAM,4EACN,IAAK,0CACL,IAAK,iDACL,IAAK,kDACL,IAAK,kBACL,IAAK,aACL,IAAK,WAEL,IAAK,kBACL,GAAI,mBACJ,IAAK,oBACL,IAAK,sBACL,KAAM,8BAEN,IAAK,aACL,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,YAEL,IAAK,YACL,KAAM,aACN,IAAK,kBACL,IAAK,kBACL,IAAK,mBAEL,KAAM,mBACN,IAAK,kBACL,KAAM,WACR,EAYA,SAAgB,iBAAiB,MAA2B,CAC1D,OAAO,MAAM,IAAK,GAAM,CACtB,IAAM,MAAQ,EAAE,YAAY,CAAC,CAAC,QAAQ,MAAO,EAAE,EAC/C,OAAO,SAAS,QAAU,CAC5B,CAAC,CACH,CASA,SAAgB,oBACd,aACA,cACiD,CACjD,GAAI,CAAC,aAAc,UAAa,GAChC,GAAI,OAAO,cAAiB,WAAY,OAAO,aAC/C,IAAM,QAAU,cAAgB,CAAE,GAAG,SAAU,GAAG,aAAc,EAAI,SAC9D,SAAW,aAAa,IAAK,GAAM,QAAQ,EAAE,YAAY,CAAC,CAAC,QAAQ,MAAO,EAAE,IAAM,CAAC,EACzF,MAAQ,WACN,SAAS,KAAM,MACb,KAAK,SAAS,IAAI,EAAI,SAAS,WAAW,KAAK,QAAQ,KAAM,GAAG,CAAC,EAAI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3F,CASA,SAAgB,kBACd,MACA,OACyD,CACzD,GAAI,OAAO,OAAS,OAAQ,MAAO,CAAC,EAEpC,IAAM,MAAQ,OAAO,WAAa,OAC5B,QAAU,OAAO,SAAW,iBAC5B,YAAc,oBAAoB,OAAO,aAAc,OAAO,aAAa,EAG3E,MADU,MAAM,OAAQ,GAAM,EAAE,YAAc,KACZ,CAAC,CAAC,IAAK,GAAM,CACnD,GAAI,CAAC,YAAY,EAAE,SAAU,EAAE,QAAQ,EACrC,MAAM,IAAI,cACR,WAAW,uBACX,aAAa,EAAE,SAAS,gBAC1B,EAEF,GAAI,EAAE,OAAO,OAAS,QACpB,MAAM,IAAI,cACR,WAAW,kBACX,QAAQ,EAAE,SAAS,eAAe,QAAQ,YAC5C,EAEF,IAAM,MAAQ,CACZ,UAAW,EAAE,UACb,aAAc,sBAAsB,EAAE,QAAQ,EAC9C,SAAU,EAAE,SACZ,KAAM,EAAE,OAAO,MACjB,EACA,MAAO,CACL,GAAG,MACH,SAAU,eAAe,MAAO,MAAM,EACtC,SAAU,OACV,OAAQ,EAAE,MACZ,CACF,CAAC,EAED,GAAI,OAAO,OAAS,SAAU,MAAO,CAAE,KAAM,MAAM,EAAG,EACtD,IAAM,SAAW,OAAO,UAAY,GACpC,MAAO,CAAE,MAAO,MAAM,MAAM,EAAG,QAAQ,CAAE,CAC3C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.3
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{n as createToken}from"./token-
|
|
12
|
-
//# sourceMappingURL=url-for-
|
|
11
|
+
import{n as createToken}from"./token-BRZwz7iz.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);if(Array.isArray(params)){let list=params,keys=[...pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map(m=>m[1]);if(list.length!==keys.length)throw Error(`urlFor('${name}'): takes ${keys.length} param${keys.length===1?``:`s`}${keys.length?` (${keys.join(`, `)})`:``}, got ${list.length}`)}let at=0,path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=Array.isArray(params)?params[at++]:params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
|
|
12
|
+
//# sourceMappingURL=url-for-C5R5ZrDW.mjs.map
|