@forinda/kickjs 10.8.0 → 10.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/{adapter-B0Q8PzQ3.d.mts → adapter-DLjn8q0c.d.mts} +2 -2
  2. package/dist/{adapter-B0Q8PzQ3.d.mts.map → adapter-DLjn8q0c.d.mts.map} +1 -1
  3. package/dist/{application-CWPS2sst.mjs → application-2cqnmnMR.mjs} +4 -4
  4. package/dist/{application-CWPS2sst.mjs.map → application-2cqnmnMR.mjs.map} +1 -1
  5. package/dist/{application-BND5VDje.d.mts → application-w0Xnc35j.d.mts} +15 -8
  6. package/dist/{application-BND5VDje.d.mts.map → application-w0Xnc35j.d.mts.map} +1 -1
  7. package/dist/{background-D8VpVDrH.mjs → background-X_AU4qmI.mjs} +3 -3
  8. package/dist/{background-D8VpVDrH.mjs.map → background-X_AU4qmI.mjs.map} +1 -1
  9. package/dist/{body-policy-DAoHt4Cr.mjs → body-policy-BkjZt30w.mjs} +2 -2
  10. package/dist/{body-policy-DAoHt4Cr.mjs.map → body-policy-BkjZt30w.mjs.map} +1 -1
  11. package/dist/{bootstrap-BpRQ1_KV.mjs → bootstrap-CF5TB3dt.mjs} +3 -3
  12. package/dist/{bootstrap-BpRQ1_KV.mjs.map → bootstrap-CF5TB3dt.mjs.map} +1 -1
  13. package/dist/{bounded-counters-BMHzTpuZ.mjs → bounded-counters-BdHZ2tZ9.mjs} +2 -2
  14. package/dist/{bounded-counters-BMHzTpuZ.mjs.map → bounded-counters-BdHZ2tZ9.mjs.map} +1 -1
  15. package/dist/{client-ip-COnqHbaF.mjs → client-ip-Db1WMxl6.mjs} +2 -2
  16. package/dist/{client-ip-COnqHbaF.mjs.map → client-ip-Db1WMxl6.mjs.map} +1 -1
  17. package/dist/config/index.mjs +2 -2
  18. package/dist/{config-Cq6_Qr4r.mjs → config-DeWWBNz5.mjs} +3 -3
  19. package/dist/{config-Cq6_Qr4r.mjs.map → config-DeWWBNz5.mjs.map} +1 -1
  20. package/dist/{context-CX0TLa4H.mjs → context-CfGBpRlD.mjs} +3 -3
  21. package/dist/{context-CX0TLa4H.mjs.map → context-CfGBpRlD.mjs.map} +1 -1
  22. package/dist/{context-errors-Chi6ESHh.mjs → context-errors-QfmGMX4-.mjs} +2 -2
  23. package/dist/{context-errors-Chi6ESHh.mjs.map → context-errors-QfmGMX4-.mjs.map} +1 -1
  24. package/dist/{contributor-runner-Da7v9Whk.mjs → contributor-runner-DmHsL9iD.mjs} +3 -3
  25. package/dist/{contributor-runner-Da7v9Whk.mjs.map → contributor-runner-DmHsL9iD.mjs.map} +1 -1
  26. package/dist/core/adapter.d.mts +1 -1
  27. package/dist/core/adapter.mjs +1 -1
  28. package/dist/core/app-module.mjs +1 -1
  29. package/dist/core/cache.mjs +1 -1
  30. package/dist/core/container.mjs +2 -2
  31. package/dist/core/cron.mjs +2 -2
  32. package/dist/core/decorators.mjs +2 -2
  33. package/dist/core/errors.mjs +1 -1
  34. package/dist/core/interfaces.mjs +1 -1
  35. package/dist/core/logger.mjs +1 -1
  36. package/dist/core/path.mjs +1 -1
  37. package/dist/core/plugin.d.mts +1 -1
  38. package/dist/core/plugin.mjs +1 -1
  39. package/dist/core/reactivity.mjs +2 -2
  40. package/dist/{core-CiwDroJ7.mjs → core-DaYy5tKw.mjs} +3 -3
  41. package/dist/{core-CiwDroJ7.mjs.map → core-DaYy5tKw.mjs.map} +1 -1
  42. package/dist/{decorate-DdzHOAA1.mjs → decorate-8MLQUvoW.mjs} +3 -3
  43. package/dist/{decorate-DdzHOAA1.mjs.map → decorate-8MLQUvoW.mjs.map} +1 -1
  44. package/dist/{define-adapter-DJnPaqbo.mjs → define-adapter-By20TI53.mjs} +2 -2
  45. package/dist/{define-adapter-DJnPaqbo.mjs.map → define-adapter-By20TI53.mjs.map} +1 -1
  46. package/dist/{di-hooks-rXw3zCor.mjs → di-hooks-CGr13ce2.mjs} +6 -4
  47. package/dist/{di-hooks-rXw3zCor.mjs.map → di-hooks-CGr13ce2.mjs.map} +1 -1
  48. package/dist/{disposables-Cpde_0BE.mjs → disposables-V3Xlgvgk.mjs} +1 -1
  49. package/dist/{error-handler-C1I8a4wY.d.mts → error-handler-BrihKETE.d.mts} +2 -2
  50. package/dist/{error-handler-C1I8a4wY.d.mts.map → error-handler-BrihKETE.d.mts.map} +1 -1
  51. package/dist/{express-fiMFHEPO.mjs → express-CZHu70JR.mjs} +3 -3
  52. package/dist/{express-fiMFHEPO.mjs.map → express-CZHu70JR.mjs.map} +1 -1
  53. package/dist/{express-lazy-DxQzDeza.mjs → express-lazy-BixrSsYx.mjs} +3 -3
  54. package/dist/{express-lazy-DxQzDeza.mjs.map → express-lazy-BixrSsYx.mjs.map} +1 -1
  55. package/dist/{handler-D5QS_90y.mjs → handler-DFZIsJH1.mjs} +3 -3
  56. package/dist/{handler-D5QS_90y.mjs.map → handler-DFZIsJH1.mjs.map} +1 -1
  57. package/dist/{host-D7vw6t1i.mjs → host-CJdqJGsr.mjs} +2 -2
  58. package/dist/{host-D7vw6t1i.mjs.map → host-CJdqJGsr.mjs.map} +1 -1
  59. package/dist/http/application.d.mts +1 -1
  60. package/dist/http/application.mjs +2 -2
  61. package/dist/http/bootstrap.d.mts +1 -1
  62. package/dist/http/bootstrap.mjs +2 -2
  63. package/dist/http/context.d.mts +1 -1
  64. package/dist/http/context.mjs +2 -2
  65. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  66. package/dist/http/middleware/breach-padding.mjs +1 -1
  67. package/dist/http/middleware/cors.mjs +1 -1
  68. package/dist/http/middleware/csrf.mjs +2 -2
  69. package/dist/http/middleware/error-handler.d.mts +1 -1
  70. package/dist/http/middleware/error-handler.mjs +2 -2
  71. package/dist/http/middleware/helmet.mjs +1 -1
  72. package/dist/http/middleware/rate-limit.mjs +2 -2
  73. package/dist/http/middleware/request-id.mjs +1 -1
  74. package/dist/http/middleware/request-logger.mjs +2 -2
  75. package/dist/http/middleware/session.mjs +2 -2
  76. package/dist/http/middleware/spa.d.mts +1 -1
  77. package/dist/http/middleware/spa.mjs +2 -2
  78. package/dist/http/middleware/upload.d.mts +2 -2
  79. package/dist/http/middleware/upload.mjs +2 -2
  80. package/dist/http/middleware/validate.mjs +1 -1
  81. package/dist/http/middleware/views.d.mts +1 -1
  82. package/dist/http/middleware/views.mjs +2 -2
  83. package/dist/http/query/index.mjs +2 -2
  84. package/dist/http/router-builder.d.mts +1 -1
  85. package/dist/http/router-builder.mjs +2 -2
  86. package/dist/http/runtimes/express.d.mts +2 -2
  87. package/dist/http/runtimes/express.mjs +2 -2
  88. package/dist/http/runtimes/fastify.d.mts +1 -1
  89. package/dist/http/runtimes/fastify.mjs +2 -2
  90. package/dist/http/runtimes/h3-web.mjs +1 -1
  91. package/dist/http/runtimes/h3.d.mts +1 -1
  92. package/dist/http/runtimes/h3.mjs +2 -2
  93. package/dist/index.d.mts +6 -6
  94. package/dist/index.mjs +2 -2
  95. package/dist/{is-production-C7DJ7c5k.mjs → is-production-CMJW948J.mjs} +2 -2
  96. package/dist/{is-production-C7DJ7c5k.mjs.map → is-production-CMJW948J.mjs.map} +1 -1
  97. package/dist/{jobs-Bdqz5n21.mjs → jobs-d2j_7_9R.mjs} +3 -3
  98. package/dist/{jobs-Bdqz5n21.mjs.map → jobs-d2j_7_9R.mjs.map} +1 -1
  99. package/dist/{kv-stores-CISRYh_H.d.mts → kv-stores-DJBnGQsJ.d.mts} +2 -2
  100. package/dist/{kv-stores-CISRYh_H.d.mts.map → kv-stores-DJBnGQsJ.d.mts.map} +1 -1
  101. package/dist/{kv-stores-BM5Fcds2.mjs → kv-stores-u0V_K-2O.mjs} +3 -3
  102. package/dist/{kv-stores-BM5Fcds2.mjs.map → kv-stores-u0V_K-2O.mjs.map} +1 -1
  103. package/dist/{lazy-serve-static-D2pf9ODr.mjs → lazy-serve-static-kB1m23xS.mjs} +3 -3
  104. package/dist/{lazy-serve-static-D2pf9ODr.mjs.map → lazy-serve-static-kB1m23xS.mjs.map} +1 -1
  105. package/dist/{metadata-Ck5f9CNm.mjs → metadata-c1TNXrm_.mjs} +1 -1
  106. package/dist/{observers-BV435fEL.mjs → observers-vX5EpqCX.mjs} +2 -2
  107. package/dist/{observers-BV435fEL.mjs.map → observers-vX5EpqCX.mjs.map} +1 -1
  108. package/dist/{precompressed-DPESwDxf.mjs → precompressed-DIkilvFq.mjs} +2 -2
  109. package/dist/{precompressed-DPESwDxf.mjs.map → precompressed-DIkilvFq.mjs.map} +1 -1
  110. package/dist/{query-Bs9mU4bx.mjs → query-BIGYogvJ.mjs} +2 -2
  111. package/dist/{query-Bs9mU4bx.mjs.map → query-BIGYogvJ.mjs.map} +1 -1
  112. package/dist/{reply-BmNC0SFg.mjs → reply-CtSYYFK5.mjs} +2 -2
  113. package/dist/{reply-BmNC0SFg.mjs.map → reply-CtSYYFK5.mjs.map} +1 -1
  114. package/dist/{request-scope-DFf8XH5R.mjs → request-scope-B1GH3d99.mjs} +3 -3
  115. package/dist/{request-scope-DFf8XH5R.mjs.map → request-scope-B1GH3d99.mjs.map} +1 -1
  116. package/dist/{respond-DbgwV87J.mjs → respond-D8cMACHW.mjs} +2 -2
  117. package/dist/{respond-DbgwV87J.mjs.map → respond-D8cMACHW.mjs.map} +1 -1
  118. package/dist/{rolldown-runtime-BIVYCGx6.mjs → rolldown-runtime-CSRdE5Vk.mjs} +1 -1
  119. package/dist/{route-flag-Dm1NxMbJ.mjs → route-flag-Ce2FkkeT.mjs} +3 -3
  120. package/dist/{route-flag-Dm1NxMbJ.mjs.map → route-flag-Ce2FkkeT.mjs.map} +1 -1
  121. package/dist/{route-policy-CdBgPlft.mjs → route-policy-BRcI3gmZ.mjs} +2 -2
  122. package/dist/{route-policy-CdBgPlft.mjs.map → route-policy-BRcI3gmZ.mjs.map} +1 -1
  123. package/dist/{router-builder-BM9t-xGP.mjs → router-builder-BgxacQbc.mjs} +3 -3
  124. package/dist/{router-builder-BM9t-xGP.mjs.map → router-builder-BgxacQbc.mjs.map} +1 -1
  125. package/dist/{router-builder-CwPowg4s.d.mts → router-builder-CPJHwoL1.d.mts} +2 -2
  126. package/dist/{router-builder-CwPowg4s.d.mts.map → router-builder-CPJHwoL1.d.mts.map} +1 -1
  127. package/dist/{settings-CPQhWD12.mjs → settings-hE0ewJKF.mjs} +3 -3
  128. package/dist/{settings-CPQhWD12.mjs.map → settings-hE0ewJKF.mjs.map} +1 -1
  129. package/dist/{token-tL_r-ZPP.mjs → token-DNQnEuMJ.mjs} +1 -1
  130. package/dist/{upload-DDDboa_F.d.mts → upload-DtQ1pdQw.d.mts} +2 -2
  131. package/dist/{upload-DDDboa_F.d.mts.map → upload-DtQ1pdQw.d.mts.map} +1 -1
  132. package/dist/{upload-config-DCm8AFEW.mjs → upload-config-ikC1nZgF.mjs} +2 -2
  133. package/dist/{upload-config-DCm8AFEW.mjs.map → upload-config-ikC1nZgF.mjs.map} +1 -1
  134. package/dist/{url-for-DAVOWiQ_.mjs → url-for-Bh43Ax1C.mjs} +3 -3
  135. package/dist/{url-for-DAVOWiQ_.mjs.map → url-for-Bh43Ax1C.mjs.map} +1 -1
  136. package/dist/{web-crypto-BMaKs6M0.mjs → web-crypto-Dx8Nmh16.mjs} +2 -2
  137. package/dist/{web-crypto-BMaKs6M0.mjs.map → web-crypto-Dx8Nmh16.mjs.map} +1 -1
  138. package/dist/web.d.mts +2 -2
  139. package/dist/web.mjs +2 -2
  140. package/package.json +10 -10
package/dist/index.d.mts CHANGED
@@ -3,32 +3,32 @@ import { a as isInjectionToken, i as ctn, n as InjectionToken, r as createToken,
3
3
  import { a as SettingsOf, c as defineSettings, i as SettingsDeclaration, l as loadSettings, n as ProvidedSettings, o as ValueOrigin, r as Settings, s as VarOrigin, t as ConfigVar, u as originsOf } from "./settings-BFQisfqG.mjs";
4
4
  import { A as Service, B as resolveAsset, C as Post, D as Put, F as ASSET_MANIFEST_VERSION, I as KickAssets, L as UnknownAssetError, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, P as ASSETS, R as assets, S as Patch, T as PreDestroy, V as useAssets, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable, z as clearAssetCache } from "./decorators-DxNb5mWw.mjs";
5
5
  import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, f as withEnv, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "./index-CNBYZDto.mjs";
6
- import { $ as ContributorSource, At as MutableModuleRegistry, B as ROUTE_URLS, Bt as reportResponse, C as UseConnectOptions, Ct as BuildContext, D as RouteShape, Dt as definePlugin, E as RequestContext, Et as PluginFactory, Ft as IntrospectionSnapshot, G as AdapterAsyncOptions, Gt as onEnv, H as UrlBuilder, Ht as AdapterCondition, I as resolveMimeTypes, It as ErrorInfo, J as defineAdapter, K as AdapterFactory, Kt as onPackage, L as ConditionalOutcome, Lt as ErrorSource, M as UploadedFile, Mt as KickJsPluginRegistry, Nt as IntrospectFn, O as SseHandler, Ot as KickPlugin, Pt as IntrospectionKind, Q as ContributorPipeline, R as Validators, Rt as ResponseInfo, S as RuntimeTypeMap, St as defineModule, T as DeepReadonly, Tt as PluginAsyncOptions, U as UrlForArgs, Ut as ConditionOutcome, V as RouteName, Vt as FailureAdvice, W as UrlQuery, Wt as allOf, X as runContributors, Y as RunContributorsOptions, Z as BuildPipelineOptions, _ as RouteMethod, _t as registerDisposable, a as KickServer, at as getMetaRecord, b as RuntimeCapabilities, bt as DefineModuleOptions, c as ActiveRuntime, ct as hasClassMeta, d as HttpRuntime, dt as setClassMeta, et as SourcedRegistration, f as KickRuntimeRegister, ft as setInMetaMap, g as RouteMeta, gt as disposeAll, h as RouteEntry, ht as Disposable, i as AppAdapterClass, it as getMetaMap, j as UploadStorageEngine, jt as KickJsPluginName, kt as ModuleRegistry, l as AdapterHttp, lt as pushClassMeta, m as RouteContributor, mt as setMethodMeta, n as AdapterMiddleware, nt as getClassMeta, o as MiddlewarePath, ot as getMethodMeta, p as MatchedRoute, pt as setInMetaRecord, q as DefineAdapterOptions, r as AppAdapter, rt as getClassMetaOrUndefined, s as MiddlewarePhase, st as getMethodMetaOrUndefined, t as AdapterContext, tt as buildPipeline, u as CtxHandler, ut as pushMethodMeta, v as RouteTable, vt as ModuleList, w as Ctx, wt as DefinePluginOptions, x as RuntimeResponse, xt as ModuleFactory, y as RuntimeAppOptions, yt as defineModules, z as evaluatePreconditions, zt as reportError } from "./adapter-B0Q8PzQ3.mjs";
6
+ import { $ as ContributorSource, At as MutableModuleRegistry, B as ROUTE_URLS, Bt as reportResponse, C as UseConnectOptions, Ct as BuildContext, D as RouteShape, Dt as definePlugin, E as RequestContext, Et as PluginFactory, Ft as IntrospectionSnapshot, G as AdapterAsyncOptions, Gt as onEnv, H as UrlBuilder, Ht as AdapterCondition, I as resolveMimeTypes, It as ErrorInfo, J as defineAdapter, K as AdapterFactory, Kt as onPackage, L as ConditionalOutcome, Lt as ErrorSource, M as UploadedFile, Mt as KickJsPluginRegistry, Nt as IntrospectFn, O as SseHandler, Ot as KickPlugin, Pt as IntrospectionKind, Q as ContributorPipeline, R as Validators, Rt as ResponseInfo, S as RuntimeTypeMap, St as defineModule, T as DeepReadonly, Tt as PluginAsyncOptions, U as UrlForArgs, Ut as ConditionOutcome, V as RouteName, Vt as FailureAdvice, W as UrlQuery, Wt as allOf, X as runContributors, Y as RunContributorsOptions, Z as BuildPipelineOptions, _ as RouteMethod, _t as registerDisposable, a as KickServer, at as getMetaRecord, b as RuntimeCapabilities, bt as DefineModuleOptions, c as ActiveRuntime, ct as hasClassMeta, d as HttpRuntime, dt as setClassMeta, et as SourcedRegistration, f as KickRuntimeRegister, ft as setInMetaMap, g as RouteMeta, gt as disposeAll, h as RouteEntry, ht as Disposable, i as AppAdapterClass, it as getMetaMap, j as UploadStorageEngine, jt as KickJsPluginName, kt as ModuleRegistry, l as AdapterHttp, lt as pushClassMeta, m as RouteContributor, mt as setMethodMeta, n as AdapterMiddleware, nt as getClassMeta, o as MiddlewarePath, ot as getMethodMeta, p as MatchedRoute, pt as setInMetaRecord, q as DefineAdapterOptions, r as AppAdapter, rt as getClassMetaOrUndefined, s as MiddlewarePhase, st as getMethodMetaOrUndefined, t as AdapterContext, tt as buildPipeline, u as CtxHandler, ut as pushMethodMeta, v as RouteTable, vt as ModuleList, w as Ctx, wt as DefinePluginOptions, x as RuntimeResponse, xt as ModuleFactory, y as RuntimeAppOptions, yt as defineModules, z as evaluatePreconditions, zt as reportError } from "./adapter-DLjn8q0c.mjs";
7
7
  import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse, r as ConnectMiddleware, t as ConnectErrorHandler } from "./connect-BlIamapT.mjs";
8
8
  import { a as tokenName, i as KickJsRegistry, n as ContainerChangeEvent, r as ContainerChangeListener, t as Container } from "./container-4iJdDkRH.mjs";
9
9
  import { _ as getRouteFlags, a as RouteFlagContext, c as RouteFlagName, d as RouteFlagTest, f as RouteFlagValue, g as defineRouteFlag, h as assertFlagTest, i as RouteFlag, l as RouteFlagPredicate, m as ValuedRouteFlag, n as KickRouteFlags, o as RouteFlagDeclaration, p as RouteFlags, r as NegatedRouteFlagName, s as RouteFlagDeclarations, t as BareRouteFlag, u as RouteFlagRecord, v as matchesFlagTest, y as resolveRouteFlags } from "./route-flag-B1lQht6v.mjs";
10
10
  import { c as PostConstructStatus, i as Constructor, l as Scope, n as BuilderOf, o as METADATA, r as ClassKind, s as MaybePromise, t as Buildable, u as ServiceOptions } from "./interfaces-C6LHcYsg.mjs";
11
11
  import { C as MetaValue, S as ExecutionContext, _ as ResolvedDeps, a as ModuleRoutes, b as ContextMeta, c as ContextDecorator, d as ContextDecoratorTarget, f as ContextDecoratorWithDefaults, g as MissingParamKeys, h as DepValue, l as ContextDecoratorRequiringParams, m as ContributorRegistrations, n as AppModuleClass, o as AnyContributorRegistration, p as ContributorRegistration, r as AppModuleEntry, s as CallSiteParams, t as AppModule, u as ContextDecoratorSpec, v as defineContextDecorator, x as ContextMetaKey, y as ContextKeys } from "./app-module-Bk3glnPP.mjs";
12
12
  import { a as CronOptions, c as getCronJobs, d as runCronJob, f as runCronJobs, i as CronJobMeta, l as isCronJobEnabled, n as Cron, o as CronRun, r as CronJob, s as cronScheduleId, t as CRON_META, u as listCronJobs } from "./cron-BTGytNg-.mjs";
13
- import { A as NoJobHandlerError, C as JOB_DISPATCHER, D as JobDispatcher, E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, M as ProcessDefinition, N as listJobHandlers, O as JobHandler, P as listJobQueues, S as JOB_CONTEXT_FIELD, T as Job, _ as Respondable, a as KvSessionStoreOptions, b as isRespondable, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, j as Process, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, p as RESPOND, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as settleBackgroundWork, v as applyHandlerResult, w as JOB_META, x as reply, y as isReply } from "./kv-stores-CISRYh_H.mjs";
13
+ import { A as NoJobHandlerError, C as JOB_DISPATCHER, D as JobDispatcher, E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, M as ProcessDefinition, N as listJobHandlers, O as JobHandler, P as listJobQueues, S as JOB_CONTEXT_FIELD, T as Job, _ as Respondable, a as KvSessionStoreOptions, b as isRespondable, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, j as Process, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, p as RESPOND, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as settleBackgroundWork, v as applyHandlerResult, w as JOB_META, x as reply, y as isReply } from "./kv-stores-DJBnGQsJ.mjs";
14
14
  import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider } from "./cache-CdRHSXow.mjs";
15
15
  import { a as describeError, i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "./logger-xE9qI_FS.mjs";
16
16
  import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "./errors-By6UueCm.mjs";
17
- import { $ as createHandler, A as requestScopeMiddleware, At as DuplicateMountNameError, B as SignerOptions, Bt as CircuitBreaker, C as ViewAdapterOptions, Ct as offerRoutePolicy, D as TraceContextOptions, Dt as GroupAssetKeysResult, E as TraceContext, Et as GroupAssetKeysOptions, F as buildRoutes, Ft as mountSort, G as PasswordHashOptions, Gt as FormatKickErrorOptions, H as createSigner, Ht as CircuitBreakerState, I as expressRuntime, It as ContributorCycleError, J as verifyPassword, Jt as formatKickError, K as VerifyPasswordOptions, Kt as KickError, L as materializeRouter, Lt as DuplicateContributorError, M as getRequestStore, Mt as MountCycleError, N as getRequestValue, Nt as MountKind, O as parseTraceparent, Ot as groupAssetKeys, P as requestStore, Pt as MountSortItem, Q as KickHandler, R as SignedCheck, Rt as MissingContextValueError, S as ViewAdapter, St as bindRoutePolicy, T as TRACEPARENT_HEADER, Tt as AssetKeyStrategy, U as LegacyHasher, Ut as CircuitBreakerStats, V as VerifyOptions, Vt as CircuitBreakerOptions, W as PasswordCheck, Wt as CircuitOpenError, X as ClusterOptions, Y as defineHttpContextDecorator, Z as isClusterPrimary, _ as HealthProbe, _t as StartupCheckError, a as ConfigDescription, at as CRON_WORKER_ENV, b as SpaAdapterOptions, bt as StartupTimelineSnapshot, c as MiddlewareEntry, ct as RAW_BODY, dt as metricsAdapter, et as bootstrap, ft as CacheResponse, g as HealthModuleConfig, gt as StartupCheck, h as HealthController, ht as CheckMessage, i as ApplicationOptions, it as RESPONSE_CHANNEL, j as RequestStore, jt as MissingMountDepError, k as traceContext, kt as stripExt, l as MountedRouteInfo, lt as MetricsOptions, m as HealthCheckResult, mt as CheckContext, n as AppStatus, nt as HANDLER_CHANNEL, o as ConfigOrigins, ot as CronAdapterOptions, p as HEALTH_PROBE, pt as CacheResponseOptions, q as hashPassword, qt as KickErrorInit, r as Application, rt as HandlerTraceContext, s as ManagementOptions, st as KickCronAdapter, t as APPLICATION, tt as ERROR_CHANNEL, u as ServerOptions, ut as RequestHistogram, v as healthModule, vt as defineCheck, wt as AssetKeyPair, xt as RoutePolicyTable, y as SpaAdapter, yt as StartupStep, z as Signer, zt as MissingContributorError } from "./application-BND5VDje.mjs";
17
+ import { $ as createHandler, A as requestScopeMiddleware, At as DuplicateMountNameError, B as SignerOptions, Bt as CircuitBreaker, C as ViewAdapterOptions, Ct as offerRoutePolicy, D as TraceContextOptions, Dt as GroupAssetKeysResult, E as TraceContext, Et as GroupAssetKeysOptions, F as buildRoutes, Ft as mountSort, G as PasswordHashOptions, Gt as FormatKickErrorOptions, H as createSigner, Ht as CircuitBreakerState, I as expressRuntime, It as ContributorCycleError, J as verifyPassword, Jt as formatKickError, K as VerifyPasswordOptions, Kt as KickError, L as materializeRouter, Lt as DuplicateContributorError, M as getRequestStore, Mt as MountCycleError, N as getRequestValue, Nt as MountKind, O as parseTraceparent, Ot as groupAssetKeys, P as requestStore, Pt as MountSortItem, Q as KickHandler, R as SignedCheck, Rt as MissingContextValueError, S as ViewAdapter, St as bindRoutePolicy, T as TRACEPARENT_HEADER, Tt as AssetKeyStrategy, U as LegacyHasher, Ut as CircuitBreakerStats, V as VerifyOptions, Vt as CircuitBreakerOptions, W as PasswordCheck, Wt as CircuitOpenError, X as ClusterOptions, Y as defineHttpContextDecorator, Z as isClusterPrimary, _ as HealthProbe, _t as StartupCheckError, a as ConfigDescription, at as CRON_WORKER_ENV, b as SpaAdapterOptions, bt as StartupTimelineSnapshot, c as MiddlewareEntry, ct as RAW_BODY, dt as metricsAdapter, et as bootstrap, ft as CacheResponse, g as HealthModuleConfig, gt as StartupCheck, h as HealthController, ht as CheckMessage, i as ApplicationOptions, it as RESPONSE_CHANNEL, j as RequestStore, jt as MissingMountDepError, k as traceContext, kt as stripExt, l as MountedRouteInfo, lt as MetricsOptions, m as HealthCheckResult, mt as CheckContext, n as AppStatus, nt as HANDLER_CHANNEL, o as ConfigOrigins, ot as CronAdapterOptions, p as HEALTH_PROBE, pt as CacheResponseOptions, q as hashPassword, qt as KickErrorInit, r as Application, rt as HandlerTraceContext, s as ManagementOptions, st as KickCronAdapter, t as APPLICATION, tt as ERROR_CHANNEL, u as ServerOptions, ut as RequestHistogram, v as healthModule, vt as defineCheck, wt as AssetKeyPair, xt as RoutePolicyTable, y as SpaAdapter, yt as StartupStep, z as Signer, zt as MissingContributorError } from "./application-w0Xnc35j.mjs";
18
18
  import { n as joinPaths, r as normalizePath, t as buildMountPath } from "./path-CMwIHsdv.mjs";
19
19
  import { a as batch, c as reactive, d as toRefs, f as unref, i as WatchOptions, l as ref, n as Ref, o as computed, p as watch, r as RefOptions, s as isRef, t as ComputedRef, u as toRef } from "./reactivity-DZrc3Yhu.mjs";
20
20
  import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData } from "./session-8uNRCplB.mjs";
21
21
  import { A as TypedParsedQuery, C as PaginatedResponse, D as QueryFieldConfig, E as QueryBuilderAdapter, O as SortItem, S as FilterOperator, T as ParsedQuery, _ as CursorQuery, a as getQueryParsingDefaults, b as FieldsOf, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as CursorPosition, h as CursorPaginatedResponse, i as buildQueryParams, l as parseSearchQuery, m as CursorPaginateOptions, n as QueryRejectReason, o as parseFilters, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as CursorValue, w as PaginationParams, x as FilterItem, y as FILTER_OPERATORS } from "./index-Blgka75E.mjs";
22
22
  import { a as validate, i as defaultValidationError, n as ValidationFailure, t as ValidationErrorFactory } from "./validate-D4Poe2EE.mjs";
23
23
  import { n as allowedHosts, t as AllowedHostsOptions } from "./allowed-hosts-BpKwviq5.mjs";
24
- import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-CwPowg4s.mjs";
24
+ import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-CPJHwoL1.mjs";
25
25
  import { n as requestId, t as REQUEST_ID_HEADER } from "./request-id-Dn64nEHK.mjs";
26
- import { n as errorHandler, r as notFoundHandler } from "./error-handler-C1I8a4wY.mjs";
26
+ import { n as errorHandler, r as notFoundHandler } from "./error-handler-BrihKETE.mjs";
27
27
  import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-w5bc-PGs.mjs";
28
28
  import { i as requestLogger, n as LoggedResponse, r as RequestLoggerOptions, t as LoggedRequest } from "./request-logger-TgcKRNDD.mjs";
29
29
  import { n as HelmetOptions, r as helmet } from "./helmet-BVuVBl-D.mjs";
30
30
  import { n as breachPadding, t as BreachPaddingOptions } from "./breach-padding-FBVGmcBb.mjs";
31
31
  import { n as cors, t as CorsOptions } from "./cors-BlR_b0Qb.mjs";
32
32
  import { i as rateLimit, n as RateLimitOptions, r as RateLimitStore } from "./rate-limit-DQDk6bAH.mjs";
33
- import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-DDDboa_F.mjs";
33
+ import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-DtQ1pdQw.mjs";
34
34
  export { APPLICATION, ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterCondition, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AllowedHostsOptions, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, type AppStatus, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, Autowired, type BareRouteFlag, type BaseUploadOptions, type BreachPaddingOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CRON_WORKER_ENV, CacheEvict, type CacheOptions, type CacheProvider, CacheResponse, type CacheResponseOptions, Cacheable, type CallSiteParams, type CheckContext, type CheckMessage, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, type ConditionOutcome, type ConditionalOutcome, type ConfigDescription, type ConfigOrigins, ConfigService, type ConfigVar, type ConnectErrorHandler, type ConnectHandler, type ConnectMiddleware, type ConnectNext, type ConnectRequest, type ConnectResponse, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronAdapterOptions, type CronJob, type CronJobMeta, type CronOptions, type CronRun, type CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, type CursorPaginateOptions, type CursorPaginatedResponse, type CursorPosition, type CursorQuery, type CursorValue, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, ERROR_CHANNEL, type Env, type EnvKey, type ErrorInfo, type ErrorSource, type ExecutionContext, FILTER_OPERATORS, type FailureAdvice, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, HANDLER_CHANNEL, HEALTH_PROBE, type HandlerTraceContext, type HealthCheckResult, HealthController, type HealthModuleConfig, type HealthProbe, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, JOB_CONTEXT_FIELD, JOB_DISPATCHER, JOB_META, Job, type JobContextCarrier, type JobDispatcher, type JobHandler, type JobLike, type KickAssets, KickCronAdapter, KickError, type KickErrorInit, type KickHandler, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRouteFlags, type KickRuntimeRegister, type KickServer, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type LegacyHasher, type LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type ManagementOptions, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, type MetricsOptions, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, type MountedRouteInfo, MutableModuleRegistry, type NegatedRouteFlagName, NoJobHandlerError, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, type PasswordCheck, type PasswordHashOptions, Patch, type PlatformContext, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Process, type ProcessDefinition, type ProvidedSettings, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, RAW_BODY, REQUEST_ID_HEADER, RESPOND, RESPONSE_CHANNEL, ROUTE_URLS, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type RefOptions, type Reply, type ReplyHeaders, type ReplyOptions, Repository, RequestContext, RequestHistogram, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type Respondable, type ResponseInfo, type RouteContributor, type RouteDefinition, type RouteEntry, type RouteFlag, type RouteFlagContext, type RouteFlagDeclaration, type RouteFlagDeclarations, type RouteFlagName, type RouteFlagPredicate, type RouteFlagRecord, type RouteFlagTest, type RouteFlagValue, type RouteFlags, type RouteMeta, type RouteMethod, type RouteName, RoutePolicyTable, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, type ServerOptions, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type Settings, type SettingsDeclaration, type SettingsOf, type SignedCheck, type Signer, type SignerOptions, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, type StartupCheck, StartupCheckError, type StartupStep, type StartupTimelineSnapshot, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UploadStorageEngine, type UploadedFile, type UrlBuilder, type UrlForArgs, type UrlQuery, type UseConnectOptions, type ValidationError, type ValidationErrorFactory, type ValidationFailure, type Validators, Value, type ValueOrigin, type ValuedRouteFlag, type VarOrigin, type VerifyOptions, type VerifyPasswordOptions, ViewAdapter, type ViewAdapterOptions, type WatchOptions, allOf, allowedHosts, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, batch, bindRoutePolicy, bootstrap, breachPadding, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createSigner, createToken, cronScheduleId, csrf, csrfGuard, ctn, defaultProblemTitle, defaultValidationError, defineAdapter, defineCheck, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, defineSettings, describeError, disposeAll, errorHandler, evaluatePreconditions, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, hashPassword, healthModule, helmet, isClusterPrimary, isCronJobEnabled, isInjectionToken, isRef, isReply, isRespondable, joinPaths, listCronJobs, listJobHandlers, listJobQueues, loadEnv, loadEnvFromSchema, loadSettings, matchesBearer, matchesFlagTest, materializeRouter, metricsAdapter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, onEnv, onPackage, originsOf, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, registerJobContext, reloadEnv, reply, reportError, reportResponse, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, resolveRouteFlags, runContributors, runCronJob, runCronJobs, runJob, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, settleBackgroundWork, stampJobContext, stripExt, toRef, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, verifyPassword, waitUntil, watch, withBuilder, withEnv };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{o as KickError,s as formatKickError}from"./di-hooks-rXw3zCor.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{i as isInjectionToken,n as createToken,r as ctn,t as INJECTION_TOKEN}from"./token-tL_r-ZPP.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-Ck5f9CNm.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{i as defineModule,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-DAVOWiQ_.mjs";import{i as reportResponse,r as reportError}from"./observers-BV435fEL.mjs";import{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs}from"./core/cron.mjs";import{a as NoJobHandlerError,c as listJobQueues,d as stampJobContext,i as Job,l as registerJobContext,n as JOB_DISPATCHER,o as Process,r as JOB_META,s as listJobHandlers,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-Bdqz5n21.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-Cpde_0BE.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-Dm1NxMbJ.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-CiwDroJ7.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-Chi6ESHh.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-BM9t-xGP.mjs";import{t as runContributors}from"./contributor-runner-Da7v9Whk.mjs";import{_ as MountCycleError,a as HealthController,c as defineCheck,d as onPackage,f as ERROR_CHANNEL,g as MissingMountDepError,h as DuplicateMountNameError,i as HEALTH_PROBE,l as allOf,m as RESPONSE_CHANNEL,n as Application,o as healthModule,p as HANDLER_CHANNEL,s as StartupCheckError,t as APPLICATION,u as onEnv,v as mountSort}from"./application-CWPS2sst.mjs";import{t as defineAdapter}from"./define-adapter-DJnPaqbo.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-CdBgPlft.mjs";import{n as randomHex,t as matchesBearer}from"./web-crypto-BMaKs6M0.mjs";import{n as RAW_BODY}from"./body-policy-DAoHt4Cr.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as getRequestStore,i as waitUntil,o as getRequestValue,r as settleBackgroundWork,s as requestStore}from"./background-D8VpVDrH.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware}from"./request-scope-DFf8XH5R.mjs";import{a as originsOf,i as loadSettings,n as defineSettings}from"./settings-CPQhWD12.mjs";import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"./decorate-DdzHOAA1.mjs";import{a as reply,i as isRespondable,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-BmNC0SFg.mjs";import{a as materializeRouter,i as expressRuntime,n as buildRoutes}from"./express-lazy-DxQzDeza.mjs";import{a as evaluatePreconditions,i as stringifyJson,t as RequestContext}from"./context-CX0TLa4H.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-BpRQ1_KV.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-Bs9mU4bx.mjs";import{defaultValidationError,validate}from"./http/middleware/validate.mjs";import{csrf,csrfGuard}from"./http/middleware/csrf.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{breachPadding}from"./http/middleware/breach-padding.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-BM5Fcds2.mjs";import{session}from"./http/middleware/session.mjs";import{o as resolveMimeTypes}from"./upload-config-DCm8AFEW.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-Cq6_Qr4r.mjs";import{createHmac,randomBytes,scrypt,timingSafeEqual}from"node:crypto";import{monitorEventLoopDelay}from"node:perf_hooks";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=/* @__PURE__ */ new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}const inFlight=/* @__PURE__ */ new Map,PERSONAL=[`authorization`,`proxy-authorization`,`x-api-key`,`cookie`];function CacheResponse(options){let maxAgeMs=options.maxAge*1e3,swrMs=(options.swr??0)*1e3,varies=(options.varies??[]).map(h=>h.toLowerCase());return(target,propertyKey,descriptor)=>{let original=descriptor.value,owner=typeof target==`function`?target.name:target.constructor?.name,prefix=typeof options.key==`string`?options.key:`kick:response:${owner??`anonymous`}.${String(propertyKey)}`,keyOf=typeof options.key==`function`?options.key:void 0;return descriptor.value=async function(ctx,...rest){let req=ctx.req,method=String(req.method??`GET`).toUpperCase(),headers=ctx.headers;if(method!==`GET`&&method!==`HEAD`||maxAgeMs+swrMs<=0)return original.call(this,ctx,...rest);let identity;if(keyOf){let chosen=keyOf(ctx);if(chosen===null)return original.call(this,ctx,...rest);identity=chosen}else{if(PERSONAL.some(h=>headers[h]!==void 0&&!varies.includes(h))||ctx.user!==void 0&&!varies.some(h=>PERSONAL.includes(h)))return original.call(this,ctx,...rest);let host=String(headers.host??``);if(!VALID_HOST.test(host))return original.call(this,ctx,...rest);identity=JSON.stringify([host.toLowerCase(),req.originalUrl??req.url??``])}let varied=varies.map(h=>`${h}=${String(headers[h]??``)}`).join(`&`),key=`${prefix}:${identity}|${varied}`,provider=getCacheProvider(),run=()=>record(original,this,ctx,rest),build=()=>buildOnce(key,run),store=async({recorded,shared})=>{if(!shared&&recorded&&cacheable(recorded)){let entry={recorded,storedAt:Date.now()};await provider.set(key,entry,maxAgeMs+swrMs)}},entry=await provider.get(key);if(entry){let age=Date.now()-entry.storedAt;if(age<maxAgeMs+swrMs){age>=maxAgeMs&&waitUntil(build().then(store)),replay(ctx,entry.recorded);return}}let built=await build();await store(built);let recorded=built.recorded;built.shared&&!(recorded&&cacheable(recorded))&&(recorded=await run()),recorded&&replay(ctx,recorded)},descriptor}}const VALID_HOST=/^(?:\[[0-9a-f:.]+\]|[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::\d{1,5})?$/i;async function buildOnce(key,run){let pending=inFlight.get(key);if(pending)return{recorded:await pending,shared:!0};let load=run().finally(()=>inFlight.delete(key));return inFlight.set(key,load),{recorded:await load,shared:!1}}function cacheable(recorded){return recorded.status===200&&!(`set-cookie`in recorded.headers)&&!recorded.native}async function record(handler,self,ctx,rest){let recorded={status:200,headers:{},body:``},sent=!1,finish=body=>{body instanceof Uint8Array?(recorded.body=toBase64(body),recorded.binary=!0):typeof body==`string`?recorded.body=body:body!=null&&(recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(body)),sent=!0},unsupported=what=>()=>{throw Error(`@CacheResponse: the handler called ${what}. A cached route answers with ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.`)},response={status(code){return recorded.status=code,response},type(contentType){return recorded.type=contentType,response},json(data){return recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(data),sent=!0,response},send(data){return finish(data),response},end(data){return finish(data),response},setHeader(name,value){recorded.headers[name.toLowerCase()]=Array.isArray(value)?[...value]:String(value)},get headersSent(){return sent},once(){},render:unsupported(`render()`),writeHead:unsupported(`writeHead()`),flushHeaders:unsupported(`flushHeaders()`),write:unsupported(`write()`)},native=new Proxy(ctx.res,{get(target,prop){let value=Reflect.get(target,prop,target);return typeof value==`function`?(...args)=>(recorded.native=!0,value.apply(target,args)):value},set(target,prop,value){return recorded.native=!0,Reflect.set(target,prop,value,target)}}),recordingCtx=Object.create(ctx,{_response:{value:response},res:{value:native}}),result=await handler.call(self,recordingCtx,...rest);return sent||await applyHandlerResult(recordingCtx,result),sent?recorded:null}function replay(ctx,recorded){if(ctx._response.headersSent)return;for(let[name,value]of Object.entries(recorded.headers))name!==`etag`&&name!==`content-type`&&ctx.setHeader(name,value);if(recorded.status===200){let etag=recorded.headers.etag??weakEtag(recorded.body);if(ctx.conditional({etag}))return}let options={status:recorded.status,type:recorded.type??`text/plain; charset=utf-8`};ctx.send(recorded.binary?fromBase64(recorded.body):recorded.body,options)}function weakEtag(body){let hash=2166136261;for(let i=0;i<body.length;i++)hash^=body.charCodeAt(i),hash=Math.imul(hash,16777619);return`W/"${body.length.toString(16)}-${(hash>>>0).toString(16)}"`}function toBase64(bytes){let binary=``;for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}function fromBase64(text){let binary=atob(text),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}const DEFAULT_BUCKETS=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],label=value=>value.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`
11
+ import{o as KickError,s as formatKickError}from"./di-hooks-CGr13ce2.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{i as isInjectionToken,n as createToken,r as ctn,t as INJECTION_TOKEN}from"./token-DNQnEuMJ.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-c1TNXrm_.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{i as defineModule,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-Bh43Ax1C.mjs";import{i as reportResponse,r as reportError}from"./observers-vX5EpqCX.mjs";import{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs}from"./core/cron.mjs";import{a as NoJobHandlerError,c as listJobQueues,d as stampJobContext,i as Job,l as registerJobContext,n as JOB_DISPATCHER,o as Process,r as JOB_META,s as listJobHandlers,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-d2j_7_9R.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-V3Xlgvgk.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-Ce2FkkeT.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-DaYy5tKw.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-QfmGMX4-.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-BgxacQbc.mjs";import{t as runContributors}from"./contributor-runner-DmHsL9iD.mjs";import{_ as MountCycleError,a as HealthController,c as defineCheck,d as onPackage,f as ERROR_CHANNEL,g as MissingMountDepError,h as DuplicateMountNameError,i as HEALTH_PROBE,l as allOf,m as RESPONSE_CHANNEL,n as Application,o as healthModule,p as HANDLER_CHANNEL,s as StartupCheckError,t as APPLICATION,u as onEnv,v as mountSort}from"./application-2cqnmnMR.mjs";import{t as defineAdapter}from"./define-adapter-By20TI53.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-BRcI3gmZ.mjs";import{n as randomHex,t as matchesBearer}from"./web-crypto-Dx8Nmh16.mjs";import{n as RAW_BODY}from"./body-policy-BkjZt30w.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as getRequestStore,i as waitUntil,o as getRequestValue,r as settleBackgroundWork,s as requestStore}from"./background-X_AU4qmI.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware}from"./request-scope-B1GH3d99.mjs";import{a as originsOf,i as loadSettings,n as defineSettings}from"./settings-hE0ewJKF.mjs";import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"./decorate-8MLQUvoW.mjs";import{a as reply,i as isRespondable,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-CtSYYFK5.mjs";import{a as materializeRouter,i as expressRuntime,n as buildRoutes}from"./express-lazy-BixrSsYx.mjs";import{a as evaluatePreconditions,i as stringifyJson,t as RequestContext}from"./context-CfGBpRlD.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-CF5TB3dt.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-BIGYogvJ.mjs";import{defaultValidationError,validate}from"./http/middleware/validate.mjs";import{csrf,csrfGuard}from"./http/middleware/csrf.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{breachPadding}from"./http/middleware/breach-padding.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-u0V_K-2O.mjs";import{session}from"./http/middleware/session.mjs";import{o as resolveMimeTypes}from"./upload-config-ikC1nZgF.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-DeWWBNz5.mjs";import{createHmac,randomBytes,scrypt,timingSafeEqual}from"node:crypto";import{monitorEventLoopDelay}from"node:perf_hooks";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=/* @__PURE__ */ new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}const inFlight=/* @__PURE__ */ new Map,PERSONAL=[`authorization`,`proxy-authorization`,`x-api-key`,`cookie`];function CacheResponse(options){let maxAgeMs=options.maxAge*1e3,swrMs=(options.swr??0)*1e3,varies=(options.varies??[]).map(h=>h.toLowerCase());return(target,propertyKey,descriptor)=>{let original=descriptor.value,owner=typeof target==`function`?target.name:target.constructor?.name,prefix=typeof options.key==`string`?options.key:`kick:response:${owner??`anonymous`}.${String(propertyKey)}`,keyOf=typeof options.key==`function`?options.key:void 0;return descriptor.value=async function(ctx,...rest){let req=ctx.req,method=String(req.method??`GET`).toUpperCase(),headers=ctx.headers;if(method!==`GET`&&method!==`HEAD`||maxAgeMs+swrMs<=0)return original.call(this,ctx,...rest);let identity;if(keyOf){let chosen=keyOf(ctx);if(chosen===null)return original.call(this,ctx,...rest);identity=chosen}else{if(PERSONAL.some(h=>headers[h]!==void 0&&!varies.includes(h))||ctx.user!==void 0&&!varies.some(h=>PERSONAL.includes(h)))return original.call(this,ctx,...rest);let host=String(headers.host??``);if(!VALID_HOST.test(host))return original.call(this,ctx,...rest);identity=JSON.stringify([host.toLowerCase(),req.originalUrl??req.url??``])}let varied=varies.map(h=>`${h}=${String(headers[h]??``)}`).join(`&`),key=`${prefix}:${identity}|${varied}`,provider=getCacheProvider(),run=()=>record(original,this,ctx,rest),build=()=>buildOnce(key,run),store=async({recorded,shared})=>{if(!shared&&recorded&&cacheable(recorded)){let entry={recorded,storedAt:Date.now()};await provider.set(key,entry,maxAgeMs+swrMs)}},entry=await provider.get(key);if(entry){let age=Date.now()-entry.storedAt;if(age<maxAgeMs+swrMs){age>=maxAgeMs&&waitUntil(build().then(store)),replay(ctx,entry.recorded);return}}let built=await build();await store(built);let recorded=built.recorded;built.shared&&!(recorded&&cacheable(recorded))&&(recorded=await run()),recorded&&replay(ctx,recorded)},descriptor}}const VALID_HOST=/^(?:\[[0-9a-f:.]+\]|[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::\d{1,5})?$/i;async function buildOnce(key,run){let pending=inFlight.get(key);if(pending)return{recorded:await pending,shared:!0};let load=run().finally(()=>inFlight.delete(key));return inFlight.set(key,load),{recorded:await load,shared:!1}}function cacheable(recorded){return recorded.status===200&&!(`set-cookie`in recorded.headers)&&!recorded.native}async function record(handler,self,ctx,rest){let recorded={status:200,headers:{},body:``},sent=!1,finish=body=>{body instanceof Uint8Array?(recorded.body=toBase64(body),recorded.binary=!0):typeof body==`string`?recorded.body=body:body!=null&&(recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(body)),sent=!0},unsupported=what=>()=>{throw Error(`@CacheResponse: the handler called ${what}. A cached route answers with ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.`)},response={status(code){return recorded.status=code,response},type(contentType){return recorded.type=contentType,response},json(data){return recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(data),sent=!0,response},send(data){return finish(data),response},end(data){return finish(data),response},setHeader(name,value){recorded.headers[name.toLowerCase()]=Array.isArray(value)?[...value]:String(value)},get headersSent(){return sent},once(){},render:unsupported(`render()`),writeHead:unsupported(`writeHead()`),flushHeaders:unsupported(`flushHeaders()`),write:unsupported(`write()`)},native=new Proxy(ctx.res,{get(target,prop){let value=Reflect.get(target,prop,target);return typeof value==`function`?(...args)=>(recorded.native=!0,value.apply(target,args)):value},set(target,prop,value){return recorded.native=!0,Reflect.set(target,prop,value,target)}}),recordingCtx=Object.create(ctx,{_response:{value:response},res:{value:native}}),result=await handler.call(self,recordingCtx,...rest);return sent||await applyHandlerResult(recordingCtx,result),sent?recorded:null}function replay(ctx,recorded){if(ctx._response.headersSent)return;for(let[name,value]of Object.entries(recorded.headers))name!==`etag`&&name!==`content-type`&&ctx.setHeader(name,value);if(recorded.status===200){let etag=recorded.headers.etag??weakEtag(recorded.body);if(ctx.conditional({etag}))return}let options={status:recorded.status,type:recorded.type??`text/plain; charset=utf-8`};ctx.send(recorded.binary?fromBase64(recorded.body):recorded.body,options)}function weakEtag(body){let hash=2166136261;for(let i=0;i<body.length;i++)hash^=body.charCodeAt(i),hash=Math.imul(hash,16777619);return`W/"${body.length.toString(16)}-${(hash>>>0).toString(16)}"`}function toBase64(bytes){let binary=``;for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}function fromBase64(text){let binary=atob(text),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}const DEFAULT_BUCKETS=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],label=value=>value.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`
12
12
  `,`\\n`);var RequestHistogram=class{series=/* @__PURE__ */ new Map;buckets;constructor(buckets=DEFAULT_BUCKETS){if(buckets.length===0||buckets.some(b=>!Number.isFinite(b)||b<=0))throw Error(`metrics: buckets must be finite positive numbers (seconds)`);this.buckets=[...new Set(buckets)].toSorted((a,b)=>a-b)}observe(info){let labels=`method="${label(knownMethod(info.method))}",route="${label(info.route??`unmatched`)}",status="${info.status}"`,series=this.series.get(labels);series||(series={labels,counts:this.buckets.map(()=>0),sum:0,count:0},this.series.set(labels,series));let seconds=info.durationMs/1e3;for(let[i,bound]of this.buckets.entries())seconds<=bound&&series.counts[i]++;series.sum+=seconds,series.count++}render(){let name=`http_request_duration_seconds`,lines=[`# HELP ${name} Time to answer an HTTP request, by route pattern.`,`# TYPE ${name} histogram`];for(let s of this.series.values()){for(let[i,bound]of this.buckets.entries())lines.push(`${name}_bucket{${s.labels},le="${bound}"} ${s.counts[i]}`);lines.push(`${name}_bucket{${s.labels},le="+Inf"} ${s.count}`),lines.push(`${name}_sum{${s.labels}} ${s.sum}`),lines.push(`${name}_count{${s.labels}} ${s.count}`)}return lines.join(`
13
13
  `)}};const METHODS=/* @__PURE__ */ new Set([`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`,`QUERY`]);function knownMethod(method){let upper=method.toUpperCase();return METHODS.has(upper)?upper:`OTHER`}function gauge(name,help,value){return`# HELP ${name} ${help}\n# TYPE ${name} gauge\n${name} ${value}`}function metricsAdapter(options={}){let path=options.path??`/metrics`,histogram=new RequestHistogram(options.buckets??DEFAULT_BUCKETS),loop,render=()=>{let memory=process.memoryUsage(),lag=loop&&loop.count>0?loop.mean/1e9:0;return[histogram.render(),gauge(`process_resident_memory_bytes`,`Resident set size.`,memory.rss),gauge(`nodejs_heap_used_bytes`,`V8 heap in use.`,memory.heapUsed),gauge(`nodejs_heap_total_bytes`,`V8 heap allocated.`,memory.heapTotal),gauge(`nodejs_eventloop_lag_seconds`,`Mean event-loop delay since the last scrape.`,lag),gauge(`process_uptime_seconds`,`Seconds since the process started.`,process.uptime())].join(`
14
14
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  function isProduction(){let env=typeof process<`u`?process.env?.NODE_ENV:void 0;return env!==`development`&&env!==`test`}export{isProduction as t};
12
- //# sourceMappingURL=is-production-C7DJ7c5k.mjs.map
12
+ //# sourceMappingURL=is-production-CMJW948J.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"is-production-C7DJ7c5k.mjs","names":[],"sources":["../src/core/is-production.ts"],"sourcesContent":["/**\n * Whether the process should behave as production — true unless `NODE_ENV`\n * is exactly `development` or `test`. Fails closed: an unset (or any other)\n * `NODE_ENV` counts as production, so a deploy that forgets to set it still\n * gets secure cookies, opaque 500s and no dev-only aids.\n *\n * Read per call, not at module scope — tests and late config may set\n * `NODE_ENV` after import — and guarded, since edge runtimes may not expose\n * `process`. Reads `process.env` rather than `getEnv()`: the framework must\n * not depend on the app's env schema (or on zod) to decide this.\n */\nexport function isProduction(): boolean {\n const env = typeof process !== 'undefined' ? process.env?.NODE_ENV : undefined\n return env !== 'development' && env !== 'test'\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgB,cAAwB,CACtC,IAAM,IAAM,OAAO,QAAY,IAAc,QAAQ,KAAK,SAAW,IAAA,GACrE,OAAO,MAAQ,eAAiB,MAAQ,MAC1C"}
1
+ {"version":3,"file":"is-production-CMJW948J.mjs","names":[],"sources":["../src/core/is-production.ts"],"sourcesContent":["/**\n * Whether the process should behave as production — true unless `NODE_ENV`\n * is exactly `development` or `test`. Fails closed: an unset (or any other)\n * `NODE_ENV` counts as production, so a deploy that forgets to set it still\n * gets secure cookies, opaque 500s and no dev-only aids.\n *\n * Read per call, not at module scope — tests and late config may set\n * `NODE_ENV` after import — and guarded, since edge runtimes may not expose\n * `process`. Reads `process.env` rather than `getEnv()`: the framework must\n * not depend on the app's env schema (or on zod) to decide this.\n */\nexport function isProduction(): boolean {\n const env = typeof process !== 'undefined' ? process.env?.NODE_ENV : undefined\n return env !== 'development' && env !== 'test'\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgB,cAAwB,CACtC,IAAM,IAAM,OAAO,QAAY,IAAc,QAAQ,KAAK,SAAW,IAAA,GACrE,OAAO,MAAQ,eAAiB,MAAQ,MAC1C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"./core/logger.mjs";import{n as createToken}from"./token-tL_r-ZPP.mjs";import{c as pushClassMeta,n as getClassMetaOrUndefined,t as getClassMeta,u as setClassMeta}from"./metadata-Ck5f9CNm.mjs";import{Service}from"./core/decorators.mjs";import{r as reportError}from"./observers-BV435fEL.mjs";const log=createLogger(`KickJobs`),JOB_META={JOB:`kick/queue/job`,PROCESS:`kick/queue/process`},jobClasses=/* @__PURE__ */ new Map;function Job(queue){return target=>{Service()(target),setClassMeta(JOB_META.JOB,queue,target),jobClasses.set(target.name,target)}}function Process(jobName){return(target,propertyKey)=>{pushClassMeta(JOB_META.PROCESS,target.constructor,{handlerName:propertyKey,jobName})}}function listJobHandlers(container){let handlers=[];for(let target of jobClasses.values()){if(!container.has(target))continue;let queue=getClassMetaOrUndefined(JOB_META.JOB,target);if(queue===void 0)continue;let processes=getClassMeta(JOB_META.PROCESS,target,[]);processes.length===0&&log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`);for(let process of processes)handlers.push({...process,queue,target})}return handlers}function listJobQueues(container){return[...new Set(listJobHandlers(container).map(h=>h.queue))]}var NoJobHandlerError=class extends Error{queue;jobName;constructor(queue,jobName){super(`No @Process handler for job "${jobName}" on queue "${queue}"`),this.queue=queue,this.jobName=jobName,this.name=`NoJobHandlerError`}};async function runJob(container,queue,job,report={}){let handlers=listJobHandlers(container).filter(h=>h.queue===queue),handler=handlers.find(h=>h.jobName===job.name)??handlers.find(h=>h.jobName===void 0);try{if(!handler)throw new NoJobHandlerError(queue,job.name);let instance=container.resolve(handler.target);return await withJobContext(job,()=>instance[handler.handlerName](job))()}catch(err){throw log.error({err},`Job ${queue}/${job.name} failed`),reportError(err,{source:`job`,context:{queue,job:job.name,id:job.id,...report}}),err}}const JOB_CONTEXT_FIELD=`__kickContext`,jobContextCarriers=/* @__PURE__ */ new Map;function registerJobContext(carrier){jobContextCarriers.set(carrier.key,carrier)}const isPlainObject=v=>!!v&&typeof v==`object`&&Object.getPrototypeOf(v)===Object.prototype;function stampJobContext(data){if(!isPlainObject(data))return data;let{[JOB_CONTEXT_FIELD]:_untrusted,...rest}=data,context={};for(let[key,carrier]of jobContextCarriers){let value=carrier.capture();value!==void 0&&(context[key]=value)}return Object.keys(context).length>0?{...rest,[JOB_CONTEXT_FIELD]:context}:rest}function withJobContext(job,run){let data=job.data;if(!isPlainObject(data)||!(`__kickContext`in data))return run;let context=data[JOB_CONTEXT_FIELD];if(delete data[JOB_CONTEXT_FIELD],!isPlainObject(context))return run;let wrapped=run;for(let[key,value]of Object.entries(context)){let carrier=jobContextCarriers.get(key);if(!carrier)continue;let inner=wrapped;wrapped=()=>carrier.restore(value,inner)}return wrapped}const JOB_DISPATCHER=createToken(`kick/jobs/Dispatcher`);export{NoJobHandlerError as a,listJobQueues as c,stampJobContext as d,Job as i,registerJobContext as l,JOB_DISPATCHER as n,Process as o,JOB_META as r,listJobHandlers as s,JOB_CONTEXT_FIELD as t,runJob as u};
12
- //# sourceMappingURL=jobs-Bdqz5n21.mjs.map
11
+ import{createLogger}from"./core/logger.mjs";import{n as createToken}from"./token-DNQnEuMJ.mjs";import{c as pushClassMeta,n as getClassMetaOrUndefined,t as getClassMeta,u as setClassMeta}from"./metadata-c1TNXrm_.mjs";import{Service}from"./core/decorators.mjs";import{r as reportError}from"./observers-vX5EpqCX.mjs";const log=createLogger(`KickJobs`),JOB_META={JOB:`kick/queue/job`,PROCESS:`kick/queue/process`},jobClasses=/* @__PURE__ */ new Map;function Job(queue){return target=>{Service()(target),setClassMeta(JOB_META.JOB,queue,target),jobClasses.set(target.name,target)}}function Process(jobName){return(target,propertyKey)=>{pushClassMeta(JOB_META.PROCESS,target.constructor,{handlerName:propertyKey,jobName})}}function listJobHandlers(container){let handlers=[];for(let target of jobClasses.values()){if(!container.has(target))continue;let queue=getClassMetaOrUndefined(JOB_META.JOB,target);if(queue===void 0)continue;let processes=getClassMeta(JOB_META.PROCESS,target,[]);processes.length===0&&log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`);for(let process of processes)handlers.push({...process,queue,target})}return handlers}function listJobQueues(container){return[...new Set(listJobHandlers(container).map(h=>h.queue))]}var NoJobHandlerError=class extends Error{queue;jobName;constructor(queue,jobName){super(`No @Process handler for job "${jobName}" on queue "${queue}"`),this.queue=queue,this.jobName=jobName,this.name=`NoJobHandlerError`}};async function runJob(container,queue,job,report={}){let handlers=listJobHandlers(container).filter(h=>h.queue===queue),handler=handlers.find(h=>h.jobName===job.name)??handlers.find(h=>h.jobName===void 0);try{if(!handler)throw new NoJobHandlerError(queue,job.name);let instance=container.resolve(handler.target);return await withJobContext(job,()=>instance[handler.handlerName](job))()}catch(err){throw log.error({err},`Job ${queue}/${job.name} failed`),reportError(err,{source:`job`,context:{queue,job:job.name,id:job.id,...report}}),err}}const JOB_CONTEXT_FIELD=`__kickContext`,jobContextCarriers=/* @__PURE__ */ new Map;function registerJobContext(carrier){jobContextCarriers.set(carrier.key,carrier)}const isPlainObject=v=>!!v&&typeof v==`object`&&Object.getPrototypeOf(v)===Object.prototype;function stampJobContext(data){if(!isPlainObject(data))return data;let{[JOB_CONTEXT_FIELD]:_untrusted,...rest}=data,context={};for(let[key,carrier]of jobContextCarriers){let value=carrier.capture();value!==void 0&&(context[key]=value)}return Object.keys(context).length>0?{...rest,[JOB_CONTEXT_FIELD]:context}:rest}function withJobContext(job,run){let data=job.data;if(!isPlainObject(data)||!(`__kickContext`in data))return run;let context=data[JOB_CONTEXT_FIELD];if(delete data[JOB_CONTEXT_FIELD],!isPlainObject(context))return run;let wrapped=run;for(let[key,value]of Object.entries(context)){let carrier=jobContextCarriers.get(key);if(!carrier)continue;let inner=wrapped;wrapped=()=>carrier.restore(value,inner)}return wrapped}const JOB_DISPATCHER=createToken(`kick/jobs/Dispatcher`);export{NoJobHandlerError as a,listJobQueues as c,stampJobContext as d,Job as i,registerJobContext as l,JOB_DISPATCHER as n,Process as o,JOB_META as r,listJobHandlers as s,JOB_CONTEXT_FIELD as t,runJob as u};
12
+ //# sourceMappingURL=jobs-d2j_7_9R.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"jobs-Bdqz5n21.mjs","names":[],"sources":["../src/core/jobs.ts"],"sourcesContent":["/**\n * Background jobs, with whatever runs them.\n *\n * `@Job(queue)` / `@Process(name)` only record which method handles which\n * job — the same way `@Cron` only records a schedule. Any job tool turns that\n * into running code in a few lines: subscribe to each queue from\n * {@link listJobQueues}, and hand every job it receives to {@link runJob}.\n *\n * @Job('email')\n * export class EmailJobs {\n * @Process('welcome')\n * async welcome(job: JobLike<{ to: string }>) { await sendWelcome(job.data.to) }\n * }\n *\n * Enqueueing goes through {@link JOB_DISPATCHER}, which the active adapter\n * provides — code that dispatches never names the tool.\n *\n * `@forinda/kickjs-queue` ships a BullMQ adapter (plus RabbitMQ / Kafka /\n * Redis pub-sub providers); the web entry's `queue()` runs Cloudflare Queues.\n */\nimport { Service } from './decorators'\nimport { getClassMeta, getClassMetaOrUndefined, pushClassMeta, setClassMeta } from './metadata'\nimport { reportError } from './observers'\nimport { createLogger } from './logger'\nimport { createToken } from './token'\n\nconst log = createLogger('KickJobs')\n\n/** Metadata keys — the same ones `@forinda/kickjs-queue` used, so existing readers keep working. */\nexport const JOB_META = {\n JOB: 'kick/queue/job',\n PROCESS: 'kick/queue/process',\n} as const\n\n/** What a `@Process` method records. */\nexport interface ProcessDefinition {\n /** Method name on the class. */\n handlerName: string\n /** Job name it handles; `undefined` handles every job in the queue. */\n jobName?: string\n}\n\n/**\n * The least a job tool hands over. Runners pass their own job object through\n * unchanged — BullMQ's `Job`, a Cloudflare message — so a handler can still\n * reach tool-specific fields (`job.attemptsMade`, `job.updateProgress()`).\n */\nexport interface JobLike<Data = unknown> {\n name: string\n data: Data\n id?: string\n}\n\n/**\n * Every `@Job` class, keyed by class name like the DI registry: an HMR\n * re-evaluation replaces the old class instead of leaving both subscribed.\n */\nconst jobClasses = new Map<string, Function>()\n\n/** Mark a class as handling jobs on `queue`. The class is a DI singleton. */\nexport function Job(queue: string): ClassDecorator {\n return (target) => {\n Service()(target)\n setClassMeta(JOB_META.JOB, queue, target)\n jobClasses.set(target.name, target)\n }\n}\n\n/** Mark a method as handling `jobName` — or, without a name, every job its queue gets. */\nexport function Process(jobName?: string): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<ProcessDefinition>(JOB_META.PROCESS, target.constructor, {\n handlerName: propertyKey as string,\n jobName,\n })\n }\n}\n\n/** One handler: its queue, job name (absent for a catch-all), class and method. */\nexport interface JobHandler extends ProcessDefinition {\n queue: string\n target: Function\n}\n\n/**\n * Every `@Process` method of a `@Job` class the container can resolve.\n * Classes it doesn't know (not in a module, or from before an HMR reload)\n * are skipped.\n */\nexport function listJobHandlers(container: { has(token: unknown): boolean }): JobHandler[] {\n const handlers: JobHandler[] = []\n for (const target of jobClasses.values()) {\n if (!container.has(target)) continue\n const queue = getClassMetaOrUndefined<string>(JOB_META.JOB, target)\n if (queue === undefined) continue\n const processes = getClassMeta<ProcessDefinition[]>(JOB_META.PROCESS, target, [])\n if (processes.length === 0) {\n log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`)\n }\n for (const process of processes) handlers.push({ ...process, queue, target })\n }\n return handlers\n}\n\n/** The queues something handles — what a runner subscribes to. */\nexport function listJobQueues(container: { has(token: unknown): boolean }): string[] {\n return [...new Set(listJobHandlers(container).map((h) => h.queue))]\n}\n\n/** Thrown when a queue receives a job no `@Process` method handles. */\nexport class NoJobHandlerError extends Error {\n constructor(\n readonly queue: string,\n readonly jobName: string,\n ) {\n super(`No @Process handler for job \"${jobName}\" on queue \"${queue}\"`)\n this.name = 'NoJobHandlerError'\n }\n}\n\n/**\n * Run one job: pick the `@Process` method for `job.name` (or the queue's\n * catch-all), resolve its class from the container and call it with `job`\n * as given. A failure is reported to the error observers (`source: 'job'`)\n * and rethrown, so the tool's own retry and dead-letter handling still\n * applies. A job nothing handles throws {@link NoJobHandlerError} rather\n * than being acknowledged and lost.\n */\nexport async function runJob(\n container: { has(token: unknown): boolean; resolve(token: unknown): unknown },\n queue: string,\n job: JobLike,\n /** Extra fields for the error report — e.g. the tool's attempt count. */\n report: Record<string, unknown> = {},\n): Promise<unknown> {\n const handlers = listJobHandlers(container).filter((h) => h.queue === queue)\n const handler =\n handlers.find((h) => h.jobName === job.name) ?? handlers.find((h) => h.jobName === undefined)\n try {\n if (!handler) throw new NoJobHandlerError(queue, job.name)\n const instance = container.resolve(handler.target) as Record<string, (j: JobLike) => unknown>\n return await withJobContext(job, () => instance[handler.handlerName]!(job))()\n } catch (err) {\n log.error({ err }, `Job ${queue}/${job.name} failed`)\n reportError(err, { source: 'job', context: { queue, job: job.name, id: job.id, ...report } })\n throw err\n }\n}\n\n/**\n * Something about where a job was dispatched from that its handler should\n * run with — the tenant, a trace id, the acting user. Captured when the job\n * is dispatched, carried in its data, and restored around the handler.\n */\nexport interface JobContextCarrier<T = unknown> {\n /** Unique: the field it travels under. */\n key: string\n /** The value to carry, or `undefined` for nothing. */\n capture(): T | undefined\n /** Run the handler with the value back in place. */\n restore<R>(value: T, run: () => R): R\n}\n\n/** The field a job's data carries its context in. Removed before the handler sees the data. */\nexport const JOB_CONTEXT_FIELD = '__kickContext'\n\nconst jobContextCarriers = new Map<string, JobContextCarrier>()\n\n/** Carry a value from dispatch to handler for every job. Registering a key again replaces it. */\nexport function registerJobContext<T>(carrier: JobContextCarrier<T>): void {\n jobContextCarriers.set(carrier.key, carrier as JobContextCarrier)\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype\n\n/**\n * `data` with the current job context added — for a {@link JobDispatcher}\n * implementation to call before enqueueing. Any `__kickContext` already in\n * `data` is removed first: only this call may set it, so a dispatcher that\n * enqueues caller-supplied data without it lets that data choose the context. Only plain-object data can carry\n * it; anything else, or nothing to carry, is returned as is.\n */\nexport function stampJobContext<Data>(data: Data): Data {\n if (!isPlainObject(data)) return data\n // Only the dispatcher's own context travels. A caller's data (a request\n // body, say) carrying the field would otherwise pick the job's tenant.\n const { [JOB_CONTEXT_FIELD]: _untrusted, ...rest } = data\n const context: Record<string, unknown> = {}\n for (const [key, carrier] of jobContextCarriers) {\n const value = carrier.capture()\n if (value !== undefined) context[key] = value\n }\n const stamped = Object.keys(context).length > 0 ? { ...rest, [JOB_CONTEXT_FIELD]: context } : rest\n return stamped as Data\n}\n\n/** Take the carried context off the job's data, and wrap `run` in every restore. */\nfunction withJobContext<R>(job: JobLike, run: () => R): () => R {\n const data = job.data\n if (!isPlainObject(data) || !(JOB_CONTEXT_FIELD in data)) return run\n const context = data[JOB_CONTEXT_FIELD]\n delete data[JOB_CONTEXT_FIELD]\n // Only an object of carrier keys is context; anything else is dropped.\n if (!isPlainObject(context)) return run\n let wrapped = run\n for (const [key, value] of Object.entries(context)) {\n const carrier = jobContextCarriers.get(key)\n if (!carrier) continue\n const inner = wrapped\n wrapped = () => carrier.restore(value, inner)\n }\n return wrapped\n}\n\n/** Enqueue a job — implemented by whichever adapter runs the jobs. */\nexport interface JobDispatcher {\n dispatch<Data = unknown>(\n queue: string,\n name: string,\n data: Data,\n options?: Record<string, unknown>,\n ): Promise<unknown>\n}\n\n/**\n * The active job dispatcher. Inject it to enqueue without naming the tool:\n * `@Inject(JOB_DISPATCHER) private jobs!: JobDispatcher`.\n */\nexport const JOB_DISPATCHER = createToken<JobDispatcher>('kick/jobs/Dispatcher')\n"],"mappings":";;;;;;;;;;0TA0BA,MAAM,IAAM,aAAa,UAAU,EAGtB,SAAW,CACtB,IAAK,iBACL,QAAS,oBACX,EAyBM,2BAAa,IAAI,IAGvB,SAAgB,IAAI,MAA+B,CACjD,MAAQ,SAAW,CACjB,QAAQ,CAAC,CAAC,MAAM,EAChB,aAAa,SAAS,IAAK,MAAO,MAAM,EACxC,WAAW,IAAI,OAAO,KAAM,MAAM,CACpC,CACF,CAGA,SAAgB,QAAQ,QAAmC,CACzD,OAAQ,OAAQ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,QAAQ,MAAO,KAAK,CAC9C,CACA,OAAO,OACT,CAgBA,MAAa,eAAiB,YAA2B,sBAAsB"}
1
+ {"version":3,"file":"jobs-d2j_7_9R.mjs","names":[],"sources":["../src/core/jobs.ts"],"sourcesContent":["/**\n * Background jobs, with whatever runs them.\n *\n * `@Job(queue)` / `@Process(name)` only record which method handles which\n * job — the same way `@Cron` only records a schedule. Any job tool turns that\n * into running code in a few lines: subscribe to each queue from\n * {@link listJobQueues}, and hand every job it receives to {@link runJob}.\n *\n * @Job('email')\n * export class EmailJobs {\n * @Process('welcome')\n * async welcome(job: JobLike<{ to: string }>) { await sendWelcome(job.data.to) }\n * }\n *\n * Enqueueing goes through {@link JOB_DISPATCHER}, which the active adapter\n * provides — code that dispatches never names the tool.\n *\n * `@forinda/kickjs-queue` ships a BullMQ adapter (plus RabbitMQ / Kafka /\n * Redis pub-sub providers); the web entry's `queue()` runs Cloudflare Queues.\n */\nimport { Service } from './decorators'\nimport { getClassMeta, getClassMetaOrUndefined, pushClassMeta, setClassMeta } from './metadata'\nimport { reportError } from './observers'\nimport { createLogger } from './logger'\nimport { createToken } from './token'\n\nconst log = createLogger('KickJobs')\n\n/** Metadata keys — the same ones `@forinda/kickjs-queue` used, so existing readers keep working. */\nexport const JOB_META = {\n JOB: 'kick/queue/job',\n PROCESS: 'kick/queue/process',\n} as const\n\n/** What a `@Process` method records. */\nexport interface ProcessDefinition {\n /** Method name on the class. */\n handlerName: string\n /** Job name it handles; `undefined` handles every job in the queue. */\n jobName?: string\n}\n\n/**\n * The least a job tool hands over. Runners pass their own job object through\n * unchanged — BullMQ's `Job`, a Cloudflare message — so a handler can still\n * reach tool-specific fields (`job.attemptsMade`, `job.updateProgress()`).\n */\nexport interface JobLike<Data = unknown> {\n name: string\n data: Data\n id?: string\n}\n\n/**\n * Every `@Job` class, keyed by class name like the DI registry: an HMR\n * re-evaluation replaces the old class instead of leaving both subscribed.\n */\nconst jobClasses = new Map<string, Function>()\n\n/** Mark a class as handling jobs on `queue`. The class is a DI singleton. */\nexport function Job(queue: string): ClassDecorator {\n return (target) => {\n Service()(target)\n setClassMeta(JOB_META.JOB, queue, target)\n jobClasses.set(target.name, target)\n }\n}\n\n/** Mark a method as handling `jobName` — or, without a name, every job its queue gets. */\nexport function Process(jobName?: string): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<ProcessDefinition>(JOB_META.PROCESS, target.constructor, {\n handlerName: propertyKey as string,\n jobName,\n })\n }\n}\n\n/** One handler: its queue, job name (absent for a catch-all), class and method. */\nexport interface JobHandler extends ProcessDefinition {\n queue: string\n target: Function\n}\n\n/**\n * Every `@Process` method of a `@Job` class the container can resolve.\n * Classes it doesn't know (not in a module, or from before an HMR reload)\n * are skipped.\n */\nexport function listJobHandlers(container: { has(token: unknown): boolean }): JobHandler[] {\n const handlers: JobHandler[] = []\n for (const target of jobClasses.values()) {\n if (!container.has(target)) continue\n const queue = getClassMetaOrUndefined<string>(JOB_META.JOB, target)\n if (queue === undefined) continue\n const processes = getClassMeta<ProcessDefinition[]>(JOB_META.PROCESS, target, [])\n if (processes.length === 0) {\n log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`)\n }\n for (const process of processes) handlers.push({ ...process, queue, target })\n }\n return handlers\n}\n\n/** The queues something handles — what a runner subscribes to. */\nexport function listJobQueues(container: { has(token: unknown): boolean }): string[] {\n return [...new Set(listJobHandlers(container).map((h) => h.queue))]\n}\n\n/** Thrown when a queue receives a job no `@Process` method handles. */\nexport class NoJobHandlerError extends Error {\n constructor(\n readonly queue: string,\n readonly jobName: string,\n ) {\n super(`No @Process handler for job \"${jobName}\" on queue \"${queue}\"`)\n this.name = 'NoJobHandlerError'\n }\n}\n\n/**\n * Run one job: pick the `@Process` method for `job.name` (or the queue's\n * catch-all), resolve its class from the container and call it with `job`\n * as given. A failure is reported to the error observers (`source: 'job'`)\n * and rethrown, so the tool's own retry and dead-letter handling still\n * applies. A job nothing handles throws {@link NoJobHandlerError} rather\n * than being acknowledged and lost.\n */\nexport async function runJob(\n container: { has(token: unknown): boolean; resolve(token: unknown): unknown },\n queue: string,\n job: JobLike,\n /** Extra fields for the error report — e.g. the tool's attempt count. */\n report: Record<string, unknown> = {},\n): Promise<unknown> {\n const handlers = listJobHandlers(container).filter((h) => h.queue === queue)\n const handler =\n handlers.find((h) => h.jobName === job.name) ?? handlers.find((h) => h.jobName === undefined)\n try {\n if (!handler) throw new NoJobHandlerError(queue, job.name)\n const instance = container.resolve(handler.target) as Record<string, (j: JobLike) => unknown>\n return await withJobContext(job, () => instance[handler.handlerName]!(job))()\n } catch (err) {\n log.error({ err }, `Job ${queue}/${job.name} failed`)\n reportError(err, { source: 'job', context: { queue, job: job.name, id: job.id, ...report } })\n throw err\n }\n}\n\n/**\n * Something about where a job was dispatched from that its handler should\n * run with — the tenant, a trace id, the acting user. Captured when the job\n * is dispatched, carried in its data, and restored around the handler.\n */\nexport interface JobContextCarrier<T = unknown> {\n /** Unique: the field it travels under. */\n key: string\n /** The value to carry, or `undefined` for nothing. */\n capture(): T | undefined\n /** Run the handler with the value back in place. */\n restore<R>(value: T, run: () => R): R\n}\n\n/** The field a job's data carries its context in. Removed before the handler sees the data. */\nexport const JOB_CONTEXT_FIELD = '__kickContext'\n\nconst jobContextCarriers = new Map<string, JobContextCarrier>()\n\n/** Carry a value from dispatch to handler for every job. Registering a key again replaces it. */\nexport function registerJobContext<T>(carrier: JobContextCarrier<T>): void {\n jobContextCarriers.set(carrier.key, carrier as JobContextCarrier)\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype\n\n/**\n * `data` with the current job context added — for a {@link JobDispatcher}\n * implementation to call before enqueueing. Any `__kickContext` already in\n * `data` is removed first: only this call may set it, so a dispatcher that\n * enqueues caller-supplied data without it lets that data choose the context. Only plain-object data can carry\n * it; anything else, or nothing to carry, is returned as is.\n */\nexport function stampJobContext<Data>(data: Data): Data {\n if (!isPlainObject(data)) return data\n // Only the dispatcher's own context travels. A caller's data (a request\n // body, say) carrying the field would otherwise pick the job's tenant.\n const { [JOB_CONTEXT_FIELD]: _untrusted, ...rest } = data\n const context: Record<string, unknown> = {}\n for (const [key, carrier] of jobContextCarriers) {\n const value = carrier.capture()\n if (value !== undefined) context[key] = value\n }\n const stamped = Object.keys(context).length > 0 ? { ...rest, [JOB_CONTEXT_FIELD]: context } : rest\n return stamped as Data\n}\n\n/** Take the carried context off the job's data, and wrap `run` in every restore. */\nfunction withJobContext<R>(job: JobLike, run: () => R): () => R {\n const data = job.data\n if (!isPlainObject(data) || !(JOB_CONTEXT_FIELD in data)) return run\n const context = data[JOB_CONTEXT_FIELD]\n delete data[JOB_CONTEXT_FIELD]\n // Only an object of carrier keys is context; anything else is dropped.\n if (!isPlainObject(context)) return run\n let wrapped = run\n for (const [key, value] of Object.entries(context)) {\n const carrier = jobContextCarriers.get(key)\n if (!carrier) continue\n const inner = wrapped\n wrapped = () => carrier.restore(value, inner)\n }\n return wrapped\n}\n\n/** Enqueue a job — implemented by whichever adapter runs the jobs. */\nexport interface JobDispatcher {\n dispatch<Data = unknown>(\n queue: string,\n name: string,\n data: Data,\n options?: Record<string, unknown>,\n ): Promise<unknown>\n}\n\n/**\n * The active job dispatcher. Inject it to enqueue without naming the tool:\n * `@Inject(JOB_DISPATCHER) private jobs!: JobDispatcher`.\n */\nexport const JOB_DISPATCHER = createToken<JobDispatcher>('kick/jobs/Dispatcher')\n"],"mappings":";;;;;;;;;;0TA0BA,MAAM,IAAM,aAAa,UAAU,EAGtB,SAAW,CACtB,IAAK,iBACL,QAAS,oBACX,EAyBM,2BAAa,IAAI,IAGvB,SAAgB,IAAI,MAA+B,CACjD,MAAQ,SAAW,CACjB,QAAQ,CAAC,CAAC,MAAM,EAChB,aAAa,SAAS,IAAK,MAAO,MAAM,EACxC,WAAW,IAAI,OAAO,KAAM,MAAM,CACpC,CACF,CAGA,SAAgB,QAAQ,QAAmC,CACzD,OAAQ,OAAQ,cAA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Q,MAAO,KAAK,CAC9C,CACA,OAAO,OACT,CAgBA,MAAa,eAAiB,YAA2B,sBAAsB"}
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { x as MiddlewareHandler } from "./decorators-DxNb5mWw.mjs";
3
- import { E as RequestContext, x as RuntimeResponse } from "./adapter-B0Q8PzQ3.mjs";
3
+ import { E as RequestContext, x as RuntimeResponse } from "./adapter-DLjn8q0c.mjs";
4
4
  import { d as RouteFlagTest } from "./route-flag-B1lQht6v.mjs";
5
5
  import { a as SessionStore, r as SessionData } from "./session-8uNRCplB.mjs";
6
6
  import { r as RateLimitStore } from "./rate-limit-DQDk6bAH.mjs";
@@ -387,4 +387,4 @@ declare class KvSessionStore implements SessionStore {
387
387
  }
388
388
  //#endregion
389
389
  export { NoJobHandlerError as A, JOB_DISPATCHER as C, JobDispatcher as D, JobContextCarrier as E, registerJobContext as F, runJob as I, stampJobContext as L, ProcessDefinition as M, listJobHandlers as N, JobHandler as O, listJobQueues as P, JOB_CONTEXT_FIELD as S, Job as T, Respondable as _, KvSessionStoreOptions as a, isRespondable as b, matchesBearer as c, waitUntil as d, InferHandlerResponse as f, ReplyOptions as g, ReplyHeaders as h, KvSessionStore as i, Process as j, JobLike as k, PlatformContext as l, Reply as m, KvRateLimitStore as n, RateLimitGuardOptions as o, RESPOND as p, KvRateLimitStoreOptions as r, rateLimitGuard as s, KvLike as t, settleBackgroundWork as u, applyHandlerResult as v, JOB_META as w, reply as x, isReply as y };
390
- //# sourceMappingURL=kv-stores-CISRYh_H.d.mts.map
390
+ //# sourceMappingURL=kv-stores-DJBnGQsJ.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"kv-stores-CISRYh_H.d.mts","names":[],"sources":["../src/core/jobs.ts","../src/http/reply.ts","../src/http/background.ts","../src/core/web-crypto.ts","../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"mappings":";;;;;;;;cA6Ba;WACX;WACA;;;UAIe;;EAEf;;EAEA;;;;;;;U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;;;iBAqBxC,mBACd,KAAK,gBACL,4BACW;;;;;;;;;;;;;;;;;iBClIG,UAAU,SAAS;;;;;iBAiBb,wBAAwB;;;;;;UAc7B;EACf,WAAW,SAAS;;;;;;;;;;;iBCrCN,cAAc,iBAAiB;;;UCvB9B;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;EAuBA,gBAAgB,KAAK;;EAErB;;;;;;EAMA,QAAQ;;EAER,QAAQ,KAAK;;;;;;;;;;;;;;;;EAgBb,aAAa;;;;;;;;;;;;;;;;;iBAoDC,eAAe,UAAS,wBAA6B;;;;;;;;;;;;;;;;;;;UCnGpD;EACf,IAAI,cAAc;EAClB,IAAI,aAAa,eAAe;IAAY;MAA2B;EACvE,OAAO,cAAc;;UAQN;;EAEf;;EAEA;;;;;;;;;;;;cAaW,4BAA4B;mBAKpB;mBAJF;mBACA;EAEjB,YACmB,IAAI,QACrB,SAAS;EAML,UAAU,cAAc;IAAU;IAAmB,WAAW;;EAahE,UAAU,cAAc;EAQxB,MAAM,cAAc;UAIZ;UAUA;;UAOC;;EAEf;;;;;;;;;;;;cAaW,0BAA0B;mBAIlB;mBAHF;EAEjB,YACmB,IAAI,QACrB,UAAS;EAKL,IAAI,cAAc,QAAQ;EAU1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EAMrD,QAAQ,cAAc;EAItB,MAAM,aAAa,iBAAiB"}
1
+ {"version":3,"file":"kv-stores-DJBnGQsJ.d.mts","names":[],"sources":["../src/core/jobs.ts","../src/http/reply.ts","../src/http/background.ts","../src/core/web-crypto.ts","../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"mappings":";;;;;;;;cA6Ba;WACX;WACA;;;UAIe;;EAEf;;EAEA;;;;;;;UAQe,QAAQ;EACvB;EACA,MAAM;EACN;;;iBAUc,IAAI,gBAAgB;;iBASpB,QAAQ,mBAAmB;;UAU1B,mBAAmB;EAClC;EACA,QAAQ;;;;;;;iBAQM,gBAAgB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;iBCrCN,cAAc,iBAAiB;;;UCvB9B;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;EAuBA,gBAAgB,KAAK;;EAErB;;;;;;EAMA,QAAQ;;EAER,QAAQ,KAAK;;;;;;;;;;;;;;;;EAgBb,aAAa;;;;;;;;;;;;;;;;;iBAoDC,eAAe,UAAS,wBAA6B;;;;;;;;;;;;;;;;;;;UCnGpD;EACf,IAAI,cAAc;EAClB,IAAI,aAAa,eAAe;IAAY;MAA2B;EACvE,OAAO,cAAc;;UAQN;;EAEf;;EAEA;;;;;;;;;;;;cAaW,4BAA4B;mBAKpB;mBAJF;mBACA;EAEjB,YACmB,IAAI,QACrB,SAAS;EAML,UAAU,cAAc;IAAU;IAAmB,WAAW;;EAahE,UAAU,cAAc;EAQxB,MAAM,cAAc;UAIZ;UAUA;;UAOC;;EAEf;;;;;;;;;;;;cAaW,0BAA0B;mBAIlB;mBAHF;EAEjB,YACmB,IAAI,QACrB,UAAS;EAKL,IAAI,cAAc,QAAQ;EAU1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EAMrD,QAAQ,cAAc;EAItB,MAAM,aAAa,iBAAiB"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as assertFlagTest,s as matchesFlagTest}from"./route-flag-Dm1NxMbJ.mjs";import{t as BoundedCounters}from"./bounded-counters-BMHzTpuZ.mjs";var LazyMemoryStore=class{counters;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit)}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function defaultKey(ctx){return ctx.ip??`global`}function rateLimitGuard(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??defaultKey,sendHeaders=options.headers??!0,store=options.store??new LazyMemoryStore(windowMs,max),exemptWhen=options.exemptWhen;return exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimitGuard({ exemptWhen })`),async(ctx,next)=>{if(options.skip?.(ctx)||exemptWhen!==void 0&&matchesFlagTest(exemptWhen,ctx.route?.flags,ctx.route))return next();let{totalHits,resetTime}=await store.increment(keyGenerator(ctx)),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(ctx.setHeader(`X-RateLimit-Limit`,String(max)),ctx.setHeader(`X-RateLimit-Remaining`,String(remaining)),ctx.setHeader(`X-RateLimit-Reset`,String(Math.ceil(resetTime.getTime()/1e3)))),totalHits>max){let retryAfter=Math.max(1,Math.ceil((resetTime.getTime()-Date.now())/1e3));sendHeaders&&ctx.setHeader(`Retry-After`,String(retryAfter)),ctx.json({message},statusCode)}else next()}}function kvTtlSeconds(ms){return Math.max(60,Math.ceil(ms/1e3))}var KvRateLimitStore=class{kv;prefix;windowMs;constructor(kv,options){this.kv=kv,this.windowMs=options.windowMs,this.prefix=options.prefix??`rl:`}async increment(key){let now=Date.now(),entry=await this.read(key);if(entry&&entry.reset>now)return entry.hits++,await this.write(key,entry),{totalHits:entry.hits,resetTime:new Date(entry.reset)};let fresh={hits:1,reset:now+this.windowMs};return await this.write(key,fresh),{totalHits:1,resetTime:new Date(fresh.reset)}}async decrement(key){let entry=await this.read(key);entry&&entry.hits>0&&(entry.hits--,await this.write(key,entry))}async reset(key){await this.kv.delete(this.prefix+key)}async read(key){let raw=await this.kv.get(this.prefix+key);if(raw===null)return null;try{return JSON.parse(raw)}catch{return null}}async write(key,entry){await this.kv.put(this.prefix+key,JSON.stringify(entry),{expirationTtl:kvTtlSeconds(Math.max(entry.reset-Date.now(),1e3))})}},KvSessionStore=class{kv;prefix;constructor(kv,options={}){this.kv=kv,this.prefix=options.prefix??`sess:`}async get(sid){let raw=await this.kv.get(this.prefix+sid);if(raw===null)return null;try{return JSON.parse(raw)}catch{return null}}async set(sid,data,maxAge){await this.kv.put(this.prefix+sid,JSON.stringify(data),{expirationTtl:kvTtlSeconds(maxAge)})}async destroy(sid){await this.kv.delete(this.prefix+sid)}async touch(sid,maxAge){let data=await this.get(sid);data!==null&&await this.set(sid,data,maxAge)}};export{KvSessionStore as n,rateLimitGuard as r,KvRateLimitStore as t};
12
- //# sourceMappingURL=kv-stores-BM5Fcds2.mjs.map
11
+ import{n as assertFlagTest,s as matchesFlagTest}from"./route-flag-Ce2FkkeT.mjs";import{t as BoundedCounters}from"./bounded-counters-BdHZ2tZ9.mjs";var LazyMemoryStore=class{counters;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit)}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function defaultKey(ctx){return ctx.ip??`global`}function rateLimitGuard(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??defaultKey,sendHeaders=options.headers??!0,store=options.store??new LazyMemoryStore(windowMs,max),exemptWhen=options.exemptWhen;return exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimitGuard({ exemptWhen })`),async(ctx,next)=>{if(options.skip?.(ctx)||exemptWhen!==void 0&&matchesFlagTest(exemptWhen,ctx.route?.flags,ctx.route))return next();let{totalHits,resetTime}=await store.increment(keyGenerator(ctx)),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(ctx.setHeader(`X-RateLimit-Limit`,String(max)),ctx.setHeader(`X-RateLimit-Remaining`,String(remaining)),ctx.setHeader(`X-RateLimit-Reset`,String(Math.ceil(resetTime.getTime()/1e3)))),totalHits>max){let retryAfter=Math.max(1,Math.ceil((resetTime.getTime()-Date.now())/1e3));sendHeaders&&ctx.setHeader(`Retry-After`,String(retryAfter)),ctx.json({message},statusCode)}else next()}}function kvTtlSeconds(ms){return Math.max(60,Math.ceil(ms/1e3))}var KvRateLimitStore=class{kv;prefix;windowMs;constructor(kv,options){this.kv=kv,this.windowMs=options.windowMs,this.prefix=options.prefix??`rl:`}async increment(key){let now=Date.now(),entry=await this.read(key);if(entry&&entry.reset>now)return entry.hits++,await this.write(key,entry),{totalHits:entry.hits,resetTime:new Date(entry.reset)};let fresh={hits:1,reset:now+this.windowMs};return await this.write(key,fresh),{totalHits:1,resetTime:new Date(fresh.reset)}}async decrement(key){let entry=await this.read(key);entry&&entry.hits>0&&(entry.hits--,await this.write(key,entry))}async reset(key){await this.kv.delete(this.prefix+key)}async read(key){let raw=await this.kv.get(this.prefix+key);if(raw===null)return null;try{return JSON.parse(raw)}catch{return null}}async write(key,entry){await this.kv.put(this.prefix+key,JSON.stringify(entry),{expirationTtl:kvTtlSeconds(Math.max(entry.reset-Date.now(),1e3))})}},KvSessionStore=class{kv;prefix;constructor(kv,options={}){this.kv=kv,this.prefix=options.prefix??`sess:`}async get(sid){let raw=await this.kv.get(this.prefix+sid);if(raw===null)return null;try{return JSON.parse(raw)}catch{return null}}async set(sid,data,maxAge){await this.kv.put(this.prefix+sid,JSON.stringify(data),{expirationTtl:kvTtlSeconds(maxAge)})}async destroy(sid){await this.kv.delete(this.prefix+sid)}async touch(sid,maxAge){let data=await this.get(sid);data!==null&&await this.set(sid,data,maxAge)}};export{KvSessionStore as n,rateLimitGuard as r,KvRateLimitStore as t};
12
+ //# sourceMappingURL=kv-stores-u0V_K-2O.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"kv-stores-BM5Fcds2.mjs","names":[],"sources":["../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"sourcesContent":["// Ctx-style rate limiter — runs on BOTH pipelines: the node runtimes (via\n// `@Middleware()` / class middleware) and the `@forinda/kickjs/web` fetch\n// entry (via `@Middleware()` or `createWebApp({ middleware })`), unlike the\n// connect-style `rateLimit()` which is node-only. Zero runtime imports —\n// part of the edge purity graph.\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport type { RateLimitStore } from './rate-limit'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitGuardOptions {\n /** Maximum number of requests per window (default: 100). */\n max?: number\n /** Time window in milliseconds (default: 60_000). */\n windowMs?: number\n /** Response message when the limit is exceeded (default: 'Too Many Requests'). */\n message?: string\n /** HTTP status code when the limit is exceeded (default: 429). */\n statusCode?: number\n /**\n * Rate-limit key per request. Defaults to `ctx.ip`, falling back to\n * `'global'`. Return a user/tenant id here for authenticated quotas.\n *\n * ::: warning Behind a proxy, configure `trustProxy` or every client shares\n * one bucket\n * On a node runtime `ctx.ip` is the runtime's vetted client address —\n * Express derives it from `trust proxy`, Fastify from `trustProxy`. Without\n * that setting it is the SOCKET address, which behind a load balancer or\n * Cloudflare is the proxy's, so every caller lands in the same bucket and one\n * noisy client exhausts the allowance for everyone.\n *\n * `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are\n * deliberately not consulted here: `x-forwarded-for` is client-controllable\n * unless a proxy overwrites it, so trusting it unconditionally would let a\n * direct caller mint a fresh allowance per request by varying the header —\n * evading the limit rather than enforcing it. The header chain\n * (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the\n * `@forinda/kickjs/web` edge entry, where there is no socket and the platform\n * has already terminated the connection.\n * :::\n */\n keyGenerator?: (ctx: RequestContext) => string\n /** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */\n headers?: boolean\n /**\n * Counter backend. Defaults to a per-isolate in-memory map — fine for a\n * single node process, useless on edge where isolates recycle: pass a\n * `KvRateLimitStore` (or Redis-backed store) there.\n */\n store?: RateLimitStore\n /** Skip limiting for a request (health checks, allowlists). */\n skip?: (ctx: RequestContext) => boolean\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate. Declared on the route rather than restated as a\n * path here, so it cannot drift when `apiPrefix` or a module's `version`\n * changes:\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })\n * ```\n *\n * Only meaningful where a route has been matched — as `@Middleware()` on a\n * class or method, or in `createWebApp({ middleware })`. Mounted app-wide\n * ahead of routing there is no route to read, and nothing is exempted.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Timer-free in-memory store: expired windows are swept on insert, from the\n * front. Bounded: see {@link BoundedCounters}.\n *\n * @internal Exported for tests.\n */\nexport class LazyMemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\nfunction defaultKey(ctx: RequestContext): string {\n // `ctx.ip` carries the resolution that used to live here: prefer the\n // runtime-computed address (Express derives it from `trust proxy`), fall\n // back to forwarded headers only for runtimes that compute none.\n return ctx.ip ?? 'global'\n}\n\n/**\n * Rate limiting as a `(ctx, next)` middleware.\n *\n * ```ts\n * // Edge (Cloudflare Workers) — app-wide:\n * const app = createWebApp({\n * h3, modules,\n * middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],\n * })\n *\n * // Any runtime — per controller/route:\n * @Middleware(rateLimitGuard({ max: 10 }))\n * @Post('/login')\n * ```\n */\nexport function rateLimitGuard(options: RateLimitGuardOptions = {}): MiddlewareHandler {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? defaultKey\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new LazyMemoryStore(windowMs, max)\n\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimitGuard({ exemptWhen })')\n\n return async (ctx: RequestContext, next: () => void): Promise<void> => {\n if (options.skip?.(ctx)) return next()\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n const { totalHits, resetTime } = await store.increment(keyGenerator(ctx))\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n ctx.setHeader('X-RateLimit-Limit', String(max))\n ctx.setHeader('X-RateLimit-Remaining', String(remaining))\n ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)))\n }\n\n if (totalHits > max) {\n const retryAfter = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 1000))\n if (sendHeaders) ctx.setHeader('Retry-After', String(retryAfter))\n ctx.json({ message }, statusCode)\n return\n }\n\n next()\n }\n}\n","// Edge-safe store adapters over a minimal KV surface. Zero runtime imports —\n// this file must stay importable from the `@forinda/kickjs/web` purity graph.\nimport type { RateLimitStore } from './rate-limit'\nimport type { SessionData, SessionStore } from './session'\n\n/**\n * The minimal async KV surface both stores need. Structurally compatible\n * with a Cloudflare Workers `KVNamespace` binding — pass it straight in:\n *\n * ```ts\n * export default {\n * fetch(req: Request, env: Env) {\n * const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })\n * // ...\n * },\n * }\n * ```\n *\n * Anything with the same shape works too (Deno KV wrapper, Upstash Redis\n * REST client adapter, a Map-backed fake in tests).\n */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/** Cloudflare KV rejects TTLs under 60 seconds — clamp up, never down. */\nfunction kvTtlSeconds(ms: number): number {\n return Math.max(60, Math.ceil(ms / 1000))\n}\n\nexport interface KvRateLimitStoreOptions {\n /** Window length in ms — must match the `windowMs` given to the limiter. */\n windowMs: number\n /** Key prefix in the KV namespace (default `'rl:'`). */\n prefix?: string\n}\n\n/**\n * {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments\n * where in-memory counters reset on every isolate.\n *\n * KV is eventually consistent and this is a read-modify-write counter, so\n * limiting is **approximate** under concurrency — bursts racing across\n * isolates can each read the same count. That is the accepted trade-off for\n * abuse throttling; use a Durable Object / Redis store when you need an\n * exact ceiling (billing quotas, strict per-key locks).\n */\nexport class KvRateLimitStore implements RateLimitStore {\n private readonly prefix: string\n private readonly windowMs: number\n\n constructor(\n private readonly kv: KvLike,\n options: KvRateLimitStoreOptions,\n ) {\n this.windowMs = options.windowMs\n this.prefix = options.prefix ?? 'rl:'\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = await this.read(key)\n if (entry && entry.reset > now) {\n entry.hits++\n await this.write(key, entry)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n await this.write(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = await this.read(key)\n if (entry && entry.hits > 0) {\n entry.hits--\n await this.write(key, entry)\n }\n }\n\n async reset(key: string): Promise<void> {\n await this.kv.delete(this.prefix + key)\n }\n\n private async read(key: string): Promise<{ hits: number; reset: number } | null> {\n const raw = await this.kv.get(this.prefix + key)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as { hits: number; reset: number }\n } catch {\n return null\n }\n }\n\n private async write(key: string, entry: { hits: number; reset: number }): Promise<void> {\n await this.kv.put(this.prefix + key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds(Math.max(entry.reset - Date.now(), 1000)),\n })\n }\n}\n\nexport interface KvSessionStoreOptions {\n /** Key prefix in the KV namespace (default `'sess:'`). */\n prefix?: string\n}\n\n/**\n * {@link SessionStore} over a {@link KvLike} namespace. Plug into the node\n * `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via\n * REST) so sessions survive restarts and horizontal scaling; TTL expiry is\n * delegated to the KV layer via `expirationTtl`.\n *\n * Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only\n * refresh), so `session({ rolling: true })` doubles KV operations per\n * request — per-operation-billed platforms may prefer `rolling: false`.\n */\nexport class KvSessionStore implements SessionStore {\n private readonly prefix: string\n\n constructor(\n private readonly kv: KvLike,\n options: KvSessionStoreOptions = {},\n ) {\n this.prefix = options.prefix ?? 'sess:'\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const raw = await this.kv.get(this.prefix + sid)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as SessionData\n } catch {\n return null\n }\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n await this.kv.put(this.prefix + sid, JSON.stringify(data), {\n expirationTtl: kvTtlSeconds(maxAge),\n })\n }\n\n async destroy(sid: string): Promise<void> {\n await this.kv.delete(this.prefix + sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const data = await this.get(sid)\n if (data !== null) await this.set(sid, data, maxAge)\n }\n}\n"],"mappings":";;;;;;;;;;kJA6EA,IAAa,gBAAb,KAAuD,CACrD,SAGA,YAAY,SAAkB,MAAgB,CAC5C,KAAK,SAAW,IAAI,gBAAgB,SAAU,KAAK,CACrD,CAEA,MAAM,UAAU,IAA8D,CAC5E,OAAO,KAAK,SAAS,UAAU,GAAG,CACpC,CAEA,MAAM,UAAU,IAA4B,CAC1C,KAAK,SAAS,UAAU,GAAG,CAC7B,CAEA,MAAM,MAAM,IAA4B,CACtC,KAAK,SAAS,MAAM,GAAG,CACzB,CACF,EAEA,SAAS,WAAW,IAA6B,CAI/C,OAAO,IAAI,IAAM,QACnB,CAiBA,SAAgB,eAAe,QAAiC,CAAC,EAAsB,CACrF,IAAM,IAAM,QAAQ,KAAO,IACrB,SAAW,QAAQ,UAAY,IAC/B,QAAU,QAAQ,SAAW,oBAC7B,WAAa,QAAQ,YAAc,IACnC,aAAe,QAAQ,cAAg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,CACvE,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,IAAK,KAAK,UAAU,IAAI,EAAG,CACzD,cAAe,aAAa,MAAM,CACpC,CAAC,CACH,CAEA,MAAM,QAAQ,IAA4B,CACxC,MAAM,KAAK,GAAG,OAAO,KAAK,OAAS,GAAG,CACxC,CAEA,MAAM,MAAM,IAAa,OAA+B,CACtD,IAAM,KAAO,MAAM,KAAK,IAAI,GAAG,EAC3B,OAAS,MAAM,MAAM,KAAK,IAAI,IAAK,KAAM,MAAM,CACrD,CACF"}
1
+ {"version":3,"file":"kv-stores-u0V_K-2O.mjs","names":[],"sources":["../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"sourcesContent":["// Ctx-style rate limiter — runs on BOTH pipelines: the node runtimes (via\n// `@Middleware()` / class middleware) and the `@forinda/kickjs/web` fetch\n// entry (via `@Middleware()` or `createWebApp({ middleware })`), unlike the\n// connect-style `rateLimit()` which is node-only. Zero runtime imports —\n// part of the edge purity graph.\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport type { RateLimitStore } from './rate-limit'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitGuardOptions {\n /** Maximum number of requests per window (default: 100). */\n max?: number\n /** Time window in milliseconds (default: 60_000). */\n windowMs?: number\n /** Response message when the limit is exceeded (default: 'Too Many Requests'). */\n message?: string\n /** HTTP status code when the limit is exceeded (default: 429). */\n statusCode?: number\n /**\n * Rate-limit key per request. Defaults to `ctx.ip`, falling back to\n * `'global'`. Return a user/tenant id here for authenticated quotas.\n *\n * ::: warning Behind a proxy, configure `trustProxy` or every client shares\n * one bucket\n * On a node runtime `ctx.ip` is the runtime's vetted client address —\n * Express derives it from `trust proxy`, Fastify from `trustProxy`. Without\n * that setting it is the SOCKET address, which behind a load balancer or\n * Cloudflare is the proxy's, so every caller lands in the same bucket and one\n * noisy client exhausts the allowance for everyone.\n *\n * `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are\n * deliberately not consulted here: `x-forwarded-for` is client-controllable\n * unless a proxy overwrites it, so trusting it unconditionally would let a\n * direct caller mint a fresh allowance per request by varying the header —\n * evading the limit rather than enforcing it. The header chain\n * (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the\n * `@forinda/kickjs/web` edge entry, where there is no socket and the platform\n * has already terminated the connection.\n * :::\n */\n keyGenerator?: (ctx: RequestContext) => string\n /** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */\n headers?: boolean\n /**\n * Counter backend. Defaults to a per-isolate in-memory map — fine for a\n * single node process, useless on edge where isolates recycle: pass a\n * `KvRateLimitStore` (or Redis-backed store) there.\n */\n store?: RateLimitStore\n /** Skip limiting for a request (health checks, allowlists). */\n skip?: (ctx: RequestContext) => boolean\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate. Declared on the route rather than restated as a\n * path here, so it cannot drift when `apiPrefix` or a module's `version`\n * changes:\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })\n * ```\n *\n * Only meaningful where a route has been matched — as `@Middleware()` on a\n * class or method, or in `createWebApp({ middleware })`. Mounted app-wide\n * ahead of routing there is no route to read, and nothing is exempted.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Timer-free in-memory store: expired windows are swept on insert, from the\n * front. Bounded: see {@link BoundedCounters}.\n *\n * @internal Exported for tests.\n */\nexport class LazyMemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\nfunction defaultKey(ctx: RequestContext): string {\n // `ctx.ip` carries the resolution that used to live here: prefer the\n // runtime-computed address (Express derives it from `trust proxy`), fall\n // back to forwarded headers only for runtimes that compute none.\n return ctx.ip ?? 'global'\n}\n\n/**\n * Rate limiting as a `(ctx, next)` middleware.\n *\n * ```ts\n * // Edge (Cloudflare Workers) — app-wide:\n * const app = createWebApp({\n * h3, modules,\n * middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],\n * })\n *\n * // Any runtime — per controller/route:\n * @Middleware(rateLimitGuard({ max: 10 }))\n * @Post('/login')\n * ```\n */\nexport function rateLimitGuard(options: RateLimitGuardOptions = {}): MiddlewareHandler {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? defaultKey\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new LazyMemoryStore(windowMs, max)\n\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimitGuard({ exemptWhen })')\n\n return async (ctx: RequestContext, next: () => void): Promise<void> => {\n if (options.skip?.(ctx)) return next()\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n const { totalHits, resetTime } = await store.increment(keyGenerator(ctx))\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n ctx.setHeader('X-RateLimit-Limit', String(max))\n ctx.setHeader('X-RateLimit-Remaining', String(remaining))\n ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)))\n }\n\n if (totalHits > max) {\n const retryAfter = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 1000))\n if (sendHeaders) ctx.setHeader('Retry-After', String(retryAfter))\n ctx.json({ message }, statusCode)\n return\n }\n\n next()\n }\n}\n","// Edge-safe store adapters over a minimal KV surface. Zero runtime imports —\n// this file must stay importable from the `@forinda/kickjs/web` purity graph.\nimport type { RateLimitStore } from './rate-limit'\nimport type { SessionData, SessionStore } from './session'\n\n/**\n * The minimal async KV surface both stores need. Structurally compatible\n * with a Cloudflare Workers `KVNamespace` binding — pass it straight in:\n *\n * ```ts\n * export default {\n * fetch(req: Request, env: Env) {\n * const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })\n * // ...\n * },\n * }\n * ```\n *\n * Anything with the same shape works too (Deno KV wrapper, Upstash Redis\n * REST client adapter, a Map-backed fake in tests).\n */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/** Cloudflare KV rejects TTLs under 60 seconds — clamp up, never down. */\nfunction kvTtlSeconds(ms: number): number {\n return Math.max(60, Math.ceil(ms / 1000))\n}\n\nexport interface KvRateLimitStoreOptions {\n /** Window length in ms — must match the `windowMs` given to the limiter. */\n windowMs: number\n /** Key prefix in the KV namespace (default `'rl:'`). */\n prefix?: string\n}\n\n/**\n * {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments\n * where in-memory counters reset on every isolate.\n *\n * KV is eventually consistent and this is a read-modify-write counter, so\n * limiting is **approximate** under concurrency — bursts racing across\n * isolates can each read the same count. That is the accepted trade-off for\n * abuse throttling; use a Durable Object / Redis store when you need an\n * exact ceiling (billing quotas, strict per-key locks).\n */\nexport class KvRateLimitStore implements RateLimitStore {\n private readonly prefix: string\n private readonly windowMs: number\n\n constructor(\n private readonly kv: KvLike,\n options: KvRateLimitStoreOptions,\n ) {\n this.windowMs = options.windowMs\n this.prefix = options.prefix ?? 'rl:'\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = await this.read(key)\n if (entry && entry.reset > now) {\n entry.hits++\n await this.write(key, entry)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n await this.write(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = await this.read(key)\n if (entry && entry.hits > 0) {\n entry.hits--\n await this.write(key, entry)\n }\n }\n\n async reset(key: string): Promise<void> {\n await this.kv.delete(this.prefix + key)\n }\n\n private async read(key: string): Promise<{ hits: number; reset: number } | null> {\n const raw = await this.kv.get(this.prefix + key)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as { hits: number; reset: number }\n } catch {\n return null\n }\n }\n\n private async write(key: string, entry: { hits: number; reset: number }): Promise<void> {\n await this.kv.put(this.prefix + key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds(Math.max(entry.reset - Date.now(), 1000)),\n })\n }\n}\n\nexport interface KvSessionStoreOptions {\n /** Key prefix in the KV namespace (default `'sess:'`). */\n prefix?: string\n}\n\n/**\n * {@link SessionStore} over a {@link KvLike} namespace. Plug into the node\n * `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via\n * REST) so sessions survive restarts and horizontal scaling; TTL expiry is\n * delegated to the KV layer via `expirationTtl`.\n *\n * Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only\n * refresh), so `session({ rolling: true })` doubles KV operations per\n * request — per-operation-billed platforms may prefer `rolling: false`.\n */\nexport class KvSessionStore implements SessionStore {\n private readonly prefix: string\n\n constructor(\n private readonly kv: KvLike,\n options: KvSessionStoreOptions = {},\n ) {\n this.prefix = options.prefix ?? 'sess:'\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const raw = await this.kv.get(this.prefix + sid)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as SessionData\n } catch {\n return null\n }\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n await this.kv.put(this.prefix + sid, JSON.stringify(data), {\n expirationTtl: kvTtlSeconds(maxAge),\n })\n }\n\n async destroy(sid: string): Promise<void> {\n await this.kv.delete(this.prefix + sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const data = await this.get(sid)\n if (data !== null) await this.set(sid, data, maxAge)\n }\n}\n"],"mappings":";;;;;;;;;;kJA6EA,IAAa,gBAAb,KAAuD,CACrD,SAGA,YAAY,SAAkB,MAAgB,CAC5C,KAAK,SAAW,IAAI,gBAAgB,SAAU,KAAK,CACrD,CAEA,MAAM,UAAU,IAA8D,CAC5E,OAAO,KAAK,SAAS,UAAU,GAAG,CACpC,CAEA,MAAM,UAAU,IAA4B,CAC1C,KAAK,SAAS,UAAU,GAAG,CAC7B,CAEA,MAAM,MAAM,IAA4B,CACtC,KAAK,SAAS,MAAM,GAAG,CACzB,CACF,EAEA,SAAS,WAAW,IAA6B,CAI/C,OAAO,IAAI,IAAM,QACnB,CAiBA,SAAgB,eAAe,QAAiC,CAAC,EAAsB,CACrF,IAAM,IAAM,QAAQ,KAAO,IACrB,SAAW,QAAQ,UAAY,IAC/B,QAAU,QAAQ,SAAW,oBAC7B,WAAa,QAAQ,YAAc,IACnC,aAAe,QAAQ,cAAgB,WACvC,YAAc,QAAQ,SAAW,GACjC,MAAQ,QAAQ,OAAS,IAAI,gBAAgB,SAAU,GAAG,EAE1D,WAAa,QAAQ,WAG3B,OAFI,aAAe,IAAA,IAAW,eAAe,WAAY,gCAAgC,EAElF,MAAO,IAAqB,OAAoC,CAErE,GADI,QAAQ,OAAO,GAAG,GAClB,aAAe,IAAA,IAAa,gBAAgB,WAAY,IAAI,OAAO,MAAO,IAAI,KAAK,EACrF,OAAO,KAAK,EAGd,GAAM,CAAE,UAAW,WAAc,MAAM,MAAM,UAAU,aAAa,GAAG,CAAC,EAClE,UAAY,KAAK,IAAI,EAAG,IAAM,SAAS,EAQ7C,GANI,cACF,IAAI,UAAU,oBAAqB,OAAO,GAAG,CAAC,EAC9C,IAAI,UAAU,wBAAyB,OAAO,SAAS,CAAC,EACxD,IAAI,UAAU,oBAAqB,OAAO,KAAK,KAAK,UAAU,QAAQ,EAAI,GAAI,C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AI,MAAQ,KAAM,OAAO,KACzB,GAAI,CACF,OAAO,KAAK,MAAM,GAAG,CACvB,MAAQ,CACN,OAAO,IACT,CACF,CAEA,MAAc,MAAM,IAAa,MAAuD,CACtF,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,IAAK,KAAK,UAAU,KAAK,EAAG,CAC1D,cAAe,aAAa,KAAK,IAAI,MAAM,MAAQ,KAAK,IAAI,EAAG,GAAI,CAAC,CACtE,CAAC,CACH,CACF,EAiBa,eAAb,KAAoD,CAI/B,GAHnB,OAEA,YACE,GACA,QAAiC,CAAC,EAClC,CAFiB,KAAA,GAAA,GAGjB,KAAK,OAAS,QAAQ,QAAU,OAClC,CAEA,MAAM,IAAI,IAA0C,CAClD,IAAM,IAAM,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,GAAG,EAC/C,GAAI,MAAQ,KAAM,OAAO,KACzB,GAAI,CACF,OAAO,KAAK,MAAM,GAAG,CACvB,MAAQ,CACN,OAAO,IACT,CACF,CAEA,MAAM,IAAI,IAAa,KAAmB,OAA+B,CACvE,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,IAAK,KAAK,UAAU,IAAI,EAAG,CACzD,cAAe,aAAa,MAAM,CACpC,CAAC,CACH,CAEA,MAAM,QAAQ,IAA4B,CACxC,MAAM,KAAK,GAAG,OAAO,KAAK,OAAS,GAAG,CACxC,CAEA,MAAM,MAAM,IAAa,OAA+B,CACtD,IAAM,KAAO,MAAM,KAAK,IAAI,GAAG,EAC3B,OAAS,MAAM,MAAM,KAAK,IAAI,IAAK,KAAM,MAAM,CACrD,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as withPrecompressed}from"./precompressed-DPESwDxf.mjs";function lazyServeStatic(dir){let serve;return withPrecompressed(dir,(req,res,next)=>{serve??=import(`serve-static`).then(mod=>(mod.default??mod)(dir)),serve.then(handler=>handler(req,res,next),next)})}export{lazyServeStatic as t};
12
- //# sourceMappingURL=lazy-serve-static-D2pf9ODr.mjs.map
11
+ import{t as withPrecompressed}from"./precompressed-DIkilvFq.mjs";function lazyServeStatic(dir){let serve;return withPrecompressed(dir,(req,res,next)=>{serve??=import(`serve-static`).then(mod=>(mod.default??mod)(dir)),serve.then(handler=>handler(req,res,next),next)})}export{lazyServeStatic as t};
12
+ //# sourceMappingURL=lazy-serve-static-kB1m23xS.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"lazy-serve-static-D2pf9ODr.mjs","names":[],"sources":["../src/http/runtimes/lazy-serve-static.ts"],"sourcesContent":["import type { ConnectHandler as RequestHandler } from '../connect'\nimport { withPrecompressed } from './precompressed'\n\n/**\n * `serve-static` as connect middleware, imported on the first request. Only\n * some apps serve files (SpaAdapter), and an `import()`, unlike\n * `createRequire`, is one a bundler follows — so a Netlify or Vercel\n * function carries the package instead of failing to find it.\n */\nexport function lazyServeStatic(dir: string): RequestHandler {\n let serve: Promise<RequestHandler> | undefined\n return withPrecompressed(dir, (req, res, next) => {\n serve ??= import('serve-static').then((mod) => {\n const factory = ((mod as { default?: unknown }).default ?? mod) as (\n root: string,\n ) => RequestHandler\n return factory(dir)\n })\n serve.then((handler) => handler(req, res, next), next)\n })\n}\n"],"mappings":";;;;;;;;;;iEASA,SAAgB,gBAAgB,IAA6B,CAC3D,IAAI,MACJ,OAAO,kBAAkB,KAAM,IAAK,IAAK,OAAS,CAChD,QAAU,OAAO,eAAe,CAAC,KAAM,MACnB,IAA8B,SAAW,IAAA,CAG5C,GAAG,CACnB,EACD,MAAM,KAAM,SAAY,QAAQ,IAAK,IAAK,IAAI,EAAG,IAAI,CACvD,CAAC,CACH"}
1
+ {"version":3,"file":"lazy-serve-static-kB1m23xS.mjs","names":[],"sources":["../src/http/runtimes/lazy-serve-static.ts"],"sourcesContent":["import type { ConnectHandler as RequestHandler } from '../connect'\nimport { withPrecompressed } from './precompressed'\n\n/**\n * `serve-static` as connect middleware, imported on the first request. Only\n * some apps serve files (SpaAdapter), and an `import()`, unlike\n * `createRequire`, is one a bundler follows — so a Netlify or Vercel\n * function carries the package instead of failing to find it.\n */\nexport function lazyServeStatic(dir: string): RequestHandler {\n let serve: Promise<RequestHandler> | undefined\n return withPrecompressed(dir, (req, res, next) => {\n serve ??= import('serve-static').then((mod) => {\n const factory = ((mod as { default?: unknown }).default ?? mod) as (\n root: string,\n ) => RequestHandler\n return factory(dir)\n })\n serve.then((handler) => handler(req, res, next), next)\n })\n}\n"],"mappings":";;;;;;;;;;iEASA,SAAgB,gBAAgB,IAA6B,CAC3D,IAAI,MACJ,OAAO,kBAAkB,KAAM,IAAK,IAAK,OAAS,CAChD,QAAU,OAAO,eAAe,CAAC,KAAM,MACnB,IAA8B,SAAW,IAAA,CAG5C,GAAG,CACnB,EACD,MAAM,KAAM,SAAY,QAAQ,IAAK,IAAK,IAAI,EAAG,IAAI,CACvD,CAAC,CACH"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  import{createLogger}from"./core/logger.mjs";const log=createLogger(`Observers`);let observers=[],publisher,publisherWantsResponses=()=>!1;function setObservers(list){return observers=list.filter(o=>o.onError||o.onResponse),observers}function releaseObservers(installed){observers===installed&&(observers=[])}function setObserverPublisher(next,wantsResponses=()=>!1){publisher=next,publisherWantsResponses=wantsResponses}function hasResponseObservers(){return observers.some(o=>o.onResponse)||publisherWantsResponses()}function notify(pick,what){for(let observer of publisher?[...observers,publisher]:observers)try{let result=pick(observer);result&&typeof result.catch==`function`&&result.catch(err=>failed(observer,what,err))}catch(err){failed(observer,what,err)}}function failed(observer,what,err){try{log.error({err},`${observer.name??`observer`}.${what} threw — skipped`)}catch{}}function reportError(error,info){notify(o=>o.onError?.(error,info),`onError`)}function reportResponse(info){notify(o=>o.onResponse?.(info),`onResponse`)}export{setObserverPublisher as a,reportResponse as i,releaseObservers as n,setObservers as o,reportError as r,hasResponseObservers as t};
12
- //# sourceMappingURL=observers-BV435fEL.mjs.map
12
+ //# sourceMappingURL=observers-vX5EpqCX.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"observers-BV435fEL.mjs","names":[],"sources":["../src/core/observers.ts"],"sourcesContent":["/**\n * One place every error and every response is reported to — so an error\n * tracker, a metrics exporter, or an APM integration hooks in once instead of\n * replacing the error handler and patching each source.\n *\n * Observers are adapters and plugins with `onError` / `onResponse`, plus\n * whatever the Node server's tracing channels publish (see `http/tracing.ts`).\n * Observe-only: they cannot change the response, and one that throws is\n * logged and skipped — it never breaks a request or another observer.\n *\n * Free of `node:` imports: `waitUntil` (shared with the web entry) reports\n * through here.\n *\n * @module @forinda/kickjs/core/observers\n */\nimport { createLogger } from './logger'\n\nconst log = createLogger('Observers')\n\n/** Where an error came from. Integrations may report their own sources. */\nexport type ErrorSource =\n | 'request'\n | 'uncaught'\n | 'unhandled-rejection'\n | 'background'\n | 'job'\n | (string & {})\n\nexport interface ErrorInfo {\n source: ErrorSource\n requestId?: string\n method?: string\n /** The request URL path, as received. */\n path?: string\n /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */\n route?: string\n /** The status the error was answered with, for request errors. */\n status?: number\n /** Anything else the reporter knows — a queue and job name, a cron schedule. */\n context?: Record<string, unknown>\n}\n\nexport interface ResponseInfo {\n method: string\n path: string\n /** The matched route pattern, or undefined when no route matched (404s). */\n route?: string\n status: number\n durationMs: number\n requestId?: string\n}\n\nexport interface Observer {\n name?: string\n onError?(error: unknown, info: ErrorInfo): void | Promise<void>\n onResponse?(info: ResponseInfo): void | Promise<void>\n}\n\nlet observers: readonly Observer[] = []\nlet publisher: Observer | undefined\nlet publisherWantsResponses: () => boolean = () => false\n\n/**\n * Replace the observer set — called by the Application from its adapters and\n * plugins. Returns the installed set, so its owner can later release exactly\n * that set (see {@link releaseObservers}).\n */\nexport function setObservers(list: readonly Observer[]): readonly Observer[] {\n observers = list.filter((o) => o.onError || o.onResponse)\n return observers\n}\n\n/**\n * Clear the observer set — but only if it is still the one `installed`. The\n * set is process-wide: a newer Application may have replaced it, and an older\n * one shutting down must not clear the newer one's observers.\n */\nexport function releaseObservers(installed: readonly Observer[]): void {\n if (observers === installed) observers = []\n}\n\n/**\n * The Node server's tracing channels, fed from the same reports. `wantsResponses`\n * is checked per request: a channel can gain a subscriber at any time.\n */\nexport function setObserverPublisher(\n next: Observer | undefined,\n wantsResponses: () => boolean = () => false,\n): void {\n publisher = next\n publisherWantsResponses = wantsResponses\n}\n\n/** Whether anything is listening for responses — lets the server skip timing work. */\nexport function hasResponseObservers(): boolean {\n return observers.some((o) => o.onResponse) || publisherWantsResponses()\n}\n\nfunction notify(pick: (o: Observer) => void | Promise<void> | undefined, what: string): void {\n for (const observer of publisher ? [...observers, publisher] : observers) {\n try {\n const result = pick(observer)\n if (result && typeof (result as Promise<void>).catch === 'function') {\n ;(result as Promise<void>).catch((err: unknown) => failed(observer, what, err))\n }\n } catch (err) {\n failed(observer, what, err)\n }\n }\n}\n\nfunction failed(observer: Observer, what: string, err: unknown): void {\n // Logged directly, never re-reported: an observer failing inside onError\n // must not loop back into onError. Guarded too: a custom LoggerProvider that\n // throws would otherwise escape reportError() — or, from an async\n // observer, become an unhandled rejection that bootstrap reports right back\n // here.\n try {\n log.error({ err }, `${observer.name ?? 'observer'}.${what} threw — skipped`)\n } catch {\n // Nothing left to tell; reportError's \"never throws\" contract wins.\n }\n}\n\n/**\n * Report an error to every observer. The framework calls this for request\n * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and\n * queue job failures; call it from your own integrations too (a cron runner,\n * a message consumer). Never throws.\n */\nexport function reportError(error: unknown, info: ErrorInfo): void {\n notify((o) => o.onError?.(error, info), 'onError')\n}\n\n/** Report a finished response to every observer. Never throws. */\nexport function reportResponse(info: ResponseInfo): void {\n notify((o) => o.onResponse?.(info), 'onResponse')\n}\n"],"mappings":";;;;;;;;;;4CAiBA,MAAM,IAAM,aAAa,WAAW,EAyCpC,IAAI,UAAiC,CAAC,EAClC,UACA,4BAA+C,GAOnD,SAAgB,aAAa,KAAgD,CAE3E,MADA,WAAY,KAAK,OAAQ,GAAM,EAAE,SAAW,EAAE,UAAU,EACjD,SACT,CAOA,SAAgB,iBAAiB,UAAsC,CACjE,YAAc,YAAW,UAAY,CAAC,EAC5C,CAMA,SAAgB,qBACd,KACA,mBAAsC,GAChC,CACN,UAAY,KACZ,wBAA0B,cAC5B,CAGA,SAAgB,sBAAgC,CAC9C,OAAO,UAAU,KAAM,GAAM,EAAE,UAAU,GAAK,wBAAwB,CACxE,CAEA,SAAS,OAAO,KAAyD,KAAoB,CAC3F,IAAK,IAAM,YAAY,UAAY,CAAC,GAAG,UAAW,SAAS,EAAI,UAC7D,GAAI,CACF,IAAM,OAAS,KAAK,QAAQ,EACxB,QAAU,OAAQ,OAAyB,OAAU,YACtD,OAA0B,MAAO,KAAiB,OAAO,SAAU,KAAM,GAAG,CAAC,CAElF,OAAS,IAAK,CACZ,OAAO,SAAU,KAAM,GAAG,CAC5B,CAEJ,CAEA,SAAS,OAAO,SAAoB,KAAc,IAAoB,CAMpE,GAAI,CACF,IAAI,MAAM,CAAE,GAAI,EAAG,GAAG,SAAS,MAAQ,WAAW,GAAG,KAAK,iBAAiB,CAC7E,MAAQ,CAER,CACF,CAQA,SAAgB,YAAY,MAAgB,KAAuB,CACjE,OAAQ,GAAM,EAAE,UAAU,MAAO,IAAI,EAAG,SAAS,CACnD,CAGA,SAAgB,eAAe,KAA0B,CACvD,OAAQ,GAAM,EAAE,aAAa,IAAI,EAAG,YAAY,CAClD"}
1
+ {"version":3,"file":"observers-vX5EpqCX.mjs","names":[],"sources":["../src/core/observers.ts"],"sourcesContent":["/**\n * One place every error and every response is reported to — so an error\n * tracker, a metrics exporter, or an APM integration hooks in once instead of\n * replacing the error handler and patching each source.\n *\n * Observers are adapters and plugins with `onError` / `onResponse`, plus\n * whatever the Node server's tracing channels publish (see `http/tracing.ts`).\n * Observe-only: they cannot change the response, and one that throws is\n * logged and skipped — it never breaks a request or another observer.\n *\n * Free of `node:` imports: `waitUntil` (shared with the web entry) reports\n * through here.\n *\n * @module @forinda/kickjs/core/observers\n */\nimport { createLogger } from './logger'\n\nconst log = createLogger('Observers')\n\n/** Where an error came from. Integrations may report their own sources. */\nexport type ErrorSource =\n | 'request'\n | 'uncaught'\n | 'unhandled-rejection'\n | 'background'\n | 'job'\n | (string & {})\n\nexport interface ErrorInfo {\n source: ErrorSource\n requestId?: string\n method?: string\n /** The request URL path, as received. */\n path?: string\n /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */\n route?: string\n /** The status the error was answered with, for request errors. */\n status?: number\n /** Anything else the reporter knows — a queue and job name, a cron schedule. */\n context?: Record<string, unknown>\n}\n\nexport interface ResponseInfo {\n method: string\n path: string\n /** The matched route pattern, or undefined when no route matched (404s). */\n route?: string\n status: number\n durationMs: number\n requestId?: string\n}\n\nexport interface Observer {\n name?: string\n onError?(error: unknown, info: ErrorInfo): void | Promise<void>\n onResponse?(info: ResponseInfo): void | Promise<void>\n}\n\nlet observers: readonly Observer[] = []\nlet publisher: Observer | undefined\nlet publisherWantsResponses: () => boolean = () => false\n\n/**\n * Replace the observer set — called by the Application from its adapters and\n * plugins. Returns the installed set, so its owner can later release exactly\n * that set (see {@link releaseObservers}).\n */\nexport function setObservers(list: readonly Observer[]): readonly Observer[] {\n observers = list.filter((o) => o.onError || o.onResponse)\n return observers\n}\n\n/**\n * Clear the observer set — but only if it is still the one `installed`. The\n * set is process-wide: a newer Application may have replaced it, and an older\n * one shutting down must not clear the newer one's observers.\n */\nexport function releaseObservers(installed: readonly Observer[]): void {\n if (observers === installed) observers = []\n}\n\n/**\n * The Node server's tracing channels, fed from the same reports. `wantsResponses`\n * is checked per request: a channel can gain a subscriber at any time.\n */\nexport function setObserverPublisher(\n next: Observer | undefined,\n wantsResponses: () => boolean = () => false,\n): void {\n publisher = next\n publisherWantsResponses = wantsResponses\n}\n\n/** Whether anything is listening for responses — lets the server skip timing work. */\nexport function hasResponseObservers(): boolean {\n return observers.some((o) => o.onResponse) || publisherWantsResponses()\n}\n\nfunction notify(pick: (o: Observer) => void | Promise<void> | undefined, what: string): void {\n for (const observer of publisher ? [...observers, publisher] : observers) {\n try {\n const result = pick(observer)\n if (result && typeof (result as Promise<void>).catch === 'function') {\n ;(result as Promise<void>).catch((err: unknown) => failed(observer, what, err))\n }\n } catch (err) {\n failed(observer, what, err)\n }\n }\n}\n\nfunction failed(observer: Observer, what: string, err: unknown): void {\n // Logged directly, never re-reported: an observer failing inside onError\n // must not loop back into onError. Guarded too: a custom LoggerProvider that\n // throws would otherwise escape reportError() — or, from an async\n // observer, become an unhandled rejection that bootstrap reports right back\n // here.\n try {\n log.error({ err }, `${observer.name ?? 'observer'}.${what} threw — skipped`)\n } catch {\n // Nothing left to tell; reportError's \"never throws\" contract wins.\n }\n}\n\n/**\n * Report an error to every observer. The framework calls this for request\n * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and\n * queue job failures; call it from your own integrations too (a cron runner,\n * a message consumer). Never throws.\n */\nexport function reportError(error: unknown, info: ErrorInfo): void {\n notify((o) => o.onError?.(error, info), 'onError')\n}\n\n/** Report a finished response to every observer. Never throws. */\nexport function reportResponse(info: ResponseInfo): void {\n notify((o) => o.onResponse?.(info), 'onResponse')\n}\n"],"mappings":";;;;;;;;;;4CAiBA,MAAM,IAAM,aAAa,WAAW,EAyCpC,IAAI,UAAiC,CAAC,EAClC,UACA,4BAA+C,GAOnD,SAAgB,aAAa,KAAgD,CAE3E,MADA,WAAY,KAAK,OAAQ,GAAM,EAAE,SAAW,EAAE,UAAU,EACjD,SACT,CAOA,SAAgB,iBAAiB,UAAsC,CACjE,YAAc,YAAW,UAAY,CAAC,EAC5C,CAMA,SAAgB,qBACd,KACA,mBAAsC,GAChC,CACN,UAAY,KACZ,wBAA0B,cAC5B,CAGA,SAAgB,sBAAgC,CAC9C,OAAO,UAAU,KAAM,GAAM,EAAE,UAAU,GAAK,wBAAwB,CACxE,CAEA,SAAS,OAAO,KAAyD,KAAoB,CAC3F,IAAK,IAAM,YAAY,UAAY,CAAC,GAAG,UAAW,SAAS,EAAI,UAC7D,GAAI,CACF,IAAM,OAAS,KAAK,QAAQ,EACxB,QAAU,OAAQ,OAAyB,OAAU,YACtD,OAA0B,MAAO,KAAiB,OAAO,SAAU,KAAM,GAAG,CAAC,CAElF,OAAS,IAAK,CACZ,OAAO,SAAU,KAAM,GAAG,CAC5B,CAEJ,CAEA,SAAS,OAAO,SAAoB,KAAc,IAAoB,CAMpE,GAAI,CACF,IAAI,MAAM,CAAE,GAAI,EAAG,GAAG,SAAS,MAAQ,WAAW,GAAG,KAAK,iBAAiB,CAC7E,MAAQ,CAER,CACF,CAQA,SAAgB,YAAY,MAAgB,KAAuB,CACjE,OAAQ,GAAM,EAAE,UAAU,MAAO,IAAI,EAAG,SAAS,CACnD,CAGA,SAAgB,eAAe,KAA0B,CACvD,OAAQ,GAAM,EAAE,aAAa,IAAI,EAAG,YAAY,CAClD"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  import{extname,join,normalize,resolve,sep}from"node:path";import{stat}from"node:fs/promises";const COMPRESSIBLE_TYPES={html:`text/html; charset=utf-8`,css:`text/css; charset=utf-8`,js:`text/javascript; charset=utf-8`,mjs:`text/javascript; charset=utf-8`,json:`application/json; charset=utf-8`,map:`application/json; charset=utf-8`,webmanifest:`application/manifest+json; charset=utf-8`,svg:`image/svg+xml`,txt:`text/plain; charset=utf-8`,xml:`application/xml; charset=utf-8`,wasm:`application/wasm`},ENCODINGS=[[`br`,`.br`],[`gzip`,`.gz`]];function acceptsEncoding(header,encoding){let star=!1;for(let part of header.toLowerCase().split(`,`)){let[name,...params]=part.trim().split(`;`),q=params.map(p=>p.trim()).find(p=>p.startsWith(`q=`)),allowed=!q||Number(q.slice(2))>0;if(name===encoding)return allowed;name===`*`&&(star=allowed)}return star}function withPrecompressed(root,serve){let base=resolve(root);return(req,res,next)=>{if(req.method!==`GET`&&req.method!==`HEAD`||req.headers.range)return serve(req,res,next);let url=req.url,q=url.indexOf(`?`),pathname=(q===-1?url:url.slice(0,q)).replace(/\/$/,`/index.html`),rel;try{rel=decodeURIComponent(pathname)}catch{return serve(req,res,next)}let type=COMPRESSIBLE_TYPES[extname(rel).slice(1).toLowerCase()];if(!type)return serve(req,res,next);let file=join(base,normalize(rel));if(!file.startsWith(base+sep))return serve(req,res,next);let vary=String(res.getHeader(`Vary`)??``);/\baccept-encoding\b/i.test(vary)||res.setHeader(`Vary`,vary?`${vary}, Accept-Encoding`:`Accept-Encoding`);let accept=String(req.headers[`accept-encoding`]??``);(async()=>{if(!(await stat(file).catch(()=>void 0))?.isFile())return serve(req,res,next);for(let[encoding,ext]of ENCODINGS)if(acceptsEncoding(accept,encoding)&&(await stat(file+ext).catch(()=>void 0))?.isFile())return res.setHeader(`Content-Encoding`,encoding),res.setHeader(`Content-Type`,type),req.url=pathname+ext+(q===-1?``:url.slice(q)),serve(req,res,err=>{res.removeHeader(`Content-Encoding`),res.removeHeader(`Content-Type`),req.url=url,next(err)});serve(req,res,next)})().catch(next)}}export{withPrecompressed as t};
12
- //# sourceMappingURL=precompressed-DPESwDxf.mjs.map
12
+ //# sourceMappingURL=precompressed-DIkilvFq.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"precompressed-DPESwDxf.mjs","names":[],"sources":["../src/http/runtimes/precompressed.ts"],"sourcesContent":["/**\n * Serve a file's precompressed sibling — `app.js.br`, `app.js.gz` — when the\n * client accepts it. In front of `serve-static` on every runtime, so one\n * `.br` written at build time saves compressing the file on each request.\n */\nimport { stat } from 'node:fs/promises'\nimport { extname, join, normalize, resolve, sep } from 'node:path'\nimport type { ConnectHandler, ConnectNext } from '../connect'\n\n/**\n * The text types worth compressing, by extension — the files a sibling is\n * looked for, and the ones `kick build` precompresses. Their `Content-Type`\n * is the original file's, not the sibling's.\n */\nexport const COMPRESSIBLE_TYPES: Readonly<Record<string, string>> = {\n html: 'text/html; charset=utf-8',\n css: 'text/css; charset=utf-8',\n js: 'text/javascript; charset=utf-8',\n mjs: 'text/javascript; charset=utf-8',\n json: 'application/json; charset=utf-8',\n map: 'application/json; charset=utf-8',\n webmanifest: 'application/manifest+json; charset=utf-8',\n svg: 'image/svg+xml',\n txt: 'text/plain; charset=utf-8',\n xml: 'application/xml; charset=utf-8',\n wasm: 'application/wasm',\n}\n\n/** Preferred first. */\nconst ENCODINGS = [\n ['br', '.br'],\n ['gzip', '.gz'],\n] as const\n\n/** Whether `Accept-Encoding` allows `encoding` — named, or via `*`, and not `q=0`. */\nexport function acceptsEncoding(header: string, encoding: string): boolean {\n let star = false\n for (const part of header.toLowerCase().split(',')) {\n const [name, ...params] = part.trim().split(';')\n const q = params.map((p) => p.trim()).find((p) => p.startsWith('q='))\n const allowed = !q || Number(q.slice(2)) > 0\n if (name === encoding) return allowed\n if (name === '*') star = allowed\n }\n return star\n}\n\n/** Wrap a `serve-static` handler for `root` so it serves precompressed siblings. */\nexport function withPrecompressed(root: string, serve: ConnectHandler): ConnectHandler {\n const base = resolve(root)\n return (req, res, next) => {\n // A byte range is a range of the file as stored; serve the original.\n if ((req.method !== 'GET' && req.method !== 'HEAD') || req.headers.range) {\n return serve(req, res, next)\n }\n const url = req.url\n const q = url.indexOf('?')\n // serve-static answers a directory with its index.html; so does this.\n const pathname = (q === -1 ? url : url.slice(0, q)).replace(/\\/$/, '/index.html')\n let rel: string\n try {\n rel = decodeURIComponent(pathname)\n } catch {\n return serve(req, res, next)\n }\n const type = COMPRESSIBLE_TYPES[extname(rel).slice(1).toLowerCase()]\n if (!type) return serve(req, res, next)\n const file = join(base, normalize(rel))\n if (!file.startsWith(base + sep)) return serve(req, res, next)\n\n // Whether the response is compressed depends on the request's encoding.\n const vary = String(res.getHeader('Vary') ?? '')\n if (!/\\baccept-encoding\\b/i.test(vary)) {\n res.setHeader('Vary', vary ? `${vary}, Accept-Encoding` : 'Accept-Encoding')\n }\n const accept = String(req.headers['accept-encoding'] ?? '')\n ;(async () => {\n // A sibling stands in for its file — never for one that's gone.\n if (!(await stat(file).catch(() => undefined))?.isFile()) return serve(req, res, next)\n for (const [encoding, ext] of ENCODINGS) {\n if (!acceptsEncoding(accept, encoding)) continue\n const sibling = await stat(file + ext).catch(() => undefined)\n if (!sibling?.isFile()) continue\n res.setHeader('Content-Encoding', encoding)\n // serve-static types the response by the path it serves only when\n // nothing has set a type — so the sibling is served as the original.\n res.setHeader('Content-Type', type)\n req.url = pathname + ext + (q === -1 ? '' : url.slice(q))\n // The sibling went away before serve-static read it: undo, carry on.\n const restore: ConnectNext = (err) => {\n res.removeHeader('Content-Encoding')\n res.removeHeader('Content-Type')\n req.url = url\n next(err)\n }\n return serve(req, res, restore)\n }\n serve(req, res, next)\n })().catch(next)\n }\n}\n"],"mappings":";;;;;;;;;;6FAcA,MAAa,mBAAuD,CAClE,KAAM,2BACN,IAAK,0BACL,GAAI,iCACJ,IAAK,iCACL,KAAM,kCACN,IAAK,kCACL,YAAa,2CACb,IAAK,gBACL,IAAK,4BACL,IAAK,iCACL,KAAM,kBACR,EAGM,UAAY,CAChB,CAAC,KAAM,KAAK,EACZ,CAAC,OAAQ,KAAK,CAChB,EAGA,SAAgB,gBAAgB,OAAgB,SAA2B,CACzE,IAAI,KAAO,GACX,IAAK,IAAM,QAAQ,OAAO,YAAY,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AE,GACxD,SAAY,CAEZ,GAAI,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC,UAAY,IAAA,EAAS,EAAA,EAAI,OAAO,EAAG,OAAO,MAAM,IAAK,IAAK,IAAI,EACrF,IAAK,GAAM,CAAC,SAAU,OAAQ,UAG5B,GAFK,gBAAgB,OAAQ,QAAQ,IAEhC,MADiB,KAAK,KAAO,GAAG,CAAC,CAAC,UAAY,IAAA,EAAS,EAAA,EAC9C,OAAO,EAarB,OAZA,IAAI,UAAU,mBAAoB,QAAQ,EAG1C,IAAI,UAAU,eAAgB,IAAI,EAClC,IAAI,IAAM,SAAW,KAAO,IAAM,GAAK,GAAK,IAAI,MAAM,CAAC,GAQhD,MAAM,IAAK,IANY,KAAQ,CACpC,IAAI,aAAa,kBAAkB,EACnC,IAAI,aAAa,cAAc,EAC/B,IAAI,IAAM,IACV,KAAK,GAAG,CACV,CAC8B,EAEhC,MAAM,IAAK,IAAK,IAAI,CACtB,EAAA,CAAG,CAAC,CAAC,MAAM,IAAI,CACjB,CACF"}
1
+ {"version":3,"file":"precompressed-DIkilvFq.mjs","names":[],"sources":["../src/http/runtimes/precompressed.ts"],"sourcesContent":["/**\n * Serve a file's precompressed sibling — `app.js.br`, `app.js.gz` — when the\n * client accepts it. In front of `serve-static` on every runtime, so one\n * `.br` written at build time saves compressing the file on each request.\n */\nimport { stat } from 'node:fs/promises'\nimport { extname, join, normalize, resolve, sep } from 'node:path'\nimport type { ConnectHandler, ConnectNext } from '../connect'\n\n/**\n * The text types worth compressing, by extension — the files a sibling is\n * looked for, and the ones `kick build` precompresses. Their `Content-Type`\n * is the original file's, not the sibling's.\n */\nexport const COMPRESSIBLE_TYPES: Readonly<Record<string, string>> = {\n html: 'text/html; charset=utf-8',\n css: 'text/css; charset=utf-8',\n js: 'text/javascript; charset=utf-8',\n mjs: 'text/javascript; charset=utf-8',\n json: 'application/json; charset=utf-8',\n map: 'application/json; charset=utf-8',\n webmanifest: 'application/manifest+json; charset=utf-8',\n svg: 'image/svg+xml',\n txt: 'text/plain; charset=utf-8',\n xml: 'application/xml; charset=utf-8',\n wasm: 'application/wasm',\n}\n\n/** Preferred first. */\nconst ENCODINGS = [\n ['br', '.br'],\n ['gzip', '.gz'],\n] as const\n\n/** Whether `Accept-Encoding` allows `encoding` — named, or via `*`, and not `q=0`. */\nexport function acceptsEncoding(header: string, encoding: string): boolean {\n let star = false\n for (const part of header.toLowerCase().split(',')) {\n const [name, ...params] = part.trim().split(';')\n const q = params.map((p) => p.trim()).find((p) => p.startsWith('q='))\n const allowed = !q || Number(q.slice(2)) > 0\n if (name === encoding) return allowed\n if (name === '*') star = allowed\n }\n return star\n}\n\n/** Wrap a `serve-static` handler for `root` so it serves precompressed siblings. */\nexport function withPrecompressed(root: string, serve: ConnectHandler): ConnectHandler {\n const base = resolve(root)\n return (req, res, next) => {\n // A byte range is a range of the file as stored; serve the original.\n if ((req.method !== 'GET' && req.method !== 'HEAD') || req.headers.range) {\n return serve(req, res, next)\n }\n const url = req.url\n const q = url.indexOf('?')\n // serve-static answers a directory with its index.html; so does this.\n const pathname = (q === -1 ? url : url.slice(0, q)).replace(/\\/$/, '/index.html')\n let rel: string\n try {\n rel = decodeURIComponent(pathname)\n } catch {\n return serve(req, res, next)\n }\n const type = COMPRESSIBLE_TYPES[extname(rel).slice(1).toLowerCase()]\n if (!type) return serve(req, res, next)\n const file = join(base, normalize(rel))\n if (!file.startsWith(base + sep)) return serve(req, res, next)\n\n // Whether the response is compressed depends on the request's encoding.\n const vary = String(res.getHeader('Vary') ?? '')\n if (!/\\baccept-encoding\\b/i.test(vary)) {\n res.setHeader('Vary', vary ? `${vary}, Accept-Encoding` : 'Accept-Encoding')\n }\n const accept = String(req.headers['accept-encoding'] ?? '')\n ;(async () => {\n // A sibling stands in for its file — never for one that's gone.\n if (!(await stat(file).catch(() => undefined))?.isFile()) return serve(req, res, next)\n for (const [encoding, ext] of ENCODINGS) {\n if (!acceptsEncoding(accept, encoding)) continue\n const sibling = await stat(file + ext).catch(() => undefined)\n if (!sibling?.isFile()) continue\n res.setHeader('Content-Encoding', encoding)\n // serve-static types the response by the path it serves only when\n // nothing has set a type — so the sibling is served as the original.\n res.setHeader('Content-Type', type)\n req.url = pathname + ext + (q === -1 ? '' : url.slice(q))\n // The sibling went away before serve-static read it: undo, carry on.\n const restore: ConnectNext = (err) => {\n res.removeHeader('Content-Encoding')\n res.removeHeader('Content-Type')\n req.url = url\n next(err)\n }\n return serve(req, res, restore)\n }\n serve(req, res, next)\n })().catch(next)\n }\n}\n"],"mappings":";;;;;;;;;;6FAcA,MAAa,mBAAuD,CAClE,KAAM,2BACN,IAAK,0BACL,GAAI,iCACJ,IAAK,iCACL,KAAM,kCACN,IAAK,kCACL,YAAa,2CACb,IAAK,gBACL,IAAK,4BACL,IAAK,iCACL,KAAM,kBACR,EAGM,UAAY,CAChB,CAAC,KAAM,KAAK,EACZ,CAAC,OAAQ,KAAK,CAChB,EAGA,SAAgB,gBAAgB,OAAgB,SAA2B,CACzE,IAAI,KAAO,GACX,IAAK,IAAM,QAAQ,OAAO,YAAY,CAAC,CAAC,MAAM,GAAG,EAAG,CAClD,GAAM,CAAC,KAAM,GAAG,QAAU,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,EACzC,EAAI,OAAO,IAAK,GAAM,EAAE,KAAK,CAAC,CAAC,CAAC,KAAM,GAAM,EAAE,WAAW,IAAI,CAAC,EAC9D,QAAU,CAAC,GAAK,OAAO,EAAE,MAAM,CAAC,CAAC,EAAI,EAC3C,GAAI,OAAS,SAAU,OAAO,QAC1B,OAAS,MAAK,KAAO,QAC3B,CACA,OAAO,IACT,CAGA,SAAgB,kBAAkB,KAAc,MAAuC,CACrF,IAAM,KAAO,QAAQ,IAAI,EACzB,OAAQ,IAAK,IAAK,OAAS,CAEzB,GAAK,IAAI,SAAW,OAAS,IAAI,SAAW,QAAW,IAAI,QAAQ,MACjE,OAAO,MAAM,IAAK,IAAK,IAAI,EAE7B,IAAM,IAAM,IAAI,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AEhC,MAAM,IAAK,IAAK,IAAI,CACtB,EAAA,CAAG,CAAC,CAAC,MAAM,IAAI,CACjB,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  const FILTER_OPERATORS=/* @__PURE__ */ new Set([`eq`,`neq`,`gt`,`gte`,`lt`,`lte`,`between`,`in`,`contains`,`starts`,`ends`]),BUILTIN_DEFAULTS={maxLimit:100,defaultLimit:20,maxSearchLength:200,defaultPage:1},defaults={...BUILTIN_DEFAULTS};function setQueryParsingDefaults(partial){partial.maxLimit!==void 0&&(defaults.maxLimit=partial.maxLimit),partial.defaultLimit!==void 0&&(defaults.defaultLimit=partial.defaultLimit),partial.maxSearchLength!==void 0&&(defaults.maxSearchLength=partial.maxSearchLength)}function getQueryParsingDefaults(){return{...defaults}}function resetQueryParsingDefaults(){Object.assign(defaults,BUILTIN_DEFAULTS)}function parseFilters(filterParam,allowedFields,options){if(!filterParam)return[];let items=Array.isArray(filterParam)?filterParam:[filterParam],results=[],allowed=allowedFields?new Set(allowedFields):null,onReject=options?.onReject;for(let item of items){let firstColon=item.indexOf(`:`);if(firstColon===-1)continue;let secondColon=item.indexOf(`:`,firstColon+1);if(secondColon===-1)continue;let field=item.slice(0,firstColon),operator=item.slice(firstColon+1,secondColon),value=item.slice(secondColon+1);field&&value&&(FILTER_OPERATORS.has(operator)?allowed&&!allowed.has(field)?onReject?.({kind:`filter`,field,reason:`field-not-allowed`}):results.push({field,operator,value}):onReject?.({kind:`filter`,field,reason:`unknown-operator`}))}return results}function parseSort(sortParam,allowedFields,options){if(!sortParam)return[];let items=(Array.isArray(sortParam)?sortParam:[sortParam]).flatMap(s=>s.split(`,`)),results=[],allowed=allowedFields?new Set(allowedFields):null,onReject=options?.onReject;for(let raw of items){let item=raw.trim();if(!item)continue;let field,dir,lastColon=item.lastIndexOf(`:`);lastColon===-1?item.startsWith(`-`)?(field=item.slice(1),dir=`desc`):(field=item.startsWith(`+`)?item.slice(1):item,dir=`asc`):(field=item.slice(0,lastColon),dir=item.slice(lastColon+1).toLowerCase()),field&&(dir===`asc`||dir===`desc`)&&(allowed&&!allowed.has(field)?onReject?.({kind:`sort`,field,reason:`field-not-allowed`}):results.push({field,direction:dir}))}return results}function parsePagination(params,options){let defaultLimit=options?.defaultLimit??defaults.defaultLimit,maxLimit=options?.maxLimit??defaults.maxLimit,page=typeof params.page==`string`?Number.parseInt(params.page,10):params.page??defaults.defaultPage,limit=typeof params.limit==`string`?Number.parseInt(params.limit,10):params.limit??defaultLimit;return(Number.isNaN(page)||page<1)&&(page=defaults.defaultPage),(Number.isNaN(limit)||limit<1)&&(limit=defaultLimit),limit>maxLimit&&(limit=maxLimit),{page,limit,offset:(page-1)*limit}}function parseSearchQuery(q,options){if(!q)return``;let maxLen=options?.maxSearchLength??defaults.maxSearchLength,trimmed=q.trim();return trimmed.length>maxLen?(options?.onReject?.({kind:`search`,field:`q`,reason:`truncated`}),trimmed.slice(0,maxLen)):trimmed}function normalizeFieldConfig(config){if(config)return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:void 0}:config}function parseQuery(query,fieldConfig,options){let normalized=normalizeFieldConfig(fieldConfig),rejectOpts=options?.onReject?{onReject:options.onReject}:void 0;return{filters:parseFilters(query.filter,normalized?.filterable,rejectOpts),sort:parseSort(query.sort,normalized?.sortable,rejectOpts),pagination:parsePagination({page:query.page,limit:query.limit},options),search:parseSearchQuery(query.q,options)}}function buildQueryParams(parsed){let params={};return parsed.filters?.length&&(params.filter=parsed.filters.map(f=>`${f.field}:${f.operator}:${f.value}`)),parsed.sort?.length&&(params.sort=parsed.sort.map(s=>`${s.field}:${s.direction}`)),parsed.pagination&&(params.page=parsed.pagination.page,params.limit=parsed.pagination.limit),parsed.search&&(params.q=parsed.search),params}export{parseQuery as a,resetQueryParsingDefaults as c,parsePagination as i,setQueryParsingDefaults as l,getQueryParsingDefaults as n,parseSearchQuery as o,parseFilters as r,parseSort as s,buildQueryParams as t,FILTER_OPERATORS as u};
12
- //# sourceMappingURL=query-Bs9mU4bx.mjs.map
12
+ //# sourceMappingURL=query-BIGYogvJ.mjs.map