@forinda/kickjs 10.13.0 → 10.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/application-1Fzmk_Ku.mjs +14 -0
- package/dist/application-1Fzmk_Ku.mjs.map +1 -0
- package/dist/{application-r0VMb-A5.d.mts → application-DsHdZoZK.d.mts} +4 -3
- package/dist/{application-r0VMb-A5.d.mts.map → application-DsHdZoZK.d.mts.map} +1 -1
- package/dist/{body-policy-BK8PLFhR.mjs → body-policy-BQnyy906.mjs} +2 -2
- package/dist/{body-policy-BK8PLFhR.mjs.map → body-policy-BQnyy906.mjs.map} +1 -1
- package/dist/{bootstrap-Cm4Tv-uh.mjs → bootstrap-Ub6N0nVd.mjs} +3 -3
- package/dist/{bootstrap-Cm4Tv-uh.mjs.map → bootstrap-Ub6N0nVd.mjs.map} +1 -1
- package/dist/{bounded-counters-DhDwQV9i.mjs → bounded-counters-BaQwi0aH.mjs} +2 -2
- package/dist/{bounded-counters-DhDwQV9i.mjs.map → bounded-counters-BaQwi0aH.mjs.map} +1 -1
- package/dist/{client-ip-gBC8rx8G.mjs → client-ip-DwLXnTke.mjs} +2 -2
- package/dist/{client-ip-gBC8rx8G.mjs.map → client-ip-DwLXnTke.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-CufiDd1o.mjs → config-Df8GxPDC.mjs} +3 -3
- package/dist/{config-CufiDd1o.mjs.map → config-Df8GxPDC.mjs.map} +1 -1
- package/dist/{context-Vy_DYHAM.mjs → context-ByBa7pR4.mjs} +3 -3
- package/dist/{context-Vy_DYHAM.mjs.map → context-ByBa7pR4.mjs.map} +1 -1
- package/dist/{context-errors-BNm2NUfA.mjs → context-errors-CWTD0Fln.mjs} +2 -2
- package/dist/{context-errors-BNm2NUfA.mjs.map → context-errors-CWTD0Fln.mjs.map} +1 -1
- package/dist/{contributor-runner-BwBRcB65.mjs → contributor-runner-BlYFb9WU.mjs} +3 -3
- package/dist/{contributor-runner-BwBRcB65.mjs.map → contributor-runner-BlYFb9WU.mjs.map} +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +2 -2
- package/dist/{core-uD7kn0hF.mjs → core-DBoFrkOu.mjs} +3 -3
- package/dist/{core-uD7kn0hF.mjs.map → core-DBoFrkOu.mjs.map} +1 -1
- package/dist/{decorate-7rlBW7PY.mjs → decorate-BFKqRpjy.mjs} +3 -3
- package/dist/{decorate-7rlBW7PY.mjs.map → decorate-BFKqRpjy.mjs.map} +1 -1
- package/dist/{define-adapter-rcNang-q.mjs → define-adapter-C4ATXXqb.mjs} +2 -2
- package/dist/{define-adapter-rcNang-q.mjs.map → define-adapter-C4ATXXqb.mjs.map} +1 -1
- package/dist/{di-hooks-CdmCtJWu.mjs → di-hooks-CUVLbOER.mjs} +2 -2
- package/dist/{di-hooks-CdmCtJWu.mjs.map → di-hooks-CUVLbOER.mjs.map} +1 -1
- package/dist/{disposables-tpEyEZ9s.mjs → disposables-DzxupKRg.mjs} +1 -1
- package/dist/{driver-C8ZOdZck.mjs → driver-CQ7sN3vu.mjs} +3 -3
- package/dist/{driver-C8ZOdZck.mjs.map → driver-CQ7sN3vu.mjs.map} +1 -1
- package/dist/{express-DjX6B-HB.mjs → express-BVQODWsY.mjs} +3 -3
- package/dist/{express-DjX6B-HB.mjs.map → express-BVQODWsY.mjs.map} +1 -1
- package/dist/{express-lazy-DBLuSOgw.mjs → express-lazy-7Ldw2LAF.mjs} +3 -3
- package/dist/{express-lazy-DBLuSOgw.mjs.map → express-lazy-7Ldw2LAF.mjs.map} +1 -1
- package/dist/{handler-CHJs4HZ3.mjs → handler-CIIBAVAD.mjs} +3 -3
- package/dist/{handler-CHJs4HZ3.mjs.map → handler-CIIBAVAD.mjs.map} +1 -1
- package/dist/{host-BxUGat0u.mjs → host-BDnmvmwu.mjs} +2 -2
- package/dist/{host-BxUGat0u.mjs.map → host-BDnmvmwu.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/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/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.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.d.mts +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{is-production-WunZdVDZ.mjs → is-production-Bmoi-4LP.mjs} +2 -2
- package/dist/{is-production-WunZdVDZ.mjs.map → is-production-Bmoi-4LP.mjs.map} +1 -1
- package/dist/{jobs-DxkFQkZG.mjs → jobs-8qPs4uhb.mjs} +3 -3
- package/dist/{jobs-DxkFQkZG.mjs.map → jobs-8qPs4uhb.mjs.map} +1 -1
- package/dist/{kv-stores-C4YUttef.mjs → kv-stores-u9frHRUO.mjs} +3 -3
- package/dist/{kv-stores-C4YUttef.mjs.map → kv-stores-u9frHRUO.mjs.map} +1 -1
- package/dist/{lazy-serve-static-BBO3lkBi.mjs → lazy-serve-static-C1iV009Y.mjs} +3 -3
- package/dist/{lazy-serve-static-BBO3lkBi.mjs.map → lazy-serve-static-C1iV009Y.mjs.map} +1 -1
- package/dist/{metadata-s6adg8tp.mjs → metadata-__BH2A1m.mjs} +1 -1
- package/dist/{observers-Dn36QtbG.mjs → observers-D3m1iUQw.mjs} +2 -2
- package/dist/{observers-Dn36QtbG.mjs.map → observers-D3m1iUQw.mjs.map} +1 -1
- package/dist/{precompressed-Dn3S9e-q.mjs → precompressed-CLMMwxxl.mjs} +2 -2
- package/dist/{precompressed-Dn3S9e-q.mjs.map → precompressed-CLMMwxxl.mjs.map} +1 -1
- package/dist/{query-BukuyQDW.mjs → query-D8Jbrl5C.mjs} +2 -2
- package/dist/{query-BukuyQDW.mjs.map → query-D8Jbrl5C.mjs.map} +1 -1
- package/dist/{reply-DDoHPeGF.mjs → reply-Dr88jBEF.mjs} +3 -3
- package/dist/{reply-DDoHPeGF.mjs.map → reply-Dr88jBEF.mjs.map} +1 -1
- package/dist/{request-scope-BmUpBk1z.mjs → request-scope-CN4JvYti.mjs} +3 -3
- package/dist/{request-scope-BmUpBk1z.mjs.map → request-scope-CN4JvYti.mjs.map} +1 -1
- package/dist/{respond-Bo3vSCwu.mjs → respond--wtqY3VK.mjs} +2 -2
- package/dist/{respond-Bo3vSCwu.mjs.map → respond--wtqY3VK.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DHJmXo5e.mjs → rolldown-runtime-C5JVZt00.mjs} +1 -1
- package/dist/{route-flag-Cwckim1c.mjs → route-flag-qXRvhsbB.mjs} +3 -3
- package/dist/{route-flag-Cwckim1c.mjs.map → route-flag-qXRvhsbB.mjs.map} +1 -1
- package/dist/{route-policy-CycYu5mR.mjs → route-policy-Dd12HOZr.mjs} +2 -2
- package/dist/{route-policy-CycYu5mR.mjs.map → route-policy-Dd12HOZr.mjs.map} +1 -1
- package/dist/{router-builder--PLE0eDf.mjs → router-builder-DIBhQIki.mjs} +3 -3
- package/dist/{router-builder--PLE0eDf.mjs.map → router-builder-DIBhQIki.mjs.map} +1 -1
- package/dist/{runtime-OgMPp4md.mjs → runtime-pz_XLMOf.mjs} +3 -3
- package/dist/{runtime-OgMPp4md.mjs.map → runtime-pz_XLMOf.mjs.map} +1 -1
- package/dist/session-DQG72vCf.d.mts.map +1 -1
- package/dist/{settings-Dn9iQ-BU.mjs → settings-DqVmZr-S.mjs} +3 -3
- package/dist/{settings-Dn9iQ-BU.mjs.map → settings-DqVmZr-S.mjs.map} +1 -1
- package/dist/{token-B3xWBu0S.mjs → token-CbeBj1AB.mjs} +1 -1
- package/dist/{upload-config-BrbOOmcm.mjs → upload-config-tyBCdMVF.mjs} +2 -2
- package/dist/{upload-config-BrbOOmcm.mjs.map → upload-config-tyBCdMVF.mjs.map} +1 -1
- package/dist/{url-for-1SdTJZzK.mjs → url-for-B3mtX1t0.mjs} +3 -3
- package/dist/{url-for-1SdTJZzK.mjs.map → url-for-B3mtX1t0.mjs.map} +1 -1
- package/dist/{view-renderer-Caqy9XY5.mjs → view-renderer-BLYp4qoe.mjs} +3 -3
- package/dist/{view-renderer-Caqy9XY5.mjs.map → view-renderer-BLYp4qoe.mjs.map} +1 -1
- package/dist/{web-crypto-DnhQ8LCv.mjs → web-crypto-Up4UvHoI.mjs} +2 -2
- package/dist/{web-crypto-DnhQ8LCv.mjs.map → web-crypto-Up4UvHoI.mjs.map} +1 -1
- package/dist/web.mjs +2 -2
- package/package.json +1 -1
- package/dist/application-dhmb3PMx.mjs +0 -14
- package/dist/application-dhmb3PMx.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"h3.d.mts","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"mappings":";;;;UAoDU;EACR,GAAG,gBAAgB,cAAc,UAAU,OAAO;EAClD,IAAI,cAAc,UAAU,OAAO;EACnC,OAAO;EACP,MAAM,SAAS,UAAU,QAAQ;;UAEzB;EACR,KAAK;IAAY;MAAY;QAAS,KAAK;QAAiB,KAAK;;;;EACjE,KAAK;EACL;IAAW,SAAS;;;iBASL;;;;;;;;EAQf;;;;;;
|
|
1
|
+
{"version":3,"file":"h3.d.mts","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"mappings":";;;;UAoDU;EACR,GAAG,gBAAgB,cAAc,UAAU,OAAO;EAClD,IAAI,cAAc,UAAU,OAAO;EACnC,OAAO;EACP,MAAM,SAAS,UAAU,QAAQ;;UAEzB;EACR,KAAK;IAAY;MAAY;QAAS,KAAK;QAAiB,KAAK;;;;EACjE,KAAK;EACL;IAAW,SAAS;;;iBASL;;;;;;;;EAQf;;;;;;wBAmac,UAAU,UAAS,mBAAwB,YAAY;;;;;iBAqKtD;EACf,SAAS;EACT,UAAU;EACV;IAAmC,YAAY,wBAAwB;MAAM;;;qBAYlE,qBAAY;;YAEb,sBAAsB;;YAEtB,oBAAoB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"../../core/logger.mjs";import{f as requestStore}from"../../view-renderer-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import{f as requestStore}from"../../view-renderer-BLYp4qoe.mjs";import{errorHandler,notFoundHandler}from"../middleware/error-handler.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-CN4JvYti.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"../../driver-CQ7sN3vu.mjs";import{n as headFromGet,r as readThrough,t as compileWebRoute}from"../../handler-CIIBAVAD.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-C1iV009Y.mjs";import*as h3Peer from"h3";const builtInError=errorHandler(),builtInNotFound=notFoundHandler(),log=createLogger(`H3Runtime`),NOTFOUND_MW=Symbol(`kickjs.h3web.notFoundMw`),ERROR_MW=Symbol(`kickjs.h3web.errorMw`),ASSEMBLED=Symbol(`kickjs.h3web.assembled`),NOOP_NEXT=()=>{},NEXT=Symbol(`kickjs.h3web.next`),NO_FALLTHROUGH=Symbol(`kickjs.h3web.noFallthrough`),TRUST_PROXY=Symbol(`kickjs.h3.trustProxy`),BODY_LIMIT=Symbol(`kickjs.h3.bodyLimit`),H3_HANDLED=Symbol.for(`h3.handled`);function unwrapH3Module(mod){let m=mod;return m&&m.__esModule&&m.default?{...m.default,...m}:m}function loadH3v2(injected){let resolved=unwrapH3Module(injected??h3Peer);if(typeof resolved.H3!=`function`)throw Error(`@forinda/kickjs: h3Runtime() requires h3 v2, but the installed h3 has no H3 class — that is the v1 line, which this version of KickJS no longer supports. Upgrade h3 to ^2.`);return resolved}async function runConnectTerminal(mw,event,err){let shim=new WebRequestShim(event.req,event.url),carry=event.req.runtime?.node?.req??FETCH_CONNECT.get(event)?.req,req=carry?readThrough(shim,carry):shim,driver=new WebResponseDriver(event.req.signal),store=createRequestStore(req.requestId||(event.req.headers.get(`x-request-id`)??``)),work=requestStore.run(store,()=>answerTerminal(mw,req,driver,err)),dispose=()=>disposeRequestStore(store);return work.then(()=>driver.ready).then(dispose,dispose),await work,driver.ready}async function answerTerminal(mw,req,driver,err){let failure=err;if(mw){let returned=err===void 0?mw(req,driver,NOOP_NEXT):mw(err,req,driver,NOOP_NEXT);if(typeof returned?.then==`function`)try{await returned}catch(handlerErr){log.error(handlerErr,`h3: the ${err===void 0?`not-found`:`error`} handler failed`),failure??=handlerErr}}driver.settled||(failure===void 0?builtInNotFound(req,driver,NOOP_NEXT):await builtInError(failure,req,driver,NOOP_NEXT))}const FETCH_CONNECT=/* @__PURE__ */ new WeakMap;function fetchConnectState(event){let state=FETCH_CONNECT.get(event);return state||(state={req:new WebRequestShim(event.req,event.url),headers:new Headers},FETCH_CONNECT.set(event,state)),state}function withConnectHeaders(event,response){let state=FETCH_CONNECT.get(event);if(!state)return response;let missing=[...state.headers].filter(([name])=>name===`set-cookie`||!response.headers.has(name));if(state.headers=new Headers,missing.length===0)return response;try{for(let[name,value]of missing)response.headers.append(name,value);return response}catch{let headers=new Headers(response.headers);for(let[name,value]of missing)headers.append(name,value);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}var FetchConnectResponse=class extends WebResponseDriver{prepared;code=200;listeners=[];constructor(prepared,signal){super(signal),this.prepared=prepared}get statusCode(){return this.code}set statusCode(code){this.status(code)}status(code){return this.code=code,super.status(code)}writeHead(code,headers){return this.code=code,super.writeHead(code,headers)}setHeader(name,value){if(Array.isArray(value)){this.prepared.delete(name);for(let v of value)this.prepared.append(name,String(v))}else this.prepared.set(name,String(value));return this}getHeader(name){return this.prepared.get(name)??void 0}hasHeader(name){return this.prepared.has(name)}removeHeader(name){this.prepared.delete(name)}once(event,listener){return this.listeners.push([event,listener]),this}on(event,listener){return this.once(event,listener)}removeListener(event,listener){return this.listeners=this.listeners.filter(([e,l])=>e!==event||l!==listener),this}off(event,listener){return this.removeListener(event,listener)}done(){let pending=[];for(let event of[`finish`,`close`]){for(let[e,listener]of this.listeners){if(e!==event)continue;let out;try{out=listener()}catch(err){log.error(err,`h3: a '${event}' listener failed`);continue}out&&typeof out.then==`function`&&pending.push(Promise.resolve(out).catch(()=>{}))}this.listeners=this.listeners.filter(([e])=>e!==event)}return Promise.all(pending).then(()=>{})}};function runConnectOnFetch(mw,event,next){let state=fetchConnectState(event),res=new FetchConnectResponse(state.headers,event.req.signal);return new Promise((resolve,reject)=>{let respond=response=>{res.done().then(()=>resolve(withConnectHeaders(event,response)))},fail=err=>{res.done().then(()=>reject(err))};res.ready.then(respond);let connectNext=err=>{if(err)return fail(err);if(res.settled)return;let id=state.req.requestId;if(id&&event.req.headers.get(`x-request-id`)!==id)try{event.req.headers.set(`x-request-id`,id)}catch{}let downstream;try{downstream=next()}catch(e){return fail(e)}Promise.resolve(downstream).then(value=>{if(value instanceof Response)return respond(value);res.done().then(()=>resolve(value))},fail)};try{mw(state.req,res,connectNext)}catch(err){fail(err)}})}function assembleCatchAll(app){let state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,app.all(`/**`,event=>{let node=event.req.runtime?.node,next=node?.req?.[NEXT];if(node&&next&&!state[NO_FALLTHROUGH])return new Promise(resolve=>{let done=()=>resolve(H3_HANDLED);node.res.once(`finish`,done),node.res.once(`close`,done),next()});let mw=state[NOTFOUND_MW];return runConnectTerminal(mw,event)}))}function proxyTrust(option){if(option!==void 0&&option!==!1){if(option===!0)return()=>!0;if(typeof option==`number`)return(_address,hop)=>hop<option;if(typeof option==`function`)return option;log.warn(`h3: trustProxy as an address or subnet list is not supported; client IPs use the socket address. Use a hop count or a function instead.`)}}function forwardedClientIp(req,trust){let socket=req.socket?.remoteAddress;if(!socket)return;let header=req.headers[`x-forwarded-for`],chain=[socket,...(Array.isArray(header)?header.join(`,`):header??``).split(`,`).map(s=>s.trim()).filter(Boolean).toReversed()];for(let hop=0;hop<chain.length-1;hop++)if(!trust(chain[hop],hop))return chain[hop];return chain[chain.length-1]}function stripMountPrefix(path,mw){let prefix=path.endsWith(`/`)?path.slice(0,-1):path;return prefix===``?mw:((req,res,next)=>{let url=req.url??`/`,rest=url.startsWith(prefix)?url.slice(prefix.length):null;return rest===null||rest!==``&&rest[0]!==`/`&&rest[0]!==`?`?mw(req,res,next):(req.originalUrl??=url,req.url=rest.startsWith(`/`)?rest:`/${rest}`,mw(req,res,err=>{req.url=url,next(err)}))})}function h3Runtime(options={}){let{H3,toNodeHandler,fromNodeHandler}=loadH3v2(options.h3);return{name:`h3`,createApp(options={}){let holder={},app=new H3({onError:(error,event)=>{let mw=holder.app?.[ERROR_MW];return runConnectTerminal(mw,event,error).then(response=>withConnectHeaders(event,response))}});return holder.app=app,app[NO_FALLTHROUGH]=options.notFoundFallthrough===!1,app[TRUST_PROXY]=proxyTrust(options.trustProxy),app[BODY_LIMIT]=options.bodyLimit,app},nodeHandler(app){assembleCatchAll(app);let listener=toNodeHandler(app),trust=app[TRUST_PROXY];return(req,res,next)=>{if(next&&(req[NEXT]=next),trust&&!req.ip){let ip=forwardedClientIp(req,trust);ip&&(req.ip=ip)}res.setMaxListeners(0);try{let result=listener(req,res);result&&typeof result.then==`function`&&result.catch(err=>next?.(err))}catch(err){next?.(err)}}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path),run=compileWebRoute(entry,{onError:async(err,req,driver)=>{let mw=app[ERROR_MW];if(mw)try{await mw(err,req,driver,NOOP_NEXT)}catch(handlerErr){log.error(handlerErr,`h3: the error handler failed`),driver.settled||await builtInError(err,req,driver,NOOP_NEXT)}}},{bodyLimit:app[BODY_LIMIT]}),handler=event=>run({request:event.req,url:event.url,params:event.context.params??{},carry:event.req.runtime?.node?.req??FETCH_CONNECT.get(event)?.req});app.on(entry.method,url,handler),entry.method===`GET`&&app.on(`HEAD`,url,event=>headFromGet(handler(event)))}},useConnect(app,rawMw,opts){let path=opts?.path;if(Array.isArray(path)){for(let member of path)this.useConnect(app,rawMw,{path:member});return}let mw=typeof path==`string`?stripMountPrefix(path,rawMw):rawMw,viaNode=fromNodeHandler(mw),handler=(event,next)=>event.req.runtime?.node?.res?viaNode(event):runConnectOnFetch(mw,event,next);path instanceof RegExp?app.use((event,next)=>path.test(event.url.pathname)?handler(event,next):next()):typeof path==`string`?app.use(joinPath(path,`/**`),handler):app.use(handler)},serveStatic(app,prefix,dir){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw,assembleCatchAll(app)},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}const h3WebRuntime=h3Runtime;export{h3Runtime,h3WebRuntime};
|
|
12
12
|
//# sourceMappingURL=h3.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"h3.mjs","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"sourcesContent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// Targets h3 v2: the web-standard line where `event.req` is a WHATWG Request,\n// handlers return values/Responses, and `app.fetch(request)` is the universal\n// entry. h3 v1 is not supported; loading it fails fast with upgrade guidance.\n//\n// The request pipeline runs through the shared web driver pair\n// (`../web/driver`, `../web/handler`) — the same code path the\n// `@forinda/kickjs/web` edge entry uses, so node bootstrap and edge deploys\n// exercise identical request semantics.\n//\n// Unmatched requests: behind a node host that passed `next` (`kick dev`'s\n// Vite server, `app.handle(req, res, next)`), they are handed back to it\n// like the Fastify runtime does, unless `notFoundFallthrough: false`;\n// everywhere else kick's notFound handler answers them.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport * as h3Peer from 'h3'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { lazyServeStatic } from './lazy-serve-static'\nimport { compileWebRoute, headFromGet, readThrough, type WebRouteHooks } from '../web/handler'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger } from '../../core/logger'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\nconst log = createLogger('H3Runtime')\n\nconst NOTFOUND_MW = Symbol('kickjs.h3web.notFoundMw')\nconst ERROR_MW = Symbol('kickjs.h3web.errorMw')\nconst ASSEMBLED = Symbol('kickjs.h3web.assembled')\nconst NOOP_NEXT = (): void => {}\n/** The host's `next`, stashed on the node request by `nodeHandler`. */\nconst NEXT = Symbol('kickjs.h3web.next')\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.h3web.noFallthrough')\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\nconst BODY_LIMIT = Symbol('kickjs.h3.bodyLimit')\n/** h3 v2's \"the node response was handled elsewhere\" return value. */\nconst H3_HANDLED = Symbol.for('h3.handled')\n\n// Minimal structural surface of h3 v2 we depend on.\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n use(...args: unknown[]): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request & { runtime?: { node?: { req: IncomingMessage; res: ServerResponse } } }\n url: URL\n context: { params?: Record<string, string> }\n}\n\ninterface H3v2Module {\n H3: new (config?: unknown) => H3AppLike\n toNodeHandler: (app: H3AppLike) => (req: IncomingMessage, res: ServerResponse) => void\n fromNodeHandler: (mw: unknown) => unknown\n}\n\nexport interface H3RuntimeOptions {\n /**\n * Pre-imported h3 module, for when the app's `h3` is a different copy from\n * the one this package resolves (a linked checkout):\n * `h3Runtime({ h3: await import('h3') })`.\n * Omitted → the installed `h3` peer. The peer must be installed either way:\n * this entry imports it statically so `kick build:netlify|vercel` bundles it.\n */\n h3?: unknown\n}\n\n/** An h3 module as `import()` or `require()` hands it over, ESM interop unwrapped. */\nfunction unwrapH3Module(mod: unknown): Record<string, unknown> {\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n return m && m.__esModule && m.default ? { ...m.default, ...m } : m\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n // A static import, so a bundle (`kick build:netlify|vercel`) carries h3.\n const resolved = unwrapH3Module(injected ?? h3Peer) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs: h3Runtime() requires h3 v2, but the installed h3 has no H3 class — that is the v1 line, ' +\n 'which this version of KickJS no longer supports. Upgrade h3 to ^2.',\n )\n }\n return resolved\n}\n\n/**\n * Bridge a connect-style terminal middleware (kick's notFound / error\n * handlers) onto the web driver pair, returning the produced Response.\n */\nasync function runConnectTerminal(\n mw: ConnectMiddleware | undefined,\n event: H3EventLike,\n err?: unknown,\n): Promise<Response> {\n const shim = new WebRequestShim(event.req, event.url)\n // What the app's connect middleware set (session, an adapter's slot) is\n // visible to the error / not-found handler, as on the route itself.\n const carry = event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req\n const req = carry ? readThrough(shim, carry) : shim\n const driver = new WebResponseDriver(event.req.signal)\n // A request store of its own, as a route has: the handler (an error page,\n // say) can use the RequestContext and REQUEST-scoped services.\n const store = createRequestStore(\n (req as { requestId?: string }).requestId || (event.req.headers.get('x-request-id') ?? ''),\n )\n const work = requestStore.run(store, () => answerTerminal(mw, req, driver, err))\n // After the handler finishes too: a streamed answer settles `ready` while\n // the handler may still be using its REQUEST-scoped instances. A handler\n // that fails may never answer, so its failure disposes at once.\n const dispose = () => disposeRequestStore(store)\n work.then(() => driver.ready).then(dispose, dispose)\n await work\n return driver.ready\n}\n\nasync function answerTerminal(\n mw: ConnectMiddleware | undefined,\n req: Parameters<typeof builtInNotFound>[0],\n driver: WebResponseDriver,\n err: unknown,\n): Promise<void> {\n // A failing handler is an error in its own right: answered as one below.\n let failure = err\n if (mw) {\n const returned =\n err !== undefined\n ? (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n : (mw as (rq: unknown, rs: unknown, n: () => void) => unknown)(req, driver, NOOP_NEXT)\n // An async handler answers after an await: wait for it before deciding\n // nothing answered. One that rejects is an error in its own right.\n if (typeof (returned as PromiseLike<void> | undefined)?.then === 'function') {\n try {\n await returned\n } catch (handlerErr) {\n log.error(handlerErr, `h3: the ${err !== undefined ? 'error' : 'not-found'} handler failed`)\n failure ??= handlerErr\n }\n }\n }\n if (!driver.settled) {\n // The configured handler didn't answer (or there wasn't one): the\n // built-in handlers answer, in the shape every other engine uses. The\n // built-in error handler logs, so the failure still leaves a trace.\n if (failure !== undefined) await builtInError(failure, req, driver, NOOP_NEXT)\n else builtInNotFound(req, driver, NOOP_NEXT)\n }\n}\n\n// ── Connect middleware on the fetch path ─────────────────────────────────\n//\n// `app.fetch(request)` (edge, Bun, Deno, a serverless function) carries no\n// node req/res, and h3's `fromNodeHandler` throws without one. Connect\n// middleware there runs against the web driver pair instead: one request shim\n// per event (so `req.requestId` set by one middleware is seen by the next) and\n// one header bag per event that is merged into whatever Response comes back.\n// The merge is ours rather than h3's `event.res.headers` because h3 skips\n// prepared headers on non-2xx responses, and a 404/422/500 must still carry\n// helmet's headers and the request id, exactly as on node.\n\ninterface FetchConnectState {\n req: WebRequestShim\n headers: Headers\n}\n\nconst FETCH_CONNECT = new WeakMap<object, FetchConnectState>()\n\nfunction fetchConnectState(event: H3EventLike): FetchConnectState {\n let state = FETCH_CONNECT.get(event)\n if (!state) {\n state = { req: new WebRequestShim(event.req, event.url), headers: new Headers() }\n FETCH_CONNECT.set(event, state)\n }\n return state\n}\n\n/**\n * Add the headers connect middleware set to `response`. The response's own\n * headers win — a later `setHeader` overrides an earlier one on node too.\n * Consumed once, so every middleware layer can call it on the way out.\n */\nfunction withConnectHeaders(event: H3EventLike, response: Response): Response {\n const state = FETCH_CONNECT.get(event)\n if (!state) return response\n const missing = [...state.headers].filter(\n ([name]) => name === 'set-cookie' || !response.headers.has(name),\n )\n state.headers = new Headers()\n if (missing.length === 0) return response\n try {\n for (const [name, value] of missing) response.headers.append(name, value)\n return response\n } catch {\n // Immutable headers (a Response from fetch) — rebuild around the body.\n const headers = new Headers(response.headers)\n for (const [name, value] of missing) headers.append(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n}\n\n/**\n * The node `res` surface connect middleware uses, over the web driver:\n * headers go to the per-event bag, `statusCode`, and `finish`/`close`\n * emitted once the response exists.\n */\nclass FetchConnectResponse extends WebResponseDriver {\n private code = 200\n private listeners: Array<[string, (...args: unknown[]) => void]> = []\n\n constructor(\n private readonly prepared: Headers,\n signal: AbortSignal,\n ) {\n super(signal)\n }\n\n get statusCode(): number {\n return this.code\n }\n\n set statusCode(code: number) {\n this.status(code)\n }\n\n override status(code: number): this {\n this.code = code\n return super.status(code)\n }\n\n override writeHead(code: number, headers?: Record<string, string | number | string[]>): this {\n this.code = code\n return super.writeHead(code, headers)\n }\n\n override setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.prepared.delete(name)\n for (const v of value) this.prepared.append(name, String(v))\n } else {\n this.prepared.set(name, String(value))\n }\n return this\n }\n\n getHeader(name: string): string | undefined {\n return this.prepared.get(name) ?? undefined\n }\n\n hasHeader(name: string): boolean {\n return this.prepared.has(name)\n }\n\n removeHeader(name: string): void {\n this.prepared.delete(name)\n }\n\n override once(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners.push([event, listener])\n return this\n }\n\n on(event: string, listener: (...args: unknown[]) => void): this {\n return this.once(event, listener)\n }\n\n removeListener(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners = this.listeners.filter(([e, l]) => e !== event || l !== listener)\n return this\n }\n\n off(event: string, listener: (...args: unknown[]) => void): this {\n return this.removeListener(event, listener)\n }\n\n /**\n * The response exists (or the request failed): fire `finish` then `close`.\n * Runs before `withConnectHeaders` merges this response's headers into the\n * route's, so a `finish` listener can still set one — the cookie session\n * store writes its cookie there.\n */\n done(): void {\n for (const event of ['finish', 'close']) {\n for (const [e, listener] of this.listeners) if (e === event) listener()\n this.listeners = this.listeners.filter(([e]) => e !== event)\n }\n }\n}\n\nfunction runConnectOnFetch(\n mw: ConnectMiddleware,\n event: H3EventLike,\n next: () => unknown,\n): Promise<unknown> {\n const state = fetchConnectState(event)\n const res = new FetchConnectResponse(state.headers, event.req.signal)\n\n return new Promise((resolve, reject) => {\n const respond = (response: Response): void => {\n res.done()\n resolve(withConnectHeaders(event, response))\n }\n const fail = (err: unknown): void => {\n res.done()\n reject(err)\n }\n\n // The middleware answered itself (`res.end`, `res.json`, `writeHead`).\n void res.ready.then(respond)\n\n const connectNext = (err?: unknown): void => {\n if (err) return fail(err)\n if (res.settled) return\n // The route builds its request store from the inbound header; hand it the\n // id requestScope/requestId settled on so body, logs and header agree.\n const id = state.req.requestId\n if (id && event.req.headers.get('x-request-id') !== id) {\n try {\n event.req.headers.set('x-request-id', id)\n } catch {\n // Immutable request headers on some runtimes — the route mints its own id.\n }\n }\n let downstream: unknown\n try {\n // Synchronous, so downstream work starts inside any AsyncLocalStorage\n // scope this middleware opened (requestScopeMiddleware).\n downstream = next()\n } catch (e) {\n return fail(e)\n }\n Promise.resolve(downstream).then((value) => {\n if (value instanceof Response) return respond(value)\n res.done()\n resolve(value)\n }, fail)\n }\n\n try {\n ;(mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => void)(\n state.req,\n res,\n connectNext,\n )\n } catch (err) {\n fail(err)\n }\n })\n}\n\n/**\n * Terminal catch-all AFTER all mounted routes: kick's own notFound handler\n * answers unmatched paths (h3 v2's default 404 never fires). rou3 ranks `/**`\n * below every concrete route, so registration time does not matter.\n */\nfunction assembleCatchAll(app: H3AppLike): void {\n const state = app as unknown as Record<symbol, unknown>\n if (state[ASSEMBLED]) return\n state[ASSEMBLED] = true\n app.all('/**', (event: H3EventLike) => {\n const node = event.req.runtime?.node\n const next = (node?.req as (IncomingMessage & { [NEXT]?: () => void }) | undefined)?.[NEXT]\n if (node && next && !state[NO_FALLTHROUGH]) {\n // Hand the request back to the host and tell h3 the node response is\n // taken care of; srvx then leaves the already-written response alone.\n return new Promise((resolve) => {\n const done = () => resolve(H3_HANDLED)\n node.res.once('finish', done)\n node.res.once('close', done)\n next()\n })\n }\n const mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n}\n\ntype ProxyTrust = (address: string, hop: number) => boolean\n\n/**\n * The `trustProxy` forms h3 can honour without an address-matching library:\n * `true` (every hop), a hop count, or a predicate — Express's semantics for\n * each. Address and subnet lists are not supported here; they are refused\n * with a warning and the socket address is kept, so a misread rule never\n * trusts a header it should not.\n */\nfunction proxyTrust(option: RuntimeAppOptions['trustProxy']): ProxyTrust | undefined {\n if (option === undefined || option === false) return undefined\n if (option === true) return () => true\n if (typeof option === 'number') return (_address, hop) => hop < option\n if (typeof option === 'function') return option\n log.warn(\n 'h3: trustProxy as an address or subnet list is not supported; client IPs ' +\n 'use the socket address. Use a hop count or a function instead.',\n )\n return undefined\n}\n\n/**\n * Express's `proxy-addr` walk: from the socket outward through\n * `x-forwarded-for`, stop at the first address the rule does not trust.\n */\nfunction forwardedClientIp(req: IncomingMessage, trust: ProxyTrust): string | undefined {\n const socket = req.socket?.remoteAddress\n if (!socket) return undefined\n const header = req.headers['x-forwarded-for']\n const forwarded = (Array.isArray(header) ? header.join(',') : (header ?? ''))\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n .toReversed()\n const chain = [socket, ...forwarded]\n for (let hop = 0; hop < chain.length - 1; hop++) {\n if (!trust(chain[hop]!, hop)) return chain[hop]\n }\n return chain[chain.length - 1]\n}\n\n/**\n * A middleware mounted at a path sees `req.url` relative to that path, as on\n * Express — `serve-static` mounted at `/files` must look up\n * `/nested/a.txt`, not `/files/nested/a.txt`. h3 v2 leaves the URL whole, so\n * strip the prefix for the call and restore it when the middleware passes on.\n * `req.originalUrl` keeps the full URL, as Express sets it.\n */\nfunction stripMountPrefix(path: string, mw: ConnectMiddleware): ConnectMiddleware {\n const prefix = path.endsWith('/') ? path.slice(0, -1) : path\n if (prefix === '') return mw\n return ((\n req: IncomingMessage & { originalUrl?: string },\n res: unknown,\n next: (err?: unknown) => void,\n ) => {\n const url = req.url ?? '/'\n const rest = url.startsWith(prefix) ? url.slice(prefix.length) : null\n if (rest === null || (rest !== '' && rest[0] !== '/' && rest[0] !== '?')) {\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n next,\n )\n }\n req.originalUrl ??= url\n req.url = rest.startsWith('/') ? rest : `/${rest}`\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n (err?: unknown) => {\n req.url = url\n next(err)\n },\n )\n }) as unknown as ConnectMiddleware\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3Runtime(options: H3RuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const holder: { app?: H3AppLike } = {}\n const app = new H3({\n // Engine-level errors (middleware throws outside the kick pipeline)\n // dispatch to the kick error handler once setErrorHandler stashes it.\n onError: (error: unknown, event: H3EventLike) => {\n const mw = (holder.app as unknown as Record<symbol, ConnectMiddleware | undefined>)?.[\n ERROR_MW\n ]\n return runConnectTerminal(mw, event, error).then((response) =>\n withConnectHeaders(event, response),\n )\n },\n })\n holder.app = app\n ;(app as unknown as Record<symbol, unknown>)[NO_FALLTHROUGH] =\n options.notFoundFallthrough === false\n ;(app as unknown as Record<symbol, unknown>)[TRUST_PROXY] = proxyTrust(options.trustProxy)\n ;(app as unknown as Record<symbol, unknown>)[BODY_LIMIT] = options.bodyLimit\n return app\n },\n\n nodeHandler(app) {\n assembleCatchAll(app)\n const listener = toNodeHandler(app)\n const trust = (app as unknown as Record<symbol, unknown>)[TRUST_PROXY] as\n | ProxyTrust\n | undefined\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n // Express and Fastify derive `req.ip` from their trust-proxy settings;\n // this is h3's equivalent, off unless the app opts in, because an\n // unverified `x-forwarded-for` is client-controllable. Without it every\n // caller behind a proxy shares the proxy's address (one rate-limit bucket).\n if (trust && !(req as { ip?: string }).ip) {\n const ip = forwardedClientIp(req, trust)\n if (ip) (req as { ip?: string }).ip = ip\n }\n // h3 v2 adds 'close' / 'finish' listeners for every connect middleware\n // and keeps them until the response ends, so an ordinary middleware\n // stack crosses Node's default of 10 and warns about a leak on every\n // request. They go away with the response; no limit is needed.\n res.setMaxListeners(0)\n try {\n const result = listener(req, res) as unknown\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n void (result as Promise<unknown>).catch((err) => next?.(err))\n }\n } catch (err) {\n next?.(err)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const hooks: WebRouteHooks = {\n onError: async (err, req, driver) => {\n const mw = (app as unknown as Record<symbol, ConnectMiddleware | undefined>)[ERROR_MW]\n if (!mw) return\n // Awaited: an async handler answers after its await, and the\n // pipeline falls back to its own answer once this returns.\n try {\n await (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } catch (handlerErr) {\n log.error(handlerErr, 'h3: the error handler failed')\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n }\n },\n }\n const run = compileWebRoute(entry, hooks, {\n bodyLimit: (app as unknown as Record<symbol, number | undefined>)[BODY_LIMIT],\n })\n const handler = (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n carry: event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req,\n })\n app.on(entry.method, url, handler)\n // HEAD answers every GET route (routes have no HEAD method of their own).\n if (entry.method === 'GET') {\n app.on('HEAD', url, (event: H3EventLike) =>\n headFromGet(handler(event) as Promise<Response>),\n )\n }\n }\n }\n },\n\n useConnect(app, rawMw: ConnectMiddleware, opts?: UseConnectOptions) {\n const path = opts?.path\n // A list mounts each member, as Express does.\n if (Array.isArray(path)) {\n for (const member of path) this.useConnect!(app, rawMw, { path: member })\n return\n }\n const mw = typeof path === 'string' ? stripMountPrefix(path, rawMw) : rawMw\n // Behind a node server (toNodeHandler) the event carries node req/res and\n // h3's own bridge runs the middleware unchanged. Called through\n // `app.fetch(request)` there is none and fromNodeHandler would throw, so\n // the middleware runs against the web driver pair instead.\n const viaNode = fromNodeHandler(mw) as (event: H3EventLike) => unknown\n const handler = (event: H3EventLike, next: () => unknown) =>\n event.req.runtime?.node?.res ? viaNode(event) : runConnectOnFetch(mw, event, next)\n if (path instanceof RegExp) {\n // h3 routes by string pattern only; test the pathname per request.\n // Like Express, a pattern mount leaves `req.url` whole.\n app.use((event: H3EventLike, next: () => unknown) =>\n path.test(event.url.pathname) ? handler(event, next) : next(),\n )\n } else if (typeof path === 'string') {\n // h3 `use` is exact-match; `/**` covers the subtree.\n app.use(joinPath(path, '/**'), handler)\n } else {\n app.use(handler)\n }\n },\n\n serveStatic(app, prefix, dir) {\n // serve-static bridged like any other connect middleware (node only).\n this.useConnect(app, lazyServeStatic(dir), { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[NOTFOUND_MW] = mw\n // Here as well as in nodeHandler: an app only ever called through\n // `app.fetch` never reaches nodeHandler, and would answer h3's own 404.\n assembleCatchAll(app)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n // srvx's node adapter writes HTTP/2 compat responses (it branches on\n // httpVersion \"2.0\"), so the node path serves `server.http2` too.\n http2: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types, for the `kick/runtime` typegen\n * augmentation. Mirrors `ExpressRuntimeTypes`.\n */\nexport interface H3RuntimeTypes {\n request: Request\n response: Response\n app: typeof import('h3') extends { H3: new (...args: never[]) => infer A } ? A : unknown\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n\n/** @deprecated Use {@link h3Runtime} — the same runtime. Removed in the next major. */\nexport const h3WebRuntime = h3Runtime\n/** @deprecated Use {@link H3RuntimeOptions}. */\nexport type H3WebRuntimeOptions = H3RuntimeOptions\n/** @deprecated Use {@link H3RuntimeTypes}. */\nexport type H3WebRuntimeTypes = H3RuntimeTypes\n"],"mappings":";;;;;;;;;;2iBAkCA,MAAM,aAAe,aAAa,EAC5B,gBAAkB,gBAAgB,EAClC,IAAM,aAAa,WAAW,EAE9B,YAAc,OAAO,yBAAyB,EAC9C,SAAW,OAAO,sBAAsB,EACxC,UAAY,OAAO,wBAAwB,EAC3C,cAAwB,CAAC,EAEzB,KAAO,OAAO,mBAAmB,EAEjC,eAAiB,OAAO,4BAA4B,EACpD,YAAc,OAAO,sBAAsB,EAC3C,WAAa,OAAO,qBAAqB,EAEzC,WAAa,OAAO,IAAI,YAAY,EAiC1C,SAAS,eAAe,IAAuC,CAC7D,IAAM,EAAI,IAIV,OAAO,GAAK,EAAE,YAAc,EAAE,QAAU,CAAE,GAAG,EAAE,QAAS,GAAG,CAAE,EAAI,CACnE,CAGA,SAAS,SAAS,SAAgC,CAEhD,IAAM,SAAW,eAAe,UAAY,MAAM,EAClD,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S,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C,CAGA,MAAa,aAAe"}
|
|
1
|
+
{"version":3,"file":"h3.mjs","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"sourcesContent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// Targets h3 v2: the web-standard line where `event.req` is a WHATWG Request,\n// handlers return values/Responses, and `app.fetch(request)` is the universal\n// entry. h3 v1 is not supported; loading it fails fast with upgrade guidance.\n//\n// The request pipeline runs through the shared web driver pair\n// (`../web/driver`, `../web/handler`) — the same code path the\n// `@forinda/kickjs/web` edge entry uses, so node bootstrap and edge deploys\n// exercise identical request semantics.\n//\n// Unmatched requests: behind a node host that passed `next` (`kick dev`'s\n// Vite server, `app.handle(req, res, next)`), they are handed back to it\n// like the Fastify runtime does, unless `notFoundFallthrough: false`;\n// everywhere else kick's notFound handler answers them.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport * as h3Peer from 'h3'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { lazyServeStatic } from './lazy-serve-static'\nimport { compileWebRoute, headFromGet, readThrough, type WebRouteHooks } from '../web/handler'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger } from '../../core/logger'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\nconst log = createLogger('H3Runtime')\n\nconst NOTFOUND_MW = Symbol('kickjs.h3web.notFoundMw')\nconst ERROR_MW = Symbol('kickjs.h3web.errorMw')\nconst ASSEMBLED = Symbol('kickjs.h3web.assembled')\nconst NOOP_NEXT = (): void => {}\n/** The host's `next`, stashed on the node request by `nodeHandler`. */\nconst NEXT = Symbol('kickjs.h3web.next')\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.h3web.noFallthrough')\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\nconst BODY_LIMIT = Symbol('kickjs.h3.bodyLimit')\n/** h3 v2's \"the node response was handled elsewhere\" return value. */\nconst H3_HANDLED = Symbol.for('h3.handled')\n\n// Minimal structural surface of h3 v2 we depend on.\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n use(...args: unknown[]): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request & { runtime?: { node?: { req: IncomingMessage; res: ServerResponse } } }\n url: URL\n context: { params?: Record<string, string> }\n}\n\ninterface H3v2Module {\n H3: new (config?: unknown) => H3AppLike\n toNodeHandler: (app: H3AppLike) => (req: IncomingMessage, res: ServerResponse) => void\n fromNodeHandler: (mw: unknown) => unknown\n}\n\nexport interface H3RuntimeOptions {\n /**\n * Pre-imported h3 module, for when the app's `h3` is a different copy from\n * the one this package resolves (a linked checkout):\n * `h3Runtime({ h3: await import('h3') })`.\n * Omitted → the installed `h3` peer. The peer must be installed either way:\n * this entry imports it statically so `kick build:netlify|vercel` bundles it.\n */\n h3?: unknown\n}\n\n/** An h3 module as `import()` or `require()` hands it over, ESM interop unwrapped. */\nfunction unwrapH3Module(mod: unknown): Record<string, unknown> {\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n return m && m.__esModule && m.default ? { ...m.default, ...m } : m\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n // A static import, so a bundle (`kick build:netlify|vercel`) carries h3.\n const resolved = unwrapH3Module(injected ?? h3Peer) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs: h3Runtime() requires h3 v2, but the installed h3 has no H3 class — that is the v1 line, ' +\n 'which this version of KickJS no longer supports. Upgrade h3 to ^2.',\n )\n }\n return resolved\n}\n\n/**\n * Bridge a connect-style terminal middleware (kick's notFound / error\n * handlers) onto the web driver pair, returning the produced Response.\n */\nasync function runConnectTerminal(\n mw: ConnectMiddleware | undefined,\n event: H3EventLike,\n err?: unknown,\n): Promise<Response> {\n const shim = new WebRequestShim(event.req, event.url)\n // What the app's connect middleware set (session, an adapter's slot) is\n // visible to the error / not-found handler, as on the route itself.\n const carry = event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req\n const req = carry ? readThrough(shim, carry) : shim\n const driver = new WebResponseDriver(event.req.signal)\n // A request store of its own, as a route has: the handler (an error page,\n // say) can use the RequestContext and REQUEST-scoped services.\n const store = createRequestStore(\n (req as { requestId?: string }).requestId || (event.req.headers.get('x-request-id') ?? ''),\n )\n const work = requestStore.run(store, () => answerTerminal(mw, req, driver, err))\n // After the handler finishes too: a streamed answer settles `ready` while\n // the handler may still be using its REQUEST-scoped instances. A handler\n // that fails may never answer, so its failure disposes at once.\n const dispose = () => disposeRequestStore(store)\n work.then(() => driver.ready).then(dispose, dispose)\n await work\n return driver.ready\n}\n\nasync function answerTerminal(\n mw: ConnectMiddleware | undefined,\n req: Parameters<typeof builtInNotFound>[0],\n driver: WebResponseDriver,\n err: unknown,\n): Promise<void> {\n // A failing handler is an error in its own right: answered as one below.\n let failure = err\n if (mw) {\n const returned =\n err !== undefined\n ? (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n : (mw as (rq: unknown, rs: unknown, n: () => void) => unknown)(req, driver, NOOP_NEXT)\n // An async handler answers after an await: wait for it before deciding\n // nothing answered. One that rejects is an error in its own right.\n if (typeof (returned as PromiseLike<void> | undefined)?.then === 'function') {\n try {\n await returned\n } catch (handlerErr) {\n log.error(handlerErr, `h3: the ${err !== undefined ? 'error' : 'not-found'} handler failed`)\n failure ??= handlerErr\n }\n }\n }\n if (!driver.settled) {\n // The configured handler didn't answer (or there wasn't one): the\n // built-in handlers answer, in the shape every other engine uses. The\n // built-in error handler logs, so the failure still leaves a trace.\n if (failure !== undefined) await builtInError(failure, req, driver, NOOP_NEXT)\n else builtInNotFound(req, driver, NOOP_NEXT)\n }\n}\n\n// ── Connect middleware on the fetch path ─────────────────────────────────\n//\n// `app.fetch(request)` (edge, Bun, Deno, a serverless function) carries no\n// node req/res, and h3's `fromNodeHandler` throws without one. Connect\n// middleware there runs against the web driver pair instead: one request shim\n// per event (so `req.requestId` set by one middleware is seen by the next) and\n// one header bag per event that is merged into whatever Response comes back.\n// The merge is ours rather than h3's `event.res.headers` because h3 skips\n// prepared headers on non-2xx responses, and a 404/422/500 must still carry\n// helmet's headers and the request id, exactly as on node.\n\ninterface FetchConnectState {\n req: WebRequestShim\n headers: Headers\n}\n\nconst FETCH_CONNECT = new WeakMap<object, FetchConnectState>()\n\nfunction fetchConnectState(event: H3EventLike): FetchConnectState {\n let state = FETCH_CONNECT.get(event)\n if (!state) {\n state = { req: new WebRequestShim(event.req, event.url), headers: new Headers() }\n FETCH_CONNECT.set(event, state)\n }\n return state\n}\n\n/**\n * Add the headers connect middleware set to `response`. The response's own\n * headers win — a later `setHeader` overrides an earlier one on node too.\n * Consumed once, so every middleware layer can call it on the way out.\n */\nfunction withConnectHeaders(event: H3EventLike, response: Response): Response {\n const state = FETCH_CONNECT.get(event)\n if (!state) return response\n const missing = [...state.headers].filter(\n ([name]) => name === 'set-cookie' || !response.headers.has(name),\n )\n state.headers = new Headers()\n if (missing.length === 0) return response\n try {\n for (const [name, value] of missing) response.headers.append(name, value)\n return response\n } catch {\n // Immutable headers (a Response from fetch) — rebuild around the body.\n const headers = new Headers(response.headers)\n for (const [name, value] of missing) headers.append(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n}\n\n/**\n * The node `res` surface connect middleware uses, over the web driver:\n * headers go to the per-event bag, `statusCode`, and `finish`/`close`\n * emitted once the response exists.\n */\nclass FetchConnectResponse extends WebResponseDriver {\n private code = 200\n private listeners: Array<[string, (...args: unknown[]) => void]> = []\n\n constructor(\n private readonly prepared: Headers,\n signal: AbortSignal,\n ) {\n super(signal)\n }\n\n get statusCode(): number {\n return this.code\n }\n\n set statusCode(code: number) {\n this.status(code)\n }\n\n override status(code: number): this {\n this.code = code\n return super.status(code)\n }\n\n override writeHead(code: number, headers?: Record<string, string | number | string[]>): this {\n this.code = code\n return super.writeHead(code, headers)\n }\n\n override setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.prepared.delete(name)\n for (const v of value) this.prepared.append(name, String(v))\n } else {\n this.prepared.set(name, String(value))\n }\n return this\n }\n\n getHeader(name: string): string | undefined {\n return this.prepared.get(name) ?? undefined\n }\n\n hasHeader(name: string): boolean {\n return this.prepared.has(name)\n }\n\n removeHeader(name: string): void {\n this.prepared.delete(name)\n }\n\n override once(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners.push([event, listener])\n return this\n }\n\n on(event: string, listener: (...args: unknown[]) => void): this {\n return this.once(event, listener)\n }\n\n removeListener(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners = this.listeners.filter(([e, l]) => e !== event || l !== listener)\n return this\n }\n\n off(event: string, listener: (...args: unknown[]) => void): this {\n return this.removeListener(event, listener)\n }\n\n /**\n * The response exists (or the request failed): fire `finish` then `close`.\n * Runs before `withConnectHeaders` merges this response's headers into the\n * route's, so a `finish` listener can still set one — the cookie session\n * store writes its cookie there. A listener that returns a promise (a session\n * store's save) is waited for: the response isn't handed back before it, so\n * the request after it sees what this one saved.\n */\n done(): Promise<void> {\n const pending: Promise<unknown>[] = []\n for (const event of ['finish', 'close']) {\n for (const [e, listener] of this.listeners) {\n if (e !== event) continue\n let out: unknown\n try {\n out = listener()\n } catch (err) {\n // One broken listener mustn't hold the response or skip the rest.\n log.error(err, `h3: a '${event}' listener failed`)\n continue\n }\n if (out && typeof (out as Promise<unknown>).then === 'function')\n pending.push(Promise.resolve(out).catch(() => {}))\n }\n this.listeners = this.listeners.filter(([e]) => e !== event)\n }\n return Promise.all(pending).then(() => {})\n }\n}\n\nfunction runConnectOnFetch(\n mw: ConnectMiddleware,\n event: H3EventLike,\n next: () => unknown,\n): Promise<unknown> {\n const state = fetchConnectState(event)\n const res = new FetchConnectResponse(state.headers, event.req.signal)\n\n return new Promise((resolve, reject) => {\n const respond = (response: Response): void => {\n void res.done().then(() => resolve(withConnectHeaders(event, response)))\n }\n const fail = (err: unknown): void => {\n void res.done().then(() => reject(err))\n }\n\n // The middleware answered itself (`res.end`, `res.json`, `writeHead`).\n void res.ready.then(respond)\n\n const connectNext = (err?: unknown): void => {\n if (err) return fail(err)\n if (res.settled) return\n // The route builds its request store from the inbound header; hand it the\n // id requestScope/requestId settled on so body, logs and header agree.\n const id = state.req.requestId\n if (id && event.req.headers.get('x-request-id') !== id) {\n try {\n event.req.headers.set('x-request-id', id)\n } catch {\n // Immutable request headers on some runtimes — the route mints its own id.\n }\n }\n let downstream: unknown\n try {\n // Synchronous, so downstream work starts inside any AsyncLocalStorage\n // scope this middleware opened (requestScopeMiddleware).\n downstream = next()\n } catch (e) {\n return fail(e)\n }\n Promise.resolve(downstream).then((value) => {\n if (value instanceof Response) return respond(value)\n void res.done().then(() => resolve(value))\n }, fail)\n }\n\n try {\n ;(mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => void)(\n state.req,\n res,\n connectNext,\n )\n } catch (err) {\n fail(err)\n }\n })\n}\n\n/**\n * Terminal catch-all AFTER all mounted routes: kick's own notFound handler\n * answers unmatched paths (h3 v2's default 404 never fires). rou3 ranks `/**`\n * below every concrete route, so registration time does not matter.\n */\nfunction assembleCatchAll(app: H3AppLike): void {\n const state = app as unknown as Record<symbol, unknown>\n if (state[ASSEMBLED]) return\n state[ASSEMBLED] = true\n app.all('/**', (event: H3EventLike) => {\n const node = event.req.runtime?.node\n const next = (node?.req as (IncomingMessage & { [NEXT]?: () => void }) | undefined)?.[NEXT]\n if (node && next && !state[NO_FALLTHROUGH]) {\n // Hand the request back to the host and tell h3 the node response is\n // taken care of; srvx then leaves the already-written response alone.\n return new Promise((resolve) => {\n const done = () => resolve(H3_HANDLED)\n node.res.once('finish', done)\n node.res.once('close', done)\n next()\n })\n }\n const mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n}\n\ntype ProxyTrust = (address: string, hop: number) => boolean\n\n/**\n * The `trustProxy` forms h3 can honour without an address-matching library:\n * `true` (every hop), a hop count, or a predicate — Express's semantics for\n * each. Address and subnet lists are not supported here; they are refused\n * with a warning and the socket address is kept, so a misread rule never\n * trusts a header it should not.\n */\nfunction proxyTrust(option: RuntimeAppOptions['trustProxy']): ProxyTrust | undefined {\n if (option === undefined || option === false) return undefined\n if (option === true) return () => true\n if (typeof option === 'number') return (_address, hop) => hop < option\n if (typeof option === 'function') return option\n log.warn(\n 'h3: trustProxy as an address or subnet list is not supported; client IPs ' +\n 'use the socket address. Use a hop count or a function instead.',\n )\n return undefined\n}\n\n/**\n * Express's `proxy-addr` walk: from the socket outward through\n * `x-forwarded-for`, stop at the first address the rule does not trust.\n */\nfunction forwardedClientIp(req: IncomingMessage, trust: ProxyTrust): string | undefined {\n const socket = req.socket?.remoteAddress\n if (!socket) return undefined\n const header = req.headers['x-forwarded-for']\n const forwarded = (Array.isArray(header) ? header.join(',') : (header ?? ''))\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n .toReversed()\n const chain = [socket, ...forwarded]\n for (let hop = 0; hop < chain.length - 1; hop++) {\n if (!trust(chain[hop]!, hop)) return chain[hop]\n }\n return chain[chain.length - 1]\n}\n\n/**\n * A middleware mounted at a path sees `req.url` relative to that path, as on\n * Express — `serve-static` mounted at `/files` must look up\n * `/nested/a.txt`, not `/files/nested/a.txt`. h3 v2 leaves the URL whole, so\n * strip the prefix for the call and restore it when the middleware passes on.\n * `req.originalUrl` keeps the full URL, as Express sets it.\n */\nfunction stripMountPrefix(path: string, mw: ConnectMiddleware): ConnectMiddleware {\n const prefix = path.endsWith('/') ? path.slice(0, -1) : path\n if (prefix === '') return mw\n return ((\n req: IncomingMessage & { originalUrl?: string },\n res: unknown,\n next: (err?: unknown) => void,\n ) => {\n const url = req.url ?? '/'\n const rest = url.startsWith(prefix) ? url.slice(prefix.length) : null\n if (rest === null || (rest !== '' && rest[0] !== '/' && rest[0] !== '?')) {\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n next,\n )\n }\n req.originalUrl ??= url\n req.url = rest.startsWith('/') ? rest : `/${rest}`\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n (err?: unknown) => {\n req.url = url\n next(err)\n },\n )\n }) as unknown as ConnectMiddleware\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3Runtime(options: H3RuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const holder: { app?: H3AppLike } = {}\n const app = new H3({\n // Engine-level errors (middleware throws outside the kick pipeline)\n // dispatch to the kick error handler once setErrorHandler stashes it.\n onError: (error: unknown, event: H3EventLike) => {\n const mw = (holder.app as unknown as Record<symbol, ConnectMiddleware | undefined>)?.[\n ERROR_MW\n ]\n return runConnectTerminal(mw, event, error).then((response) =>\n withConnectHeaders(event, response),\n )\n },\n })\n holder.app = app\n ;(app as unknown as Record<symbol, unknown>)[NO_FALLTHROUGH] =\n options.notFoundFallthrough === false\n ;(app as unknown as Record<symbol, unknown>)[TRUST_PROXY] = proxyTrust(options.trustProxy)\n ;(app as unknown as Record<symbol, unknown>)[BODY_LIMIT] = options.bodyLimit\n return app\n },\n\n nodeHandler(app) {\n assembleCatchAll(app)\n const listener = toNodeHandler(app)\n const trust = (app as unknown as Record<symbol, unknown>)[TRUST_PROXY] as\n | ProxyTrust\n | undefined\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n // Express and Fastify derive `req.ip` from their trust-proxy settings;\n // this is h3's equivalent, off unless the app opts in, because an\n // unverified `x-forwarded-for` is client-controllable. Without it every\n // caller behind a proxy shares the proxy's address (one rate-limit bucket).\n if (trust && !(req as { ip?: string }).ip) {\n const ip = forwardedClientIp(req, trust)\n if (ip) (req as { ip?: string }).ip = ip\n }\n // h3 v2 adds 'close' / 'finish' listeners for every connect middleware\n // and keeps them until the response ends, so an ordinary middleware\n // stack crosses Node's default of 10 and warns about a leak on every\n // request. They go away with the response; no limit is needed.\n res.setMaxListeners(0)\n try {\n const result = listener(req, res) as unknown\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n void (result as Promise<unknown>).catch((err) => next?.(err))\n }\n } catch (err) {\n next?.(err)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const hooks: WebRouteHooks = {\n onError: async (err, req, driver) => {\n const mw = (app as unknown as Record<symbol, ConnectMiddleware | undefined>)[ERROR_MW]\n if (!mw) return\n // Awaited: an async handler answers after its await, and the\n // pipeline falls back to its own answer once this returns.\n try {\n await (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } catch (handlerErr) {\n log.error(handlerErr, 'h3: the error handler failed')\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n }\n },\n }\n const run = compileWebRoute(entry, hooks, {\n bodyLimit: (app as unknown as Record<symbol, number | undefined>)[BODY_LIMIT],\n })\n const handler = (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n carry: event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req,\n })\n app.on(entry.method, url, handler)\n // HEAD answers every GET route (routes have no HEAD method of their own).\n if (entry.method === 'GET') {\n app.on('HEAD', url, (event: H3EventLike) =>\n headFromGet(handler(event) as Promise<Response>),\n )\n }\n }\n }\n },\n\n useConnect(app, rawMw: ConnectMiddleware, opts?: UseConnectOptions) {\n const path = opts?.path\n // A list mounts each member, as Express does.\n if (Array.isArray(path)) {\n for (const member of path) this.useConnect!(app, rawMw, { path: member })\n return\n }\n const mw = typeof path === 'string' ? stripMountPrefix(path, rawMw) : rawMw\n // Behind a node server (toNodeHandler) the event carries node req/res and\n // h3's own bridge runs the middleware unchanged. Called through\n // `app.fetch(request)` there is none and fromNodeHandler would throw, so\n // the middleware runs against the web driver pair instead.\n const viaNode = fromNodeHandler(mw) as (event: H3EventLike) => unknown\n const handler = (event: H3EventLike, next: () => unknown) =>\n event.req.runtime?.node?.res ? viaNode(event) : runConnectOnFetch(mw, event, next)\n if (path instanceof RegExp) {\n // h3 routes by string pattern only; test the pathname per request.\n // Like Express, a pattern mount leaves `req.url` whole.\n app.use((event: H3EventLike, next: () => unknown) =>\n path.test(event.url.pathname) ? handler(event, next) : next(),\n )\n } else if (typeof path === 'string') {\n // h3 `use` is exact-match; `/**` covers the subtree.\n app.use(joinPath(path, '/**'), handler)\n } else {\n app.use(handler)\n }\n },\n\n serveStatic(app, prefix, dir) {\n // serve-static bridged like any other connect middleware (node only).\n this.useConnect(app, lazyServeStatic(dir), { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[NOTFOUND_MW] = mw\n // Here as well as in nodeHandler: an app only ever called through\n // `app.fetch` never reaches nodeHandler, and would answer h3's own 404.\n assembleCatchAll(app)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n // srvx's node adapter writes HTTP/2 compat responses (it branches on\n // httpVersion \"2.0\"), so the node path serves `server.http2` too.\n http2: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types, for the `kick/runtime` typegen\n * augmentation. Mirrors `ExpressRuntimeTypes`.\n */\nexport interface H3RuntimeTypes {\n request: Request\n response: Response\n app: typeof import('h3') extends { H3: new (...args: never[]) => infer A } ? A : unknown\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n\n/** @deprecated Use {@link h3Runtime} — the same runtime. Removed in the next major. */\nexport const h3WebRuntime = h3Runtime\n/** @deprecated Use {@link H3RuntimeOptions}. */\nexport type H3WebRuntimeOptions = H3RuntimeOptions\n/** @deprecated Use {@link H3RuntimeTypes}. */\nexport type H3WebRuntimeTypes = H3RuntimeTypes\n"],"mappings":";;;;;;;;;;2iBAkCA,MAAM,aAAe,aAAa,EAC5B,gBAAkB,gBAAgB,EAClC,IAAM,aAAa,WAAW,EAE9B,YAAc,OAAO,yBAAyB,EAC9C,SAAW,OAAO,sBAAsB,EACxC,UAAY,OAAO,wBAAwB,EAC3C,cAAwB,CAAC,EAEzB,KAAO,OAAO,mBAAmB,EAEjC,eAAiB,OAAO,4BAA4B,EACpD,YAAc,OAAO,sBAAsB,EAC3C,WAAa,OAAO,qBAAqB,EAEzC,WAAa,OAAO,IAAI,YAAY,EAiC1C,SAAS,eAAe,IAAuC,CAC7D,IAAM,EAAI,IAIV,OAAO,GAAK,EAAE,YAAc,EAAE,QAAU,CAAE,GAAG,EAAE,QAAS,GAAG,CAAE,EAAI,CACnE,CAGA,SAAS,SAAS,SAAgC,CAEhD,IAAM,SAAW,eAAe,UAAY,M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,GAAG,EAAG,CAAE,KAAM,MAAO,CAAC,CAC7D,EAEA,YAAY,IAAK,GAAuB,CACrC,IAAsD,aAAe,GAGtE,iBAAiB,GAAG,CACtB,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAAsD,UAAY,EACrE,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GAGnB,MAAO,EACT,CACF,CACF,CAaA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C,CAGA,MAAa,aAAe"}
|
package/dist/index.d.mts
CHANGED
|
@@ -14,7 +14,7 @@ import { A as NoJobHandlerError, C as JOB_DISPATCHER, D as JobDispatcher, E as J
|
|
|
14
14
|
import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider } from "./cache-CdRHSXow.mjs";
|
|
15
15
|
import { a as describeError, i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "./logger-xE9qI_FS.mjs";
|
|
16
16
|
import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "./errors-By6UueCm.mjs";
|
|
17
|
-
import { $ as createSigner, $t as CircuitBreaker, A as requestScopeMiddleware, At as StartupCheckError, B as formErrorHandler, Bt as GroupAssetKeysResult, C as ViewAdapterOptions, Ct as RequestHistogram, D as TraceContextOptions, Dt as CheckContext, E as TraceContext, Et as CacheResponseOptions, F as buildRoutes, Ft as bindRoutePolicy, G as SECRET_FIELD, Gt as MountCycleError, H as FORM_ERRORS_KEY, Ht as stripExt, I as expressRuntime, It as offerRoutePolicy, J as oldInput, Jt as mountSort, K as fieldErrors, Kt as MountKind, L as materializeRouter, Lt as AssetKeyPair, M as getRequestStore, Mt as StartupStep, N as getRequestValue, Nt as StartupTimelineSnapshot, O as parseTraceparent, Ot as CheckMessage, P as requestStore, Pt as RoutePolicyTable, Q as VerifyOptions, Qt as MissingContributorError, R as FormErrorHandler, Rt as AssetKeyStrategy, S as ViewAdapter, St as MetricsOptions, T as TRACEPARENT_HEADER, Tt as CacheResponse, U as OLD_INPUT_KEY, Ut as DuplicateMountNameError, V as FLASH_KEY, Vt as groupAssetKeys, W as PREVIOUS_URL_KEY, Wt as MissingMountDepError, X as Signer, Xt as DuplicateContributorError, Y as SignedCheck, Yt as ContributorCycleError, Z as SignerOptions, Zt as MissingContextValueError, _ as HealthProbe, _t as CronAdapterOptions, a as ConfigDescription, an as KickError, at as verifyPassword, b as SpaAdapterOptions, bt as KickCronAdapter, c as MiddlewareEntry, ct as isClusterPrimary, dt as bootstrap, en as CircuitBreakerOptions, et as LegacyHasher, ft as ERROR_CHANNEL, g as HealthModuleConfig, gt as CRON_WORKER_ENV, h as HealthController, ht as RESPONSE_CHANNEL, i as ApplicationOptions, in as FormatKickErrorOptions, it as hashPassword, j as RequestStore, jt as defineCheck, k as traceContext, kt as StartupCheck, l as MountedRouteInfo, lt as KickHandler, m as HealthCheckResult, mt as HandlerTraceContext, n as AppStatus, nn as CircuitBreakerStats, nt as PasswordHashOptions, o as ConfigOrigins, on as KickErrorInit, ot as defineHttpContextDecorator, p as HEALTH_PROBE, pt as HANDLER_CHANNEL, q as flash, qt as MountSortItem, r as Application, rn as CircuitOpenError, rt as VerifyPasswordOptions, s as ManagementOptions, sn as formatKickError, st as ClusterOptions, t as APPLICATION, tn as CircuitBreakerState, tt as PasswordCheck, u as ServerOptions, ut as createHandler, v as healthModule, vt as CronSchedule, wt as metricsAdapter, xt as RAW_BODY, y as SpaAdapter, yt as CronScheduler, z as FormErrorHandlerOptions, zt as GroupAssetKeysOptions } from "./application-
|
|
17
|
+
import { $ as createSigner, $t as CircuitBreaker, A as requestScopeMiddleware, At as StartupCheckError, B as formErrorHandler, Bt as GroupAssetKeysResult, C as ViewAdapterOptions, Ct as RequestHistogram, D as TraceContextOptions, Dt as CheckContext, E as TraceContext, Et as CacheResponseOptions, F as buildRoutes, Ft as bindRoutePolicy, G as SECRET_FIELD, Gt as MountCycleError, H as FORM_ERRORS_KEY, Ht as stripExt, I as expressRuntime, It as offerRoutePolicy, J as oldInput, Jt as mountSort, K as fieldErrors, Kt as MountKind, L as materializeRouter, Lt as AssetKeyPair, M as getRequestStore, Mt as StartupStep, N as getRequestValue, Nt as StartupTimelineSnapshot, O as parseTraceparent, Ot as CheckMessage, P as requestStore, Pt as RoutePolicyTable, Q as VerifyOptions, Qt as MissingContributorError, R as FormErrorHandler, Rt as AssetKeyStrategy, S as ViewAdapter, St as MetricsOptions, T as TRACEPARENT_HEADER, Tt as CacheResponse, U as OLD_INPUT_KEY, Ut as DuplicateMountNameError, V as FLASH_KEY, Vt as groupAssetKeys, W as PREVIOUS_URL_KEY, Wt as MissingMountDepError, X as Signer, Xt as DuplicateContributorError, Y as SignedCheck, Yt as ContributorCycleError, Z as SignerOptions, Zt as MissingContextValueError, _ as HealthProbe, _t as CronAdapterOptions, a as ConfigDescription, an as KickError, at as verifyPassword, b as SpaAdapterOptions, bt as KickCronAdapter, c as MiddlewareEntry, ct as isClusterPrimary, dt as bootstrap, en as CircuitBreakerOptions, et as LegacyHasher, ft as ERROR_CHANNEL, g as HealthModuleConfig, gt as CRON_WORKER_ENV, h as HealthController, ht as RESPONSE_CHANNEL, i as ApplicationOptions, in as FormatKickErrorOptions, it as hashPassword, j as RequestStore, jt as defineCheck, k as traceContext, kt as StartupCheck, l as MountedRouteInfo, lt as KickHandler, m as HealthCheckResult, mt as HandlerTraceContext, n as AppStatus, nn as CircuitBreakerStats, nt as PasswordHashOptions, o as ConfigOrigins, on as KickErrorInit, ot as defineHttpContextDecorator, p as HEALTH_PROBE, pt as HANDLER_CHANNEL, q as flash, qt as MountSortItem, r as Application, rn as CircuitOpenError, rt as VerifyPasswordOptions, s as ManagementOptions, sn as formatKickError, st as ClusterOptions, t as APPLICATION, tn as CircuitBreakerState, tt as PasswordCheck, u as ServerOptions, ut as createHandler, v as healthModule, vt as CronSchedule, wt as metricsAdapter, xt as RAW_BODY, y as SpaAdapter, yt as CronScheduler, z as FormErrorHandlerOptions, zt as GroupAssetKeysOptions } from "./application-DsHdZoZK.mjs";
|
|
18
18
|
import { n as joinPaths, r as normalizePath, t as buildMountPath } from "./path-CMwIHsdv.mjs";
|
|
19
19
|
import { a as batch, c as reactive, d as toRefs, f as unref, i as WatchOptions, l as ref, n as Ref, o as computed, p as watch, r as RefOptions, s as isRef, t as ComputedRef, u as toRef } from "./reactivity-DZrc3Yhu.mjs";
|
|
20
20
|
import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData } from "./session-DQG72vCf.mjs";
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{o as KickError,s as formatKickError}from"./di-hooks-CdmCtJWu.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{i as isInjectionToken,n as createToken,r as ctn,t as INJECTION_TOKEN}from"./token-B3xWBu0S.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-s6adg8tp.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{i as defineModule,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-1SdTJZzK.mjs";import{i as reportResponse,r as reportError}from"./observers-Dn36QtbG.mjs";import{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs}from"./core/cron.mjs";import{a as NoJobHandlerError,c as listJobQueues,d as stampJobContext,i as Job,l as registerJobContext,n as JOB_DISPATCHER,o as Process,r as JOB_META,s as listJobHandlers,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-DxkFQkZG.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-tpEyEZ9s.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-Cwckim1c.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-uD7kn0hF.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-BNm2NUfA.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder--PLE0eDf.mjs";import{t as runContributors}from"./contributor-runner-BwBRcB65.mjs";import{_ as MountCycleError,a as HealthController,c as defineCheck,d as onPackage,f as ERROR_CHANNEL,g as MissingMountDepError,h as DuplicateMountNameError,i as HEALTH_PROBE,l as allOf,m as RESPONSE_CHANNEL,n as Application,o as healthModule,p as HANDLER_CHANNEL,s as StartupCheckError,t as APPLICATION,u as onEnv,v as mountSort}from"./application-dhmb3PMx.mjs";import{t as defineAdapter}from"./define-adapter-rcNang-q.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-CycYu5mR.mjs";import{n as randomHex,t as matchesBearer}from"./web-crypto-DnhQ8LCv.mjs";import{n as RAW_BODY}from"./body-policy-BK8PLFhR.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as viewRendererFor,c as settleBackgroundWork,d as getRequestValue,f as requestStore,l as waitUntil,n as bindViewRenderer,t as VIEW_RENDERER,u as getRequestStore}from"./view-renderer-Caqy9XY5.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware}from"./request-scope-BmUpBk1z.mjs";import{a as originsOf,i as loadSettings,n as defineSettings}from"./settings-Dn9iQ-BU.mjs";import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"./decorate-7rlBW7PY.mjs";import{a as reply,i as isRespondable,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-DDoHPeGF.mjs";import{a as materializeRouter,i as expressRuntime,n as buildRoutes}from"./express-lazy-DBLuSOgw.mjs";import{r as evaluatePreconditions,t as RequestContext}from"./context-Vy_DYHAM.mjs";import{r as stringifyJson}from"./runtime-OgMPp4md.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-Cm4Tv-uh.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-BukuyQDW.mjs";import{defaultValidationError,validate}from"./http/middleware/validate.mjs";import{csrf,csrfGuard,csrfToken}from"./http/middleware/csrf.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{breachPadding}from"./http/middleware/breach-padding.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-C4YUttef.mjs";import{session}from"./http/middleware/session.mjs";import{o as resolveMimeTypes}from"./upload-config-BrbOOmcm.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-CufiDd1o.mjs";import{createHmac,randomBytes,scrypt,timingSafeEqual}from"node:crypto";import{monitorEventLoopDelay}from"node:perf_hooks";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=/* @__PURE__ */ new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}const inFlight=/* @__PURE__ */ new Map,PERSONAL=[`authorization`,`proxy-authorization`,`x-api-key`,`cookie`];function CacheResponse(options){let maxAgeMs=options.maxAge*1e3,swrMs=(options.swr??0)*1e3,varies=(options.varies??[]).map(h=>h.toLowerCase());return(target,propertyKey,descriptor)=>{let original=descriptor.value,owner=typeof target==`function`?target.name:target.constructor?.name,prefix=typeof options.key==`string`?options.key:`kick:response:${owner??`anonymous`}.${String(propertyKey)}`,keyOf=typeof options.key==`function`?options.key:void 0;return descriptor.value=async function(ctx,...rest){let req=ctx.req,method=String(req.method??`GET`).toUpperCase(),headers=ctx.headers;if(method!==`GET`&&method!==`HEAD`||maxAgeMs+swrMs<=0)return original.call(this,ctx,...rest);let identity;if(keyOf){let chosen=keyOf(ctx);if(chosen===null)return original.call(this,ctx,...rest);identity=chosen}else{if(PERSONAL.some(h=>headers[h]!==void 0&&!varies.includes(h))||ctx.user!==void 0&&!varies.some(h=>PERSONAL.includes(h)))return original.call(this,ctx,...rest);let host=String(headers.host??``);if(!VALID_HOST.test(host))return original.call(this,ctx,...rest);identity=JSON.stringify([host.toLowerCase(),req.originalUrl??req.url??``])}let varied=varies.map(h=>`${h}=${String(headers[h]??``)}`).join(`&`),key=`${prefix}:${identity}|${varied}`,provider=getCacheProvider(),run=()=>record(original,this,ctx,rest),build=()=>buildOnce(key,run),store=async({recorded,shared})=>{if(!shared&&recorded&&cacheable(recorded)){let entry={recorded,storedAt:Date.now()};await provider.set(key,entry,maxAgeMs+swrMs)}},entry=await provider.get(key);if(entry){let age=Date.now()-entry.storedAt;if(age<maxAgeMs+swrMs){age>=maxAgeMs&&waitUntil(build().then(store)),replay(ctx,entry.recorded);return}}let built=await build();await store(built);let recorded=built.recorded;built.shared&&!(recorded&&cacheable(recorded))&&(recorded=await run()),recorded&&replay(ctx,recorded)},descriptor}}const VALID_HOST=/^(?:\[[0-9a-f:.]+\]|[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::\d{1,5})?$/i;async function buildOnce(key,run){let pending=inFlight.get(key);if(pending)return{recorded:await pending,shared:!0};let load=run().finally(()=>inFlight.delete(key));return inFlight.set(key,load),{recorded:await load,shared:!1}}function cacheable(recorded){return recorded.status===200&&!(`set-cookie`in recorded.headers)&&!recorded.native}async function record(handler,self,ctx,rest){let recorded={status:200,headers:{},body:``},sent=!1,finish=body=>{body instanceof Uint8Array?(recorded.body=toBase64(body),recorded.binary=!0):typeof body==`string`?recorded.body=body:body!=null&&(recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(body)),sent=!0},unsupported=what=>()=>{throw Error(`@CacheResponse: the handler called ${what}. A cached route answers with ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.`)},response={status(code){return recorded.status=code,response},type(contentType){return recorded.type=contentType,response},json(data){return recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(data),sent=!0,response},send(data){return finish(data),response},end(data){return finish(data),response},setHeader(name,value){recorded.headers[name.toLowerCase()]=Array.isArray(value)?[...value]:String(value)},get headersSent(){return sent},once(){},render:unsupported(`render()`),writeHead:unsupported(`writeHead()`),flushHeaders:unsupported(`flushHeaders()`),write:unsupported(`write()`)},native=new Proxy(ctx.res,{get(target,prop){let value=Reflect.get(target,prop,target);return typeof value==`function`?(...args)=>(recorded.native=!0,value.apply(target,args)):value},set(target,prop,value){return recorded.native=!0,Reflect.set(target,prop,value,target)}}),recordingCtx=Object.create(ctx,{_response:{value:response},res:{value:native}}),result=await handler.call(self,recordingCtx,...rest);return sent||await applyHandlerResult(recordingCtx,result),sent?recorded:null}function replay(ctx,recorded){if(ctx._response.headersSent)return;for(let[name,value]of Object.entries(recorded.headers))name!==`etag`&&name!==`content-type`&&ctx.setHeader(name,value);if(recorded.status===200){let etag=recorded.headers.etag??weakEtag(recorded.body);if(ctx.conditional({etag}))return}let options={status:recorded.status,type:recorded.type??`text/plain; charset=utf-8`};ctx.send(recorded.binary?fromBase64(recorded.body):recorded.body,options)}function weakEtag(body){let hash=2166136261;for(let i=0;i<body.length;i++)hash^=body.charCodeAt(i),hash=Math.imul(hash,16777619);return`W/"${body.length.toString(16)}-${(hash>>>0).toString(16)}"`}function toBase64(bytes){let binary=``;for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}function fromBase64(text){let binary=atob(text),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}const DEFAULT_BUCKETS=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],label=value=>value.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`
|
|
11
|
+
import{o as KickError,s as formatKickError}from"./di-hooks-CUVLbOER.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{i as isInjectionToken,n as createToken,r as ctn,t as INJECTION_TOKEN}from"./token-CbeBj1AB.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-__BH2A1m.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{i as defineModule,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-B3mtX1t0.mjs";import{i as reportResponse,r as reportError}from"./observers-D3m1iUQw.mjs";import{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs}from"./core/cron.mjs";import{a as NoJobHandlerError,c as listJobQueues,d as stampJobContext,i as Job,l as registerJobContext,n as JOB_DISPATCHER,o as Process,r as JOB_META,s as listJobHandlers,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-8qPs4uhb.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-DzxupKRg.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-qXRvhsbB.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-DBoFrkOu.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-CWTD0Fln.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-DIBhQIki.mjs";import{t as runContributors}from"./contributor-runner-BlYFb9WU.mjs";import{_ as MountCycleError,a as HealthController,c as defineCheck,d as onPackage,f as ERROR_CHANNEL,g as MissingMountDepError,h as DuplicateMountNameError,i as HEALTH_PROBE,l as allOf,m as RESPONSE_CHANNEL,n as Application,o as healthModule,p as HANDLER_CHANNEL,s as StartupCheckError,t as APPLICATION,u as onEnv,v as mountSort}from"./application-1Fzmk_Ku.mjs";import{t as defineAdapter}from"./define-adapter-C4ATXXqb.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-Dd12HOZr.mjs";import{n as randomHex,t as matchesBearer}from"./web-crypto-Up4UvHoI.mjs";import{n as RAW_BODY}from"./body-policy-BQnyy906.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as viewRendererFor,c as settleBackgroundWork,d as getRequestValue,f as requestStore,l as waitUntil,n as bindViewRenderer,t as VIEW_RENDERER,u as getRequestStore}from"./view-renderer-BLYp4qoe.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware}from"./request-scope-CN4JvYti.mjs";import{a as originsOf,i as loadSettings,n as defineSettings}from"./settings-DqVmZr-S.mjs";import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"./decorate-BFKqRpjy.mjs";import{a as reply,i as isRespondable,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-Dr88jBEF.mjs";import{a as materializeRouter,i as expressRuntime,n as buildRoutes}from"./express-lazy-7Ldw2LAF.mjs";import{r as evaluatePreconditions,t as RequestContext}from"./context-ByBa7pR4.mjs";import{r as stringifyJson}from"./runtime-pz_XLMOf.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-Ub6N0nVd.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-D8Jbrl5C.mjs";import{defaultValidationError,validate}from"./http/middleware/validate.mjs";import{csrf,csrfGuard,csrfToken}from"./http/middleware/csrf.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{breachPadding}from"./http/middleware/breach-padding.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-u9frHRUO.mjs";import{session}from"./http/middleware/session.mjs";import{o as resolveMimeTypes}from"./upload-config-tyBCdMVF.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-Df8GxPDC.mjs";import{createHmac,randomBytes,scrypt,timingSafeEqual}from"node:crypto";import{monitorEventLoopDelay}from"node:perf_hooks";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=/* @__PURE__ */ new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}const inFlight=/* @__PURE__ */ new Map,PERSONAL=[`authorization`,`proxy-authorization`,`x-api-key`,`cookie`];function CacheResponse(options){let maxAgeMs=options.maxAge*1e3,swrMs=(options.swr??0)*1e3,varies=(options.varies??[]).map(h=>h.toLowerCase());return(target,propertyKey,descriptor)=>{let original=descriptor.value,owner=typeof target==`function`?target.name:target.constructor?.name,prefix=typeof options.key==`string`?options.key:`kick:response:${owner??`anonymous`}.${String(propertyKey)}`,keyOf=typeof options.key==`function`?options.key:void 0;return descriptor.value=async function(ctx,...rest){let req=ctx.req,method=String(req.method??`GET`).toUpperCase(),headers=ctx.headers;if(method!==`GET`&&method!==`HEAD`||maxAgeMs+swrMs<=0)return original.call(this,ctx,...rest);let identity;if(keyOf){let chosen=keyOf(ctx);if(chosen===null)return original.call(this,ctx,...rest);identity=chosen}else{if(PERSONAL.some(h=>headers[h]!==void 0&&!varies.includes(h))||ctx.user!==void 0&&!varies.some(h=>PERSONAL.includes(h)))return original.call(this,ctx,...rest);let host=String(headers.host??``);if(!VALID_HOST.test(host))return original.call(this,ctx,...rest);identity=JSON.stringify([host.toLowerCase(),req.originalUrl??req.url??``])}let varied=varies.map(h=>`${h}=${String(headers[h]??``)}`).join(`&`),key=`${prefix}:${identity}|${varied}`,provider=getCacheProvider(),run=()=>record(original,this,ctx,rest),build=()=>buildOnce(key,run),store=async({recorded,shared})=>{if(!shared&&recorded&&cacheable(recorded)){let entry={recorded,storedAt:Date.now()};await provider.set(key,entry,maxAgeMs+swrMs)}},entry=await provider.get(key);if(entry){let age=Date.now()-entry.storedAt;if(age<maxAgeMs+swrMs){age>=maxAgeMs&&waitUntil(build().then(store)),replay(ctx,entry.recorded);return}}let built=await build();await store(built);let recorded=built.recorded;built.shared&&!(recorded&&cacheable(recorded))&&(recorded=await run()),recorded&&replay(ctx,recorded)},descriptor}}const VALID_HOST=/^(?:\[[0-9a-f:.]+\]|[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::\d{1,5})?$/i;async function buildOnce(key,run){let pending=inFlight.get(key);if(pending)return{recorded:await pending,shared:!0};let load=run().finally(()=>inFlight.delete(key));return inFlight.set(key,load),{recorded:await load,shared:!1}}function cacheable(recorded){return recorded.status===200&&!(`set-cookie`in recorded.headers)&&!recorded.native}async function record(handler,self,ctx,rest){let recorded={status:200,headers:{},body:``},sent=!1,finish=body=>{body instanceof Uint8Array?(recorded.body=toBase64(body),recorded.binary=!0):typeof body==`string`?recorded.body=body:body!=null&&(recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(body)),sent=!0},unsupported=what=>()=>{throw Error(`@CacheResponse: the handler called ${what}. A cached route answers with ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.`)},response={status(code){return recorded.status=code,response},type(contentType){return recorded.type=contentType,response},json(data){return recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(data),sent=!0,response},send(data){return finish(data),response},end(data){return finish(data),response},setHeader(name,value){recorded.headers[name.toLowerCase()]=Array.isArray(value)?[...value]:String(value)},get headersSent(){return sent},once(){},render:unsupported(`render()`),writeHead:unsupported(`writeHead()`),flushHeaders:unsupported(`flushHeaders()`),write:unsupported(`write()`)},native=new Proxy(ctx.res,{get(target,prop){let value=Reflect.get(target,prop,target);return typeof value==`function`?(...args)=>(recorded.native=!0,value.apply(target,args)):value},set(target,prop,value){return recorded.native=!0,Reflect.set(target,prop,value,target)}}),recordingCtx=Object.create(ctx,{_response:{value:response},res:{value:native}}),result=await handler.call(self,recordingCtx,...rest);return sent||await applyHandlerResult(recordingCtx,result),sent?recorded:null}function replay(ctx,recorded){if(ctx._response.headersSent)return;for(let[name,value]of Object.entries(recorded.headers))name!==`etag`&&name!==`content-type`&&ctx.setHeader(name,value);if(recorded.status===200){let etag=recorded.headers.etag??weakEtag(recorded.body);if(ctx.conditional({etag}))return}let options={status:recorded.status,type:recorded.type??`text/plain; charset=utf-8`};ctx.send(recorded.binary?fromBase64(recorded.body):recorded.body,options)}function weakEtag(body){let hash=2166136261;for(let i=0;i<body.length;i++)hash^=body.charCodeAt(i),hash=Math.imul(hash,16777619);return`W/"${body.length.toString(16)}-${(hash>>>0).toString(16)}"`}function toBase64(bytes){let binary=``;for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}function fromBase64(text){let binary=atob(text),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}const DEFAULT_BUCKETS=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],label=value=>value.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`
|
|
12
12
|
`,`\\n`);var RequestHistogram=class{series=/* @__PURE__ */ new Map;buckets;constructor(buckets=DEFAULT_BUCKETS){if(buckets.length===0||buckets.some(b=>!Number.isFinite(b)||b<=0))throw Error(`metrics: buckets must be finite positive numbers (seconds)`);this.buckets=[...new Set(buckets)].toSorted((a,b)=>a-b)}observe(info){let labels=`method="${label(knownMethod(info.method))}",route="${label(info.route??`unmatched`)}",status="${info.status}"`,series=this.series.get(labels);series||(series={labels,counts:this.buckets.map(()=>0),sum:0,count:0},this.series.set(labels,series));let seconds=info.durationMs/1e3;for(let[i,bound]of this.buckets.entries())seconds<=bound&&series.counts[i]++;series.sum+=seconds,series.count++}render(){let name=`http_request_duration_seconds`,lines=[`# HELP ${name} Time to answer an HTTP request, by route pattern.`,`# TYPE ${name} histogram`];for(let s of this.series.values()){for(let[i,bound]of this.buckets.entries())lines.push(`${name}_bucket{${s.labels},le="${bound}"} ${s.counts[i]}`);lines.push(`${name}_bucket{${s.labels},le="+Inf"} ${s.count}`),lines.push(`${name}_sum{${s.labels}} ${s.sum}`),lines.push(`${name}_count{${s.labels}} ${s.count}`)}return lines.join(`
|
|
13
13
|
`)}};const METHODS=/* @__PURE__ */ new Set([`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`,`QUERY`]);function knownMethod(method){let upper=method.toUpperCase();return METHODS.has(upper)?upper:`OTHER`}function gauge(name,help,value){return`# HELP ${name} ${help}\n# TYPE ${name} gauge\n${name} ${value}`}function metricsAdapter(options={}){let path=options.path??`/metrics`,histogram=new RequestHistogram(options.buckets??DEFAULT_BUCKETS),loop,render=()=>{let memory=process.memoryUsage(),lag=loop&&loop.count>0?loop.mean/1e9:0;return[histogram.render(),gauge(`process_resident_memory_bytes`,`Resident set size.`,memory.rss),gauge(`nodejs_heap_used_bytes`,`V8 heap in use.`,memory.heapUsed),gauge(`nodejs_heap_total_bytes`,`V8 heap allocated.`,memory.heapTotal),gauge(`nodejs_eventloop_lag_seconds`,`Mean event-loop delay since the last scrape.`,lag),gauge(`process_uptime_seconds`,`Seconds since the process started.`,process.uptime())].join(`
|
|
14
14
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function isProduction(){let env=typeof process<`u`?process.env?.NODE_ENV:void 0;return env!==`development`&&env!==`test`}export{isProduction as t};
|
|
12
|
-
//# sourceMappingURL=is-production-
|
|
12
|
+
//# sourceMappingURL=is-production-Bmoi-4LP.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"is-production-
|
|
1
|
+
{"version":3,"file":"is-production-Bmoi-4LP.mjs","names":[],"sources":["../src/core/is-production.ts"],"sourcesContent":["/**\n * Whether the process should behave as production — true unless `NODE_ENV`\n * is exactly `development` or `test`. Fails closed: an unset (or any other)\n * `NODE_ENV` counts as production, so a deploy that forgets to set it still\n * gets secure cookies, opaque 500s and no dev-only aids.\n *\n * Read per call, not at module scope — tests and late config may set\n * `NODE_ENV` after import — and guarded, since edge runtimes may not expose\n * `process`. Reads `process.env` rather than `getEnv()`: the framework must\n * not depend on the app's env schema (or on zod) to decide this.\n */\nexport function isProduction(): boolean {\n const env = typeof process !== 'undefined' ? process.env?.NODE_ENV : undefined\n return env !== 'development' && env !== 'test'\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgB,cAAwB,CACtC,IAAM,IAAM,OAAO,QAAY,IAAc,QAAQ,KAAK,SAAW,IAAA,GACrE,OAAO,MAAQ,eAAiB,MAAQ,MAC1C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"./core/logger.mjs";import{n as createToken}from"./token-
|
|
12
|
-
//# sourceMappingURL=jobs-
|
|
11
|
+
import{createLogger}from"./core/logger.mjs";import{n as createToken}from"./token-CbeBj1AB.mjs";import{c as pushClassMeta,n as getClassMetaOrUndefined,t as getClassMeta,u as setClassMeta}from"./metadata-__BH2A1m.mjs";import{Service}from"./core/decorators.mjs";import{r as reportError}from"./observers-D3m1iUQw.mjs";const log=createLogger(`KickJobs`),JOB_META={JOB:`kick/queue/job`,PROCESS:`kick/queue/process`},jobClasses=/* @__PURE__ */ new Map;function Job(queue){return target=>{Service()(target),setClassMeta(JOB_META.JOB,queue,target),jobClasses.set(target.name,target)}}function Process(jobName){return(target,propertyKey)=>{pushClassMeta(JOB_META.PROCESS,target.constructor,{handlerName:propertyKey,jobName})}}function listJobHandlers(container){let handlers=[];for(let target of jobClasses.values()){if(!container.has(target))continue;let queue=getClassMetaOrUndefined(JOB_META.JOB,target);if(queue===void 0)continue;let processes=getClassMeta(JOB_META.PROCESS,target,[]);processes.length===0&&log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`);for(let process of processes)handlers.push({...process,queue,target})}return handlers}function listJobQueues(container){return[...new Set(listJobHandlers(container).map(h=>h.queue))]}var NoJobHandlerError=class extends Error{queue;jobName;constructor(queue,jobName){super(`No @Process handler for job "${jobName}" on queue "${queue}"`),this.queue=queue,this.jobName=jobName,this.name=`NoJobHandlerError`}};async function runJob(container,queue,job,report={}){let handlers=listJobHandlers(container).filter(h=>h.queue===queue),handler=handlers.find(h=>h.jobName===job.name)??handlers.find(h=>h.jobName===void 0);try{if(!handler)throw new NoJobHandlerError(queue,job.name);let instance=container.resolve(handler.target);return await withJobContext(job,()=>instance[handler.handlerName](job))()}catch(err){throw log.error({err},`Job ${queue}/${job.name} failed`),reportError(err,{source:`job`,context:{queue,job:job.name,id:job.id,...report}}),err}}const JOB_CONTEXT_FIELD=`__kickContext`,jobContextCarriers=/* @__PURE__ */ new Map;function registerJobContext(carrier){jobContextCarriers.set(carrier.key,carrier)}const isPlainObject=v=>!!v&&typeof v==`object`&&Object.getPrototypeOf(v)===Object.prototype;function stampJobContext(data){if(!isPlainObject(data))return data;let{[JOB_CONTEXT_FIELD]:_untrusted,...rest}=data,context={};for(let[key,carrier]of jobContextCarriers){let value=carrier.capture();value!==void 0&&(context[key]=value)}return Object.keys(context).length>0?{...rest,[JOB_CONTEXT_FIELD]:context}:rest}function withJobContext(job,run){let data=job.data;if(!isPlainObject(data)||!(`__kickContext`in data))return run;let context=data[JOB_CONTEXT_FIELD];if(delete data[JOB_CONTEXT_FIELD],!isPlainObject(context))return run;let wrapped=run;for(let[key,value]of Object.entries(context)){let carrier=jobContextCarriers.get(key);if(!carrier)continue;let inner=wrapped;wrapped=()=>carrier.restore(value,inner)}return wrapped}const JOB_DISPATCHER=createToken(`kick/jobs/Dispatcher`);export{NoJobHandlerError as a,listJobQueues as c,stampJobContext as d,Job as i,registerJobContext as l,JOB_DISPATCHER as n,Process as o,JOB_META as r,listJobHandlers as s,JOB_CONTEXT_FIELD as t,runJob as u};
|
|
12
|
+
//# sourceMappingURL=jobs-8qPs4uhb.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jobs-DxkFQkZG.mjs","names":[],"sources":["../src/core/jobs.ts"],"sourcesContent":["/**\n * Background jobs, with whatever runs them.\n *\n * `@Job(queue)` / `@Process(name)` only record which method handles which\n * job — the same way `@Cron` only records a schedule. Any job tool turns that\n * into running code in a few lines: subscribe to each queue from\n * {@link listJobQueues}, and hand every job it receives to {@link runJob}.\n *\n * @Job('email')\n * export class EmailJobs {\n * @Process('welcome')\n * async welcome(job: JobLike<{ to: string }>) { await sendWelcome(job.data.to) }\n * }\n *\n * Enqueueing goes through {@link JOB_DISPATCHER}, which the active adapter\n * provides — code that dispatches never names the tool.\n *\n * `@forinda/kickjs-queue` ships a BullMQ adapter (plus RabbitMQ / Kafka /\n * Redis pub-sub providers); the web entry's `queue()` runs Cloudflare Queues.\n */\nimport { Service } from './decorators'\nimport { getClassMeta, getClassMetaOrUndefined, pushClassMeta, setClassMeta } from './metadata'\nimport { reportError } from './observers'\nimport { createLogger } from './logger'\nimport { createToken } from './token'\n\nconst log = createLogger('KickJobs')\n\n/** Metadata keys — the same ones `@forinda/kickjs-queue` used, so existing readers keep working. */\nexport const JOB_META = {\n JOB: 'kick/queue/job',\n PROCESS: 'kick/queue/process',\n} as const\n\n/** What a `@Process` method records. */\nexport interface ProcessDefinition {\n /** Method name on the class. */\n handlerName: string\n /** Job name it handles; `undefined` handles every job in the queue. */\n jobName?: string\n}\n\n/**\n * The least a job tool hands over. Runners pass their own job object through\n * unchanged — BullMQ's `Job`, a Cloudflare message — so a handler can still\n * reach tool-specific fields (`job.attemptsMade`, `job.updateProgress()`).\n */\nexport interface JobLike<Data = unknown> {\n name: string\n data: Data\n id?: string\n}\n\n/**\n * Every `@Job` class, keyed by class name like the DI registry: an HMR\n * re-evaluation replaces the old class instead of leaving both subscribed.\n */\nconst jobClasses = new Map<string, Function>()\n\n/** Mark a class as handling jobs on `queue`. The class is a DI singleton. */\nexport function Job(queue: string): ClassDecorator {\n return (target) => {\n Service()(target)\n setClassMeta(JOB_META.JOB, queue, target)\n jobClasses.set(target.name, target)\n }\n}\n\n/** Mark a method as handling `jobName` — or, without a name, every job its queue gets. */\nexport function Process(jobName?: string): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<ProcessDefinition>(JOB_META.PROCESS, target.constructor, {\n handlerName: propertyKey as string,\n jobName,\n })\n }\n}\n\n/** One handler: its queue, job name (absent for a catch-all), class and method. */\nexport interface JobHandler extends ProcessDefinition {\n queue: string\n target: Function\n}\n\n/**\n * Every `@Process` method of a `@Job` class the container can resolve.\n * Classes it doesn't know (not in a module, or from before an HMR reload)\n * are skipped.\n */\nexport function listJobHandlers(container: { has(token: unknown): boolean }): JobHandler[] {\n const handlers: JobHandler[] = []\n for (const target of jobClasses.values()) {\n if (!container.has(target)) continue\n const queue = getClassMetaOrUndefined<string>(JOB_META.JOB, target)\n if (queue === undefined) continue\n const processes = getClassMeta<ProcessDefinition[]>(JOB_META.PROCESS, target, [])\n if (processes.length === 0) {\n log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`)\n }\n for (const process of processes) handlers.push({ ...process, queue, target })\n }\n return handlers\n}\n\n/** The queues something handles — what a runner subscribes to. */\nexport function listJobQueues(container: { has(token: unknown): boolean }): string[] {\n return [...new Set(listJobHandlers(container).map((h) => h.queue))]\n}\n\n/** Thrown when a queue receives a job no `@Process` method handles. */\nexport class NoJobHandlerError extends Error {\n constructor(\n readonly queue: string,\n readonly jobName: string,\n ) {\n super(`No @Process handler for job \"${jobName}\" on queue \"${queue}\"`)\n this.name = 'NoJobHandlerError'\n }\n}\n\n/**\n * Run one job: pick the `@Process` method for `job.name` (or the queue's\n * catch-all), resolve its class from the container and call it with `job`\n * as given. A failure is reported to the error observers (`source: 'job'`)\n * and rethrown, so the tool's own retry and dead-letter handling still\n * applies. A job nothing handles throws {@link NoJobHandlerError} rather\n * than being acknowledged and lost.\n */\nexport async function runJob(\n container: { has(token: unknown): boolean; resolve(token: unknown): unknown },\n queue: string,\n job: JobLike,\n /** Extra fields for the error report — e.g. the tool's attempt count. */\n report: Record<string, unknown> = {},\n): Promise<unknown> {\n const handlers = listJobHandlers(container).filter((h) => h.queue === queue)\n const handler =\n handlers.find((h) => h.jobName === job.name) ?? handlers.find((h) => h.jobName === undefined)\n try {\n if (!handler) throw new NoJobHandlerError(queue, job.name)\n const instance = container.resolve(handler.target) as Record<string, (j: JobLike) => unknown>\n return await withJobContext(job, () => instance[handler.handlerName]!(job))()\n } catch (err) {\n log.error({ err }, `Job ${queue}/${job.name} failed`)\n reportError(err, { source: 'job', context: { queue, job: job.name, id: job.id, ...report } })\n throw err\n }\n}\n\n/**\n * Something about where a job was dispatched from that its handler should\n * run with — the tenant, a trace id, the acting user. Captured when the job\n * is dispatched, carried in its data, and restored around the handler.\n */\nexport interface JobContextCarrier<T = unknown> {\n /** Unique: the field it travels under. */\n key: string\n /** The value to carry, or `undefined` for nothing. */\n capture(): T | undefined\n /** Run the handler with the value back in place. */\n restore<R>(value: T, run: () => R): R\n}\n\n/** The field a job's data carries its context in. Removed before the handler sees the data. */\nexport const JOB_CONTEXT_FIELD = '__kickContext'\n\nconst jobContextCarriers = new Map<string, JobContextCarrier>()\n\n/** Carry a value from dispatch to handler for every job. Registering a key again replaces it. */\nexport function registerJobContext<T>(carrier: JobContextCarrier<T>): void {\n jobContextCarriers.set(carrier.key, carrier as JobContextCarrier)\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype\n\n/**\n * `data` with the current job context added — for a {@link JobDispatcher}\n * implementation to call before enqueueing. Any `__kickContext` already in\n * `data` is removed first: only this call may set it, so a dispatcher that\n * enqueues caller-supplied data without it lets that data choose the context. Only plain-object data can carry\n * it; anything else, or nothing to carry, is returned as is.\n */\nexport function stampJobContext<Data>(data: Data): Data {\n if (!isPlainObject(data)) return data\n // Only the dispatcher's own context travels. A caller's data (a request\n // body, say) carrying the field would otherwise pick the job's tenant.\n const { [JOB_CONTEXT_FIELD]: _untrusted, ...rest } = data\n const context: Record<string, unknown> = {}\n for (const [key, carrier] of jobContextCarriers) {\n const value = carrier.capture()\n if (value !== undefined) context[key] = value\n }\n const stamped = Object.keys(context).length > 0 ? { ...rest, [JOB_CONTEXT_FIELD]: context } : rest\n return stamped as Data\n}\n\n/** Take the carried context off the job's data, and wrap `run` in every restore. */\nfunction withJobContext<R>(job: JobLike, run: () => R): () => R {\n const data = job.data\n if (!isPlainObject(data) || !(JOB_CONTEXT_FIELD in data)) return run\n const context = data[JOB_CONTEXT_FIELD]\n delete data[JOB_CONTEXT_FIELD]\n // Only an object of carrier keys is context; anything else is dropped.\n if (!isPlainObject(context)) return run\n let wrapped = run\n for (const [key, value] of Object.entries(context)) {\n const carrier = jobContextCarriers.get(key)\n if (!carrier) continue\n const inner = wrapped\n wrapped = () => carrier.restore(value, inner)\n }\n return wrapped\n}\n\n/** Enqueue a job — implemented by whichever adapter runs the jobs. */\nexport interface JobDispatcher {\n dispatch<Data = unknown>(\n queue: string,\n name: string,\n data: Data,\n options?: Record<string, unknown>,\n ): Promise<unknown>\n}\n\n/**\n * The active job dispatcher. Inject it to enqueue without naming the tool:\n * `@Inject(JOB_DISPATCHER) private jobs!: JobDispatcher`.\n */\nexport const JOB_DISPATCHER = createToken<JobDispatcher>('kick/j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KAAO,IAAI,KACjB,GAAI,CAAC,cAAc,IAAI,GAAK,EAAA,kBAAuB,MAAO,OAAO,IACjE,IAAM,QAAU,KAAK,mBAGrB,GAFA,OAAO,KAAK,mBAER,CAAC,cAAc,OAAO,EAAG,OAAO,IACpC,IAAI,QAAU,IACd,IAAK,GAAM,CAAC,IAAK,SAAU,OAAO,QAAQ,OAAO,EAAG,CAClD,IAAM,QAAU,mBAAmB,IAAI,GAAG,EAC1C,GAAI,CAAC,QAAS,SACd,IAAM,MAAQ,QACd,YAAgB,QAAQ,QAAQ,MAAO,KAAK,CAC9C,CACA,OAAO,OACT,CAgBA,MAAa,eAAiB,YAA2B,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"jobs-8qPs4uhb.mjs","names":[],"sources":["../src/core/jobs.ts"],"sourcesContent":["/**\n * Background jobs, with whatever runs them.\n *\n * `@Job(queue)` / `@Process(name)` only record which method handles which\n * job — the same way `@Cron` only records a schedule. Any job tool turns that\n * into running code in a few lines: subscribe to each queue from\n * {@link listJobQueues}, and hand every job it receives to {@link runJob}.\n *\n * @Job('email')\n * export class EmailJobs {\n * @Process('welcome')\n * async welcome(job: JobLike<{ to: string }>) { await sendWelcome(job.data.to) }\n * }\n *\n * Enqueueing goes through {@link JOB_DISPATCHER}, which the active adapter\n * provides — code that dispatches never names the tool.\n *\n * `@forinda/kickjs-queue` ships a BullMQ adapter (plus RabbitMQ / Kafka /\n * Redis pub-sub providers); the web entry's `queue()` runs Cloudflare Queues.\n */\nimport { Service } from './decorators'\nimport { getClassMeta, getClassMetaOrUndefined, pushClassMeta, setClassMeta } from './metadata'\nimport { reportError } from './observers'\nimport { createLogger } from './logger'\nimport { createToken } from './token'\n\nconst log = createLogger('KickJobs')\n\n/** Metadata keys — the same ones `@forinda/kickjs-queue` used, so existing readers keep working. */\nexport const JOB_META = {\n JOB: 'kick/queue/job',\n PROCESS: 'kick/queue/process',\n} as const\n\n/** What a `@Process` method records. */\nexport interface ProcessDefinition {\n /** Method name on the class. */\n handlerName: string\n /** Job name it handles; `undefined` handles every job in the queue. */\n jobName?: string\n}\n\n/**\n * The least a job tool hands over. Runners pass their own job object through\n * unchanged — BullMQ's `Job`, a Cloudflare message — so a handler can still\n * reach tool-specific fields (`job.attemptsMade`, `job.updateProgress()`).\n */\nexport interface JobLike<Data = unknown> {\n name: string\n data: Data\n id?: string\n}\n\n/**\n * Every `@Job` class, keyed by class name like the DI registry: an HMR\n * re-evaluation replaces the old class instead of leaving both subscribed.\n */\nconst jobClasses = new Map<string, Function>()\n\n/** Mark a class as handling jobs on `queue`. The class is a DI singleton. */\nexport function Job(queue: string): ClassDecorator {\n return (target) => {\n Service()(target)\n setClassMeta(JOB_META.JOB, queue, target)\n jobClasses.set(target.name, target)\n }\n}\n\n/** Mark a method as handling `jobName` — or, without a name, every job its queue gets. */\nexport function Process(jobName?: string): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<ProcessDefinition>(JOB_META.PROCESS, target.constructor, {\n handlerName: propertyKey as string,\n jobName,\n })\n }\n}\n\n/** One handler: its queue, job name (absent for a catch-all), class and method. */\nexport interface JobHandler extends ProcessDefinition {\n queue: string\n target: Function\n}\n\n/**\n * Every `@Process` method of a `@Job` class the container can resolve.\n * Classes it doesn't know (not in a module, or from before an HMR reload)\n * are skipped.\n */\nexport function listJobHandlers(container: { has(token: unknown): boolean }): JobHandler[] {\n const handlers: JobHandler[] = []\n for (const target of jobClasses.values()) {\n if (!container.has(target)) continue\n const queue = getClassMetaOrUndefined<string>(JOB_META.JOB, target)\n if (queue === undefined) continue\n const processes = getClassMeta<ProcessDefinition[]>(JOB_META.PROCESS, target, [])\n if (processes.length === 0) {\n log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`)\n }\n for (const process of processes) handlers.push({ ...process, queue, target })\n }\n return handlers\n}\n\n/** The queues something handles — what a runner subscribes to. */\nexport function listJobQueues(container: { has(token: unknown): boolean }): string[] {\n return [...new Set(listJobHandlers(container).map((h) => h.queue))]\n}\n\n/** Thrown when a queue receives a job no `@Process` method handles. */\nexport class NoJobHandlerError extends Error {\n constructor(\n readonly queue: string,\n readonly jobName: string,\n ) {\n super(`No @Process handler for job \"${jobName}\" on queue \"${queue}\"`)\n this.name = 'NoJobHandlerError'\n }\n}\n\n/**\n * Run one job: pick the `@Process` method for `job.name` (or the queue's\n * catch-all), resolve its class from the container and call it with `job`\n * as given. A failure is reported to the error observers (`source: 'job'`)\n * and rethrown, so the tool's own retry and dead-letter handling still\n * applies. A job nothing handles throws {@link NoJobHandlerError} rather\n * than being acknowledged and lost.\n */\nexport async function runJob(\n container: { has(token: unknown): boolean; resolve(token: unknown): unknown },\n queue: string,\n job: JobLike,\n /** Extra fields for the error report — e.g. the tool's attempt count. */\n report: Record<string, unknown> = {},\n): Promise<unknown> {\n const handlers = listJobHandlers(container).filter((h) => h.queue === queue)\n const handler =\n handlers.find((h) => h.jobName === job.name) ?? handlers.find((h) => h.jobName === undefined)\n try {\n if (!handler) throw new NoJobHandlerError(queue, job.name)\n const instance = container.resolve(handler.target) as Record<string, (j: JobLike) => unknown>\n return await withJobContext(job, () => instance[handler.handlerName]!(job))()\n } catch (err) {\n log.error({ err }, `Job ${queue}/${job.name} failed`)\n reportError(err, { source: 'job', context: { queue, job: job.name, id: job.id, ...report } })\n throw err\n }\n}\n\n/**\n * Something about where a job was dispatched from that its handler should\n * run with — the tenant, a trace id, the acting user. Captured when the job\n * is dispatched, carried in its data, and restored around the handler.\n */\nexport interface JobContextCarrier<T = unknown> {\n /** Unique: the field it travels under. */\n key: string\n /** The value to carry, or `undefined` for nothing. */\n capture(): T | undefined\n /** Run the handler with the value back in place. */\n restore<R>(value: T, run: () => R): R\n}\n\n/** The field a job's data carries its context in. Removed before the handler sees the data. */\nexport const JOB_CONTEXT_FIELD = '__kickContext'\n\nconst jobContextCarriers = new Map<string, JobContextCarrier>()\n\n/** Carry a value from dispatch to handler for every job. Registering a key again replaces it. */\nexport function registerJobContext<T>(carrier: JobContextCarrier<T>): void {\n jobContextCarriers.set(carrier.key, carrier as JobContextCarrier)\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype\n\n/**\n * `data` with the current job context added — for a {@link JobDispatcher}\n * implementation to call before enqueueing. Any `__kickContext` already in\n * `data` is removed first: only this call may set it, so a dispatcher that\n * enqueues caller-supplied data without it lets that data choose the context. Only plain-object data can carry\n * it; anything else, or nothing to carry, is returned as is.\n */\nexport function stampJobContext<Data>(data: Data): Data {\n if (!isPlainObject(data)) return data\n // Only the dispatcher's own context travels. A caller's data (a request\n // body, say) carrying the field would otherwise pick the job's tenant.\n const { [JOB_CONTEXT_FIELD]: _untrusted, ...rest } = data\n const context: Record<string, unknown> = {}\n for (const [key, carrier] of jobContextCarriers) {\n const value = carrier.capture()\n if (value !== undefined) context[key] = value\n }\n const stamped = Object.keys(context).length > 0 ? { ...rest, [JOB_CONTEXT_FIELD]: context } : rest\n return stamped as Data\n}\n\n/** Take the carried context off the job's data, and wrap `run` in every restore. */\nfunction withJobContext<R>(job: JobLike, run: () => R): () => R {\n const data = job.data\n if (!isPlainObject(data) || !(JOB_CONTEXT_FIELD in data)) return run\n const context = data[JOB_CONTEXT_FIELD]\n delete data[JOB_CONTEXT_FIELD]\n // Only an object of carrier keys is context; anything else is dropped.\n if (!isPlainObject(context)) return run\n let wrapped = run\n for (const [key, value] of Object.entries(context)) {\n const carrier = jobContextCarriers.get(key)\n if (!carrier) continue\n const inner = wrapped\n wrapped = () => carrier.restore(value, inner)\n }\n return wrapped\n}\n\n/** Enqueue a job — implemented by whichever adapter runs the jobs. */\nexport interface JobDispatcher {\n dispatch<Data = unknown>(\n queue: string,\n name: string,\n data: Data,\n options?: Record<string, unknown>,\n ): Promise<unknown>\n}\n\n/**\n * The active job dispatcher. Inject it to enqueue without naming the tool:\n * `@Inject(JOB_DISPATCHER) private jobs!: JobDispatcher`.\n */\nexport const JOB_DISPATCHER = createToken<JobDispatcher>('kick/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,KAAO,IAAI,KACjB,GAAI,CAAC,cAAc,IAAI,GAAK,EAAA,kBAAuB,MAAO,OAAO,IACjE,IAAM,QAAU,KAAK,mBAGrB,GAFA,OAAO,KAAK,mBAER,CAAC,cAAc,OAAO,EAAG,OAAO,IACpC,IAAI,QAAU,IACd,IAAK,GAAM,CAAC,IAAK,SAAU,OAAO,QAAQ,OAAO,EAAG,CAClD,IAAM,QAAU,mBAAmB,IAAI,GAAG,EAC1C,GAAI,CAAC,QAAS,SACd,IAAM,MAAQ,QACd,YAAgB,QAAQ,QAAQ,MAAO,KAAK,CAC9C,CACA,OAAO,OACT,CAgBA,MAAa,eAAiB,YAA2B,sBAAsB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{n as assertFlagTest,s as matchesFlagTest}from"./route-flag-
|
|
12
|
-
//# sourceMappingURL=kv-stores-
|
|
11
|
+
import{n as assertFlagTest,s as matchesFlagTest}from"./route-flag-qXRvhsbB.mjs";import{t as BoundedCounters}from"./bounded-counters-BaQwi0aH.mjs";var LazyMemoryStore=class{counters;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit)}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function defaultKey(ctx){return ctx.ip??`global`}function rateLimitGuard(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??defaultKey,sendHeaders=options.headers??!0,store=options.store??new LazyMemoryStore(windowMs,max),exemptWhen=options.exemptWhen;return exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimitGuard({ exemptWhen })`),async(ctx,next)=>{if(options.skip?.(ctx)||exemptWhen!==void 0&&matchesFlagTest(exemptWhen,ctx.route?.flags,ctx.route))return next();let{totalHits,resetTime}=await store.increment(keyGenerator(ctx)),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(ctx.setHeader(`X-RateLimit-Limit`,String(max)),ctx.setHeader(`X-RateLimit-Remaining`,String(remaining)),ctx.setHeader(`X-RateLimit-Reset`,String(Math.ceil(resetTime.getTime()/1e3)))),totalHits>max){let retryAfter=Math.max(1,Math.ceil((resetTime.getTime()-Date.now())/1e3));sendHeaders&&ctx.setHeader(`Retry-After`,String(retryAfter)),ctx.json({message},statusCode)}else next()}}function kvTtlSeconds(ms){return Math.max(60,Math.ceil(ms/1e3))}var KvRateLimitStore=class{kv;prefix;windowMs;constructor(kv,options){this.kv=kv,this.windowMs=options.windowMs,this.prefix=options.prefix??`rl:`}async increment(key){let now=Date.now(),entry=await this.read(key);if(entry&&entry.reset>now)return entry.hits++,await this.write(key,entry),{totalHits:entry.hits,resetTime:new Date(entry.reset)};let fresh={hits:1,reset:now+this.windowMs};return await this.write(key,fresh),{totalHits:1,resetTime:new Date(fresh.reset)}}async decrement(key){let entry=await this.read(key);entry&&entry.hits>0&&(entry.hits--,await this.write(key,entry))}async reset(key){await this.kv.delete(this.prefix+key)}async read(key){let raw=await this.kv.get(this.prefix+key);if(raw===null)return null;try{return JSON.parse(raw)}catch{return null}}async write(key,entry){await this.kv.put(this.prefix+key,JSON.stringify(entry),{expirationTtl:kvTtlSeconds(Math.max(entry.reset-Date.now(),1e3))})}},KvSessionStore=class{kv;prefix;constructor(kv,options={}){this.kv=kv,this.prefix=options.prefix??`sess:`}async get(sid){let raw=await this.kv.get(this.prefix+sid);if(raw===null)return null;try{return JSON.parse(raw)}catch{return null}}async set(sid,data,maxAge){await this.kv.put(this.prefix+sid,JSON.stringify(data),{expirationTtl:kvTtlSeconds(maxAge)})}async destroy(sid){await this.kv.delete(this.prefix+sid)}async touch(sid,maxAge){let data=await this.get(sid);data!==null&&await this.set(sid,data,maxAge)}};export{KvSessionStore as n,rateLimitGuard as r,KvRateLimitStore as t};
|
|
12
|
+
//# sourceMappingURL=kv-stores-u9frHRUO.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kv-stores-C4YUttef.mjs","names":[],"sources":["../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"sourcesContent":["// Ctx-style rate limiter — runs on BOTH pipelines: the node runtimes (via\n// `@Middleware()` / class middleware) and the `@forinda/kickjs/web` fetch\n// entry (via `@Middleware()` or `createWebApp({ middleware })`), unlike the\n// connect-style `rateLimit()` which is node-only. Zero runtime imports —\n// part of the edge purity graph.\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport type { RateLimitStore } from './rate-limit'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitGuardOptions {\n /** Maximum number of requests per window (default: 100). */\n max?: number\n /** Time window in milliseconds (default: 60_000). */\n windowMs?: number\n /** Response message when the limit is exceeded (default: 'Too Many Requests'). */\n message?: string\n /** HTTP status code when the limit is exceeded (default: 429). */\n statusCode?: number\n /**\n * Rate-limit key per request. Defaults to `ctx.ip`, falling back to\n * `'global'`. Return a user/tenant id here for authenticated quotas.\n *\n * ::: warning Behind a proxy, configure `trustProxy` or every client shares\n * one bucket\n * On a node runtime `ctx.ip` is the runtime's vetted client address —\n * Express derives it from `trust proxy`, Fastify from `trustProxy`. Without\n * that setting it is the SOCKET address, which behind a load balancer or\n * Cloudflare is the proxy's, so every caller lands in the same bucket and one\n * noisy client exhausts the allowance for everyone.\n *\n * `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are\n * deliberately not consulted here: `x-forwarded-for` is client-controllable\n * unless a proxy overwrites it, so trusting it unconditionally would let a\n * direct caller mint a fresh allowance per request by varying the header —\n * evading the limit rather than enforcing it. The header chain\n * (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the\n * `@forinda/kickjs/web` edge entry, where there is no socket and the platform\n * has already terminated the connection.\n * :::\n */\n keyGenerator?: (ctx: RequestContext) => string\n /** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */\n headers?: boolean\n /**\n * Counter backend. Defaults to a per-isolate in-memory map — fine for a\n * single node process, useless on edge where isolates recycle: pass a\n * `KvRateLimitStore` (or Redis-backed store) there.\n */\n store?: RateLimitStore\n /** Skip limiting for a request (health checks, allowlists). */\n skip?: (ctx: RequestContext) => boolean\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate. Declared on the route rather than restated as a\n * path here, so it cannot drift when `apiPrefix` or a module's `version`\n * changes:\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })\n * ```\n *\n * Only meaningful where a route has been matched — as `@Middleware()` on a\n * class or method, or in `createWebApp({ middleware })`. Mounted app-wide\n * ahead of routing there is no route to read, and nothing is exempted.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Timer-free in-memory store: expired windows are swept on insert, from the\n * front. Bounded: see {@link BoundedCounters}.\n *\n * @internal Exported for tests.\n */\nexport class LazyMemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\nfunction defaultKey(ctx: RequestContext): string {\n // `ctx.ip` carries the resolution that used to live here: prefer the\n // runtime-computed address (Express derives it from `trust proxy`), fall\n // back to forwarded headers only for runtimes that compute none.\n return ctx.ip ?? 'global'\n}\n\n/**\n * Rate limiting as a `(ctx, next)` middleware.\n *\n * ```ts\n * // Edge (Cloudflare Workers) — app-wide:\n * const app = createWebApp({\n * h3, modules,\n * middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],\n * })\n *\n * // Any runtime — per controller/route:\n * @Middleware(rateLimitGuard({ max: 10 }))\n * @Post('/login')\n * ```\n */\nexport function rateLimitGuard(options: RateLimitGuardOptions = {}): MiddlewareHandler {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? defaultKey\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new LazyMemoryStore(windowMs, max)\n\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimitGuard({ exemptWhen })')\n\n return async (ctx: RequestContext, next: () => void): Promise<void> => {\n if (options.skip?.(ctx)) return next()\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n const { totalHits, resetTime } = await store.increment(keyGenerator(ctx))\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n ctx.setHeader('X-RateLimit-Limit', String(max))\n ctx.setHeader('X-RateLimit-Remaining', String(remaining))\n ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)))\n }\n\n if (totalHits > max) {\n const retryAfter = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 1000))\n if (sendHeaders) ctx.setHeader('Retry-After', String(retryAfter))\n ctx.json({ message }, statusCode)\n return\n }\n\n next()\n }\n}\n","// Edge-safe store adapters over a minimal KV surface. Zero runtime imports —\n// this file must stay importable from the `@forinda/kickjs/web` purity graph.\nimport type { RateLimitStore } from './rate-limit'\nimport type { SessionData, SessionStore } from './session'\n\n/**\n * The minimal async KV surface both stores need. Structurally compatible\n * with a Cloudflare Workers `KVNamespace` binding — pass it straight in:\n *\n * ```ts\n * export default {\n * fetch(req: Request, env: Env) {\n * const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })\n * // ...\n * },\n * }\n * ```\n *\n * Anything with the same shape works too (Deno KV wrapper, Upstash Redis\n * REST client adapter, a Map-backed fake in tests).\n */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/** Cloudflare KV rejects TTLs under 60 seconds — clamp up, never down. */\nfunction kvTtlSeconds(ms: number): number {\n return Math.max(60, Math.ceil(ms / 1000))\n}\n\nexport interface KvRateLimitStoreOptions {\n /** Window length in ms — must match the `windowMs` given to the limiter. */\n windowMs: number\n /** Key prefix in the KV namespace (default `'rl:'`). */\n prefix?: string\n}\n\n/**\n * {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments\n * where in-memory counters reset on every isolate.\n *\n * KV is eventually consistent and this is a read-modify-write counter, so\n * limiting is **approximate** under concurrency — bursts racing across\n * isolates can each read the same count. That is the accepted trade-off for\n * abuse throttling; use a Durable Object / Redis store when you need an\n * exact ceiling (billing quotas, strict per-key locks).\n */\nexport class KvRateLimitStore implements RateLimitStore {\n private readonly prefix: string\n private readonly windowMs: number\n\n constructor(\n private readonly kv: KvLike,\n options: KvRateLimitStoreOptions,\n ) {\n this.windowMs = options.windowMs\n this.prefix = options.prefix ?? 'rl:'\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = await this.read(key)\n if (entry && entry.reset > now) {\n entry.hits++\n await this.write(key, entry)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n await this.write(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = await this.read(key)\n if (entry && entry.hits > 0) {\n entry.hits--\n await this.write(key, entry)\n }\n }\n\n async reset(key: string): Promise<void> {\n await this.kv.delete(this.prefix + key)\n }\n\n private async read(key: string): Promise<{ hits: number; reset: number } | null> {\n const raw = await this.kv.get(this.prefix + key)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as { hits: number; reset: number }\n } catch {\n return null\n }\n }\n\n private async write(key: string, entry: { hits: number; reset: number }): Promise<void> {\n await this.kv.put(this.prefix + key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds(Math.max(entry.reset - Date.now(), 1000)),\n })\n }\n}\n\nexport interface KvSessionStoreOptions {\n /** Key prefix in the KV namespace (default `'sess:'`). */\n prefix?: string\n}\n\n/**\n * {@link SessionStore} over a {@link KvLike} namespace. Plug into the node\n * `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via\n * REST) so sessions survive restarts and horizontal scaling; TTL expiry is\n * delegated to the KV layer via `expirationTtl`.\n *\n * Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only\n * refresh), so `session({ rolling: true })` doubles KV operations per\n * request — per-operation-billed platforms may prefer `rolling: false`.\n */\nexport class KvSessionStore implements SessionStore {\n private readonly prefix: string\n\n constructor(\n private readonly kv: KvLike,\n options: KvSessionStoreOptions = {},\n ) {\n this.prefix = options.prefix ?? 'sess:'\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const raw = await this.kv.get(this.prefix + sid)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as SessionData\n } catch {\n return null\n }\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n await this.kv.put(this.prefix + sid, JSON.stringify(data), {\n expirationTtl: kvTtlSeconds(maxAge),\n })\n }\n\n async destroy(sid: string): Promise<void> {\n await this.kv.delete(this.prefix + sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const data = await this.get(sid)\n if (data !== null) await this.set(sid, data, maxAge)\n }\n}\n"],"mappings":";;;;;;;;;;kJA6EA,IAAa,gBAAb,KAAuD,CACrD,SAGA,YAAY,SAAkB,MA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AS,IAAK,KAAK,UAAU,KAAK,EAAG,CAC1D,cAAe,aAAa,KAAK,IAAI,MAAM,MAAQ,KAAK,IAAI,EAAG,GAAI,CAAC,CACtE,CAAC,CACH,CACF,EAiBa,eAAb,KAAoD,CAI/B,GAHnB,OAEA,YACE,GACA,QAAiC,CAAC,EAClC,CAFiB,KAAA,GAAA,GAGjB,KAAK,OAAS,QAAQ,QAAU,OAClC,CAEA,MAAM,IAAI,IAA0C,CAClD,IAAM,IAAM,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,GAAG,EAC/C,GAAI,MAAQ,KAAM,OAAO,KACzB,GAAI,CACF,OAAO,KAAK,MAAM,GAAG,CACvB,MAAQ,CACN,OAAO,IACT,CACF,CAEA,MAAM,IAAI,IAAa,KAAmB,OAA+B,CACvE,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,IAAK,KAAK,UAAU,IAAI,EAAG,CACzD,cAAe,aAAa,MAAM,CACpC,CAAC,CACH,CAEA,MAAM,QAAQ,IAA4B,CACxC,MAAM,KAAK,GAAG,OAAO,KAAK,OAAS,GAAG,CACxC,CAEA,MAAM,MAAM,IAAa,OAA+B,CACtD,IAAM,KAAO,MAAM,KAAK,IAAI,GAAG,EAC3B,OAAS,MAAM,MAAM,KAAK,IAAI,IAAK,KAAM,MAAM,CACrD,CACF"}
|
|
1
|
+
{"version":3,"file":"kv-stores-u9frHRUO.mjs","names":[],"sources":["../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"sourcesContent":["// Ctx-style rate limiter — runs on BOTH pipelines: the node runtimes (via\n// `@Middleware()` / class middleware) and the `@forinda/kickjs/web` fetch\n// entry (via `@Middleware()` or `createWebApp({ middleware })`), unlike the\n// connect-style `rateLimit()` which is node-only. Zero runtime imports —\n// part of the edge purity graph.\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport type { RateLimitStore } from './rate-limit'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitGuardOptions {\n /** Maximum number of requests per window (default: 100). */\n max?: number\n /** Time window in milliseconds (default: 60_000). */\n windowMs?: number\n /** Response message when the limit is exceeded (default: 'Too Many Requests'). */\n message?: string\n /** HTTP status code when the limit is exceeded (default: 429). */\n statusCode?: number\n /**\n * Rate-limit key per request. Defaults to `ctx.ip`, falling back to\n * `'global'`. Return a user/tenant id here for authenticated quotas.\n *\n * ::: warning Behind a proxy, configure `trustProxy` or every client shares\n * one bucket\n * On a node runtime `ctx.ip` is the runtime's vetted client address —\n * Express derives it from `trust proxy`, Fastify from `trustProxy`. Without\n * that setting it is the SOCKET address, which behind a load balancer or\n * Cloudflare is the proxy's, so every caller lands in the same bucket and one\n * noisy client exhausts the allowance for everyone.\n *\n * `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are\n * deliberately not consulted here: `x-forwarded-for` is client-controllable\n * unless a proxy overwrites it, so trusting it unconditionally would let a\n * direct caller mint a fresh allowance per request by varying the header —\n * evading the limit rather than enforcing it. The header chain\n * (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the\n * `@forinda/kickjs/web` edge entry, where there is no socket and the platform\n * has already terminated the connection.\n * :::\n */\n keyGenerator?: (ctx: RequestContext) => string\n /** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */\n headers?: boolean\n /**\n * Counter backend. Defaults to a per-isolate in-memory map — fine for a\n * single node process, useless on edge where isolates recycle: pass a\n * `KvRateLimitStore` (or Redis-backed store) there.\n */\n store?: RateLimitStore\n /** Skip limiting for a request (health checks, allowlists). */\n skip?: (ctx: RequestContext) => boolean\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate. Declared on the route rather than restated as a\n * path here, so it cannot drift when `apiPrefix` or a module's `version`\n * changes:\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })\n * ```\n *\n * Only meaningful where a route has been matched — as `@Middleware()` on a\n * class or method, or in `createWebApp({ middleware })`. Mounted app-wide\n * ahead of routing there is no route to read, and nothing is exempted.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Timer-free in-memory store: expired windows are swept on insert, from the\n * front. Bounded: see {@link BoundedCounters}.\n *\n * @internal Exported for tests.\n */\nexport class LazyMemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\nfunction defaultKey(ctx: RequestContext): string {\n // `ctx.ip` carries the resolution that used to live here: prefer the\n // runtime-computed address (Express derives it from `trust proxy`), fall\n // back to forwarded headers only for runtimes that compute none.\n return ctx.ip ?? 'global'\n}\n\n/**\n * Rate limiting as a `(ctx, next)` middleware.\n *\n * ```ts\n * // Edge (Cloudflare Workers) — app-wide:\n * const app = createWebApp({\n * h3, modules,\n * middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],\n * })\n *\n * // Any runtime — per controller/route:\n * @Middleware(rateLimitGuard({ max: 10 }))\n * @Post('/login')\n * ```\n */\nexport function rateLimitGuard(options: RateLimitGuardOptions = {}): MiddlewareHandler {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? defaultKey\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new LazyMemoryStore(windowMs, max)\n\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimitGuard({ exemptWhen })')\n\n return async (ctx: RequestContext, next: () => void): Promise<void> => {\n if (options.skip?.(ctx)) return next()\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n const { totalHits, resetTime } = await store.increment(keyGenerator(ctx))\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n ctx.setHeader('X-RateLimit-Limit', String(max))\n ctx.setHeader('X-RateLimit-Remaining', String(remaining))\n ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)))\n }\n\n if (totalHits > max) {\n const retryAfter = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 1000))\n if (sendHeaders) ctx.setHeader('Retry-After', String(retryAfter))\n ctx.json({ message }, statusCode)\n return\n }\n\n next()\n }\n}\n","// Edge-safe store adapters over a minimal KV surface. Zero runtime imports —\n// this file must stay importable from the `@forinda/kickjs/web` purity graph.\nimport type { RateLimitStore } from './rate-limit'\nimport type { SessionData, SessionStore } from './session'\n\n/**\n * The minimal async KV surface both stores need. Structurally compatible\n * with a Cloudflare Workers `KVNamespace` binding — pass it straight in:\n *\n * ```ts\n * export default {\n * fetch(req: Request, env: Env) {\n * const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })\n * // ...\n * },\n * }\n * ```\n *\n * Anything with the same shape works too (Deno KV wrapper, Upstash Redis\n * REST client adapter, a Map-backed fake in tests).\n */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/** Cloudflare KV rejects TTLs under 60 seconds — clamp up, never down. */\nfunction kvTtlSeconds(ms: number): number {\n return Math.max(60, Math.ceil(ms / 1000))\n}\n\nexport interface KvRateLimitStoreOptions {\n /** Window length in ms — must match the `windowMs` given to the limiter. */\n windowMs: number\n /** Key prefix in the KV namespace (default `'rl:'`). */\n prefix?: string\n}\n\n/**\n * {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments\n * where in-memory counters reset on every isolate.\n *\n * KV is eventually consistent and this is a read-modify-write counter, so\n * limiting is **approximate** under concurrency — bursts racing across\n * isolates can each read the same count. That is the accepted trade-off for\n * abuse throttling; use a Durable Object / Redis store when you need an\n * exact ceiling (billing quotas, strict per-key locks).\n */\nexport class KvRateLimitStore implements RateLimitStore {\n private readonly prefix: string\n private readonly windowMs: number\n\n constructor(\n private readonly kv: KvLike,\n options: KvRateLimitStoreOptions,\n ) {\n this.windowMs = options.windowMs\n this.prefix = options.prefix ?? 'rl:'\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = await this.read(key)\n if (entry && entry.reset > now) {\n entry.hits++\n await this.write(key, entry)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n await this.write(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = await this.read(key)\n if (entry && entry.hits > 0) {\n entry.hits--\n await this.write(key, entry)\n }\n }\n\n async reset(key: string): Promise<void> {\n await this.kv.delete(this.prefix + key)\n }\n\n private async read(key: string): Promise<{ hits: number; reset: number } | null> {\n const raw = await this.kv.get(this.prefix + key)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as { hits: number; reset: number }\n } catch {\n return null\n }\n }\n\n private async write(key: string, entry: { hits: number; reset: number }): Promise<void> {\n await this.kv.put(this.prefix + key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds(Math.max(entry.reset - Date.now(), 1000)),\n })\n }\n}\n\nexport interface KvSessionStoreOptions {\n /** Key prefix in the KV namespace (default `'sess:'`). */\n prefix?: string\n}\n\n/**\n * {@link SessionStore} over a {@link KvLike} namespace. Plug into the node\n * `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via\n * REST) so sessions survive restarts and horizontal scaling; TTL expiry is\n * delegated to the KV layer via `expirationTtl`.\n *\n * Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only\n * refresh), so `session({ rolling: true })` doubles KV operations per\n * request — per-operation-billed platforms may prefer `rolling: false`.\n */\nexport class KvSessionStore implements SessionStore {\n private readonly prefix: string\n\n constructor(\n private readonly kv: KvLike,\n options: KvSessionStoreOptions = {},\n ) {\n this.prefix = options.prefix ?? 'sess:'\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const raw = await this.kv.get(this.prefix + sid)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as SessionData\n } catch {\n return null\n }\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n await this.kv.put(this.prefix + sid, JSON.stringify(data), {\n expirationTtl: kvTtlSeconds(maxAge),\n })\n }\n\n async destroy(sid: string): Promise<void> {\n await this.kv.delete(this.prefix + sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const data = await this.get(sid)\n if (data !== null) await this.set(sid, data, maxAge)\n }\n}\n"],"mappings":";;;;;;;;;;kJA6EA,IAAa,gBAAb,KAAuD,CACrD,SAGA,YAAY,SAAkB,MAAgB,CAC5C,KAAK,SAAW,IAAI,gBAAgB,SAAU,KAAK,CACrD,CAEA,MAAM,UAAU,IAA8D,CAC5E,OAAO,KAAK,SAAS,UAAU,GAAG,CACpC,CAEA,MAAM,UAAU,IAA4B,CAC1C,KAAK,SAAS,UAAU,GAAG,CAC7B,CAEA,MAAM,MAAM,IAA4B,CACtC,KAAK,SAAS,MAAM,GAAG,CACzB,CACF,EAEA,SAAS,WAAW,IAA6B,CAI/C,OAAO,IAAI,IAAM,QACnB,CAiBA,SAAgB,eAAe,QAAiC,CAAC,EAAsB,CACrF,IAAM,IAAM,QAAQ,KAAO,IACrB,SAAW,QAAQ,UAAY,IAC/B,QAAU,QAAQ,SAAW,oBAC7B,WAAa,QAAQ,YAAc,IACnC,aAAe,QAAQ,cAAgB,WACvC,YAAc,QAAQ,SAAW,GACjC,MAAQ,QAAQ,OAAS,IAAI,gBAAgB,SAAU,GAAG,EAE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,aAAa,MAAM,CACpC,CAAC,CACH,CAEA,MAAM,QAAQ,IAA4B,CACxC,MAAM,KAAK,GAAG,OAAO,KAAK,OAAS,GAAG,CACxC,CAEA,MAAM,MAAM,IAAa,OAA+B,CACtD,IAAM,KAAO,MAAM,KAAK,IAAI,GAAG,EAC3B,OAAS,MAAM,MAAM,KAAK,IAAI,IAAK,KAAM,MAAM,CACrD,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.13.
|
|
2
|
+
* @forinda/kickjs v10.13.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as withPrecompressed}from"./precompressed-
|
|
12
|
-
//# sourceMappingURL=lazy-serve-static-
|
|
11
|
+
import{t as withPrecompressed}from"./precompressed-CLMMwxxl.mjs";function lazyServeStatic(dir){let serve;return withPrecompressed(dir,(req,res,next)=>{serve??=import(`serve-static`).then(mod=>(mod.default??mod)(dir)),serve.then(handler=>handler(req,res,next),next)})}export{lazyServeStatic as t};
|
|
12
|
+
//# sourceMappingURL=lazy-serve-static-C1iV009Y.mjs.map
|