@forinda/kickjs 10.14.1 → 10.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-DL9JPcvC.d.mts → adapter-D_nUmKEQ.d.mts} +175 -77
- package/dist/adapter-D_nUmKEQ.d.mts.map +1 -0
- package/dist/{allowed-hosts-BpKwviq5.d.mts → allowed-hosts-BQlQFt-1.d.mts} +7 -4
- package/dist/allowed-hosts-BQlQFt-1.d.mts.map +1 -0
- package/dist/{app-module-Dk2Wenqx.d.mts → app-module-BmViGLgj.d.mts} +7 -13
- package/dist/app-module-BmViGLgj.d.mts.map +1 -0
- package/dist/application-B16ltRnC.mjs +14 -0
- package/dist/application-B16ltRnC.mjs.map +1 -0
- package/dist/{application-D921r4MW.d.mts → application-ClCq0AgY.d.mts} +200 -115
- package/dist/application-ClCq0AgY.d.mts.map +1 -0
- package/dist/{body-policy-CwgUYBw7.mjs → body-policy-D8LveWmO.mjs} +2 -2
- package/dist/{body-policy-CwgUYBw7.mjs.map → body-policy-D8LveWmO.mjs.map} +1 -1
- package/dist/{bootstrap-CY0v5VVF.mjs → bootstrap-C5NvsxHQ.mjs} +3 -3
- package/dist/bootstrap-C5NvsxHQ.mjs.map +1 -0
- package/dist/{bounded-counters-CF8EnVUm.mjs → bounded-counters-BtvB2daV.mjs} +2 -2
- package/dist/{bounded-counters-CF8EnVUm.mjs.map → bounded-counters-BtvB2daV.mjs.map} +1 -1
- package/dist/{breach-padding-FBVGmcBb.d.mts → breach-padding-BUuc21Eu.d.mts} +7 -4
- package/dist/breach-padding-BUuc21Eu.d.mts.map +1 -0
- package/dist/{cache-CdRHSXow.d.mts → cache-ByX5O2Hp.d.mts} +26 -3
- package/dist/cache-ByX5O2Hp.d.mts.map +1 -0
- package/dist/{client-ip-CpEuptqr.mjs → client-ip-CWvyHmqt.mjs} +2 -2
- package/dist/{client-ip-CpEuptqr.mjs.map → client-ip-CWvyHmqt.mjs.map} +1 -1
- package/dist/config/index.d.mts +6 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-Djisd0f5.mjs → config-BIQoDNil.mjs} +3 -3
- package/dist/{config-Djisd0f5.mjs.map → config-BIQoDNil.mjs.map} +1 -1
- package/dist/{connect-BlIamapT.d.mts → connect-DamOelO8.d.mts} +1 -3
- package/dist/connect-DamOelO8.d.mts.map +1 -0
- package/dist/container-DtdUiRwr.d.mts +3 -0
- package/dist/{context-Cgr5dtIZ.mjs → context-BzFNflxV.mjs} +3 -3
- package/dist/context-BzFNflxV.mjs.map +1 -0
- package/dist/{context-errors-6x0bjldv.mjs → context-errors-BmaG4vwd.mjs} +2 -2
- package/dist/context-errors-BmaG4vwd.mjs.map +1 -0
- package/dist/{contributor-runner-DQ2fXJ29.mjs → contributor-runner-BnJzu2GI.mjs} +3 -3
- package/dist/contributor-runner-BnJzu2GI.mjs.map +1 -0
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.d.mts +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.d.mts +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.d.mts +1 -1
- package/dist/core/cron.mjs +2 -2
- package/dist/core/cron.mjs.map +1 -1
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.d.mts +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/errors.mjs.map +1 -1
- package/dist/core/interfaces.d.mts +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.d.mts +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.d.mts +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/path.mjs.map +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.d.mts +1 -1
- package/dist/core/reactivity.mjs +2 -2
- package/dist/core/reactivity.mjs.map +1 -1
- package/dist/core-Dqzah_BX.mjs +12 -0
- package/dist/core-Dqzah_BX.mjs.map +1 -0
- package/dist/{cors-BlR_b0Qb.d.mts → cors-u1OwTxQ8.d.mts} +7 -4
- package/dist/cors-u1OwTxQ8.d.mts.map +1 -0
- package/dist/{cron-BTGytNg-.d.mts → cron-Bxm2MY8u.d.mts} +10 -3
- package/dist/cron-Bxm2MY8u.d.mts.map +1 -0
- package/dist/{csrf-DOAaYozG.d.mts → csrf-8-Jknvmc.d.mts} +14 -6
- package/dist/csrf-8-Jknvmc.d.mts.map +1 -0
- package/dist/decorate-C3to8dG-.mjs +13 -0
- package/dist/decorate-C3to8dG-.mjs.map +1 -0
- package/dist/{decorators-DxNb5mWw.d.mts → decorators-Bflncyz6.d.mts} +122 -10
- package/dist/decorators-Bflncyz6.d.mts.map +1 -0
- package/dist/{define-adapter-CZCFyDp5.mjs → define-adapter-DCjNTP6m.mjs} +2 -2
- package/dist/define-adapter-DCjNTP6m.mjs.map +1 -0
- package/dist/{di-hooks-ZfnBZMDp.mjs → di-hooks-DTDy7ABs.mjs} +2 -2
- package/dist/di-hooks-DTDy7ABs.mjs.map +1 -0
- package/dist/{disposables-DFZXQuVg.mjs → disposables-BC291ukb.mjs} +1 -1
- package/dist/{driver-D_bUSW7N.mjs → driver-D59oWDec.mjs} +3 -3
- package/dist/{driver-D_bUSW7N.mjs.map → driver-D59oWDec.mjs.map} +1 -1
- package/dist/{error-handler-D7DLWe1Q.d.mts → error-handler-gZLQFHeE.d.mts} +2 -4
- package/dist/error-handler-gZLQFHeE.d.mts.map +1 -0
- package/dist/{errors-By6UueCm.d.mts → errors-CppqPy0A.d.mts} +2 -3
- package/dist/{errors-By6UueCm.d.mts.map → errors-CppqPy0A.d.mts.map} +1 -1
- package/dist/{express-31o4SoCz.mjs → express-JAXx9MK0.mjs} +3 -3
- package/dist/{express-31o4SoCz.mjs.map → express-JAXx9MK0.mjs.map} +1 -1
- package/dist/{express-lazy-GCgYyykt.mjs → express-lazy-jIFBeDpY.mjs} +3 -3
- package/dist/{express-lazy-GCgYyykt.mjs.map → express-lazy-jIFBeDpY.mjs.map} +1 -1
- package/dist/{handler-Bvs0gx1o.mjs → handler-C8iAD_xz.mjs} +3 -3
- package/dist/{handler-Bvs0gx1o.mjs.map → handler-C8iAD_xz.mjs.map} +1 -1
- package/dist/{helmet-BVuVBl-D.d.mts → helmet-1H0LKr6y.d.mts} +7 -4
- package/dist/helmet-1H0LKr6y.d.mts.map +1 -0
- package/dist/{host-CKz7eCtO.mjs → host-Crxmi91N.mjs} +2 -2
- package/dist/{host-CKz7eCtO.mjs.map → host-Crxmi91N.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.d.mts +1 -1
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
- package/dist/http/middleware/breach-padding.d.mts +1 -1
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/breach-padding.mjs.map +1 -1
- package/dist/http/middleware/cors.d.mts +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.d.mts +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.d.mts +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.d.mts +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/request-logger.mjs.map +1 -1
- package/dist/http/middleware/session.d.mts +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.d.mts +2 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.d.mts +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +4 -7
- package/dist/http/runtimes/express.d.mts.map +1 -1
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +3 -5
- package/dist/http/runtimes/fastify.d.mts.map +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -3
- package/dist/http/runtimes/h3.d.mts.map +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-Blgka75E.d.mts → index-CtjmSXFy.d.mts} +11 -5
- package/dist/index-CtjmSXFy.d.mts.map +1 -0
- package/dist/{index-DP_I4puv.d.mts → index-DoukvKwh.d.mts} +3 -7
- package/dist/index-DoukvKwh.d.mts.map +1 -0
- package/dist/index.d.mts +38 -32
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{interfaces-C6LHcYsg.d.mts → interfaces-CvO9sAea.d.mts} +3 -5
- package/dist/interfaces-CvO9sAea.d.mts.map +1 -0
- package/dist/{is-production-6wpWSGvS.mjs → is-production-LziEMGrc.mjs} +2 -2
- package/dist/{is-production-6wpWSGvS.mjs.map → is-production-LziEMGrc.mjs.map} +1 -1
- package/dist/{jobs-BTnyyRY1.mjs → jobs-D7ToA0yF.mjs} +3 -3
- package/dist/jobs-D7ToA0yF.mjs.map +1 -0
- package/dist/{kv-stores-CwJdsMln.d.mts → kv-stores-DdGPLXQG.d.mts} +33 -20
- package/dist/kv-stores-DdGPLXQG.d.mts.map +1 -0
- package/dist/{kv-stores-HUdUibOx.mjs → kv-stores-DpM57Xr5.mjs} +3 -3
- package/dist/kv-stores-DpM57Xr5.mjs.map +1 -0
- package/dist/{lazy-serve-static-CZBn-40v.mjs → lazy-serve-static-DxI2K-zs.mjs} +3 -3
- package/dist/{lazy-serve-static-CZBn-40v.mjs.map → lazy-serve-static-DxI2K-zs.mjs.map} +1 -1
- package/dist/{logger-xE9qI_FS.d.mts → logger-ByJsVwqY.d.mts} +3 -5
- package/dist/logger-ByJsVwqY.d.mts.map +1 -0
- package/dist/{metadata-UjLEzS06.mjs → metadata-nTTSnVTO.mjs} +1 -1
- package/dist/{observers-C4bWQTop.mjs → observers-fQtCIKLq.mjs} +2 -2
- package/dist/observers-fQtCIKLq.mjs.map +1 -0
- package/dist/{path-CMwIHsdv.d.mts → path-DsenzqJ7.d.mts} +1 -3
- package/dist/path-DsenzqJ7.d.mts.map +1 -0
- package/dist/{precompressed-BNkw1Vrz.mjs → precompressed-BtwmgzyS.mjs} +2 -2
- package/dist/{precompressed-BNkw1Vrz.mjs.map → precompressed-BtwmgzyS.mjs.map} +1 -1
- package/dist/{query-DXIo1mII.mjs → query-Dr28oT30.mjs} +2 -2
- package/dist/query-Dr28oT30.mjs.map +1 -0
- package/dist/{rate-limit-DQDk6bAH.d.mts → rate-limit-BQx_P6gG.d.mts} +13 -5
- package/dist/rate-limit-BQx_P6gG.d.mts.map +1 -0
- package/dist/{reactivity-DZrc3Yhu.d.mts → reactivity-KZOrwVeK.d.mts} +32 -3
- package/dist/reactivity-KZOrwVeK.d.mts.map +1 -0
- package/dist/{reply-CpMbB8uH.mjs → reply-ChoI5SvM.mjs} +3 -3
- package/dist/{reply-CpMbB8uH.mjs.map → reply-ChoI5SvM.mjs.map} +1 -1
- package/dist/{request-id-Dn64nEHK.d.mts → request-id-B9Myiv75.d.mts} +3 -4
- package/dist/request-id-B9Myiv75.d.mts.map +1 -0
- package/dist/{request-logger-TgcKRNDD.d.mts → request-logger-CYyAuPmo.d.mts} +6 -3
- package/dist/request-logger-CYyAuPmo.d.mts.map +1 -0
- package/dist/{request-scope-DZQceiLY.mjs → request-scope-BfSNdmz9.mjs} +3 -3
- package/dist/{request-scope-DZQceiLY.mjs.map → request-scope-BfSNdmz9.mjs.map} +1 -1
- package/dist/{respond-Bc71p7sN.mjs → respond-1BjaDME9.mjs} +2 -2
- package/dist/{respond-Bc71p7sN.mjs.map → respond-1BjaDME9.mjs.map} +1 -1
- package/dist/rolldown-runtime-B5KeNctS.mjs +11 -0
- package/dist/{route-flag-DWNbpMIE.mjs → route-flag-B6ZmhkfI.mjs} +3 -3
- package/dist/{route-flag-DWNbpMIE.mjs.map → route-flag-B6ZmhkfI.mjs.map} +1 -1
- package/dist/{route-flag-B1lQht6v.d.mts → route-flag-CjXQl-oX.d.mts} +1 -3
- package/dist/route-flag-CjXQl-oX.d.mts.map +1 -0
- package/dist/{route-policy-DsdJx3bk.mjs → route-policy-BG--gAcF.mjs} +2 -2
- package/dist/route-policy-BG--gAcF.mjs.map +1 -0
- package/dist/{router-builder-C5EtcFSL.d.mts → router-builder-BkIW_qjz.d.mts} +4 -5
- package/dist/router-builder-BkIW_qjz.d.mts.map +1 -0
- package/dist/{router-builder-CiwYhiUM.mjs → router-builder-DHKtp4I8.mjs} +3 -3
- package/dist/router-builder-DHKtp4I8.mjs.map +1 -0
- package/dist/{runtime-Bus9RVyU.mjs → runtime-CUfFIHiC.mjs} +3 -3
- package/dist/runtime-CUfFIHiC.mjs.map +1 -0
- package/dist/{session-DQG72vCf.d.mts → session-DPTbfwKO.d.mts} +41 -4
- package/dist/session-DPTbfwKO.d.mts.map +1 -0
- package/dist/{settings-DgZLgcNU.d.mts → settings-CB6lh6_s.d.mts} +1 -3
- package/dist/settings-CB6lh6_s.d.mts.map +1 -0
- package/dist/{settings-CNZ7iRli.mjs → settings-I7GUX5ps.mjs} +4 -4
- package/dist/settings-I7GUX5ps.mjs.map +1 -0
- package/dist/{token-CroYM4Lm.mjs → token-uWfhVlfe.mjs} +1 -1
- package/dist/{upload-DnwvZQyi.d.mts → upload-O3VTcODy.d.mts} +4 -6
- package/dist/upload-O3VTcODy.d.mts.map +1 -0
- package/dist/{upload-config-Bq3qcDel.mjs → upload-config-BXqBuyza.mjs} +2 -2
- package/dist/{upload-config-Bq3qcDel.mjs.map → upload-config-BXqBuyza.mjs.map} +1 -1
- package/dist/url-for-CuMaQ2wS.mjs +12 -0
- package/dist/url-for-CuMaQ2wS.mjs.map +1 -0
- package/dist/{validate-D4Poe2EE.d.mts → validate-CTgfm7oE.d.mts} +3 -5
- package/dist/validate-CTgfm7oE.d.mts.map +1 -0
- package/dist/{view-renderer-Dbha_94K.mjs → view-renderer-Bf1Wy-DQ.mjs} +3 -3
- package/dist/view-renderer-Bf1Wy-DQ.mjs.map +1 -0
- package/dist/{web-crypto-CJiyfQrv.mjs → web-crypto-JzoGmiG0.mjs} +2 -2
- package/dist/{web-crypto-CJiyfQrv.mjs.map → web-crypto-JzoGmiG0.mjs.map} +1 -1
- package/dist/web.d.mts +7 -13
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +13 -13
- package/dist/adapter-DL9JPcvC.d.mts.map +0 -1
- package/dist/allowed-hosts-BpKwviq5.d.mts.map +0 -1
- package/dist/app-module-Dk2Wenqx.d.mts.map +0 -1
- package/dist/application-BosHcuBZ.mjs +0 -14
- package/dist/application-BosHcuBZ.mjs.map +0 -1
- package/dist/application-D921r4MW.d.mts.map +0 -1
- package/dist/bootstrap-CY0v5VVF.mjs.map +0 -1
- package/dist/breach-padding-FBVGmcBb.d.mts.map +0 -1
- package/dist/cache-CdRHSXow.d.mts.map +0 -1
- package/dist/connect-BlIamapT.d.mts.map +0 -1
- package/dist/container-4iJdDkRH.d.mts +0 -3
- package/dist/context-Cgr5dtIZ.mjs.map +0 -1
- package/dist/context-errors-6x0bjldv.mjs.map +0 -1
- package/dist/contributor-runner-DQ2fXJ29.mjs.map +0 -1
- package/dist/core-g3y9VDwr.mjs +0 -12
- package/dist/core-g3y9VDwr.mjs.map +0 -1
- package/dist/cors-BlR_b0Qb.d.mts.map +0 -1
- package/dist/cron-BTGytNg-.d.mts.map +0 -1
- package/dist/csrf-DOAaYozG.d.mts.map +0 -1
- package/dist/decorate-LMK39Sn6.mjs +0 -13
- package/dist/decorate-LMK39Sn6.mjs.map +0 -1
- package/dist/decorators-DxNb5mWw.d.mts.map +0 -1
- package/dist/define-adapter-CZCFyDp5.mjs.map +0 -1
- package/dist/di-hooks-ZfnBZMDp.mjs.map +0 -1
- package/dist/error-handler-D7DLWe1Q.d.mts.map +0 -1
- package/dist/helmet-BVuVBl-D.d.mts.map +0 -1
- package/dist/index-Blgka75E.d.mts.map +0 -1
- package/dist/index-DP_I4puv.d.mts.map +0 -1
- package/dist/interfaces-C6LHcYsg.d.mts.map +0 -1
- package/dist/jobs-BTnyyRY1.mjs.map +0 -1
- package/dist/kv-stores-CwJdsMln.d.mts.map +0 -1
- package/dist/kv-stores-HUdUibOx.mjs.map +0 -1
- package/dist/logger-xE9qI_FS.d.mts.map +0 -1
- package/dist/observers-C4bWQTop.mjs.map +0 -1
- package/dist/path-CMwIHsdv.d.mts.map +0 -1
- package/dist/query-DXIo1mII.mjs.map +0 -1
- package/dist/rate-limit-DQDk6bAH.d.mts.map +0 -1
- package/dist/reactivity-DZrc3Yhu.d.mts.map +0 -1
- package/dist/request-id-Dn64nEHK.d.mts.map +0 -1
- package/dist/request-logger-TgcKRNDD.d.mts.map +0 -1
- package/dist/rolldown-runtime-Z3gdyCfQ.mjs +0 -11
- package/dist/route-flag-B1lQht6v.d.mts.map +0 -1
- package/dist/route-policy-DsdJx3bk.mjs.map +0 -1
- package/dist/router-builder-C5EtcFSL.d.mts.map +0 -1
- package/dist/router-builder-CiwYhiUM.mjs.map +0 -1
- package/dist/runtime-Bus9RVyU.mjs.map +0 -1
- package/dist/session-DQG72vCf.d.mts.map +0 -1
- package/dist/settings-CNZ7iRli.mjs.map +0 -1
- package/dist/settings-DgZLgcNU.d.mts.map +0 -1
- package/dist/upload-DnwvZQyi.d.mts.map +0 -1
- package/dist/url-for-BCQLTEJj.mjs +0 -12
- package/dist/url-for-BCQLTEJj.mjs.map +0 -1
- package/dist/validate-D4Poe2EE.d.mts.map +0 -1
- package/dist/view-renderer-Dbha_94K.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"application-ClCq0AgY.d.mts","names":["_$__0.AdapterFactory","Request","Response","NextFunction","Request","Response","NextFunction","_$_____0.AdapterFactory","_$_____0.AdapterFactory","_$__reply0.Reply","_$__0.ModuleFactory"],"sources":["../src/core/kick-error.ts","../src/core/circuit-breaker.ts","../src/core/context-errors.ts","../src/core/mount-sort.ts","../src/core/asset-keys.ts","../src/core/route-policy.ts","../src/http/startup-timeline.ts","../src/http/startup-checks.ts","../src/http/cache-response.ts","../src/http/metrics.ts","../src/http/body-policy.ts","../src/http/cron-adapter.ts","../src/http/tracing.ts","../src/http/bootstrap.ts","../src/http/handler.ts","../src/http/cluster.ts","../src/http/define-http-context-decorator.ts","../src/core/password.ts","../src/core/signing.ts","../src/http/form.ts","../src/http/middleware/form-errors.ts","../src/http/runtimes/express-lazy.ts","../src/http/request-store.ts","../src/http/middleware/request-scope.ts","../src/http/middleware/trace-context.ts","../src/http/middleware/views.ts","../src/http/middleware/spa.ts","../src/http/health-module.ts","../src/http/application.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;UACiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBC,kBAAkB;WACb;WACA;WACA;WACA;WACA;WACA,UAAU;EAE1B,YAAY,MAAM;;;UAkDH;;;;;;EAMf;;;;;;;iBAQc,gBACd,KAAK,gBAAgB,WACrB,UAAS;KC7GC;;UAGK;;EAEf;;EAEA;;EAEA;;;UAIe;EACf;EACA;EACA,OAAO;EACP,cAAc;;;;;cAMH,yBAAyB;WACR;EAA5B,YAA4B;;;;;;;;;;;;;;;;;;;;;cAyBjB;WAaO;UAZV;UACA;UACA;UACA;UACA;UACA;mBAES;mBACA;mBACA;EAEjB,YACkB,cAChB,SAAS;;;;;EAWL,QAAQ,GAAG,UAAU,QAAQ,KAAK,QAAQ;;EA0BhD,YAAY;;EAMZ,YAAY;;EAWZ;UASQ;UAWA;UAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;cC7HG,gCAAgC;WAClC;WACA;WACA;WACA;EAET,YAAY,aAAa,mBAAmB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0CjD,iCAAiC;WACnC;WACA;EAET,YAAY,aAAa;;;;;;;;;;;;cA6Cd,8BAA8B;WAChC;WACA;EAET,YAAY,0BAA0B;;;;;;;;;;;;;;;;;;;cA0B3B,kCAAkC;WACpC;WACA;EAET,YAAY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;;;;;;;;;EAatB,OAAO,UAAU,WAAW,MAAM,MAAM,MAAM,WAAW;;UAMjD;;;;;;;;EAkBR,kBAAkB;;;;;;;EAyClB,iBAAiB;;UAuBT;;UAgBA;;UAUA;EAUF,SAAS;;EAkgBT,gBAAgB;;;;;;;;;EAYhB,sBAAsB;;;;;UAQd;UASA;;;;;;;;;;EAmCR,SAAS;UAID;;UA0FA;UA6CA;;UAWA;;UAwBN;UAeA;;EAsBF,WAAW;;;;;;;;;;;EAgEjB,SAAS,UAAS,kBAAuB;UAW3B;;;;;;;EA4Ld,iBAAiB;;;;;;;;EAWjB;IAAsB;IAAc,cAAc;;;EAKlD,iBAAiB;;EAKjB,eAAe;;;;;;EASf,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;EA2BvB,sBAAsB;EAItB,mBAAmB;IACjB;IACA;IACA;IACA;;EA+DF,iBAAiB;;;;;;EASjB,uBAAuB,KAAK,SAAS,MAAM;;;;;;;;;;;;;;UAmBnC;UAWA;UAmBA;UAUA;;;;;;;;UAeA;;UAoBA;;;;;;iBAgDM,eAAe,iBAAiB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import{HttpException}from"./core/errors.mjs";function normalizeMediaType(contentType){return((Array.isArray(contentType)?contentType[0]:contentType)??``).split(`;`)[0].trim().toLowerCase()}function isJsonMediaType(mediaType){return mediaType===`application/json`||/^application\/[\w.+-]+\+json$/.test(mediaType)}function classifyMediaType(contentType){let mediaType=normalizeMediaType(contentType);return mediaType?isJsonMediaType(mediaType)?`json`:mediaType===`application/x-www-form-urlencoded`?`urlencoded`:mediaType.startsWith(`multipart/`)?`multipart`:mediaType.startsWith(`text/`)?`text`:`unsupported`:`unsupported`}const EXPRESS_JSON_TYPES=[`application/json`,`application/*+json`],SUPPORTED_BODY_TYPES=[`application/json`,`application/*+json`,`application/x-www-form-urlencoded`,`text/*`,`multipart/form-data`];function unsupportedMediaTypeError(contentType){let mediaType=normalizeMediaType(contentType);return new HttpException(415,mediaType?`Unsupported Media Type: ${mediaType}`:`Unsupported Media Type: request has a body but no Content-Type`,void 0,{Accept:SUPPORTED_BODY_TYPES.join(`, `)})}const BODY_METHODS=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]),RAW_BODY=Symbol.for(`kick/http/raw-body`);function rejectUnsupportedBody(){return(req,_res,next)=>{if(!BODY_METHODS.has((req.method??`GET`).toUpperCase())||req[RAW_BODY]||classifyMediaType(req.headers?.[`content-type`])!==`unsupported`)return next();let reject=()=>next(unsupportedMediaTypeError(req.headers?.[`content-type`])),length=req.headers?.[`content-length`];if(length!==void 0)return length===`0`?next():reject();if(req.headers?.[`transfer-encoding`]===void 0)return next();let decided=!1,settle=fn=>()=>{decided||(decided=!0,req.off?.(`data`,onData),req.off?.(`end`,onEnd),fn())},onData=settle(reject),onEnd=settle(()=>next());req.on?.(`data`,onData),req.on?.(`end`,onEnd)}}const BYTE_UNITS={b:1,kb:1024,mb:1024**2,gb:1024**3};function parseByteSize(value){if(typeof value==`number`)return value;let match=/^\s*(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?\s*$/i.exec(value);if(!match)throw Error(`Invalid body size limit: '${value}'`);return Math.floor(Number(match[1])*BYTE_UNITS[(match[2]??`b`).toLowerCase()])}function tooLarge(limit){return new HttpException(413,`Request body is larger than the ${limit}-byte limit`)}async function readBodyBytes(request,limit){if(Number(request.headers.get(`content-length`))>limit)throw tooLarge(limit);if(!request.body)return/* @__PURE__ */ new Uint8Array;let reader=request.body.getReader(),chunks=[],size=0;for(;;){let{done,value}=await reader.read();if(done)break;if(size+=value.byteLength,size>limit)throw await reader.cancel().catch(()=>{}),tooLarge(limit);chunks.push(value)}let bytes=new Uint8Array(size),offset=0;for(let chunk of chunks)bytes.set(chunk,offset),offset+=chunk.byteLength;return bytes}async function readBodyText(request,limit){return new TextDecoder().decode(await readBodyBytes(request,limit))}function parseForm(raw){return formFields(new URLSearchParams(raw))}function formFields(pairs){let fields=/* @__PURE__ */ new Map;for(let[key,value]of pairs){let prev=fields.get(key);prev===void 0?fields.set(key,value):Array.isArray(prev)?prev.push(value):fields.set(key,[prev,value])}return Object.fromEntries(fields)}function hasPrototypeKey(value){let pending=[value],seen=/* @__PURE__ */ new Set;for(;pending.length>0;){let current=pending.pop();if(typeof current!=`object`||!current||seen.has(current)||ArrayBuffer.isView(current))continue;if(seen.add(current),Object.hasOwn(current,`__proto__`))return!0;let ctor=Object.hasOwn(current,`constructor`)?current.constructor:void 0;if(typeof ctor==`object`&&ctor&&Object.hasOwn(ctor,`prototype`))return!0;for(let key of Object.keys(current))pending.push(current[key])}return!1}function prototypeKeyError(){return HttpException.badRequest(`A body key that sets a prototype (__proto__, constructor.prototype) is not allowed`)}export{hasPrototypeKey as a,prototypeKeyError as c,rejectUnsupportedBody as d,tooLarge as f,formFields as i,readBodyBytes as l,RAW_BODY as n,parseByteSize as o,unsupportedMediaTypeError as p,classifyMediaType as r,parseForm as s,EXPRESS_JSON_TYPES as t,readBodyText as u};
|
|
12
|
-
//# sourceMappingURL=body-policy-
|
|
12
|
+
//# sourceMappingURL=body-policy-D8LveWmO.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"body-policy-CwgUYBw7.mjs","names":[],"sources":["../src/http/body-policy.ts"],"sourcesContent":["/**\n * How a request body is interpreted, decided in ONE place for every runtime.\n *\n * Before this, each engine brought its own library's opinion: Express parsed\n * only exact `application/json` and silently left everything else `undefined`,\n * Fastify answered 415 for anything it had no parser for, and h3 routed\n * unrecognised types through `destr` — so the same request produced a parsed\n * object, an empty body, or a 415 depending on which engine the app was\n * configured with. The runtime is meant to be swappable; that made it not\n * swappable for any app accepting a body outside `application/json` (#590).\n *\n * @module @forinda/kickjs/http/body-policy\n */\n\nimport { HttpException } from '../core/errors'\n\n/**\n * A header as the runtimes hand it over. Node's `IncomingHttpHeaders` and\n * Fastify's normalised map both allow `string[]`, so take the union here\n * rather than casting at every call site.\n */\nexport type HeaderValue = string | string[] | undefined\n\n/** What the framework does with a body of a given media type. */\nexport type BodyKind =\n /** Parse as JSON, strictly. */\n | 'json'\n /** Parse as `application/x-www-form-urlencoded` into an object. */\n | 'urlencoded'\n /** Hand the handler the raw string. Never JSON — see `classifyMediaType`. */\n | 'text'\n /** Left to the upload path, which consumes the stream itself. */\n | 'multipart'\n /** Not parsed. `ctx.body` stays undefined. */\n | 'unsupported'\n\n/**\n * Strip parameters and normalise: `Application/JSON; charset=utf-8` →\n * `application/json`. h3's own check is `===` against the bare type, which is\n * why `application/json; charset=utf-8` — what most clients actually send —\n * missed it and fell to a non-strict branch.\n */\nexport function normalizeMediaType(contentType: HeaderValue): string {\n const value = Array.isArray(contentType) ? contentType[0] : contentType\n return (value ?? '').split(';')[0].trim().toLowerCase()\n}\n\n/**\n * `application/*+json` is JSON, and this is not a judgement call: RFC 6838\n * §4.2.8 says a media type \"MUST NOT be given names incorporating suffixes for\n * structured syntaxes they do not actually employ\", and RFC 6839 §2 exists so\n * receivers can \"do generic processing of the underlying representation\".\n * Spring, ASP.NET Core and Hono's validator all match the suffix by default.\n *\n * So `application/merge-patch+json` (RFC 7396) and `application/problem+json`\n * (RFC 9457) parse as JSON — which the framework already emits for every\n * problem response, and previously could not read back.\n */\nfunction isJsonMediaType(mediaType: string): boolean {\n return mediaType === 'application/json' || /^application\\/[\\w.+-]+\\+json$/.test(mediaType)\n}\n\n/**\n * Decide how to treat a body, from its declared media type alone.\n *\n * `text/*` deliberately yields the raw string and is NEVER JSON-parsed.\n * `text/plain` is one of three CORS-safelisted content types, so it crosses\n * origins without a preflight; JSON-parsing it would re-open the simple-request\n * CSRF that requiring `application/json` closes. h3's own source carries this\n * warning, and h3 v2 pulled back from `destr` partly because of it.\n */\nexport function classifyMediaType(contentType: HeaderValue): BodyKind {\n const mediaType = normalizeMediaType(contentType)\n if (!mediaType) return 'unsupported'\n if (isJsonMediaType(mediaType)) return 'json'\n if (mediaType === 'application/x-www-form-urlencoded') return 'urlencoded'\n if (mediaType.startsWith('multipart/')) return 'multipart'\n if (mediaType.startsWith('text/')) return 'text'\n return 'unsupported'\n}\n\n/**\n * Media types Express should hand to its JSON body parser. `express.json()`\n * defaults to the exact string `application/json`, and `type-is` will not match\n * `application/json` against a bare wildcard-plus-json pattern (a length guard rejects\n * it), so BOTH entries are required — passing only the wildcard silently stops\n * parsing ordinary JSON.\n */\nexport const EXPRESS_JSON_TYPES = ['application/json', 'application/*+json'] as const\n\n/** Media types the framework claims to parse, for diagnostics and docs. */\nexport const SUPPORTED_BODY_TYPES = [\n 'application/json',\n 'application/*+json',\n 'application/x-www-form-urlencoded',\n 'text/*',\n 'multipart/form-data',\n] as const\n\n/**\n * The 415 for a body whose media type the framework does not parse.\n *\n * Only ever raised when a body was actually SENT. An absent or empty body is\n * treated as absent regardless of its declared type — the same call Spring's\n * `readWithMessageConverters` and ASP.NET's `BodyModelBinder` both make, and\n * the reason neither rejects a bodyless POST. A bare `POST` with no payload is\n * a legitimate request, not an unsupported one.\n *\n * Carries `Accept`, which RFC 9110 §15.5.16 says a 415 \"can\" use to indicate\n * which media types would have been accepted.\n */\nexport function unsupportedMediaTypeError(contentType: HeaderValue): HttpException {\n const mediaType = normalizeMediaType(contentType)\n return new HttpException(\n 415,\n mediaType\n ? `Unsupported Media Type: ${mediaType}`\n : 'Unsupported Media Type: request has a body but no Content-Type',\n undefined,\n { Accept: SUPPORTED_BODY_TYPES.join(', ') },\n )\n}\n\n/** Verbs whose body the framework reads. */\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Did this request actually carry a body? Decided from the framing headers\n * rather than from whether a parser produced anything — the distinction that\n * separates \"nothing was sent\" from \"something was sent that we could not\n * read\", which is the whole basis for answering 415 on one and 200 on the other.\n */\nexport function hasRequestBody(headers: Record<string, unknown>): boolean {\n const length = headers['content-length'] as string | undefined\n const encoding = headers['transfer-encoding'] as string | undefined\n return encoding !== undefined || (length !== undefined && length !== '0')\n}\n\n/**\n * Set to `true` on a request (`req[RAW_BODY] = true`) by middleware that will\n * read the body stream itself — a tus endpoint, a proxy — so the 415 below\n * leaves it alone. Mark it in an earlier phase (an adapter's `beforeGlobal`),\n * consume it later.\n */\nexport const RAW_BODY = Symbol.for('kick/http/raw-body')\n\n/**\n * Connect middleware that answers 415 for a body Express's parsers left\n * untouched.\n *\n * Express has no concept of an unsupported type: a parser whose `type` does not\n * match simply calls `next()` and leaves `req.body` undefined, indistinguishable\n * from a request that sent nothing. Mounted after the parsers, this restores the\n * distinction so Express agrees with the other runtimes.\n */\nexport function rejectUnsupportedBody() {\n return (req: any, _res: unknown, next: (err?: unknown) => void): void => {\n if (!BODY_METHODS.has((req.method ?? 'GET').toUpperCase())) return next()\n if (req[RAW_BODY]) return next()\n if (classifyMediaType(req.headers?.['content-type']) !== 'unsupported') return next()\n\n const reject = (): void => next(unsupportedMediaTypeError(req.headers?.['content-type']))\n const length = req.headers?.['content-length'] as string | undefined\n if (length !== undefined) return length === '0' ? next() : reject()\n if (req.headers?.['transfer-encoding'] === undefined) return next()\n\n // Chunked: the framing headers say a body MAY follow, but an empty chunked\n // post sends none. Deciding on the headers alone would 415 a request that\n // sent nothing, so wait to see whether a byte actually arrives — the same\n // distinction the other runtimes make by inspecting the read body.\n let decided = false\n const settle = (fn: () => void) => (): void => {\n if (decided) return\n decided = true\n req.off?.('data', onData)\n req.off?.('end', onEnd)\n fn()\n }\n const onData = settle(reject)\n const onEnd = settle(() => next())\n req.on?.('data', onData)\n req.on?.('end', onEnd)\n }\n}\n\n/** Default body size limit — Express's `express.json()` default. */\nexport const DEFAULT_BODY_LIMIT = '1mb'\n\nconst BYTE_UNITS: Record<string, number> = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 }\n\n/**\n * `'1mb'` / `'512kb'` / `1048576` → bytes, the forms `express.json({ limit })`\n * accepts (1024-based, like the `bytes` package Express uses), so one\n * `jsonLimit` means the same size on every engine.\n */\nexport function parseByteSize(value: string | number): number {\n if (typeof value === 'number') return value\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb)?\\s*$/i.exec(value)\n if (!match) throw new Error(`Invalid body size limit: '${value}'`)\n return Math.floor(Number(match[1]) * BYTE_UNITS[(match[2] ?? 'b').toLowerCase()])\n}\n\n/** The 413 for a body past `limit` bytes. */\nexport function tooLarge(limit: number): HttpException {\n return new HttpException(413, `Request body is larger than the ${limit}-byte limit`)\n}\n\n/**\n * Read a web `Request` body, refusing more than `limit` bytes with a 413 —\n * from `Content-Length` before reading, and while streaming for a body that\n * doesn't declare one (or declares less than it sends).\n */\nexport async function readBodyBytes(request: Request, limit: number): Promise<Uint8Array> {\n const declared = Number(request.headers.get('content-length'))\n if (declared > limit) throw tooLarge(limit)\n if (!request.body) return new Uint8Array(0)\n\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > limit) {\n await reader.cancel().catch(() => {})\n throw tooLarge(limit)\n }\n chunks.push(value)\n }\n const bytes = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n return bytes\n}\n\n/** {@link readBodyBytes}, decoded as UTF-8. */\nexport async function readBodyText(request: Request, limit: number): Promise<string> {\n return new TextDecoder().decode(await readBodyBytes(request, limit))\n}\n\n/**\n * `application/x-www-form-urlencoded` → object, with a repeated key becoming\n * an array — the same rule the query string follows on every engine, and\n * what Express's form parser does.\n */\nexport function parseForm(raw: string): Record<string, string | string[]> {\n return formFields(new URLSearchParams(raw))\n}\n\n/**\n * Form fields → object, a repeated name becoming an array — urlencoded bodies\n * and multipart fields alike. A Map, then fromEntries: assigning keys onto a\n * plain object would let a `__proto__` field set the result's prototype, or\n * vanish; this way it is an own key, which {@link hasPrototypeKey} refuses.\n */\nexport function formFields(\n pairs: Iterable<readonly [string, string]>,\n): Record<string, string | string[]> {\n const fields = new Map<string, string | string[]>()\n for (const [key, value] of pairs) {\n const prev = fields.get(key)\n if (prev === undefined) fields.set(key, value)\n else if (Array.isArray(prev)) prev.push(value)\n else fields.set(key, [prev, value])\n }\n return Object.fromEntries(fields)\n}\n\n/**\n * Whether parsed input carries a key that can rewrite a prototype: `__proto__`\n * anywhere, or `constructor.prototype`. A body with one is refused on every\n * engine, as Fastify's parsers already do. Harmless while it sits in the body,\n * it turns `Object.assign(target, ctx.body)` or a naive deep merge into\n * prototype pollution.\n */\nexport function hasPrototypeKey(value: unknown): boolean {\n const pending: unknown[] = [value]\n const seen = new Set<object>()\n while (pending.length > 0) {\n const current = pending.pop()\n if (current === null || typeof current !== 'object' || seen.has(current)) continue\n // Bytes (a raw body) have no keys worth walking.\n if (ArrayBuffer.isView(current)) continue\n seen.add(current)\n if (Object.hasOwn(current, '__proto__')) return true\n const ctor: unknown = Object.hasOwn(current, 'constructor')\n ? (current as { constructor: unknown }).constructor\n : undefined\n if (ctor !== null && typeof ctor === 'object' && Object.hasOwn(ctor, 'prototype')) return true\n for (const key of Object.keys(current)) pending.push((current as Record<string, unknown>)[key])\n }\n return false\n}\n\n/** The 400 for a body {@link hasPrototypeKey} refuses. */\nexport function prototypeKeyError(): HttpException {\n return HttpException.badRequest(\n 'A body key that sets a prototype (__proto__, constructor.prototype) is not allowed',\n )\n}\n"],"mappings":";;;;;;;;;;6CA0CA,SAAgB,mBAAmB,YAAkC,CAEnE,QADc,MAAM,QAAQ,WAAW,EAAI,YAAY,GAAK,cAC3C,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,YAAY,CACxD,CAaA,SAAS,gBAAgB,UAA4B,CACnD,OA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BAAgB,GAAG,CAAC,CAC5C,CAQA,SAAgB,WACd,MACmC,CACnC,IAAM,uBAAS,IAAI,IACnB,IAAK,GAAM,CAAC,IAAK,SAAU,MAAO,CAChC,IAAM,KAAO,OAAO,IAAI,GAAG,EACvB,OAAS,IAAA,GAAW,OAAO,IAAI,IAAK,KAAK,EACpC,MAAM,QAAQ,IAAI,EAAG,KAAK,KAAK,KAAK,EACxC,OAAO,IAAI,IAAK,CAAC,KAAM,KAAK,CAAC,CACpC,CACA,OAAO,OAAO,YAAY,MAAM,CAClC,CASA,SAAgB,gBAAgB,MAAyB,CACvD,IAAM,QAAqB,CAAC,KAAK,EAC3B,qBAAO,IAAI,IACjB,KAAO,QAAQ,OAAS,GAAG,CACzB,IAAM,QAAU,QAAQ,IAAI,EAG5B,GAFwB,OAAO,SAAY,WAAvC,SAAmD,KAAK,IAAI,OAAO,GAEnE,YAAY,OAAO,OAAO,EAAG,SAEjC,GADA,KAAK,IAAI,OAAO,EACZ,OAAO,OAAO,QAAS,WAAW,EAAG,MAAO,GAChD,IAAM,KAAgB,OAAO,OAAO,QAAS,aAAa,EACrD,QAAqC,YACtC,IAAA,GACJ,GAAqB,OAAO,MAAS,UAAjC,MAA6C,OAAO,OAAO,KAAM,WAAW,EAAG,MAAO,GAC1F,IAAK,IAAM,OAAO,OAAO,KAAK,OAAO,EAAG,QAAQ,KAAM,QAAoC,IAAI,CAChG,CACA,MAAO,EACT,CAGA,SAAgB,mBAAmC,CACjD,OAAO,cAAc,WACnB,oFACF,CACF"}
|
|
1
|
+
{"version":3,"file":"body-policy-D8LveWmO.mjs","names":[],"sources":["../src/http/body-policy.ts"],"sourcesContent":["/**\n * How a request body is interpreted, decided in ONE place for every runtime.\n *\n * Before this, each engine brought its own library's opinion: Express parsed\n * only exact `application/json` and silently left everything else `undefined`,\n * Fastify answered 415 for anything it had no parser for, and h3 routed\n * unrecognised types through `destr` — so the same request produced a parsed\n * object, an empty body, or a 415 depending on which engine the app was\n * configured with. The runtime is meant to be swappable; that made it not\n * swappable for any app accepting a body outside `application/json` (#590).\n *\n * @module @forinda/kickjs/http/body-policy\n */\n\nimport { HttpException } from '../core/errors'\n\n/**\n * A header as the runtimes hand it over. Node's `IncomingHttpHeaders` and\n * Fastify's normalised map both allow `string[]`, so take the union here\n * rather than casting at every call site.\n */\nexport type HeaderValue = string | string[] | undefined\n\n/** What the framework does with a body of a given media type. */\nexport type BodyKind =\n /** Parse as JSON, strictly. */\n | 'json'\n /** Parse as `application/x-www-form-urlencoded` into an object. */\n | 'urlencoded'\n /** Hand the handler the raw string. Never JSON — see `classifyMediaType`. */\n | 'text'\n /** Left to the upload path, which consumes the stream itself. */\n | 'multipart'\n /** Not parsed. `ctx.body` stays undefined. */\n | 'unsupported'\n\n/**\n * Strip parameters and normalise: `Application/JSON; charset=utf-8` →\n * `application/json`. h3's own check is `===` against the bare type, which is\n * why `application/json; charset=utf-8` — what most clients actually send —\n * missed it and fell to a non-strict branch.\n */\nexport function normalizeMediaType(contentType: HeaderValue): string {\n const value = Array.isArray(contentType) ? contentType[0] : contentType\n return (value ?? '').split(';')[0].trim().toLowerCase()\n}\n\n/**\n * `application/*+json` is JSON, and this is not a judgement call: RFC 6838\n * §4.2.8 says a media type \"MUST NOT be given names incorporating suffixes for\n * structured syntaxes they do not actually employ\", and RFC 6839 §2 exists so\n * receivers can \"do generic processing of the underlying representation\".\n * Spring, ASP.NET Core and Hono's validator all match the suffix by default.\n *\n * So `application/merge-patch+json` (RFC 7396) and `application/problem+json`\n * (RFC 9457) parse as JSON — which the framework already emits for every\n * problem response, and previously could not read back.\n */\nfunction isJsonMediaType(mediaType: string): boolean {\n return mediaType === 'application/json' || /^application\\/[\\w.+-]+\\+json$/.test(mediaType)\n}\n\n/**\n * Decide how to treat a body, from its declared media type alone.\n *\n * `text/*` deliberately yields the raw string and is NEVER JSON-parsed.\n * `text/plain` is one of three CORS-safelisted content types, so it crosses\n * origins without a preflight; JSON-parsing it would re-open the simple-request\n * CSRF that requiring `application/json` closes. h3's own source carries this\n * warning, and h3 v2 pulled back from `destr` partly because of it.\n */\nexport function classifyMediaType(contentType: HeaderValue): BodyKind {\n const mediaType = normalizeMediaType(contentType)\n if (!mediaType) return 'unsupported'\n if (isJsonMediaType(mediaType)) return 'json'\n if (mediaType === 'application/x-www-form-urlencoded') return 'urlencoded'\n if (mediaType.startsWith('multipart/')) return 'multipart'\n if (mediaType.startsWith('text/')) return 'text'\n return 'unsupported'\n}\n\n/**\n * Media types Express should hand to its JSON body parser. `express.json()`\n * defaults to the exact string `application/json`, and `type-is` will not match\n * `application/json` against a bare wildcard-plus-json pattern (a length guard rejects\n * it), so BOTH entries are required — passing only the wildcard silently stops\n * parsing ordinary JSON.\n */\nexport const EXPRESS_JSON_TYPES = ['application/json', 'application/*+json'] as const\n\n/** Media types the framework claims to parse, for diagnostics and docs. */\nexport const SUPPORTED_BODY_TYPES = [\n 'application/json',\n 'application/*+json',\n 'application/x-www-form-urlencoded',\n 'text/*',\n 'multipart/form-data',\n] as const\n\n/**\n * The 415 for a body whose media type the framework does not parse.\n *\n * Only ever raised when a body was actually SENT. An absent or empty body is\n * treated as absent regardless of its declared type — the same call Spring's\n * `readWithMessageConverters` and ASP.NET's `BodyModelBinder` both make, and\n * the reason neither rejects a bodyless POST. A bare `POST` with no payload is\n * a legitimate request, not an unsupported one.\n *\n * Carries `Accept`, which RFC 9110 §15.5.16 says a 415 \"can\" use to indicate\n * which media types would have been accepted.\n */\nexport function unsupportedMediaTypeError(contentType: HeaderValue): HttpException {\n const mediaType = normalizeMediaType(contentType)\n return new HttpException(\n 415,\n mediaType\n ? `Unsupported Media Type: ${mediaType}`\n : 'Unsupported Media Type: request has a body but no Content-Type',\n undefined,\n { Accept: SUPPORTED_BODY_TYPES.join(', ') },\n )\n}\n\n/** Verbs whose body the framework reads. */\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Did this request actually carry a body? Decided from the framing headers\n * rather than from whether a parser produced anything — the distinction that\n * separates \"nothing was sent\" from \"something was sent that we could not\n * read\", which is the whole basis for answering 415 on one and 200 on the other.\n */\nexport function hasRequestBody(headers: Record<string, unknown>): boolean {\n const length = headers['content-length'] as string | undefined\n const encoding = headers['transfer-encoding'] as string | undefined\n return encoding !== undefined || (length !== undefined && length !== '0')\n}\n\n/**\n * Set to `true` on a request (`req[RAW_BODY] = true`) by middleware that will\n * read the body stream itself — a tus endpoint, a proxy — so the 415 below\n * leaves it alone. Mark it in an earlier phase (an adapter's `beforeGlobal`),\n * consume it later.\n */\nexport const RAW_BODY = Symbol.for('kick/http/raw-body')\n\n/**\n * Connect middleware that answers 415 for a body Express's parsers left\n * untouched.\n *\n * Express has no concept of an unsupported type: a parser whose `type` does not\n * match simply calls `next()` and leaves `req.body` undefined, indistinguishable\n * from a request that sent nothing. Mounted after the parsers, this restores the\n * distinction so Express agrees with the other runtimes.\n */\nexport function rejectUnsupportedBody() {\n return (req: any, _res: unknown, next: (err?: unknown) => void): void => {\n if (!BODY_METHODS.has((req.method ?? 'GET').toUpperCase())) return next()\n if (req[RAW_BODY]) return next()\n if (classifyMediaType(req.headers?.['content-type']) !== 'unsupported') return next()\n\n const reject = (): void => next(unsupportedMediaTypeError(req.headers?.['content-type']))\n const length = req.headers?.['content-length'] as string | undefined\n if (length !== undefined) return length === '0' ? next() : reject()\n if (req.headers?.['transfer-encoding'] === undefined) return next()\n\n // Chunked: the framing headers say a body MAY follow, but an empty chunked\n // post sends none. Deciding on the headers alone would 415 a request that\n // sent nothing, so wait to see whether a byte actually arrives — the same\n // distinction the other runtimes make by inspecting the read body.\n let decided = false\n const settle = (fn: () => void) => (): void => {\n if (decided) return\n decided = true\n req.off?.('data', onData)\n req.off?.('end', onEnd)\n fn()\n }\n const onData = settle(reject)\n const onEnd = settle(() => next())\n req.on?.('data', onData)\n req.on?.('end', onEnd)\n }\n}\n\n/** Default body size limit — Express's `express.json()` default. */\nexport const DEFAULT_BODY_LIMIT = '1mb'\n\nconst BYTE_UNITS: Record<string, number> = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 }\n\n/**\n * `'1mb'` / `'512kb'` / `1048576` → bytes, the forms `express.json({ limit })`\n * accepts (1024-based, like the `bytes` package Express uses), so one\n * `jsonLimit` means the same size on every engine.\n */\nexport function parseByteSize(value: string | number): number {\n if (typeof value === 'number') return value\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb)?\\s*$/i.exec(value)\n if (!match) throw new Error(`Invalid body size limit: '${value}'`)\n return Math.floor(Number(match[1]) * BYTE_UNITS[(match[2] ?? 'b').toLowerCase()])\n}\n\n/** The 413 for a body past `limit` bytes. */\nexport function tooLarge(limit: number): HttpException {\n return new HttpException(413, `Request body is larger than the ${limit}-byte limit`)\n}\n\n/**\n * Read a web `Request` body, refusing more than `limit` bytes with a 413 —\n * from `Content-Length` before reading, and while streaming for a body that\n * doesn't declare one (or declares less than it sends).\n */\nexport async function readBodyBytes(request: Request, limit: number): Promise<Uint8Array> {\n const declared = Number(request.headers.get('content-length'))\n if (declared > limit) throw tooLarge(limit)\n if (!request.body) return new Uint8Array(0)\n\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > limit) {\n await reader.cancel().catch(() => {})\n throw tooLarge(limit)\n }\n chunks.push(value)\n }\n const bytes = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n return bytes\n}\n\n/** {@link readBodyBytes}, decoded as UTF-8. */\nexport async function readBodyText(request: Request, limit: number): Promise<string> {\n return new TextDecoder().decode(await readBodyBytes(request, limit))\n}\n\n/**\n * `application/x-www-form-urlencoded` → object, with a repeated key becoming\n * an array — the same rule the query string follows on every engine, and\n * what Express's form parser does.\n */\nexport function parseForm(raw: string): Record<string, string | string[]> {\n return formFields(new URLSearchParams(raw))\n}\n\n/**\n * Form fields → object, a repeated name becoming an array — urlencoded bodies\n * and multipart fields alike. A Map, then fromEntries: assigning keys onto a\n * plain object would let a `__proto__` field set the result's prototype, or\n * vanish; this way it is an own key, which {@link hasPrototypeKey} refuses.\n */\nexport function formFields(\n pairs: Iterable<readonly [string, string]>,\n): Record<string, string | string[]> {\n const fields = new Map<string, string | string[]>()\n for (const [key, value] of pairs) {\n const prev = fields.get(key)\n if (prev === undefined) fields.set(key, value)\n else if (Array.isArray(prev)) prev.push(value)\n else fields.set(key, [prev, value])\n }\n return Object.fromEntries(fields)\n}\n\n/**\n * Whether parsed input carries a key that can rewrite a prototype: `__proto__`\n * anywhere, or `constructor.prototype`. A body with one is refused on every\n * engine, as Fastify's parsers already do. Harmless while it sits in the body,\n * it turns `Object.assign(target, ctx.body)` or a naive deep merge into\n * prototype pollution.\n */\nexport function hasPrototypeKey(value: unknown): boolean {\n const pending: unknown[] = [value]\n const seen = new Set<object>()\n while (pending.length > 0) {\n const current = pending.pop()\n if (current === null || typeof current !== 'object' || seen.has(current)) continue\n // Bytes (a raw body) have no keys worth walking.\n if (ArrayBuffer.isView(current)) continue\n seen.add(current)\n if (Object.hasOwn(current, '__proto__')) return true\n const ctor: unknown = Object.hasOwn(current, 'constructor')\n ? (current as { constructor: unknown }).constructor\n : undefined\n if (ctor !== null && typeof ctor === 'object' && Object.hasOwn(ctor, 'prototype')) return true\n for (const key of Object.keys(current)) pending.push((current as Record<string, unknown>)[key])\n }\n return false\n}\n\n/** The 400 for a body {@link hasPrototypeKey} refuses. */\nexport function prototypeKeyError(): HttpException {\n return HttpException.badRequest(\n 'A body key that sets a prototype (__proto__, constructor.prototype) is not allowed',\n )\n}\n"],"mappings":";;;;;;;;;;A,6CA0CA,SAAgB,mBAAmB,YAAkC,CAEnE,QADc,MAAM,QAAQ,WAAW,EAAI,YAAY,GAAK,cAC3C,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,YAAY,CACxD,CAaA,SAA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
|
12
|
-
//# sourceMappingURL=bootstrap-
|
|
11
|
+
import{r as reportError}from"./observers-fQtCIKLq.mjs";import{Container}from"./core/container.mjs";import"./core-Dqzah_BX.mjs";import{c as reloadEnv}from"./decorate-C3to8dG-.mjs";import{n as Application}from"./application-B16ltRnC.mjs";import{t as defineAdapter}from"./define-adapter-DCjNTP6m.mjs";import{createLogger}from"./core/logger.mjs";import{listCronJobs,runCronJob}from"./core/cron.mjs";import{reactive,ref}from"./core/reactivity.mjs";import{c as settleBackgroundWork,o as forwardBackgroundWork}from"./view-renderer-Bf1Wy-DQ.mjs";import{createRequire}from"node:module";import cluster from"node:cluster";import os from"node:os";const log$2=createLogger(`KickCronAdapter`),peerRequire=createRequire(import.meta.url),CRON_WORKER_ENV=`KICK_CRON_WORKER`;function croner(){try{let Croner=peerRequire(`croner`).Cron;return(expression,{timezone},tick)=>new Croner(expression,timezone?{timezone}:{},tick)}catch{return}}function isCronProcess(){return!cluster.isWorker||process.env.KICK_CRON_WORKER===`1`}const KickCronAdapter=defineAdapter({name:`KickCronAdapter`,defaults:{enabled:!0},build(options){let schedules=[],inFlight=/* @__PURE__ */ new Set,jobs=[];return{afterStart({container}){if(options.enabled===!1||!isCronProcess()||(jobs=listCronJobs(container),jobs.length===0))return;let schedule=options.schedule??croner();if(!schedule){log$2.warn(`${jobs.length} @Cron job(s) found but "croner" is not installed, so none will run. Install it (pnpm add croner), or pass KickCronAdapter({ schedule }).`);return}let run=(job,trigger)=>{let p=runCronJob(job,container,trigger).catch(()=>{});inFlight.add(p),p.finally(()=>inFlight.delete(p))};for(let job of jobs)schedules.push(schedule(job.expression,job.timezone?{timezone:job.timezone}:{},()=>run(job,`schedule`))),job.runOnInit&&run(job,`init`);log$2.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map(j=>j.name).join(`, `)}`)},async shutdown(){for(let schedule of schedules.splice(0))schedule.stop();await Promise.all(inFlight)},introspect(){return{protocolVersion:1,name:`KickCronAdapter`,kind:`adapter`,state:{jobs:jobs.map(j=>({name:j.name,expression:j.expression,timezone:j.timezone,description:j.description}))}}}}}}),log$1=createLogger(`Cluster`);function isClusterPrimary(){return cluster.isPrimary}function setupClusterPrimary(opts){let numWorkers=opts.workers??os.cpus().length,gracefulTimeout=opts.gracefulShutdownTimeout??5e3,restartDelay=opts.restartDelay??1e3,maxFailures=opts.maxFailures??5,restartWindow=opts.restartWindow??3e4,startupTimeouts=/* @__PURE__ */ new Map,state=reactive({failureTimestamps:[],shuttingDown:!1}),activeWorkers=ref(0);log$1.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`);let cronWorkerId,forkWorker=()=>{let takesCron=cronWorkerId===void 0,worker=cluster.fork(takesCron?{[CRON_WORKER_ENV]:`1`}:void 0);takesCron&&(cronWorkerId=worker.id)};for(let i=0;i<numWorkers;i++)forkWorker();cluster.on(`fork`,worker=>{let timeout=setTimeout(()=>{log$1.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`),worker.kill()},1e4);startupTimeouts.set(worker.id,timeout),activeWorkers.value++,log$1.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)}),cluster.on(`listening`,(worker,address)=>{let timeout=startupTimeouts.get(worker.id);timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),log$1.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)}),cluster.on(`online`,worker=>{log$1.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)}),cluster.on(`exit`,(worker,code,signal)=>{let timeout=startupTimeouts.get(worker.id);if(timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),activeWorkers.value--,worker.id===cronWorkerId&&(cronWorkerId=void 0),worker.exitedAfterDisconnect){log$1.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`);return}let now=Date.now();for(;state.failureTimestamps.length>0&&now-state.failureTimestamps[0]>=restartWindow;)state.failureTimestamps.shift();state.failureTimestamps.push(now),state.failureTimestamps.length>maxFailures?(log$1.error(`${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`),activeWorkers.value===0&&(log$1.error(`All workers have crashed, exiting primary`),process.exit(1))):(log$1.warn(`Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`),setTimeout(()=>{activeWorkers.value<numWorkers&&forkWorker()},restartDelay))}),cluster.on(`disconnect`,worker=>{log$1.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)});for(let signal of[`SIGTERM`,`SIGINT`])process.on(signal,()=>{state.shuttingDown||(state.shuttingDown=!0,log$1.info(`Primary received ${signal}, disconnecting workers...`),cluster.disconnect(()=>{log$1.info(`All workers disconnected, exiting primary`),process.exit(0)}),setTimeout(()=>{log$1.warn(`Graceful shutdown timed out, forcing exit`),process.exit(1)},gracefulTimeout).unref())})}const ENTRY_CAPTURE=Symbol.for(`kickjs.handler.entryCapture`);function captureEntry(load){let pending;return()=>pending??=(async()=>{let captured,g=globalThis,capture=(first,options)=>{captured??={first,options}};g[ENTRY_CAPTURE]=capture;try{await load()}finally{g[ENTRY_CAPTURE]===capture&&delete g[ENTRY_CAPTURE]}if(!captured)throw Error(`createHandler(): the entry finished loading without calling bootstrap(). Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.`);return captured})().catch(err=>{throw pending=void 0,err})}function createHandler(options){let app,entry=typeof options==`function`?captureEntry(options):async()=>({first:void 0,options}),firstUsed=!1,ready=()=>(app??=(async()=>{let loaded;try{loaded=await entry()}catch(err){throw app=void 0,err}let instance=loaded.first&&!firstUsed?loaded.first:new Application(loaded.options);firstUsed=!0;try{await instance.startWithoutServer()}catch(err){throw app=void 0,await instance.shutdown().catch(()=>{}),err}return instance})(),app);return{ready,async fetch(request,platform){let response=await(await ready()).fetch(request);return forwardBackgroundWork(platform),response},async node(req,res,platform){if((await ready()).handle(req,res),platform?.waitUntil){let sent=new Promise(resolve=>res.once(`close`,()=>resolve()));platform.waitUntil(sent.then(settleBackgroundWork))}},async close(){let current=app;app=void 0,current&&await(await current).shutdown()}}}function tryReloadEnv(){try{reloadEnv()}catch{}}const log=createLogger(`Process`);async function bootstrap(options){let capture=globalThis[ENTRY_CAPTURE];if(typeof capture==`function`){let app=new Application(options);return capture(app,options),app}let isViteDev=!!globalThis.__kickjs_httpServer;if(options.cluster&&isViteDev&&log.warn(`Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).`),options.cluster&&cluster.isPrimary&&!isViteDev)return setupClusterPrimary(typeof options.cluster==`object`?options.cluster:{}),new Application(options);let g=globalThis,processHooks=options.processHooks??`auto`;if(!g.__kickBootstrapped){if(processHooks!==`manual`&&(process.on(`uncaughtException`,err=>{log.error(err,`Uncaught exception`),reportError(err,{source:`uncaught`}),process.exitCode=1}),process.on(`unhandledRejection`,reason=>{log.error(reason,`Unhandled rejection`),reportError(reason,{source:`unhandled-rejection`}),process.exitCode=1})),processHooks===`auto`&&!g.__kickjs_httpServer)for(let signal of[`SIGINT`,`SIGTERM`])process.on(signal,async()=>{log.info(`Received ${signal}, shutting down...`),g.__app&&await g.__app.shutdown(),process.exit(0)});g.__kickBootstrapped=!0}let run=(g.__kickBoot??Promise.resolve()).then(()=>boot(options,g));return g.__kickBoot=run.catch(()=>{}),run}async function boot(options,g){if(g.__app){log.debug(`HMR rebuild triggered`);try{await g.__app.shutdown({closeServer:!1})}catch(err){log.error(err,`HMR teardown of the previous app failed`)}tryReloadEnv(),Container.reset();let freshApp=new Application(options);return g.__app=freshApp,g.__kickjs_container=freshApp.getContainer(),await freshApp.start(),log.debug(`HMR rebuild complete`),freshApp}let app=new Application(options);return g.__app=app,g.__kickjs_container=app.getContainer(),process.env.KICK_TINKER?(await app.registerOnly(),app):(await app.start(),app)}export{KickCronAdapter as a,CRON_WORKER_ENV as i,createHandler as n,isClusterPrimary as r,bootstrap as t};
|
|
12
|
+
//# sourceMappingURL=bootstrap-C5NvsxHQ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bootstrap-C5NvsxHQ.mjs","names":["log","log","\"KICK_CRON_WORKER\""],"sources":["../src/http/cron-adapter.ts","../src/http/cluster.ts","../src/http/handler.ts","../src/http/bootstrap.ts"],"sourcesContent":["/**\n * `KickCronAdapter()` — runs `@Cron` jobs on the Node server.\n *\n * Named with the `Kick` prefix (adapter name and logger too) so it never\n * collides with an app's own `CronAdapter` — which is also why it is opt-in.\n *\n * Opt-in: `@Cron` only records metadata, and apps that schedule jobs with\n * their own adapter keep doing so — adding this one to such an app would run\n * every job twice. Register it once:\n *\n * ```ts\n * bootstrap({ modules, adapters: [KickCronAdapter()] })\n * ```\n *\n * Timing comes from `schedule` — any scheduler library, a few lines to wire —\n * or, without one, from the optional peer `croner` (`pnpm add croner`), loaded\n * only when there is a job to schedule. Each tick resolves the job's class\n * from the container (the same singletons a request gets) and calls\n * `runCronJob`, which applies `enabled` / `overlap` and reports failures to\n * the error observers.\n *\n * Several processes: in `bootstrap({ cluster })`, only the worker the primary\n * marks with `KICK_CRON_WORKER=1` schedules, so a job runs once per cluster.\n * Several separate instances (replicas behind a load balancer) each schedule\n * every job — turn it off on all but one (`KickCronAdapter({ enabled: false })`),\n * or have the job take a lock.\n *\n * @module @forinda/kickjs/http/cron-adapter\n */\nimport cluster from 'node:cluster'\nimport { createRequire } from 'node:module'\nimport { defineAdapter } from '../core/define-adapter'\nimport { createLogger } from '../core/logger'\nimport { listCronJobs, runCronJob, type CronJob } from '../core/cron'\nimport type { Container } from '../core/container'\n\nconst log = createLogger('KickCronAdapter')\nconst peerRequire = createRequire(import.meta.url)\n\n/** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */\nexport const CRON_WORKER_ENV = 'KICK_CRON_WORKER'\n\n/** A running schedule, as {@link CronScheduler} returns it. */\nexport interface CronSchedule {\n stop(): void\n}\n\n/**\n * Starts one job's timer: call `tick` on every match of `expression` (in\n * `timezone` when set) until `stop()`. The adapter does the rest — resolving\n * the job, `enabled`, `overlap`, error reporting, waiting on shutdown.\n *\n * @example\n * ```ts\n * import cron from 'node-cron'\n *\n * KickCronAdapter({\n * schedule: (expression, { timezone }, tick) => {\n * const task = cron.schedule(expression, tick, { timezone })\n * // destroy(), not stop(): node-cron keeps stopped tasks.\n * return { stop: () => task.destroy() }\n * },\n * })\n * ```\n */\nexport type CronScheduler = (\n expression: string,\n options: { timezone?: string },\n tick: () => void,\n) => CronSchedule\n\n/**\n * Options for {@link KickCronAdapter}.\n *\n * @see https://kickjs.app/guide/cron\n */\nexport interface CronAdapterOptions {\n /** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */\n enabled?: boolean\n /** The scheduler that drives the jobs. Default: `croner`, which must then be installed. */\n schedule?: CronScheduler\n}\n\ntype Schedule = CronSchedule\n\ntype CronerCtor = new (pattern: string, options: { timezone?: string }, fn: () => void) => Schedule\n\nfunction croner(): CronScheduler | undefined {\n try {\n const Croner = (peerRequire('croner') as { Cron: CronerCtor }).Cron\n // No croner `name`: croner keeps names in a process-wide registry and\n // throws on a duplicate.\n return (expression, { timezone }, tick) =>\n new Croner(expression, timezone ? { timezone } : {}, tick)\n } catch {\n return undefined\n }\n}\n\n/** Whether this process should schedule jobs — one worker per cluster. */\nfunction isCronProcess(): boolean {\n return !cluster.isWorker || process.env[CRON_WORKER_ENV] === '1'\n}\n\n/**\n * Runs every `@Cron()` method of the app's services on its schedule, after\n * the server starts. Uses `croner` unless `schedule` brings another\n * scheduler; `enabled: false` turns it off for a process. Under a cluster\n * only one process runs the jobs.\n *\n * @example\n * ```ts\n * // pnpm add croner — or pass `schedule`\n * bootstrap({ modules, adapters: [KickCronAdapter()] })\n * ```\n *\n * @see https://kickjs.app/guide/cron\n */\nexport const KickCronAdapter = defineAdapter<CronAdapterOptions>({\n name: 'KickCronAdapter',\n defaults: { enabled: true },\n build(options) {\n const schedules: Schedule[] = []\n const inFlight = new Set<Promise<unknown>>()\n let jobs: CronJob[] = []\n\n return {\n afterStart({ container }) {\n if (options.enabled === false || !isCronProcess()) return\n jobs = listCronJobs(container)\n if (jobs.length === 0) return\n\n const schedule = options.schedule ?? croner()\n if (!schedule) {\n log.warn(\n `${jobs.length} @Cron job(s) found but \"croner\" is not installed, so none will run. ` +\n 'Install it (pnpm add croner), or pass KickCronAdapter({ schedule }).',\n )\n return\n }\n\n const run = (job: CronJob, trigger: 'schedule' | 'init') => {\n // Failures are already logged and reported by runCronJob.\n const p = runCronJob(job, container as Container, trigger).catch(() => {})\n inFlight.add(p)\n void p.finally(() => inFlight.delete(p))\n }\n\n for (const job of jobs) {\n schedules.push(\n schedule(job.expression, job.timezone ? { timezone: job.timezone } : {}, () =>\n run(job, 'schedule'),\n ),\n )\n if (job.runOnInit) run(job, 'init')\n }\n log.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map((j) => j.name).join(', ')}`)\n },\n\n /**\n * Stops the schedules, then waits for running jobs so they don't lose\n * their dependencies mid-run. Also runs on every HMR reload, so a reload\n * never leaves a second copy ticking.\n */\n async shutdown() {\n for (const schedule of schedules.splice(0)) schedule.stop()\n await Promise.all(inFlight)\n },\n\n introspect() {\n return {\n protocolVersion: 1,\n name: 'KickCronAdapter',\n kind: 'adapter',\n state: {\n jobs: jobs.map((j) => ({\n name: j.name,\n expression: j.expression,\n timezone: j.timezone,\n description: j.description,\n })),\n },\n } as never\n },\n }\n },\n})\n","import cluster from 'node:cluster'\nimport { CRON_WORKER_ENV } from './cron-adapter'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\n/** Options for {@link setupClusterPrimary}: worker count, shutdown timeout and restart limits. */\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Exactly one worker runs `KickCronAdapter` jobs, so a job fires once per\n // cluster rather than once per worker. The primary marks it with\n // KICK_CRON_WORKER=1; when it dies, the next fork inherits the role.\n let cronWorkerId: number | undefined\n const forkWorker = (): void => {\n const takesCron = cronWorkerId === undefined\n const worker = cluster.fork(takesCron ? { [CRON_WORKER_ENV]: '1' } : undefined)\n if (takesCron) cronWorkerId = worker.id\n }\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n forkWorker()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n if (worker.id === cronWorkerId) cronWorkerId = undefined\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n forkWorker()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","/**\n * The app as a request handler, with no listening server of its own — for\n * platforms that hand you requests instead of a port: Netlify Functions,\n * Vercel Functions, and any other serverless or embedding host.\n *\n * @module @forinda/kickjs/http/handler\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { Application, type ApplicationOptions } from './application'\nimport { forwardBackgroundWork, settleBackgroundWork, type PlatformContext } from './background'\n\n/** A KickJS app exposed as request handlers. See {@link createHandler}. */\nexport interface KickHandler {\n /**\n * Web-standard handler: `fetch(Request) → Response`. Netlify Functions,\n * Vercel's fetch export, and anything else that speaks `Request`.\n *\n * Pass the platform context (Netlify's `context`, `{ waitUntil }` from\n * `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after\n * the response instead of being frozen with the instance.\n */\n fetch(request: Request, platform?: PlatformContext): Promise<Response>\n /** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */\n node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>\n /** Set the app up now instead of on the first request (warm-up). */\n ready(): Promise<Application>\n /** Shut adapters down and stop the internal forwarding server, if one started. */\n close(): Promise<void>\n}\n\n/**\n * Set on `globalThis` while `createHandler(() => import('./index'))` loads the\n * app's entry: `bootstrap()` hands its app here instead of starting it.\n * @internal\n */\nexport const ENTRY_CAPTURE = Symbol.for('kickjs.handler.entryCapture')\n\n/** What `bootstrap()` hands to a loading handler. @internal */\nexport type EntryCapture = (app: Application, options: ApplicationOptions) => void\n\n/**\n * Load the app's own entry and keep the app its `bootstrap()` call builds.\n * Retries after a failed setup reuse the captured options.\n */\nfunction captureEntry(\n load: () => Promise<unknown>,\n): () => Promise<{ first: Application; options: ApplicationOptions }> {\n let pending: Promise<{ first: Application; options: ApplicationOptions }> | undefined\n return () =>\n (pending ??= (async () => {\n let captured: { first: Application; options: ApplicationOptions } | undefined\n const g = globalThis as Record<symbol, unknown>\n const capture: EntryCapture = (first, options) => {\n captured ??= { first, options }\n }\n g[ENTRY_CAPTURE] = capture\n try {\n await load()\n } finally {\n if (g[ENTRY_CAPTURE] === capture) delete g[ENTRY_CAPTURE]\n }\n if (!captured) {\n throw new Error(\n 'createHandler(): the entry finished loading without calling bootstrap(). ' +\n \"Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.\",\n )\n }\n return captured\n })().catch((err) => {\n pending = undefined\n throw err\n }))\n}\n\n/**\n * Build a KickJS app as request handlers instead of a listening server.\n *\n * Takes the same options as `bootstrap()`, or a function that imports the\n * app's entry — the file that calls `bootstrap()`. With the entry, the app\n * is built from that one `bootstrap({ ... })` call, so the server and the\n * function never drift apart:\n *\n * ```ts\n * // src/serverless.ts\n * export const handler = createHandler(() => import('./index'))\n * ```\n *\n * While the entry loads, its `bootstrap()` call builds the app without\n * starting it — no port, no process signal handlers, no cluster. The app is set up once per process\n * (per function instance), lazily on the first request, and reused after that.\n * Nothing listens on a port, `afterStart` does not run, and no process signal\n * handlers are registered — the platform owns the process.\n *\n * `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).\n * Runtimes built on Node request/response objects — Express, the default —\n * are served through a server bound to `127.0.0.1` on a random port inside the\n * same process, started on first use: the `Request` is forwarded to it and its\n * response returned. Request bodies are buffered on that path; response bodies\n * stream. Adapters that rewrite the `res` prototype (Express does) make a\n * direct Request→`res` bridge unreliable, which is why this forwards instead.\n *\n * One handler per process: the DI container is process-wide.\n *\n * @example\n * ```ts\n * // server/src/serverless.ts\n * import 'reflect-metadata'\n * import './config'\n * import { createHandler } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const handler = createHandler({ modules })\n *\n * // netlify/functions/api.mjs\n * export default (request, context) => handler.fetch(request, context)\n * export const config = { path: '/api/*' }\n * ```\n */\nexport function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler {\n let app: Promise<Application> | undefined\n const entry =\n typeof options === 'function'\n ? captureEntry(options)\n : async () => ({ first: undefined, options })\n // The app the entry's bootstrap() built is used once; a retry builds anew.\n let firstUsed = false\n\n const ready = (): Promise<Application> => {\n app ??= (async () => {\n let loaded: Awaited<ReturnType<typeof entry>>\n try {\n loaded = await entry()\n } catch (err) {\n // The entry failed to load: try again on the next request.\n app = undefined\n throw err\n }\n const instance = loaded.first && !firstUsed ? loaded.first : new Application(loaded.options)\n firstUsed = true\n try {\n await instance.startWithoutServer()\n } catch (err) {\n // A failed setup (a database that was briefly down, say) is retried on\n // the next request. Shut this attempt down first so its adapters don't\n // stay live next to the retry's.\n app = undefined\n await instance.shutdown().catch(() => {})\n throw err\n }\n return instance\n })()\n return app\n }\n\n return {\n ready,\n\n async fetch(request, platform) {\n const response = await (await ready()).fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n\n async node(req, res, platform) {\n const instance = await ready()\n instance.handle(req, res)\n if (platform?.waitUntil) {\n // The response is written asynchronously: start settling only once it\n // has gone out, so work the handler registered along the way is included.\n const sent = new Promise<void>((resolve) => res.once('close', () => resolve()))\n platform.waitUntil(sent.then(settleBackgroundWork))\n }\n },\n\n async close() {\n const current = app\n app = undefined\n if (current) await (await current).shutdown()\n },\n }\n}\n","import cluster from 'node:cluster'\nimport { reportError } from '../core/observers'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\nimport { ENTRY_CAPTURE, type EntryCapture } from './handler'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Loaded by createHandler(() => import('./index')) ────────────────\n // The serverless entry reuses this call's options: build the app and hand\n // it over without listening, forking or registering process hooks.\n const capture = (globalThis as Record<symbol, unknown>)[ENTRY_CAPTURE]\n if (typeof capture === 'function') {\n const app = new Application(options)\n ;(capture as EntryCapture)(app, options)\n return app\n }\n\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers + signal hooks ─────────────────────────────\n // `processHooks` controls whether KickJS registers its own\n // process-level handlers. Defaults to `'auto'` — register everything.\n // Adopters that bring their own observability stack (OpenTelemetry SDK,\n // Sentry, custom shutdown choreographer) often register their own\n // SIGINT/SIGTERM handlers and need to opt out of ours so the two don't\n // race to call `process.exit(0)`. Three modes:\n // - 'auto' (default): register uncaughtException/unhandledRejection\n // loggers + SIGINT/SIGTERM → `app.shutdown()` → `process.exit(0)`.\n // - 'errors-only': register the error loggers; skip signal handlers.\n // Use this when you have your own shutdown choreographer that calls\n // `app.shutdown()` itself.\n // - 'manual': skip everything. Adopter is responsible for both error\n // logging and signal-driven shutdown.\n const processHooks = options.processHooks ?? 'auto'\n\n if (!g.__kickBootstrapped) {\n if (processHooks !== 'manual') {\n // A listener here replaces Node's own handling, which exits with code\n // 1. Keep the failure in the exit code: a boot that throws — a top-level\n // `await bootstrap()` rejecting — must not end the process with 0, or a\n // deploy reads the crash as success.\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n reportError(err, { source: 'uncaught' })\n process.exitCode = 1\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n reportError(reason, { source: 'unhandled-rejection' })\n process.exitCode = 1\n })\n }\n\n if (processHooks === 'auto' && !g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // One boot at a time. A save before the last reload finished ran a second\n // bootstrap() alongside it: it shut down an app still starting (whose\n // afterStart ran anyway, leaving e.g. a socket.io server attached for good)\n // and its Container.reset() swapped the container under the other boot.\n const run = (g.__kickBoot ?? Promise.resolve()).then(() => boot(options, g))\n g.__kickBoot = run.catch(() => {})\n return run\n}\n\nasync function boot(options: ApplicationOptions, g: any): Promise<Application> {\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n\n // Tear the PREVIOUS app down before replacing it. Without this the old\n // Application was dropped on the floor still running: its adapters kept\n // their sockets and consumers open, so every save added another set.\n //\n // Observed in the wild as one process holding several consumer-group\n // members — on a single-partition topic only one can hold the assignment,\n // and it was a leaked consumer no longer wired to anything, so jobs\n // stopped being processed. A second socket.io server on the same HTTP\n // server crashed `handleUpgrade()` the same way.\n //\n // `closeServer: false` is load-bearing: the dev HTTP server is shared\n // across rebuilds, so a full shutdown would close the listening socket and\n // kill HMR on the first save.\n //\n // Failures are logged, not thrown — one broken adapter must not leave the\n // dev server wedged with no app at all.\n try {\n await g.__app.shutdown({ closeServer: false })\n } catch (err) {\n log.error(err as Error, 'HMR teardown of the previous app failed')\n }\n\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;;;;;;A,2nBAoCA,MAAMA,MAAM,aAAa,iBAAiB,EACpC,YAAc,cAAc,YAAY,GAAG,EAGpC,gBAAkB,mBA+C/B,SAAS,QAAoC,CAC3C,GAAI,CACF,IAAM,OAAU,YAAY,QAAQ,CAAC,CAA0B,KAG/D,OAAQ,WAAY,CAAE,UAAY,OAChC,IAAI,OAAO,WAAY,SAAW,CAAE,QAAS,EAAI,CAAC,EAAG,IAAI,CAC7D,MAAQ,CACN,MACF,CACF,CAGA,SAAS,eAAyB,CAChC,MAAO,CAAC,QAAQ,UAAY,QAAQ,IAAAE,mBAAyB,GAC/D,CAgBA,MAAa,gBAAkB,cAAkC,CAC/D,KAAM,kBACN,SAAU,CAAE,QAAS,EAAK,EAC1B,MAAM,QAAS,CACb,IAAM,UAAwB,CAAC,EACzB,yBAAW,IAAI,IACjB,KAAkB,CAAC,EAEvB,MAAO,CACL,WAAW,CAAE,WAAa,CAGxB,GAFI,QAAQ,UAAY,I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Ac,QAAQ,QAAQ,EAAA,CAAG,SAAW,KAAK,QAAS,CAAC,CAAC,EAE3E,MADA,GAAE,WAAa,IAAI,UAAY,CAAC,CAAC,EAC1B,GACT,CAEA,eAAe,KAAK,QAA6B,EAA8B,CAE7E,GAAI,EAAE,MAAO,CACX,IAAI,MAAM,uBAAuB,EAkBjC,GAAI,CACF,MAAM,EAAE,MAAM,SAAS,CAAE,YAAa,EAAM,CAAC,CAC/C,OAAS,IAAK,CACZ,IAAI,MAAM,IAAc,yCAAyC,CACnE,CAEA,aAAa,EACb,UAAU,MAAM,EAEhB,IAAM,SAAW,IAAI,YAAY,OAAO,EAMxC,MALA,GAAE,MAAQ,SACV,EAAE,mBAAqB,SAAS,aAAa,EAE7C,MAAM,SAAS,MAAM,EACrB,IAAI,MAAM,sBAAsB,EACzB,QACT,CAGA,IAAM,IAAM,IAAI,YAAY,OAAO,EAWnC,MAVA,GAAE,MAAQ,IACV,EAAE,mBAAqB,IAAI,aAAa,EAEpC,QAAQ,IAAI,aACd,MAAM,IAAI,aAAa,EAChB,MAGT,MAAM,IAAI,MAAM,EAET,IACT,C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
var BoundedCounters=class{windowMs;limit;max;hits=/* @__PURE__ */ new Map;singles=/* @__PURE__ */ new Set;constructor(windowMs,limit=1/0,max=1e5){this.windowMs=windowMs,this.limit=limit,this.max=max}get size(){return this.hits.size}increment(key){let now=Date.now(),entry=this.hits.get(key);if(entry&&entry.reset>now)return entry.hits++,entry.hits>1&&this.singles.delete(key),{totalHits:entry.hits,resetTime:new Date(entry.reset)};if(this.remove(key),this.sweep(now),this.hits.size>=this.max){let single=this.limit>1?this.singles.values().next().value:void 0;if(single===void 0){let oldest=this.hits.values().next().value;return{totalHits:1/0,resetTime:new Date(oldest.reset)}}this.remove(single)}let fresh={hits:1,reset:now+this.windowMs};return this.hits.set(key,fresh),this.singles.add(key),{totalHits:1,resetTime:new Date(fresh.reset)}}decrement(key){let entry=this.hits.get(key);entry&&entry.hits!==0&&(entry.hits--,entry.hits<=1&&this.singles.add(key))}reset(key){this.remove(key)}sweep(now=Date.now()){for(let[key,entry]of this.hits){if(entry.reset>now)break;this.remove(key)}}clear(){this.hits.clear(),this.singles.clear()}remove(key){this.hits.delete(key),this.singles.delete(key)}};export{BoundedCounters as t};
|
|
12
|
-
//# sourceMappingURL=bounded-counters-
|
|
12
|
+
//# sourceMappingURL=bounded-counters-BtvB2daV.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bounded-counters-
|
|
1
|
+
{"version":3,"file":"bounded-counters-BtvB2daV.mjs","names":[],"sources":["../src/http/middleware/bounded-counters.ts"],"sourcesContent":["/**\n * Per-key hit counters for a fixed window, in memory, bounded — the core of\n * the in-memory rate-limit stores. Keys come from clients (an IP, a header\n * behind a proxy, a username from a custom key), so the map is capped, and\n * what happens at the cap decides who a flood of new keys can hurt:\n *\n * - Expired windows go first. The map is kept in window order (a key starting\n * a new window moves to the back), so they are always at the front, and a\n * sweep stops at the first live one — no full scan.\n * - Then a counter still at one hit, oldest first — when the limit is above\n * one, so a single hit is below it. A flood of single requests from made-up\n * keys just recycles itself; a counter a client has hit twice (a username\n * with failed logins) is never pushed out, so flooding can't reset it. At\n * most it costs a key one hit, while that key is at one. With a limit of\n * one, a single hit is already the limit, so nothing live is evicted.\n * - Only when every counter is at two or more is a new key refused, counted\n * as over any limit until the oldest window ends. Reaching that takes two\n * requests per key across the whole cap within one window.\n *\n * @internal\n */\nexport class BoundedCounters {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n /** Keys at one hit (or fewer), oldest first: the only ones evicted. */\n private readonly singles = new Set<string>()\n\n /**\n * @param limit The rate limit these counters enforce (`max`): one-hit\n * counters are only evictable while that's below it.\n */\n constructor(\n private readonly windowMs: number,\n private readonly limit = Number.POSITIVE_INFINITY,\n // ponytail: fixed cap; a store shared between instances (Redis) has its own limits.\n private readonly max = 100_000,\n ) {}\n\n get size(): number {\n return this.hits.size\n }\n\n increment(key: string): { totalHits: number; resetTime: Date } {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n if (entry.hits > 1) this.singles.delete(key)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n this.remove(key)\n this.sweep(now)\n if (this.hits.size >= this.max) {\n const single = this.limit > 1 ? this.singles.values().next().value : undefined\n if (single === undefined) {\n const oldest = this.hits.values().next().value!\n return { totalHits: Number.POSITIVE_INFINITY, resetTime: new Date(oldest.reset) }\n }\n this.remove(single)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n this.singles.add(key)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n decrement(key: string): void {\n const entry = this.hits.get(key)\n if (!entry || entry.hits === 0) return\n entry.hits--\n if (entry.hits <= 1) this.singles.add(key)\n }\n\n reset(key: string): void {\n this.remove(key)\n }\n\n /** Drop expired windows, from the front. */\n sweep(now = Date.now()): void {\n for (const [key, entry] of this.hits) {\n if (entry.reset > now) break\n this.remove(key)\n }\n }\n\n clear(): void {\n this.hits.clear()\n this.singles.clear()\n }\n\n private remove(key: string): void {\n this.hits.delete(key)\n this.singles.delete(key)\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,gBAAb,KAA6B,CAUR,SACA,MAEA,IAZF,qBAAO,IAAI,IAEX,wBAAU,IAAI,IAM/B,YACmB,SACA,MAAQ,IAER,IAAM,IACvB,CAJiB,KAAA,SAAA,SACA,KAAA,MAAA,MAEA,KAAA,IAAA,GAChB,CAEH,IAAI,MAAe,CACjB,OAAO,KAAK,KAAK,IACnB,CAEA,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EAChB,KAAK,QAAQ,MAAM,CACrB,CAEQ,OAAO,IAAmB,CAChC,KAAK,KAAK,OAAO,GAAG,EACpB,KAAK,QAAQ,OAAO,GAAG,CACzB,CACF,E"}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-
|
|
3
|
-
|
|
2
|
+
import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-DamOelO8.mjs";
|
|
3
|
+
/**
|
|
4
|
+
* Options for {@link breachPadding}.
|
|
5
|
+
*
|
|
6
|
+
* @see https://kickjs.app/guide/middleware
|
|
7
|
+
*/
|
|
4
8
|
interface BreachPaddingOptions {
|
|
5
9
|
/**
|
|
6
10
|
* Padding added to each compressed response is 0 to `maxBytes - 1` bytes,
|
|
@@ -34,6 +38,5 @@ declare function padGzipHeader(chunk: Uint8Array, maxBytes: number): Uint8Array;
|
|
|
34
38
|
* and Cloudflare compress at the edge.
|
|
35
39
|
*/
|
|
36
40
|
declare function breachPadding(options?: BreachPaddingOptions): (req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => void;
|
|
37
|
-
//#endregion
|
|
38
41
|
export { breachPadding as n, padGzipHeader as r, BreachPaddingOptions as t };
|
|
39
|
-
//# sourceMappingURL=breach-padding-
|
|
42
|
+
//# sourceMappingURL=breach-padding-BUuc21Eu.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"breach-padding-BUuc21Eu.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/breach-padding.ts"],"mappings":";;;;;;;UAWiB;;;;;EAKf;;;;;;;;;iBAoBc,cAAc,OAAO,YAAY,mBAAmB;;;;;;;;;;;;;;;;;;iBAuCpD,cAAc,UAAS,wBAAyB,KAGjDA,gBAAO,KAAOC,iBAAQ,MAAQC"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
|
|
2
2
|
import "reflect-metadata";
|
|
3
|
-
//#region src/core/cache.d.ts
|
|
4
3
|
declare const CACHEABLE_META = "kick/cacheable";
|
|
5
4
|
/**
|
|
6
5
|
* Abstract cache backend. Implement this interface to use Redis, Memcached,
|
|
@@ -75,12 +74,35 @@ declare class MemoryCacheProvider implements CacheProvider {
|
|
|
75
74
|
declare function setCacheProvider(provider: CacheProvider): void;
|
|
76
75
|
/** Get the current cache provider */
|
|
77
76
|
declare function getCacheProvider(): CacheProvider;
|
|
77
|
+
/**
|
|
78
|
+
* Options for {@link Cacheable}.
|
|
79
|
+
*
|
|
80
|
+
* @see https://kickjs.app/guide/caching
|
|
81
|
+
*/
|
|
78
82
|
interface CacheOptions {
|
|
79
83
|
/** Time-to-live in seconds (default: 60) */
|
|
80
84
|
ttl?: number;
|
|
81
85
|
/** Cache key prefix (default: `methodName:ClassName`) */
|
|
82
86
|
key?: string;
|
|
83
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Caches a method's result for `ttl` seconds (default 60) in the
|
|
90
|
+
* {@link CacheProvider}. The key is a prefix plus the JSON arguments
|
|
91
|
+
* (`method:Class:[42]`); a string `options.key` replaces the prefix, and a
|
|
92
|
+
* function of the arguments returns the whole key. Simultaneous misses on one
|
|
93
|
+
* key share one call. `@CacheEvict(prefix)` clears entries when the provider
|
|
94
|
+
* implements `delByPrefix`.
|
|
95
|
+
*
|
|
96
|
+
* @example
|
|
97
|
+
* ```ts
|
|
98
|
+
* `@Cacheable(300)`
|
|
99
|
+
* findAll() {
|
|
100
|
+
* return this.repo.list()
|
|
101
|
+
* }
|
|
102
|
+
* ```
|
|
103
|
+
*
|
|
104
|
+
* @see https://kickjs.app/guide/caching
|
|
105
|
+
*/
|
|
84
106
|
declare function Cacheable(ttl?: number, options?: {
|
|
85
107
|
key?: string | ((...args: any[]) => string);
|
|
86
108
|
}): MethodDecorator;
|
|
@@ -90,8 +112,9 @@ declare function Cacheable(ttl?: number, options?: {
|
|
|
90
112
|
*
|
|
91
113
|
* @param key - Cache key prefix to evict (matches the @Cacheable key), or a
|
|
92
114
|
* function of the method's arguments that returns it — e.g. `(id) => "product:" + id`.
|
|
115
|
+
*
|
|
116
|
+
* @see https://kickjs.app/guide/caching
|
|
93
117
|
*/
|
|
94
118
|
declare function CacheEvict(key: string | ((...args: any[]) => string)): MethodDecorator;
|
|
95
|
-
//#endregion
|
|
96
119
|
export { Cacheable as a, setCacheProvider as c, CacheProvider as i, CacheEvict as n, MemoryCacheProvider as o, CacheOptions as r, getCacheProvider as s, CACHEABLE_META as t };
|
|
97
|
-
//# sourceMappingURL=cache-
|
|
120
|
+
//# sourceMappingURL=cache-ByX5O2Hp.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-ByX5O2Hp.d.mts","names":[],"sources":["../src/core/cache.ts"],"mappings":";;cAKM;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BW;;EAEf,IAAI,cAAc;;EAElB,IAAI,aAAa,YAAY,gBAAgB;;EAE7C,IAAI,cAAc;;EAElB,aAAa,iBAAiB;;EAE9B,aAAa;;;;;;;;;;;;cAeF,+BAA+B;mBAGb;UAFrB;EAER,YAA6B;EAEvB,IAAI,cAAc;EAclB,IAAI,aAAa,YAAY,gBAAgB;EAU7C,IAAI,cAAc;EAIlB,YAAY,iBAAiB;EAQ7B,YAAY;;;;;;;;;;;;;;iBAqBJ,iBAAiB,UAAU;;iBAK3B,oBAAoB;;;;;;UAWnB;;EAEf;;EAEA;;;;;;;;;;;;;;;;;;;;iBA4Dc,UACd,cACA;EAAY,oBAAoB;IAC/B;;;;;;;;;;iBAkEa,WAAW,mBAAmB,0BAA0B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function firstHop(value){return typeof value==`string`&&value.length>0?value.split(`,`)[0].trim():void 0}function headerValue(headers,name){if(headers)return typeof headers.get==`function`?headers.get(name):headers[name]}function resolveClientIp(req){if(typeof req.ip==`string`&&req.ip.length>0)return req.ip;let socketAddress=req.socket?.remoteAddress;if(socketAddress)return socketAddress;let h=req.headers;return firstHop(headerValue(h,`cf-connecting-ip`))??firstHop(headerValue(h,`x-forwarded-for`))??firstHop(headerValue(h,`x-real-ip`))}function resolvePathname(req){if(typeof req.path==`string`&&req.path.length>0)return req.path;let url=req.url;if(!url)return`/`;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(url))try{return new URL(url).pathname||`/`}catch{return`/`}let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}export{resolvePathname as n,resolveClientIp as t};
|
|
12
|
-
//# sourceMappingURL=client-ip-
|
|
12
|
+
//# sourceMappingURL=client-ip-CWvyHmqt.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-ip-
|
|
1
|
+
{"version":3,"file":"client-ip-CWvyHmqt.mjs","names":[],"sources":["../src/http/client-ip.ts"],"sourcesContent":["/**\n * Client address + pathname resolution shared by everything that runs as\n * connect-style middleware.\n *\n * Fastify and h3 hand middleware the RAW node request, so the Express\n * conveniences (`req.ip`, `req.path`, `req.originalUrl`) are `undefined`\n * there. Reading them directly produced two live bugs:\n *\n * rate-limit → every caller keyed as the `'127.0.0.1'` fallback, i.e. ONE\n * shared bucket, so a single client could exhaust the limit\n * for everyone\n * csrf → `ignorePaths` never matched, so configured exemptions were\n * silently dead\n *\n * Edge-safe: no node imports.\n */\n\n/** The request members these helpers read, from node's shape rather than Express's. */\nexport interface ClientRequestLike {\n url?: string\n /** Express-only convenience. */\n path?: string\n /** Express-only; the full path before router mounting rewrote `url`. */\n originalUrl?: string\n /** Express and Fastify compute this from their trust-proxy settings. */\n ip?: unknown\n /**\n * A plain object on every path the framework currently takes — `WebRequestShim`\n * normalizes a WHATWG `Headers` before the context is built. A `Headers`\n * instance is accepted defensively: it is not index-accessible, so if one ever\n * did arrive, every lookup would return `undefined` SILENTLY and drop each\n * caller into one shared rate-limit bucket.\n */\n headers?: Record<string, string | string[] | undefined> | Headers\n socket?: { remoteAddress?: string }\n}\n\n/** First entry of a possibly comma-separated header value. */\nfunction firstHop(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value.split(',')[0]!.trim() : undefined\n}\n\n/** Read one header from either a plain object or a WHATWG `Headers`. */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined> | Headers | undefined,\n name: string,\n): unknown {\n if (!headers) return undefined\n // `Headers` has no index access, so `headers[name]` silently yields\n // `undefined` rather than the value.\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name)\n return (headers as Record<string, string | string[] | undefined>)[name]\n}\n\n/**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the address the runtime computed — Express derives `req.ip` from\n * `trust proxy`, Fastify from `trustProxy` — because raw forwarded headers are\n * client-SPOOFABLE wherever nothing normalizes them. h3 takes the same stance:\n * its `getRequestIP` only consults `x-forwarded-for` when explicitly opted in.\n *\n * Order is `req.ip` → `socket.remoteAddress` → forwarded headers. The socket\n * comes BEFORE the headers deliberately: it cannot be spoofed, whereas a direct\n * client can vary `x-forwarded-for` per request to get a fresh rate-limit\n * bucket each time. Headers are consulted only where there is no socket — the\n * web/edge entry, where the platform terminates the connection.\n */\nexport function resolveClientIp(req: ClientRequestLike): string | undefined {\n // 1. What the runtime computed. Express derives `req.ip` from `trust proxy`,\n // Fastify from `trustProxy` — a value vetted against a CONFIGURED proxy,\n // which is the only reason to believe a forwarded header at all.\n if (typeof req.ip === 'string' && req.ip.length > 0) return req.ip\n\n // 2. The socket. Unspoofable, and present on every node runtime.\n //\n // This MUST precede the headers. A raw Fastify / h3 request has no\n // `req.ip`, so consulting `x-forwarded-for` first let a DIRECT client send\n // a different value per request and land in a fresh rate-limit bucket each\n // time — evading the limit entirely. Behind a real proxy the socket is the\n // proxy's address, which buckets clients together; the fix for that is to\n // configure the runtime's trust-proxy setting so step 1 answers, not to\n // trust an unverified header here.\n const socketAddress = req.socket?.remoteAddress\n if (socketAddress) return socketAddress\n\n // 3. Headers, only where there is no socket at all — the web/edge entry,\n // where the platform terminates the connection and these are the only\n // signal available.\n const h = req.headers\n return (\n firstHop(headerValue(h, 'cf-connecting-ip')) ??\n firstHop(headerValue(h, 'x-forwarded-for')) ??\n firstHop(headerValue(h, 'x-real-ip'))\n )\n}\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nexport function resolvePathname(req: ClientRequestLike): string {\n if (typeof req.path === 'string' && req.path.length > 0) return req.path\n const url = req.url\n if (!url) return '/'\n // `WebRequestShim` already reduces the WHATWG `Request.url` to path+search,\n // but an ABSOLUTE url would otherwise be returned whole — so a skip prefix\n // like `/health` would never match `https://host/health`.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)) {\n try {\n return new URL(url).pathname || '/'\n } catch {\n return '/'\n }\n }\n const q = url.indexOf('?')\n return (q === -1 ? url : url.slice(0, q)) || '/'\n}\n"],"mappings":";;;;;;;;;;AAsCA,SAAS,SAAS,MAAoC,CACpD,OAAO,OAAO,OAAU,UAAY,MAAM,OAAS,EAAI,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,KAAK,EAAI,IAAA,EACvF,CAGA,SAAS,YACP,QACA,KACS,CACT,GAAK,QAIL,OADI,OAAQ,QAAoB,KAAQ,WAAoB,QAAoB,IAAI,IAAI,EAChF,QAA0D,KACpE,CAgBA,SAAgB,gBAAgB,IAA4C,CAI1E,GAAI,OAAO,IAAI,IAAO,UAAY,IAAI,GAAG,OAAS,EAAG,OAAO,IAAI,GAWhE,IAAM,cAAgB,IAAI,QAAQ,cAClC,GAAI,cAAe,OAAO,cAK1B,IAAM,EAAI,IAAI,QACd,OACE,SAAS,YAAY,EAAG,kBAAkB,CAAC,GAC3C,SAAS,YAAY,EAAG,iBAAiB,CAAC,GAC1C,SAAS,YAAY,EAAG,WAAW,CAAC,CAExC,CAGA,SAAgB,gBAAgB,IAAgC,CAC9D,GAAI,OAAO,IAAI,MAAS,UAAY,IAAI,KAAK,OAAS,EAAG,OAAO,IAAI,KACpE,IAAM,IAAM,IAAI,IAChB,GAAI,CAAC,IAAK,MAAO,IAIjB,GAAI,2BAA2B,KAAK,GAAG,EACrC,GAAI,CACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC,UAAY,GAClC,MAAQ,CACN,MAAO,GACT,CAEF,IAAM,EAAI,IAAI,QAAQ,GAAG,EACzB,OAAQ,IAAM,GAAK,IAAM,IAAI,MAAM,EAAG,CAAC,IAAM,GAC/C,C"}
|
package/dist/config/index.d.mts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Environment validation and typed config — formerly published as
|
|
4
|
+
* `@forinda/kickjs-config` (removed in v4). Now lives inside
|
|
5
|
+
* `@forinda/kickjs` so apps pick it up with no extra install.
|
|
6
|
+
*/
|
|
7
|
+
import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, f as withEnv, i as Env, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "../index-DoukvKwh.mjs";
|
|
3
8
|
export { ConfigService, type Env, type TypedConfigService, baseEnvSchema, createConfigService, defineEnv, getEnv, loadEnv, loadEnvFromSchema, reloadEnv, resetEnvCache, withEnv };
|
package/dist/config/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
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-
|
|
11
|
+
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-C3to8dG-.mjs";import{n as createConfigService,t as ConfigService}from"../config-BIQoDNil.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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{
|
|
12
|
-
//# sourceMappingURL=config-
|
|
11
|
+
import{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-C3to8dG-.mjs";import{Service}from"./core/decorators.mjs";let ConfigService=class{get env(){return loadEnv()}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
|
|
12
|
+
//# sourceMappingURL=config-BIQoDNil.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-
|
|
1
|
+
{"version":3,"file":"config-BIQoDNil.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container.envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>\n /** With a fallback, returned when the value is unset (`undefined` or `null`). */\n get<K extends string, T = any>(\n key: ConfigKey<K>,\n fallback: NonNullable<ConfigValue<K, T>>,\n ): NonNullable<ConfigValue<K, T>>\n get(key: string, fallback?: unknown): unknown {\n return this.env[key] ?? fallback\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n get(key: string, fallback?: unknown): unknown {\n return (this.env as Record<string, unknown>)[key] ?? fallback\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;A,4HA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAiBA,IAAI,IAAa,SAA6B,CAC5C,OAAO,KAAK,IAAI,MAAQ,QAC1B,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAjEC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EA6GT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAIA,IAAI,IAAa,SAA6B,CAC5C,OAAQ,KAAK,IAAgC,MAAQ,QACvD,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAnCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAmCF,mBAGT,C"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
|
|
2
2
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
3
|
-
//#region src/http/connect.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* The request a connect middleware sees: Node's `IncomingMessage`, plus the
|
|
6
5
|
* members Express adds. Those are optional — under Fastify and h3 a member
|
|
@@ -36,6 +35,5 @@ type ConnectHandler = Bivariant<(req: ConnectRequest, res: ConnectResponse, next
|
|
|
36
35
|
type ConnectErrorHandler = Bivariant<(err: any, req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => unknown>;
|
|
37
36
|
/** Either kind of connect middleware. */
|
|
38
37
|
type ConnectMiddleware = ConnectHandler | ConnectErrorHandler;
|
|
39
|
-
//#endregion
|
|
40
38
|
export { ConnectRequest as a, ConnectNext as i, ConnectHandler as n, ConnectResponse as o, ConnectMiddleware as r, ConnectErrorHandler as t };
|
|
41
|
-
//# sourceMappingURL=connect-
|
|
39
|
+
//# sourceMappingURL=connect-DamOelO8.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-DamOelO8.d.mts","names":[],"sources":["../src/http/connect.ts"],"mappings":";;;;;;;UAgBiB,uBAAuB;;EAEtC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;;GAET;;;UAIc,wBAAwB;GACtC;;;KAIS,eAAe;KAItB,UAAU,cAAc;EAC3B,MAAM,MAAM,WAAW;;;KAIb,iBAAiB,WAC1B,KAAK,gBAAgB,KAAK,iBAAiB,MAAM;;KAIxC,sBAAsB,WAC/B,UAAU,KAAK,gBAAgB,KAAK,iBAAiB,MAAM;;KAIlD,oBAAoB,iBAAiB"}
|