@forinda/kickjs 8.4.0 → 8.6.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-989ssCBx.d.mts → adapter-2bnoYEPX.d.mts} +38 -8
- package/dist/{adapter-989ssCBx.d.mts.map → adapter-2bnoYEPX.d.mts.map} +1 -1
- package/dist/{app-module-OQsddkor.d.mts → app-module-DCA65GZZ.d.mts} +2 -2
- package/dist/{app-module-OQsddkor.d.mts.map → app-module-DCA65GZZ.d.mts.map} +1 -1
- package/dist/application-DZiG1QCw.mjs +12 -0
- package/dist/application-DZiG1QCw.mjs.map +1 -0
- package/dist/{application-C2WveUZr.d.mts → application-_QOiAVx2.d.mts} +90 -15
- package/dist/application-_QOiAVx2.d.mts.map +1 -0
- package/dist/{bootstrap-DHftqJ1m.mjs → bootstrap-BEbka3UV.mjs} +3 -3
- package/dist/{bootstrap-DHftqJ1m.mjs.map → bootstrap-BEbka3UV.mjs.map} +1 -1
- package/dist/{client-ip-D9nKcjVJ.mjs → client-ip-DF_smNX7.mjs} +2 -2
- package/dist/{client-ip-D9nKcjVJ.mjs.map → client-ip-DF_smNX7.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-pot4-2DS.mjs → config-CIOXZmLS.mjs} +3 -3
- package/dist/{config-pot4-2DS.mjs.map → config-CIOXZmLS.mjs.map} +1 -1
- package/dist/{container-BB_XC2ww.mjs → container-DF8FRoY8.mjs} +3 -3
- package/dist/{container-BB_XC2ww.mjs.map → container-DF8FRoY8.mjs.map} +1 -1
- package/dist/{context-Xd8C4fIo.mjs → context-BTqeZH1A.mjs} +3 -3
- package/dist/{context-Xd8C4fIo.mjs.map → context-BTqeZH1A.mjs.map} +1 -1
- package/dist/{context-errors-doMQ4bAU.mjs → context-errors-Ch0DuUQo.mjs} +2 -2
- package/dist/{context-errors-doMQ4bAU.mjs.map → context-errors-Ch0DuUQo.mjs.map} +1 -1
- package/dist/{contributor-runner-DflutMFy.mjs → contributor-runner-DujKZy4N.mjs} +3 -3
- package/dist/{contributor-runner-DflutMFy.mjs.map → contributor-runner-DujKZy4N.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.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.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/{core-CTyRc4AM.mjs → core-y8QbzHM5.mjs} +3 -3
- package/dist/{core-CTyRc4AM.mjs.map → core-y8QbzHM5.mjs.map} +1 -1
- package/dist/{csrf-DDwUOF45.d.mts → csrf-C4MwaMp4.d.mts} +2 -2
- package/dist/{csrf-DDwUOF45.d.mts.map → csrf-C4MwaMp4.d.mts.map} +1 -1
- package/dist/{csrf-CMzwva6A.mjs → csrf-RP5hgc0c.mjs} +3 -3
- package/dist/{csrf-CMzwva6A.mjs.map → csrf-RP5hgc0c.mjs.map} +1 -1
- package/dist/{decorate-BbFyJ1kh.mjs → decorate-D85rEnU-.mjs} +1 -1
- package/dist/{define-adapter-CsDcNhlh.mjs → define-adapter-C1Db6xfO.mjs} +2 -2
- package/dist/{define-adapter-CsDcNhlh.mjs.map → define-adapter-C1Db6xfO.mjs.map} +1 -1
- package/dist/{disposables-CZ7vf6L_.mjs → disposables-CEAxve3A.mjs} +2 -2
- package/dist/{disposables-CZ7vf6L_.mjs.map → disposables-CEAxve3A.mjs.map} +1 -1
- package/dist/{env-BTOmTNsH.mjs → env-BelmDj19.mjs} +3 -3
- package/dist/{env-BTOmTNsH.mjs.map → env-BelmDj19.mjs.map} +1 -1
- package/dist/{error-handler-BNpeUs-0.d.mts → error-handler-C1uWVGVY.d.mts} +2 -2
- package/dist/{error-handler-BNpeUs-0.d.mts.map → error-handler-C1uWVGVY.d.mts.map} +1 -1
- package/dist/{handler-8OeK5Hkh.mjs → handler-DHlakr0v.mjs} +3 -3
- package/dist/{handler-8OeK5Hkh.mjs.map → handler-DHlakr0v.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- 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/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.d.mts +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- 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.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.d.mts +1 -1
- package/dist/http/runtimes/h3-web.d.mts.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs.map +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/index.d.mts +11 -11
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{kv-stores-C755yuvc.mjs → kv-stores-DUFcps01.mjs} +3 -3
- package/dist/{kv-stores-C755yuvc.mjs.map → kv-stores-DUFcps01.mjs.map} +1 -1
- package/dist/{kv-stores-Dijnf9sF.d.mts → kv-stores-Dx5RvIaP.d.mts} +4 -4
- package/dist/{kv-stores-Dijnf9sF.d.mts.map → kv-stores-Dx5RvIaP.d.mts.map} +1 -1
- package/dist/{metadata-C_bLigwT.mjs → metadata-B8_KXybT.mjs} +2 -2
- package/dist/{metadata-C_bLigwT.mjs.map → metadata-B8_KXybT.mjs.map} +1 -1
- package/dist/{module-registry-B_gw6smc.mjs → module-registry-BFrJ1PQ4.mjs} +2 -2
- package/dist/{module-registry-B_gw6smc.mjs.map → module-registry-BFrJ1PQ4.mjs.map} +1 -1
- package/dist/{query-B7_CJZaf.mjs → query-CC7o6I5K.mjs} +2 -2
- package/dist/{query-B7_CJZaf.mjs.map → query-CC7o6I5K.mjs.map} +1 -1
- package/dist/{rate-limit-D5FHbYKG.d.mts → rate-limit-Bwed3jOV.d.mts} +2 -2
- package/dist/{rate-limit-D5FHbYKG.d.mts.map → rate-limit-Bwed3jOV.d.mts.map} +1 -1
- package/dist/{respond-EdWjQfD6.mjs → respond-B-EDymxF.mjs} +2 -2
- package/dist/{respond-EdWjQfD6.mjs.map → respond-B-EDymxF.mjs.map} +1 -1
- package/dist/{route-flag-BMlwj3Nk.d.mts → route-flag-B1lQht6v.d.mts} +14 -2
- package/dist/{route-flag-BMlwj3Nk.d.mts.map → route-flag-B1lQht6v.d.mts.map} +1 -1
- package/dist/{route-flag-C7AilXtr.mjs → route-flag-B4sNP7zH.mjs} +3 -3
- package/dist/{route-flag-C7AilXtr.mjs.map → route-flag-B4sNP7zH.mjs.map} +1 -1
- package/dist/{route-policy-BQfQEuFn.mjs → route-policy-CDlMbl1b.mjs} +2 -2
- package/dist/{route-policy-BQfQEuFn.mjs.map → route-policy-CDlMbl1b.mjs.map} +1 -1
- package/dist/{router-builder-DPrRk4Pv.d.mts → router-builder-C6gmK0nZ.d.mts} +3 -3
- package/dist/{router-builder-DPrRk4Pv.d.mts.map → router-builder-C6gmK0nZ.d.mts.map} +1 -1
- package/dist/{router-builder-CFAHKq4e.mjs → router-builder-cTsA2XtO.mjs} +3 -3
- package/dist/{router-builder-CFAHKq4e.mjs.map → router-builder-cTsA2XtO.mjs.map} +1 -1
- package/dist/{runtime-B2oXJDwr.mjs → runtime-C-7Yhs7a.mjs} +3 -3
- package/dist/{runtime-B2oXJDwr.mjs.map → runtime-C-7Yhs7a.mjs.map} +1 -1
- package/dist/{upload-DwGoAQ6R.d.mts → upload-TW2ZuECF.d.mts} +2 -2
- package/dist/{upload-DwGoAQ6R.d.mts.map → upload-TW2ZuECF.d.mts.map} +1 -1
- package/dist/{upload-config-C23IAKGT.mjs → upload-config-CoE6BzM4.mjs} +2 -2
- package/dist/{upload-config-C23IAKGT.mjs.map → upload-config-CoE6BzM4.mjs.map} +1 -1
- package/dist/web.d.mts +3 -3
- package/dist/web.mjs +2 -2
- package/package.json +8 -8
- package/dist/application-Bm3wCm06.mjs +0 -12
- package/dist/application-Bm3wCm06.mjs.map +0 -1
- package/dist/application-C2WveUZr.d.mts.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{r as registerDisposable}from"../../disposables-
|
|
11
|
+
import{r as registerDisposable}from"../../disposables-CEAxve3A.mjs";import{i as setCookie,t as parseCookieHeader}from"../../respond-B-EDymxF.mjs";import{createHmac,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=new Map;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),null):entry.data:null}async set(sid,data,maxAge){this.sessions.set(sid,{data,expires:Date.now()+maxAge})}async destroy(sid){this.sessions.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge)}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&this.sessions.delete(sid)}};function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secret){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),providedSig=raw.slice(dotIndex+1),expectedSig=createHmac(`sha256`,secret).update(value).digest(`base64url`),a=Buffer.from(providedSig),b=Buffer.from(expectedSig);return a.length!==b.length||!timingSafeEqual(a,b)?!1:value}function session(options){let{secret,cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,store=new MemoryStore,cookie:cookieOpts={}}=options,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??process.env.NODE_ENV===`production`,sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1;signedCookie&&(sid=unsign(signedCookie,secret),sid&&(sessionData=await store.get(sid))),(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,res.clearCookie(cookieName,{path:cookieDefaults.path})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||(!isNew||saveUninitialized||Object.keys(currentData).length!==0)&&(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),rolling&&!isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}export{session};
|
|
12
12
|
//# sourceMappingURL=session.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { d as SpaAdapter, f as SpaAdapterOptions, p as resolveClientDir } from "../../application-
|
|
2
|
+
import { d as SpaAdapter, f as SpaAdapterOptions, p as resolveClientDir } from "../../application-_QOiAVx2.mjs";
|
|
3
3
|
export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{Logger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import"../../core-y8QbzHM5.mjs";import{t as defineAdapter}from"../../define-adapter-C1Db6xfO.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=new Set;function snapshotClientDir(){let paths=new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);if(!existsSync(indexPath)){log.warn(`index.html not found in ${clientDir}`);return}indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
|
|
12
12
|
//# sourceMappingURL=spa.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-
|
|
2
|
+
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-TW2ZuECF.mjs";
|
|
3
3
|
export { type RawUploadPart, UploadOptions, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{HttpException,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-
|
|
11
|
+
import{HttpException,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-CoE6BzM4.mjs";import{createRequire}from"node:module";import{unlink}from"node:fs/promises";const requireFromHere=createRequire(import.meta.url);let _multer;function loadMulter(){if(_multer)return _multer;try{return _multer=requireFromHere(`multer`),_multer}catch{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed.
|
|
12
12
|
Install it as a peer dependency: pnpm add multer (or npm i multer / yarn add multer).`)}}function translateMulterErrors(mw,options){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}next(err)})}}function createMulter(options){let limits={fileSize:options.maxSize??5242880},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}};return loadMulter()(multerOptions)}function single(fieldName,options={}){return translateMulterErrors(createMulter(options).single(fieldName),options)}function array(fieldName,maxCount=10,options={}){return translateMulterErrors(createMulter(options).array(fieldName,maxCount),options)}function none(options={}){return translateMulterErrors(createMulter(options).none(),options)}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
|
|
13
13
|
//# sourceMappingURL=upload.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{Logger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import"../../core-y8QbzHM5.mjs";import{t as defineAdapter}from"../../define-adapter-C1Db6xfO.mjs";import{resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app}){let{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,resolve(viewsDir)),log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)}})});export{ViewAdapter};
|
|
12
12
|
//# sourceMappingURL=views.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{a as 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-
|
|
11
|
+
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-CC7o6I5K.mjs";export{FILTER_OPERATORS,buildQueryParams,getQueryParsingDefaults,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,resetQueryParsingDefaults,setQueryParsingDefaults};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-
|
|
2
|
+
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-C6gmK0nZ.mjs";
|
|
3
3
|
export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"../router-builder-
|
|
11
|
+
import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"../router-builder-cTsA2XtO.mjs";export{_setExternalContributorSources,assertRouteUnique,buildRouteTable};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{HttpException}from"../../core/errors.mjs";import{a as createRequestStore,f as unsupportedMediaTypeError,n as applyHandlerResult,o as disposeRequestStore,t as publishMatchedRoute}from"../../runtime-
|
|
11
|
+
import{HttpException}from"../../core/errors.mjs";import{a as createRequestStore,f as unsupportedMediaTypeError,n as applyHandlerResult,o as disposeRequestStore,t as publishMatchedRoute}from"../../runtime-C-7Yhs7a.mjs";import{i as requestStore,t as RequestContext}from"../../context-BTqeZH1A.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-CoE6BzM4.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),loadPeer=name=>{let mod=peerRequire(name);return mod&&mod.__esModule&&mod.default?mod.default:mod.default??mod},QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}setHeader(name,value){return this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.end(data),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
|
|
12
12
|
Install it as a peer dependency: pnpm add @fastify/multipart.`);let rawParts=[],fields={};for await(let part of request.parts())part.type===`file`&&part.toBuffer?rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer:await part.toBuffer()}):fields[part.fieldname]=part.value;let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...fields}}let headerId=raw.headers[`x-request-id`],requestId=(Array.isArray(headerId)?headerId[0]:headerId)||raw.requestId,store=createRequestStore(requestId);raw.requestId=store.requestId,reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(raw,entry);let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),reply.sent))return;validator&&await new Promise((resolve,reject)=>{validator(raw,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||reply.sent)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),reply.sent)return;let result=await entry.handler(ctx);reply.sent||applyHandlerResult(ctx,result)})}}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=loadPeer(`fastify`)({logger:!1,routerOptions:{ignoreTrailingSlash:!0},trustProxy:typeof options.trustProxy!=`function`&&options.trustProxy});app[QUEUE]=[];let addParser=app.addContentTypeParser?.bind(app);return addParser&&(addParser(/^application\/[\w.+-]+\+json$/,{parseAs:`string`},(_req,body,done)=>{if(body===``)return done(null,void 0);try{done(null,JSON.parse(body))}catch(err){done(HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`),void 0)}}),addParser(`application/x-www-form-urlencoded`,{parseAs:`string`},(_req,body,done)=>{done(null,Object.fromEntries(new URLSearchParams(body)))}),addParser(/^text\//,{parseAs:`string`},(_req,body,done)=>{done(null,body)}),addParser(`*`,{parseAs:`string`},(req,body,done)=>{if(!body)return done(null,void 0);done(unsupportedMediaTypeError(req.headers?.[`content-type`]),void 0)})),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=loadPeer(`@fastify/multipart`);await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=loadPeer(`@fastify/middie`);await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY];return(req,res,next)=>{next&&(req[NEXT]=next),readyP.then(()=>app.routing(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){let serveStatic=loadPeer(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];if(next){reply.hijack(),next();return}mw(request.raw,replyDriver(reply),NOOP_NEXT)})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{mw(err,request.raw,replyDriver(reply),NOOP_NEXT)})},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{fastifyRuntime};
|
|
13
13
|
//# sourceMappingURL=fastify.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"h3-web.d.mts","names":[],"sources":["../../../src/http/runtimes/h3-web.ts"],"mappings":";;;;UA0CU;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-web.d.mts","names":[],"sources":["../../../src/http/runtimes/h3-web.ts"],"mappings":";;;;UA0CU;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;;;;;;wBA4Rc,aAAa,UAAS,sBAA2B,YAAY;;;;;iBAiH5D;EACf,SAAS;EACT,UAAU;EACV"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger,describeError}from"../../core/logger.mjs";import{n as WebRequestShim,r as WebResponseDriver,t as compileWebRoute}from"../../handler-
|
|
11
|
+
import{createLogger,describeError}from"../../core/logger.mjs";import{n as WebRequestShim,r as WebResponseDriver,t as compileWebRoute}from"../../handler-DHlakr0v.mjs";import{createRequire}from"node:module";const log=createLogger(`H3WebRuntime`),peerRequire=createRequire(import.meta.url),NOTFOUND_MW=Symbol(`kickjs.h3web.notFoundMw`),ERROR_MW=Symbol(`kickjs.h3web.errorMw`),ASSEMBLED=Symbol(`kickjs.h3web.assembled`),NOOP_NEXT=()=>{};function loadH3v2(injected){let m=injected??peerRequire(`h3`),resolved=m&&m.__esModule&&m.default?{...m.default,...m}:m;if(typeof resolved.H3!=`function`)throw Error("@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), but the installed h3 has no H3 class — that is the v1 line. Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.");return resolved}async function runConnectTerminal(mw,event,err){let req=new WebRequestShim(event.req,event.url),driver=new WebResponseDriver(event.req.signal);return mw&&(err===void 0?mw(req,driver,NOOP_NEXT):mw(err,req,driver,NOOP_NEXT)),driver.settled||(err===void 0?driver.status(404).json({error:`Not Found`}):(log.error(err,`h3-web: error handler did not settle the response — ${describeError(err)}`),driver.status(500).json({error:`Internal Server Error`,...typeof process<`u`&&process.env?.NODE_ENV===`production`?{}:{message:describeError(err)}}))),driver.ready}const FETCH_CONNECT=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(){for(let event of[`finish`,`close`]){for(let[e,listener]of this.listeners)e===event&&listener();this.listeners=this.listeners.filter(([e])=>e!==event)}}};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(),resolve(withConnectHeaders(event,response))},fail=err=>{res.done(),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(),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 mw=state[NOTFOUND_MW];return runConnectTerminal(mw,event)}))}function h3WebRuntime(options={}){let{H3,toNodeHandler,fromNodeHandler}=loadH3v2(options.h3);return{name:`h3-web`,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},nodeHandler(app){assembleCatchAll(app);let listener=toNodeHandler(app);return(req,res,next)=>{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];mw&&mw(err,req,driver,NOOP_NEXT)}});app.on(entry.method,url,event=>run({request:event.req,url:event.url,params:event.context.params??{}}))}},useConnect(app,mw,opts){let viaNode=fromNodeHandler(mw),handler=(event,next)=>event.req.runtime?.node?.res?viaNode(event):runConnectOnFetch(mw,event,next);opts?.path===void 0?app.use(handler):app.use(joinPath(String(opts.path),`/**`),handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(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}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3WebRuntime};
|
|
12
12
|
//# sourceMappingURL=h3-web.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"h3-web.mjs","names":[],"sources":["../../../src/http/runtimes/h3-web.ts"],"sourcesContent":["// The h3 v2 (web-standards) runtime — `@forinda/kickjs/h3-web`.\n//\n// ADDITIVE runtime: the h3 v1 runtime (`./h3.ts`, `@forinda/kickjs/h3`)\n// stays untouched so existing adopters keep working (locked decision,\n// web-standards-edge-design.md §3.1). This runtime targets h3 >= 2 — the\n// web-standard rebase where `event.req` is a WHATWG Request, handlers\n// return values/Responses, and `app.fetch(request)` is the universal entry.\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// Known limitation vs the v1 runtime: no Vite dev-server fall-through —\n// unmatched requests are answered by the kick notFound handler (h3 v2 owns\n// the full request; there is no node `next()` bail-out mid-engine). Use the\n// v1 h3 runtime or Express for Vite-integrated dev setups.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { compileWebRoute, type WebRouteHooks } from '../web/handler'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger, describeError } from '../../core/logger'\n\nconst log = createLogger('H3WebRuntime')\n\nconst peerRequire = createRequire(import.meta.url)\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\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 H3WebRuntimeOptions {\n /**\n * Pre-imported h3 v2 module. Two audiences:\n * - Edge/worker bundlers with no `createRequire` at runtime:\n * `h3WebRuntime({ h3: await import('h3') })`\n * - Tests running both h3 majors side by side via an npm alias.\n * Omitted → the peer is loaded via `createRequire` (node bootstrap path).\n */\n h3?: unknown\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n const mod = injected ?? peerRequire('h3')\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n const resolved = (m && m.__esModule && m.default\n ? { ...m.default, ...m }\n : m) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n \"@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), \" +\n 'but the installed h3 has no H3 class — that is the v1 line. ' +\n \"Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.\",\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 req = new WebRequestShim(event.req, event.url)\n const driver = new WebResponseDriver(event.req.signal)\n if (mw) {\n if (err !== undefined) {\n ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } else {\n ;(mw as (rq: unknown, rs: unknown, n: () => void) => void)(req, driver, NOOP_NEXT)\n }\n }\n if (!driver.settled) {\n if (err !== undefined) {\n // The configured error handler ran but didn't settle the response\n // (or there wasn't one). Emitting a bare 500 with no log entry\n // makes this failure invisible on both sides — log it here, since\n // by definition nothing downstream will.\n log.error(err, `h3-web: error handler did not settle the response — ${describeError(err)}`)\n driver.status(500).json({\n error: 'Internal Server Error',\n ...(typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'\n ? {}\n : { message: describeError(err) }),\n })\n } else {\n driver.status(404).json({ error: 'Not Found' })\n }\n }\n return driver.ready\n}\n\n/**\n * The h3 v2 HTTP runtime. Pass to `bootstrap({ runtime: h3WebRuntime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3WebRuntime(options: H3WebRuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3-web',\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)\n },\n })\n holder.app = app\n return app\n },\n\n nodeHandler(app) {\n const state = app as unknown as Record<symbol, unknown>\n if (!state[ASSEMBLED]) {\n state[ASSEMBLED] = true\n // Terminal catch-all AFTER all mounted routes: kick's own notFound\n // handler answers unmatched paths (h3 v2's default 404 never fires).\n app.all('/**', (event: H3EventLike) => {\n const mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n }\n const listener = toNodeHandler(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\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 ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n },\n }\n const run = compileWebRoute(entry, hooks)\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n }),\n )\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n // Node bootstrap path only — h3 v2 bridges node middleware via\n // fromNodeHandler (the edge entry never calls useConnect).\n const handler = fromNodeHandler(mw)\n if (opts?.path !== undefined) {\n // v2 `use` is exact-match; `/**` covers the subtree like v1's prefix.\n app.use(joinPath(String(opts.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 const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[NOTFOUND_MW] = mw\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 },\n }\n}\n\n/**\n * h3-web runtime engine types for the `kick/runtime` typegen augmentation —\n * mirrors {@link import('./h3').H3RuntimeTypes} for the v1 runtime.\n */\nexport interface H3WebRuntimeTypes {\n request: Request\n response: Response\n app: 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"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"h3-web.mjs","names":[],"sources":["../../../src/http/runtimes/h3-web.ts"],"sourcesContent":["// The h3 v2 (web-standards) runtime — `@forinda/kickjs/h3-web`.\n//\n// ADDITIVE runtime: the h3 v1 runtime (`./h3.ts`, `@forinda/kickjs/h3`)\n// stays untouched so existing adopters keep working (locked decision,\n// web-standards-edge-design.md §3.1). This runtime targets h3 >= 2 — the\n// web-standard rebase where `event.req` is a WHATWG Request, handlers\n// return values/Responses, and `app.fetch(request)` is the universal entry.\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// Known limitation vs the v1 runtime: no Vite dev-server fall-through —\n// unmatched requests are answered by the kick notFound handler (h3 v2 owns\n// the full request; there is no node `next()` bail-out mid-engine). Use the\n// v1 h3 runtime or Express for Vite-integrated dev setups.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { compileWebRoute, type WebRouteHooks } from '../web/handler'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger, describeError } from '../../core/logger'\n\nconst log = createLogger('H3WebRuntime')\n\nconst peerRequire = createRequire(import.meta.url)\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\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 H3WebRuntimeOptions {\n /**\n * Pre-imported h3 v2 module. Two audiences:\n * - Edge/worker bundlers with no `createRequire` at runtime:\n * `h3WebRuntime({ h3: await import('h3') })`\n * - Tests running both h3 majors side by side via an npm alias.\n * Omitted → the peer is loaded via `createRequire` (node bootstrap path).\n */\n h3?: unknown\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n const mod = injected ?? peerRequire('h3')\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n const resolved = (m && m.__esModule && m.default\n ? { ...m.default, ...m }\n : m) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n \"@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), \" +\n 'but the installed h3 has no H3 class — that is the v1 line. ' +\n \"Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.\",\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 req = new WebRequestShim(event.req, event.url)\n const driver = new WebResponseDriver(event.req.signal)\n if (mw) {\n if (err !== undefined) {\n ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } else {\n ;(mw as (rq: unknown, rs: unknown, n: () => void) => void)(req, driver, NOOP_NEXT)\n }\n }\n if (!driver.settled) {\n if (err !== undefined) {\n // The configured error handler ran but didn't settle the response\n // (or there wasn't one). Emitting a bare 500 with no log entry\n // makes this failure invisible on both sides — log it here, since\n // by definition nothing downstream will.\n log.error(err, `h3-web: error handler did not settle the response — ${describeError(err)}`)\n driver.status(500).json({\n error: 'Internal Server Error',\n ...(typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'\n ? {}\n : { message: describeError(err) }),\n })\n } else {\n driver.status(404).json({ error: 'Not Found' })\n }\n }\n return driver.ready\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 /** The response exists (or the request failed): fire `finish` then `close`. */\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 mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n}\n\n/**\n * The h3 v2 HTTP runtime. Pass to `bootstrap({ runtime: h3WebRuntime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3WebRuntime(options: H3WebRuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3-web',\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 return app\n },\n\n nodeHandler(app) {\n assembleCatchAll(app)\n const listener = toNodeHandler(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\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 ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n },\n }\n const run = compileWebRoute(entry, hooks)\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n }),\n )\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\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 (opts?.path !== undefined) {\n // v2 `use` is exact-match; `/**` covers the subtree like v1's prefix.\n app.use(joinPath(String(opts.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 const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { 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 },\n }\n}\n\n/**\n * h3-web runtime engine types for the `kick/runtime` typegen augmentation —\n * mirrors {@link import('./h3').H3RuntimeTypes} for the v1 runtime.\n */\nexport interface H3WebRuntimeTypes {\n request: Request\n response: Response\n app: 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"],"mappings":"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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{HttpException}from"../../core/errors.mjs";import{a as createRequestStore,f as unsupportedMediaTypeError,n as applyHandlerResult,o as disposeRequestStore,t as publishMatchedRoute,u as classifyMediaType}from"../../runtime-
|
|
11
|
+
import{HttpException}from"../../core/errors.mjs";import{a as createRequestStore,f as unsupportedMediaTypeError,n as applyHandlerResult,o as disposeRequestStore,t as publishMatchedRoute,u as classifyMediaType}from"../../runtime-C-7Yhs7a.mjs";import{i as requestStore,t as RequestContext}from"../../context-BTqeZH1A.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-CoE6BzM4.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),h3=()=>peerRequire(`h3`),NEXT=Symbol(`kickjs.h3.next`),ERROR_MW=Symbol(`kickjs.h3.errorMw`),ROUTER=Symbol(`kickjs.h3.router`),NOTFOUND_MW=Symbol(`kickjs.h3.notFoundMw`),ASSEMBLED=Symbol(`kickjs.h3.assembled`),NOOP_NEXT=()=>{},BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var NodeResDriver=class{res;constructor(res){this.res=res}status(code){return this.res.statusCode=code,this}json(data){return!this.res.headersSent&&!this.res.getHeader(`content-type`)&&this.res.setHeader(`content-type`,`application/json; charset=utf-8`),this.res.end(JSON.stringify(data)),this}send(data){return this.res.end(data),this}type(contentType){return this.res.setHeader(`content-type`,contentType),this}setHeader(name,value){return this.res.setHeader(name,value),this}render(){throw Error(`ctx.render() is not supported on the h3 runtime (no view engine).`)}writeHead(statusCode,headers){return this.res.writeHead(statusCode,headers),this}flushHeaders(){return this.res.flushHeaders(),this}write(chunk){return this.res.write(chunk)}end(data){return this.res.end(data),this}once(event,listener){return this.res.once(event,listener),this}get headersSent(){return this.res.headersSent}};function resDriver(res){return new NodeResDriver(res)}const TRUST_PROXY=Symbol(`kickjs.h3.trustProxy`);function makeEventHandler(entry,trustProxy){let{getRouterParams,getQuery,readRawBody,readMultipartFormData}=h3(),upload=entry.meta.upload,validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async event=>{let req=event.node.req,res=event.node.res;if(trustProxy&&!req.ip){let forwarded=req.headers[`x-forwarded-for`],first=(Array.isArray(forwarded)?forwarded[0]:forwarded)?.split(`,`)[0]?.trim();first&&(req.ip=first)}if(req.params=getRouterParams(event)??{},req.query=getQuery(event)??{},upload&&upload.mode!==`none`){let form=await readMultipartFormData(event).catch(()=>void 0),rawParts=[],fields={};for(let part of form??[])part.filename?rawParts.push({fieldname:part.name??``,filename:part.filename,mimetype:part.type??`application/octet-stream`,buffer:part.data}):part.name&&(fields[part.name]=part.data.toString(`utf-8`));let{file,files}=applyUploadConfig(rawParts,upload);req.file=file,req.files=files,req.body=fields}else if(BODY_METHODS.has(req.method??`GET`)){let{"content-length":length,"transfer-encoding":encoding}=req.headers;if(encoding!==void 0||length!==void 0&&length!==`0`){let kind=classifyMediaType(req.headers[`content-type`]);if(kind!==`multipart`){let raw=await readRawBody(event,`utf8`);if(raw){if(kind===`unsupported`)throw unsupportedMediaTypeError(req.headers[`content-type`]);if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){throw 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 headerId=req.headers[`x-request-id`],requestId=(Array.isArray(headerId)?headerId[0]:headerId)||req.requestId,store=createRequestStore(requestId);req.requestId=store.requestId,res.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(req,entry);let ctx=new RequestContext(req,res,NOOP_NEXT,resDriver(res));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),res.writableEnded))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||res.writableEnded)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),res.writableEnded)return;let result=await entry.handler(ctx);!res.writableEnded&&!res.headersSent&&applyHandlerResult(ctx,result)})}}function unwrapH3Error(error){if(!(error instanceof Error))return error;let{cause}=error;return cause instanceof Error?cause:error}function h3Runtime(){return{name:`h3`,createApp(options={}){let{createApp}=h3(),app=createApp({onError:(error,event)=>{let res=event.node.res;if(res.writableEnded)return;let state=app;if(error?.statusCode===404){let next=event.node.req[NEXT];if(next){next();return}let nf=state[NOTFOUND_MW];if(nf){nf(event.node.req,resDriver(res),NOOP_NEXT);return}}let mw=state[ERROR_MW];mw&&mw(unwrapH3Error(error),event.node.req,resDriver(res),NOOP_NEXT)}});return app[TRUST_PROXY]=options.trustProxy,app},nodeHandler(app){let{toNodeListener}=h3(),state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,state[ROUTER]&&app.use(state[ROUTER]));let listener=toNodeListener(app);return(req,res,next)=>{next&&(req[NEXT]=next),Promise.resolve(listener(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){let{createRouter,eventHandler}=h3(),trustProxy=!!app[TRUST_PROXY],state=app;state[ROUTER]||(state[ROUTER]=createRouter());let router=state[ROUTER];for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path);router[entry.method.toLowerCase()](url,eventHandler(makeEventHandler(entry,trustProxy)))}},useConnect(app,mw,opts){let{fromNodeMiddleware}=h3(),handler=fromNodeMiddleware(mw);opts?.path===void 0?app.use(handler):app.use(opts.path,handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3Runtime};
|
|
12
12
|
//# sourceMappingURL=h3.mjs.map
|
package/dist/index.d.mts
CHANGED
|
@@ -3,27 +3,27 @@ import { a as METADATA, c as Scope, i as Constructor, l as ServiceOptions, n as
|
|
|
3
3
|
import { a as tokenName, c as createToken, i as KickJsRegistry, l as isInjectionToken, n as ContainerChangeEvent, o as INJECTION_TOKEN, r as ContainerChangeListener, s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
|
|
4
4
|
import { A as Service, B as resolveAsset, C as Post, D as Put, F as ASSET_MANIFEST_VERSION, I as KickAssets, L as UnknownAssetError, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, P as ASSETS, R as assets, S as Patch, T as PreDestroy, V as useAssets, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable, z as clearAssetCache } from "./decorators-mg0qJ6Qc.mjs";
|
|
5
5
|
import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "./index-Btz1W0X5.mjs";
|
|
6
|
-
import { _ as
|
|
7
|
-
import { C as MetaValue, S as ExecutionContext, _ as ResolvedDeps, a as ModuleRoutes, b as ContextMeta, c as ContextDecorator, d as ContextDecoratorTarget, f as ContextDecoratorWithDefaults, g as MissingParamKeys, h as DepValue, l as ContextDecoratorRequiringParams, m as ContributorRegistrations, n as AppModuleClass, o as AnyContributorRegistration, p as ContributorRegistration, r as AppModuleEntry, s as CallSiteParams, t as AppModule, u as ContextDecoratorSpec, v as defineContextDecorator, x as ContextMetaKey, y as ContextKeys } from "./app-module-
|
|
8
|
-
import { $ as ModuleList, A as AdapterFactory, B as getClassMeta, C as UseConnectOptions, D as RouteShape, E as RequestContext, F as BuildPipelineOptions, G as getMethodMetaOrUndefined, H as getMetaMap, I as ContributorPipeline, J as pushMethodMeta, K as hasClassMeta, L as ContributorSource, M as defineAdapter, N as RunContributorsOptions, O as SseHandler, P as runContributors, Q as setMethodMeta, R as SourcedRegistration, S as RuntimeTypeMap, T as DeepReadonly, U as getMetaRecord, V as getClassMetaOrUndefined, W as getMethodMeta, X as setInMetaMap, Y as setClassMeta, Z as setInMetaRecord, _ as RouteMethod, _t as IntrospectionKind, a as MiddlewarePath, at as DefinePluginOptions, b as RuntimeCapabilities, c as AdapterHttp, ct as definePlugin, d as ExpressRuntimeTypes, dt as MutableModuleRegistry, et as defineModules, f as HttpRuntime, ft as AugmentationMeta, g as RouteMeta, gt as IntrospectFn, h as RouteEntry, ht as defineAugmentation, i as AppAdapterClass, it as BuildContext, j as DefineAdapterOptions, k as AdapterAsyncOptions, l as ConnectMiddleware, lt as KickPlugin, m as MatchedRoute, mt as KickJsPluginRegistry, n as AdapterMiddleware, nt as ModuleFactory, o as MiddlewarePhase, ot as PluginAsyncOptions, p as KickRuntimeRegister, pt as KickJsPluginName, q as pushClassMeta, r as AppAdapter, rt as defineModule, s as ActiveRuntime, st as PluginFactory, t as AdapterContext, tt as DefineModuleOptions, u as CtxHandler, ut as ModuleRegistry, v as RouteTable, vt as IntrospectionSnapshot, w as Ctx, x as RuntimeResponse, y as RuntimeAppOptions, z as buildPipeline } from "./adapter-
|
|
6
|
+
import { _ as getRouteFlags, a as RouteFlagContext, c as RouteFlagName, d as RouteFlagTest, f as RouteFlagValue, g as defineRouteFlag, h as assertFlagTest, i as RouteFlag, l as RouteFlagPredicate, m as ValuedRouteFlag, n as KickRouteFlags, o as RouteFlagDeclaration, p as RouteFlags, r as NegatedRouteFlagName, s as RouteFlagDeclarations, t as BareRouteFlag, u as RouteFlagRecord, v as matchesFlagTest, y as resolveRouteFlags } from "./route-flag-B1lQht6v.mjs";
|
|
7
|
+
import { C as MetaValue, S as ExecutionContext, _ as ResolvedDeps, a as ModuleRoutes, b as ContextMeta, c as ContextDecorator, d as ContextDecoratorTarget, f as ContextDecoratorWithDefaults, g as MissingParamKeys, h as DepValue, l as ContextDecoratorRequiringParams, m as ContributorRegistrations, n as AppModuleClass, o as AnyContributorRegistration, p as ContributorRegistration, r as AppModuleEntry, s as CallSiteParams, t as AppModule, u as ContextDecoratorSpec, v as defineContextDecorator, x as ContextMetaKey, y as ContextKeys } from "./app-module-DCA65GZZ.mjs";
|
|
8
|
+
import { $ as ModuleList, A as AdapterFactory, B as getClassMeta, C as UseConnectOptions, D as RouteShape, E as RequestContext, F as BuildPipelineOptions, G as getMethodMetaOrUndefined, H as getMetaMap, I as ContributorPipeline, J as pushMethodMeta, K as hasClassMeta, L as ContributorSource, M as defineAdapter, N as RunContributorsOptions, O as SseHandler, P as runContributors, Q as setMethodMeta, R as SourcedRegistration, S as RuntimeTypeMap, T as DeepReadonly, U as getMetaRecord, V as getClassMetaOrUndefined, W as getMethodMeta, X as setInMetaMap, Y as setClassMeta, Z as setInMetaRecord, _ as RouteMethod, _t as IntrospectionKind, a as MiddlewarePath, at as DefinePluginOptions, b as RuntimeCapabilities, c as AdapterHttp, ct as definePlugin, d as ExpressRuntimeTypes, dt as MutableModuleRegistry, et as defineModules, f as HttpRuntime, ft as AugmentationMeta, g as RouteMeta, gt as IntrospectFn, h as RouteEntry, ht as defineAugmentation, i as AppAdapterClass, it as BuildContext, j as DefineAdapterOptions, k as AdapterAsyncOptions, l as ConnectMiddleware, lt as KickPlugin, m as MatchedRoute, mt as KickJsPluginRegistry, n as AdapterMiddleware, nt as ModuleFactory, o as MiddlewarePhase, ot as PluginAsyncOptions, p as KickRuntimeRegister, pt as KickJsPluginName, q as pushClassMeta, r as AppAdapter, rt as defineModule, s as ActiveRuntime, st as PluginFactory, t as AdapterContext, tt as DefineModuleOptions, u as CtxHandler, ut as ModuleRegistry, v as RouteTable, vt as IntrospectionSnapshot, w as Ctx, x as RuntimeResponse, y as RuntimeAppOptions, z as buildPipeline } from "./adapter-2bnoYEPX.mjs";
|
|
9
9
|
import { i as getCronJobs, n as Cron, r as CronJobMeta, t as CRON_META } from "./cron-DOOtTY4q.mjs";
|
|
10
10
|
import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider } from "./cache-C0qL0NSD.mjs";
|
|
11
11
|
import { a as describeError, i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "./logger-DA43DvNY.mjs";
|
|
12
|
-
import { $ as
|
|
12
|
+
import { $ as MissingContributorError, A as ClusterOptions, B as GroupAssetKeysOptions, C as getRequestStore, D as expressRuntime, E as buildRoutes, F as RoutePolicyTable, G as MissingMountDepError, H as groupAssetKeys, I as bindRoutePolicy, J as MountSortItem, K as MountCycleError, L as offerRoutePolicy, M as KickHandler, N as createHandler, O as materializeRouter, P as bootstrap, Q as MissingContextValueError, R as AssetKeyPair, S as RequestStore, T as requestStore, U as stripExt, V as GroupAssetKeysResult, W as DuplicateMountNameError, X as ContributorCycleError, Y as mountSort, Z as DuplicateContributorError, _ as TraceContext, a as HEALTH_PROBE, at as FormatKickErrorOptions, b as traceContext, c as HealthModuleConfig, ct as formatKickError, d as SpaAdapter, dt as registerDisposable, et as CircuitBreaker, f as SpaAdapterOptions, g as TRACEPARENT_HEADER, h as ViewAdapterOptions, it as CircuitOpenError, j as isClusterPrimary, k as defineHttpContextDecorator, l as HealthProbe, lt as Disposable, m as ViewAdapter, n as ApplicationOptions, nt as CircuitBreakerState, o as HealthCheckResult, ot as KickError, q as MountKind, r as MiddlewareEntry, rt as CircuitBreakerStats, s as HealthController, st as KickErrorInit, t as Application, tt as CircuitBreakerOptions, u as healthModule, ut as disposeAll, v as TraceContextOptions, w as getRequestValue, x as requestScopeMiddleware, y as parseTraceparent, z as AssetKeyStrategy } from "./application-_QOiAVx2.mjs";
|
|
13
13
|
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";
|
|
14
14
|
import { n as joinPaths, r as normalizePath, t as buildMountPath } from "./path-CMwIHsdv.mjs";
|
|
15
15
|
import { a as isRef, c as toRefs, i as computed, l as unref, n as Ref, o as reactive, r as WatchOptions, s as ref, t as ComputedRef, u as watch } from "./reactivity-BkMNA0kp.mjs";
|
|
16
16
|
import { C as SortItem, S as QueryFieldConfig, T as TypedParsedQuery, _ as FilterOperator, a as getQueryParsingDefaults, b as ParsedQuery, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as FilterItem, h as FieldsOf, i as buildQueryParams, l as parseSearchQuery, m as FILTER_OPERATORS, n as QueryRejectReason, o as parseFilters, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as PaginatedResponse, x as QueryBuilderAdapter, y as PaginationParams } from "./index-BfT5KZ-M.mjs";
|
|
17
|
-
import { a as KvSessionStoreOptions, c as InferHandlerResponse, d as isReply, f as reply, i as KvSessionStore, l as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as applyHandlerResult } from "./kv-stores-
|
|
18
|
-
import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-
|
|
17
|
+
import { a as KvSessionStoreOptions, c as InferHandlerResponse, d as isReply, f as reply, i as KvSessionStore, l as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as applyHandlerResult } from "./kv-stores-Dx5RvIaP.mjs";
|
|
18
|
+
import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-C6gmK0nZ.mjs";
|
|
19
19
|
import { n as requestId, t as REQUEST_ID_HEADER } from "./request-id-CVzJ1uHD.mjs";
|
|
20
20
|
import { n as validate } from "./validate-DMYpUnrf.mjs";
|
|
21
|
-
import { n as errorHandler, r as notFoundHandler } from "./error-handler-
|
|
22
|
-
import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-
|
|
21
|
+
import { n as errorHandler, r as notFoundHandler } from "./error-handler-C1uWVGVY.mjs";
|
|
22
|
+
import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-C4MwaMp4.mjs";
|
|
23
23
|
import { i as requestLogger, n as LoggedResponse, r as RequestLoggerOptions, t as LoggedRequest } from "./request-logger-TgcKRNDD.mjs";
|
|
24
24
|
import { n as HelmetOptions, r as helmet } from "./helmet-C2QEU6S-.mjs";
|
|
25
25
|
import { n as cors, t as CorsOptions } from "./cors-CsibNTQ6.mjs";
|
|
26
|
-
import { n as RateLimitStore, r as rateLimit, t as RateLimitOptions } from "./rate-limit-
|
|
26
|
+
import { n as RateLimitStore, r as rateLimit, t as RateLimitOptions } from "./rate-limit-Bwed3jOV.mjs";
|
|
27
27
|
import { a as session, i as SessionStore, n as SessionData, r as SessionOptions, t as Session } from "./session-BHgRyfqZ.mjs";
|
|
28
|
-
import { i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-
|
|
29
|
-
export { ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, type AugmentationMeta, Autowired, type BareRouteFlag, type BaseUploadOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CacheEvict, type CacheOptions, type CacheProvider, Cacheable, type CallSiteParams, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, ConfigService, type ConnectMiddleware, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronJobMeta, type CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, type Env, type EnvKey, type ExecutionContext, type ExpressRuntimeTypes, FILTER_OPERATORS, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, HEALTH_PROBE, type HealthCheckResult, HealthController, type HealthModuleConfig, type HealthProbe, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, type KickAssets, KickError, type KickErrorInit, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRouteFlags, type KickRuntimeRegister, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, MutableModuleRegistry, type NegatedRouteFlagName, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, Patch, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, REQUEST_ID_HEADER, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type Reply, Repository, RequestContext, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type RouteDefinition, type RouteEntry, type RouteFlag, type RouteFlagContext, type RouteFlagDeclaration, type RouteFlagDeclarations, type RouteFlagName, type RouteFlagPredicate, type RouteFlagRecord, type RouteFlagTest, type RouteFlagValue, type RouteFlags, type RouteMeta, type RouteMethod, RoutePolicyTable, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UseConnectOptions, type ValidationError, Value, type ValuedRouteFlag, ViewAdapter, type ViewAdapterOptions, type WatchOptions, applyHandlerResult, assets, baseEnvSchema, bindRoutePolicy, bootstrap, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createLogger, createToken, csrf, csrfGuard, defaultProblemTitle, defineAdapter, defineAugmentation, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, describeError, disposeAll, errorHandler, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, healthModule, helmet, isClusterPrimary, isInjectionToken, isRef, isReply, joinPaths, loadEnv, loadEnvFromSchema, matchesFlagTest, materializeRouter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, reloadEnv, reply, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, resolveRouteFlags, runContributors, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, watch, withBuilder };
|
|
28
|
+
import { i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-TW2ZuECF.mjs";
|
|
29
|
+
export { ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, type AugmentationMeta, Autowired, type BareRouteFlag, type BaseUploadOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CacheEvict, type CacheOptions, type CacheProvider, Cacheable, type CallSiteParams, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, ConfigService, type ConnectMiddleware, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronJobMeta, type CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, type Env, type EnvKey, type ExecutionContext, type ExpressRuntimeTypes, FILTER_OPERATORS, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, HEALTH_PROBE, type HealthCheckResult, HealthController, type HealthModuleConfig, type HealthProbe, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, type KickAssets, KickError, type KickErrorInit, type KickHandler, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRouteFlags, type KickRuntimeRegister, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, MutableModuleRegistry, type NegatedRouteFlagName, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, Patch, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, REQUEST_ID_HEADER, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type Reply, Repository, RequestContext, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type RouteDefinition, type RouteEntry, type RouteFlag, type RouteFlagContext, type RouteFlagDeclaration, type RouteFlagDeclarations, type RouteFlagName, type RouteFlagPredicate, type RouteFlagRecord, type RouteFlagTest, type RouteFlagValue, type RouteFlags, type RouteMeta, type RouteMethod, RoutePolicyTable, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UseConnectOptions, type ValidationError, Value, type ValuedRouteFlag, ViewAdapter, type ViewAdapterOptions, type WatchOptions, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, bindRoutePolicy, bootstrap, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createToken, csrf, csrfGuard, defaultProblemTitle, defineAdapter, defineAugmentation, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, describeError, disposeAll, errorHandler, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, healthModule, helmet, isClusterPrimary, isInjectionToken, isRef, isReply, joinPaths, loadEnv, loadEnvFromSchema, matchesFlagTest, materializeRouter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, reloadEnv, reply, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, resolveRouteFlags, runContributors, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, watch, withBuilder };
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v8.
|
|
2
|
+
* @forinda/kickjs v8.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{a as loadEnvFromSchema,i as loadEnv,n as defineEnv,o as reloadEnv,r as getEnv,s as resetEnvCache,t as baseEnvSchema}from"./env-BTOmTNsH.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,c as KickError,i as createToken,l as formatKickError,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-BB_XC2ww.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.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-C_bLigwT.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{a as HEALTH_PROBE,c as DuplicateMountNameError,d as mountSort,f as defineModule,i as materializeRouter,l as MissingMountDepError,n as buildRoutes,o as HealthController,r as expressRuntime,s as healthModule,t as Application,u as MountCycleError}from"./application-Bm3wCm06.mjs";import{t as MutableModuleRegistry}from"./module-registry-B_gw6smc.mjs";import{CRON_META,Cron,getCronJobs}from"./core/cron.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-CZ7vf6L_.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-C7AilXtr.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-CTyRc4AM.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-doMQ4bAU.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-CFAHKq4e.mjs";import{t as runContributors}from"./contributor-runner-DflutMFy.mjs";import{t as defineAdapter}from"./define-adapter-CsDcNhlh.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-BQfQEuFn.mjs";import{c as requestScopeMiddleware,i as reply,n as applyHandlerResult,r as isReply}from"./runtime-B2oXJDwr.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as requestStore,n as getRequestStore,r as getRequestValue,t as RequestContext}from"./context-Xd8C4fIo.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-B7_CJZaf.mjs";import{validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-C23IAKGT.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{n as isClusterPrimary,t as bootstrap}from"./bootstrap-DHftqJ1m.mjs";import{n as csrfGuard,r as randomHex,t as csrf}from"./csrf-CMzwva6A.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.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-C755yuvc.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-pot4-2DS.mjs";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=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}function defineAugmentation(name,meta){}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CacheEvict,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,FILTER_OPERATORS,FileUpload,Get,HEALTH_PROBE,HealthController,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Put,REQUEST_ID_HEADER,Repository,RequestContext,RoutePolicyTable,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,applyHandlerResult,assets,baseEnvSchema,bindRoutePolicy,bootstrap,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createLogger,createToken,csrf,csrfGuard,defaultProblemTitle,defineAdapter,defineAugmentation,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,defineRouteFlag,describeError,disposeAll,errorHandler,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,getRouteFlags,groupAssetKeys,hasClassMeta,healthModule,helmet,isClusterPrimary,isInjectionToken,isRef,isReply,joinPaths,loadEnv,loadEnvFromSchema,matchesFlagTest,materializeRouter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,offerRoutePolicy,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,reloadEnv,reply,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,resolveRouteFlags,runContributors,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,stripExt,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,watch,withBuilder};
|
|
11
|
+
import{a as loadEnvFromSchema,i as loadEnv,n as defineEnv,o as reloadEnv,r as getEnv,s as resetEnvCache,t as baseEnvSchema}from"./env-BelmDj19.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,c as KickError,i as createToken,l as formatKickError,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-DF8FRoY8.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.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-B8_KXybT.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{a as HEALTH_PROBE,c as DuplicateMountNameError,d as mountSort,f as defineModule,i as materializeRouter,l as MissingMountDepError,n as buildRoutes,o as HealthController,r as expressRuntime,s as healthModule,t as Application,u as MountCycleError}from"./application-DZiG1QCw.mjs";import{t as MutableModuleRegistry}from"./module-registry-BFrJ1PQ4.mjs";import{CRON_META,Cron,getCronJobs}from"./core/cron.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-CEAxve3A.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,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-B4sNP7zH.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-y8QbzHM5.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-Ch0DuUQo.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-cTsA2XtO.mjs";import{t as runContributors}from"./contributor-runner-DujKZy4N.mjs";import{t as defineAdapter}from"./define-adapter-C1Db6xfO.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-CDlMbl1b.mjs";import{c as requestScopeMiddleware,i as reply,n as applyHandlerResult,r as isReply}from"./runtime-C-7Yhs7a.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as requestStore,n as getRequestStore,r as getRequestValue,t as RequestContext}from"./context-BTqeZH1A.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-CC7o6I5K.mjs";import{validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-CoE6BzM4.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{n as isClusterPrimary,t as bootstrap}from"./bootstrap-BEbka3UV.mjs";import{n as csrfGuard,r as randomHex,t as csrf}from"./csrf-RP5hgc0c.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.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-DUFcps01.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-CIOXZmLS.mjs";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=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}function defineAugmentation(name,meta){}function createHandler(options){let app,ready=()=>(app??=(async()=>{let instance=new Application(options);try{await instance.startWithoutServer()}catch(err){throw app=void 0,await instance.shutdown().catch(()=>{}),err}return instance})(),app);return{ready,async fetch(request){return(await ready()).fetch(request)},async node(req,res){(await ready()).handle(req,res)},async close(){let current=app;app=void 0,current&&await(await current).shutdown()}}}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CacheEvict,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,FILTER_OPERATORS,FileUpload,Get,HEALTH_PROBE,HealthController,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Put,REQUEST_ID_HEADER,Repository,RequestContext,RoutePolicyTable,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,applyHandlerResult,assertFlagTest,assets,baseEnvSchema,bindRoutePolicy,bootstrap,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createHandler,createLogger,createToken,csrf,csrfGuard,defaultProblemTitle,defineAdapter,defineAugmentation,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,defineRouteFlag,describeError,disposeAll,errorHandler,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,getRouteFlags,groupAssetKeys,hasClassMeta,healthModule,helmet,isClusterPrimary,isInjectionToken,isRef,isReply,joinPaths,loadEnv,loadEnvFromSchema,matchesFlagTest,materializeRouter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,offerRoutePolicy,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,reloadEnv,reply,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,resolveRouteFlags,runContributors,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,stripExt,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,watch,withBuilder};
|
|
12
12
|
//# sourceMappingURL=index.mjs.map
|