@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":"define-adapter-
|
|
1
|
+
{"version":3,"file":"define-adapter-C_97M6VW.mjs","names":[],"sources":["../src/core/define-adapter.ts"],"sourcesContent":["import type { AppAdapter, AdapterContext } from './adapter'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}\n * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter\n * symmetry rationale.\n *\n * The optional `TExtra` generic lets an adapter ship public methods\n * beyond the standard {@link AppAdapter} contract — they're preserved\n * on the returned adapter instance so external callers (tests, peer\n * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`\n * for the canonical use case.\n */\nexport interface DefineAdapterOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`\n * namespacing. Required for adapters that participate in `dependsOn`\n * sort — error messages reference adapters by name.\n */\n name: string\n version?: string\n requires?: { kickjs?: string }\n defaults?: Partial<TConfig>\n build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra\n}\n\n/**\n * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`\n * but resolved during `beforeStart` (the earliest async hook in\n * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner\n * adapter are **not** picked up. Use the bare/`.scoped()` form when you need\n * those.\n */\nexport interface AdapterAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link defineAdapter}. Same surface as\n * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn\n * one mental model for both primitives. Returned instances carry both\n * the standard {@link AppAdapter} contract and any `TExtra` extension\n * methods the `build` function exposed.\n */\nexport interface AdapterFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppAdapter & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra\n async(opts: AdapterAsyncOptions<TConfig>): AppAdapter\n readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppAdapter} factory from a typed definition. See\n * `architecture.md` §21.3.4 for migration guidance — most first-party\n * adapter packages collapse to a single `defineAdapter()` call after this\n * lands.\n *\n * @example\n * ```ts\n * const TenantAdapter = defineAdapter<TenantConfig>({\n * name: 'TenantAdapter',\n * defaults: { strategy: 'header', required: true },\n * build: (config) => ({\n * middleware: () => [tenantResolverMiddleware(config)],\n * beforeStart: ({ container }) => registerTenantFactory(container, config),\n * }),\n * })\n *\n * bootstrap({\n * adapters: [\n * TenantAdapter({ strategy: 'subdomain' }),\n * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),\n * ],\n * })\n * ```\n */\nexport function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineAdapterOptions<TConfig, TExtra>,\n): AdapterFactory<TConfig, TExtra> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppAdapter & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n // Extension methods declared by the build function (`TExtra`) survive\n // the mutation since they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped }) as AppAdapter & TExtra\n ;(built as AppAdapter).name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: AdapterAsyncOptions<TConfig>): AppAdapter => {\n let inner: AppAdapter | undefined\n\n return {\n name: instanceName,\n async beforeStart(ctx: AdapterContext) {\n const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n await inner.beforeStart?.(ctx)\n },\n async afterStart(ctx: AdapterContext) {\n await inner?.afterStart?.(ctx)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n async onHealthCheck() {\n return (await inner?.onHealthCheck?.()) ?? { name: instanceName, status: 'up' }\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as AdapterFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: AdapterAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n"],"mappings":";;;;;;;;;;AAqDA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA2BxE,SAAgB,cACd,QACiC,CACjC,IAAM,WACJ,aACA,OACA,YACwB,CACxB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAElE,MADC,OAAsB,KAAO,aACvB,KACT,EAEM,YAAc,aAAsB,OAAmD,CAC3F,IAAI,MAEJ,MAAO,CACL,KAAM,aACN,MAAM,YAAY,IAAqB,CACrC,IAAM,MAAQ,KAAK,QAAU,CAAC,EAAA,CAAG,IAAK,KAAQ,IAAI,UAAU,QAAQ,GAAY,CAAC,EAC3E,OAAS,MAAM,KAAK,WAAW,GAAG,IAAI,EAC5C,MAAQ,UAAU,aAAc,GAAO,MAA0B,EACjE,MAAM,MAAM,cAAc,GAAG,CAC/B,EACA,MAAM,WAAW,IAAqB,CACpC,MAAM,OAAO,aAAa,GAAG,CAC/B,EACA,MAAM,UAAW,CACf,MAAM,OAAO,WAAW,CAC1B,EACA,MAAM,eAAgB,CACpB,OAAQ,MAAM,OAAO,gBAAgB,GAAM,CAAE,KAAM,aAAc,OAAQ,IAAK,CAChF,CACF,CACF,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GASvC,MAPA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,QAAQ,MAAS,MAAuC,WAAW,QAAQ,KAAM,IAAI,EAErF,OAAO,eAAe,QAAS,aAAc,CAAE,MAAO,OAAO,OAAO,CAAE,GAAG,OAAQ,CAAC,CAAE,CAAC,EAE9E,OACT"}
|
|
@@ -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
|
*
|
|
@@ -136,4 +136,4 @@ Behind a proxy or service mesh that speaks cleartext HTTP/2 to the app (gRPC
|
|
|
136
136
|
through Envoy or Linkerd), use \`http2: 'h2c'\` instead. Or remove \`http2\` if
|
|
137
137
|
the proxy sends HTTP/1.1.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`})}function tlsCredentialsError(problem){return new KickError({code:`KICK009`,summary:`server.tls is not usable: ${problem}`,cause:`\`bootstrap({ server: { tls } })\` was given TLS options the server cannot use:
|
|
138
138
|
${problem}. Node would start anyway and fail every TLS handshake.`,fix:"Give the server an identity:\n • `key` and `cert` together (PEM, matching each other), or\n • `pfx` (with `passphrase` if it is encrypted), or\n • `SNICallback` / `pskCallback` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }",docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{problem}})}const CATALOGUE={KICK001:noProviderError,KICK002:requestScopeMiddlewareMissingError,KICK003:requestScopeOutsideRequestError,KICK004:envValueMissingError,KICK010:fallbackAlreadyResolvedError};Container.setErrorFactory((code,subject)=>CATALOGUE[code](subject)),Container.setLogger(createLogger(`Container`)),Container.definePropertyInjector(METADATA.ASSET,({assetKey})=>{let slash=assetKey.indexOf(`/`);if(slash===-1)throw Error(`@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);let namespace=assetKey.slice(0,slash),key=assetKey.slice(slash+1);return()=>resolveAssetViaSlot(namespace,key)});export{tlsCredentialsError as a,_setAssetResolver as c,moduleRouteMissingControllerError as i,http2RequiresTlsError as n,KickError as o,http2UnsupportedRuntimeError as r,formatKickError as s,duplicateRouteError as t};
|
|
139
|
-
//# sourceMappingURL=di-hooks-
|
|
139
|
+
//# sourceMappingURL=di-hooks-CBFaF0h-.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"di-hooks-BCQxqvPP.mjs","names":[],"sources":["../src/core/asset-resolver-slot.ts","../src/core/kick-error.ts","../src/core/kick-errors.ts","../src/core/di-hooks.ts"],"sourcesContent":["/**\n * Indirection slot between the DI container's `@Asset` property injection\n * and the asset manager. The container must NOT import `./assets` directly —\n * its eager `node:fs`/`node:path` imports would poison the edge-safe\n * `@forinda/kickjs/web` entry graph (every graph includes the container).\n *\n * `./assets` registers the real resolver at module scope, so any node app\n * that imports the asset manager (the core barrel does) gets full `@Asset`\n * behavior; an edge bundle that never imports it gets a clear error on\n * first `@Asset` property access instead of a broken bundle.\n */\n\ntype AssetResolver = (namespace: string, key: string) => unknown\n\nlet impl: AssetResolver | null = null\n\n/** Called by `./assets` at module scope to install the real resolver. */\nexport function _setAssetResolver(fn: AssetResolver): void {\n impl = fn\n}\n\n/** Resolve an asset through the slot — throws when no asset manager is loaded. */\nexport function resolveAssetViaSlot(namespace: string, key: string): unknown {\n if (!impl) {\n throw new Error(\n `@Asset('${namespace}/${key}'): the asset manager is not loaded. ` +\n \"Import it (any import from '@forinda/kickjs' loads it) — note @Asset \" +\n 'reads from the filesystem and is not supported on edge runtimes.',\n )\n }\n return impl(namespace, key)\n}\n","/**\n * Structured framework error with code, cause, and actionable fix hint.\n *\n * The goal is \"the developer who hits this knows what to do next.\" A\n * cryptic `Error('No binding found for: UserService')` becomes a\n * multi-line explanation pointing at the likely cause, the exact code\n * change to apply, and a docs link.\n *\n * `.message` carries the full multi-line plain-text body so Node's\n * default `Error.toString()` and unhandled-exception printing still\n * surface the helpful version. Call {@link formatKickError} to render a\n * colorized version for terminals.\n *\n * Per-error factories live in `kick-errors.ts` — those are the public\n * entry points framework code uses. `KickError` is exported so adopters\n * can build their own structured errors using the same shape.\n */\nexport interface KickErrorInit {\n /** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */\n code: string\n /** One-line headline. */\n summary: string\n /** Multi-line explanation of why this happened. */\n cause?: string\n /** Multi-line actionable fix — show exact code if possible. */\n fix?: string\n /** Absolute URL to the docs page that covers this error. */\n docsUrl?: string\n /** Arbitrary structured fields for log consumers / debug tooling. */\n context?: Record<string, unknown>\n}\n\nexport class KickError extends Error {\n public readonly code: string\n public readonly summary: string\n public readonly cause?: string\n public readonly fix?: string\n public readonly docsUrl?: string\n public readonly context?: Record<string, unknown>\n\n constructor(init: KickErrorInit) {\n super(formatKickError(init, { color: false }))\n this.name = 'KickError'\n this.code = init.code\n this.summary = init.summary\n if (init.cause !== undefined) this.cause = init.cause\n if (init.fix !== undefined) this.fix = init.fix\n if (init.docsUrl !== undefined) this.docsUrl = init.docsUrl\n if (init.context !== undefined) this.context = init.context\n }\n}\n\n// ── ANSI colour helpers ────────────────────────────────────────────────\n\n/**\n * `true` when the runtime can render ANSI escape codes on stderr.\n * Honors `NO_COLOR` (https://no-color.org) and `FORCE_COLOR`.\n */\nfunction ansiEnabled(): boolean {\n if (process.env.NO_COLOR) return false\n if (process.env.FORCE_COLOR) return true\n // Node sets `isTTY` on the writable streams when stdout/stderr is a\n // terminal. KickError output goes to stderr conceptually (it's an\n // error), so we follow that stream's affordances.\n return process.stderr?.isTTY === true\n}\n\n// Use the Unicode-escape form (`\u001b`) rather than the hex-escape (`\\x1b`)\n// for the ANSI ESC byte — both produce the same character, but oxlint's\n// `no-control-character` rule flags the hex form as \"unexpected control\n// character in string literal\". Functionally identical, lint-clean.\nconst ESC = '\u001b['\nconst RESET = `${ESC}0m`\n\nfunction paint(text: string, code: string, enabled: boolean): string {\n return enabled ? `${ESC}${code}m${text}${RESET}` : text\n}\n\nconst c = {\n red: (s: string, enabled: boolean) => paint(s, '31', enabled),\n bold: (s: string, enabled: boolean) => paint(s, '1', enabled),\n dim: (s: string, enabled: boolean) => paint(s, '2', enabled),\n cyan: (s: string, enabled: boolean) => paint(s, '36', enabled),\n blue: (s: string, enabled: boolean) => paint(s, '34', enabled),\n underline: (s: string, enabled: boolean) => paint(s, '4', enabled),\n}\n\n// ── Formatter ─────────────────────────────────────────────────────────\n\nexport interface FormatKickErrorOptions {\n /**\n * Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /\n * `FORCE_COLOR` env vars honoured). Pass `false` for log files,\n * structured loggers, or HTTP response bodies.\n */\n color?: boolean\n}\n\n/**\n * Render a {@link KickErrorInit} (or {@link KickError} instance) into a\n * multi-line human-readable string. Identical layout regardless of\n * colour — the colour flag only toggles ANSI codes.\n */\nexport function formatKickError(\n err: KickErrorInit | KickError,\n options: FormatKickErrorOptions = {},\n): string {\n const color = options.color ?? ansiEnabled()\n const lines: string[] = []\n\n // Headline: `KICK001: No provider for UserService`\n const code = c.bold(c.red(err.code, color), color)\n lines.push(`${code}: ${err.summary}`)\n\n if (err.cause) {\n lines.push('', ` ${c.bold(c.dim('Cause:', color), color)}`)\n for (const line of err.cause.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.fix) {\n lines.push('', ` ${c.bold(c.dim('Fix:', color), color)}`)\n for (const line of err.fix.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.docsUrl) {\n lines.push('', ` ${c.bold(c.dim('Docs:', color), color)}`)\n lines.push(` ${c.underline(c.blue(err.docsUrl, color), color)}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Highlight inline `code spans` in a line of cause/fix text. Anything\n * between backticks gets cyan when colour is enabled; backticks stay\n * in the output so the plain-text rendering still distinguishes\n * literals.\n */\nfunction highlightInline(line: string, color: boolean): string {\n if (!color) return line\n return line.replace(/`([^`]+)`/g, (_, inner: string) => `\\`${c.cyan(inner, true)}\\``)\n}\n","/**\n * Catalog of framework errors with structured cause + fix hints.\n *\n * Each factory function returns a {@link KickError} with a stable\n * `code` (KICK001, KICK002, …), a human-readable summary, an\n * explanation of the likely cause, an actionable fix, and a docs URL.\n *\n * Adding a new error: pick the next free code, add the factory below,\n * call it from the framework site that used to throw a bare `Error`.\n * Keep the public function name descriptive — `noProviderError`,\n * `envValueMissingError` — so call sites grep cleanly.\n *\n * Codes are stable. Reordering or renumbering breaks adopters whose\n * tools key on `err.code`.\n */\nimport { KickError } from './kick-error'\n\nconst DOCS_BASE = 'https://kickjs.app'\n\n// ── DI container ──────────────────────────────────────────────────────\n\n/**\n * KICK001 — No provider registered for a token.\n *\n * Thrown by `Container.resolve()` when no binding can be found for the\n * requested token. The most common cause is forgetting to add the\n * enclosing module to `bootstrap({ modules })`.\n */\nexport function noProviderError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK001',\n summary: `No provider for ${tokenName}`,\n cause: `\\`${tokenName}\\` was requested from the DI container but no binding is registered.\nThis usually means one of:\n • The class is decorated with @Service() / @Repository() / @Controller(),\n but its enclosing module isn't passed to bootstrap({ modules: [...] }).\n • The class isn't decorated at all (decorators register the binding).\n • You're injecting a token (created with createToken()) that nothing\n provides — add a Container.register(TOKEN, ...) call or a module that\n binds it.`,\n fix: `If \\`${tokenName}\\` lives in a module, add the module to bootstrap:\n\n bootstrap({\n modules: [\n UsersModule, // add this\n OtherModule,\n ],\n })\n\nIf it's a custom token, register it explicitly:\n\n const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')\n Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#registering-services`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK002 — REQUEST-scoped binding resolved without a request store\n * provider configured.\n */\nexport function requestScopeMiddlewareMissingError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK002',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" — request scope middleware not mounted`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` but no AsyncLocalStorage frame is wired.\nThe framework's request-scope middleware sets up that frame; without it,\nREQUEST-scoped resolutions have nowhere to cache the per-request instance.`,\n fix: `Add \\`requestScopeMiddleware()\\` to your global middleware pipeline,\nor let the framework auto-mount it by using \\`contextStore: 'auto'\\`\n(the default — only check this if you set it to 'manual' explicitly):\n\n bootstrap({\n modules,\n // contextStore: 'auto', // default; no need to set\n })\n\nIf you set \\`contextStore: 'manual'\\` deliberately (rare), you own the\nALS wrapping — call \\`requestStore.run({...}, () => ...)\\` around the\ncode that resolves the binding.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK003 — REQUEST-scoped binding resolved outside any HTTP request\n * context (no ALS store active).\n */\nexport function requestScopeOutsideRequestError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK003',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" outside an HTTP request`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` and was resolved outside\nany HTTP request context. The request-scope middleware is wired, but\nthe call happened before a request started (e.g. in a top-level\nimport, a constructor, a cron job, a test without setup).`,\n fix: `If the caller is request-scoped (controller, request-scoped service),\nmake sure the call happens inside the request lifecycle, not at module\nload time.\n\nIn tests, wrap setup in an ALS frame manually:\n\n import { requestStore } from '@forinda/kickjs'\n\n requestStore.run(\n { requestId: 'test', instances: new Map(), values: new Map() },\n () => {\n const svc = container.resolve(MyRequestScopedService)\n // ...\n },\n )\n\nIf the caller is a SINGLETON, change \\`${tokenName}\\` to TRANSIENT or\nSINGLETON scope, or inject a factory instead of the instance directly.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK010 — A token was bound normally after its `registerFallback()`\n * singleton had already been resolved.\n *\n * Whatever resolved the fallback still holds that instance; letting the new\n * binding take over would leave two instances that disagree.\n */\nexport function fallbackAlreadyResolvedError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK010',\n summary: `Cannot bind ${tokenName}: its fallback was already resolved`,\n cause: `\\`${tokenName}\\` has a default from \\`container.registerFallback()\\`, and something\nresolved that default before the app bound its own. Code that resolved it holds\nthe fallback instance; the new binding would hand everyone else a different one.`,\n fix: `Bind \\`${tokenName}\\` before anything resolves it — in a module's\n\\`register(container)\\` or a plugin's \\`register()\\`, not later in a request or\nan \\`afterStart\\` hook. If an adapter resolves the token while booting (in\n\\`beforeMount\\`), resolve it lazily instead (in \\`beforeStart\\` or on first use).`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#fallback-bindings`,\n context: { token: tokenName },\n })\n}\n\n// ── Config / env wiring ───────────────────────────────────────────────\n\n/**\n * KICK004 — `@Value('X')` resolved but the env var isn't set and no\n * default was provided.\n *\n * This is the canonical \"you forgot to wire env\" symptom — surfaces\n * when ConfigService can't find the key. The fix usually involves\n * either setting the env var or wiring `loadEnv(envSchema)` at startup.\n */\nexport function envValueMissingError(envKey: string): KickError {\n return new KickError({\n code: 'KICK004',\n summary: `@Value('${envKey}'): environment variable not set and no default provided`,\n cause: `\\`@Value('${envKey}')\\` resolved but the env var isn't present and the\ndecorator didn't declare a default. Possible reasons:\n • The variable is genuinely missing from your environment / .env file.\n • Your \\`src/env.ts\\` calls \\`loadEnv(envSchema)\\` but \\`src/index.ts\\`\n doesn't import \\`./env\\` before \\`bootstrap()\\`. Without that import\n the schema never runs and ConfigService stays empty — \\`@Value\\`\n only finds the var via the \\`process.env\\` fallback.`,\n fix: `Either set the variable in your shell / .env file:\n\n ${envKey}=...\n\nOr add a default at the decorator:\n\n @Value('${envKey}', { default: 'fallback' })\n private value!: string\n\nIf you're using a schema, make sure \\`src/env.ts\\` is imported from\n\\`src/index.ts\\` BEFORE bootstrap runs:\n\n // src/index.ts\n import 'reflect-metadata'\n import './env' // ← this line is required\n import { bootstrap } from '@forinda/kickjs'\n // ...`,\n docsUrl: `${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,\n context: { envKey },\n })\n}\n\n// ── Module setup ──────────────────────────────────────────────────────\n\n/**\n * KICK005 — A module's `routes()` return value declares a mount path\n * but provides neither a `controller` class nor a pre-built `router`.\n */\nexport function moduleRouteMissingControllerError(mountPath: string): KickError {\n return new KickError({\n code: 'KICK005',\n summary: `Module route at ${mountPath} requires either 'controller' or 'router'`,\n cause: `A module's \\`routes()\\` returned an entry for \\`${mountPath}\\` but didn't\nspecify how to build the router. The framework needs either a decorated\ncontroller class (it calls \\`buildRoutes()\\` internally) or a hand-built\nExpress Router.`,\n fix: `Pass \\`controller:\\` for the common case:\n\n routes() {\n return {\n path: '${mountPath}',\n controller: UsersController,\n }\n }\n\nOr pass \\`router:\\` for full control:\n\n routes() {\n return {\n path: '${mountPath}',\n router: myExpressRouter,\n }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { mountPath },\n })\n}\n\n/**\n * KICK006 — Two handlers claim the same HTTP verb + mounted path. The\n * engine would silently dispatch one of them (Express/h3: first wins,\n * Fastify: its own throw), while typegen and the typed client may\n * describe the other — so this fails at boot instead.\n */\nexport function duplicateRouteError(\n method: string,\n path: string,\n owner: string,\n prior: string,\n): KickError {\n return new KickError({\n code: 'KICK006',\n summary: `Duplicate route: ${method} ${path} is registered twice`,\n cause: `\\`${owner}\\` registers \\`${method} ${path}\\`, but that verb + path is\nalready claimed by \\`${prior}\\`. Only one handler can win at dispatch\ntime, and which one depends on the engine — while \\`kick typegen\\` and\nthe typed client may describe the other. Param names are ignored when\ncomparing (\\`/:id\\` and \\`/:taskId\\` are the same route).`,\n fix: `Change one of the two paths, remove the duplicate handler, or mount\nthe second controller under a different module path / version:\n\n routes() {\n return { path: '/tasks', controller: TasksController, version: 2 }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { method, path, owner, prior },\n })\n}\n\n// ── Server ────────────────────────────────────────────────────────────\n\n/**\n * KICK007 — `server.http2` on a runtime that cannot serve HTTP/2. Express 5\n * does not run on Node's HTTP/2 compatibility layer (requests hang and it\n * throws internally), so this fails at boot rather than on the first request.\n */\nexport function http2UnsupportedRuntimeError(runtime: string): KickError {\n return new KickError({\n code: 'KICK007',\n summary: `The ${runtime} runtime cannot serve HTTP/2`,\n cause: `\\`bootstrap({ server: { http2: true } })\\` asks for an HTTP/2 server, but the\n\\`${runtime}\\` runtime does not support Node's HTTP/2 compatibility layer —\nrequests would hang instead of being answered.`,\n fix: `Pick one:\n • Switch to a runtime that serves HTTP/2:\n bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })\n (or h3Runtime()).\n • Drop \\`http2\\` and keep HTTPS over HTTP/1.1: server: { tls }.\n • Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { runtime },\n })\n}\n\n/**\n * KICK008 — `server.http2: true` without `server.tls`, or `http2: 'h2c'` with\n * it. Browsers only speak HTTP/2 over TLS, so cleartext HTTP/2 is its own,\n * explicit setting.\n */\nexport function http2RequiresTlsError(h2cWithTls = false): KickError {\n if (h2cWithTls) {\n return new KickError({\n code: 'KICK008',\n summary: \"server.http2: 'h2c' does not take server.tls\",\n cause: `\\`http2: 'h2c'\\` serves cleartext HTTP/2, but \\`tls\\` was set too.`,\n fix: `Use \\`http2: true\\` to serve HTTP/2 over TLS, or drop \\`tls\\` for cleartext HTTP/2.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n }\n return new KickError({\n code: 'KICK008',\n summary: 'server.http2 requires server.tls',\n cause: `\\`bootstrap({ server: { http2: true } })\\` was set without \\`tls\\`. Browsers only\nnegotiate HTTP/2 over TLS.`,\n fix: `Pass the certificate and key alongside http2:\n\n server: {\n tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },\n http2: true,\n }\n\nBehind a proxy or service mesh that speaks cleartext HTTP/2 to the app (gRPC\nthrough Envoy or Linkerd), use \\`http2: 'h2c'\\` instead. Or remove \\`http2\\` if\nthe proxy sends HTTP/1.1.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n}\n\n/**\n * KICK009 — `server.tls` cannot identify the server. Node starts an HTTPS /\n * HTTP/2 server without a certificate (or with a key that does not match it)\n * and then fails every TLS handshake, so this is checked at boot instead.\n */\nexport function tlsCredentialsError(problem: string): KickError {\n return new KickError({\n code: 'KICK009',\n summary: `server.tls is not usable: ${problem}`,\n cause: `\\`bootstrap({ server: { tls } })\\` was given TLS options the server cannot use:\n${problem}. Node would start anyway and fail every TLS handshake.`,\n fix: `Give the server an identity:\n • \\`key\\` and \\`cert\\` together (PEM, matching each other), or\n • \\`pfx\\` (with \\`passphrase\\` if it is encrypted), or\n • \\`SNICallback\\` / \\`pskCallback\\` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { problem },\n })\n}\n","/**\n * Connects the DI core (`@forinda/kickjs-di`) to\n * the framework: catalogued errors, the logger, and `@Asset` injection.\n * Imported by `./container` and `./decorators`, so every kickjs entry that\n * reaches the container installs them.\n */\nimport { Container, type DiErrorCode } from '@forinda/kickjs-di'\n// Slot indirection, NOT `./assets` — that module's eager node:fs import\n// would poison the edge-safe web entry graph (see asset-resolver-slot.ts).\nimport { resolveAssetViaSlot } from './asset-resolver-slot'\nimport { METADATA } from './interfaces'\nimport {\n envValueMissingError,\n fallbackAlreadyResolvedError,\n noProviderError,\n requestScopeMiddlewareMissingError,\n requestScopeOutsideRequestError,\n} from './kick-errors'\nimport { createLogger } from './logger'\n\nconst CATALOGUE: Record<DiErrorCode, (subject: string) => Error> = {\n KICK001: noProviderError,\n KICK002: requestScopeMiddlewareMissingError,\n KICK003: requestScopeOutsideRequestError,\n KICK004: envValueMissingError,\n KICK010: fallbackAlreadyResolvedError,\n}\n\nContainer.setErrorFactory((code, subject) => CATALOGUE[code](subject))\nContainer.setLogger(createLogger('Container'))\nContainer.definePropertyInjector(METADATA.ASSET, ({ assetKey }: { assetKey: string }) => {\n const slash = assetKey.indexOf('/')\n if (slash === -1) {\n throw new Error(\n `@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`,\n )\n }\n const namespace = assetKey.slice(0, slash)\n const key = assetKey.slice(slash + 1)\n return () => resolveAssetViaSlot(namespace, key)\n})\n"],"mappings":";;;;;;;;;;kIAcA,IAAI,KAA6B,KAGjC,SAAgB,kBAAkB,GAAyB,CACzD,KAAO,EACT,CAGA,SAAgB,oBAAoB,UAAmB,IAAsB,CAC3E,GAAI,CAAC,KACH,MAAU,MACR,WAAW,UAAU,GAAG,IAAI,2KAG9B,EAEF,OAAO,KAAK,UAAW,GAAG,CAC5B,CCCA,IAAa,UAAb,cAA+B,KAAM,CACnC,KACA,QACA,MACA,IACA,QACA,QAEA,YAAY,KAAqB,CAC/B,MAAM,gBAAgB,KAAM,CAAE,MAAO,EAAM,CAAC,CAAC,EAC7C,KAAK,KAAO,YACZ,KAAK,KAAO,KAAK,KACjB,KAAK,QAAU,KAAK,QAChB,KAAK,QAAU,IAAA,KAAW,KAAK,MAAQ,KAAK,OAC5C,KAAK,MAAQ,IAAA,KAAW,KAAK,IAAM,KAAK,KACxC,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,SAChD,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,QACtD,CACF,EAQA,SAAS,aAAuB,CAM9B,OALI,QAAQ,IAAI,SAAiB,GAC7B,QAAQ,IAAI,YAAoB,GAI7B,QAAQ,QAAQ,QAAU,EACnC,CASA,SAAS,MAAM,KAAc,KAAc,QAA0B,CACnE,OAAO,QAAU,K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,CACrB,CAAC,CACH,CCzTA,MAAM,UAA6D,CACjE,QAAS,gBACT,QAAS,mCACT,QAAS,gCACT,QAAS,qBACT,QAAS,4BACX,EAEA,UAAU,iBAAiB,KAAM,UAAY,UAAU,KAAK,CAAC,OAAO,CAAC,EACrE,UAAU,UAAU,aAAa,WAAW,CAAC,EAC7C,UAAU,uBAAuB,SAAS,OAAQ,CAAE,YAAqC,CACvF,IAAM,MAAQ,SAAS,QAAQ,GAAG,EAClC,GAAI,QAAU,GACZ,MAAU,MACR,WAAW,SAAS,mEACtB,EAEF,IAAM,UAAY,SAAS,MAAM,EAAG,KAAK,EACnC,IAAM,SAAS,MAAM,MAAQ,CAAC,EACpC,UAAa,oBAAoB,UAAW,GAAG,CACjD,CAAC"}
|
|
1
|
+
{"version":3,"file":"di-hooks-CBFaF0h-.mjs","names":[],"sources":["../src/core/asset-resolver-slot.ts","../src/core/kick-error.ts","../src/core/kick-errors.ts","../src/core/di-hooks.ts"],"sourcesContent":["/**\n * Indirection slot between the DI container's `@Asset` property injection\n * and the asset manager. The container must NOT import `./assets` directly —\n * its eager `node:fs`/`node:path` imports would poison the edge-safe\n * `@forinda/kickjs/web` entry graph (every graph includes the container).\n *\n * `./assets` registers the real resolver at module scope, so any node app\n * that imports the asset manager (the core barrel does) gets full `@Asset`\n * behavior; an edge bundle that never imports it gets a clear error on\n * first `@Asset` property access instead of a broken bundle.\n */\n\ntype AssetResolver = (namespace: string, key: string) => unknown\n\nlet impl: AssetResolver | null = null\n\n/** Called by `./assets` at module scope to install the real resolver. */\nexport function _setAssetResolver(fn: AssetResolver): void {\n impl = fn\n}\n\n/** Resolve an asset through the slot — throws when no asset manager is loaded. */\nexport function resolveAssetViaSlot(namespace: string, key: string): unknown {\n if (!impl) {\n throw new Error(\n `@Asset('${namespace}/${key}'): the asset manager is not loaded. ` +\n \"Import it (any import from '@forinda/kickjs' loads it) — note @Asset \" +\n 'reads from the filesystem and is not supported on edge runtimes.',\n )\n }\n return impl(namespace, key)\n}\n","/**\n * Structured framework error with code, cause, and actionable fix hint.\n *\n * The goal is \"the developer who hits this knows what to do next.\" A\n * cryptic `Error('No binding found for: UserService')` becomes a\n * multi-line explanation pointing at the likely cause, the exact code\n * change to apply, and a docs link.\n *\n * `.message` carries the full multi-line plain-text body so Node's\n * default `Error.toString()` and unhandled-exception printing still\n * surface the helpful version. Call {@link formatKickError} to render a\n * colorized version for terminals.\n *\n * Per-error factories live in `kick-errors.ts` — those are the public\n * entry points framework code uses. `KickError` is exported so adopters\n * can build their own structured errors using the same shape.\n */\nexport interface KickErrorInit {\n /** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */\n code: string\n /** One-line headline. */\n summary: string\n /** Multi-line explanation of why this happened. */\n cause?: string\n /** Multi-line actionable fix — show exact code if possible. */\n fix?: string\n /** Absolute URL to the docs page that covers this error. */\n docsUrl?: string\n /** Arbitrary structured fields for log consumers / debug tooling. */\n context?: Record<string, unknown>\n}\n\nexport class KickError extends Error {\n public readonly code: string\n public readonly summary: string\n public readonly cause?: string\n public readonly fix?: string\n public readonly docsUrl?: string\n public readonly context?: Record<string, unknown>\n\n constructor(init: KickErrorInit) {\n super(formatKickError(init, { color: false }))\n this.name = 'KickError'\n this.code = init.code\n this.summary = init.summary\n if (init.cause !== undefined) this.cause = init.cause\n if (init.fix !== undefined) this.fix = init.fix\n if (init.docsUrl !== undefined) this.docsUrl = init.docsUrl\n if (init.context !== undefined) this.context = init.context\n }\n}\n\n// ── ANSI colour helpers ────────────────────────────────────────────────\n\n/**\n * `true` when the runtime can render ANSI escape codes on stderr.\n * Honors `NO_COLOR` (https://no-color.org) and `FORCE_COLOR`.\n */\nfunction ansiEnabled(): boolean {\n if (process.env.NO_COLOR) return false\n if (process.env.FORCE_COLOR) return true\n // Node sets `isTTY` on the writable streams when stdout/stderr is a\n // terminal. KickError output goes to stderr conceptually (it's an\n // error), so we follow that stream's affordances.\n return process.stderr?.isTTY === true\n}\n\n// Use the Unicode-escape form (`\u001b`) rather than the hex-escape (`\\x1b`)\n// for the ANSI ESC byte — both produce the same character, but oxlint's\n// `no-control-character` rule flags the hex form as \"unexpected control\n// character in string literal\". Functionally identical, lint-clean.\nconst ESC = '\u001b['\nconst RESET = `${ESC}0m`\n\nfunction paint(text: string, code: string, enabled: boolean): string {\n return enabled ? `${ESC}${code}m${text}${RESET}` : text\n}\n\nconst c = {\n red: (s: string, enabled: boolean) => paint(s, '31', enabled),\n bold: (s: string, enabled: boolean) => paint(s, '1', enabled),\n dim: (s: string, enabled: boolean) => paint(s, '2', enabled),\n cyan: (s: string, enabled: boolean) => paint(s, '36', enabled),\n blue: (s: string, enabled: boolean) => paint(s, '34', enabled),\n underline: (s: string, enabled: boolean) => paint(s, '4', enabled),\n}\n\n// ── Formatter ─────────────────────────────────────────────────────────\n\nexport interface FormatKickErrorOptions {\n /**\n * Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /\n * `FORCE_COLOR` env vars honoured). Pass `false` for log files,\n * structured loggers, or HTTP response bodies.\n */\n color?: boolean\n}\n\n/**\n * Render a {@link KickErrorInit} (or {@link KickError} instance) into a\n * multi-line human-readable string. Identical layout regardless of\n * colour — the colour flag only toggles ANSI codes.\n */\nexport function formatKickError(\n err: KickErrorInit | KickError,\n options: FormatKickErrorOptions = {},\n): string {\n const color = options.color ?? ansiEnabled()\n const lines: string[] = []\n\n // Headline: `KICK001: No provider for UserService`\n const code = c.bold(c.red(err.code, color), color)\n lines.push(`${code}: ${err.summary}`)\n\n if (err.cause) {\n lines.push('', ` ${c.bold(c.dim('Cause:', color), color)}`)\n for (const line of err.cause.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.fix) {\n lines.push('', ` ${c.bold(c.dim('Fix:', color), color)}`)\n for (const line of err.fix.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.docsUrl) {\n lines.push('', ` ${c.bold(c.dim('Docs:', color), color)}`)\n lines.push(` ${c.underline(c.blue(err.docsUrl, color), color)}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Highlight inline `code spans` in a line of cause/fix text. Anything\n * between backticks gets cyan when colour is enabled; backticks stay\n * in the output so the plain-text rendering still distinguishes\n * literals.\n */\nfunction highlightInline(line: string, color: boolean): string {\n if (!color) return line\n return line.replace(/`([^`]+)`/g, (_, inner: string) => `\\`${c.cyan(inner, true)}\\``)\n}\n","/**\n * Catalog of framework errors with structured cause + fix hints.\n *\n * Each factory function returns a {@link KickError} with a stable\n * `code` (KICK001, KICK002, …), a human-readable summary, an\n * explanation of the likely cause, an actionable fix, and a docs URL.\n *\n * Adding a new error: pick the next free code, add the factory below,\n * call it from the framework site that used to throw a bare `Error`.\n * Keep the public function name descriptive — `noProviderError`,\n * `envValueMissingError` — so call sites grep cleanly.\n *\n * Codes are stable. Reordering or renumbering breaks adopters whose\n * tools key on `err.code`.\n */\nimport { KickError } from './kick-error'\n\nconst DOCS_BASE = 'https://kickjs.app'\n\n// ── DI container ──────────────────────────────────────────────────────\n\n/**\n * KICK001 — No provider registered for a token.\n *\n * Thrown by `Container.resolve()` when no binding can be found for the\n * requested token. The most common cause is forgetting to add the\n * enclosing module to `bootstrap({ modules })`.\n */\nexport function noProviderError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK001',\n summary: `No provider for ${tokenName}`,\n cause: `\\`${tokenName}\\` was requested from the DI container but no binding is registered.\nThis usually means one of:\n • The class is decorated with @Service() / @Repository() / @Controller(),\n but its enclosing module isn't passed to bootstrap({ modules: [...] }).\n • The class isn't decorated at all (decorators register the binding).\n • You're injecting a token (created with createToken()) that nothing\n provides — add a Container.register(TOKEN, ...) call or a module that\n binds it.`,\n fix: `If \\`${tokenName}\\` lives in a module, add the module to bootstrap:\n\n bootstrap({\n modules: [\n UsersModule, // add this\n OtherModule,\n ],\n })\n\nIf it's a custom token, register it explicitly:\n\n const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')\n Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#registering-services`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK002 — REQUEST-scoped binding resolved without a request store\n * provider configured.\n */\nexport function requestScopeMiddlewareMissingError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK002',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" — request scope middleware not mounted`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` but no AsyncLocalStorage frame is wired.\nThe framework's request-scope middleware sets up that frame; without it,\nREQUEST-scoped resolutions have nowhere to cache the per-request instance.`,\n fix: `Add \\`requestScopeMiddleware()\\` to your global middleware pipeline,\nor let the framework auto-mount it by using \\`contextStore: 'auto'\\`\n(the default — only check this if you set it to 'manual' explicitly):\n\n bootstrap({\n modules,\n // contextStore: 'auto', // default; no need to set\n })\n\nIf you set \\`contextStore: 'manual'\\` deliberately (rare), you own the\nALS wrapping — call \\`requestStore.run({...}, () => ...)\\` around the\ncode that resolves the binding.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK003 — REQUEST-scoped binding resolved outside any HTTP request\n * context (no ALS store active).\n */\nexport function requestScopeOutsideRequestError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK003',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" outside an HTTP request`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` and was resolved outside\nany HTTP request context. The request-scope middleware is wired, but\nthe call happened before a request started (e.g. in a top-level\nimport, a constructor, a cron job, a test without setup).`,\n fix: `If the caller is request-scoped (controller, request-scoped service),\nmake sure the call happens inside the request lifecycle, not at module\nload time.\n\nIn tests, wrap setup in an ALS frame manually:\n\n import { requestStore } from '@forinda/kickjs'\n\n requestStore.run(\n { requestId: 'test', instances: new Map(), values: new Map() },\n () => {\n const svc = container.resolve(MyRequestScopedService)\n // ...\n },\n )\n\nIf the caller is a SINGLETON, change \\`${tokenName}\\` to TRANSIENT or\nSINGLETON scope, or inject a factory instead of the instance directly.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK010 — A token was bound normally after its `registerFallback()`\n * singleton had already been resolved.\n *\n * Whatever resolved the fallback still holds that instance; letting the new\n * binding take over would leave two instances that disagree.\n */\nexport function fallbackAlreadyResolvedError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK010',\n summary: `Cannot bind ${tokenName}: its fallback was already resolved`,\n cause: `\\`${tokenName}\\` has a default from \\`container.registerFallback()\\`, and something\nresolved that default before the app bound its own. Code that resolved it holds\nthe fallback instance; the new binding would hand everyone else a different one.`,\n fix: `Bind \\`${tokenName}\\` before anything resolves it — in a module's\n\\`register(container)\\` or a plugin's \\`register()\\`, not later in a request or\nan \\`afterStart\\` hook. If an adapter resolves the token while booting (in\n\\`beforeMount\\`), resolve it lazily instead (in \\`beforeStart\\` or on first use).`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#fallback-bindings`,\n context: { token: tokenName },\n })\n}\n\n// ── Config / env wiring ───────────────────────────────────────────────\n\n/**\n * KICK004 — `@Value('X')` resolved but the env var isn't set and no\n * default was provided.\n *\n * This is the canonical \"you forgot to wire env\" symptom — surfaces\n * when ConfigService can't find the key. The fix usually involves\n * either setting the env var or wiring `loadEnv(envSchema)` at startup.\n */\nexport function envValueMissingError(envKey: string): KickError {\n return new KickError({\n code: 'KICK004',\n summary: `@Value('${envKey}'): environment variable not set and no default provided`,\n cause: `\\`@Value('${envKey}')\\` resolved but the env var isn't present and the\ndecorator didn't declare a default. Possible reasons:\n • The variable is genuinely missing from your environment / .env file.\n • Your \\`src/env.ts\\` calls \\`loadEnv(envSchema)\\` but \\`src/index.ts\\`\n doesn't import \\`./env\\` before \\`bootstrap()\\`. Without that import\n the schema never runs and ConfigService stays empty — \\`@Value\\`\n only finds the var via the \\`process.env\\` fallback.`,\n fix: `Either set the variable in your shell / .env file:\n\n ${envKey}=...\n\nOr add a default at the decorator:\n\n @Value('${envKey}', { default: 'fallback' })\n private value!: string\n\nIf you're using a schema, make sure \\`src/env.ts\\` is imported from\n\\`src/index.ts\\` BEFORE bootstrap runs:\n\n // src/index.ts\n import 'reflect-metadata'\n import './env' // ← this line is required\n import { bootstrap } from '@forinda/kickjs'\n // ...`,\n docsUrl: `${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,\n context: { envKey },\n })\n}\n\n// ── Module setup ──────────────────────────────────────────────────────\n\n/**\n * KICK005 — A module's `routes()` return value declares a mount path\n * but provides neither a `controller` class nor a pre-built `router`.\n */\nexport function moduleRouteMissingControllerError(mountPath: string): KickError {\n return new KickError({\n code: 'KICK005',\n summary: `Module route at ${mountPath} requires either 'controller' or 'router'`,\n cause: `A module's \\`routes()\\` returned an entry for \\`${mountPath}\\` but didn't\nspecify how to build the router. The framework needs either a decorated\ncontroller class (it calls \\`buildRoutes()\\` internally) or a hand-built\nExpress Router.`,\n fix: `Pass \\`controller:\\` for the common case:\n\n routes() {\n return {\n path: '${mountPath}',\n controller: UsersController,\n }\n }\n\nOr pass \\`router:\\` for full control:\n\n routes() {\n return {\n path: '${mountPath}',\n router: myExpressRouter,\n }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { mountPath },\n })\n}\n\n/**\n * KICK006 — Two handlers claim the same HTTP verb + mounted path. The\n * engine would silently dispatch one of them (Express/h3: first wins,\n * Fastify: its own throw), while typegen and the typed client may\n * describe the other — so this fails at boot instead.\n */\nexport function duplicateRouteError(\n method: string,\n path: string,\n owner: string,\n prior: string,\n): KickError {\n return new KickError({\n code: 'KICK006',\n summary: `Duplicate route: ${method} ${path} is registered twice`,\n cause: `\\`${owner}\\` registers \\`${method} ${path}\\`, but that verb + path is\nalready claimed by \\`${prior}\\`. Only one handler can win at dispatch\ntime, and which one depends on the engine — while \\`kick typegen\\` and\nthe typed client may describe the other. Param names are ignored when\ncomparing (\\`/:id\\` and \\`/:taskId\\` are the same route).`,\n fix: `Change one of the two paths, remove the duplicate handler, or mount\nthe second controller under a different module path / version:\n\n routes() {\n return { path: '/tasks', controller: TasksController, version: 2 }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { method, path, owner, prior },\n })\n}\n\n// ── Server ────────────────────────────────────────────────────────────\n\n/**\n * KICK007 — `server.http2` on a runtime that cannot serve HTTP/2. Express 5\n * does not run on Node's HTTP/2 compatibility layer (requests hang and it\n * throws internally), so this fails at boot rather than on the first request.\n */\nexport function http2UnsupportedRuntimeError(runtime: string): KickError {\n return new KickError({\n code: 'KICK007',\n summary: `The ${runtime} runtime cannot serve HTTP/2`,\n cause: `\\`bootstrap({ server: { http2: true } })\\` asks for an HTTP/2 server, but the\n\\`${runtime}\\` runtime does not support Node's HTTP/2 compatibility layer —\nrequests would hang instead of being answered.`,\n fix: `Pick one:\n • Switch to a runtime that serves HTTP/2:\n bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })\n (or h3Runtime()).\n • Drop \\`http2\\` and keep HTTPS over HTTP/1.1: server: { tls }.\n • Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { runtime },\n })\n}\n\n/**\n * KICK008 — `server.http2: true` without `server.tls`, or `http2: 'h2c'` with\n * it. Browsers only speak HTTP/2 over TLS, so cleartext HTTP/2 is its own,\n * explicit setting.\n */\nexport function http2RequiresTlsError(h2cWithTls = false): KickError {\n if (h2cWithTls) {\n return new KickError({\n code: 'KICK008',\n summary: \"server.http2: 'h2c' does not take server.tls\",\n cause: `\\`http2: 'h2c'\\` serves cleartext HTTP/2, but \\`tls\\` was set too.`,\n fix: `Use \\`http2: true\\` to serve HTTP/2 over TLS, or drop \\`tls\\` for cleartext HTTP/2.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n }\n return new KickError({\n code: 'KICK008',\n summary: 'server.http2 requires server.tls',\n cause: `\\`bootstrap({ server: { http2: true } })\\` was set without \\`tls\\`. Browsers only\nnegotiate HTTP/2 over TLS.`,\n fix: `Pass the certificate and key alongside http2:\n\n server: {\n tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },\n http2: true,\n }\n\nBehind a proxy or service mesh that speaks cleartext HTTP/2 to the app (gRPC\nthrough Envoy or Linkerd), use \\`http2: 'h2c'\\` instead. Or remove \\`http2\\` if\nthe proxy sends HTTP/1.1.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n}\n\n/**\n * KICK009 — `server.tls` cannot identify the server. Node starts an HTTPS /\n * HTTP/2 server without a certificate (or with a key that does not match it)\n * and then fails every TLS handshake, so this is checked at boot instead.\n */\nexport function tlsCredentialsError(problem: string): KickError {\n return new KickError({\n code: 'KICK009',\n summary: `server.tls is not usable: ${problem}`,\n cause: `\\`bootstrap({ server: { tls } })\\` was given TLS options the server cannot use:\n${problem}. Node would start anyway and fail every TLS handshake.`,\n fix: `Give the server an identity:\n • \\`key\\` and \\`cert\\` together (PEM, matching each other), or\n • \\`pfx\\` (with \\`passphrase\\` if it is encrypted), or\n • \\`SNICallback\\` / \\`pskCallback\\` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { problem },\n })\n}\n","/**\n * Connects the DI core (`@forinda/kickjs-di`) to\n * the framework: catalogued errors, the logger, and `@Asset` injection.\n * Imported by `./container` and `./decorators`, so every kickjs entry that\n * reaches the container installs them.\n */\nimport { Container, type DiErrorCode } from '@forinda/kickjs-di'\n// Slot indirection, NOT `./assets` — that module's eager node:fs import\n// would poison the edge-safe web entry graph (see asset-resolver-slot.ts).\nimport { resolveAssetViaSlot } from './asset-resolver-slot'\nimport { METADATA } from './interfaces'\nimport {\n envValueMissingError,\n fallbackAlreadyResolvedError,\n noProviderError,\n requestScopeMiddlewareMissingError,\n requestScopeOutsideRequestError,\n} from './kick-errors'\nimport { createLogger } from './logger'\n\nconst CATALOGUE: Record<DiErrorCode, (subject: string) => Error> = {\n KICK001: noProviderError,\n KICK002: requestScopeMiddlewareMissingError,\n KICK003: requestScopeOutsideRequestError,\n KICK004: envValueMissingError,\n KICK010: fallbackAlreadyResolvedError,\n}\n\nContainer.setErrorFactory((code, subject) => CATALOGUE[code](subject))\nContainer.setLogger(createLogger('Container'))\nContainer.definePropertyInjector(METADATA.ASSET, ({ assetKey }: { assetKey: string }) => {\n const slash = assetKey.indexOf('/')\n if (slash === -1) {\n throw new Error(\n `@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`,\n )\n }\n const namespace = assetKey.slice(0, slash)\n const key = assetKey.slice(slash + 1)\n return () => resolveAssetViaSlot(namespace, key)\n})\n"],"mappings":";;;;;;;;;;kIAcA,IAAI,KAA6B,KAGjC,SAAgB,kBAAkB,GAAyB,CACzD,KAAO,EACT,CAGA,SAAgB,oBAAoB,UAAmB,IAAsB,CAC3E,GAAI,CAAC,KACH,MAAU,MACR,WAAW,UAAU,GAAG,IAAI,2KAG9B,EAEF,OAAO,KAAK,UAAW,GAAG,CAC5B,CCCA,IAAa,UAAb,cAA+B,KAAM,CACnC,KACA,QACA,MACA,IACA,QACA,QAEA,YAAY,KAAqB,CAC/B,MAAM,gBAAgB,KAAM,CAAE,MAAO,EAAM,CAAC,CAAC,EAC7C,KAAK,KAAO,YACZ,KAAK,KAAO,KAAK,KACjB,KAAK,QAAU,KAAK,QAChB,KAAK,QAAU,IAAA,KAAW,KAAK,MAAQ,KAAK,OAC5C,KAAK,MAAQ,IAAA,KAAW,KAAK,IAAM,KAAK,KACxC,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,SAChD,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,QACtD,CACF,EAQA,SAAS,aAAuB,CAM9B,OALI,QAAQ,IAAI,SAAiB,GAC7B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,KAAM,UACN,QAAS,6BAA6B,UACtC,MAAO;EACT,QAAQ,yDACN,IAAK,6SAML,QAAS,GAAG,UAAU,uCACtB,QAAS,CAAE,OAAQ,CACrB,CAAC,CACH,CCzTA,MAAM,UAA6D,CACjE,QAAS,gBACT,QAAS,mCACT,QAAS,gCACT,QAAS,qBACT,QAAS,4BACX,EAEA,UAAU,iBAAiB,KAAM,UAAY,UAAU,KAAK,CAAC,OAAO,CAAC,EACrE,UAAU,UAAU,aAAa,WAAW,CAAC,EAC7C,UAAU,uBAAuB,SAAS,OAAQ,CAAE,YAAqC,CACvF,IAAM,MAAQ,SAAS,QAAQ,GAAG,EAClC,GAAI,QAAU,GACZ,MAAU,MACR,WAAW,SAAS,mEACtB,EAEF,IAAM,UAAY,SAAS,MAAM,EAAG,KAAK,EACnC,IAAM,SAAS,MAAM,MAAQ,CAAC,EACpC,UAAa,oBAAoB,UAAW,GAAG,CACjD,CAAC"}
|
|
@@ -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{r as stringifyJson}from"./runtime-
|
|
12
|
-
//# sourceMappingURL=driver-
|
|
11
|
+
import{r as stringifyJson}from"./runtime-BMyg1FYH.mjs";var WebRequestShim=class{method;url;headers;body;params={};query={};requestId;file;files;signal;constructor(request,url){this.method=request.method,this.url=url.pathname+url.search,this.signal=request.signal;let headers={};request.headers.forEach((value,key)=>{headers[key]=value}),this.headers=headers;let query={};for(let key of url.searchParams.keys()){let all=url.searchParams.getAll(key);query[key]=all.length>1?all:all[0]}this.query=query}once(event,listener){return event===`close`&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}on(event,listener){return this.once(event,listener)}};const encoder=new TextEncoder;function toBytes(chunk){return chunk instanceof Uint8Array?chunk:encoder.encode(String(chunk))}const utf8=new TextEncoder;var WebResponseDriver=class{signal;ready;settled=!1;_status=200;headers=new Headers;_headersSent=!1;writer;resolveReady;constructor(signal){this.signal=signal,this.ready=new Promise(resolve=>{this.resolveReady=resolve})}status(code){return this._status=code,this}json(data){return this.headers.has(`content-type`)||this.headers.set(`content-type`,`application/json; charset=utf-8`),this.finish(stringifyJson(data))}send(data){return typeof data==`object`&&data&&!(data instanceof Uint8Array)?this.json(data):this.finish(data)}type(contentType){return this.headers.set(`content-type`,contentType),this}getHeader(name){if(name.toLowerCase()===`set-cookie`){let cookies=this.headers.getSetCookie();return cookies.length>0?cookies:void 0}return this.headers.get(name)??void 0}setHeader(name,value){if(Array.isArray(value)){this.headers.delete(name);for(let v of value)this.headers.append(name,String(v))}else this.headers.set(name,String(value));return this}render(){throw Error(`ctx.render() is not supported on the web runtime (no view engine).`)}writeHead(statusCode,headers){if(this._status=statusCode,headers)for(let[name,value]of Object.entries(headers))this.setHeader(name,value);return this.startStream(),this}flushHeaders(){return this.startStream(),this}write(chunk){return this.startStream(),this.writer.write(toBytes(chunk)).catch(()=>{}),!0}end(data){return this.writer?(data!==void 0&&this.write(data),this.writer.close().catch(()=>{}),this.writer=void 0,this):this.finish(data)}once(event,listener){return event===`close`&&this.signal&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}get headersSent(){return this._headersSent}finish(body){if(this.settled)return this;this.settled=!0,this._headersSent=!0;let bodyAllowed=this._status!==204&&this._status!==304;if(bodyAllowed&&body!=null&&!this.headers.has(`content-length`)){let length=typeof body==`string`?utf8.encode(body).byteLength:body.byteLength;this.headers.set(`content-length`,String(length))}return this.resolveReady(new Response(bodyAllowed?body??null:null,{status:this._status,headers:this.headers})),this}startStream(){if(this.writer||this.settled)return;let{readable,writable}=new TransformStream;this.writer=writable.getWriter(),this.settled=!0,this._headersSent=!0,this.signal?.addEventListener(`abort`,()=>{this.writer?.abort().catch(()=>{}),this.writer=void 0},{once:!0}),this.resolveReady(new Response(readable,{status:this._status,headers:this.headers}))}};export{WebResponseDriver as n,WebRequestShim as t};
|
|
12
|
+
//# sourceMappingURL=driver-B8NPLeRC.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"driver-60Ojtg4A.mjs","names":[],"sources":["../src/http/web/driver.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, type RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\n/** Edge-safe byte length — no `Buffer` on Workers. */\nconst utf8 = new TextEncoder()\n\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(stringifyJson(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n /** What `setHeader` recorded — `Set-Cookie` as its list, like node's `res.getHeader`. */\n getHeader(name: string): string | string[] | undefined {\n if (name.toLowerCase() === 'set-cookie') {\n const cookies = this.headers.getSetCookie()\n return cookies.length > 0 ? cookies : undefined\n }\n return this.headers.get(name) ?? undefined\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n // A buffered body has a known length: say so, as the node runtimes do —\n // no chunked encoding for a small reply, and middleware that decides by\n // size (compression's threshold) can see it.\n if (bodyAllowed && body != null && !this.headers.has('content-length')) {\n const length = typeof body === 'string' ? utf8.encode(body).byteLength : body.byteLength\n this.headers.set('content-length', String(length))\n }\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n"],"mappings":";;;;;;;;;;uDAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,aAAa,KAAK,EAAG,CACzC,IAAM,IAAM,IAAI,aAAa,OAAO,GAAG,EACvC,MAAM,KAAO,IAAI,OAAS,EAAI,IAAM,IAAI,EAC1C,CACA,KAAK,MAAQ,KACf,CAGA,KAAK,MAAe,SAA4B,CAE9C,OADI,QAAU,SAAS,KAAK,OAAO,iBAAiB,QAAS,SAAU,CAAE,KAAM,EAAK,CAAC,EAC9E,IACT,CAGA,GAAG,MAAe,SAA4B,CAC5C,OAAO,KAAK,KAAK,MAAO,QAAQ,CAClC,CACF,EAEA,MAAM,QAAU,IAAI,YAEpB,SAAS,QAAQ,MAA4B,CAE3C,OADI,iBAAiB,WAAmB,MACjC,QAAQ,OAAO,OAAO,KAAK,CAAC,CACrC,CAiBA,MAAM,KAAO,IAAI,YAEjB,IAAa,kBAAb,K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,QAAQ,MAAM,CAAC,CAAC,UAAY,CAAC,CAAC,EACxC,KAAK,OAAS,IAAA,EAChB,EACA,CAAE,KAAM,EAAK,CACf,EACA,KAAK,aAAa,IAAI,SAAS,SAAU,CAAE,OAAQ,KAAK,QAAS,QAAS,KAAK,OAAQ,CAAC,CAAC,CAC3F,CACF"}
|
|
1
|
+
{"version":3,"file":"driver-B8NPLeRC.mjs","names":[],"sources":["../src/http/web/driver.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, type RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\n/** Edge-safe byte length — no `Buffer` on Workers. */\nconst utf8 = new TextEncoder()\n\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(stringifyJson(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n /** What `setHeader` recorded — `Set-Cookie` as its list, like node's `res.getHeader`. */\n getHeader(name: string): string | string[] | undefined {\n if (name.toLowerCase() === 'set-cookie') {\n const cookies = this.headers.getSetCookie()\n return cookies.length > 0 ? cookies : undefined\n }\n return this.headers.get(name) ?? undefined\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n // A buffered body has a known length: say so, as the node runtimes do —\n // no chunked encoding for a small reply, and middleware that decides by\n // size (compression's threshold) can see it.\n if (bodyAllowed && body != null && !this.headers.has('content-length')) {\n const length = typeof body === 'string' ? utf8.encode(body).byteLength : body.byteLength\n this.headers.set('content-length', String(length))\n }\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n"],"mappings":";;;;;;;;;;uDAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,aAAa,KAAK,EAAG,CACzC,IAAM,IAAM,IAAI,aAAa,OAAO,GAAG,EACvC,MAAM,KAAO,IAAI,OAAS,EAAI,IAAM,IAAI,EAC1C,CACA,KAAK,MAAQ,KACf,CAGA,KAAK,MAAe,SAA4B,CAE9C,OADI,QAAU,SAAS,KAAK,OAAO,iBAAiB,QAAS,SAAU,CAAE,KAAM,EAAK,CAAC,EAC9E,IACT,CAGA,GAAG,MAAe,SAA4B,CAC5C,OAAO,KAAK,KAAK,MAAO,QAAQ,CAClC,CACF,EAEA,MAAM,QAAU,IAAI,YAEpB,SAAS,QAAQ,MAA4B,CAE3C,OADI,iBAAiB,WAAmB,MACjC,QAAQ,OAAO,OAAO,KAAK,CAAC,CACrC,CA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e,GAEpB,KAAK,QAAQ,iBACX,YACM,CACJ,KAAU,QAAQ,MAAM,CAAC,CAAC,UAAY,CAAC,CAAC,EACxC,KAAK,OAAS,IAAA,EAChB,EACA,CAAE,KAAM,EAAK,CACf,EACA,KAAK,aAAa,IAAI,SAAS,SAAU,CAAE,OAAQ,KAAK,QAAS,QAAS,KAAK,OAAQ,CAAC,CAAC,CAC3F,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,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as __exportAll}from"./rolldown-runtime-
|
|
12
|
-
//# sourceMappingURL=express-
|
|
11
|
+
import{t as __exportAll}from"./rolldown-runtime-Bdw01CLM.mjs";import{r as buildRouteTable}from"./router-builder-BgoS_JoM.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,d as rejectUnsupportedBody,t as EXPRESS_JSON_TYPES}from"./body-policy-mOP2Y9X_.mjs";import{n as applyHandlerResult}from"./reply-CjA0lh5T.mjs";import{t as EXPRESS_CAPABILITIES}from"./express-lazy-DaYQBnt_.mjs";import{t as RequestContext}from"./context-CvicRipm.mjs";import{n as publishMatchedRoute}from"./runtime-BMyg1FYH.mjs";import{validate}from"./http/middleware/validate.mjs";import{buildUploadMiddleware}from"./http/middleware/upload.mjs";import{t as withPrecompressed}from"./precompressed-Cc2hpa1k.mjs";import express,{Router}from"express";var express_exports=/* @__PURE__ */ __exportAll({buildRoutes:()=>buildRoutes,expressRuntime:()=>expressRuntime,materializeRouter:()=>materializeRouter});function materializeRouter(entries){return expressRouter(entries)}function expressRouter(entries){let router=Router();for(let entry of entries){let method=entry.method.toLowerCase(),handlers=[],refusePrototypeKeys=(req,_res,next)=>next(hasPrototypeKey(req.body)?prototypeKeyError():void 0);handlers.push((req,res,next)=>{publishMatchedRoute(req,entry),refusePrototypeKeys(req,res,next)});let contributorStep=run=>async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{await run(ctx),res.headersSent||next()}catch(err){next(err)}};entry.earlyContributorRunner&&handlers.push(contributorStep(entry.earlyContributorRunner)),entry.meta.validation&&handlers.push(validate(entry.meta.validation,{validationError:entry.validationError})),entry.meta.upload&&handlers.push(buildUploadMiddleware(entry.meta.upload),refusePrototypeKeys);for(let mw of entry.middlewares)handlers.push((req,res,next)=>{let ctx=new RequestContext(req,res,next);Promise.resolve(mw(ctx,next)).catch(next)});entry.contributorRunner&&handlers.push(contributorStep(entry.contributorRunner)),handlers.push(async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{let result=await entry.handler(ctx);res.headersSent||await applyHandlerResult(ctx,result)}catch(err){next(err)}}),router[method](entry.path,...handlers)}return router}function buildRoutes(controllerClass,options={}){return expressRouter(buildRouteTable(controllerClass,options))}function expressRuntime(){return{name:`express`,createApp(options={}){let app=express();return app.disable(`x-powered-by`),app.set(`trust proxy`,options.trustProxy??!1),app},nodeHandler(app){return(req,res,next)=>{next?app(req,res,next):app(req,res)}},mountRoutes(app,table){for(let{mountPath,routes}of table)app.use(mountPath,expressRouter(routes))},useConnect(app,mw,opts={}){opts.path===void 0?app.use(mw):app.use(opts.path,mw)},serveStatic(app,prefix,dir){app.use(prefix,withPrecompressed(dir,express.static(dir)))},setNotFound(app,mw){app.use(mw)},setErrorHandler(app,mw){app.use(mw)},bodyParsers({limit}){return[express.json({limit,type:[...EXPRESS_JSON_TYPES]}),express.urlencoded({extended:!0,limit}),express.text({limit,type:`text/*`}),rejectUnsupportedBody()]},capabilities:EXPRESS_CAPABILITIES}}export{materializeRouter as i,expressRuntime as n,express_exports as r,buildRoutes as t};
|
|
12
|
+
//# sourceMappingURL=express-_PaI8hxC.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express-cGEtQgNP.mjs","names":[],"sources":["../src/http/runtimes/express.ts"],"sourcesContent":["// The default Express runtime — the M1 reference implementation of HttpRuntime.\n//\n// Its route materializer rebuilds the exact `(req, res, next)` handler chain\n// the old `buildRoutes()` produced, so swapping decorators → RouteTable →\n// runtime is behavior-neutral under Express. `buildRoutes()` (the public,\n// Router-returning API) now lives here as a thin shim over `buildRouteTable()`\n// + this materializer.\n\nimport express, {\n Router,\n type Express,\n type Request,\n type Response,\n type NextFunction,\n type RequestHandler,\n} from 'express'\n\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\nimport { RequestContext } from '../context'\nimport { applyHandlerResult } from '../reply'\nimport { validate } from '../middleware/validate'\nimport { publishMatchedRoute } from '../runtime'\nimport { buildUploadMiddleware } from '../middleware/upload'\nimport type { ConnectHandler } from '../connect'\nimport {\n EXPRESS_JSON_TYPES,\n hasPrototypeKey,\n prototypeKeyError,\n rejectUnsupportedBody,\n} from '../body-policy'\nimport { withPrecompressed } from './precompressed'\nimport { EXPRESS_CAPABILITIES } from './express-lazy'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\n\n/**\n * Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.\n * Reproduces the legacy handler ordering precisely: validation → upload →\n * `(ctx, next)` middleware → contributor runner → terminal handler, with\n * `beforeValidation` contributors ahead of validation. Each step\n * constructs its own `RequestContext` over the same `req`/`res` — request-scoped\n * state lives in the AsyncLocalStorage store, not on the ctx instance, so the\n * per-step instances share state exactly as before.\n */\nexport function materializeRouter(entries: RouteEntry[]): ConnectHandler {\n return expressRouter(entries)\n}\n\nfunction expressRouter(entries: RouteEntry[]): Router {\n const router = Router()\n\n for (const entry of entries) {\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n const handlers: RequestHandler[] = []\n\n // Publish the matched route first, so every later step — validation,\n // upload, middleware, contributors, handler — reads the same `ctx.route`.\n // A body key that could rewrite a prototype is refused before any of the\n // app's code sees it — here for the app's body parsers, and again after\n // the upload step for multer's multipart fields.\n const refusePrototypeKeys: RequestHandler = (req, _res, next) =>\n next(hasPrototypeKey(req.body) ? prototypeKeyError() : undefined)\n\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n publishMatchedRoute(req, entry)\n refusePrototypeKeys(req, res, next)\n })\n\n // Context Contributor pipeline (#107) — runs, then advances the chain\n // unless a contributor already answered.\n const contributorStep =\n (run: NonNullable<RouteEntry['contributorRunner']>): RequestHandler =>\n async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n await run(ctx)\n if (!res.headersSent) next()\n } catch (err) {\n next(err)\n }\n }\n\n // `beforeValidation` contributors (#677) — an auth rejection answers 401\n // before a malformed body could answer 422.\n if (entry.earlyContributorRunner) {\n handlers.push(contributorStep(entry.earlyContributorRunner))\n }\n\n // Validation middleware (shared with the standalone validate() export).\n if (entry.meta.validation) {\n handlers.push(validate(entry.meta.validation, { validationError: entry.validationError }))\n }\n\n // @FileUpload — auto-attach upload middleware from metadata.\n if (entry.meta.upload) {\n handlers.push(buildUploadMiddleware(entry.meta.upload), refusePrototypeKeys)\n }\n\n // Class + method middleware — wrapped as Express middleware with error catching.\n for (const mw of entry.middlewares) {\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n Promise.resolve(mw(ctx, next)).catch(next)\n })\n }\n\n if (entry.contributorRunner) {\n handlers.push(contributorStep(entry.contributorRunner))\n }\n\n // Terminal handler.\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send the returned payload\n // when the handler wrote nothing. `undefined` keeps prior behavior.\n if (!res.headersSent) await applyHandlerResult(ctx, result)\n } catch (err) {\n next(err)\n }\n })\n ;(router as any)[method](entry.path, ...handlers)\n }\n\n return router\n}\n\n/**\n * Build an Express Router from a controller class decorated with @Get, @Post,\n * etc. The public, back-compatible entry point: a thin shim over\n * {@link buildRouteTable} + {@link materializeRouter}. Returns an\n * `express.Router` exactly as before — modules pass it to `app.use(path, router)`.\n *\n * @see buildRouteTable for the engine-neutral route-table form.\n */\nexport function buildRoutes(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): ConnectHandler {\n return expressRouter(buildRouteTable(controllerClass, options))\n}\n\n/**\n * The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;\n * apps that pass no `runtime` get this and behave exactly as before.\n */\nexport function expressRuntime(): HttpRuntime {\n const runtime: HttpRuntime<Express> = {\n name: 'express',\n\n createApp(options: RuntimeAppOptions = {}): Express {\n const app = express()\n // Engine hardening + config the Application used to apply directly.\n app.disable('x-powered-by')\n app.set('trust proxy', options.trustProxy ?? false)\n return app\n },\n\n nodeHandler(app) {\n return (req, res, next) => {\n if (next) {\n ;(app as any)(req, res, next)\n } else {\n ;(app as any)(req, res)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n app.use(mountPath, expressRouter(routes))\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts: UseConnectOptions = {}) {\n if (opts.path !== undefined) {\n ;(app as any).use(opts.path, mw)\n } else {\n ;(app as any).use(mw)\n }\n },\n\n serveStatic(app, prefix, dir) {\n app.use(prefix, withPrecompressed(dir, express.static(dir) as ConnectHandler))\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n bodyParsers({ limit }) {\n return [\n // EXPRESS_JSON_TYPES, not the default: `express.json()` matches the\n // exact string `application/json`, so `application/merge-patch+json`\n // arrived unparsed while Fastify answered 415 and h3 parsed it (#590).\n express.json({ limit, type: [...EXPRESS_JSON_TYPES] }),\n // Forms and text were parsed by h3 and rejected by Fastify; on Express\n // they reached the handler as `undefined`, because the engine parsed\n // only what its middleware list happened to cover.\n express.urlencoded({ extended: true, limit }),\n express.text({ limit, type: 'text/*' }),\n // After the parsers: Express leaves an unmatched type as `undefined`,\n // which is indistinguishable from \"no body sent\". This restores the\n // difference so an unsupported type is answered rather than ignored.\n rejectUnsupportedBody(),\n ]\n },\n\n capabilities: EXPRESS_CAPABILITIES,\n }\n return runtime as HttpRuntime\n}\n"],"mappings":";;;;;;;;;;22BAkDA,SAAgB,kBAAkB,QAAuC,CACvE,OAAO,cAAc,OAAO,CAC9B,CAEA,SAAS,cAAc,QAA+B,CACpD,IAAM,OAAS,OAAO,EAEtB,IAAK,IAAM,SAAS,QAAS,CAC3B,IAAM,OAAS,MAAM,OAAO,YAAY,EAClC,SAA6B,CAAC,EAO9B,qBAAuC,IAAK,KAAM,OACtD,KAAK,gBAAgB,IAAI,IAAI,EAAI,kBAAkB,EAAI,IAAA,EAAS,EAElE,SAAS,MAAM,IAAc,IAAe,OAAuB,CACjE,oBAAoB,IAAK,KAAK,EAC9B,oBAAoB,IAAK,IAAK,IAAI,CACpC,CAAC,EAID,IAAM,gBACH,KACD,MAAO,IAAc,IAAe,OAAuB,CACzD,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,IAAI,EAC7C,GAAI,CACF,MAAM,IAAI,GAAG,EACR,IAAI,aAAa,KAAK,CAC7B,OAAS,IAAK,CACZ,KAAK,GAAG,CACV,CACF,EAIE,MAAM,wBACR,SAAS,KAAK,gBAAgB,MAAM,sBAAsB,CAAC,EAIzD,MAAM,KAAK,YACb,SAAS,KAAK,SAAS,MAAM,KAAK,WAAY,CAAE,gBAAiB,MAAM,eAAgB,CAAC,CAAC,EAIvF,MAAM,KAAK,QACb,SAAS,KAAK,sBAAsB,MAAM,KAAK,MAAM,EAAG,mBAAmB,EAI7E,IAAK,IAAM,MAAM,MAAM,YACrB,SAAS,MAAM,IAAc,IAAe,OAAuB,CACjE,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,IAAI,EA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A,YAAY,IAAK,GAAuB,CACrC,IAAa,IAAI,EAAE,CACtB,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAAa,IAAI,EAAE,CACtB,EAEA,YAAY,CAAE,OAAS,CACrB,MAAO,CAIL,QAAQ,KAAK,CAAE,MAAO,KAAM,CAAC,GAAG,kBAAkB,CAAE,CAAC,EAIrD,QAAQ,WAAW,CAAE,SAAU,GAAM,KAAM,CAAC,EAC5C,QAAQ,KAAK,CAAE,MAAO,KAAM,QAAS,CAAC,EAItC,sBAAsB,CACxB,CACF,EAEA,aAAc,oBAEH,CACf"}
|
|
1
|
+
{"version":3,"file":"express-_PaI8hxC.mjs","names":[],"sources":["../src/http/runtimes/express.ts"],"sourcesContent":["// The default Express runtime — the M1 reference implementation of HttpRuntime.\n//\n// Its route materializer rebuilds the exact `(req, res, next)` handler chain\n// the old `buildRoutes()` produced, so swapping decorators → RouteTable →\n// runtime is behavior-neutral under Express. `buildRoutes()` (the public,\n// Router-returning API) now lives here as a thin shim over `buildRouteTable()`\n// + this materializer.\n\nimport express, {\n Router,\n type Express,\n type Request,\n type Response,\n type NextFunction,\n type RequestHandler,\n} from 'express'\n\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\nimport { RequestContext } from '../context'\nimport { applyHandlerResult } from '../reply'\nimport { validate } from '../middleware/validate'\nimport { publishMatchedRoute } from '../runtime'\nimport { buildUploadMiddleware } from '../middleware/upload'\nimport type { ConnectHandler } from '../connect'\nimport {\n EXPRESS_JSON_TYPES,\n hasPrototypeKey,\n prototypeKeyError,\n rejectUnsupportedBody,\n} from '../body-policy'\nimport { withPrecompressed } from './precompressed'\nimport { EXPRESS_CAPABILITIES } from './express-lazy'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\n\n/**\n * Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.\n * Reproduces the legacy handler ordering precisely: validation → upload →\n * `(ctx, next)` middleware → contributor runner → terminal handler, with\n * `beforeValidation` contributors ahead of validation. Each step\n * constructs its own `RequestContext` over the same `req`/`res` — request-scoped\n * state lives in the AsyncLocalStorage store, not on the ctx instance, so the\n * per-step instances share state exactly as before.\n */\nexport function materializeRouter(entries: RouteEntry[]): ConnectHandler {\n return expressRouter(entries)\n}\n\nfunction expressRouter(entries: RouteEntry[]): Router {\n const router = Router()\n\n for (const entry of entries) {\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n const handlers: RequestHandler[] = []\n\n // Publish the matched route first, so every later step — validation,\n // upload, middleware, contributors, handler — reads the same `ctx.route`.\n // A body key that could rewrite a prototype is refused before any of the\n // app's code sees it — here for the app's body parsers, and again after\n // the upload step for multer's multipart fields.\n const refusePrototypeKeys: RequestHandler = (req, _res, next) =>\n next(hasPrototypeKey(req.body) ? prototypeKeyError() : undefined)\n\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n publishMatchedRoute(req, entry)\n refusePrototypeKeys(req, res, next)\n })\n\n // Context Contributor pipeline (#107) — runs, then advances the chain\n // unless a contributor already answered.\n const contributorStep =\n (run: NonNullable<RouteEntry['contributorRunner']>): RequestHandler =>\n async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n await run(ctx)\n if (!res.headersSent) next()\n } catch (err) {\n next(err)\n }\n }\n\n // `beforeValidation` contributors (#677) — an auth rejection answers 401\n // before a malformed body could answer 422.\n if (entry.earlyContributorRunner) {\n handlers.push(contributorStep(entry.earlyContributorRunner))\n }\n\n // Validation middleware (shared with the standalone validate() export).\n if (entry.meta.validation) {\n handlers.push(validate(entry.meta.validation, { validationError: entry.validationError }))\n }\n\n // @FileUpload — auto-attach upload middleware from metadata.\n if (entry.meta.upload) {\n handlers.push(buildUploadMiddleware(entry.meta.upload), refusePrototypeKeys)\n }\n\n // Class + method middleware — wrapped as Express middleware with error catching.\n for (const mw of entry.middlewares) {\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n Promise.resolve(mw(ctx, next)).catch(next)\n })\n }\n\n if (entry.contributorRunner) {\n handlers.push(contributorStep(entry.contributorRunner))\n }\n\n // Terminal handler.\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send the returned payload\n // when the handler wrote nothing. `undefined` keeps prior behavior.\n if (!res.headersSent) await applyHandlerResult(ctx, result)\n } catch (err) {\n next(err)\n }\n })\n ;(router as any)[method](entry.path, ...handlers)\n }\n\n return router\n}\n\n/**\n * Build an Express Router from a controller class decorated with @Get, @Post,\n * etc. The public, back-compatible entry point: a thin shim over\n * {@link buildRouteTable} + {@link materializeRouter}. Returns an\n * `express.Router` exactly as before — modules pass it to `app.use(path, router)`.\n *\n * @see buildRouteTable for the engine-neutral route-table form.\n */\nexport function buildRoutes(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): ConnectHandler {\n return expressRouter(buildRouteTable(controllerClass, options))\n}\n\n/**\n * The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;\n * apps that pass no `runtime` get this and behave exactly as before.\n */\nexport function expressRuntime(): HttpRuntime {\n const runtime: HttpRuntime<Express> = {\n name: 'express',\n\n createApp(options: RuntimeAppOptions = {}): Express {\n const app = express()\n // Engine hardening + config the Application used to apply directly.\n app.disable('x-powered-by')\n app.set('trust proxy', options.trustProxy ?? false)\n return app\n },\n\n nodeHandler(app) {\n return (req, res, next) => {\n if (next) {\n ;(app as any)(req, res, next)\n } else {\n ;(app as any)(req, res)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n app.use(mountPath, expressRouter(routes))\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts: UseConnectOptions = {}) {\n if (opts.path !== undefined) {\n ;(app as any).use(opts.path, mw)\n } else {\n ;(app as any).use(mw)\n }\n },\n\n serveStatic(app, prefix, dir) {\n app.use(prefix, withPrecompressed(dir, express.static(dir) as ConnectHandler))\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n bodyParsers({ limit }) {\n return [\n // EXPRESS_JSON_TYPES, not the default: `express.json()` matches the\n // exact string `application/json`, so `application/merge-patch+json`\n // arrived unparsed while Fastify answered 415 and h3 parsed it (#590).\n express.json({ limit, type: [...EXPRESS_JSON_TYPES] }),\n // Forms and text were parsed by h3 and rejected by Fastify; on Express\n // they reached the handler as `undefined`, because the engine parsed\n // only what its middleware list happened to cover.\n express.urlencoded({ extended: true, limit }),\n express.text({ limit, type: 'text/*' }),\n // After the parsers: Express leaves an unmatched type as `undefined`,\n // which is indistinguishable from \"no body sent\". This restores the\n // difference so an unsupported type is answered rather than ignored.\n rejectUnsupportedBody(),\n ]\n },\n\n capabilities: EXPRESS_CAPABILITIES,\n }\n return runtime as HttpRuntime\n}\n"],"mappings":";;;;;;;;;;22BAkDA,SAAgB,kBAAkB,QAAuC,CACvE,OAAO,cAAc,OAAO,CAC9B,CAEA,SAAS,cAAc,QAA+B,CACpD,IAAM,OAAS,OAAO,EAEtB,IAAK,IAAM,SAAS,QAAS,CAC3B,IAAM,OAAS,MAAM,OAAO,YAAY,EAClC,SAA6B,CAAC,EAO9B,qBAAuC,IAAK,KAAM,OACtD,KAAK,gBAAgB,IAAI,IAAI,EAAI,kBAAkB,EAAI,IAAA,EAAS,EAElE,SAAS,MAAM,IAAc,IAAe,OAAuB,CACjE,oBAAoB,IAAK,KAAK,EAC9B,oBAAoB,IAAK,IAAK,IAAI,CACpC,CAAC,EAID,IAAM,gBACH,KACD,MAAO,IAAc,IAAe,OAAuB,CACzD,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,IAAI,EAC7C,GAAI,CACF,MAAM,IAAI,GAAG,EACR,IAAI,aAAa,KAAK,CAC7B,OAAS,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,IAAK,GAAG,CAE1B,CACF,EAEA,YAAY,IAAK,MAAmB,CAClC,IAAK,GAAM,CAAE,UAAW,UAAY,MAClC,IAAI,IAAI,UAAW,cAAc,MAAM,CAAC,CAE5C,EAEA,WAAW,IAAK,GAAuB,KAA0B,CAAC,EAAG,CAC/D,KAAK,OAAS,IAAA,GAGf,IAAa,IAAI,EAAE,EAFnB,IAAa,IAAI,KAAK,KAAM,EAAE,CAInC,EAEA,YAAY,IAAK,OAAQ,IAAK,CAC5B,IAAI,IAAI,OAAQ,kBAAkB,IAAK,QAAQ,OAAO,GAAG,CAAmB,CAAC,CAC/E,EAEA,YAAY,IAAK,GAAuB,CACrC,IAAa,IAAI,EAAE,CACtB,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAAa,IAAI,EAAE,CACtB,EAEA,YAAY,CAAE,OAAS,CACrB,MAAO,CAIL,QAAQ,KAAK,CAAE,MAAO,KAAM,CAAC,GAAG,kBAAkB,CAAE,CAAC,EAIrD,QAAQ,WAAW,CAAE,SAAU,GAAM,KAAM,CAAC,EAC5C,QAAQ,KAAK,CAAE,MAAO,KAAM,QAAS,CAAC,EAItC,sBAAsB,CACxB,CACF,EAEA,aAAc,oBAEH,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,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{r as buildRouteTable}from"./router-builder-
|
|
12
|
-
//# sourceMappingURL=express-lazy-
|
|
11
|
+
import{r as buildRouteTable}from"./router-builder-BgoS_JoM.mjs";const EXPRESS_CAPABILITIES={render:!0,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!1,http2:!1};let loaded,loading,loadError;function loadExpress(){return loading??=import(`./express-_PaI8hxC.mjs`).then(n=>n.r).then(mod=>loaded=mod,err=>{throw loadError=Error("kickjs: the Express runtime needs the 'express' package — install it, or pass another runtime to bootstrap(): `runtime: fastifyRuntime()` from '@forinda/kickjs/fastify', or `h3Runtime()` from '@forinda/kickjs/h3'.",{cause:err})}),loading}async function settleExpressLoad(){await loading?.catch(()=>{})}async function expressBodyParsers(limit){return(await loadExpress()).expressRuntime().bodyParsers?.({limit})??[]}function notLoaded(what){return/* @__PURE__ */ Error(`kickjs: ${what} is Express-only and runs once the Express runtime has loaded — in an app running it. Outside one, import it from '@forinda/kickjs/express'.`)}function expressRuntime(){loadExpress().catch(()=>{});let real,engine=()=>(real??=loaded?.expressRuntime())??fail(),fail=()=>{throw loadError??notLoaded(`expressRuntime() used before load()`)};return{name:`express`,capabilities:EXPRESS_CAPABILITIES,async load(){await loadExpress(),engine()},createApp:options=>engine().createApp(options),nodeHandler:app=>engine().nodeHandler(app),mountRoutes:(app,table)=>engine().mountRoutes(app,table),useConnect:(app,mw,opts)=>engine().useConnect(app,mw,opts),serveStatic:(app,prefix,dir)=>engine().serveStatic(app,prefix,dir),setNotFound:(app,mw)=>engine().setNotFound(app,mw),setErrorHandler:(app,mw)=>engine().setErrorHandler(app,mw),close:app=>engine().close?.(app),bodyParsers:options=>engine().bodyParsers?.(options)??[]}}function materializeRouter(entries){let router;return(req,res,next)=>{if(!loaded)throw notLoaded(`materializeRouter()`);return router??=loaded.materializeRouter(entries),router(req,res,next)}}function buildRoutes(controllerClass,options={}){return materializeRouter(buildRouteTable(controllerClass,options))}export{materializeRouter as a,expressRuntime as i,buildRoutes as n,settleExpressLoad as o,expressBodyParsers as r,EXPRESS_CAPABILITIES as t};
|
|
12
|
+
//# sourceMappingURL=express-lazy-DaYQBnt_.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express-lazy-
|
|
1
|
+
{"version":3,"file":"express-lazy-DaYQBnt_.mjs","names":[],"sources":["../src/http/runtimes/express-lazy.ts"],"sourcesContent":["/**\n * The Express runtime as the root entry exports it: `expressRuntime()`,\n * `buildRoutes()` and `materializeRouter()` without importing `express` when\n * `@forinda/kickjs` loads, so an app on Fastify or h3 runs without it installed.\n * The engine loads in `HttpRuntime.load()`, which the Application awaits before\n * creating its app — through a literal dynamic `import()`, which bundlers\n * follow, so `kick build:netlify|vercel` still inlines Express.\n *\n * `@forinda/kickjs/express` exports the same three, loaded eagerly.\n */\nimport type { ConnectHandler } from '../connect'\nimport type { HttpRuntime, RouteEntry, RuntimeCapabilities } from '../runtime'\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\n\ntype ExpressModule = typeof import('./express')\n\n/** What the Express runtime supports — read before the engine loads (`start()` checks `http2`). */\nexport const EXPRESS_CAPABILITIES: RuntimeCapabilities = {\n render: true,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: false,\n http2: false,\n}\n\nlet loaded: ExpressModule | undefined\nlet loading: Promise<ExpressModule> | undefined\n/** Why the load failed — thrown where Express is used, not at every app's setup. */\nlet loadError: Error | undefined\n\n/** Start loading Express once; every caller shares the one load. */\nfunction loadExpress(): Promise<ExpressModule> {\n loading ??= import('./express').then(\n (mod) => (loaded = mod),\n (err: unknown) => {\n throw (loadError = new Error(\n \"kickjs: the Express runtime needs the 'express' package — install it, or pass another \" +\n \"runtime to bootstrap(): `runtime: fastifyRuntime()` from '@forinda/kickjs/fastify', \" +\n \"or `h3Runtime()` from '@forinda/kickjs/h3'.\",\n { cause: err },\n ))\n },\n )\n return loading\n}\n\n/**\n * Wait for an Express load something already started — `expressRuntime()`\n * starts one when called, so a custom runtime wrapping it (and calling its\n * methods without forwarding `load()`) still finds Express there by setup.\n * Never throws: an app on another runtime mustn't fail because something else\n * asked for Express; a failed load surfaces where Express is used.\n */\nexport async function settleExpressLoad(): Promise<void> {\n await loading?.catch(() => {})\n}\n\n/**\n * Express's body parsers, for a runtime that neither parses bodies itself nor\n * supplies `bodyParsers()` — what the Application mounted before runtimes\n * could supply their own.\n */\nexport async function expressBodyParsers(limit: string | number) {\n const mod = await loadExpress()\n return mod.expressRuntime().bodyParsers?.({ limit }) ?? []\n}\n\nfunction notLoaded(what: string): Error {\n return new Error(\n `kickjs: ${what} is Express-only and runs once the Express runtime has loaded — ` +\n \"in an app running it. Outside one, import it from '@forinda/kickjs/express'.\",\n )\n}\n\n/** The default HTTP runtime; Express loads on the Application's first setup. */\nexport function expressRuntime(): HttpRuntime {\n // Started now and awaited at setup; a failure surfaces there, not as an\n // unhandled rejection here.\n loadExpress().catch(() => {})\n let real: HttpRuntime | undefined\n const engine = (): HttpRuntime => real ?? (real = loaded?.expressRuntime()) ?? fail()\n const fail = (): never => {\n throw loadError ?? notLoaded('expressRuntime() used before load()')\n }\n return {\n name: 'express',\n capabilities: EXPRESS_CAPABILITIES,\n async load() {\n await loadExpress()\n engine()\n },\n createApp: (options) => engine().createApp(options),\n nodeHandler: (app) => engine().nodeHandler(app),\n mountRoutes: (app, table) => engine().mountRoutes(app, table),\n useConnect: (app, mw, opts) => engine().useConnect(app, mw, opts),\n serveStatic: (app, prefix, dir) => engine().serveStatic(app, prefix, dir),\n setNotFound: (app, mw) => engine().setNotFound(app, mw),\n setErrorHandler: (app, mw) => engine().setErrorHandler(app, mw),\n close: (app) => engine().close?.(app),\n bodyParsers: (options) => engine().bodyParsers?.(options) ?? [],\n }\n}\n\n/**\n * Materialize route entries onto an Express `Router`, built on the first\n * request (Express has loaded by then in an app running it).\n */\nexport function materializeRouter(entries: RouteEntry[]): ConnectHandler {\n let router: ConnectHandler | undefined\n return (req, res, next) => {\n if (!loaded) throw notLoaded('materializeRouter()')\n router ??= loaded.materializeRouter(entries)\n return router(req, res, next)\n }\n}\n\n/**\n * A controller's routes as an Express `Router`. The route table is built now,\n * so a contributor cycle or a missing dependency still fails at boot; the\n * router on the first request.\n */\nexport function buildRoutes(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): ConnectHandler {\n return materializeRouter(buildRouteTable(controllerClass, options))\n}\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,EACtD,iBAAkB,IAAK,KAAO,OAAO,CAAC,CAAC,gBAAgB,IAAK,EAAE,EAC9D,MAAQ,KAAQ,OAAO,CAAC,CAAC,QAAQ,GAAG,EACpC,YAAc,SAAY,OAAO,CAAC,CAAC,cAAc,OAAO,GAAK,CAAC,CAChE,CACF,CAMA,SAAgB,kBAAkB,QAAuC,CACvE,IAAI,OACJ,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAI,CAAC,OAAQ,MAAM,UAAU,qBAAqB,EAElD,MADA,UAAW,OAAO,kBAAkB,OAAO,EACpC,OAAO,IAAK,IAAK,IAAI,CAC9B,CACF,CAOA,SAAgB,YACd,gBACA,QAA8B,CAAC,EACf,CAChB,OAAO,kBAAkB,gBAAgB,gBAAiB,OAAO,CAAC,CACpE"}
|
|
@@ -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{HttpException}from"./core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,i as formFields,l as readBodyBytes,o as parseByteSize,p as unsupportedMediaTypeError,r as classifyMediaType,s as parseForm,u as readBodyText}from"./body-policy-
|
|
12
|
-
//# sourceMappingURL=handler-
|
|
11
|
+
import{HttpException}from"./core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,i as formFields,l as readBodyBytes,o as parseByteSize,p as unsupportedMediaTypeError,r as classifyMediaType,s as parseForm,u as readBodyText}from"./body-policy-mOP2Y9X_.mjs";import{f as requestStore}from"./view-renderer-BvDWb7GV.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{n as disposeRequestStore,t as createRequestStore}from"./request-scope-BjBvqXuj.mjs";import{n as applyHandlerResult}from"./reply-CjA0lh5T.mjs";import{t as RequestContext}from"./context-CvicRipm.mjs";import{n as publishMatchedRoute}from"./runtime-BMyg1FYH.mjs";import{validate}from"./http/middleware/validate.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"./driver-B8NPLeRC.mjs";import{c as tooManyFiles,l as uploadLimits,r as applyUploadConfig}from"./upload-config-C_SlwFq0.mjs";const NOOP_NEXT=()=>{},BODY_METHODS=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]),builtInError=errorHandler(),builtInNotFound=notFoundHandler();function decodeParams(params){let decoded={};for(let key in params){let value=params[key];decoded[key]=value.includes(`%`)?decodeURIComponent(value):value}return decoded}function readThrough(shim,carry){return new Proxy(shim,{get(target,prop,receiver){let own=Reflect.get(target,prop,receiver);return own===void 0?Reflect.get(carry,prop,carry):own},has(target,prop){return Reflect.has(target,prop)||Reflect.has(carry,prop)}})}function compileWebRoute(entry,hooks,options={}){let bodyLimit=options.bodyLimit??parseByteSize(`1mb`),validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0,upload=entry.meta.upload&&entry.meta.upload.mode!==`none`?entry.meta.upload:null;return async({request,url,params,carry})=>{let shim=new WebRequestShim(request,url),req=carry?readThrough(shim,carry):shim,bodyError;try{req.params=decodeParams(params)}catch{req.params=params,bodyError=HttpException.badRequest(`Malformed URL parameter`)}if(upload){let limits=uploadLimits(upload),form;try{let bytes=await readBodyBytes(request,limits.total),type=request.headers.get(`content-type`)??``;form=await new Response(bytes,{headers:{"content-type":type}}).formData().catch(()=>void 0)}catch(err){err instanceof HttpException&&(bodyError=err)}if(form){let rawParts=[],fields=[];for(let[name,value]of form.entries())typeof value==`string`?fields.push([name,value]):rawParts.push({fieldname:name,filename:value.name??``,mimetype:value.type||`application/octet-stream`,buffer:typeof Buffer==`function`?Buffer.from(await value.arrayBuffer()):new Uint8Array(await value.arrayBuffer())});if(req.body=formFields(fields),rawParts.length>limits.files)bodyError=tooManyFiles(limits.files);else try{let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);req.file=file,req.files=files}catch(err){bodyError=err}}}else if(BODY_METHODS.has(request.method)){let raw=``;try{raw=await readBodyText(request,bodyLimit)}catch(err){err instanceof HttpException&&(bodyError=err)}let kind=classifyMediaType(req.headers[`content-type`]);if(raw!==``&&kind===`unsupported`)bodyError=unsupportedMediaTypeError(req.headers[`content-type`]);else if(raw!==``&&kind!==`multipart`){if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){bodyError=HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`)}else req.body=kind===`urlencoded`?parseForm(raw):raw}}!bodyError&&hasPrototypeKey(req.body)&&(bodyError=prototypeKeyError());let store=createRequestStore(req.requestId||req.headers[`x-request-id`]);req.requestId=store.requestId;let driver=new WebResponseDriver(request.signal);driver.setHeader(`x-request-id`,store.requestId),publishMatchedRoute(req,entry),carry&&publishMatchedRoute(carry,entry);let pipeline=requestStore.run(store,async()=>{if(bodyError)throw bodyError;let ctx=new RequestContext(req,driver,NOOP_NEXT,driver);if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),driver.settled))return;validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||driver.settled)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),driver.settled)return;let result=await entry.handler(ctx);driver.settled||await applyHandlerResult(ctx,result)});try{try{await Promise.race([pipeline,driver.ready])}catch(err){driver.settled||await requestStore.run(store,async()=>{hooks?.onError&&await hooks.onError(err,req,driver),driver.settled||await builtInError(err,req,driver,NOOP_NEXT)})}return driver.settled||builtInNotFound(req,driver,NOOP_NEXT),await driver.ready}finally{Promise.resolve(pipeline).catch(()=>{}).then(()=>disposeRequestStore(store))}}}async function headFromGet(response){let res=await response;return res.body?.cancel().catch(()=>{}),new Response(null,{status:res.status,statusText:res.statusText,headers:res.headers})}export{headFromGet as n,readThrough as r,compileWebRoute as t};
|
|
12
|
+
//# sourceMappingURL=handler-B5jN9Wms.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler-BDivc8AT.mjs","names":[],"sources":["../src/http/web/handler.ts"],"sourcesContent":["// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n readBodyBytes,\n readBodyText,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport {\n applyUploadConfig,\n tooManyFiles,\n uploadLimits,\n type RawUploadPart,\n} from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n // Bounded before anything is parsed: the route's file budget plus room\n // for fields. Past it is a 413, held like a parse failure below.\n const limits = uploadLimits(upload)\n let form: FormData | undefined\n try {\n const bytes = await readBodyBytes(request, limits.total)\n const type = request.headers.get('content-type') ?? ''\n form = await new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], {\n headers: { 'content-type': type },\n })\n .formData()\n .catch(() => undefined)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields.push([name, value])\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n req.body = formFields(fields)\n // A refused type (415), an oversized file or too many (413) is held like\n // a parse failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n if (rawParts.length > limits.files) {\n bodyError = tooManyFiles(limits.files)\n } else {\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\n }\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (!bodyError && hasPrototypeKey(req.body)) bodyError = prototypeKeyError()\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n // Inside the request's store: an error page renders with the same\n // context and REQUEST-scoped services the route had.\n if (!driver.settled) {\n await requestStore.run(store, async () => {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n })\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n\n/**\n * HEAD for a GET route: run the route and answer with its status and\n * headers, without the body — what Express and Fastify do for every GET.\n */\nexport async function headFromGet(response: Promise<Response> | Response): Promise<Response> {\n const res = await response\n // A streamed GET (SSE) would otherwise keep producing for nobody.\n res.body?.cancel().catch(() => {})\n return new Response(null, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n })\n}\n"],"mappings":";;;;;;;;;;04BAkCA,MAAM,cAAwB,CAAC,EACzB,6BAAe,IAAI,IAAI,CAAC,OAAQ,MAAO,QAAS,QAAQ,CAAC,EA6BzD,aAAe,aAAa,EAC5B,gBAAkB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AAK,CAGP,OAAO,SACV,MAAM,aAAa,IAAI,MAAO,SAAY,CACpC,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAK,IAAK,MAAM,EACnD,OAAO,SAAS,MAAM,aAAa,IAAK,IAAK,OAAQ,SAAS,CACrE,CAAC,CAEL,CAKA,OAJK,OAAO,SAEV,gBAAgB,IAAK,OAAQ,SAAS,EAEjC,MAAM,OAAO,KACtB,QAAU,CAIR,QAAa,QAAQ,QAAQ,CAAC,CAC3B,UAAY,CAAC,CAAC,CAAC,CACf,SAAW,oBAAoB,KAAK,CAAC,CAC1C,CACF,CACF,CAMA,eAAsB,YAAY,SAA2D,CAC3F,IAAM,IAAM,MAAM,SAGlB,OADA,IAAI,MAAM,OAAO,CAAC,CAAC,UAAY,CAAC,CAAC,EAC1B,IAAI,SAAS,KAAM,CACxB,OAAQ,IAAI,OACZ,WAAY,IAAI,WAChB,QAAS,IAAI,OACf,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"handler-B5jN9Wms.mjs","names":[],"sources":["../src/http/web/handler.ts"],"sourcesContent":["// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n readBodyBytes,\n readBodyText,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport {\n applyUploadConfig,\n tooManyFiles,\n uploadLimits,\n type RawUploadPart,\n} from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n // Bounded before anything is parsed: the route's file budget plus room\n // for fields. Past it is a 413, held like a parse failure below.\n const limits = uploadLimits(upload)\n let form: FormData | undefined\n try {\n const bytes = await readBodyBytes(request, limits.total)\n const type = request.headers.get('content-type') ?? ''\n form = await new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], {\n headers: { 'content-type': type },\n })\n .formData()\n .catch(() => undefined)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields.push([name, value])\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n req.body = formFields(fields)\n // A refused type (415), an oversized file or too many (413) is held like\n // a parse failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n if (rawParts.length > limits.files) {\n bodyError = tooManyFiles(limits.files)\n } else {\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\n }\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (!bodyError && hasPrototypeKey(req.body)) bodyError = prototypeKeyError()\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n // Inside the request's store: an error page renders with the same\n // context and REQUEST-scoped services the route had.\n if (!driver.settled) {\n await requestStore.run(store, async () => {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n })\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n\n/**\n * HEAD for a GET route: run the route and answer with its status and\n * headers, without the body — what Express and Fastify do for every GET.\n */\nexport async function headFromGet(response: Promise<Response> | Response): Promise<Response> {\n const res = await response\n // A streamed GET (SSE) would otherwise keep producing for nobody.\n res.body?.cancel().catch(() => {})\n return new Response(null, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n })\n}\n"],"mappings":";;;;;;;;;;04BAkCA,MAAM,cAAwB,CAAC,EACzB,6BAAe,IAAI,IAAI,CAAC,OAAQ,MAAO,QAAS,QAAQ,CAAC,EA6BzD,aAAe,aAAa,EAC5B,gBAAkB,gBAAgB,EAExC,SAAS,aAAa,OAAwD,CAC5E,IAAM,QAAkC,CAAC,EACzC,IAAK,IAAM,OAAO,OAAQ,CACxB,IAAM,MAAQ,OAAO,KACrB,QAAQ,KAAO,MAAM,SAAS,GAAG,EAAI,mBAAmB,KAAK,EAAI,KACnE,CACA,OAAO,OACT,CAYA,SAAgB,YAAY,KAAsB,MAA+B,CAC/E,OAAO,IAAI,MAAM,KAAM,CACrB,IAAI,OAAQ,KAAM,SAAU,CAC1B,IAAM,IAAM,QAAQ,IAAI,OAAQ,KAAM,QAAQ,EAC9C,OAAO,MAAQ,IAAA,GAAkB,QAAQ,IAAI,MAAO,KAAM,KAAK,EAApC,GAC7B,EACA,IAAI,OAAQ,KAAM,CAChB,OAAO,QAAQ,IAAI,OAAQ,IAAI,GAAK,QAAQ,IAAI,MAAO,IAAI,CAC7D,CACF,CAAC,CACH,CAEA,SAAgB,gBACd,MACA,MACA,QAAkC,CAAC,EACoB,CACvD,IAAM,UAAY,QAAQ,WAAa,cAAA,KAAgC,EACjE,UAAY,MAAM,KAAK,WACzB,SAAS,MAAM,KAAK,WAAY,CAAE,gBAAiB,MAAM,eAAgB,CAAC,EAC1E,IAAA,GACE,OAAS,MAAM,KAAK,QAAU,MAAM,KAAK,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
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function parseHttpUrl(value){try{let url=new URL(value);return url.protocol===`http:`||url.protocol===`https:`?url:void 0}catch{return}}const HOST_GRAMMAR=/^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::\d{1,5})?$/;function canonicalHost(host,protocol){if(host&&HOST_GRAMMAR.test(host))return parseHttpUrl(`${protocol}//${host}`)?.host}export{canonicalHost as n,parseHttpUrl as r,HOST_GRAMMAR as t};
|
|
12
|
-
//# sourceMappingURL=host-
|
|
12
|
+
//# sourceMappingURL=host-Ix7FHVzW.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-
|
|
1
|
+
{"version":3,"file":"host-Ix7FHVzW.mjs","names":[],"sources":["../src/http/host.ts"],"sourcesContent":["/**\n * Host header parsing shared by the middleware that trusts it (CSRF origin\n * check, allowed hosts). One grammar and one canonical form, so two checks\n * never disagree about what host a request named.\n *\n * @module @forinda/kickjs/http/host\n */\n\n/** An http(s) URL, or undefined for anything else (`null`, `file:`, garbage). */\nexport function parseHttpUrl(value: string): URL | undefined {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * RFC 9110 `Host`: a hostname or bracketed IPv6 literal, optional port. Checked\n * before parsing, so the URL parser never sees userinfo, a path or whitespace —\n * `x@a.test` would otherwise parse to the host `a.test`.\n */\nexport const HOST_GRAMMAR = /^(?:[A-Za-z0-9.-]+|\\[[0-9A-Fa-f:.]+\\])(?::\\d{1,5})?$/\n\n/**\n * The request's host, canonicalized the way `URL` canonicalizes the origin it\n * is compared with (case, IDN, default port for that scheme) — comparing two\n * strings parsed by different rules is how checks like this get bypassed.\n */\nexport function canonicalHost(host: string | undefined, protocol: string): string | undefined {\n if (!host || !HOST_GRAMMAR.test(host)) return undefined\n return parseHttpUrl(`${protocol}//${host}`)?.host\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,aAAa,MAAgC,CAC3D,GAAI,CACF,IAAM,IAAM,IAAI,IAAI,KAAK,EACzB,OAAO,IAAI,WAAa,SAAW,IAAI,WAAa,SAAW,IAAM,IAAA,EACvE,MAAQ,CACN,MACF,CACF,CAOA,MAAa,aAAe,uDAO5B,SAAgB,cAAc,KAA0B,SAAsC,CAC5F,GAAK,MAAS,aAAa,KAAK,IAAI,EACpC,OAAO,aAAa,GAAG,SAAS,IAAI,MAAM,CAAC,EAAE,IAC/C"}
|