@forinda/kickjs 10.1.0 → 10.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-BYdxuKiM.d.mts +4916 -0
- package/dist/adapter-BYdxuKiM.d.mts.map +1 -0
- package/dist/allowed-hosts-D6qcuK5I.d.mts +46 -0
- package/dist/allowed-hosts-D6qcuK5I.d.mts.map +1 -0
- package/dist/{app-module-DCA65GZZ.d.mts → app-module-Ftz6m7SO.d.mts} +8 -2
- package/dist/app-module-Ftz6m7SO.d.mts.map +1 -0
- package/dist/application-B2e5XYHm.mjs +14 -0
- package/dist/application-B2e5XYHm.mjs.map +1 -0
- package/dist/bootstrap-BmALF-1Y.mjs +12 -0
- package/dist/{bootstrap-BdyBlBMe.mjs.map → bootstrap-BmALF-1Y.mjs.map} +1 -1
- package/dist/bounded-counters-aA3iI_Ei.mjs +12 -0
- package/dist/bounded-counters-aA3iI_Ei.mjs.map +1 -0
- package/dist/breach-padding-C-Dnq8CS.d.mts +39 -0
- package/dist/breach-padding-C-Dnq8CS.d.mts.map +1 -0
- package/dist/{client-ip-BbLDp03S.mjs → client-ip-D2dsx8RG.mjs} +2 -2
- package/dist/{client-ip-BbLDp03S.mjs.map → client-ip-D2dsx8RG.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/config-B77LTW_E.mjs +12 -0
- package/dist/{config-CJiGeOca.mjs.map → config-B77LTW_E.mjs.map} +1 -1
- package/dist/{container-CS9v9UFU.mjs → container-mvaAYThX.mjs} +3 -3
- package/dist/{container-CS9v9UFU.mjs.map → container-mvaAYThX.mjs.map} +1 -1
- package/dist/context-GbQnJB-L.mjs +12 -0
- package/dist/context-GbQnJB-L.mjs.map +1 -0
- package/dist/{context-errors-7C5TBYn7.mjs → context-errors-CPqYYhl0.mjs} +2 -2
- package/dist/{context-errors-7C5TBYn7.mjs.map → context-errors-CPqYYhl0.mjs.map} +1 -1
- package/dist/{contributor-runner-DBpRR5dl.mjs → contributor-runner-Cl5yZZy1.mjs} +3 -3
- package/dist/{contributor-runner-DBpRR5dl.mjs.map → contributor-runner-Cl5yZZy1.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +2 -2
- package/dist/core/errors.mjs.map +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.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/core-D1AV-Tvd.mjs +12 -0
- package/dist/{core-B0JmdBvX.mjs.map → core-D1AV-Tvd.mjs.map} +1 -1
- package/dist/{cors-CsibNTQ6.d.mts → cors-2Bwhyhpt.d.mts} +4 -1
- package/dist/{cors-CsibNTQ6.d.mts.map → cors-2Bwhyhpt.d.mts.map} +1 -1
- package/dist/{csrf-C73UkRgc.d.mts → csrf-Cy1meSpf.d.mts} +27 -3
- package/dist/csrf-Cy1meSpf.d.mts.map +1 -0
- package/dist/csrf-D3prC4FK.mjs +12 -0
- package/dist/csrf-D3prC4FK.mjs.map +1 -0
- package/dist/decorate-BiXL-9e9.mjs +13 -0
- package/dist/decorate-BiXL-9e9.mjs.map +1 -0
- package/dist/{decorators-BxNSz9Qt.d.mts → decorators-DaQUNXOn.d.mts} +2 -2
- package/dist/{decorators-BxNSz9Qt.d.mts.map → decorators-DaQUNXOn.d.mts.map} +1 -1
- package/dist/{define-adapter-BLKlUbSL.mjs → define-adapter-D22SDe0U.mjs} +2 -2
- package/dist/{define-adapter-BLKlUbSL.mjs.map → define-adapter-D22SDe0U.mjs.map} +1 -1
- package/dist/{disposables-CuY2S3bw.mjs → disposables-CJD_gWlA.mjs} +2 -2
- package/dist/{disposables-CuY2S3bw.mjs.map → disposables-CJD_gWlA.mjs.map} +1 -1
- package/dist/errors-By6UueCm.d.mts.map +1 -1
- package/dist/handler-gW_h2miq.mjs +12 -0
- package/dist/handler-gW_h2miq.mjs.map +1 -0
- package/dist/{helmet-C2QEU6S-.d.mts → helmet-CEOmo516.d.mts} +4 -1
- package/dist/helmet-CEOmo516.d.mts.map +1 -0
- package/dist/host-D__uZPyz.mjs +12 -0
- package/dist/host-D__uZPyz.mjs.map +1 -0
- package/dist/http/application.d.mts +2 -2
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.d.mts +3 -0
- package/dist/http/middleware/allowed-hosts.mjs +12 -0
- package/dist/http/middleware/allowed-hosts.mjs.map +1 -0
- package/dist/http/middleware/breach-padding.d.mts +3 -0
- package/dist/http/middleware/breach-padding.mjs +12 -0
- package/dist/http/middleware/breach-padding.mjs.map +1 -0
- package/dist/http/middleware/cors.d.mts +1 -1
- package/dist/http/middleware/cors.mjs +2 -2
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.d.mts +2 -2
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.d.mts +1 -1
- package/dist/http/middleware/helmet.mjs +2 -2
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.d.mts +2 -2
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.mjs +2 -2
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +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.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -3
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.d.mts +2 -2
- package/dist/http/middleware/validate.mjs +2 -2
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +2 -2
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +5 -1
- package/dist/http/runtimes/fastify.d.mts.map +1 -1
- package/dist/http/runtimes/fastify.mjs +3 -3
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +5 -4
- 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-CNHSbZTE.d.mts → index-CuiWSnZL.d.mts} +3 -2
- package/dist/index-CuiWSnZL.d.mts.map +1 -0
- package/dist/index.d.mts +16 -18
- package/dist/index.mjs +6 -2
- package/dist/index.mjs.map +1 -1
- package/dist/is-production-Dbm13WNL.mjs +12 -0
- package/dist/is-production-Dbm13WNL.mjs.map +1 -0
- package/dist/{jobs-BQ4t3TAb.mjs → jobs-s4__kZLr.mjs} +3 -3
- package/dist/{jobs-BQ4t3TAb.mjs.map → jobs-s4__kZLr.mjs.map} +1 -1
- package/dist/kv-stores-Cjel_Dkc.mjs +12 -0
- package/dist/kv-stores-Cjel_Dkc.mjs.map +1 -0
- package/dist/lazy-serve-static-w94Xs3wQ.mjs +12 -0
- package/dist/lazy-serve-static-w94Xs3wQ.mjs.map +1 -0
- package/dist/{metadata-zvd6AWkE.mjs → metadata-C2GK_17k.mjs} +2 -2
- package/dist/{metadata-zvd6AWkE.mjs.map → metadata-C2GK_17k.mjs.map} +1 -1
- package/dist/{observers-DZgs48UM.mjs → observers-boPE9XGi.mjs} +2 -2
- package/dist/{observers-DZgs48UM.mjs.map → observers-boPE9XGi.mjs.map} +1 -1
- package/dist/{query-B_k9qn0R.mjs → query-DjTeF1d4.mjs} +2 -2
- package/dist/{query-B_k9qn0R.mjs.map → query-DjTeF1d4.mjs.map} +1 -1
- package/dist/{rate-limit-Bwed3jOV.d.mts → rate-limit-BgoeahE5.d.mts} +17 -2
- package/dist/rate-limit-BgoeahE5.d.mts.map +1 -0
- package/dist/reply-CYY_CzRf.mjs +12 -0
- package/dist/reply-CYY_CzRf.mjs.map +1 -0
- package/dist/respond-Dc18G0X7.mjs +12 -0
- package/dist/respond-Dc18G0X7.mjs.map +1 -0
- package/dist/{route-flag-BWuvJsGZ.mjs → route-flag-BOQZs2Wn.mjs} +3 -3
- package/dist/{route-flag-BWuvJsGZ.mjs.map → route-flag-BOQZs2Wn.mjs.map} +1 -1
- package/dist/{route-policy-B3vM6bSf.mjs → route-policy-B8c6QfiU.mjs} +2 -2
- package/dist/{route-policy-B3vM6bSf.mjs.map → route-policy-B8c6QfiU.mjs.map} +1 -1
- package/dist/{router-builder-JvMTp50k.mjs → router-builder-DoWOIGmG.mjs} +3 -3
- package/dist/router-builder-DoWOIGmG.mjs.map +1 -0
- package/dist/{session-B4hOZj90.d.mts → session-ChXx7jG5.d.mts} +31 -4
- package/dist/session-ChXx7jG5.d.mts.map +1 -0
- package/dist/settings-C8VKewNS.d.mts +119 -0
- package/dist/settings-C8VKewNS.d.mts.map +1 -0
- package/dist/settings-DcytOCC6.mjs +14 -0
- package/dist/settings-DcytOCC6.mjs.map +1 -0
- package/dist/{upload-config-Dz2INCaa.mjs → upload-config-CzxbJALL.mjs} +2 -2
- package/dist/{upload-config-Dz2INCaa.mjs.map → upload-config-CzxbJALL.mjs.map} +1 -1
- package/dist/url-for-DGSrVfdD.mjs +12 -0
- package/dist/url-for-DGSrVfdD.mjs.map +1 -0
- package/dist/validate-CzjCbRUn.d.mts +53 -0
- package/dist/validate-CzjCbRUn.d.mts.map +1 -0
- package/dist/web.d.mts +19 -19
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +18 -1
- package/dist/adapter-ClEh-Oos.d.mts +0 -2134
- package/dist/adapter-ClEh-Oos.d.mts.map +0 -1
- package/dist/app-module-DCA65GZZ.d.mts.map +0 -1
- package/dist/application-Dv514EeR.mjs +0 -12
- package/dist/application-Dv514EeR.mjs.map +0 -1
- package/dist/application-oIPzgjfk.d.mts +0 -1589
- package/dist/application-oIPzgjfk.d.mts.map +0 -1
- package/dist/bootstrap-BdyBlBMe.mjs +0 -12
- package/dist/config-CJiGeOca.mjs +0 -12
- package/dist/context-CtL9RxXp.mjs +0 -12
- package/dist/context-CtL9RxXp.mjs.map +0 -1
- package/dist/core-B0JmdBvX.mjs +0 -12
- package/dist/csrf--1t4qDov.mjs +0 -12
- package/dist/csrf--1t4qDov.mjs.map +0 -1
- package/dist/csrf-C73UkRgc.d.mts.map +0 -1
- package/dist/decorate-BHkdkV4l.mjs +0 -11
- package/dist/env-BwzF9MkZ.mjs +0 -13
- package/dist/env-BwzF9MkZ.mjs.map +0 -1
- package/dist/error-handler-BB9wAElm.d.mts +0 -63
- package/dist/error-handler-BB9wAElm.d.mts.map +0 -1
- package/dist/handler-zKfIgNo4.mjs +0 -13
- package/dist/handler-zKfIgNo4.mjs.map +0 -1
- package/dist/helmet-C2QEU6S-.d.mts.map +0 -1
- package/dist/index-CNHSbZTE.d.mts.map +0 -1
- package/dist/kv-stores-Co5k2PYA.d.mts +0 -367
- package/dist/kv-stores-Co5k2PYA.d.mts.map +0 -1
- package/dist/kv-stores-DsfVy2fk.mjs +0 -12
- package/dist/kv-stores-DsfVy2fk.mjs.map +0 -1
- package/dist/module-registry-Daf_P2oD.mjs +0 -12
- package/dist/module-registry-Daf_P2oD.mjs.map +0 -1
- package/dist/rate-limit-Bwed3jOV.d.mts.map +0 -1
- package/dist/reply-BDK9xt7Z.mjs +0 -12
- package/dist/reply-BDK9xt7Z.mjs.map +0 -1
- package/dist/respond-DFRj2-7q.mjs +0 -12
- package/dist/respond-DFRj2-7q.mjs.map +0 -1
- package/dist/router-builder-JvMTp50k.mjs.map +0 -1
- package/dist/router-builder-zWuVIOmd.d.mts +0 -56
- package/dist/router-builder-zWuVIOmd.d.mts.map +0 -1
- package/dist/session-B4hOZj90.d.mts.map +0 -1
- package/dist/upload-CiMtdXWD.d.mts +0 -104
- package/dist/upload-CiMtdXWD.d.mts.map +0 -1
- package/dist/validate-DMYpUnrf.d.mts +0 -25
- package/dist/validate-DMYpUnrf.d.mts.map +0 -1
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.1.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{createLogger,describeError}from"./core/logger.mjs";import{HttpException}from"./core/errors.mjs";import{d as classifyMediaType,n as applyHandlerResult,o as createRequestStore,p as unsupportedMediaTypeError,s as disposeRequestStore}from"./reply-BDK9xt7Z.mjs";import{d as requestStore,i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"./context-CtL9RxXp.mjs";import{validate}from"./http/middleware/validate.mjs";import{t as applyUploadConfig}from"./upload-config-Dz2INCaa.mjs";var WebRequestShim=class{method;url;headers;body;params={};query={};requestId;file;files;signal;constructor(request,url){this.method=request.method,this.url=url.pathname+url.search,this.signal=request.signal;let headers={};request.headers.forEach((value,key)=>{headers[key]=value}),this.headers=headers;let query={};for(let key of url.searchParams.keys()){let all=url.searchParams.getAll(key);query[key]=all.length>1?all:all[0]}this.query=query}once(event,listener){return event===`close`&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}on(event,listener){return this.once(event,listener)}};const encoder=new TextEncoder;function toBytes(chunk){return chunk instanceof Uint8Array?chunk:encoder.encode(String(chunk))}var WebResponseDriver=class{signal;ready;settled=!1;_status=200;headers=new Headers;_headersSent=!1;writer;resolveReady;constructor(signal){this.signal=signal,this.ready=new Promise(resolve=>{this.resolveReady=resolve})}status(code){return this._status=code,this}json(data){return this.headers.has(`content-type`)||this.headers.set(`content-type`,`application/json; charset=utf-8`),this.finish(stringifyJson(data))}send(data){return typeof data==`object`&&data&&!(data instanceof Uint8Array)?this.json(data):this.finish(data)}type(contentType){return this.headers.set(`content-type`,contentType),this}setHeader(name,value){if(Array.isArray(value)){this.headers.delete(name);for(let v of value)this.headers.append(name,String(v))}else this.headers.set(name,String(value));return this}render(){throw Error(`ctx.render() is not supported on the web runtime (no view engine).`)}writeHead(statusCode,headers){if(this._status=statusCode,headers)for(let[name,value]of Object.entries(headers))this.setHeader(name,value);return this.startStream(),this}flushHeaders(){return this.startStream(),this}write(chunk){return this.startStream(),this.writer.write(toBytes(chunk)).catch(()=>{}),!0}end(data){return this.writer?(data!==void 0&&this.write(data),this.writer.close().catch(()=>{}),this.writer=void 0,this):this.finish(data)}once(event,listener){return event===`close`&&this.signal&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}get headersSent(){return this._headersSent}finish(body){if(this.settled)return this;this.settled=!0,this._headersSent=!0;let bodyAllowed=this._status!==204&&this._status!==304;return this.resolveReady(new Response(bodyAllowed?body??null:null,{status:this._status,headers:this.headers})),this}startStream(){if(this.writer||this.settled)return;let{readable,writable}=new TransformStream;this.writer=writable.getWriter(),this.settled=!0,this._headersSent=!0,this.signal?.addEventListener(`abort`,()=>{this.writer?.abort().catch(()=>{}),this.writer=void 0},{once:!0}),this.resolveReady(new Response(readable,{status:this._status,headers:this.headers}))}};const log=createLogger(`WebPipeline`),NOOP_NEXT=()=>{},BODY_METHODS=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);function defaultErrorResponse(err,driver){let status=typeof err?.status==`number`?err.status:typeof err?.statusCode==`number`?err.statusCode:500;if(status>=500){log.error(err,`Unhandled error in web pipeline — ${describeError(err)}`);let stack=err?.stack;driver.status(status).json({error:`Internal Server Error`,...isProduction()?{}:{message:describeError(err),...typeof stack==`string`?{stack:stack.split(`
|
|
12
|
-
`)}:{}}})}else driver.status(status).json({error:err?.message??`Request failed`})}function isProduction(){return typeof process<`u`&&process.env?.NODE_ENV===`production`}function readThrough(shim,carry){return new Proxy(shim,{get(target,prop,receiver){let own=Reflect.get(target,prop,receiver);return own===void 0?Reflect.get(carry,prop,carry):own},has(target,prop){return Reflect.has(target,prop)||Reflect.has(carry,prop)}})}function compileWebRoute(entry,hooks){let validator=entry.meta.validation?validate(entry.meta.validation):void 0,upload=entry.meta.upload&&entry.meta.upload.mode!==`none`?entry.meta.upload:null;return async({request,url,params,carry})=>{let shim=new WebRequestShim(request,url),req=carry?readThrough(shim,carry):shim;req.params=params;let bodyError;if(upload){let form=await request.formData().catch(()=>void 0);if(form){let rawParts=[],fields={};for(let[name,value]of form.entries())typeof value==`string`?fields[name]=value:rawParts.push({fieldname:name,filename:value.name??``,mimetype:value.type||`application/octet-stream`,buffer:typeof Buffer==`function`?Buffer.from(await value.arrayBuffer()):new Uint8Array(await value.arrayBuffer())});let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);req.file=file,req.files=files,req.body=fields}}else if(BODY_METHODS.has(request.method)){let raw=request.body===null?``:await request.text().catch(()=>``),kind=classifyMediaType(req.headers[`content-type`]);if(raw!==``&&kind===`unsupported`)bodyError=unsupportedMediaTypeError(req.headers[`content-type`]);else if(raw!==``&&kind!==`multipart`){if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){bodyError=HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`)}else req.body=kind===`urlencoded`?Object.fromEntries(new URLSearchParams(raw)):raw}}let store=createRequestStore(req.requestId??req.headers[`x-request-id`]);req.requestId=store.requestId;let driver=new WebResponseDriver(request.signal);driver.setHeader(`x-request-id`,store.requestId),publishMatchedRoute(req,entry),carry&&publishMatchedRoute(carry,entry);let pipeline=requestStore.run(store,async()=>{if(bodyError)throw bodyError;let ctx=new RequestContext(req,driver,NOOP_NEXT,driver);if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),driver.settled))return;validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||driver.settled)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),driver.settled)return;let result=await entry.handler(ctx);driver.settled||await applyHandlerResult(ctx,result)});try{try{await Promise.race([pipeline,driver.ready])}catch(err){driver.settled||(hooks?.onError&&await hooks.onError(err,req,driver),driver.settled||defaultErrorResponse(err,driver))}return driver.settled||driver.status(404).json({error:`Not Found`}),await driver.ready}finally{Promise.resolve(pipeline).catch(()=>{}).then(()=>disposeRequestStore(store))}}}export{WebResponseDriver as i,readThrough as n,WebRequestShim as r,compileWebRoute as t};
|
|
13
|
-
//# sourceMappingURL=handler-zKfIgNo4.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"handler-zKfIgNo4.mjs","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, type RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(stringifyJson(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n","// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport { classifyMediaType, unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { createLogger, describeError } from '../../core/logger'\n\nconst log = createLogger('WebPipeline')\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n/**\n * Fallback error shape when no engine error handler settles the response.\n *\n * This path used to be completely silent: a bare\n * `{ error: 'Internal Server Error' }` with no log line anywhere, so a\n * failure that reached here left no trace on either side. It is a\n * last-resort branch, which is exactly when diagnostics matter most.\n */\nfunction defaultErrorResponse(err: unknown, driver: WebResponseDriver): void {\n const status =\n typeof (err as { status?: number })?.status === 'number'\n ? (err as { status: number }).status\n : typeof (err as { statusCode?: number })?.statusCode === 'number'\n ? (err as { statusCode: number }).statusCode\n : 500\n\n if (status >= 500) {\n log.error(err, `Unhandled error in web pipeline — ${describeError(err)}`)\n const stack = (err as Error)?.stack\n driver.status(status).json({\n error: 'Internal Server Error',\n ...(isProduction()\n ? {}\n : {\n message: describeError(err),\n ...(typeof stack === 'string' ? { stack: stack.split('\\n') } : {}),\n }),\n })\n return\n }\n\n driver.status(status).json({ error: (err as Error)?.message ?? 'Request failed' })\n}\n\n/**\n * Read per-call, not at module scope: the web entry is imported once and\n * reused across invocations, and edge runtimes may not expose `process`.\n */\nfunction isProduction(): boolean {\n return typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n req.params = params\n let bodyError: unknown\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n const form = await request.formData().catch(() => undefined)\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields[name] = value\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n req.body = fields\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n const raw = request.body === null ? '' : await request.text().catch(() => '')\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = Object.fromEntries(new URLSearchParams(raw))\n } else {\n req.body = raw\n }\n }\n }\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId ?? req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n if (!driver.settled) {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) defaultErrorResponse(err, driver)\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — canonical 404 shape.\n driver.status(404).json({ error: 'Not Found' })\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n"],"mappings":";;;;;;;;;;ofAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,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QAAQ,GAAG,EAGjC,OAAO,SAAS,MAAM,mBAAmB,IAAK,MAAM,CAC3D,CAAC,EAED,GAAI,CAGF,GAAI,CACF,MAAM,QAAQ,KAAK,CAAC,SAAU,OAAO,KAAK,CAAC,CAC7C,OAAS,IAAK,CACP,OAAO,UACN,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAK,IAAK,MAAM,EACnD,OAAO,SAAS,qBAAqB,IAAK,MAAM,EAEzD,CAKA,OAJK,OAAO,SAEV,OAAO,OAAO,GAAG,CAAC,CAAC,KAAK,CAAE,MAAO,WAAY,CAAC,EAEzC,MAAM,OAAO,KACtB,QAAU,CAIR,QAAa,QAAQ,QAAQ,CAAC,CAC3B,UAAY,CAAC,CAAC,CAAC,CACf,SAAW,oBAAoB,KAAK,CAAC,CAC1C,CACF,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"helmet-C2QEU6S-.d.mts","names":[],"sources":["../src/http/middleware/helmet.ts"],"mappings":";;;;cAGa;UAEI;;EAEf,kCAAkC;;EAElC;;EAEA;;EAEA;IAAiB;IAAiB;IAA6B;;;EAE/D;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;iBAcc,OAAO,UAAS,iBAAkB,KAY1B,SAAO,KAAO,UAAQ,MAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-CNHSbZTE.d.mts","names":[],"sources":["../src/config/env.ts","../src/config/config-service.ts"],"mappings":";;;;;;;;;;iBAsOS,sBAAkB,EAAA;;;;;;;;GAQ1B,EAAA,KAAA;;KAGW,gBAAgB,kBAAkB;;;;;;;;;;;cAsBjC,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6DZ,UAAU,UAAU,EAAE,aACpC,SAAS,aAAa,kBAAkB,EAAE,UAAU,KACnD,EAAE,iBAAiB,cAAc,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;iBAgC5B,QAAQ,UAAU,EAAE,gBAAgB,QAA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yt.mjs";
|
|
3
|
-
import { x as MiddlewareHandler } from "./decorators-BxNSz9Qt.mjs";
|
|
4
|
-
import { D as RequestContext, S as RuntimeResponse } from "./adapter-ClEh-Oos.mjs";
|
|
5
|
-
import { d as RouteFlagTest } from "./route-flag-B1lQht6v.mjs";
|
|
6
|
-
import { i as SessionStore, n as SessionData } from "./session-B4hOZj90.mjs";
|
|
7
|
-
import { n as RateLimitStore } from "./rate-limit-Bwed3jOV.mjs";
|
|
8
|
-
//#region src/core/jobs.d.ts
|
|
9
|
-
/** Metadata keys — the same ones `@forinda/kickjs-queue` used, so existing readers keep working. */
|
|
10
|
-
declare const JOB_META: {
|
|
11
|
-
readonly JOB: 'kick/queue/job';
|
|
12
|
-
readonly PROCESS: 'kick/queue/process';
|
|
13
|
-
};
|
|
14
|
-
/** What a `@Process` method records. */
|
|
15
|
-
interface ProcessDefinition {
|
|
16
|
-
/** Method name on the class. */
|
|
17
|
-
handlerName: string;
|
|
18
|
-
/** Job name it handles; `undefined` handles every job in the queue. */
|
|
19
|
-
jobName?: string;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* The least a job tool hands over. Runners pass their own job object through
|
|
23
|
-
* unchanged — BullMQ's `Job`, a Cloudflare message — so a handler can still
|
|
24
|
-
* reach tool-specific fields (`job.attemptsMade`, `job.updateProgress()`).
|
|
25
|
-
*/
|
|
26
|
-
interface JobLike<Data = unknown> {
|
|
27
|
-
name: string;
|
|
28
|
-
data: Data;
|
|
29
|
-
id?: string;
|
|
30
|
-
}
|
|
31
|
-
/** Mark a class as handling jobs on `queue`. The class is a DI singleton. */
|
|
32
|
-
declare function Job(queue: string): ClassDecorator;
|
|
33
|
-
/** Mark a method as handling `jobName` — or, without a name, every job its queue gets. */
|
|
34
|
-
declare function Process(jobName?: string): MethodDecorator;
|
|
35
|
-
/** One handler: its queue, job name (absent for a catch-all), class and method. */
|
|
36
|
-
interface JobHandler extends ProcessDefinition {
|
|
37
|
-
queue: string;
|
|
38
|
-
target: Function;
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Every `@Process` method of a `@Job` class the container can resolve.
|
|
42
|
-
* Classes it doesn't know (not in a module, or from before an HMR reload)
|
|
43
|
-
* are skipped.
|
|
44
|
-
*/
|
|
45
|
-
declare function listJobHandlers(container: {
|
|
46
|
-
has(token: unknown): boolean;
|
|
47
|
-
}): JobHandler[];
|
|
48
|
-
/** The queues something handles — what a runner subscribes to. */
|
|
49
|
-
declare function listJobQueues(container: {
|
|
50
|
-
has(token: unknown): boolean;
|
|
51
|
-
}): string[];
|
|
52
|
-
/** Thrown when a queue receives a job no `@Process` method handles. */
|
|
53
|
-
declare class NoJobHandlerError extends Error {
|
|
54
|
-
readonly queue: string;
|
|
55
|
-
readonly jobName: string;
|
|
56
|
-
constructor(queue: string, jobName: string);
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Run one job: pick the `@Process` method for `job.name` (or the queue's
|
|
60
|
-
* catch-all), resolve its class from the container and call it with `job`
|
|
61
|
-
* as given. A failure is reported to the error observers (`source: 'job'`)
|
|
62
|
-
* and rethrown, so the tool's own retry and dead-letter handling still
|
|
63
|
-
* applies. A job nothing handles throws {@link NoJobHandlerError} rather
|
|
64
|
-
* than being acknowledged and lost.
|
|
65
|
-
*/
|
|
66
|
-
declare function runJob(container: {
|
|
67
|
-
has(token: unknown): boolean;
|
|
68
|
-
resolve(token: unknown): unknown;
|
|
69
|
-
}, queue: string, job: JobLike,
|
|
70
|
-
/** Extra fields for the error report — e.g. the tool's attempt count. */
|
|
71
|
-
report?: Record<string, unknown>): Promise<unknown>;
|
|
72
|
-
/**
|
|
73
|
-
* Something about where a job was dispatched from that its handler should
|
|
74
|
-
* run with — the tenant, a trace id, the acting user. Captured when the job
|
|
75
|
-
* is dispatched, carried in its data, and restored around the handler.
|
|
76
|
-
*/
|
|
77
|
-
interface JobContextCarrier<T = unknown> {
|
|
78
|
-
/** Unique: the field it travels under. */
|
|
79
|
-
key: string;
|
|
80
|
-
/** The value to carry, or `undefined` for nothing. */
|
|
81
|
-
capture(): T | undefined;
|
|
82
|
-
/** Run the handler with the value back in place. */
|
|
83
|
-
restore<R>(value: T, run: () => R): R;
|
|
84
|
-
}
|
|
85
|
-
/** The field a job's data carries its context in. Removed before the handler sees the data. */
|
|
86
|
-
declare const JOB_CONTEXT_FIELD = "__kickContext";
|
|
87
|
-
/** Carry a value from dispatch to handler for every job. Registering a key again replaces it. */
|
|
88
|
-
declare function registerJobContext<T>(carrier: JobContextCarrier<T>): void;
|
|
89
|
-
/**
|
|
90
|
-
* `data` with the current job context added — for a {@link JobDispatcher}
|
|
91
|
-
* implementation to call before enqueueing. Any `__kickContext` already in
|
|
92
|
-
* `data` is removed first: only this call may set it, so a dispatcher that
|
|
93
|
-
* enqueues caller-supplied data without it lets that data choose the context. Only plain-object data can carry
|
|
94
|
-
* it; anything else, or nothing to carry, is returned as is.
|
|
95
|
-
*/
|
|
96
|
-
declare function stampJobContext<Data>(data: Data): Data;
|
|
97
|
-
/** Enqueue a job — implemented by whichever adapter runs the jobs. */
|
|
98
|
-
interface JobDispatcher {
|
|
99
|
-
dispatch<Data = unknown>(queue: string, name: string, data: Data, options?: Record<string, unknown>): Promise<unknown>;
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* The active job dispatcher. Inject it to enqueue without naming the tool:
|
|
103
|
-
* `@Inject(JOB_DISPATCHER) private jobs!: JobDispatcher`.
|
|
104
|
-
*/
|
|
105
|
-
declare const JOB_DISPATCHER: InjectionToken<JobDispatcher>;
|
|
106
|
-
//#endregion
|
|
107
|
-
//#region src/http/background.d.ts
|
|
108
|
-
/**
|
|
109
|
-
* Keep `promise` alive past the response. A rejection is logged (with the
|
|
110
|
-
* request id when called during a request), never left unhandled.
|
|
111
|
-
*
|
|
112
|
-
* @example
|
|
113
|
-
* ```ts
|
|
114
|
-
* @Post('/')
|
|
115
|
-
* async create(ctx: RequestContext) {
|
|
116
|
-
* const order = await this.orders.create(ctx.body)
|
|
117
|
-
* ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler
|
|
118
|
-
* return order
|
|
119
|
-
* }
|
|
120
|
-
* ```
|
|
121
|
-
*/
|
|
122
|
-
declare function waitUntil(promise: Promise<unknown>): void;
|
|
123
|
-
/**
|
|
124
|
-
* Resolve once every registered promise has settled — including work
|
|
125
|
-
* registered while waiting. Never rejects.
|
|
126
|
-
*/
|
|
127
|
-
declare function settleBackgroundWork(): Promise<void>;
|
|
128
|
-
/**
|
|
129
|
-
* The platform hook `createHandler()` and the web entry forward background
|
|
130
|
-
* work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`
|
|
131
|
-
* from `@vercel/functions` all have this shape.
|
|
132
|
-
*/
|
|
133
|
-
interface PlatformContext {
|
|
134
|
-
waitUntil?(promise: Promise<unknown>): void;
|
|
135
|
-
}
|
|
136
|
-
//#endregion
|
|
137
|
-
//#region src/http/reply.d.ts
|
|
138
|
-
declare const REPLY_BRAND: unique symbol;
|
|
139
|
-
/**
|
|
140
|
-
* A status-carrying response payload for return-value handlers. Create via
|
|
141
|
-
* {@link reply} — the brand is what runtimes detect, and the generics are
|
|
142
|
-
* what the `kick/routes` response typegen unwraps (`Reply<S, T>` → `T`).
|
|
143
|
-
*/
|
|
144
|
-
interface Reply<S extends number = number, T = unknown> {
|
|
145
|
-
readonly [REPLY_BRAND]: true;
|
|
146
|
-
readonly status: S;
|
|
147
|
-
readonly body: T;
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Wrap a return-value handler's payload with an explicit status code:
|
|
151
|
-
*
|
|
152
|
-
* ```ts
|
|
153
|
-
* @Post('/')
|
|
154
|
-
* async create(ctx: RequestContext) {
|
|
155
|
-
* return reply(201, await this.tasks.create(ctx.body))
|
|
156
|
-
* }
|
|
157
|
-
* ```
|
|
158
|
-
*/
|
|
159
|
-
declare function reply<S extends number, T>(status: S, body: T): Reply<S, T>;
|
|
160
|
-
declare namespace reply {
|
|
161
|
-
var ok: <T>(body: T) => Reply<200, T>;
|
|
162
|
-
var created: <T>(body: T) => Reply<201, T>;
|
|
163
|
-
var accepted: <T>(body: T) => Reply<202, T>;
|
|
164
|
-
var noContent: () => Reply<204, undefined>;
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* The statically-inferred response type of a controller handler — what
|
|
168
|
-
* `kick typegen` emits into `KickRoutes[...].response`:
|
|
169
|
-
*
|
|
170
|
-
* - `Awaited<ReturnType>` of the method
|
|
171
|
-
* - `Reply<S, T>` unwraps to `T`
|
|
172
|
-
* - `void`/`undefined` members are dropped (imperative `ctx.json` branches);
|
|
173
|
-
* a handler that never returns a value stays `unknown`, matching the
|
|
174
|
-
* pre-inference emission
|
|
175
|
-
*
|
|
176
|
-
* ```ts
|
|
177
|
-
* type R = InferHandlerResponse<UsersController['get']> // → User
|
|
178
|
-
* ```
|
|
179
|
-
*/
|
|
180
|
-
type InferHandlerResponse<H> = H extends ((...args: never[]) => infer R) ? [Exclude<Awaited<R>, void | undefined>] extends [never] ? unknown : UnwrapReply<Exclude<Awaited<R>, void | undefined>> : unknown;
|
|
181
|
-
type UnwrapReply<A> = A extends Reply<number, infer B> ? B : A extends RuntimeResponse ? unknown : A;
|
|
182
|
-
declare function isReply(value: unknown): value is Reply;
|
|
183
|
-
/**
|
|
184
|
-
* Key of the method a self-sending result carries. A returned value with
|
|
185
|
-
* `[RESPOND](ctx)` writes its own response — how an integration (an Inertia
|
|
186
|
-
* page, a rendered view) works as a return value without the framework
|
|
187
|
-
* knowing its format. Registry symbol, so a second copy of the package still
|
|
188
|
-
* matches.
|
|
189
|
-
*/
|
|
190
|
-
declare const RESPOND: unique symbol;
|
|
191
|
-
/** A handler return value that writes its own response. */
|
|
192
|
-
interface Respondable {
|
|
193
|
-
[RESPOND](ctx: RequestContext): void | PromiseLike<void>;
|
|
194
|
-
}
|
|
195
|
-
declare function isRespondable(value: unknown): value is Respondable;
|
|
196
|
-
/**
|
|
197
|
-
* Send a handler's RETURN value when the pipeline finished without anything
|
|
198
|
-
* having written a response. Callers guard on "driver/response unsettled" —
|
|
199
|
-
* this only decides how to send:
|
|
200
|
-
*
|
|
201
|
-
* - `undefined` → not handled (returns false; runtime keeps today's behavior)
|
|
202
|
-
* - `Respondable` → its `[RESPOND](ctx)` writes the response (may be async)
|
|
203
|
-
* - `Reply` wrapper → status + body (204 → `ctx.noContent()`)
|
|
204
|
-
* - anything else → `ctx.json(value)` (200)
|
|
205
|
-
*
|
|
206
|
-
* Returns true when a response was produced — a promise of it for an async
|
|
207
|
-
* `Respondable`, which callers await so its errors reach the error handler.
|
|
208
|
-
*/
|
|
209
|
-
declare function applyHandlerResult(ctx: RequestContext, result: unknown): boolean | Promise<boolean>;
|
|
210
|
-
//#endregion
|
|
211
|
-
//#region src/http/middleware/rate-limit-guard.d.ts
|
|
212
|
-
interface RateLimitGuardOptions {
|
|
213
|
-
/** Maximum number of requests per window (default: 100). */
|
|
214
|
-
max?: number;
|
|
215
|
-
/** Time window in milliseconds (default: 60_000). */
|
|
216
|
-
windowMs?: number;
|
|
217
|
-
/** Response message when the limit is exceeded (default: 'Too Many Requests'). */
|
|
218
|
-
message?: string;
|
|
219
|
-
/** HTTP status code when the limit is exceeded (default: 429). */
|
|
220
|
-
statusCode?: number;
|
|
221
|
-
/**
|
|
222
|
-
* Rate-limit key per request. Defaults to `ctx.ip`, falling back to
|
|
223
|
-
* `'global'`. Return a user/tenant id here for authenticated quotas.
|
|
224
|
-
*
|
|
225
|
-
* ::: warning Behind a proxy, configure `trustProxy` or every client shares
|
|
226
|
-
* one bucket
|
|
227
|
-
* On a node runtime `ctx.ip` is the runtime's vetted client address —
|
|
228
|
-
* Express derives it from `trust proxy`, Fastify from `trustProxy`. Without
|
|
229
|
-
* that setting it is the SOCKET address, which behind a load balancer or
|
|
230
|
-
* Cloudflare is the proxy's, so every caller lands in the same bucket and one
|
|
231
|
-
* noisy client exhausts the allowance for everyone.
|
|
232
|
-
*
|
|
233
|
-
* `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are
|
|
234
|
-
* deliberately not consulted here: `x-forwarded-for` is client-controllable
|
|
235
|
-
* unless a proxy overwrites it, so trusting it unconditionally would let a
|
|
236
|
-
* direct caller mint a fresh allowance per request by varying the header —
|
|
237
|
-
* evading the limit rather than enforcing it. The header chain
|
|
238
|
-
* (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the
|
|
239
|
-
* `@forinda/kickjs/web` edge entry, where there is no socket and the platform
|
|
240
|
-
* has already terminated the connection.
|
|
241
|
-
* :::
|
|
242
|
-
*/
|
|
243
|
-
keyGenerator?: (ctx: RequestContext) => string;
|
|
244
|
-
/** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */
|
|
245
|
-
headers?: boolean;
|
|
246
|
-
/**
|
|
247
|
-
* Counter backend. Defaults to a per-isolate in-memory map — fine for a
|
|
248
|
-
* single node process, useless on edge where isolates recycle: pass a
|
|
249
|
-
* `KvRateLimitStore` (or Redis-backed store) there.
|
|
250
|
-
*/
|
|
251
|
-
store?: RateLimitStore;
|
|
252
|
-
/** Skip limiting for a request (health checks, allowlists). */
|
|
253
|
-
skip?: (ctx: RequestContext) => boolean;
|
|
254
|
-
/**
|
|
255
|
-
* Skip limiting on routes carrying a route flag — a name, a list of names
|
|
256
|
-
* (any-of), or a predicate. Declared on the route rather than restated as a
|
|
257
|
-
* path here, so it cannot drift when `apiPrefix` or a module's `version`
|
|
258
|
-
* changes:
|
|
259
|
-
*
|
|
260
|
-
* ```ts
|
|
261
|
-
* const Public = defineRouteFlag('auth.public')
|
|
262
|
-
* rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })
|
|
263
|
-
* ```
|
|
264
|
-
*
|
|
265
|
-
* Only meaningful where a route has been matched — as `@Middleware()` on a
|
|
266
|
-
* class or method, or in `createWebApp({ middleware })`. Mounted app-wide
|
|
267
|
-
* ahead of routing there is no route to read, and nothing is exempted.
|
|
268
|
-
*/
|
|
269
|
-
exemptWhen?: RouteFlagTest;
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* Rate limiting as a `(ctx, next)` middleware.
|
|
273
|
-
*
|
|
274
|
-
* ```ts
|
|
275
|
-
* // Edge (Cloudflare Workers) — app-wide:
|
|
276
|
-
* const app = createWebApp({
|
|
277
|
-
* h3, modules,
|
|
278
|
-
* middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],
|
|
279
|
-
* })
|
|
280
|
-
*
|
|
281
|
-
* // Any runtime — per controller/route:
|
|
282
|
-
* @Middleware(rateLimitGuard({ max: 10 }))
|
|
283
|
-
* @Post('/login')
|
|
284
|
-
* ```
|
|
285
|
-
*/
|
|
286
|
-
declare function rateLimitGuard(options?: RateLimitGuardOptions): MiddlewareHandler;
|
|
287
|
-
//#endregion
|
|
288
|
-
//#region src/http/middleware/kv-stores.d.ts
|
|
289
|
-
/**
|
|
290
|
-
* The minimal async KV surface both stores need. Structurally compatible
|
|
291
|
-
* with a Cloudflare Workers `KVNamespace` binding — pass it straight in:
|
|
292
|
-
*
|
|
293
|
-
* ```ts
|
|
294
|
-
* export default {
|
|
295
|
-
* fetch(req: Request, env: Env) {
|
|
296
|
-
* const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })
|
|
297
|
-
* // ...
|
|
298
|
-
* },
|
|
299
|
-
* }
|
|
300
|
-
* ```
|
|
301
|
-
*
|
|
302
|
-
* Anything with the same shape works too (Deno KV wrapper, Upstash Redis
|
|
303
|
-
* REST client adapter, a Map-backed fake in tests).
|
|
304
|
-
*/
|
|
305
|
-
interface KvLike {
|
|
306
|
-
get(key: string): Promise<string | null>;
|
|
307
|
-
put(key: string, value: string, options?: {
|
|
308
|
-
expirationTtl?: number;
|
|
309
|
-
}): Promise<void>;
|
|
310
|
-
delete(key: string): Promise<void>;
|
|
311
|
-
}
|
|
312
|
-
interface KvRateLimitStoreOptions {
|
|
313
|
-
/** Window length in ms — must match the `windowMs` given to the limiter. */
|
|
314
|
-
windowMs: number;
|
|
315
|
-
/** Key prefix in the KV namespace (default `'rl:'`). */
|
|
316
|
-
prefix?: string;
|
|
317
|
-
}
|
|
318
|
-
/**
|
|
319
|
-
* {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments
|
|
320
|
-
* where in-memory counters reset on every isolate.
|
|
321
|
-
*
|
|
322
|
-
* KV is eventually consistent and this is a read-modify-write counter, so
|
|
323
|
-
* limiting is **approximate** under concurrency — bursts racing across
|
|
324
|
-
* isolates can each read the same count. That is the accepted trade-off for
|
|
325
|
-
* abuse throttling; use a Durable Object / Redis store when you need an
|
|
326
|
-
* exact ceiling (billing quotas, strict per-key locks).
|
|
327
|
-
*/
|
|
328
|
-
declare class KvRateLimitStore implements RateLimitStore {
|
|
329
|
-
private readonly kv;
|
|
330
|
-
private readonly prefix;
|
|
331
|
-
private readonly windowMs;
|
|
332
|
-
constructor(kv: KvLike, options: KvRateLimitStoreOptions);
|
|
333
|
-
increment(key: string): Promise<{
|
|
334
|
-
totalHits: number;
|
|
335
|
-
resetTime: Date;
|
|
336
|
-
}>;
|
|
337
|
-
decrement(key: string): Promise<void>;
|
|
338
|
-
reset(key: string): Promise<void>;
|
|
339
|
-
private read;
|
|
340
|
-
private write;
|
|
341
|
-
}
|
|
342
|
-
interface KvSessionStoreOptions {
|
|
343
|
-
/** Key prefix in the KV namespace (default `'sess:'`). */
|
|
344
|
-
prefix?: string;
|
|
345
|
-
}
|
|
346
|
-
/**
|
|
347
|
-
* {@link SessionStore} over a {@link KvLike} namespace. Plug into the node
|
|
348
|
-
* `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via
|
|
349
|
-
* REST) so sessions survive restarts and horizontal scaling; TTL expiry is
|
|
350
|
-
* delegated to the KV layer via `expirationTtl`.
|
|
351
|
-
*
|
|
352
|
-
* Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only
|
|
353
|
-
* refresh), so `session({ rolling: true })` doubles KV operations per
|
|
354
|
-
* request — per-operation-billed platforms may prefer `rolling: false`.
|
|
355
|
-
*/
|
|
356
|
-
declare class KvSessionStore implements SessionStore {
|
|
357
|
-
private readonly kv;
|
|
358
|
-
private readonly prefix;
|
|
359
|
-
constructor(kv: KvLike, options?: KvSessionStoreOptions);
|
|
360
|
-
get(sid: string): Promise<SessionData | null>;
|
|
361
|
-
set(sid: string, data: SessionData, maxAge: number): Promise<void>;
|
|
362
|
-
destroy(sid: string): Promise<void>;
|
|
363
|
-
touch(sid: string, maxAge: number): Promise<void>;
|
|
364
|
-
}
|
|
365
|
-
//#endregion
|
|
366
|
-
export { listJobHandlers as A, JobContextCarrier as C, NoJobHandlerError as D, JobLike as E, registerJobContext as M, runJob as N, Process as O, stampJobContext as P, Job as S, JobHandler as T, settleBackgroundWork as _, KvSessionStoreOptions as a, JOB_DISPATCHER as b, InferHandlerResponse as c, Respondable as d, applyHandlerResult as f, PlatformContext as g, reply as h, KvSessionStore as i, listJobQueues as j, ProcessDefinition as k, RESPOND as l, isRespondable as m, KvRateLimitStore as n, RateLimitGuardOptions as o, isReply as p, KvRateLimitStoreOptions as r, rateLimitGuard as s, KvLike as t, Reply as u, waitUntil as v, JobDispatcher as w, JOB_META as x, JOB_CONTEXT_FIELD as y };
|
|
367
|
-
//# sourceMappingURL=kv-stores-Co5k2PYA.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kv-stores-Co5k2PYA.d.mts","names":["_$__token0.InjectionToken"],"sources":["../src/core/jobs.ts","../src/http/background.ts","../src/http/reply.ts","../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"mappings":";;;;;;;;;cA6Ba;WACX;WACA;;;UAIe;;EAEf;;EAEA;;;;;;;UAQe,QAAQ;EACvB;EACA,MAAM;EACN;;;iBAUc,IAAI,gBAAgB;;iBASpB,QAAQ,mBAAmB;;UAU1B,mBAAmB;EAClC;EACA,QAAQ;;;;;;;iBAQM,gBAAgB;EAAa,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AMA,QAAQ;;EAER,QAAQ,KAAK;;;;;;;;;;;;;;;;EAgBb,aAAa;;;;;;;;;;;;;;;;;iBA0DC,eAAe,UAAS,wBAA6B;;;;;;;;;;;;;;;;;;;UCxGpD;EACf,IAAI,cAAc;EAClB,IAAI,aAAa,eAAe;IAAY;MAA2B;EACvE,OAAO,cAAc;;UAQN;;EAEf;;EAEA;;;;;;;;;;;;cAaW,4BAA4B;mBAKpB;mBAJF;mBACA;EAEjB,YACmB,IAAI,QACrB,SAAS;EAML,UAAU,cAAc;IAAU;IAAmB,WAAW;;EAahE,UAAU,cAAc;EAQxB,MAAM,cAAc;UAIZ;UAUA;;UAOC;;EAEf;;;;;;;;;;;;cAaW,0BAA0B;mBAIlB;mBAHF;EAEjB,YACmB,IAAI,QACrB,UAAS;EAKL,IAAI,cAAc,QAAQ;EAU1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EAMrD,QAAQ,cAAc;EAItB,MAAM,aAAa,iBAAiB"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.1.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{n as assertFlagTest,s as matchesFlagTest}from"./route-flag-BWuvJsGZ.mjs";var LazyMemoryStore=class{windowMs;hits=/* @__PURE__ */ new Map;constructor(windowMs){this.windowMs=windowMs}async increment(key){let now=Date.now(),entry=this.hits.get(key);if(entry&&entry.reset>now)return entry.hits++,{totalHits:entry.hits,resetTime:new Date(entry.reset)};if(this.hits.size>1e4)for(let[k,e]of this.hits)e.reset<=now&&this.hits.delete(k);let fresh={hits:1,reset:now+this.windowMs};return this.hits.set(key,fresh),{totalHits:1,resetTime:new Date(fresh.reset)}}async decrement(key){let entry=this.hits.get(key);entry&&entry.hits>0&&entry.hits--}async reset(key){this.hits.delete(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),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-DsfVy2fk.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kv-stores-DsfVy2fk.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'\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/** Timer-free in-memory store: sweeps expired entries when the map grows. */\nclass LazyMemoryStore implements RateLimitStore {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n\n constructor(private readonly windowMs: number) {}\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n // ponytail: sweep-on-growth instead of a cleanup interval — no timer to\n // dispose, edge-safe. Bound is 10k live keys before a full sweep.\n if (this.hits.size > 10_000) {\n for (const [k, e] of this.hits) if (e.reset <= now) this.hits.delete(k)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.hits.get(key)\n if (entry && entry.hits > 0) entry.hits--\n }\n\n async reset(key: string): Promise<void> {\n this.hits.delete(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)\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":";;;;;;;;;;gFAuEA,IAAM,gBAAN,KAAgD,CAGjB,SAF7B,qBAAwB,IAAI,IAE5B,YAAY,SAAmC,CAAlB,KAAA,SAAA,QAAmB,CAEhD,MAAM,UAAU,IAA8D,CAC5E,IAAM,IAAM,KAAK,IAAI,EACf,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC/B,GAAI,OAAS,MAAM,MAAQ,IAEzB,MADA,OAAM,OACC,CAAE,UAAW,MAAM,KAAM,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,EAInE,GAAI,KAAK,KAAK,KAAO,IACd,IAAA,GAAM,CAAC,EAAG,KAAM,KAAK,KAAU,EAAE,OAAS,KAAK,KAAK,KAAK,OAAO,CAAC,EAExE,IAAM,MAAQ,CAAE,KAAM,EAAG,MAAO,IAAM,KAAK,QAAS,EAEpD,OADA,KAAK,KAAK,IAAI,IAAK,KAAK,EACjB,CAAE,UAAW,EAAG,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,CAC1D,CAEA,MAAM,UAAU,IAA4B,CAC1C,IAAM,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC3B,OAAS,MAAM,KAAO,GAAG,MAAM,MACrC,CAEA,MAAM,MAAM,IAA4B,CACtC,KAAK,KAAK,OAAO,GAAG,CACtB,CACF,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EA,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,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.1.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};export{MutableModuleRegistry as t};
|
|
12
|
-
//# sourceMappingURL=module-registry-Daf_P2oD.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"module-registry-Daf_P2oD.mjs","names":[],"sources":["../src/core/module-registry.ts"],"sourcesContent":["import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n"],"mappings":";;;;;;;;;;AAwDA,IAAa,sBAAb,KAA6D,CAC3D,QAAqC,CAAC,EAEtC,MAAM,OAA8B,CAClC,KAAK,QAAQ,KAAK,MAAM,CAC1B,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit-Bwed3jOV.d.mts","names":[],"sources":["../src/http/middleware/rate-limit.ts"],"mappings":";;;;UAQiB;EACf,UAAU,cAAc;IAAU;IAAmB,WAAW;;EAChE,UAAU,cAAc;EACxB,MAAM,cAAc;;UAGL;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB,KAAK;;EAErB;;EAEA,QAAQ;;EAER,QAAQ,KAAK;;EAEb;;;;;;;;;;;;;;;;;;;EAmBA,aAAa;;;;;;;;;;;;;;;;;;;;;;iBAsFC,UAAU,UAAS,oBAAqB,KAwB1B,SAAO,KAAO,UAAQ,MAAQ,iBAAY"}
|
package/dist/reply-BDK9xt7Z.mjs
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.1.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{METADATA}from"./core/interfaces.mjs";import{createLogger}from"./core/logger.mjs";import{n as getClassMetaOrUndefined}from"./metadata-zvd6AWkE.mjs";import{HttpException}from"./core/errors.mjs";import{d as requestStore}from"./context-CtL9RxXp.mjs";function normalizeMediaType(contentType){return((Array.isArray(contentType)?contentType[0]:contentType)??``).split(`;`)[0].trim().toLowerCase()}function isJsonMediaType(mediaType){return mediaType===`application/json`||/^application\/[\w.+-]+\+json$/.test(mediaType)}function classifyMediaType(contentType){let mediaType=normalizeMediaType(contentType);return mediaType?isJsonMediaType(mediaType)?`json`:mediaType===`application/x-www-form-urlencoded`?`urlencoded`:mediaType.startsWith(`multipart/`)?`multipart`:mediaType.startsWith(`text/`)?`text`:`unsupported`:`unsupported`}const EXPRESS_JSON_TYPES=[`application/json`,`application/*+json`],SUPPORTED_BODY_TYPES=[`application/json`,`application/*+json`,`application/x-www-form-urlencoded`,`text/*`,`multipart/form-data`];function unsupportedMediaTypeError(contentType){let mediaType=normalizeMediaType(contentType);return new HttpException(415,mediaType?`Unsupported Media Type: ${mediaType}`:`Unsupported Media Type: request has a body but no Content-Type`,void 0,{Accept:SUPPORTED_BODY_TYPES.join(`, `)})}const BODY_METHODS=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);function rejectUnsupportedBody(){return(req,_res,next)=>{if(!BODY_METHODS.has((req.method??`GET`).toUpperCase())||classifyMediaType(req.headers?.[`content-type`])!==`unsupported`)return next();let reject=()=>next(unsupportedMediaTypeError(req.headers?.[`content-type`])),length=req.headers?.[`content-length`];if(length!==void 0)return length===`0`?next():reject();if(req.headers?.[`transfer-encoding`]===void 0)return next();let decided=!1,settle=fn=>()=>{decided||(decided=!0,req.off?.(`data`,onData),req.off?.(`end`,onEnd),fn())},onData=settle(reject),onEnd=settle(()=>next());req.on?.(`data`,onData),req.on?.(`end`,onEnd)}}const log=createLogger(`RequestScope`),preDestroyCache=/* @__PURE__ */ new Map;function preDestroyMethod(ctor){let method=preDestroyCache.get(ctor);return method===void 0&&(method=getClassMetaOrUndefined(METADATA.PRE_DESTROY,ctor.prototype)??null,preDestroyCache.set(ctor,method)),method}function disposeRequestStore(store){if(!store.disposed&&(store.disposed=!0,store.instances.size!==0)){for(let instance of store.instances.values()){if(typeof instance!=`object`||!instance)continue;let method=preDestroyMethod(instance.constructor);if(method&&typeof instance[method]==`function`)try{let result=instance[method]();result&&typeof result.then==`function`&&result.catch(err=>log.error(err,`@PreDestroy on ${instance.constructor.name} rejected`))}catch(err){log.error(err,`@PreDestroy on ${instance.constructor.name} threw`)}}store.instances.clear()}}const REQUEST_SCOPE_MIDDLEWARE_MARKER=Symbol.for(`@kickjs/requestScopeMiddleware`);function createRequestStore(requestId){return{requestId:requestId||crypto.randomUUID(),instances:/* @__PURE__ */ new Map,values:/* @__PURE__ */ new Map}}function requestScopeMiddleware(){let mw=(req,res,next)=>{let requestIdHeader=req.headers[`x-request-id`],requestId=(Array.isArray(requestIdHeader)?requestIdHeader[0]:requestIdHeader)||crypto.randomUUID(),store=createRequestStore(requestId);req.requestId=requestId,res.once(`close`,()=>disposeRequestStore(store)),requestStore.run(store,next)};return mw[REQUEST_SCOPE_MIDDLEWARE_MARKER]=!0,mw}function isRequestScopeMiddleware(value){return typeof value==`function`&&value[REQUEST_SCOPE_MIDDLEWARE_MARKER]===!0}const REPLY_BRAND=Symbol.for(`kickjs.reply`);function reply(status,body){return{[REPLY_BRAND]:!0,status,body}}reply.ok=body=>reply(200,body),reply.created=body=>reply(201,body),reply.accepted=body=>reply(202,body),reply.noContent=()=>reply(204,void 0);function isReply(value){return typeof value==`object`&&!!value&&value[REPLY_BRAND]===!0}const RESPOND=Symbol.for(`kickjs.respond`);function isRespondable(value){return typeof value==`object`&&!!value&&typeof value[RESPOND]==`function`}function applyHandlerResult(ctx,result){if(result===void 0)return!1;if(isRespondable(result)){let sent=result[RESPOND](ctx);return typeof sent?.then!=`function`||Promise.resolve(sent).then(()=>!0)}return isReply(result)?result.status===204?(ctx.noContent(),!0):(ctx.json(result.body,result.status),!0):(ctx.json(result),!0)}export{reply as a,isRequestScopeMiddleware as c,classifyMediaType as d,rejectUnsupportedBody as f,isRespondable as i,requestScopeMiddleware as l,applyHandlerResult as n,createRequestStore as o,unsupportedMediaTypeError as p,isReply as r,disposeRequestStore as s,RESPOND as t,EXPRESS_JSON_TYPES as u};
|
|
12
|
-
//# sourceMappingURL=reply-BDK9xt7Z.mjs.map
|