elysia 1.4.21 → 1.4.22

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/bun/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  // @bun
2
- var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;var __toESM=(mod,isNodeMode,target)=>{target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:()=>mod[key],enumerable:!0});return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __require=import.meta.require;var require_fast_decode_uri_component=__commonJS((exports,module)=>{var UTF8_ACCEPT=12,UTF8_REJECT=0,UTF8_DATA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function decodeURIComponent2(uri){var percentPosition=uri.indexOf("%");if(percentPosition===-1)return uri;var length=uri.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri[percentPosition+1],4),low=hexCodeToInt(uri[percentPosition+2],0),byte=high|low,type=UTF8_DATA[byte];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri.slice(last)}var HEX={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function hexCodeToInt(c,shift){var i=HEX[c];return i===void 0?255:i<<shift}module.exports=decodeURIComponent2});var require_dist=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.parseCookie=parseCookie;exports.parse=parseCookie;exports.stringifyCookie=stringifyCookie;exports.stringifySetCookie=stringifySetCookie;exports.serialize=stringifySetCookie;exports.parseSetCookie=parseSetCookie;exports.stringifySetCookie=stringifySetCookie;exports.serialize=stringifySetCookie;var cookieNameRegExp=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,cookieValueRegExp=/^[\u0021-\u003A\u003C-\u007E]*$/,domainValueRegExp=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,pathValueRegExp=/^[\u0020-\u003A\u003D-\u007E]*$/,maxAgeRegExp=/^-?\d+$/,__toString=Object.prototype.toString,NullObject=(()=>{let C=function(){};return C.prototype=Object.create(null),C})();function parseCookie(str,options){let obj=new NullObject,len=str.length;if(len<2)return obj;let dec=options?.decode||decode,index=0;do{let eqIdx=eqIndex(str,index,len);if(eqIdx===-1)break;let endIdx=endIndex(str,index,len);if(eqIdx>endIdx){index=str.lastIndexOf(";",eqIdx-1)+1;continue}let key=valueSlice(str,index,eqIdx);if(obj[key]===void 0)obj[key]=dec(valueSlice(str,eqIdx+1,endIdx));index=endIdx+1}while(index<len);return obj}function stringifyCookie(cookie,options){let enc=options?.encode||encodeURIComponent,cookieStrings=[];for(let name of Object.keys(cookie)){let val=cookie[name];if(val===void 0)continue;if(!cookieNameRegExp.test(name))throw TypeError(`cookie name is invalid: ${name}`);let value=enc(val);if(!cookieValueRegExp.test(value))throw TypeError(`cookie val is invalid: ${val}`);cookieStrings.push(`${name}=${value}`)}return cookieStrings.join("; ")}function stringifySetCookie(_name,_val,_opts){let cookie=typeof _name==="object"?_name:{..._opts,name:_name,value:String(_val)},enc=(typeof _val==="object"?_val:_opts)?.encode||encodeURIComponent;if(!cookieNameRegExp.test(cookie.name))throw TypeError(`argument name is invalid: ${cookie.name}`);let value=cookie.value?enc(cookie.value):"";if(!cookieValueRegExp.test(value))throw TypeError(`argument val is invalid: ${cookie.value}`);let str=cookie.name+"="+value;if(cookie.maxAge!==void 0){if(!Number.isInteger(cookie.maxAge))throw TypeError(`option maxAge is invalid: ${cookie.maxAge}`);str+="; Max-Age="+cookie.maxAge}if(cookie.domain){if(!domainValueRegExp.test(cookie.domain))throw TypeError(`option domain is invalid: ${cookie.domain}`);str+="; Domain="+cookie.domain}if(cookie.path){if(!pathValueRegExp.test(cookie.path))throw TypeError(`option path is invalid: ${cookie.path}`);str+="; Path="+cookie.path}if(cookie.expires){if(!isDate(cookie.expires)||!Number.isFinite(cookie.expires.valueOf()))throw TypeError(`option expires is invalid: ${cookie.expires}`);str+="; Expires="+cookie.expires.toUTCString()}if(cookie.httpOnly)str+="; HttpOnly";if(cookie.secure)str+="; Secure";if(cookie.partitioned)str+="; Partitioned";if(cookie.priority)switch(typeof cookie.priority==="string"?cookie.priority.toLowerCase():void 0){case"low":str+="; Priority=Low";break;case"medium":str+="; Priority=Medium";break;case"high":str+="; Priority=High";break;default:throw TypeError(`option priority is invalid: ${cookie.priority}`)}if(cookie.sameSite)switch(typeof cookie.sameSite==="string"?cookie.sameSite.toLowerCase():cookie.sameSite){case!0:case"strict":str+="; SameSite=Strict";break;case"lax":str+="; SameSite=Lax";break;case"none":str+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${cookie.sameSite}`)}return str}function parseSetCookie(str,options){let dec=options?.decode||decode,len=str.length,endIdx=endIndex(str,0,len),eqIdx=eqIndex(str,0,endIdx),setCookie=eqIdx===-1?{name:"",value:dec(valueSlice(str,0,endIdx))}:{name:valueSlice(str,0,eqIdx),value:dec(valueSlice(str,eqIdx+1,endIdx))},index=endIdx+1;while(index<len){let endIdx2=endIndex(str,index,len),eqIdx2=eqIndex(str,index,endIdx2),attr=eqIdx2===-1?valueSlice(str,index,endIdx2):valueSlice(str,index,eqIdx2),val=eqIdx2===-1?void 0:valueSlice(str,eqIdx2+1,endIdx2);switch(attr.toLowerCase()){case"httponly":setCookie.httpOnly=!0;break;case"secure":setCookie.secure=!0;break;case"partitioned":setCookie.partitioned=!0;break;case"domain":setCookie.domain=val;break;case"path":setCookie.path=val;break;case"max-age":if(val&&maxAgeRegExp.test(val))setCookie.maxAge=Number(val);break;case"expires":if(!val)break;let date2=new Date(val);if(Number.isFinite(date2.valueOf()))setCookie.expires=date2;break;case"priority":if(!val)break;let priority=val.toLowerCase();if(priority==="low"||priority==="medium"||priority==="high")setCookie.priority=priority;break;case"samesite":if(!val)break;let sameSite=val.toLowerCase();if(sameSite==="lax"||sameSite==="strict"||sameSite==="none")setCookie.sameSite=sameSite;break}index=endIdx2+1}return setCookie}function endIndex(str,min,len){let index=str.indexOf(";",min);return index===-1?len:index}function eqIndex(str,min,max){let index=str.indexOf("=",min);return index<max?index:-1}function valueSlice(str,min,max){let start=min,end=max;do{let code=str.charCodeAt(start);if(code!==32&&code!==9)break}while(++start<end);while(end>start){let code=str.charCodeAt(end-1);if(code!==32&&code!==9)break;end--}return str.slice(start,end)}function decode(str){if(str.indexOf("%")===-1)return str;try{return decodeURIComponent(str)}catch(e){return str}}function isDate(val){return __toString.call(val)==="[object Date]"}});var Y=(v,b)=>{let A=b?.length?{}:null;if(A)for(let Q of b)A[Q.part.charCodeAt(0)]=Q;return{part:v,store:null,inert:A,params:null,wildcardStore:null}},k=(v,b)=>({...v,part:b}),T=(v)=>({name:v,store:null,inert:null});class _{config;root={};history=[];deferred=[];constructor(v={}){if(this.config=v,v.lazy)this.find=this.lazyFind;if(v.onParam&&!Array.isArray(v.onParam))this.config.onParam=[this.config.onParam]}static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/(\/:\w+\?)/g};lazyFind=(v,b)=>{if(!this.config.lazy)return this.find;return this.build(),this.find(v,b)};build(){if(!this.config.lazy)return;for(let[v,b,A]of this.deferred)this.add(v,b,A,{lazy:!1,ignoreHistory:!0});this.deferred=[],this.find=(v,b)=>{let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}add(v,b,A,{ignoreError:Q=!1,ignoreHistory:O=!1,lazy:V=this.config.lazy}={}){if(V)return this.find=this.lazyFind,this.deferred.push([v,b,A]),A;if(typeof b!=="string")throw TypeError("Route path must be a string");if(b==="")b="/";else if(b[0]!=="/")b=`/${b}`;let X=b[b.length-1]==="*",J=b.match(_.regex.optionalParams);if(J){let F=b.replaceAll("?","");this.add(v,F,A,{ignoreError:Q,ignoreHistory:O,lazy:V});for(let B=0;B<J.length;B++){let D=b.replace(J[B],"");this.add(v,D,A,{ignoreError:!0,ignoreHistory:O,lazy:V})}return A}if(J)b=b.replaceAll("?","");if(this.history.find(([F,B,D])=>F===v&&B===b))return A;if(X||J&&b.charCodeAt(b.length-1)===63)b=b.slice(0,-1);if(!O)this.history.push([v,b,A]);let K=b.split(_.regex.static),G=b.match(_.regex.params)||[];if(K[K.length-1]==="")K.pop();let q;if(!this.root[v])q=this.root[v]=Y("/");else q=this.root[v];let U=0;for(let F=0;F<K.length;++F){let B=K[F];if(F>0){let D=G[U++].slice(1);if(q.params===null)q.params=T(D);else if(q.params.name!==D)if(Q)return A;else throw Error(`Cannot create route "${b}" with parameter "${D}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);let S=q.params;if(S.inert===null){q=S.inert=Y(B);continue}q=S.inert}for(let D=0;;){if(D===B.length){if(D<q.part.length){let S=k(q,q.part.slice(D));Object.assign(q,Y(B,[S]))}break}if(D===q.part.length){if(q.inert===null)q.inert={};let S=q.inert[B.charCodeAt(D)];if(S){q=S,B=B.slice(D),D=0;continue}let Z=Y(B.slice(D));q.inert[B.charCodeAt(D)]=Z,q=Z;break}if(B[D]!==q.part[D]){let S=k(q,q.part.slice(D)),Z=Y(B.slice(D));Object.assign(q,Y(q.part.slice(0,D),[S,Z])),q=Z;break}++D}}if(U<G.length){let B=G[U].slice(1);if(q.params===null)q.params=T(B);else if(q.params.name!==B)if(Q)return A;else throw Error(`Cannot create route "${b}" with parameter "${B}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);if(q.params.store===null)q.params.store=A;return q.params.store}if(X){if(q.wildcardStore===null)q.wildcardStore=A;return q.wildcardStore}if(q.store===null)q.store=A;return q.store}find(v,b){let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}var $=(v,b,A,Q,O)=>{let V=A.part,X=V.length,J=Q+X;if(X>1){if(J>b)return null;if(X<15){for(let K=1,G=Q+1;K<X;++K,++G)if(V.charCodeAt(K)!==v.charCodeAt(G))return null}else if(v.slice(Q,J)!==V)return null}if(J===b){if(A.store!==null)return{store:A.store,params:{}};if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":""}};return null}if(A.inert!==null){let K=A.inert[v.charCodeAt(J)];if(K!==void 0){let G=$(v,b,K,J,O);if(G!==null)return G}}if(A.params!==null){let{store:K,name:G,inert:q}=A.params,U=v.indexOf("/",J);if(U!==J){if(U===-1||U>=b){if(K!==null){let F={};if(F[G]=v.substring(J,b),O)for(let B=0;B<O.length;B++){let D=O[B](F[G],G);if(D!==void 0)F[G]=D}return{store:K,params:F}}}else if(q!==null){let F=$(v,b,q,U,O);if(F!==null){if(F.params[G]=v.substring(J,U),O)for(let B=0;B<O.length;B++){let D=O[B](F.params[G],G);if(D!==void 0)F.params[G]=D}return F}}}}if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":v.substring(J,b)}};return null};var import_fast_decode_uri_component4=__toESM(require_fast_decode_uri_component(),1);import{Kind as Kind7}from"@sinclair/typebox";import{Type,Kind as Kind2}from"@sinclair/typebox";import{Kind,TypeRegistry,Unsafe}from"@sinclair/typebox";import{Value as Value2}from"@sinclair/typebox/value";import{TypeCompiler}from"@sinclair/typebox/compiler";var isBun=typeof Bun<"u";var mime={aac:"audio/aac",abw:"application/x-abiword",ai:"application/postscript",arc:"application/octet-stream",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",dll:"application/octet-stream",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",mid:"audio/midi",midi:"audio/midi",mp2:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mpa:"video/mpeg",mpe:"video/mpeg",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",otf:"font/otf",png:"image/png",pdf:"application/pdf",ppt:"application/vnd.ms-powerpoint",rar:"application/x-rar-compressed",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"application/typescript",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/x-wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xlsx_OLD:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3gp_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp","3gp2":"video/3gpp2","3gp2_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp2","7z":"application/x-7z-compressed"},getFileExtension=(path)=>{let index=path.lastIndexOf(".");if(index===-1)return"";return path.slice(index+1)},file=(path)=>new ElysiaFile(path),createReadStream,stat;class ElysiaFile{path;value;stats;constructor(path){this.path=path;if(isBun)this.value=Bun.file(path);else{if(!createReadStream||!stat){if(typeof window<"u"){console.warn("Browser environment does not support file");return}let warnMissing=(name)=>console.warn(Error(`[elysia] \`file\` require \`fs${name?"."+name:""}\` ${name?.includes(".")?"module ":""}which is not available in this environment`));if(typeof process>"u"||typeof process.getBuiltinModule!=="function"){warnMissing();return}let fs=process.getBuiltinModule("fs");if(!fs){warnMissing();return}if(typeof fs.createReadStream!=="function"){warnMissing();return}if(typeof fs.promises?.stat!=="function"){warnMissing();return}createReadStream=fs.createReadStream,stat=fs.promises.stat}this.value=(()=>createReadStream(path))(),this.stats=stat(path)}}get type(){return mime[getFileExtension(this.path)]||"application/octet-stream"}get length(){if(isBun)return this.value.size;return this.stats?.then((x)=>x.size)??0}}import{Value}from"@sinclair/typebox/value";var hasHeaderShorthand="toJSON"in new Headers,replaceUrlPath=(url,pathname)=>{let urlObject=new URL(url);return urlObject.pathname=pathname,urlObject.toString()},isClass=(v)=>typeof v==="function"&&/^\s*class\s+/.test(v.toString())||v.toString&&v.toString().startsWith("[object ")&&v.toString()!=="[object Object]"||isNotEmpty(Object.getPrototypeOf(v)),isObject=(item)=>item&&typeof item==="object"&&!Array.isArray(item),mergeDeep=(target,source,options)=>{let skipKeys=options?.skipKeys,override=options?.override??!0,mergeArray=options?.mergeArray??!1,seen=options?.seen??new WeakSet;if(!isObject(target)||!isObject(source))return target;if(seen.has(source))return target;seen.add(source);for(let[key,value]of Object.entries(source)){if(skipKeys?.includes(key)||["__proto__","constructor","prototype"].includes(key))continue;if(mergeArray&&Array.isArray(value)){target[key]=Array.isArray(target[key])?[...target[key],...value]:target[key]=value;continue}if(!isObject(value)||!(key in target)||isClass(value)){if((override||!(key in target))&&!Object.isFrozen(target))try{target[key]=value}catch{}continue}if(!Object.isFrozen(target[key]))try{target[key]=mergeDeep(target[key],value,{skipKeys,override,mergeArray,seen})}catch{}}return seen.delete(source),target},mergeCookie=(a,b)=>{let v=mergeDeep(Object.assign({},a),b,{skipKeys:["properties"],mergeArray:!1});if(v.properties)delete v.properties;return v},mergeObjectArray=(a,b)=>{if(!b)return a;let array=[],checksums=[];if(a){if(!Array.isArray(a))a=[a];for(let item of a)if(array.push(item),item.checksum)checksums.push(item.checksum)}if(b){if(!Array.isArray(b))b=[b];for(let item of b)if(!checksums.includes(item.checksum))array.push(item)}return array},primitiveHooks=["start","request","parse","transform","resolve","beforeHandle","afterHandle","mapResponse","afterResponse","trace","error","stop","body","headers","params","query","response","type","detail"],primitiveHookMap=primitiveHooks.reduce((acc,x)=>(acc[x]=!0,acc),{}),isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every((x2)=>!isNaN(+x2)),mergeResponse=(a,b)=>{if(isRecordNumber(a)&&isRecordNumber(b))return Object.assign({},a,b);else if(a&&!isRecordNumber(a)&&isRecordNumber(b))return Object.assign({200:a},b);return b??a},mergeSchemaValidator=(a,b)=>{if(!a&&!b)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return{body:b?.body??a?.body,headers:b?.headers??a?.headers,params:b?.params??a?.params,query:b?.query??a?.query,cookie:b?.cookie??a?.cookie,response:mergeResponse(a?.response,b?.response)}},mergeHook=(a,b)=>{if(!b)return a??{};if(!a)return b??{};if(!Object.values(b).find((x)=>x!==void 0&&x!==null))return{...a};let hook={...a,...b,body:b.body??a.body,headers:b.headers??a.headers,params:b.params??a.params,query:b.query??a.query,cookie:b.cookie??a.cookie,response:mergeResponse(a.response,b.response),type:a.type||b.type,detail:mergeDeep(b.detail??{},a.detail??{}),parse:mergeObjectArray(a.parse,b.parse),transform:mergeObjectArray(a.transform,b.transform),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a.resolve,"resolve"),a.beforeHandle),mergeObjectArray(fnToContainer(b.resolve,"resolve"),b.beforeHandle)),afterHandle:mergeObjectArray(a.afterHandle,b.afterHandle),mapResponse:mergeObjectArray(a.mapResponse,b.mapResponse),afterResponse:mergeObjectArray(a.afterResponse,b.afterResponse),trace:mergeObjectArray(a.trace,b.trace),error:mergeObjectArray(a.error,b.error),standaloneSchema:a.standaloneSchema||b.standaloneSchema?a.standaloneSchema&&!b.standaloneSchema?a.standaloneSchema:b.standaloneSchema&&!a.standaloneSchema?b.standaloneSchema:[...a.standaloneSchema??[],...b.standaloneSchema??[]]:void 0};if(hook.resolve)delete hook.resolve;return hook},lifeCycleToArray=(a)=>{if(a.parse&&!Array.isArray(a.parse))a.parse=[a.parse];if(a.transform&&!Array.isArray(a.transform))a.transform=[a.transform];if(a.afterHandle&&!Array.isArray(a.afterHandle))a.afterHandle=[a.afterHandle];if(a.mapResponse&&!Array.isArray(a.mapResponse))a.mapResponse=[a.mapResponse];if(a.afterResponse&&!Array.isArray(a.afterResponse))a.afterResponse=[a.afterResponse];if(a.trace&&!Array.isArray(a.trace))a.trace=[a.trace];if(a.error&&!Array.isArray(a.error))a.error=[a.error];let beforeHandle=[];if(a.resolve)beforeHandle=fnToContainer(Array.isArray(a.resolve)?a.resolve:[a.resolve],"resolve"),delete a.resolve;if(a.beforeHandle)if(beforeHandle.length)beforeHandle=beforeHandle.concat(Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle]);else beforeHandle=Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle];if(beforeHandle.length)a.beforeHandle=beforeHandle;return a},isBun2=typeof Bun<"u",hasBunHash=isBun2&&typeof Bun.hash==="function",hasSetImmediate=typeof setImmediate==="function",checksum=(s)=>{let h=9;for(let i=0;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),387420489);return h=h^h>>>9},injectChecksum=(checksum2,x)=>{if(!x)return;if(!Array.isArray(x)){let fn=x;if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local";return fn}let fns=[...x];for(let fn of fns){if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local"}return fns},mergeLifeCycle=(a,b,checksum2)=>{return{start:mergeObjectArray(a.start,injectChecksum(checksum2,b?.start)),request:mergeObjectArray(a.request,injectChecksum(checksum2,b?.request)),parse:mergeObjectArray(a.parse,injectChecksum(checksum2,b?.parse)),transform:mergeObjectArray(a.transform,injectChecksum(checksum2,b?.transform)),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a.resolve,"resolve"),a.beforeHandle),injectChecksum(checksum2,mergeObjectArray(fnToContainer(b?.resolve,"resolve"),b?.beforeHandle))),afterHandle:mergeObjectArray(a.afterHandle,injectChecksum(checksum2,b?.afterHandle)),mapResponse:mergeObjectArray(a.mapResponse,injectChecksum(checksum2,b?.mapResponse)),afterResponse:mergeObjectArray(a.afterResponse,injectChecksum(checksum2,b?.afterResponse)),trace:mergeObjectArray(a.trace,injectChecksum(checksum2,b?.trace)),error:mergeObjectArray(a.error,injectChecksum(checksum2,b?.error)),stop:mergeObjectArray(a.stop,injectChecksum(checksum2,b?.stop))}},asHookType=(fn,inject,{skipIfHasType=!1})=>{if(!fn)return fn;if(!Array.isArray(fn)){if(skipIfHasType)fn.scope??=inject;else fn.scope=inject;return fn}for(let x of fn)if(skipIfHasType)x.scope??=inject;else x.scope=inject;return fn},filterGlobal=(fn)=>{if(!fn)return fn;if(!Array.isArray(fn))switch(fn.scope){case"global":case"scoped":return{...fn};default:return{fn}}let array=[];for(let x of fn)switch(x.scope){case"global":case"scoped":array.push({...x});break}return array},filterGlobalHook=(hook)=>{return{...hook,type:hook?.type,detail:hook?.detail,parse:filterGlobal(hook?.parse),transform:filterGlobal(hook?.transform),beforeHandle:filterGlobal(hook?.beforeHandle),afterHandle:filterGlobal(hook?.afterHandle),mapResponse:filterGlobal(hook?.mapResponse),afterResponse:filterGlobal(hook?.afterResponse),error:filterGlobal(hook?.error),trace:filterGlobal(hook?.trace)}},StatusMap={Continue:100,"Switching Protocols":101,Processing:102,"Early Hints":103,OK:200,Created:201,Accepted:202,"Non-Authoritative Information":203,"No Content":204,"Reset Content":205,"Partial Content":206,"Multi-Status":207,"Already Reported":208,"Multiple Choices":300,"Moved Permanently":301,Found:302,"See Other":303,"Not Modified":304,"Temporary Redirect":307,"Permanent Redirect":308,"Bad Request":400,Unauthorized:401,"Payment Required":402,Forbidden:403,"Not Found":404,"Method Not Allowed":405,"Not Acceptable":406,"Proxy Authentication Required":407,"Request Timeout":408,Conflict:409,Gone:410,"Length Required":411,"Precondition Failed":412,"Payload Too Large":413,"URI Too Long":414,"Unsupported Media Type":415,"Range Not Satisfiable":416,"Expectation Failed":417,"I'm a teapot":418,"Enhance Your Calm":420,"Misdirected Request":421,"Unprocessable Content":422,Locked:423,"Failed Dependency":424,"Too Early":425,"Upgrade Required":426,"Precondition Required":428,"Too Many Requests":429,"Request Header Fields Too Large":431,"Unavailable For Legal Reasons":451,"Internal Server Error":500,"Not Implemented":501,"Bad Gateway":502,"Service Unavailable":503,"Gateway Timeout":504,"HTTP Version Not Supported":505,"Variant Also Negotiates":506,"Insufficient Storage":507,"Loop Detected":508,"Not Extended":510,"Network Authentication Required":511},InvertedStatusMap=Object.fromEntries(Object.entries(StatusMap).map(([k2,v])=>[v,k2]));function removeTrailingEquals(digest){let trimmedDigest=digest;while(trimmedDigest.endsWith("="))trimmedDigest=trimmedDigest.slice(0,-1);return trimmedDigest}var encoder=new TextEncoder,signCookie=async(val,secret)=>{if(typeof val==="object")val=JSON.stringify(val);else if(typeof val!=="string")val=val+"";if(secret===null)throw TypeError("Secret key must be provided.");let secretKey=await crypto.subtle.importKey("raw",encoder.encode(secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),hmacBuffer=await crypto.subtle.sign("HMAC",secretKey,encoder.encode(val));return val+"."+removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"))},constantTimeEqual=typeof crypto?.timingSafeEqual==="function"?(a,b)=>{let ab=Buffer.from(a,"utf8"),bb=Buffer.from(b,"utf8");if(ab.length!==bb.length)return!1;return crypto.timingSafeEqual(ab,bb)}:(a,b)=>a===b,unsignCookie=async(input,secret)=>{if(typeof input!=="string")throw TypeError("Signed cookie string must be provided.");if(secret===null)throw TypeError("Secret key must be provided.");let dot=input.lastIndexOf(".");if(dot<=0)return!1;let tentativeValue=input.slice(0,dot),expectedInput=await signCookie(tentativeValue,secret);return constantTimeEqual(expectedInput,input)?tentativeValue:!1},insertStandaloneValidator=(hook,name,value)=>{if(!hook.standaloneValidator?.length||!Array.isArray(hook.standaloneValidator)){hook.standaloneValidator=[{[name]:value}];return}let last=hook.standaloneValidator[hook.standaloneValidator.length-1];if(name in last)hook.standaloneValidator.push({[name]:value});else last[name]=value},parseNumericString=(message)=>{if(typeof message==="number")return message;if(message.length<16){if(message.trim().length===0)return null;let length=Number(message);if(Number.isNaN(length))return null;return length}if(message.length===16){if(message.trim().length===0)return null;let number=Number(message);if(Number.isNaN(number)||number.toString()!==message)return null;return number}return null},isNumericString=(message)=>parseNumericString(message)!==null;class PromiseGroup{onError;onFinally;root=null;promises=[];constructor(onError=console.error,onFinally=()=>{}){this.onError=onError;this.onFinally=onFinally}get size(){return this.promises.length}add(promise){if(this.promises.push(promise),this.root||=this.drain(),this.promises.length===1)this.then(this.onFinally);return promise}async drain(){while(this.promises.length>0){try{await this.promises[0]}catch(error){this.onError(error)}this.promises.shift()}this.root=null}then(onfulfilled,onrejected){return(this.root??Promise.resolve()).then(onfulfilled,onrejected)}}var fnToContainer=(fn,subType)=>{if(!fn)return fn;if(!Array.isArray(fn)){if(typeof fn==="function"||typeof fn==="string")return subType?{fn,subType}:{fn};else if("fn"in fn)return fn}let fns=[];for(let x of fn)if(typeof x==="function"||typeof x==="string")fns.push(subType?{fn:x,subType}:{fn:x});else if("fn"in x)fns.push(x);return fns},localHookToLifeCycleStore=(a)=>{if(a.start)a.start=fnToContainer(a.start);if(a.request)a.request=fnToContainer(a.request);if(a.parse)a.parse=fnToContainer(a.parse);if(a.transform)a.transform=fnToContainer(a.transform);if(a.beforeHandle)a.beforeHandle=fnToContainer(a.beforeHandle);if(a.afterHandle)a.afterHandle=fnToContainer(a.afterHandle);if(a.mapResponse)a.mapResponse=fnToContainer(a.mapResponse);if(a.afterResponse)a.afterResponse=fnToContainer(a.afterResponse);if(a.trace)a.trace=fnToContainer(a.trace);if(a.error)a.error=fnToContainer(a.error);if(a.stop)a.stop=fnToContainer(a.stop);return a},lifeCycleToFn=(a)=>{let lifecycle=Object.create(null);if(a.start?.map)lifecycle.start=a.start.map((x)=>x.fn);if(a.request?.map)lifecycle.request=a.request.map((x)=>x.fn);if(a.parse?.map)lifecycle.parse=a.parse.map((x)=>x.fn);if(a.transform?.map)lifecycle.transform=a.transform.map((x)=>x.fn);if(a.beforeHandle?.map)lifecycle.beforeHandle=a.beforeHandle.map((x)=>x.fn);if(a.afterHandle?.map)lifecycle.afterHandle=a.afterHandle.map((x)=>x.fn);if(a.mapResponse?.map)lifecycle.mapResponse=a.mapResponse.map((x)=>x.fn);if(a.afterResponse?.map)lifecycle.afterResponse=a.afterResponse.map((x)=>x.fn);if(a.error?.map)lifecycle.error=a.error.map((x)=>x.fn);if(a.stop?.map)lifecycle.stop=a.stop.map((x)=>x.fn);if(a.trace?.map)lifecycle.trace=a.trace.map((x)=>x.fn);else lifecycle.trace=[];return lifecycle},cloneInference=(inference)=>({body:inference.body,cookie:inference.cookie,headers:inference.headers,query:inference.query,set:inference.set,server:inference.server,path:inference.path,route:inference.route,url:inference.url}),redirect=(url,status=302)=>Response.redirect(url,status),ELYSIA_FORM_DATA=Symbol("ElysiaFormData"),ELYSIA_REQUEST_ID=Symbol("ElysiaRequestId"),form=(items)=>{let formData=new FormData;if(formData[ELYSIA_FORM_DATA]={},items)for(let[key,value]of Object.entries(items)){if(Array.isArray(value)){formData[ELYSIA_FORM_DATA][key]=[];for(let v of value){if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key].push(value)}continue}if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key]=value}return formData},randomId=typeof crypto>"u"?()=>{let result="",characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",charactersLength=characters.length;for(let i=0;i<16;i++)result+=characters.charAt(Math.floor(Math.random()*charactersLength));return result}:()=>{let uuid=crypto.randomUUID();return uuid.slice(0,8)+uuid.slice(24,32)},deduplicateChecksum=(array)=>{if(!array.length)return[];let hashes=[];for(let i=0;i<array.length;i++){let item=array[i];if(item.checksum){if(hashes.includes(item.checksum))array.splice(i,1),i--;hashes.push(item.checksum)}}return array},promoteEvent=(events,as="scoped")=>{if(!events)return;if(as==="scoped"){for(let event of events)if("scope"in event&&event.scope==="local")event.scope="scoped";return}for(let event of events)if("scope"in event)event.scope="global"},getLoosePath=(path)=>{if(path.charCodeAt(path.length-1)===47)return path.slice(0,path.length-1);return path+"/"},isNotEmpty=(obj)=>{if(!obj)return!1;for(let _2 in obj)return!0;return!1},encodePath=(path,{dynamic=!1}={})=>{let encoded=encodeURIComponent(path).replace(/%2F/g,"/");if(dynamic)encoded=encoded.replace(/%3A/g,":").replace(/%3F/g,"?");return encoded},supportPerMethodInlineHandler=(()=>{if(typeof Bun>"u")return!0;if(Bun.semver?.satisfies?.(Bun.version,">=1.2.14"))return!0;return!1})(),sse=(_payload)=>{if(_payload instanceof ReadableStream)return _payload.sse=!0,_payload;let payload=typeof _payload==="string"?{data:_payload}:_payload;return payload.sse=!0,payload.toSSE=()=>{let payloadString="";if(payload.id!==void 0&&payload.id!==null)payloadString+=`id: ${payload.id}
2
+ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;var __toESM=(mod,isNodeMode,target)=>{target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:()=>mod[key],enumerable:!0});return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __require=import.meta.require;var require_fast_decode_uri_component=__commonJS((exports,module)=>{var UTF8_ACCEPT=12,UTF8_REJECT=0,UTF8_DATA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function decodeURIComponent2(uri){var percentPosition=uri.indexOf("%");if(percentPosition===-1)return uri;var length=uri.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri[percentPosition+1],4),low=hexCodeToInt(uri[percentPosition+2],0),byte=high|low,type=UTF8_DATA[byte];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri.slice(last)}var HEX={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function hexCodeToInt(c,shift){var i=HEX[c];return i===void 0?255:i<<shift}module.exports=decodeURIComponent2});var require_dist=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.parseCookie=parseCookie;exports.parse=parseCookie;exports.stringifyCookie=stringifyCookie;exports.stringifySetCookie=stringifySetCookie;exports.serialize=stringifySetCookie;exports.parseSetCookie=parseSetCookie;exports.stringifySetCookie=stringifySetCookie;exports.serialize=stringifySetCookie;var cookieNameRegExp=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,cookieValueRegExp=/^[\u0021-\u003A\u003C-\u007E]*$/,domainValueRegExp=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,pathValueRegExp=/^[\u0020-\u003A\u003D-\u007E]*$/,maxAgeRegExp=/^-?\d+$/,__toString=Object.prototype.toString,NullObject=(()=>{let C=function(){};return C.prototype=Object.create(null),C})();function parseCookie(str,options){let obj=new NullObject,len=str.length;if(len<2)return obj;let dec=options?.decode||decode,index=0;do{let eqIdx=eqIndex(str,index,len);if(eqIdx===-1)break;let endIdx=endIndex(str,index,len);if(eqIdx>endIdx){index=str.lastIndexOf(";",eqIdx-1)+1;continue}let key=valueSlice(str,index,eqIdx);if(obj[key]===void 0)obj[key]=dec(valueSlice(str,eqIdx+1,endIdx));index=endIdx+1}while(index<len);return obj}function stringifyCookie(cookie,options){let enc=options?.encode||encodeURIComponent,cookieStrings=[];for(let name of Object.keys(cookie)){let val=cookie[name];if(val===void 0)continue;if(!cookieNameRegExp.test(name))throw TypeError(`cookie name is invalid: ${name}`);let value=enc(val);if(!cookieValueRegExp.test(value))throw TypeError(`cookie val is invalid: ${val}`);cookieStrings.push(`${name}=${value}`)}return cookieStrings.join("; ")}function stringifySetCookie(_name,_val,_opts){let cookie=typeof _name==="object"?_name:{..._opts,name:_name,value:String(_val)},enc=(typeof _val==="object"?_val:_opts)?.encode||encodeURIComponent;if(!cookieNameRegExp.test(cookie.name))throw TypeError(`argument name is invalid: ${cookie.name}`);let value=cookie.value?enc(cookie.value):"";if(!cookieValueRegExp.test(value))throw TypeError(`argument val is invalid: ${cookie.value}`);let str=cookie.name+"="+value;if(cookie.maxAge!==void 0){if(!Number.isInteger(cookie.maxAge))throw TypeError(`option maxAge is invalid: ${cookie.maxAge}`);str+="; Max-Age="+cookie.maxAge}if(cookie.domain){if(!domainValueRegExp.test(cookie.domain))throw TypeError(`option domain is invalid: ${cookie.domain}`);str+="; Domain="+cookie.domain}if(cookie.path){if(!pathValueRegExp.test(cookie.path))throw TypeError(`option path is invalid: ${cookie.path}`);str+="; Path="+cookie.path}if(cookie.expires){if(!isDate(cookie.expires)||!Number.isFinite(cookie.expires.valueOf()))throw TypeError(`option expires is invalid: ${cookie.expires}`);str+="; Expires="+cookie.expires.toUTCString()}if(cookie.httpOnly)str+="; HttpOnly";if(cookie.secure)str+="; Secure";if(cookie.partitioned)str+="; Partitioned";if(cookie.priority)switch(typeof cookie.priority==="string"?cookie.priority.toLowerCase():void 0){case"low":str+="; Priority=Low";break;case"medium":str+="; Priority=Medium";break;case"high":str+="; Priority=High";break;default:throw TypeError(`option priority is invalid: ${cookie.priority}`)}if(cookie.sameSite)switch(typeof cookie.sameSite==="string"?cookie.sameSite.toLowerCase():cookie.sameSite){case!0:case"strict":str+="; SameSite=Strict";break;case"lax":str+="; SameSite=Lax";break;case"none":str+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${cookie.sameSite}`)}return str}function parseSetCookie(str,options){let dec=options?.decode||decode,len=str.length,endIdx=endIndex(str,0,len),eqIdx=eqIndex(str,0,endIdx),setCookie=eqIdx===-1?{name:"",value:dec(valueSlice(str,0,endIdx))}:{name:valueSlice(str,0,eqIdx),value:dec(valueSlice(str,eqIdx+1,endIdx))},index=endIdx+1;while(index<len){let endIdx2=endIndex(str,index,len),eqIdx2=eqIndex(str,index,endIdx2),attr=eqIdx2===-1?valueSlice(str,index,endIdx2):valueSlice(str,index,eqIdx2),val=eqIdx2===-1?void 0:valueSlice(str,eqIdx2+1,endIdx2);switch(attr.toLowerCase()){case"httponly":setCookie.httpOnly=!0;break;case"secure":setCookie.secure=!0;break;case"partitioned":setCookie.partitioned=!0;break;case"domain":setCookie.domain=val;break;case"path":setCookie.path=val;break;case"max-age":if(val&&maxAgeRegExp.test(val))setCookie.maxAge=Number(val);break;case"expires":if(!val)break;let date2=new Date(val);if(Number.isFinite(date2.valueOf()))setCookie.expires=date2;break;case"priority":if(!val)break;let priority=val.toLowerCase();if(priority==="low"||priority==="medium"||priority==="high")setCookie.priority=priority;break;case"samesite":if(!val)break;let sameSite=val.toLowerCase();if(sameSite==="lax"||sameSite==="strict"||sameSite==="none")setCookie.sameSite=sameSite;break}index=endIdx2+1}return setCookie}function endIndex(str,min,len){let index=str.indexOf(";",min);return index===-1?len:index}function eqIndex(str,min,max){let index=str.indexOf("=",min);return index<max?index:-1}function valueSlice(str,min,max){let start=min,end=max;do{let code=str.charCodeAt(start);if(code!==32&&code!==9)break}while(++start<end);while(end>start){let code=str.charCodeAt(end-1);if(code!==32&&code!==9)break;end--}return str.slice(start,end)}function decode(str){if(str.indexOf("%")===-1)return str;try{return decodeURIComponent(str)}catch(e){return str}}function isDate(val){return __toString.call(val)==="[object Date]"}});var Y=(v,b)=>{let A=b?.length?{}:null;if(A)for(let Q of b)A[Q.part.charCodeAt(0)]=Q;return{part:v,store:null,inert:A,params:null,wildcardStore:null}},k=(v,b)=>({...v,part:b}),T=(v)=>({name:v,store:null,inert:null});class _{config;root={};history=[];deferred=[];constructor(v={}){if(this.config=v,v.lazy)this.find=this.lazyFind;if(v.onParam&&!Array.isArray(v.onParam))this.config.onParam=[this.config.onParam]}static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/(\/:\w+\?)/g};lazyFind=(v,b)=>{if(!this.config.lazy)return this.find;return this.build(),this.find(v,b)};build(){if(!this.config.lazy)return;for(let[v,b,A]of this.deferred)this.add(v,b,A,{lazy:!1,ignoreHistory:!0});this.deferred=[],this.find=(v,b)=>{let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}add(v,b,A,{ignoreError:Q=!1,ignoreHistory:O=!1,lazy:V=this.config.lazy}={}){if(V)return this.find=this.lazyFind,this.deferred.push([v,b,A]),A;if(typeof b!=="string")throw TypeError("Route path must be a string");if(b==="")b="/";else if(b[0]!=="/")b=`/${b}`;let X=b[b.length-1]==="*",J=b.match(_.regex.optionalParams);if(J){let F=b.replaceAll("?","");this.add(v,F,A,{ignoreError:Q,ignoreHistory:O,lazy:V});for(let B=0;B<J.length;B++){let D=b.replace(J[B],"");this.add(v,D,A,{ignoreError:!0,ignoreHistory:O,lazy:V})}return A}if(J)b=b.replaceAll("?","");if(this.history.find(([F,B,D])=>F===v&&B===b))return A;if(X||J&&b.charCodeAt(b.length-1)===63)b=b.slice(0,-1);if(!O)this.history.push([v,b,A]);let K=b.split(_.regex.static),G=b.match(_.regex.params)||[];if(K[K.length-1]==="")K.pop();let q;if(!this.root[v])q=this.root[v]=Y("/");else q=this.root[v];let U=0;for(let F=0;F<K.length;++F){let B=K[F];if(F>0){let D=G[U++].slice(1);if(q.params===null)q.params=T(D);else if(q.params.name!==D)if(Q)return A;else throw Error(`Cannot create route "${b}" with parameter "${D}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);let S=q.params;if(S.inert===null){q=S.inert=Y(B);continue}q=S.inert}for(let D=0;;){if(D===B.length){if(D<q.part.length){let S=k(q,q.part.slice(D));Object.assign(q,Y(B,[S]))}break}if(D===q.part.length){if(q.inert===null)q.inert={};let S=q.inert[B.charCodeAt(D)];if(S){q=S,B=B.slice(D),D=0;continue}let Z=Y(B.slice(D));q.inert[B.charCodeAt(D)]=Z,q=Z;break}if(B[D]!==q.part[D]){let S=k(q,q.part.slice(D)),Z=Y(B.slice(D));Object.assign(q,Y(q.part.slice(0,D),[S,Z])),q=Z;break}++D}}if(U<G.length){let B=G[U].slice(1);if(q.params===null)q.params=T(B);else if(q.params.name!==B)if(Q)return A;else throw Error(`Cannot create route "${b}" with parameter "${B}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);if(q.params.store===null)q.params.store=A;return q.params.store}if(X){if(q.wildcardStore===null)q.wildcardStore=A;return q.wildcardStore}if(q.store===null)q.store=A;return q.store}find(v,b){let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}var $=(v,b,A,Q,O)=>{let V=A.part,X=V.length,J=Q+X;if(X>1){if(J>b)return null;if(X<15){for(let K=1,G=Q+1;K<X;++K,++G)if(V.charCodeAt(K)!==v.charCodeAt(G))return null}else if(v.slice(Q,J)!==V)return null}if(J===b){if(A.store!==null)return{store:A.store,params:{}};if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":""}};return null}if(A.inert!==null){let K=A.inert[v.charCodeAt(J)];if(K!==void 0){let G=$(v,b,K,J,O);if(G!==null)return G}}if(A.params!==null){let{store:K,name:G,inert:q}=A.params,U=v.indexOf("/",J);if(U!==J){if(U===-1||U>=b){if(K!==null){let F={};if(F[G]=v.substring(J,b),O)for(let B=0;B<O.length;B++){let D=O[B](F[G],G);if(D!==void 0)F[G]=D}return{store:K,params:F}}}else if(q!==null){let F=$(v,b,q,U,O);if(F!==null){if(F.params[G]=v.substring(J,U),O)for(let B=0;B<O.length;B++){let D=O[B](F.params[G],G);if(D!==void 0)F.params[G]=D}return F}}}}if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":v.substring(J,b)}};return null};var import_fast_decode_uri_component4=__toESM(require_fast_decode_uri_component(),1);import{Kind as Kind7}from"@sinclair/typebox";import{Type,Kind as Kind2}from"@sinclair/typebox";import{Kind,TypeRegistry,Unsafe}from"@sinclair/typebox";import{Value as Value2}from"@sinclair/typebox/value";import{TypeCompiler}from"@sinclair/typebox/compiler";var isBun=typeof Bun<"u";var mime={aac:"audio/aac",abw:"application/x-abiword",ai:"application/postscript",arc:"application/octet-stream",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",dll:"application/octet-stream",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",mid:"audio/midi",midi:"audio/midi",mp2:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mpa:"video/mpeg",mpe:"video/mpeg",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",otf:"font/otf",png:"image/png",pdf:"application/pdf",ppt:"application/vnd.ms-powerpoint",rar:"application/x-rar-compressed",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"application/typescript",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/x-wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xlsx_OLD:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3gp_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp","3gp2":"video/3gpp2","3gp2_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp2","7z":"application/x-7z-compressed"},getFileExtension=(path)=>{let index=path.lastIndexOf(".");if(index===-1)return"";return path.slice(index+1)},file=(path)=>new ElysiaFile(path),createReadStream,stat;class ElysiaFile{path;value;stats;constructor(path){this.path=path;if(isBun)this.value=Bun.file(path);else{if(!createReadStream||!stat){if(typeof window<"u"){console.warn("Browser environment does not support file");return}let warnMissing=(name)=>console.warn(Error(`[elysia] \`file\` require \`fs${name?"."+name:""}\` ${name?.includes(".")?"module ":""}which is not available in this environment`));if(typeof process>"u"||typeof process.getBuiltinModule!=="function"){warnMissing();return}let fs=process.getBuiltinModule("fs");if(!fs){warnMissing();return}if(typeof fs.createReadStream!=="function"){warnMissing();return}if(typeof fs.promises?.stat!=="function"){warnMissing();return}createReadStream=fs.createReadStream,stat=fs.promises.stat}this.value=(()=>createReadStream(path))(),this.stats=stat(path)}}get type(){return mime[getFileExtension(this.path)]||"application/octet-stream"}get length(){if(isBun)return this.value.size;return this.stats?.then((x)=>x.size)??0}}import{Value}from"@sinclair/typebox/value";var hasHeaderShorthand="toJSON"in new Headers,replaceUrlPath=(url,pathname)=>{let pathStartIndex=url.indexOf("/",11),queryIndex=url.indexOf("?",pathStartIndex);if(queryIndex===-1)return`${url.slice(0,pathStartIndex)}${pathname.charCodeAt(0)===47?"":"/"}${pathname}`;return`${url.slice(0,pathStartIndex)}${pathname.charCodeAt(0)===47?"":"/"}${pathname}${url.slice(queryIndex)}`},isClass=(v)=>typeof v==="function"&&/^\s*class\s+/.test(v.toString())||v.toString&&v.toString().startsWith("[object ")&&v.toString()!=="[object Object]"||isNotEmpty(Object.getPrototypeOf(v)),isObject=(item)=>item&&typeof item==="object"&&!Array.isArray(item),mergeDeep=(target,source,options)=>{let skipKeys=options?.skipKeys,override=options?.override??!0,mergeArray=options?.mergeArray??!1,seen=options?.seen??new WeakSet;if(!isObject(target)||!isObject(source))return target;if(seen.has(source))return target;seen.add(source);for(let[key,value]of Object.entries(source)){if(skipKeys?.includes(key)||["__proto__","constructor","prototype"].includes(key))continue;if(mergeArray&&Array.isArray(value)){target[key]=Array.isArray(target[key])?[...target[key],...value]:target[key]=value;continue}if(!isObject(value)||!(key in target)||isClass(value)){if((override||!(key in target))&&!Object.isFrozen(target))try{target[key]=value}catch{}continue}if(!Object.isFrozen(target[key]))try{target[key]=mergeDeep(target[key],value,{skipKeys,override,mergeArray,seen})}catch{}}return seen.delete(source),target},mergeCookie=(a,b)=>{let v=mergeDeep(Object.assign({},a),b,{skipKeys:["properties"],mergeArray:!1});if(v.properties)delete v.properties;return v},mergeObjectArray=(a,b)=>{if(!b)return a;let array=[],checksums=[];if(a){if(!Array.isArray(a))a=[a];for(let item of a)if(array.push(item),item.checksum)checksums.push(item.checksum)}if(b){if(!Array.isArray(b))b=[b];for(let item of b)if(!checksums.includes(item.checksum))array.push(item)}return array},primitiveHooks=["start","request","parse","transform","resolve","beforeHandle","afterHandle","mapResponse","afterResponse","trace","error","stop","body","headers","params","query","response","type","detail"],primitiveHookMap=primitiveHooks.reduce((acc,x)=>(acc[x]=!0,acc),{}),isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every((x2)=>!isNaN(+x2)),mergeResponse=(a,b)=>{if(isRecordNumber(a)&&isRecordNumber(b))return Object.assign({},a,b);else if(a&&!isRecordNumber(a)&&isRecordNumber(b))return Object.assign({200:a},b);return b??a},mergeSchemaValidator=(a,b)=>{if(!a&&!b)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return{body:b?.body??a?.body,headers:b?.headers??a?.headers,params:b?.params??a?.params,query:b?.query??a?.query,cookie:b?.cookie??a?.cookie,response:mergeResponse(a?.response,b?.response)}},mergeHook=(a,b)=>{if(!b)return a??{};if(!a)return b??{};if(!Object.values(b).find((x)=>x!==void 0&&x!==null))return{...a};let hook={...a,...b,body:b.body??a.body,headers:b.headers??a.headers,params:b.params??a.params,query:b.query??a.query,cookie:b.cookie??a.cookie,response:mergeResponse(a.response,b.response),type:a.type||b.type,detail:mergeDeep(b.detail??{},a.detail??{}),parse:mergeObjectArray(a.parse,b.parse),transform:mergeObjectArray(a.transform,b.transform),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a.resolve,"resolve"),a.beforeHandle),mergeObjectArray(fnToContainer(b.resolve,"resolve"),b.beforeHandle)),afterHandle:mergeObjectArray(a.afterHandle,b.afterHandle),mapResponse:mergeObjectArray(a.mapResponse,b.mapResponse),afterResponse:mergeObjectArray(a.afterResponse,b.afterResponse),trace:mergeObjectArray(a.trace,b.trace),error:mergeObjectArray(a.error,b.error),standaloneSchema:a.standaloneSchema||b.standaloneSchema?a.standaloneSchema&&!b.standaloneSchema?a.standaloneSchema:b.standaloneSchema&&!a.standaloneSchema?b.standaloneSchema:[...a.standaloneSchema??[],...b.standaloneSchema??[]]:void 0};if(hook.resolve)delete hook.resolve;return hook},lifeCycleToArray=(a)=>{if(a.parse&&!Array.isArray(a.parse))a.parse=[a.parse];if(a.transform&&!Array.isArray(a.transform))a.transform=[a.transform];if(a.afterHandle&&!Array.isArray(a.afterHandle))a.afterHandle=[a.afterHandle];if(a.mapResponse&&!Array.isArray(a.mapResponse))a.mapResponse=[a.mapResponse];if(a.afterResponse&&!Array.isArray(a.afterResponse))a.afterResponse=[a.afterResponse];if(a.trace&&!Array.isArray(a.trace))a.trace=[a.trace];if(a.error&&!Array.isArray(a.error))a.error=[a.error];let beforeHandle=[];if(a.resolve)beforeHandle=fnToContainer(Array.isArray(a.resolve)?a.resolve:[a.resolve],"resolve"),delete a.resolve;if(a.beforeHandle)if(beforeHandle.length)beforeHandle=beforeHandle.concat(Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle]);else beforeHandle=Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle];if(beforeHandle.length)a.beforeHandle=beforeHandle;return a},isBun2=typeof Bun<"u",hasBunHash=isBun2&&typeof Bun.hash==="function",hasSetImmediate=typeof setImmediate==="function",checksum=(s)=>{let h=9;for(let i=0;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),387420489);return h=h^h>>>9},injectChecksum=(checksum2,x)=>{if(!x)return;if(!Array.isArray(x)){let fn=x;if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local";return fn}let fns=[...x];for(let fn of fns){if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local"}return fns},mergeLifeCycle=(a,b,checksum2)=>{return{start:mergeObjectArray(a.start,injectChecksum(checksum2,b?.start)),request:mergeObjectArray(a.request,injectChecksum(checksum2,b?.request)),parse:mergeObjectArray(a.parse,injectChecksum(checksum2,b?.parse)),transform:mergeObjectArray(a.transform,injectChecksum(checksum2,b?.transform)),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a.resolve,"resolve"),a.beforeHandle),injectChecksum(checksum2,mergeObjectArray(fnToContainer(b?.resolve,"resolve"),b?.beforeHandle))),afterHandle:mergeObjectArray(a.afterHandle,injectChecksum(checksum2,b?.afterHandle)),mapResponse:mergeObjectArray(a.mapResponse,injectChecksum(checksum2,b?.mapResponse)),afterResponse:mergeObjectArray(a.afterResponse,injectChecksum(checksum2,b?.afterResponse)),trace:mergeObjectArray(a.trace,injectChecksum(checksum2,b?.trace)),error:mergeObjectArray(a.error,injectChecksum(checksum2,b?.error)),stop:mergeObjectArray(a.stop,injectChecksum(checksum2,b?.stop))}},asHookType=(fn,inject,{skipIfHasType=!1})=>{if(!fn)return fn;if(!Array.isArray(fn)){if(skipIfHasType)fn.scope??=inject;else fn.scope=inject;return fn}for(let x of fn)if(skipIfHasType)x.scope??=inject;else x.scope=inject;return fn},filterGlobal=(fn)=>{if(!fn)return fn;if(!Array.isArray(fn))switch(fn.scope){case"global":case"scoped":return{...fn};default:return{fn}}let array=[];for(let x of fn)switch(x.scope){case"global":case"scoped":array.push({...x});break}return array},filterGlobalHook=(hook)=>{return{...hook,type:hook?.type,detail:hook?.detail,parse:filterGlobal(hook?.parse),transform:filterGlobal(hook?.transform),beforeHandle:filterGlobal(hook?.beforeHandle),afterHandle:filterGlobal(hook?.afterHandle),mapResponse:filterGlobal(hook?.mapResponse),afterResponse:filterGlobal(hook?.afterResponse),error:filterGlobal(hook?.error),trace:filterGlobal(hook?.trace)}},StatusMap={Continue:100,"Switching Protocols":101,Processing:102,"Early Hints":103,OK:200,Created:201,Accepted:202,"Non-Authoritative Information":203,"No Content":204,"Reset Content":205,"Partial Content":206,"Multi-Status":207,"Already Reported":208,"Multiple Choices":300,"Moved Permanently":301,Found:302,"See Other":303,"Not Modified":304,"Temporary Redirect":307,"Permanent Redirect":308,"Bad Request":400,Unauthorized:401,"Payment Required":402,Forbidden:403,"Not Found":404,"Method Not Allowed":405,"Not Acceptable":406,"Proxy Authentication Required":407,"Request Timeout":408,Conflict:409,Gone:410,"Length Required":411,"Precondition Failed":412,"Payload Too Large":413,"URI Too Long":414,"Unsupported Media Type":415,"Range Not Satisfiable":416,"Expectation Failed":417,"I'm a teapot":418,"Enhance Your Calm":420,"Misdirected Request":421,"Unprocessable Content":422,Locked:423,"Failed Dependency":424,"Too Early":425,"Upgrade Required":426,"Precondition Required":428,"Too Many Requests":429,"Request Header Fields Too Large":431,"Unavailable For Legal Reasons":451,"Internal Server Error":500,"Not Implemented":501,"Bad Gateway":502,"Service Unavailable":503,"Gateway Timeout":504,"HTTP Version Not Supported":505,"Variant Also Negotiates":506,"Insufficient Storage":507,"Loop Detected":508,"Not Extended":510,"Network Authentication Required":511},InvertedStatusMap=Object.fromEntries(Object.entries(StatusMap).map(([k2,v])=>[v,k2]));function removeTrailingEquals(digest){let trimmedDigest=digest;while(trimmedDigest.endsWith("="))trimmedDigest=trimmedDigest.slice(0,-1);return trimmedDigest}var encoder=new TextEncoder,signCookie=async(val,secret)=>{if(typeof val==="object")val=JSON.stringify(val);else if(typeof val!=="string")val=val+"";if(secret===null)throw TypeError("Secret key must be provided.");let secretKey=await crypto.subtle.importKey("raw",encoder.encode(secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),hmacBuffer=await crypto.subtle.sign("HMAC",secretKey,encoder.encode(val));return val+"."+removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"))},constantTimeEqual=typeof crypto?.timingSafeEqual==="function"?(a,b)=>{let ab=Buffer.from(a,"utf8"),bb=Buffer.from(b,"utf8");if(ab.length!==bb.length)return!1;return crypto.timingSafeEqual(ab,bb)}:(a,b)=>a===b,unsignCookie=async(input,secret)=>{if(typeof input!=="string")throw TypeError("Signed cookie string must be provided.");if(secret===null)throw TypeError("Secret key must be provided.");let dot=input.lastIndexOf(".");if(dot<=0)return!1;let tentativeValue=input.slice(0,dot),expectedInput=await signCookie(tentativeValue,secret);return constantTimeEqual(expectedInput,input)?tentativeValue:!1},insertStandaloneValidator=(hook,name,value)=>{if(!hook.standaloneValidator?.length||!Array.isArray(hook.standaloneValidator)){hook.standaloneValidator=[{[name]:value}];return}let last=hook.standaloneValidator[hook.standaloneValidator.length-1];if(name in last)hook.standaloneValidator.push({[name]:value});else last[name]=value},parseNumericString=(message)=>{if(typeof message==="number")return message;if(message.length<16){if(message.trim().length===0)return null;let length=Number(message);if(Number.isNaN(length))return null;return length}if(message.length===16){if(message.trim().length===0)return null;let number=Number(message);if(Number.isNaN(number)||number.toString()!==message)return null;return number}return null},isNumericString=(message)=>parseNumericString(message)!==null;class PromiseGroup{onError;onFinally;root=null;promises=[];constructor(onError=console.error,onFinally=()=>{}){this.onError=onError;this.onFinally=onFinally}get size(){return this.promises.length}add(promise){if(this.promises.push(promise),this.root||=this.drain(),this.promises.length===1)this.then(this.onFinally);return promise}async drain(){while(this.promises.length>0){try{await this.promises[0]}catch(error){this.onError(error)}this.promises.shift()}this.root=null}then(onfulfilled,onrejected){return(this.root??Promise.resolve()).then(onfulfilled,onrejected)}}var fnToContainer=(fn,subType)=>{if(!fn)return fn;if(!Array.isArray(fn)){if(typeof fn==="function"||typeof fn==="string")return subType?{fn,subType}:{fn};else if("fn"in fn)return fn}let fns=[];for(let x of fn)if(typeof x==="function"||typeof x==="string")fns.push(subType?{fn:x,subType}:{fn:x});else if("fn"in x)fns.push(x);return fns},localHookToLifeCycleStore=(a)=>{if(a.start)a.start=fnToContainer(a.start);if(a.request)a.request=fnToContainer(a.request);if(a.parse)a.parse=fnToContainer(a.parse);if(a.transform)a.transform=fnToContainer(a.transform);if(a.beforeHandle)a.beforeHandle=fnToContainer(a.beforeHandle);if(a.afterHandle)a.afterHandle=fnToContainer(a.afterHandle);if(a.mapResponse)a.mapResponse=fnToContainer(a.mapResponse);if(a.afterResponse)a.afterResponse=fnToContainer(a.afterResponse);if(a.trace)a.trace=fnToContainer(a.trace);if(a.error)a.error=fnToContainer(a.error);if(a.stop)a.stop=fnToContainer(a.stop);return a},lifeCycleToFn=(a)=>{let lifecycle=Object.create(null);if(a.start?.map)lifecycle.start=a.start.map((x)=>x.fn);if(a.request?.map)lifecycle.request=a.request.map((x)=>x.fn);if(a.parse?.map)lifecycle.parse=a.parse.map((x)=>x.fn);if(a.transform?.map)lifecycle.transform=a.transform.map((x)=>x.fn);if(a.beforeHandle?.map)lifecycle.beforeHandle=a.beforeHandle.map((x)=>x.fn);if(a.afterHandle?.map)lifecycle.afterHandle=a.afterHandle.map((x)=>x.fn);if(a.mapResponse?.map)lifecycle.mapResponse=a.mapResponse.map((x)=>x.fn);if(a.afterResponse?.map)lifecycle.afterResponse=a.afterResponse.map((x)=>x.fn);if(a.error?.map)lifecycle.error=a.error.map((x)=>x.fn);if(a.stop?.map)lifecycle.stop=a.stop.map((x)=>x.fn);if(a.trace?.map)lifecycle.trace=a.trace.map((x)=>x.fn);else lifecycle.trace=[];return lifecycle},cloneInference=(inference)=>({body:inference.body,cookie:inference.cookie,headers:inference.headers,query:inference.query,set:inference.set,server:inference.server,path:inference.path,route:inference.route,url:inference.url}),redirect=(url,status=302)=>Response.redirect(url,status),ELYSIA_FORM_DATA=Symbol("ElysiaFormData"),ELYSIA_REQUEST_ID=Symbol("ElysiaRequestId"),form=(items)=>{let formData=new FormData;if(formData[ELYSIA_FORM_DATA]={},items)for(let[key,value]of Object.entries(items)){if(Array.isArray(value)){formData[ELYSIA_FORM_DATA][key]=[];for(let v of value){if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key].push(value)}continue}if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key]=value}return formData},randomId=typeof crypto>"u"?()=>{let result="",characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",charactersLength=characters.length;for(let i=0;i<16;i++)result+=characters.charAt(Math.floor(Math.random()*charactersLength));return result}:()=>{let uuid=crypto.randomUUID();return uuid.slice(0,8)+uuid.slice(24,32)},deduplicateChecksum=(array)=>{if(!array.length)return[];let hashes=[];for(let i=0;i<array.length;i++){let item=array[i];if(item.checksum){if(hashes.includes(item.checksum))array.splice(i,1),i--;hashes.push(item.checksum)}}return array},promoteEvent=(events,as="scoped")=>{if(!events)return;if(as==="scoped"){for(let event of events)if("scope"in event&&event.scope==="local")event.scope="scoped";return}for(let event of events)if("scope"in event)event.scope="global"},getLoosePath=(path)=>{if(path.charCodeAt(path.length-1)===47)return path.slice(0,path.length-1);return path+"/"},isNotEmpty=(obj)=>{if(!obj)return!1;for(let _2 in obj)return!0;return!1},encodePath=(path,{dynamic=!1}={})=>{let encoded=encodeURIComponent(path).replace(/%2F/g,"/");if(dynamic)encoded=encoded.replace(/%3A/g,":").replace(/%3F/g,"?");return encoded},supportPerMethodInlineHandler=(()=>{if(typeof Bun>"u")return!0;if(Bun.semver?.satisfies?.(Bun.version,">=1.2.14"))return!0;return!1})(),sse=(_payload)=>{if(_payload instanceof ReadableStream)return _payload.sse=!0,_payload;let payload=typeof _payload==="string"?{data:_payload}:_payload;return payload.sse=!0,payload.toSSE=()=>{let payloadString="";if(payload.id!==void 0&&payload.id!==null)payloadString+=`id: ${payload.id}
3
3
  `;if(payload.event)payloadString+=`event: ${payload.event}
4
4
  `;if(payload.retry!==void 0)payloadString+=`retry: ${payload.retry}
5
5
  `;if(payload.data===null)payloadString+=`data: null
6
6
  `;else if(typeof payload.data==="string")payloadString+=`data: ${payload.data}
7
7
  `;else if(typeof payload.data==="object")payloadString+=`data: ${JSON.stringify(payload.data)}
8
8
  `;if(payloadString)payloadString+=`
9
- `;return payloadString},payload};async function getResponseLength(response){if(response.bodyUsed||!response.body)return 0;let length=0,reader=response.body.getReader();while(!0){let{done,value}=await reader.read();if(done)break;length+=value.byteLength}return length}var emptySchema={headers:!0,cookie:!0,query:!0,params:!0,body:!0,response:!0};var env=typeof Bun<"u"?Bun.env:typeof process<"u"?process?.env:void 0,ERROR_CODE=Symbol("ElysiaErrorCode"),isProduction=(env?.NODE_ENV??env?.ENV)==="production",emptyHttpStatus={101:void 0,204:void 0,205:void 0,304:void 0,307:void 0,308:void 0};class ElysiaCustomStatusResponse{code;response;constructor(code,response){let res=response??(code in InvertedStatusMap?InvertedStatusMap[code]:code);if(this.code=StatusMap[code]??code,code in emptyHttpStatus)this.response=void 0;else this.response=res}}var status=(code,response)=>new ElysiaCustomStatusResponse(code,response);class InternalServerError extends Error{code="INTERNAL_SERVER_ERROR";status=500;constructor(message){super(message??"INTERNAL_SERVER_ERROR")}}class NotFoundError extends Error{code="NOT_FOUND";status=404;constructor(message){super(message??"NOT_FOUND")}}class ParseError extends Error{code="PARSE";status=400;constructor(cause){super("Bad Request",{cause})}}class InvalidCookieSignature extends Error{key;code="INVALID_COOKIE_SIGNATURE";status=400;constructor(key,message){super(message??`"${key}" has invalid cookie signature`);this.key=key}}var mapValueError=(error)=>{if(!error)return{summary:void 0};let{message,path,value,type}=error;if(Array.isArray(path))path=path[0];let property=typeof path==="string"?path.slice(1).replaceAll("/","."):"unknown",isRoot=path==="";switch(type){case 42:return{...error,summary:isRoot?"Value should not be provided":`Property '${property}' should not be provided`};case 45:return{...error,summary:isRoot?"Value is missing":`Property '${property}' is missing`};case 50:let quoteIndex=message.indexOf("'"),format=message.slice(quoteIndex+1,message.indexOf("'",quoteIndex+1));return{...error,summary:isRoot?"Value should be an email":`Property '${property}' should be ${format}`};case 54:return{...error,summary:`${message.slice(0,9).trim()} property '${property}' to be ${message.slice(8).trim()} but found: ${value}`};case 62:let union=error.schema.anyOf.map((x)=>`'${x?.format??x.type}'`).join(", ");return{...error,summary:isRoot?`Value should be one of ${union}`:`Property '${property}' should be one of: ${union}`};default:return{summary:message,...error}}};class InvalidFileType extends Error{property;expected;message;code="INVALID_FILE_TYPE";status=422;constructor(property,expected,message=`"${property}" has invalid file type`){super(message);this.property=property;this.expected=expected;this.message=message;Object.setPrototypeOf(this,InvalidFileType.prototype)}toResponse(headers){if(isProduction)return new Response(JSON.stringify({type:"validation",on:"body"}),{status:422,headers:{...headers,"content-type":"application/json"}});return new Response(JSON.stringify({type:"validation",on:"body",summary:"Invalid file type",message:this.message,property:this.property,expected:this.expected}),{status:422,headers:{...headers,"content-type":"application/json"}})}}class ValidationError extends Error{type;validator;value;allowUnsafeValidationDetails;code="VALIDATION";status=422;valueError;get messageValue(){return this.valueError}expected;customError;constructor(type,validator,value,allowUnsafeValidationDetails=!1,errors){let message="",error,expected,customError;if(validator?.provider==="standard"||"~standard"in validator||validator.schema&&"~standard"in validator.schema){let standard=("~standard"in validator?validator:validator.schema)["~standard"];if(error=(errors??standard.validate(value).issues)?.[0],isProduction&&!allowUnsafeValidationDetails)message=JSON.stringify({type:"validation",on:type,found:value});else message=JSON.stringify({type:"validation",on:type,property:error.path?.[0]||"root",message:error?.message,summary:error?.problem,expected,found:value,errors},null,2);customError=error?.message}else{if(value&&typeof value==="object"&&value instanceof ElysiaCustomStatusResponse)value=value.response;error=errors?.First()??("Errors"in validator?validator.Errors(value).First():Value.Errors(validator,value).First());let accessor=error?.path||"root",schema=validator?.schema??validator;if(!isProduction&&!allowUnsafeValidationDetails)try{expected=Value.Create(schema)}catch(error2){expected={type:"Could not create expected value",message:error2?.message,error:error2}}if(customError=error?.schema?.message||error?.schema?.error!==void 0?typeof error.schema.error==="function"?error.schema.error(isProduction&&!allowUnsafeValidationDetails?{type:"validation",on:type,found:value}:{type:"validation",on:type,value,property:accessor,message:error?.message,summary:mapValueError(error).summary,found:value,expected,errors:"Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value.Errors(validator,value)].map(mapValueError)},validator):error.schema.error:void 0,customError!==void 0)message=typeof customError==="object"?JSON.stringify(customError):customError+"";else if(isProduction&&!allowUnsafeValidationDetails)message=JSON.stringify({type:"validation",on:type,found:value});else message=JSON.stringify({type:"validation",on:type,property:accessor,message:error?.message,summary:mapValueError(error).summary,expected,found:value,errors:"Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value.Errors(validator,value)].map(mapValueError)},null,2)}super(message);this.type=type;this.validator=validator;this.value=value;this.allowUnsafeValidationDetails=allowUnsafeValidationDetails;this.valueError=error,this.expected=expected,this.customError=customError,Object.setPrototypeOf(this,ValidationError.prototype)}get all(){if(this.validator?.provider==="standard"||"~standard"in this.validator||"schema"in this.validator&&this.validator.schema&&"~standard"in this.validator.schema)return("~standard"in this.validator?this.validator:this.validator.schema)["~standard"].validate(this.value).issues?.map((issue)=>({summary:issue.message,path:issue.path?.join(".")||"root",message:issue.message,value:this.value}))||[];return"Errors"in this.validator?[...this.validator.Errors(this.value)].map(mapValueError):[...Value.Errors(this.validator,this.value)].map(mapValueError)}static simplifyModel(validator){let model="schema"in validator?validator.schema:validator;try{return Value.Create(model)}catch{return model}}get model(){if("~standard"in this.validator)return this.validator;return ValidationError.simplifyModel(this.validator)}toResponse(headers){return new Response(this.message,{status:400,headers:{...headers,"content-type":"application/json"}})}detail(message,allowUnsafeValidatorDetails=this.allowUnsafeValidationDetails){if(!this.customError)return this.message;let value=this.value,expected=this.expected,errors=this.all;return isProduction&&!allowUnsafeValidatorDetails?{type:"validation",on:this.type,found:value,message}:{type:"validation",on:this.type,property:this.valueError?.path||"root",message,summary:mapValueError(this.valueError).summary,found:value,expected,errors}}}var tryParse=(v,schema)=>{try{return JSON.parse(v)}catch{throw new ValidationError("property",schema,v)}};function createType(kind,func){if(!TypeRegistry.Has(kind))TypeRegistry.Set(kind,func);return(options={})=>Unsafe({...options,[Kind]:kind})}var compile=(schema)=>{try{let compiler=TypeCompiler.Compile(schema);return compiler.Create=()=>Value2.Create(schema),compiler.Error=(v)=>new ValidationError("property",schema,v,compiler.Errors(v)),compiler}catch{return{Check:(v)=>Value2.Check(schema,v),CheckThrow:(v)=>{if(!Value2.Check(schema,v))throw new ValidationError("property",schema,v,Value2.Errors(schema,v))},Decode:(v)=>Value2.Decode(schema,v),Create:()=>Value2.Create(schema),Error:(v)=>new ValidationError("property",schema,v,Value2.Errors(schema,v))}}},parseFileUnit=(size)=>{if(typeof size==="string")switch(size.slice(-1)){case"k":return+size.slice(0,size.length-1)*1024;case"m":return+size.slice(0,size.length-1)*1048576;default:return+size}return size},checkFileExtension=(type,extension)=>{if(type.startsWith(extension))return!0;return extension.charCodeAt(extension.length-1)===42&&extension.charCodeAt(extension.length-2)===47&&type.startsWith(extension.slice(0,-1))},_fileTypeFromBlobWarn=!1,warnIfFileTypeIsNotInstalled=()=>{if(!_fileTypeFromBlobWarn)console.warn("[Elysia] Attempt to validate file type without 'file-type'. This may lead to security risks. We recommend installing 'file-type' to properly validate file extension."),_fileTypeFromBlobWarn=!0},loadFileType=async()=>import("file-type").then((x)=>{return _fileTypeFromBlob=x.fileTypeFromBlob,_fileTypeFromBlob}).catch(warnIfFileTypeIsNotInstalled),_fileTypeFromBlob,fileTypeFromBlob=(file2)=>{if(_fileTypeFromBlob)return _fileTypeFromBlob(file2);return loadFileType().then((mod)=>{if(mod)return mod(file2)})},fileType=async(file2,extension,name=file2?.name??"")=>{if(Array.isArray(file2))return await Promise.all(file2.map((f)=>fileType(f,extension,name))),!0;if(!file2)return!1;let result=await fileTypeFromBlob(file2);if(!result)throw new InvalidFileType(name,extension);if(typeof extension==="string"){if(!checkFileExtension(result.mime,extension))throw new InvalidFileType(name,extension)}for(let i=0;i<extension.length;i++)if(checkFileExtension(result.mime,extension[i]))return!0;throw new InvalidFileType(name,extension)},validateFile=(options,value)=>{if(value instanceof ElysiaFile)return!0;if(!(value instanceof Blob))return!1;if(options.minSize&&value.size<parseFileUnit(options.minSize))return!1;if(options.maxSize&&value.size>parseFileUnit(options.maxSize))return!1;if(options.extension){if(typeof options.extension==="string")return checkFileExtension(value.type,options.extension);for(let i=0;i<options.extension.length;i++)if(checkFileExtension(value.type,options.extension[i]))return!0;return!1}return!0},validationDetail=(message)=>(error)=>({...error,message});import{FormatRegistry}from"@sinclair/typebox";var fullFormats={date,time:getTime(!0),"date-time":getDateTime(!0),"iso-time":getTime(!1),"iso-date-time":getDateTime(!1),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:!0,binary:!0};function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date(str){let matches=DATE.exec(str);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function(str){let matches=TIME.exec(str);if(!matches)return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3],tz=matches[4],tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return!1;if(hr<=23&&min<=59&&sec<60)return!0;let utcMin=min-tzM*tzSign,utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}var parseDateTimeEmptySpace=(str)=>{if(str.charCodeAt(str.length-6)===32)return str.slice(0,-6)+"+"+str.slice(-5);return str},DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time=getTime(strictTimeZone);return function(str){let dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date(dateTime[0])&&time(dateTime[1])}}var NOT_URI_FRAGMENT=/\/|:/,URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){return BYTE.lastIndex=0,BYTE.test(str)}var MIN_INT32=-2147483648,MAX_INT32=2147483647;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return!0}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return!1;try{return new RegExp(str),!0}catch(e){return!1}}var isISO8601=/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/,isFormalDate=/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT(?:\+|-)\d{4}\s\([^)]+\)/,isShortenDate=/^(?:(?:(?:(?:0?[1-9]|[12][0-9]|3[01])[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:19|20)\d{2})|(?:(?:19|20)\d{2}[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:0?[1-9]|[12][0-9]|3[01]))))(?:\s(?:1[012]|0?[1-9]):[0-5][0-9](?::[0-5][0-9])?(?:\s[AP]M)?)?$/,_validateDate=fullFormats.date,_validateDateTime=fullFormats["date-time"];if(!FormatRegistry.Has("date"))FormatRegistry.Set("date",(value)=>{let temp=parseDateTimeEmptySpace(value).replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDate(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});if(!FormatRegistry.Has("date-time"))FormatRegistry.Set("date-time",(value)=>{let temp=value.replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDateTime(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});Object.entries(fullFormats).forEach((formatEntry)=>{let[formatName,formatValue]=formatEntry;if(!FormatRegistry.Has(formatName)){if(formatValue instanceof RegExp)FormatRegistry.Set(formatName,(value)=>formatValue.test(value));else if(typeof formatValue==="function")FormatRegistry.Set(formatName,formatValue)}});if(!FormatRegistry.Has("numeric"))FormatRegistry.Set("numeric",(value)=>!!value&&!isNaN(+value));if(!FormatRegistry.Has("integer"))FormatRegistry.Set("integer",(value)=>!!value&&Number.isInteger(+value));if(!FormatRegistry.Has("boolean"))FormatRegistry.Set("boolean",(value)=>value==="true"||value==="false");if(!FormatRegistry.Has("ObjectString"))FormatRegistry.Set("ObjectString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});if(!FormatRegistry.Has("ArrayString"))FormatRegistry.Set("ArrayString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});import{TypeSystemPolicy,TypeSystem,TypeSystemDuplicateFormat,TypeSystemDuplicateTypeKind}from"@sinclair/typebox/system";import{TypeRegistry as TypeRegistry2,FormatRegistry as FormatRegistry2}from"@sinclair/typebox";import{TypeCompiler as TypeCompiler2,TypeCheck as TypeCheck2}from"@sinclair/typebox/compiler";var t=Object.assign({},Type);createType("UnionEnum",(schema,value)=>(typeof value==="number"||typeof value==="string"||value===null)&&schema.enum.includes(value));createType("ArrayBuffer",(schema,value)=>value instanceof ArrayBuffer);var internalFiles=createType("Files",(options,value)=>{if(options.minItems&&options.minItems>1&&!Array.isArray(value))return!1;if(!Array.isArray(value))return validateFile(options,value);if(options.minItems&&value.length<options.minItems)return!1;if(options.maxItems&&value.length>options.maxItems)return!1;for(let i=0;i<value.length;i++)if(!validateFile(options,value[i]))return!1;return!0}),internalFormData=createType("ElysiaForm",({compiler,...schema},value)=>{if(!(value instanceof FormData))return!1;if(compiler){if(!(ELYSIA_FORM_DATA in value))throw new ValidationError("property",schema,value);if(!compiler.Check(value[ELYSIA_FORM_DATA]))throw compiler.Error(value[ELYSIA_FORM_DATA])}return!0}),ElysiaType={String:(property)=>Type.String(property),Numeric:(property)=>{let schema=Type.Number(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"numeric",default:0}),t.Number(property)],property)).Decode((value)=>{let number=+value;if(isNaN(number))return value;if(property&&!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},NumericEnum(item,property){let schema=Type.Enum(item,property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"numeric"}),t.Number()],property)).Decode((value)=>{let number=+value;if(isNaN(number))throw compiler.Error(number);if(!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},Integer:(property)=>{let schema=Type.Integer(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"integer",default:0}),Type.Integer(property)],property)).Decode((value)=>{let number=+value;if(!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},Date:(property)=>{let schema=Type.Date(property),compiler=compile(schema),_default=property?.default?new Date(property.default):void 0;return t.Transform(t.Union([Type.Date(property),t.String({format:"date-time",default:_default?.toISOString()}),t.String({format:"date",default:_default?.toISOString()}),t.Number({default:_default?.getTime()})],property)).Decode((value)=>{if(typeof value==="number"){let date3=new Date(value);if(!compiler.Check(date3))throw compiler.Error(date3);return date3}if(value instanceof Date)return value;let date2=new Date(parseDateTimeEmptySpace(value));if(!date2||isNaN(date2.getTime()))throw new ValidationError("property",schema,date2);if(!compiler.Check(date2))throw compiler.Error(date2);return date2}).Encode((value)=>{if(value instanceof Date)return value.toISOString();if(typeof value==="string"){let parsed=new Date(parseDateTimeEmptySpace(value));if(isNaN(parsed.getTime()))throw new ValidationError("property",schema,value);return parsed.toISOString()}if(!compiler.Check(value))throw compiler.Error(value);return value})},BooleanString:(property)=>{let schema=Type.Boolean(property),compiler=compile(schema);return t.Transform(t.Union([t.Boolean(property),t.String({format:"boolean",default:!1})],property)).Decode((value)=>{if(typeof value==="string")return value==="true";if(value!==void 0&&!compiler.Check(value))throw compiler.Error(value);return value}).Encode((value)=>value)},ObjectString:(properties,options)=>{let schema=t.Object(properties,options),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"ObjectString",default:options?.default}),schema],{elysiaMeta:"ObjectString"})).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==123)throw new ValidationError("property",schema,value);if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw compiler.Error(value);return original??JSON.stringify(value)})},ArrayString:(children=t.String(),options)=>{let schema=t.Array(children,options),compiler=compile(schema),decode=(value,isProperty=!1)=>{if(value.charCodeAt(0)===91){if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}if(isProperty)return value;throw new ValidationError("property",schema,value)};return t.Transform(t.Union([t.String({format:"ArrayString",default:options?.default}),schema],{elysiaMeta:"ArrayString"})).Decode((value)=>{if(Array.isArray(value)){let values=[];for(let i=0;i<value.length;i++){let v=value[i];if(typeof v==="string"){let t2=decode(v,!0);if(Array.isArray(t2))values=values.concat(t2);else values.push(t2);continue}values.push(v)}return values}if(typeof value==="string")return decode(value);return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw new ValidationError("property",schema,value);return original??JSON.stringify(value)})},ArrayQuery:(children=t.String(),options)=>{let schema=t.Array(children,options),compiler=compile(schema),decode=(value)=>{if(value.indexOf(",")!==-1)return compiler.Decode(value.split(","));return[value]};return t.Transform(t.Union([t.String({default:options?.default}),schema],{elysiaMeta:"ArrayQuery"})).Decode((value)=>{if(Array.isArray(value)){let values=[];for(let i=0;i<value.length;i++){let v=value[i];if(typeof v==="string"){let t2=decode(v);if(Array.isArray(t2))values=values.concat(t2);else values.push(t2);continue}values.push(v)}return values}if(typeof value==="string")return decode(value);return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw new ValidationError("property",schema,value);return original??JSON.stringify(value)})},File:createType("File",validateFile),Files:(options={})=>t.Transform(internalFiles(options)).Decode((value)=>{if(Array.isArray(value))return value;return[value]}).Encode((value)=>value),Nullable:(schema,options)=>t.Union([schema,t.Null()],{...options,nullable:!0}),MaybeEmpty:(schema,options)=>t.Union([schema,t.Null(),t.Undefined()],options),Cookie:(properties,{domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign,...options}={})=>{let v=t.Object(properties,options);return v.config={domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign},v},UnionEnum:(values,options={})=>{let type=values.every((value)=>typeof value==="string")?{type:"string"}:values.every((value)=>typeof value==="number")?{type:"number"}:values.every((value)=>value===null)?{type:"null"}:{};if(values.some((x)=>typeof x==="object"&&x!==null))throw Error("This type does not support objects or arrays");return{default:values[0],...options,[Kind2]:"UnionEnum",...type,enum:values}},NoValidate:(v,enabled=!0)=>{return v.noValidate=enabled,v},Form:(v,options={})=>{let schema=t.Object(v,{default:form({}),...options}),compiler=compile(schema);return t.Union([schema,internalFormData({compiler})])},ArrayBuffer(options={}){return{default:[1,2,3],...options,[Kind2]:"ArrayBuffer"}},Uint8Array:(options)=>{let schema=Type.Uint8Array(options),compiler=compile(schema);return t.Transform(t.Union([t.ArrayBuffer(),Type.Uint8Array(options)])).Decode((value)=>{if(value instanceof ArrayBuffer){if(!compiler.Check(value=new Uint8Array(value)))throw compiler.Error(value);return value}return value}).Encode((value)=>value)}};t.BooleanString=ElysiaType.BooleanString;t.ObjectString=ElysiaType.ObjectString;t.ArrayString=ElysiaType.ArrayString;t.ArrayQuery=ElysiaType.ArrayQuery;t.Numeric=ElysiaType.Numeric;t.NumericEnum=ElysiaType.NumericEnum;t.Integer=ElysiaType.Integer;t.File=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.File({default:"File",...arg,extension:arg?.type,type:"string",format:"binary"})};t.Files=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.Files({...arg,elysiaMeta:"Files",default:"Files",extension:arg?.type,type:"array",items:{...arg,default:"Files",type:"string",format:"binary"}})};t.Nullable=ElysiaType.Nullable;t.MaybeEmpty=ElysiaType.MaybeEmpty;t.Cookie=ElysiaType.Cookie;t.Date=ElysiaType.Date;t.UnionEnum=ElysiaType.UnionEnum;t.NoValidate=ElysiaType.NoValidate;t.Form=ElysiaType.Form;t.ArrayBuffer=ElysiaType.ArrayBuffer;t.Uint8Array=ElysiaType.Uint8Array;var import_cookie=__toESM(require_dist(),1),import_fast_decode_uri_component=__toESM(require_fast_decode_uri_component(),1);var hashString=(str)=>{let hash=2166136261,len=str.length;for(let i=0;i<len;i++)hash^=str.charCodeAt(i),hash=Math.imul(hash,16777619);return hash>>>0};class Cookie{name;jar;initial;valueHash;constructor(name,jar,initial={}){this.name=name;this.jar=jar;this.initial=initial}get cookie(){return this.jar[this.name]??this.initial}set cookie(jar){if(!(this.name in this.jar))this.jar[this.name]=this.initial;this.jar[this.name]=jar,this.valueHash=void 0}get setCookie(){if(!(this.name in this.jar))this.jar[this.name]=this.initial;return this.jar[this.name]}set setCookie(jar){this.cookie=jar}get value(){return this.cookie.value}set value(value){let current=this.cookie.value;if(current===value)return;if(typeof current==="object"&&current!==null&&typeof value==="object"&&value!==null)try{let valueStr=JSON.stringify(value),newHash=hashString(valueStr);if(this.valueHash!==void 0&&this.valueHash!==newHash)this.valueHash=newHash;else{if(JSON.stringify(current)===valueStr){this.valueHash=newHash;return}this.valueHash=newHash}}catch{}if(!(this.name in this.jar))this.jar[this.name]={...this.initial};this.jar[this.name].value=value}get expires(){return this.cookie.expires}set expires(expires){this.setCookie.expires=expires}get maxAge(){return this.cookie.maxAge}set maxAge(maxAge){this.setCookie.maxAge=maxAge}get domain(){return this.cookie.domain}set domain(domain){this.setCookie.domain=domain}get path(){return this.cookie.path}set path(path){this.setCookie.path=path}get secure(){return this.cookie.secure}set secure(secure){this.setCookie.secure=secure}get httpOnly(){return this.cookie.httpOnly}set httpOnly(httpOnly){this.setCookie.httpOnly=httpOnly}get sameSite(){return this.cookie.sameSite}set sameSite(sameSite){this.setCookie.sameSite=sameSite}get priority(){return this.cookie.priority}set priority(priority){this.setCookie.priority=priority}get partitioned(){return this.cookie.partitioned}set partitioned(partitioned){this.setCookie.partitioned=partitioned}get secrets(){return this.cookie.secrets}set secrets(secrets){this.setCookie.secrets=secrets}update(config){return this.setCookie=Object.assign(this.cookie,typeof config==="function"?config(this.cookie):config),this}set(config){return this.setCookie=Object.assign({...this.initial,value:this.value},typeof config==="function"?config(this.cookie):config),this}remove(){if(this.value===void 0)return;return this.set({expires:new Date(0),maxAge:0,value:""}),this}toString(){return typeof this.value==="object"?JSON.stringify(this.value):this.value?.toString()??""}}var createCookieJar=(set2,store,initial)=>{if(!set2.cookie)set2.cookie={};return new Proxy(store,{get(_2,key){if(key in store)return new Cookie(key,set2.cookie,Object.assign({},initial??{},store[key]));return new Cookie(key,set2.cookie,Object.assign({},initial))}})},parseCookie=async(set2,cookieString,{secrets,sign,...initial}={})=>{if(!cookieString)return createCookieJar(set2,{},initial);let isStringKey=typeof secrets==="string";if(sign&&sign!==!0&&!Array.isArray(sign))sign=[sign];let jar={},cookies=import_cookie.parse(cookieString);for(let[name,v]of Object.entries(cookies)){if(v===void 0)continue;let value=import_fast_decode_uri_component.default(v);if(value){let starts=value.charCodeAt(0),ends=value.charCodeAt(value.length-1);if(starts===123&&ends===125||starts===91&&ends===93)try{value=JSON.parse(value)}catch{}}if(sign===!0||sign?.includes(name)){if(!secrets)throw Error("No secret is provided to cookie plugin");if(isStringKey){if(typeof value!=="string")throw new InvalidCookieSignature(name);let temp=await unsignCookie(value,secrets);if(temp===!1)throw new InvalidCookieSignature(name);value=temp}else{let decoded=!1;for(let i=0;i<secrets.length;i++){if(typeof value!=="string")throw new InvalidCookieSignature(name);let temp=await unsignCookie(value,secrets[i]);if(temp!==!1){decoded=!0,value=temp;break}}if(!decoded)throw new InvalidCookieSignature(name)}}jar[name]={value}}return createCookieJar(set2,jar,initial)},serializeCookie=(cookies)=>{if(!cookies||!isNotEmpty(cookies))return;let set2=[];for(let[key,property]of Object.entries(cookies)){if(!key||!property)continue;let value=property.value;if(value===void 0||value===null)continue;set2.push(import_cookie.serialize(key,typeof value==="object"?JSON.stringify(value):value+"",property))}if(set2.length===0)return;if(set2.length===1)return set2[0];return set2};var env2=isBun?Bun.env:typeof process<"u"&&process?.env?process.env:{};var handleFile=(response,set2)=>{if(!isBun&&response instanceof Promise)return response.then((res)=>handleFile(res,set2));let size=response.size,immutable=set2&&(set2.status===206||set2.status===304||set2.status===412||set2.status===416),defaultHeader=immutable?{}:{"accept-ranges":"bytes","content-range":size?`bytes 0-${size-1}/${size}`:void 0};if(!set2&&!size)return new Response(response);if(!set2)return new Response(response,{headers:defaultHeader});if(set2.headers instanceof Headers){for(let key of Object.keys(defaultHeader))if(key in set2.headers)set2.headers.append(key,defaultHeader[key]);if(immutable)set2.headers.delete("content-length"),set2.headers.delete("accept-ranges");return new Response(response,set2)}if(isNotEmpty(set2.headers))return new Response(response,{status:set2.status,headers:Object.assign(defaultHeader,set2.headers)});return new Response(response,{status:set2.status,headers:defaultHeader})},parseSetCookies=(headers,setCookie)=>{if(!headers)return headers;headers.delete("set-cookie");for(let i=0;i<setCookie.length;i++){let index=setCookie[i].indexOf("=");headers.append("set-cookie",`${setCookie[i].slice(0,index)}=${setCookie[i].slice(index+1)||""}`)}return headers},responseToSetHeaders=(response,set2)=>{if(set2?.headers){if(response){if(hasHeaderShorthand)Object.assign(set2.headers,response.headers.toJSON());else for(let[key,value]of response.headers.entries())if(key in set2.headers)set2.headers[key]=value}if(set2.status===200)set2.status=response.status;if(set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}if(!response)return{headers:{},status:set2?.status??200};if(hasHeaderShorthand){if(set2={headers:response.headers.toJSON(),status:set2?.status??200},set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}set2={headers:{},status:set2?.status??200};for(let[key,value]of response.headers.entries()){if(key==="content-encoding")continue;if(key in set2.headers)set2.headers[key]=value}return set2},allowRapidStream=env2.ELYSIA_RAPID_STREAM==="true",createStreamHandler=({mapResponse,mapCompactResponse})=>async(generator,set2,request)=>{let init=generator.next?.();if(set2)handleSet(set2);if(init instanceof Promise)init=await init;if(init?.value instanceof ReadableStream)generator=init.value;else if(init&&(typeof init?.done>"u"||init?.done)){if(set2)return mapResponse(init.value,set2,request);return mapCompactResponse(init.value,request)}let isSSE=init?.value?.sse??generator?.sse??set2?.headers["content-type"]?.startsWith("text/event-stream"),format=isSSE?(data)=>`data: ${data}
9
+ `;return payloadString},payload};async function getResponseLength(response){if(response.bodyUsed||!response.body)return 0;let length=0,reader=response.body.getReader();while(!0){let{done,value}=await reader.read();if(done)break;length+=value.byteLength}return length}var emptySchema={headers:!0,cookie:!0,query:!0,params:!0,body:!0,response:!0};var env=typeof Bun<"u"?Bun.env:typeof process<"u"?process?.env:void 0,ERROR_CODE=Symbol("ElysiaErrorCode"),isProduction=(env?.NODE_ENV??env?.ENV)==="production",emptyHttpStatus={101:void 0,204:void 0,205:void 0,304:void 0,307:void 0,308:void 0};class ElysiaCustomStatusResponse{code;response;constructor(code,response){let res=response??(code in InvertedStatusMap?InvertedStatusMap[code]:code);if(this.code=StatusMap[code]??code,code in emptyHttpStatus)this.response=void 0;else this.response=res}}var status=(code,response)=>new ElysiaCustomStatusResponse(code,response);class InternalServerError extends Error{code="INTERNAL_SERVER_ERROR";status=500;constructor(message){super(message??"INTERNAL_SERVER_ERROR")}}class NotFoundError extends Error{code="NOT_FOUND";status=404;constructor(message){super(message??"NOT_FOUND")}}class ParseError extends Error{code="PARSE";status=400;constructor(cause){super("Bad Request",{cause})}}class InvalidCookieSignature extends Error{key;code="INVALID_COOKIE_SIGNATURE";status=400;constructor(key,message){super(message??`"${key}" has invalid cookie signature`);this.key=key}}var mapValueError=(error)=>{if(!error)return error;let{message,path,value,type}=error;if(Array.isArray(path))path=path[0];let property=typeof path==="string"?path.slice(1).replaceAll("/","."):"unknown",isRoot=path==="";switch(type){case 42:return{...error,summary:isRoot?"Value should not be provided":`Property '${property}' should not be provided`};case 45:return{...error,summary:isRoot?"Value is missing":`Property '${property}' is missing`};case 50:let quoteIndex=message.indexOf("'"),format=message.slice(quoteIndex+1,message.indexOf("'",quoteIndex+1));return{...error,summary:isRoot?"Value should be an email":`Property '${property}' should be ${format}`};case 54:return{...error,summary:`${message.slice(0,9).trim()} property '${property}' to be ${message.slice(8).trim()} but found: ${value}`};case 62:let union=error.schema.anyOf.map((x)=>`'${x?.format??x.type}'`).join(", ");return{...error,summary:isRoot?`Value should be one of ${union}`:`Property '${property}' should be one of: ${union}`};default:return{summary:message,...error}}};class InvalidFileType extends Error{property;expected;message;code="INVALID_FILE_TYPE";status=422;constructor(property,expected,message=`"${property}" has invalid file type`){super(message);this.property=property;this.expected=expected;this.message=message;Object.setPrototypeOf(this,InvalidFileType.prototype)}toResponse(headers){if(isProduction)return new Response(JSON.stringify({type:"validation",on:"body"}),{status:422,headers:{...headers,"content-type":"application/json"}});return new Response(JSON.stringify({type:"validation",on:"body",summary:"Invalid file type",message:this.message,property:this.property,expected:this.expected}),{status:422,headers:{...headers,"content-type":"application/json"}})}}class ValidationError extends Error{type;validator;value;allowUnsafeValidationDetails;code="VALIDATION";status=422;valueError;get messageValue(){return this.valueError}expected;customError;constructor(type,validator,value,allowUnsafeValidationDetails=!1,errors){let message="",error,expected,customError;if(validator?.provider==="standard"||"~standard"in validator||validator.schema&&"~standard"in validator.schema){let standard=("~standard"in validator?validator:validator.schema)["~standard"];if(error=(errors??standard.validate(value).issues)?.[0],isProduction&&!allowUnsafeValidationDetails)message=JSON.stringify({type:"validation",on:type,found:value});else message=JSON.stringify({type:"validation",on:type,property:error.path?.[0]||"root",message:error?.message,summary:error?.problem,expected,found:value,errors},null,2);customError=error?.message}else{if(value&&typeof value==="object"&&value instanceof ElysiaCustomStatusResponse)value=value.response;error=errors?.First()??("Errors"in validator?validator.Errors(value).First():Value.Errors(validator,value).First());let accessor=error?.path||"root",schema=validator?.schema??validator;if(!isProduction&&!allowUnsafeValidationDetails)try{expected=Value.Create(schema)}catch(error2){expected={type:"Could not create expected value",message:error2?.message,error:error2}}if(customError=error?.schema?.message||error?.schema?.error!==void 0?typeof error.schema.error==="function"?error.schema.error(isProduction&&!allowUnsafeValidationDetails?{type:"validation",on:type,found:value}:{type:"validation",on:type,value,property:accessor,message:error?.message,summary:mapValueError(error).summary,found:value,expected,errors:"Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value.Errors(validator,value)].map(mapValueError)},validator):error.schema.error:void 0,customError!==void 0)message=typeof customError==="object"?JSON.stringify(customError):customError+"";else if(isProduction&&!allowUnsafeValidationDetails)message=JSON.stringify({type:"validation",on:type,found:value});else message=JSON.stringify({type:"validation",on:type,property:accessor,message:error?.message,summary:mapValueError(error).summary,expected,found:value,errors:"Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value.Errors(validator,value)].map(mapValueError)},null,2)}super(message);this.type=type;this.validator=validator;this.value=value;this.allowUnsafeValidationDetails=allowUnsafeValidationDetails;this.valueError=error,this.expected=expected,this.customError=customError,Object.setPrototypeOf(this,ValidationError.prototype)}get all(){if(this.validator?.provider==="standard"||"~standard"in this.validator||"schema"in this.validator&&this.validator.schema&&"~standard"in this.validator.schema)return("~standard"in this.validator?this.validator:this.validator.schema)["~standard"].validate(this.value).issues?.map((issue)=>({summary:issue.message,path:issue.path?.join(".")||"root",message:issue.message,value:this.value}))||[];return"Errors"in this.validator?[...this.validator.Errors(this.value)].map(mapValueError):[...Value.Errors(this.validator,this.value)].map(mapValueError)}static simplifyModel(validator){let model="schema"in validator?validator.schema:validator;try{return Value.Create(model)}catch{return model}}get model(){if("~standard"in this.validator)return this.validator;return ValidationError.simplifyModel(this.validator)}toResponse(headers){return new Response(this.message,{status:400,headers:{...headers,"content-type":"application/json"}})}detail(message,allowUnsafeValidatorDetails=this.allowUnsafeValidationDetails){if(!this.customError)return this.message;let value=this.value,expected=this.expected,errors=this.all;return isProduction&&!allowUnsafeValidatorDetails?{type:"validation",on:this.type,found:value,message}:{type:"validation",on:this.type,property:this.valueError?.path||"root",message,summary:this.valueError?mapValueError(this.valueError).summary:void 0,found:value,expected,errors}}}var tryParse=(v,schema)=>{try{return JSON.parse(v)}catch{throw new ValidationError("property",schema,v)}};function createType(kind,func){if(!TypeRegistry.Has(kind))TypeRegistry.Set(kind,func);return(options={})=>Unsafe({...options,[Kind]:kind})}var compile=(schema)=>{try{let compiler=TypeCompiler.Compile(schema);return compiler.Create=()=>Value2.Create(schema),compiler.Error=(v)=>new ValidationError("property",schema,v,compiler.Errors(v)),compiler}catch{return{Check:(v)=>Value2.Check(schema,v),CheckThrow:(v)=>{if(!Value2.Check(schema,v))throw new ValidationError("property",schema,v,Value2.Errors(schema,v))},Decode:(v)=>Value2.Decode(schema,v),Create:()=>Value2.Create(schema),Error:(v)=>new ValidationError("property",schema,v,Value2.Errors(schema,v))}}},parseFileUnit=(size)=>{if(typeof size==="string")switch(size.slice(-1)){case"k":return+size.slice(0,size.length-1)*1024;case"m":return+size.slice(0,size.length-1)*1048576;default:return+size}return size},checkFileExtension=(type,extension)=>{if(type.startsWith(extension))return!0;return extension.charCodeAt(extension.length-1)===42&&extension.charCodeAt(extension.length-2)===47&&type.startsWith(extension.slice(0,-1))},_fileTypeFromBlobWarn=!1,warnIfFileTypeIsNotInstalled=()=>{if(!_fileTypeFromBlobWarn)console.warn("[Elysia] Attempt to validate file type without 'file-type'. This may lead to security risks. We recommend installing 'file-type' to properly validate file extension."),_fileTypeFromBlobWarn=!0},loadFileType=async()=>import("file-type").then((x)=>{return _fileTypeFromBlob=x.fileTypeFromBlob,_fileTypeFromBlob}).catch(warnIfFileTypeIsNotInstalled),_fileTypeFromBlob,fileTypeFromBlob=(file2)=>{if(_fileTypeFromBlob)return _fileTypeFromBlob(file2);return loadFileType().then((mod)=>{if(mod)return mod(file2)})},fileType=async(file2,extension,name=file2?.name??"")=>{if(Array.isArray(file2))return await Promise.all(file2.map((f)=>fileType(f,extension,name))),!0;if(!file2)return!1;let result=await fileTypeFromBlob(file2);if(!result)throw new InvalidFileType(name,extension);if(typeof extension==="string"){if(!checkFileExtension(result.mime,extension))throw new InvalidFileType(name,extension)}for(let i=0;i<extension.length;i++)if(checkFileExtension(result.mime,extension[i]))return!0;throw new InvalidFileType(name,extension)},validateFile=(options,value)=>{if(value instanceof ElysiaFile)return!0;if(!(value instanceof Blob))return!1;if(options.minSize&&value.size<parseFileUnit(options.minSize))return!1;if(options.maxSize&&value.size>parseFileUnit(options.maxSize))return!1;if(options.extension){if(typeof options.extension==="string")return checkFileExtension(value.type,options.extension);for(let i=0;i<options.extension.length;i++)if(checkFileExtension(value.type,options.extension[i]))return!0;return!1}return!0},validationDetail=(message)=>(error)=>({...error,message});import{FormatRegistry}from"@sinclair/typebox";var fullFormats={date,time:getTime(!0),"date-time":getDateTime(!0),"iso-time":getTime(!1),"iso-date-time":getDateTime(!1),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:!0,binary:!0};function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date(str){let matches=DATE.exec(str);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function(str){let matches=TIME.exec(str);if(!matches)return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3],tz=matches[4],tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return!1;if(hr<=23&&min<=59&&sec<60)return!0;let utcMin=min-tzM*tzSign,utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}var parseDateTimeEmptySpace=(str)=>{if(str.charCodeAt(str.length-6)===32)return str.slice(0,-6)+"+"+str.slice(-5);return str},DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time=getTime(strictTimeZone);return function(str){let dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date(dateTime[0])&&time(dateTime[1])}}var NOT_URI_FRAGMENT=/\/|:/,URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){return BYTE.lastIndex=0,BYTE.test(str)}var MIN_INT32=-2147483648,MAX_INT32=2147483647;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return!0}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return!1;try{return new RegExp(str),!0}catch(e){return!1}}var isISO8601=/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/,isFormalDate=/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT(?:\+|-)\d{4}\s\([^)]+\)/,isShortenDate=/^(?:(?:(?:(?:0?[1-9]|[12][0-9]|3[01])[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:19|20)\d{2})|(?:(?:19|20)\d{2}[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:0?[1-9]|[12][0-9]|3[01]))))(?:\s(?:1[012]|0?[1-9]):[0-5][0-9](?::[0-5][0-9])?(?:\s[AP]M)?)?$/,_validateDate=fullFormats.date,_validateDateTime=fullFormats["date-time"];if(!FormatRegistry.Has("date"))FormatRegistry.Set("date",(value)=>{let temp=parseDateTimeEmptySpace(value).replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDate(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});if(!FormatRegistry.Has("date-time"))FormatRegistry.Set("date-time",(value)=>{let temp=value.replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDateTime(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});Object.entries(fullFormats).forEach((formatEntry)=>{let[formatName,formatValue]=formatEntry;if(!FormatRegistry.Has(formatName)){if(formatValue instanceof RegExp)FormatRegistry.Set(formatName,(value)=>formatValue.test(value));else if(typeof formatValue==="function")FormatRegistry.Set(formatName,formatValue)}});if(!FormatRegistry.Has("numeric"))FormatRegistry.Set("numeric",(value)=>!!value&&!isNaN(+value));if(!FormatRegistry.Has("integer"))FormatRegistry.Set("integer",(value)=>!!value&&Number.isInteger(+value));if(!FormatRegistry.Has("boolean"))FormatRegistry.Set("boolean",(value)=>value==="true"||value==="false");if(!FormatRegistry.Has("ObjectString"))FormatRegistry.Set("ObjectString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});if(!FormatRegistry.Has("ArrayString"))FormatRegistry.Set("ArrayString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});import{TypeSystemPolicy,TypeSystem,TypeSystemDuplicateFormat,TypeSystemDuplicateTypeKind}from"@sinclair/typebox/system";import{TypeRegistry as TypeRegistry2,FormatRegistry as FormatRegistry2}from"@sinclair/typebox";import{TypeCompiler as TypeCompiler2,TypeCheck as TypeCheck2}from"@sinclair/typebox/compiler";var t=Object.assign({},Type);createType("UnionEnum",(schema,value)=>(typeof value==="number"||typeof value==="string"||value===null)&&schema.enum.includes(value));createType("ArrayBuffer",(schema,value)=>value instanceof ArrayBuffer);var internalFiles=createType("Files",(options,value)=>{if(options.minItems&&options.minItems>1&&!Array.isArray(value))return!1;if(!Array.isArray(value))return validateFile(options,value);if(options.minItems&&value.length<options.minItems)return!1;if(options.maxItems&&value.length>options.maxItems)return!1;for(let i=0;i<value.length;i++)if(!validateFile(options,value[i]))return!1;return!0}),internalFormData=createType("ElysiaForm",({compiler,...schema},value)=>{if(!(value instanceof FormData))return!1;if(compiler){if(!(ELYSIA_FORM_DATA in value))throw new ValidationError("property",schema,value);if(!compiler.Check(value[ELYSIA_FORM_DATA]))throw compiler.Error(value[ELYSIA_FORM_DATA])}return!0}),ElysiaType={String:(property)=>Type.String(property),Numeric:(property)=>{let schema=Type.Number(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"numeric",default:0}),t.Number(property)],property)).Decode((value)=>{let number=+value;if(isNaN(number))return value;if(property&&!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},NumericEnum(item,property){let schema=Type.Enum(item,property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"numeric"}),t.Number()],property)).Decode((value)=>{let number=+value;if(isNaN(number))throw compiler.Error(number);if(!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},Integer:(property)=>{let schema=Type.Integer(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"integer",default:0}),Type.Integer(property)],property)).Decode((value)=>{let number=+value;if(!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},Date:(property)=>{let schema=Type.Date(property),compiler=compile(schema),_default=property?.default?new Date(property.default):void 0;return t.Transform(t.Union([Type.Date(property),t.String({format:"date-time",default:_default?.toISOString()}),t.String({format:"date",default:_default?.toISOString()}),t.Number({default:_default?.getTime()})],property)).Decode((value)=>{if(typeof value==="number"){let date3=new Date(value);if(!compiler.Check(date3))throw compiler.Error(date3);return date3}if(value instanceof Date)return value;let date2=new Date(parseDateTimeEmptySpace(value));if(!date2||isNaN(date2.getTime()))throw new ValidationError("property",schema,date2);if(!compiler.Check(date2))throw compiler.Error(date2);return date2}).Encode((value)=>{if(value instanceof Date)return value.toISOString();if(typeof value==="string"){let parsed=new Date(parseDateTimeEmptySpace(value));if(isNaN(parsed.getTime()))throw new ValidationError("property",schema,value);return parsed.toISOString()}if(!compiler.Check(value))throw compiler.Error(value);return value})},BooleanString:(property)=>{let schema=Type.Boolean(property),compiler=compile(schema);return t.Transform(t.Union([t.Boolean(property),t.String({format:"boolean",default:!1})],property)).Decode((value)=>{if(typeof value==="string")return value==="true";if(value!==void 0&&!compiler.Check(value))throw compiler.Error(value);return value}).Encode((value)=>value)},ObjectString:(properties,options)=>{let schema=t.Object(properties,options),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"ObjectString",default:options?.default}),schema],{elysiaMeta:"ObjectString"})).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==123)throw new ValidationError("property",schema,value);if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw compiler.Error(value);return original??JSON.stringify(value)})},ArrayString:(children=t.String(),options)=>{let schema=t.Array(children,options),compiler=compile(schema),decode=(value,isProperty=!1)=>{if(value.charCodeAt(0)===91){if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}if(isProperty)return value;throw new ValidationError("property",schema,value)};return t.Transform(t.Union([t.String({format:"ArrayString",default:options?.default}),schema],{elysiaMeta:"ArrayString"})).Decode((value)=>{if(Array.isArray(value)){let values=[];for(let i=0;i<value.length;i++){let v=value[i];if(typeof v==="string"){let t2=decode(v,!0);if(Array.isArray(t2))values=values.concat(t2);else values.push(t2);continue}values.push(v)}return values}if(typeof value==="string")return decode(value);return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw new ValidationError("property",schema,value);return original??JSON.stringify(value)})},ArrayQuery:(children=t.String(),options)=>{let schema=t.Array(children,options),compiler=compile(schema),decode=(value)=>{if(value.indexOf(",")!==-1)return compiler.Decode(value.split(","));return compiler.Decode([value])};return t.Transform(t.Union([t.String({default:options?.default}),schema],{elysiaMeta:"ArrayQuery"})).Decode((value)=>{if(Array.isArray(value)){let values=[];for(let i=0;i<value.length;i++){let v=value[i];if(typeof v==="string"){let t2=decode(v);if(Array.isArray(t2))values=values.concat(t2);else values.push(t2);continue}values.push(v)}return values}if(typeof value==="string")return decode(value);return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw new ValidationError("property",schema,value);return original??JSON.stringify(value)})},File:createType("File",validateFile),Files:(options={})=>t.Transform(internalFiles(options)).Decode((value)=>{if(Array.isArray(value))return value;return[value]}).Encode((value)=>value),Nullable:(schema,options)=>t.Union([schema,t.Null()],{...options,nullable:!0}),MaybeEmpty:(schema,options)=>t.Union([schema,t.Null(),t.Undefined()],options),Cookie:(properties,{domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign,...options}={})=>{let v=t.Object(properties,options);return v.config={domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign},v},UnionEnum:(values,options={})=>{let type=values.every((value)=>typeof value==="string")?{type:"string"}:values.every((value)=>typeof value==="number")?{type:"number"}:values.every((value)=>value===null)?{type:"null"}:{};if(values.some((x)=>typeof x==="object"&&x!==null))throw Error("This type does not support objects or arrays");return{default:values[0],...options,[Kind2]:"UnionEnum",...type,enum:values}},NoValidate:(v,enabled=!0)=>{return v.noValidate=enabled,v},Form:(v,options={})=>{let schema=t.Object(v,{default:form({}),...options}),compiler=compile(schema);return t.Union([schema,internalFormData({compiler})])},ArrayBuffer(options={}){return{default:[1,2,3],...options,[Kind2]:"ArrayBuffer"}},Uint8Array:(options)=>{let schema=Type.Uint8Array(options),compiler=compile(schema);return t.Transform(t.Union([t.ArrayBuffer(),Type.Uint8Array(options)])).Decode((value)=>{if(value instanceof ArrayBuffer){if(!compiler.Check(value=new Uint8Array(value)))throw compiler.Error(value);return value}return value}).Encode((value)=>value)}};t.BooleanString=ElysiaType.BooleanString;t.ObjectString=ElysiaType.ObjectString;t.ArrayString=ElysiaType.ArrayString;t.ArrayQuery=ElysiaType.ArrayQuery;t.Numeric=ElysiaType.Numeric;t.NumericEnum=ElysiaType.NumericEnum;t.Integer=ElysiaType.Integer;t.File=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.File({default:"File",...arg,extension:arg?.type,type:"string",format:"binary"})};t.Files=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.Files({...arg,elysiaMeta:"Files",default:"Files",extension:arg?.type,type:"array",items:{...arg,default:"Files",type:"string",format:"binary"}})};t.Nullable=ElysiaType.Nullable;t.MaybeEmpty=ElysiaType.MaybeEmpty;t.Cookie=ElysiaType.Cookie;t.Date=ElysiaType.Date;t.UnionEnum=ElysiaType.UnionEnum;t.NoValidate=ElysiaType.NoValidate;t.Form=ElysiaType.Form;t.ArrayBuffer=ElysiaType.ArrayBuffer;t.Uint8Array=ElysiaType.Uint8Array;var import_cookie=__toESM(require_dist(),1),import_fast_decode_uri_component=__toESM(require_fast_decode_uri_component(),1);var hashString=(str)=>{let hash=2166136261,len=str.length;for(let i=0;i<len;i++)hash^=str.charCodeAt(i),hash=Math.imul(hash,16777619);return hash>>>0};class Cookie{name;jar;initial;valueHash;constructor(name,jar,initial={}){this.name=name;this.jar=jar;this.initial=initial}get cookie(){return this.jar[this.name]??this.initial}set cookie(jar){if(!(this.name in this.jar))this.jar[this.name]=this.initial;this.jar[this.name]=jar,this.valueHash=void 0}get setCookie(){if(!(this.name in this.jar))this.jar[this.name]=this.initial;return this.jar[this.name]}set setCookie(jar){this.cookie=jar}get value(){return this.cookie.value}set value(value){let current=this.cookie.value;if(current===value)return;if(typeof current==="object"&&current!==null&&typeof value==="object"&&value!==null)try{let valueStr=JSON.stringify(value),newHash=hashString(valueStr);if(this.valueHash!==void 0&&this.valueHash!==newHash)this.valueHash=newHash;else{if(JSON.stringify(current)===valueStr){this.valueHash=newHash;return}this.valueHash=newHash}}catch{}if(!(this.name in this.jar))this.jar[this.name]={...this.initial};this.jar[this.name].value=value}get expires(){return this.cookie.expires}set expires(expires){this.setCookie.expires=expires}get maxAge(){return this.cookie.maxAge}set maxAge(maxAge){this.setCookie.maxAge=maxAge}get domain(){return this.cookie.domain}set domain(domain){this.setCookie.domain=domain}get path(){return this.cookie.path}set path(path){this.setCookie.path=path}get secure(){return this.cookie.secure}set secure(secure){this.setCookie.secure=secure}get httpOnly(){return this.cookie.httpOnly}set httpOnly(httpOnly){this.setCookie.httpOnly=httpOnly}get sameSite(){return this.cookie.sameSite}set sameSite(sameSite){this.setCookie.sameSite=sameSite}get priority(){return this.cookie.priority}set priority(priority){this.setCookie.priority=priority}get partitioned(){return this.cookie.partitioned}set partitioned(partitioned){this.setCookie.partitioned=partitioned}get secrets(){return this.cookie.secrets}set secrets(secrets){this.setCookie.secrets=secrets}update(config){return this.setCookie=Object.assign(this.cookie,typeof config==="function"?config(this.cookie):config),this}set(config){return this.setCookie=Object.assign({...this.initial,value:this.value},typeof config==="function"?config(this.cookie):config),this}remove(){if(this.value===void 0)return;return this.set({expires:new Date(0),maxAge:0,value:""}),this}toString(){return typeof this.value==="object"?JSON.stringify(this.value):this.value?.toString()??""}}var createCookieJar=(set,store,initial)=>{if(!set.cookie)set.cookie={};return new Proxy(store,{get(_2,key){if(key in store)return new Cookie(key,set.cookie,Object.assign({},initial??{},store[key]));return new Cookie(key,set.cookie,Object.assign({},initial))}})},parseCookie=async(set,cookieString,{secrets,sign,...initial}={})=>{if(!cookieString)return createCookieJar(set,{},initial);let isStringKey=typeof secrets==="string";if(sign&&sign!==!0&&!Array.isArray(sign))sign=[sign];let jar={},cookies=import_cookie.parse(cookieString);for(let[name,v]of Object.entries(cookies)){if(v===void 0)continue;let value=import_fast_decode_uri_component.default(v);if(value){let starts=value.charCodeAt(0),ends=value.charCodeAt(value.length-1);if(starts===123&&ends===125||starts===91&&ends===93)try{value=JSON.parse(value)}catch{}}if(sign===!0||sign?.includes(name)){if(!secrets)throw Error("No secret is provided to cookie plugin");if(isStringKey){if(typeof value!=="string")throw new InvalidCookieSignature(name);let temp=await unsignCookie(value,secrets);if(temp===!1)throw new InvalidCookieSignature(name);value=temp}else{let decoded=!1;for(let i=0;i<secrets.length;i++){if(typeof value!=="string")throw new InvalidCookieSignature(name);let temp=await unsignCookie(value,secrets[i]);if(temp!==!1){decoded=!0,value=temp;break}}if(!decoded)throw new InvalidCookieSignature(name)}}jar[name]={value}}return createCookieJar(set,jar,initial)},serializeCookie=(cookies)=>{if(!cookies||!isNotEmpty(cookies))return;let set=[];for(let[key,property]of Object.entries(cookies)){if(!key||!property)continue;let value=property.value;if(value===void 0||value===null)continue;set.push(import_cookie.serialize(key,typeof value==="object"?JSON.stringify(value):value+"",property))}if(set.length===0)return;if(set.length===1)return set[0];return set};var env2=isBun?Bun.env:typeof process<"u"&&process?.env?process.env:{};var handleFile=(response,set)=>{if(!isBun&&response instanceof Promise)return response.then((res)=>handleFile(res,set));let size=response.size,immutable=set&&(set.status===206||set.status===304||set.status===412||set.status===416),defaultHeader=immutable?{}:{"accept-ranges":"bytes","content-range":size?`bytes 0-${size-1}/${size}`:void 0};if(!set&&!size)return new Response(response);if(!set)return new Response(response,{headers:defaultHeader});if(set.headers instanceof Headers){for(let key of Object.keys(defaultHeader))if(key in set.headers)set.headers.append(key,defaultHeader[key]);if(immutable)set.headers.delete("content-length"),set.headers.delete("accept-ranges");return new Response(response,set)}if(isNotEmpty(set.headers))return new Response(response,{status:set.status,headers:Object.assign(defaultHeader,set.headers)});return new Response(response,{status:set.status,headers:defaultHeader})},parseSetCookies=(headers,setCookie)=>{if(!headers)return headers;headers.delete("set-cookie");for(let i=0;i<setCookie.length;i++){let index=setCookie[i].indexOf("=");headers.append("set-cookie",`${setCookie[i].slice(0,index)}=${setCookie[i].slice(index+1)||""}`)}return headers},responseToSetHeaders=(response,set)=>{if(set?.headers){if(response){if(hasHeaderShorthand)Object.assign(set.headers,response.headers.toJSON());else for(let[key,value]of response.headers.entries())if(key in set.headers)set.headers[key]=value}if(set.status===200)set.status=response.status;if(set.headers["content-encoding"])delete set.headers["content-encoding"];return set}if(!response)return{headers:{},status:set?.status??200};if(hasHeaderShorthand){if(set={headers:response.headers.toJSON(),status:set?.status??200},set.headers["content-encoding"])delete set.headers["content-encoding"];return set}set={headers:{},status:set?.status??200};for(let[key,value]of response.headers.entries()){if(key==="content-encoding")continue;if(key in set.headers)set.headers[key]=value}return set},allowRapidStream=env2.ELYSIA_RAPID_STREAM==="true",createStreamHandler=({mapResponse,mapCompactResponse})=>async(generator,set,request,skipFormat)=>{let init=generator.next?.();if(set)handleSet(set);if(init instanceof Promise)init=await init;if(init?.value instanceof ReadableStream)generator=init.value;else if(init&&(typeof init?.done>"u"||init?.done)){if(set)return mapResponse(init.value,set,request);return mapCompactResponse(init.value,request)}let isSSE=!skipFormat&&(init?.value?.sse??generator?.sse??set?.headers["content-type"]?.startsWith("text/event-stream")),format=isSSE?(data)=>`data: ${data}
10
10
 
11
- `:(data)=>data,contentType=isSSE?"text/event-stream":init?.value&&typeof init?.value==="object"?"application/json":"text/plain";if(set2?.headers){if(!set2.headers["transfer-encoding"])set2.headers["transfer-encoding"]="chunked";if(!set2.headers["content-type"])set2.headers["content-type"]=contentType;if(!set2.headers["cache-control"])set2.headers["cache-control"]="no-cache"}else set2={status:200,headers:{"content-type":contentType,"transfer-encoding":"chunked","cache-control":"no-cache",connection:"keep-alive"}};let isBrowser=request?.headers.has("Origin");return new Response(new ReadableStream({async start(controller){let end=!1;if(request?.signal?.addEventListener("abort",()=>{end=!0;try{controller.close()}catch{}}),!init||init.value instanceof ReadableStream);else if(init.value!==void 0&&init.value!==null)if(init.value.toSSE)controller.enqueue(init.value.toSSE());else if(typeof init.value==="object")try{controller.enqueue(format(JSON.stringify(init.value)))}catch{controller.enqueue(format(init.value.toString()))}else controller.enqueue(format(init.value.toString()));try{for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(chunk.toSSE)controller.enqueue(chunk.toSSE());else{if(typeof chunk==="object")try{controller.enqueue(format(JSON.stringify(chunk)))}catch{controller.enqueue(format(chunk.toString()))}else controller.enqueue(format(chunk.toString()));if(!allowRapidStream&&isBrowser&&!isSSE)await new Promise((resolve)=>setTimeout(()=>resolve(),0))}}}catch(error){console.warn(error)}try{controller.close()}catch{}}}),set2)};async function*streamResponse(response){let body=response.body;if(!body)return;let reader=body.getReader(),decoder=new TextDecoder;try{while(!0){let{done,value}=await reader.read();if(done)break;if(typeof value==="string")yield value;else yield decoder.decode(value)}}finally{reader.releaseLock()}}var handleSet=(set2)=>{if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"])},createResponseHandler=(handler)=>{let handleStream=createStreamHandler(handler);return(response,set2,request)=>{let isCookieSet=!1;if(set2.headers instanceof Headers){for(let key of set2.headers.keys())if(key==="set-cookie"){if(isCookieSet)continue;isCookieSet=!0;for(let cookie of set2.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else if(!response.headers.has(key))response.headers.set(key,set2.headers?.get(key)??"")}else for(let key in set2.headers)if(key==="set-cookie")response.headers.append(key,set2.headers[key]);else if(!response.headers.has(key))response.headers.set(key,set2.headers[key]);let status2=set2.status??200;if(response.status!==status2&&status2!==200&&(response.status<=300||response.status>400)){let newResponse=new Response(response.body,{headers:response.headers,status:set2.status});if(!newResponse.headers.has("content-length")&&newResponse.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(newResponse),responseToSetHeaders(newResponse,set2),request);return newResponse}if(!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);return response}};async function tee(source,branches=2){let buffer=[],done=!1,waiting=[];(async()=>{for await(let value of source)buffer.push(value),waiting.forEach((w)=>w.resolve()),waiting=[];done=!0,waiting.forEach((w)=>w.resolve())})();async function*makeIterator(){let i=0;while(!0)if(i<buffer.length)yield buffer[i++];else if(done)return;else await new Promise((resolve)=>waiting.push({resolve}))}return Array.from({length:branches},makeIterator)}var handleElysiaFile=(file2,set2={headers:{}})=>{let path=file2.path,contentType=mime[path.slice(path.lastIndexOf(".")+1)];if(contentType)set2.headers["content-type"]=contentType;if(file2.stats&&set2.status!==206&&set2.status!==304&&set2.status!==412&&set2.status!==416)return file2.stats.then((stat2)=>{let size=stat2.size;if(size!==void 0)set2.headers["content-range"]=`bytes 0-${size-1}/${size}`,set2.headers["content-length"]=size;return handleFile(file2.value,set2)});return handleFile(file2.value,set2)},mapResponse=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse(response.response,set2,request);case void 0:if(!response)return new Response("",set2);return new Response(JSON.stringify(response),set2);case"Response":return handleResponse(response,set2,request);case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>mapResponse(x,set2,request));case"Function":return mapResponse(response(),set2,request);case"Number":case"Boolean":return new Response(response.toString(),set2);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response,set2);default:if(response instanceof Response)return handleResponse(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse(x,set2));if(typeof response?.toResponse==="function")return mapResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);return mapCompactResponse(response,request)},mapEarlyResponse=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case void 0:if(!response)return;return new Response(JSON.stringify(response),set2);case"Response":return handleResponse(response,set2,request);case"Promise":return response.then((x)=>mapEarlyResponse(x,set2));case"Error":return errorToResponse(response,set2);case"Function":return mapEarlyResponse(response(),set2);case"Number":case"Boolean":return new Response(response.toString(),set2);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);default:if(response instanceof Response)return handleResponse(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}else switch(response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Promise":return response.then((x)=>{let r=mapEarlyResponse(x,set2);if(r!==void 0)return r});case"Error":return errorToResponse(response,set2);case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response)}},mapCompactResponse=(response,request)=>{switch(response?.constructor?.name){case"String":return new Response(response,{headers:{"Content-Type":"text/plain"}});case"Object":case"Array":return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}});case"ElysiaFile":return handleElysiaFile(response);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Error":return errorToResponse(response);case"Promise":return response.then((x)=>mapCompactResponse(x,request));case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapCompactResponse(x,request));if(response instanceof Error)return errorToResponse(response);if(response instanceof ElysiaCustomStatusResponse)return mapResponse(response.response,{status:response.code,headers:{}});if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,void 0,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse(x,set));if(typeof response?.toResponse==="function")return mapCompactResponse(response.toResponse());if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91)return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}})}return new Response(response)}},errorToResponse=(error,set2)=>{if(typeof error?.toResponse==="function"){let raw=error.toResponse(),targetSet=set2??{headers:{},status:200,redirect:""},apply=(resolved)=>{if(resolved instanceof Response)targetSet.status=resolved.status;return mapResponse(resolved,targetSet)};return typeof raw?.then==="function"?raw.then(apply):apply(raw)}return new Response(JSON.stringify({name:error?.name,message:error?.message,cause:error?.cause}),{status:set2?.status!==200?set2?.status??500:500,headers:set2?.headers})},createStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return()=>response.clone()},handleResponse=createResponseHandler({mapResponse,mapCompactResponse}),handleStream=createStreamHandler({mapResponse,mapCompactResponse});var WebStandardAdapter={name:"web-standard",isWebStandard:!0,handler:{mapResponse,mapEarlyResponse,mapCompactResponse,createStaticHandler},composeHandler:{mapResponseContext:"c.request",preferWebstandardHeaders:!0,headers:`c.headers={}
11
+ `:(data)=>data,contentType=isSSE?"text/event-stream":init?.value&&typeof init?.value==="object"?"application/json":"text/plain";if(set?.headers){if(!set.headers["transfer-encoding"])set.headers["transfer-encoding"]="chunked";if(!set.headers["content-type"])set.headers["content-type"]=contentType;if(!set.headers["cache-control"])set.headers["cache-control"]="no-cache"}else set={status:200,headers:{"content-type":contentType,"transfer-encoding":"chunked","cache-control":"no-cache",connection:"keep-alive"}};let isBrowser=request?.headers.has("Origin");return new Response(new ReadableStream({async start(controller){let end=!1;if(request?.signal?.addEventListener("abort",()=>{end=!0;try{controller.close()}catch{}}),!init||init.value instanceof ReadableStream);else if(init.value!==void 0&&init.value!==null)if(init.value.toSSE)controller.enqueue(init.value.toSSE());else if(typeof init.value==="object")try{controller.enqueue(format(JSON.stringify(init.value)))}catch{controller.enqueue(format(init.value.toString()))}else controller.enqueue(format(init.value.toString()));try{for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(chunk.toSSE)controller.enqueue(chunk.toSSE());else{if(typeof chunk==="object")try{controller.enqueue(format(JSON.stringify(chunk)))}catch{controller.enqueue(format(chunk.toString()))}else controller.enqueue(format(chunk.toString()));if(!allowRapidStream&&isBrowser&&!isSSE)await new Promise((resolve)=>setTimeout(()=>resolve(),0))}}}catch(error){console.warn(error)}try{controller.close()}catch{}}}),set)};async function*streamResponse(response){let body=response.body;if(!body)return;let reader=body.getReader(),decoder=new TextDecoder;try{while(!0){let{done,value}=await reader.read();if(done)break;if(typeof value==="string")yield value;else yield decoder.decode(value)}}finally{reader.releaseLock()}}var handleSet=(set)=>{if(typeof set.status==="string")set.status=StatusMap[set.status];if(set.cookie&&isNotEmpty(set.cookie)){let cookie=serializeCookie(set.cookie);if(cookie)set.headers["set-cookie"]=cookie}if(set.headers["set-cookie"]&&Array.isArray(set.headers["set-cookie"]))set.headers=parseSetCookies(new Headers(set.headers),set.headers["set-cookie"])},createResponseHandler=(handler)=>{let handleStream=createStreamHandler(handler);return(response,set,request)=>{let isCookieSet=!1;if(set.headers instanceof Headers){for(let key of set.headers.keys())if(key==="set-cookie"){if(isCookieSet)continue;isCookieSet=!0;for(let cookie of set.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else if(!response.headers.has(key))response.headers.set(key,set.headers?.get(key)??"")}else for(let key in set.headers)if(key==="set-cookie")response.headers.append(key,set.headers[key]);else if(!response.headers.has(key))response.headers.set(key,set.headers[key]);let status2=set.status??200;if(response.status!==status2&&status2!==200&&(response.status<=300||response.status>400)){let newResponse=new Response(response.body,{headers:response.headers,status:set.status});if(!newResponse.headers.has("content-length")&&newResponse.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(newResponse),responseToSetHeaders(newResponse,set),request,!0);return newResponse}if(!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set),request,!0);return response}};async function tee(source,branches=2){let buffer=[],done=!1,waiting=[];(async()=>{for await(let value of source)buffer.push(value),waiting.forEach((w)=>w.resolve()),waiting=[];done=!0,waiting.forEach((w)=>w.resolve())})();async function*makeIterator(){let i=0;while(!0)if(i<buffer.length)yield buffer[i++];else if(done)return;else await new Promise((resolve)=>waiting.push({resolve}))}return Array.from({length:branches},makeIterator)}var handleElysiaFile=(file2,set={headers:{}})=>{let path=file2.path,contentType=mime[path.slice(path.lastIndexOf(".")+1)];if(contentType)set.headers["content-type"]=contentType;if(file2.stats&&set.status!==206&&set.status!==304&&set.status!==412&&set.status!==416)return file2.stats.then((stat2)=>{let size=stat2.size;if(size!==void 0)set.headers["content-range"]=`bytes 0-${size-1}/${size}`,set.headers["content-length"]=size;return handleFile(file2.value,set)});return handleFile(file2.value,set)},mapResponse=(response,set,request)=>{if(isNotEmpty(set.headers)||set.status!==200||set.cookie)switch(handleSet(set),response?.constructor?.name){case"String":return set.headers["content-type"]="text/plain",new Response(response,set);case"Array":case"Object":return set.headers["content-type"]="application/json",new Response(JSON.stringify(response),set);case"ElysiaFile":return handleElysiaFile(response,set);case"File":return handleFile(response,set);case"Blob":return handleFile(response,set);case"ElysiaCustomStatusResponse":return set.status=response.code,mapResponse(response.response,set,request);case void 0:if(!response)return new Response("",set);return new Response(JSON.stringify(response),set);case"Response":return handleResponse(response,set,request);case"Error":return errorToResponse(response,set);case"Promise":return response.then((x)=>mapResponse(x,set,request));case"Function":return mapResponse(response(),set,request);case"Number":case"Boolean":return new Response(response.toString(),set);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set);return new Response(response?.toString(),set);case"FormData":return new Response(response,set);default:if(response instanceof Response)return handleResponse(response,set,request);if(response instanceof Promise)return response.then((x)=>mapResponse(x,set));if(response instanceof Error)return errorToResponse(response,set);if(response instanceof ElysiaCustomStatusResponse)return set.status=response.code,mapResponse(response.response,set,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse(x,set));if(typeof response?.toResponse==="function")return mapResponse(response.toResponse(),set);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set.headers["Content-Type"])set.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set)}}return new Response(response,set)}if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set,request);return mapCompactResponse(response,request)},mapEarlyResponse=(response,set,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set.headers)||set.status!==200||set.cookie)switch(handleSet(set),response?.constructor?.name){case"String":return set.headers["content-type"]="text/plain",new Response(response,set);case"Array":case"Object":return set.headers["content-type"]="application/json",new Response(JSON.stringify(response),set);case"ElysiaFile":return handleElysiaFile(response,set);case"File":return handleFile(response,set);case"Blob":return handleFile(response,set);case"ElysiaCustomStatusResponse":return set.status=response.code,mapEarlyResponse(response.response,set,request);case void 0:if(!response)return;return new Response(JSON.stringify(response),set);case"Response":return handleResponse(response,set,request);case"Promise":return response.then((x)=>mapEarlyResponse(x,set));case"Error":return errorToResponse(response,set);case"Function":return mapEarlyResponse(response(),set);case"Number":case"Boolean":return new Response(response.toString(),set);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set);return new Response(response?.toString(),set);default:if(response instanceof Response)return handleResponse(response,set,request);if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set));if(response instanceof Error)return errorToResponse(response,set);if(response instanceof ElysiaCustomStatusResponse)return set.status=response.code,mapEarlyResponse(response.response,set,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set.headers["Content-Type"])set.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set)}}return new Response(response,set)}else switch(response?.constructor?.name){case"String":return set.headers["content-type"]="text/plain",new Response(response);case"Array":case"Object":return set.headers["content-type"]="application/json",new Response(JSON.stringify(response),set);case"ElysiaFile":return handleElysiaFile(response,set);case"File":return handleFile(response,set);case"Blob":return handleFile(response,set);case"ElysiaCustomStatusResponse":return set.status=response.code,mapEarlyResponse(response.response,set,request);case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Promise":return response.then((x)=>{let r=mapEarlyResponse(x,set);if(r!==void 0)return r});case"Error":return errorToResponse(response,set);case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"Cookie":if(response instanceof Cookie)return new Response(response.value,set);return new Response(response?.toString(),set);case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set));if(response instanceof Error)return errorToResponse(response,set);if(response instanceof ElysiaCustomStatusResponse)return set.status=response.code,mapEarlyResponse(response.response,set,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set.headers["Content-Type"])set.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set)}}return new Response(response)}},mapCompactResponse=(response,request)=>{switch(response?.constructor?.name){case"String":return new Response(response,{headers:{"Content-Type":"text/plain"}});case"Object":case"Array":return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}});case"ElysiaFile":return handleElysiaFile(response);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Error":return errorToResponse(response);case"Promise":return response.then((x)=>mapCompactResponse(x,request));case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapCompactResponse(x,request));if(response instanceof Error)return errorToResponse(response);if(response instanceof ElysiaCustomStatusResponse)return mapResponse(response.response,{status:response.code,headers:{}});if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,void 0,request);if(typeof response?.then==="function")return response.then((x)=>mapCompactResponse(x,request));if(typeof response?.toResponse==="function")return mapCompactResponse(response.toResponse());if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91)return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}})}return new Response(response)}},errorToResponse=(error,set)=>{if(typeof error?.toResponse==="function"){let raw=error.toResponse(),targetSet=set??{headers:{},status:200,redirect:""},apply=(resolved)=>{if(resolved instanceof Response)targetSet.status=resolved.status;return mapResponse(resolved,targetSet)};return typeof raw?.then==="function"?raw.then(apply):apply(raw)}return new Response(JSON.stringify({name:error?.name,message:error?.message,cause:error?.cause}),{status:set?.status!==200?set?.status??500:500,headers:set?.headers})},createStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return()=>response.clone()},handleResponse=createResponseHandler({mapResponse,mapCompactResponse}),handleStream=createStreamHandler({mapResponse,mapCompactResponse});var WebStandardAdapter={name:"web-standard",isWebStandard:!0,handler:{mapResponse,mapEarlyResponse,mapCompactResponse,createStaticHandler},composeHandler:{mapResponseContext:"c.request",preferWebstandardHeaders:!0,headers:`c.headers={}
12
12
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
13
13
  `,parser:{json(isOptional){if(isOptional)return`try{c.body=await c.request.json()}catch{}
14
14
  `;return`c.body=await c.request.json()
@@ -58,7 +58,7 @@ break
58
58
  }catch{throw new ValidationError('response',validator.response[${status2}],${name},${allowUnsafeValidationDetails})}`:`throw new ValidationError('response',validator.response[${status2}],${name}),${allowUnsafeValidationDetails}`)+"}"}else{if(!appliedCleaner)code+=clean();if(!noValidate)code+=`if(validator.response[${status2}].Check(${name})===false)throw new ValidationError('response',validator.response[${status2}],${name},${allowUnsafeValidationDetails})
59
59
  c.set.status=${status2}
60
60
  `}code+=`break
61
- `}return code+"}"}}),isAsyncName=(v)=>{return(v?.fn??v).constructor.name==="AsyncFunction"},matchResponseClone=/=>\s?response\.clone\(/,matchFnReturn=/(?:return|=>)\s?\S+\(|a(?:sync|wait)/,isAsync=(v)=>{let isObject2=typeof v==="object";if(isObject2&&v.isAsync!==void 0)return v.isAsync;let fn=isObject2?v.fn:v;if(fn.constructor.name==="AsyncFunction")return!0;let literal=fn.toString();if(matchResponseClone.test(literal)){if(isObject2)v.isAsync=!1;return!1}let result=matchFnReturn.test(literal);if(isObject2)v.isAsync=result;return result},hasReturn=(v)=>{let isObject2=typeof v==="object";if(isObject2&&v.hasReturn!==void 0)return v.hasReturn;let fnLiteral=isObject2?v.fn.toString():typeof v==="string"?v.toString():v,parenthesisEnd=fnLiteral.indexOf(")");if(fnLiteral.charCodeAt(parenthesisEnd+2)===61&&fnLiteral.charCodeAt(parenthesisEnd+5)!==123){if(isObject2)v.hasReturn=!0;return!0}let result=fnLiteral.includes("return");if(isObject2)v.hasReturn=result;return result},isGenerator=(v)=>{let fn=v?.fn??v;return fn.constructor.name==="AsyncGeneratorFunction"||fn.constructor.name==="GeneratorFunction"},coerceTransformDecodeError=(fnLiteral,type,allowUnsafeValidationDetails=!1,value=`c.${type}`)=>`try{${fnLiteral}}catch(error){if(error.constructor.name === 'TransformDecodeError'){c.set.status=422
61
+ `}return code+"}"}}),isAsyncName=(v)=>{return(v?.fn??v).constructor.name==="AsyncFunction"},matchResponseClone=/=>\s?response\.clone\(/,matchFnReturn=/(?:return|=>)\s?\S+\(|a(?:sync|wait)/,isAsync=(v)=>{let isObject2=typeof v==="object";if(isObject2&&v.isAsync!==void 0)return v.isAsync;let fn=isObject2?v.fn:v;if(fn.constructor.name==="AsyncFunction")return!0;let literal=fn.toString();if(matchResponseClone.test(literal)){if(isObject2)v.isAsync=!1;return!1}let result=matchFnReturn.test(literal);if(isObject2)v.isAsync=result;return result},hasReturn=(v)=>{let isObject2=typeof v==="object";if(isObject2&&v.hasReturn!==void 0)return v.hasReturn;let fnLiteral=isObject2?v.fn.toString():typeof v==="string"?v.toString():v.toString(),parenthesisEnd=fnLiteral.indexOf(")"),arrowIndex=fnLiteral.indexOf("=>",parenthesisEnd);if(arrowIndex!==-1){let afterArrow=arrowIndex+2,charCode;while(afterArrow<fnLiteral.length&&((charCode=fnLiteral.charCodeAt(afterArrow))===32||charCode===9||charCode===10||charCode===13))afterArrow++;if(afterArrow<fnLiteral.length&&fnLiteral.charCodeAt(afterArrow)!==123){if(isObject2)v.hasReturn=!0;return!0}}let result=fnLiteral.includes("return");if(isObject2)v.hasReturn=result;return result},isGenerator=(v)=>{let fn=v?.fn??v;return fn.constructor.name==="AsyncGeneratorFunction"||fn.constructor.name==="GeneratorFunction"},coerceTransformDecodeError=(fnLiteral,type,allowUnsafeValidationDetails=!1,value=`c.${type}`)=>`try{${fnLiteral}}catch(error){if(error.constructor.name === 'TransformDecodeError'){c.set.status=422
62
62
  throw error.error ?? new ValidationError('${type}',validator.${type},${value},${allowUnsafeValidationDetails})}}`,setImmediateFn=hasSetImmediate?"setImmediate":"Promise.resolve().then",composeHandler=({app,path,method,hooks,validator,handler,allowMeta=!1,inference})=>{let adapter=app["~adapter"].composeHandler,adapterHandler=app["~adapter"].handler,isHandleFn=typeof handler==="function";if(!isHandleFn){handler=adapterHandler.mapResponse(handler,{headers:app.setHeaders??{}});let isResponse=handler instanceof Response||handler?.constructor?.name==="Response"&&typeof handler?.clone==="function";if(hooks.parse?.length&&hooks.transform?.length&&hooks.beforeHandle?.length&&hooks.afterHandle?.length){if(isResponse)return Function("a",`"use strict";
63
63
  return function(){return a.clone()}`)(handler);return Function("a",`"use strict";
64
64
  return function(){return a}`)(handler)}if(isResponse){let response=handler;handler=()=>response.clone()}}let handle=isHandleFn?"handler(c)":"handler",hasTrace=!!hooks.trace?.length,fnLiteral="";if(inference=sucrose(Object.assign({handler},hooks),inference,app.config.sucrose),adapter.declare){let literal=adapter.declare(inference);if(literal)fnLiteral+=literal}if(inference.server)fnLiteral+=`Object.defineProperty(c,'server',{get:function(){return getServer()}})
@@ -348,18 +348,18 @@ return mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}`;let
348
348
  const error404={clone:()=>new Response(error404Message,{status:404})}
349
349
  `}}},beforeCompile(app){app.handleError=composeErrorHandler(app);for(let route of app.routes)route.compile()},listen(){return()=>{console.warn("Cloudflare Worker does not support listen method. Please export default Elysia instance instead.")}}};var separateFunction=(code)=>{if(code.startsWith("async"))code=code.slice(5);code=code.trimStart();let index=-1;if(code.charCodeAt(0)===40){if(index=code.indexOf("=>",code.indexOf(")")),index!==-1){let bracketEndIndex=index;while(bracketEndIndex>0)if(code.charCodeAt(--bracketEndIndex)===41)break;let body=code.slice(index+2);if(body.charCodeAt(0)===32)body=body.trimStart();return[code.slice(1,bracketEndIndex),body,{isArrowReturn:body.charCodeAt(0)!==123}]}}if(/^(\w+)=>/g.test(code)){if(index=code.indexOf("=>"),index!==-1){let body=code.slice(index+2);if(body.charCodeAt(0)===32)body=body.trimStart();return[code.slice(0,index),body,{isArrowReturn:body.charCodeAt(0)!==123}]}}if(code.startsWith("function")){index=code.indexOf("(");let end=code.indexOf(")");return[code.slice(index+1,end),code.slice(end+2),{isArrowReturn:!1}]}let start=code.indexOf("(");if(start!==-1){let sep=code.indexOf(`
350
350
  `,2),parameter=code.slice(0,sep),end=parameter.lastIndexOf(")")+1,body=code.slice(sep+1);return[parameter.slice(start,end),"{"+body,{isArrowReturn:!1}]}let x=code.split(`
351
- `,2);return[x[0],x[1],{isArrowReturn:!1}]},bracketPairRange=(parameter)=>{let start=parameter.indexOf("{");if(start===-1)return[-1,0];let end=start+1,deep=1;for(;end<parameter.length;end++){let char=parameter.charCodeAt(end);if(char===123)deep++;else if(char===125)deep--;if(deep===0)break}if(deep!==0)return[0,parameter.length];return[start,end+1]},bracketPairRangeReverse=(parameter)=>{let end=parameter.lastIndexOf("}");if(end===-1)return[-1,0];let start=end-1,deep=1;for(;start>=0;start--){let char=parameter.charCodeAt(start);if(char===125)deep++;else if(char===123)deep--;if(deep===0)break}if(deep!==0)return[-1,0];return[start,end+1]},removeColonAlias=(parameter)=>{while(!0){let start=parameter.indexOf(":");if(start===-1)break;let end=parameter.indexOf(",",start);if(end===-1)end=parameter.indexOf("}",start)-1;if(end===-2)end=parameter.length;parameter=parameter.slice(0,start)+parameter.slice(end)}return parameter},retrieveRootParamters=(parameter)=>{let hasParenthesis=!1;if(parameter.charCodeAt(0)===40)parameter=parameter.slice(1,-1);if(parameter.charCodeAt(0)===123)hasParenthesis=!0,parameter=parameter.slice(1,-1);parameter=parameter.replace(/( |\t|\n)/g,"").trim();let parameters=[];while(!0){let[start,end]=bracketPairRange(parameter);if(start===-1)break;if(parameters.push(parameter.slice(0,start-1)),parameter.charCodeAt(end)===44)end++;parameter=parameter.slice(end)}if(parameter=removeColonAlias(parameter),parameter)parameters=parameters.concat(parameter.split(","));let parameterMap=Object.create(null);for(let p of parameters){if(p.indexOf(",")===-1){parameterMap[p]=!0;continue}for(let q of p.split(","))parameterMap[q.trim()]=!0}return{hasParenthesis,parameters:parameterMap}},findParameterReference=(parameter,inference)=>{let{parameters,hasParenthesis}=retrieveRootParamters(parameter);if(parameters.query)inference.query=!0;if(parameters.headers)inference.headers=!0;if(parameters.body)inference.body=!0;if(parameters.cookie)inference.cookie=!0;if(parameters.set)inference.set=!0;if(parameters.server)inference.server=!0;if(parameters.route)inference.route=!0;if(parameters.url)inference.url=!0;if(parameters.path)inference.path=!0;if(hasParenthesis)return`{ ${Object.keys(parameters).join(", ")} }`;return Object.keys(parameters).join(", ")},findEndIndex=(type,content,index)=>{let regex2=new RegExp(`${type.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\n\\t,; ]`);if(index!==void 0)regex2.lastIndex=index;let match=regex2.exec(content);return match?match.index:-1};var findAlias=(type,body,depth=0)=>{if(depth>5)return[];let aliases=[],content=body;while(!0){let index=findEndIndex(" = "+type,content);if(index===-1)index=findEndIndex("="+type,content);if(index===-1){let lastIndex=content.indexOf(" = "+type);if(lastIndex===-1)lastIndex=content.indexOf("="+type);if(lastIndex+3+type.length!==content.length)break;index=lastIndex}let part=content.slice(0,index),lastPart=part.lastIndexOf(" "),variable=part.slice(lastPart!==-1?lastPart+1:-1);if(variable==="}"){let[start,end]=bracketPairRangeReverse(part);aliases.push(removeColonAlias(content.slice(start,end))),content=content.slice(index+3+type.length);continue}while(variable.charCodeAt(0)===44)variable=variable.slice(1);while(variable.charCodeAt(0)===9)variable=variable.slice(1);if(!variable.includes("("))aliases.push(variable);content=content.slice(index+3+type.length)}for(let alias of aliases){if(alias.charCodeAt(0)===123)continue;let deepAlias=findAlias(alias,body);if(deepAlias.length>0)aliases.push(...deepAlias)}return aliases},extractMainParameter=(parameter)=>{if(!parameter)return;if(parameter.charCodeAt(0)!==123)return parameter;if(parameter=parameter.slice(2,-2),!parameter.includes(",")){if(parameter.indexOf("...")!==-1)return parameter.slice(parameter.indexOf("...")+3);return}let spreadIndex=parameter.indexOf("...");if(spreadIndex===-1)return;return parameter.slice(spreadIndex+3).trimEnd()},inferBodyReference=(code,aliases,inference)=>{let access=(type,alias)=>new RegExp(`${alias}\\.(${type})|${alias}\\["${type}"\\]|${alias}\\['${type}'\\]`).test(code);for(let alias of aliases){if(!alias)continue;if(alias.charCodeAt(0)===123){let parameters=retrieveRootParamters(alias).parameters;if(parameters.query)inference.query=!0;if(parameters.headers)inference.headers=!0;if(parameters.body)inference.body=!0;if(parameters.cookie)inference.cookie=!0;if(parameters.set)inference.set=!0;if(parameters.server)inference.server=!0;if(parameters.url)inference.url=!0;if(parameters.route)inference.route=!0;if(parameters.path)inference.path=!0;continue}if(!inference.query&&(access("query",alias)||code.includes("return "+alias)||code.includes("return "+alias+".query")))inference.query=!0;if(!inference.headers&&access("headers",alias))inference.headers=!0;if(!inference.body&&access("body",alias))inference.body=!0;if(!inference.cookie&&access("cookie",alias))inference.cookie=!0;if(!inference.set&&access("set",alias))inference.set=!0;if(!inference.server&&access("server",alias))inference.server=!0;if(!inference.route&&access("route",alias))inference.route=!0;if(!inference.url&&access("url",alias))inference.url=!0;if(!inference.path&&access("path",alias))inference.path=!0;if(inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server&&inference.route&&inference.url&&inference.path)break}return aliases};var isContextPassToFunction=(context,body,inference)=>{try{let captureFunction=new RegExp(`\\w\\((?:.*?)?${context}(?:.*?)?\\)`,"gs"),exactParameter=new RegExp(`${context}(,|\\))`,"gs"),length=body.length,fn;fn=captureFunction.exec(body)+"";while(captureFunction.lastIndex!==0&&captureFunction.lastIndex<length+(fn?fn.length:0)){if(fn&&exactParameter.test(fn))return inference.query=!0,inference.headers=!0,inference.body=!0,inference.cookie=!0,inference.set=!0,inference.server=!0,inference.url=!0,inference.route=!0,inference.path=!0,!0;fn=captureFunction.exec(body)+""}let nextChar=body.charCodeAt(captureFunction.lastIndex);if(nextChar===41||nextChar===44)return inference.query=!0,inference.headers=!0,inference.body=!0,inference.cookie=!0,inference.set=!0,inference.server=!0,inference.url=!0,inference.route=!0,inference.path=!0,!0;return!1}catch(error){return console.log("[Sucrose] warning: unexpected isContextPassToFunction error, you may continue development as usual but please report the following to maintainers:"),console.log("--- body ---"),console.log(body),console.log("--- context ---"),console.log(context),!0}},pendingGC,caches2={},clearSucroseCache=(delay)=>{if(delay===null||isCloudflareWorker())return;if(delay===void 0)delay=295000;if(pendingGC)clearTimeout(pendingGC);pendingGC=setTimeout(()=>{if(caches2={},pendingGC=void 0,isBun)Bun.gc(!1)},delay),pendingGC.unref?.()},mergeInference=(a,b)=>{return{body:a.body||b.body,cookie:a.cookie||b.cookie,headers:a.headers||b.headers,query:a.query||b.query,set:a.set||b.set,server:a.server||b.server,url:a.url||b.url,route:a.route||b.route,path:a.path||b.path}},sucrose=(lifeCycle,inference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1,url:!1,route:!1,path:!1},settings={})=>{let events=[];if(lifeCycle.request?.length)events.push(...lifeCycle.request);if(lifeCycle.beforeHandle?.length)events.push(...lifeCycle.beforeHandle);if(lifeCycle.parse?.length)events.push(...lifeCycle.parse);if(lifeCycle.error?.length)events.push(...lifeCycle.error);if(lifeCycle.transform?.length)events.push(...lifeCycle.transform);if(lifeCycle.afterHandle?.length)events.push(...lifeCycle.afterHandle);if(lifeCycle.mapResponse?.length)events.push(...lifeCycle.mapResponse);if(lifeCycle.afterResponse?.length)events.push(...lifeCycle.afterResponse);if(lifeCycle.handler&&typeof lifeCycle.handler==="function")events.push(lifeCycle.handler);for(let i=0;i<events.length;i++){let e=events[i];if(!e)continue;let event=typeof e==="object"?e.fn:e;if(typeof event!=="function")continue;let content=event.toString(),key=checksum(content),cachedInference=caches2[key];if(cachedInference){inference=mergeInference(inference,cachedInference);continue}clearSucroseCache(settings.gcTime);let fnInference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1,url:!1,route:!1,path:!1},[parameter,body]=separateFunction(content),rootParameters=findParameterReference(parameter,fnInference),mainParameter=extractMainParameter(rootParameters);if(mainParameter){let aliases=findAlias(mainParameter,body.slice(1,-1));aliases.splice(0,-1,mainParameter);let code=body;if(code.charCodeAt(0)===123&&code.charCodeAt(body.length-1)===125)code=code.slice(1,-1).trim();if(!isContextPassToFunction(mainParameter,code,fnInference))inferBodyReference(code,aliases,fnInference);if(!fnInference.query&&code.includes("return "+mainParameter+".query"))fnInference.query=!0}if(!caches2[key])caches2[key]=fnInference;if(inference=mergeInference(inference,fnInference),inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server&&inference.url&&inference.route&&inference.path)break}return inference};var mapResponse2=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleFile(response.value,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse2(response.response,set2,request);case void 0:if(!response)return new Response("",set2);return new Response(JSON.stringify(response),set2);case"Response":return handleResponse2(response,set2,request);case"Error":return errorToResponse2(response,set2);case"Promise":return response.then((x)=>mapResponse2(x,set2,request));case"Function":return mapResponse2(response(),set2,request);case"Number":case"Boolean":return new Response(response.toString(),set2);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response,set2);default:if(response instanceof Response)return handleResponse2(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapResponse2(x,set2));if(response instanceof Error)return errorToResponse2(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapResponse2(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse2(x,set2));if(typeof response?.toResponse==="function")return mapResponse2(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set2,request);return mapCompactResponse2(response,request)},mapEarlyResponse2=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleFile(response.value,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);case void 0:if(!response)return;return new Response(JSON.stringify(response),set2);case"Response":return handleResponse2(response,set2,request);case"Promise":return response.then((x)=>mapEarlyResponse2(x,set2));case"Error":return errorToResponse2(response,set2);case"Function":return mapEarlyResponse2(response(),set2);case"Number":case"Boolean":return new Response(response.toString(),set2);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);default:if(response instanceof Response)return handleResponse2(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapEarlyResponse2(x,set2));if(response instanceof Error)return errorToResponse2(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse2(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse2(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}else switch(response?.constructor?.name){case"String":return new Response(response);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleFile(response.value,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Promise":return response.then((x)=>{let r=mapEarlyResponse2(x,set2);if(r!==void 0)return r});case"Error":return errorToResponse2(response,set2);case"Function":return mapCompactResponse2(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapEarlyResponse2(x,set2));if(response instanceof Error)return errorToResponse2(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse2(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse2(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response)}},mapCompactResponse2=(response,request)=>{switch(response?.constructor?.name){case"String":return new Response(response);case"Object":case"Array":return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}});case"ElysiaFile":return handleFile(response.value);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse2(response.response,{status:response.code,headers:{}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Error":return errorToResponse2(response);case"Promise":return response.then((x)=>mapCompactResponse2(x,request));case"Function":return mapCompactResponse2(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapCompactResponse2(x,request));if(response instanceof Error)return errorToResponse2(response);if(response instanceof ElysiaCustomStatusResponse)return mapResponse2(response.response,{status:response.code,headers:{}});if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,void 0,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse2(x,set));if(typeof response?.toResponse==="function")return mapCompactResponse2(response.toResponse());if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91)return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}})}return new Response(response)}},errorToResponse2=(error,set2)=>{if(typeof error?.toResponse==="function"){let raw=error.toResponse(),targetSet=set2??{headers:{},status:200,redirect:""},apply=(resolved)=>{if(resolved instanceof Response)targetSet.status=resolved.status;return mapResponse2(resolved,targetSet)};return typeof raw?.then==="function"?raw.then(apply):apply(raw)}return new Response(JSON.stringify({name:error?.name,message:error?.message,cause:error?.cause}),{status:set2?.status!==200?set2?.status??500:500,headers:set2?.headers})},createStaticHandler2=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse2(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return()=>response.clone()},handleResponse2=createResponseHandler({mapResponse:mapResponse2,mapCompactResponse:mapCompactResponse2}),handleStream2=createStreamHandler({mapResponse:mapResponse2,mapCompactResponse:mapCompactResponse2});var allocateIf2=(value,condition)=>condition?value:"",createContext=(app,route,inference,isInline=!1)=>{let fnLiteral="",defaultHeaders=app.setHeaders,hasTrace=!!app.event.trace?.length;if(hasTrace)fnLiteral+=`const id=randomId()
352
- `;let isDynamic=/[:*]/.test(route.path),getQi=`const u=request.url,s=u.indexOf('/',${app.config.handler?.standardHostname??!0?11:7}),qi=u.indexOf('?', s + 1)
351
+ `,2);return[x[0],x[1],{isArrowReturn:!1}]},bracketPairRange=(parameter)=>{let start=parameter.indexOf("{");if(start===-1)return[-1,0];let end=start+1,deep=1;for(;end<parameter.length;end++){let char=parameter.charCodeAt(end);if(char===123)deep++;else if(char===125)deep--;if(deep===0)break}if(deep!==0)return[0,parameter.length];return[start,end+1]},bracketPairRangeReverse=(parameter)=>{let end=parameter.lastIndexOf("}");if(end===-1)return[-1,0];let start=end-1,deep=1;for(;start>=0;start--){let char=parameter.charCodeAt(start);if(char===125)deep++;else if(char===123)deep--;if(deep===0)break}if(deep!==0)return[-1,0];return[start,end+1]},removeColonAlias=(parameter)=>{while(!0){let start=parameter.indexOf(":");if(start===-1)break;let end=parameter.indexOf(",",start);if(end===-1)end=parameter.indexOf("}",start)-1;if(end===-2)end=parameter.length;parameter=parameter.slice(0,start)+parameter.slice(end)}return parameter},retrieveRootParamters=(parameter)=>{let hasParenthesis=!1;if(parameter.charCodeAt(0)===40)parameter=parameter.slice(1,-1);if(parameter.charCodeAt(0)===123)hasParenthesis=!0,parameter=parameter.slice(1,-1);parameter=parameter.replace(/( |\t|\n)/g,"").trim();let parameters=[];while(!0){let[start,end]=bracketPairRange(parameter);if(start===-1)break;if(parameters.push(parameter.slice(0,start-1)),parameter.charCodeAt(end)===44)end++;parameter=parameter.slice(end)}if(parameter=removeColonAlias(parameter),parameter)parameters=parameters.concat(parameter.split(","));let parameterMap=Object.create(null);for(let p of parameters){if(p.indexOf(",")===-1){parameterMap[p]=!0;continue}for(let q of p.split(","))parameterMap[q.trim()]=!0}return{hasParenthesis,parameters:parameterMap}},findParameterReference=(parameter,inference)=>{let{parameters,hasParenthesis}=retrieveRootParamters(parameter);if(parameters.query)inference.query=!0;if(parameters.headers)inference.headers=!0;if(parameters.body)inference.body=!0;if(parameters.cookie)inference.cookie=!0;if(parameters.set)inference.set=!0;if(parameters.server)inference.server=!0;if(parameters.route)inference.route=!0;if(parameters.url)inference.url=!0;if(parameters.path)inference.path=!0;if(hasParenthesis)return`{ ${Object.keys(parameters).join(", ")} }`;return Object.keys(parameters).join(", ")},findEndIndex=(type,content,index)=>{let regex2=new RegExp(`${type.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\n\\t,; ]`);if(index!==void 0)regex2.lastIndex=index;let match=regex2.exec(content);return match?match.index:-1};var findAlias=(type,body,depth=0)=>{if(depth>5)return[];let aliases=[],content=body;while(!0){let index=findEndIndex(" = "+type,content);if(index===-1)index=findEndIndex("="+type,content);if(index===-1){let lastIndex=content.indexOf(" = "+type);if(lastIndex===-1)lastIndex=content.indexOf("="+type);if(lastIndex+3+type.length!==content.length)break;index=lastIndex}let part=content.slice(0,index),lastPart=part.lastIndexOf(" "),variable=part.slice(lastPart!==-1?lastPart+1:-1);if(variable==="}"){let[start,end]=bracketPairRangeReverse(part);aliases.push(removeColonAlias(content.slice(start,end))),content=content.slice(index+3+type.length);continue}while(variable.charCodeAt(0)===44)variable=variable.slice(1);while(variable.charCodeAt(0)===9)variable=variable.slice(1);if(!variable.includes("("))aliases.push(variable);content=content.slice(index+3+type.length)}for(let alias of aliases){if(alias.charCodeAt(0)===123)continue;let deepAlias=findAlias(alias,body);if(deepAlias.length>0)aliases.push(...deepAlias)}return aliases},extractMainParameter=(parameter)=>{if(!parameter)return;if(parameter.charCodeAt(0)!==123)return parameter;if(parameter=parameter.slice(2,-2),!parameter.includes(",")){if(parameter.indexOf("...")!==-1)return parameter.slice(parameter.indexOf("...")+3);return}let spreadIndex=parameter.indexOf("...");if(spreadIndex===-1)return;return parameter.slice(spreadIndex+3).trimEnd()},inferBodyReference=(code,aliases,inference)=>{let access=(type,alias)=>new RegExp(`${alias}\\.(${type})|${alias}\\["${type}"\\]|${alias}\\['${type}'\\]`).test(code);for(let alias of aliases){if(!alias)continue;if(alias.charCodeAt(0)===123){let parameters=retrieveRootParamters(alias).parameters;if(parameters.query)inference.query=!0;if(parameters.headers)inference.headers=!0;if(parameters.body)inference.body=!0;if(parameters.cookie)inference.cookie=!0;if(parameters.set)inference.set=!0;if(parameters.server)inference.server=!0;if(parameters.url)inference.url=!0;if(parameters.route)inference.route=!0;if(parameters.path)inference.path=!0;continue}if(!inference.query&&(access("query",alias)||code.includes("return "+alias)||code.includes("return "+alias+".query")))inference.query=!0;if(!inference.headers&&access("headers",alias))inference.headers=!0;if(!inference.body&&access("body",alias))inference.body=!0;if(!inference.cookie&&access("cookie",alias))inference.cookie=!0;if(!inference.set&&access("set",alias))inference.set=!0;if(!inference.server&&access("server",alias))inference.server=!0;if(!inference.route&&access("route",alias))inference.route=!0;if(!inference.url&&access("url",alias))inference.url=!0;if(!inference.path&&access("path",alias))inference.path=!0;if(inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server&&inference.route&&inference.url&&inference.path)break}return aliases};var isContextPassToFunction=(context,body,inference)=>{try{let captureFunction=new RegExp(`\\w\\((?:.*?)?${context}(?:.*?)?\\)`,"gs"),exactParameter=new RegExp(`${context}(,|\\))`,"gs"),length=body.length,fn;fn=captureFunction.exec(body)+"";while(captureFunction.lastIndex!==0&&captureFunction.lastIndex<length+(fn?fn.length:0)){if(fn&&exactParameter.test(fn))return inference.query=!0,inference.headers=!0,inference.body=!0,inference.cookie=!0,inference.set=!0,inference.server=!0,inference.url=!0,inference.route=!0,inference.path=!0,!0;fn=captureFunction.exec(body)+""}let nextChar=body.charCodeAt(captureFunction.lastIndex);if(nextChar===41||nextChar===44)return inference.query=!0,inference.headers=!0,inference.body=!0,inference.cookie=!0,inference.set=!0,inference.server=!0,inference.url=!0,inference.route=!0,inference.path=!0,!0;return!1}catch(error){return console.log("[Sucrose] warning: unexpected isContextPassToFunction error, you may continue development as usual but please report the following to maintainers:"),console.log("--- body ---"),console.log(body),console.log("--- context ---"),console.log(context),!0}},pendingGC,caches2={},clearSucroseCache=(delay)=>{if(delay===null||isCloudflareWorker())return;if(delay===void 0)delay=295000;if(pendingGC)clearTimeout(pendingGC);pendingGC=setTimeout(()=>{if(caches2={},pendingGC=void 0,isBun)Bun.gc(!1)},delay),pendingGC.unref?.()},mergeInference=(a,b)=>{return{body:a.body||b.body,cookie:a.cookie||b.cookie,headers:a.headers||b.headers,query:a.query||b.query,set:a.set||b.set,server:a.server||b.server,url:a.url||b.url,route:a.route||b.route,path:a.path||b.path}},sucrose=(lifeCycle,inference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1,url:!1,route:!1,path:!1},settings={})=>{let events=[];if(lifeCycle.request?.length)events.push(...lifeCycle.request);if(lifeCycle.beforeHandle?.length)events.push(...lifeCycle.beforeHandle);if(lifeCycle.parse?.length)events.push(...lifeCycle.parse);if(lifeCycle.error?.length)events.push(...lifeCycle.error);if(lifeCycle.transform?.length)events.push(...lifeCycle.transform);if(lifeCycle.afterHandle?.length)events.push(...lifeCycle.afterHandle);if(lifeCycle.mapResponse?.length)events.push(...lifeCycle.mapResponse);if(lifeCycle.afterResponse?.length)events.push(...lifeCycle.afterResponse);if(lifeCycle.handler&&typeof lifeCycle.handler==="function")events.push(lifeCycle.handler);for(let i=0;i<events.length;i++){let e=events[i];if(!e)continue;let event=typeof e==="object"?e.fn:e;if(typeof event!=="function")continue;let content=event.toString(),key=checksum(content),cachedInference=caches2[key];if(cachedInference){inference=mergeInference(inference,cachedInference);continue}clearSucroseCache(settings.gcTime);let fnInference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1,url:!1,route:!1,path:!1},[parameter,body]=separateFunction(content),rootParameters=findParameterReference(parameter,fnInference),mainParameter=extractMainParameter(rootParameters);if(mainParameter){let aliases=findAlias(mainParameter,body.slice(1,-1));aliases.splice(0,-1,mainParameter);let code=body;if(code.charCodeAt(0)===123&&code.charCodeAt(body.length-1)===125)code=code.slice(1,-1).trim();if(!isContextPassToFunction(mainParameter,code,fnInference))inferBodyReference(code,aliases,fnInference);if(!fnInference.query&&code.includes("return "+mainParameter+".query"))fnInference.query=!0}if(!caches2[key])caches2[key]=fnInference;if(inference=mergeInference(inference,fnInference),inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server&&inference.url&&inference.route&&inference.path)break}return inference};var mapResponse2=(response,set,request)=>{if(isNotEmpty(set.headers)||set.status!==200||set.cookie)switch(handleSet(set),response?.constructor?.name){case"String":return new Response(response,set);case"Array":case"Object":return set.headers["content-type"]="application/json",new Response(JSON.stringify(response),set);case"ElysiaFile":return handleFile(response.value,set);case"File":return handleFile(response,set);case"Blob":return handleFile(response,set);case"ElysiaCustomStatusResponse":return set.status=response.code,mapResponse2(response.response,set,request);case void 0:if(!response)return new Response("",set);return new Response(JSON.stringify(response),set);case"Response":return handleResponse2(response,set,request);case"Error":return errorToResponse2(response,set);case"Promise":return response.then((x)=>mapResponse2(x,set,request));case"Function":return mapResponse2(response(),set,request);case"Number":case"Boolean":return new Response(response.toString(),set);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set);return new Response(response?.toString(),set);case"FormData":return new Response(response,set);default:if(response instanceof Response)return handleResponse2(response,set,request);if(response instanceof Promise)return response.then((x)=>mapResponse2(x,set));if(response instanceof Error)return errorToResponse2(response,set);if(response instanceof ElysiaCustomStatusResponse)return set.status=response.code,mapResponse2(response.response,set,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse2(x,set));if(typeof response?.toResponse==="function")return mapResponse2(response.toResponse(),set);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set.headers["Content-Type"])set.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set)}}return new Response(response,set)}if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set,request);return mapCompactResponse2(response,request)},mapEarlyResponse2=(response,set,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set.headers)||set.status!==200||set.cookie)switch(handleSet(set),response?.constructor?.name){case"String":return new Response(response,set);case"Array":case"Object":return set.headers["content-type"]="application/json",new Response(JSON.stringify(response),set);case"ElysiaFile":return handleFile(response.value,set);case"File":return handleFile(response,set);case"Blob":return handleFile(response,set);case"ElysiaCustomStatusResponse":return set.status=response.code,mapEarlyResponse2(response.response,set,request);case void 0:if(!response)return;return new Response(JSON.stringify(response),set);case"Response":return handleResponse2(response,set,request);case"Promise":return response.then((x)=>mapEarlyResponse2(x,set));case"Error":return errorToResponse2(response,set);case"Function":return mapEarlyResponse2(response(),set);case"Number":case"Boolean":return new Response(response.toString(),set);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set);return new Response(response?.toString(),set);default:if(response instanceof Response)return handleResponse2(response,set,request);if(response instanceof Promise)return response.then((x)=>mapEarlyResponse2(x,set));if(response instanceof Error)return errorToResponse2(response,set);if(response instanceof ElysiaCustomStatusResponse)return set.status=response.code,mapEarlyResponse2(response.response,set,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse2(x,set));if(typeof response?.toResponse==="function")return mapEarlyResponse2(response.toResponse(),set);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set.headers["Content-Type"])set.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set)}}return new Response(response,set)}else switch(response?.constructor?.name){case"String":return new Response(response);case"Array":case"Object":return set.headers["content-type"]="application/json",new Response(JSON.stringify(response),set);case"ElysiaFile":return handleFile(response.value,set);case"File":return handleFile(response,set);case"Blob":return handleFile(response,set);case"ElysiaCustomStatusResponse":return set.status=response.code,mapEarlyResponse2(response.response,set,request);case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Promise":return response.then((x)=>{let r=mapEarlyResponse2(x,set);if(r!==void 0)return r});case"Error":return errorToResponse2(response,set);case"Function":return mapCompactResponse2(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"Cookie":if(response instanceof Cookie)return new Response(response.value,set);return new Response(response?.toString(),set);case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapEarlyResponse2(x,set));if(response instanceof Error)return errorToResponse2(response,set);if(response instanceof ElysiaCustomStatusResponse)return set.status=response.code,mapEarlyResponse2(response.response,set,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse2(x,set));if(typeof response?.toResponse==="function")return mapEarlyResponse2(response.toResponse(),set);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set.headers["Content-Type"])set.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set)}}return new Response(response)}},mapCompactResponse2=(response,request)=>{switch(response?.constructor?.name){case"String":return new Response(response);case"Object":case"Array":return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}});case"ElysiaFile":return handleFile(response.value);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse2(response.response,{status:response.code,headers:{}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Error":return errorToResponse2(response);case"Promise":return response.then((x)=>mapCompactResponse2(x,request));case"Function":return mapCompactResponse2(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapCompactResponse2(x,request));if(response instanceof Error)return errorToResponse2(response);if(response instanceof ElysiaCustomStatusResponse)return mapResponse2(response.response,{status:response.code,headers:{}});if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,void 0,request);if(typeof response?.then==="function")return response.then((x)=>mapCompactResponse2(x,request));if(typeof response?.toResponse==="function")return mapCompactResponse2(response.toResponse());if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91)return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}})}return new Response(response)}},errorToResponse2=(error,set)=>{if(typeof error?.toResponse==="function"){let raw=error.toResponse(),targetSet=set??{headers:{},status:200,redirect:""},apply=(resolved)=>{if(resolved instanceof Response)targetSet.status=resolved.status;return mapResponse2(resolved,targetSet)};return typeof raw?.then==="function"?raw.then(apply):apply(raw)}return new Response(JSON.stringify({name:error?.name,message:error?.message,cause:error?.cause}),{status:set?.status!==200?set?.status??500:500,headers:set?.headers})},createStaticHandler2=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse2(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return()=>response.clone()},handleResponse2=createResponseHandler({mapResponse:mapResponse2,mapCompactResponse:mapCompactResponse2}),handleStream2=createStreamHandler({mapResponse:mapResponse2,mapCompactResponse:mapCompactResponse2});var allocateIf2=(value,condition)=>condition?value:"",createContext=(app,route,inference,isInline=!1)=>{let fnLiteral="",defaultHeaders=app.setHeaders,hasTrace=!!app.event.trace?.length;if(hasTrace)fnLiteral+=`const id=randomId()
352
+ `;let isDynamic=/[:*]/.test(route.path),getQi=`const u=request.url,s=u.indexOf('/',${app.config.handler?.standardHostname??!0?11:7}),qi=u.indexOf('?',s+1)
353
353
  `,needsQuery=inference.query||!!route.hooks.query||!!route.hooks.standaloneValidator?.find((x)=>x.query)||app.event.request?.length;if(needsQuery)fnLiteral+=getQi;let getPath=!inference.path?"":!isDynamic?`path:'${route.path}',`:"get path(){"+(needsQuery?"":getQi)+`if(qi===-1)return u.substring(s)
354
354
  return u.substring(s,qi)
355
355
  },`;if(fnLiteral+=allocateIf2("const c=",!isInline)+"{request,store,"+allocateIf2("qi,",needsQuery)+allocateIf2("params:request.params,",isDynamic)+getPath+allocateIf2("url:request.url,",hasTrace||inference.url||needsQuery)+"redirect,status,set:{headers:"+(isNotEmpty(defaultHeaders)?"Object.assign({},app.setHeaders)":"Object.create(null)")+",status:200}",inference.server)fnLiteral+=",get server(){return app.getServer()}";if(hasTrace)fnLiteral+=",[ELYSIA_REQUEST_ID]:id";{let decoratorsLiteral="";for(let key of Object.keys(app.singleton.decorator))decoratorsLiteral+=`,'${key}':decorator['${key}']`;fnLiteral+=decoratorsLiteral}return fnLiteral+=`}
356
356
  `,fnLiteral},createBunRouteHandler=(app,route)=>{let hasTrace=!!app.event.trace?.length,hasHoc=!!app.extender.higherOrderFunctions.length,inference=sucrose(route.hooks,app.inference);inference=sucrose({handler:route.handler},inference);let fnLiteral="const handler=data.handler,app=data.app,store=data.store,decorator=data.decorator,redirect=data.redirect,route=data.route,mapEarlyResponse=data.mapEarlyResponse,"+allocateIf2("randomId=data.randomId,",hasTrace)+allocateIf2("ELYSIA_REQUEST_ID=data.ELYSIA_REQUEST_ID,",hasTrace)+allocateIf2("ELYSIA_TRACE=data.ELYSIA_TRACE,",hasTrace)+allocateIf2("trace=data.trace,",hasTrace)+allocateIf2("hoc=data.hoc,",hasHoc)+`status=data.status
357
357
  `;if(app.event.request?.length)fnLiteral+=`const onRequest=app.event.request.map(x=>x.fn)
358
- `;fnLiteral+=`${app.event.request?.find(isAsync)?"async":""} function map(request){`;let needsQuery=inference.query||!!route.hooks.query||!!route.hooks.standaloneValidator?.find((x)=>x.query);if(hasTrace||needsQuery||app.event.request?.length)fnLiteral+=createContext(app,route,inference),fnLiteral+=createOnRequestHandler(app),fnLiteral+="return handler(c)}";else fnLiteral+=`return handler(${createContext(app,route,inference,!0)})}`;return fnLiteral+=createHoc(app),Function("data",fnLiteral)({app,handler:route.compile?.()??route.composed,redirect,status,hoc:app.extender.higherOrderFunctions.map((x)=>x.fn),store:app.store,decorator:app.decorator,route:route.path,randomId:hasTrace?randomId:void 0,ELYSIA_TRACE:hasTrace?ELYSIA_TRACE:void 0,ELYSIA_REQUEST_ID:hasTrace?ELYSIA_REQUEST_ID:void 0,trace:hasTrace?app.event.trace?.map((x)=>x?.fn??x):void 0,mapEarlyResponse:mapEarlyResponse2})};var createNativeStaticHandler=(handle,hooks,set2)=>{if(typeof handle==="function"||handle instanceof Blob)return;if(isHTMLBundle(handle))return()=>handle;let response=mapResponse2(handle,set2??{headers:{}});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length){if(response instanceof Promise)return response.then((response2)=>{if(!response2)return;if(!response2.headers.has("content-type"))response2.headers.append("content-type","text/plain");return response2.clone()});if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain");return()=>response.clone()}};var websocket={open(ws){ws.data.open?.(ws)},message(ws,message){ws.data.message?.(ws,message)},drain(ws){ws.data.drain?.(ws)},close(ws,code,reason){ws.data.close?.(ws,code,reason)},ping(ws){ws.data.ping?.(ws)},pong(ws){ws.data.pong?.(ws)}};class ElysiaWS{raw;data;body;constructor(raw,data,body=void 0){this.raw=raw;this.data=data;this.body=body;this.validator=raw.data?.validator,this.sendText=raw.sendText.bind(raw),this.sendBinary=raw.sendBinary.bind(raw),this.close=raw.close.bind(raw),this.terminate=raw.terminate.bind(raw),this.publishText=raw.publishText.bind(raw),this.publishBinary=raw.publishBinary.bind(raw),this.subscribe=raw.subscribe.bind(raw),this.unsubscribe=raw.unsubscribe.bind(raw),this.isSubscribed=raw.isSubscribed.bind(raw),this.cork=raw.cork.bind(raw),this.remoteAddress=raw.remoteAddress,this.binaryType=raw.binaryType,this.data=raw.data,this.subscriptions=raw.subscriptions,this.send=this.send.bind(this),this.ping=this.ping.bind(this),this.pong=this.pong.bind(this),this.publish=this.publish.bind(this)}send(data,compress){if(Buffer.isBuffer(data))return this.raw.send(data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data,compress)}ping(data){if(Buffer.isBuffer(data))return this.raw.ping(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.ping(data)}pong(data){if(Buffer.isBuffer(data))return this.raw.pong(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.pong(data)}publish(topic,data,compress){if(Buffer.isBuffer(data))return this.raw.publish(topic,data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress)}sendText;sendBinary;close;terminate;publishText;publishBinary;subscribe;unsubscribe;isSubscribed;cork;remoteAddress;binaryType;subscriptions;get readyState(){return this.raw.readyState}validator;["~types"];get id(){return this.data.id}}var createWSMessageParser=(parse2)=>{let parsers=typeof parse2==="function"?[parse2]:parse2;return async function(ws,message){if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===34||start===47||start===91||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message;else if(message==="true")message=!0;else if(message==="false")message=!1;else if(message==="null")message=null}if(parsers)for(let i=0;i<parsers.length;i++){let temp=parsers[i](ws,message);if(temp instanceof Promise)temp=await temp;if(temp!==void 0)return temp}return message}},createHandleWSResponse=(responseValidator)=>{let handleWSResponse=(ws,data)=>{if(data instanceof Promise)return data.then((data2)=>handleWSResponse(ws,data2));if(Buffer.isBuffer(data))return ws.send(data.toString());if(data===void 0)return;let validateResponse=responseValidator?responseValidator.provider==="standard"?(data2)=>responseValidator.schema["~standard"].validate(data2).issues:(data2)=>responseValidator.Check(data2)===!1:void 0,send=(datum)=>{if(validateResponse&&validateResponse(datum)===!1)return ws.send(new ValidationError("message",responseValidator,datum).message);if(typeof datum==="object")return ws.send(JSON.stringify(datum));ws.send(datum)};if(typeof data?.next!=="function")return void send(data);let init=data.next();if(init instanceof Promise)return(async()=>{let first=await init;if(validateResponse&&validateResponse(first))return ws.send(new ValidationError("message",responseValidator,first).message);if(send(first.value),!first.done)for await(let datum of data)send(datum)})();if(send(init.value),!init.done)for(let datum of data)send(datum)};return handleWSResponse};var optionalParam=/:.+?\?(?=\/|$)/,getPossibleParams=(path)=>{let match=optionalParam.exec(path);if(!match)return[path];let routes=[],head=path.slice(0,match.index),param=match[0].slice(0,-1),tail=path.slice(match.index+match[0].length);routes.push(head.slice(0,-1)),routes.push(head+param);for(let fragment of getPossibleParams(tail)){if(!fragment)continue;if(!fragment.startsWith("/:"))routes.push(head.slice(0,-1)+fragment);routes.push(head+param+fragment)}return routes},isHTMLBundle=(handle)=>{return typeof handle==="object"&&handle!==null&&(handle.toString()==="[object HTMLBundle]"||typeof handle.index==="string")},supportedMethods={GET:!0,HEAD:!0,OPTIONS:!0,DELETE:!0,PATCH:!0,POST:!0,PUT:!0},mapRoutes=(app)=>{if(!app.config.aot||!app.config.systemRouter)return;let routes={},add=(route,handler)=>{let path=encodeURI(route.path);if(routes[path]){if(!routes[path][route.method])routes[path][route.method]=handler}else routes[path]={[route.method]:handler}},tree=app.routeTree;for(let route of app.router.history){if(typeof route.handler!=="function")continue;let method=route.method;if(method==="GET"&&`WS_${route.path}`in tree||method==="WS"||route.path.charCodeAt(route.path.length-1)===42||!(method in supportedMethods))continue;if(method==="ALL"){if(!(`WS_${route.path}`in tree))routes[route.path]=route.hooks?.config?.mount?route.hooks.trace||app.event.trace||app.extender.higherOrderFunctions?createBunRouteHandler(app,route):route.hooks.mount||route.handler:route.handler;continue}let compiled,handler=app.config.precompile?createBunRouteHandler(app,route):(request)=>{if(compiled)return compiled(request);return(compiled=createBunRouteHandler(app,route))(request)};for(let path of getPossibleParams(route.path))add({method,path},handler)}return routes},mergeRoutes=(r1,r2)=>{if(!r2)return r1;for(let key of Object.keys(r2)){if(r1[key]===r2[key])continue;if(!r1[key]){r1[key]=r2[key];continue}if(r1[key]&&r2[key]){if(typeof r1[key]==="function"||r1[key]instanceof Response){r1[key]=r2[key];continue}r1[key]={...r1[key],...r2[key]}}}return r1},BunAdapter={...WebStandardAdapter,name:"bun",handler:{mapResponse:mapResponse2,mapEarlyResponse:mapEarlyResponse2,mapCompactResponse:mapCompactResponse2,createStaticHandler:createStaticHandler2,createNativeStaticHandler},composeHandler:{...WebStandardAdapter.composeHandler,headers:hasHeaderShorthand?`c.headers=c.request.headers.toJSON()
358
+ `;fnLiteral+=`${app.event.request?.find(isAsync)?"async":""} function map(request){`;let needsQuery=inference.query||!!route.hooks.query||!!route.hooks.standaloneValidator?.find((x)=>x.query);if(hasTrace||needsQuery||app.event.request?.length)fnLiteral+=createContext(app,route,inference),fnLiteral+=createOnRequestHandler(app),fnLiteral+="return handler(c)}";else fnLiteral+=`return handler(${createContext(app,route,inference,!0)})}`;return fnLiteral+=createHoc(app),Function("data",fnLiteral)({app,handler:route.compile?.()??route.composed,redirect,status,hoc:app.extender.higherOrderFunctions.map((x)=>x.fn),store:app.store,decorator:app.decorator,route:route.path,randomId:hasTrace?randomId:void 0,ELYSIA_TRACE:hasTrace?ELYSIA_TRACE:void 0,ELYSIA_REQUEST_ID:hasTrace?ELYSIA_REQUEST_ID:void 0,trace:hasTrace?app.event.trace?.map((x)=>x?.fn??x):void 0,mapEarlyResponse:mapEarlyResponse2})};var createNativeStaticHandler=(handle,hooks,set)=>{if(typeof handle==="function"||handle instanceof Blob)return;if(isHTMLBundle(handle))return()=>handle;let response=mapResponse2(handle,set??{headers:{}});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length){if(response instanceof Promise)return response.then((response2)=>{if(!response2)return;if(!response2.headers.has("content-type"))response2.headers.append("content-type","text/plain");return response2.clone()});if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain");return()=>response.clone()}};var websocket={open(ws){ws.data.open?.(ws)},message(ws,message){ws.data.message?.(ws,message)},drain(ws){ws.data.drain?.(ws)},close(ws,code,reason){ws.data.close?.(ws,code,reason)},ping(ws){ws.data.ping?.(ws)},pong(ws){ws.data.pong?.(ws)}};class ElysiaWS{raw;data;body;constructor(raw,data,body=void 0){this.raw=raw;this.data=data;this.body=body;this.validator=raw.data?.validator,this.sendText=raw.sendText.bind(raw),this.sendBinary=raw.sendBinary.bind(raw),this.close=raw.close.bind(raw),this.terminate=raw.terminate.bind(raw),this.publishText=raw.publishText.bind(raw),this.publishBinary=raw.publishBinary.bind(raw),this.subscribe=raw.subscribe.bind(raw),this.unsubscribe=raw.unsubscribe.bind(raw),this.isSubscribed=raw.isSubscribed.bind(raw),this.cork=raw.cork.bind(raw),this.remoteAddress=raw.remoteAddress,this.binaryType=raw.binaryType,this.data=raw.data,this.subscriptions=raw.subscriptions,this.send=this.send.bind(this),this.ping=this.ping.bind(this),this.pong=this.pong.bind(this),this.publish=this.publish.bind(this)}send(data,compress){if(Buffer.isBuffer(data))return this.raw.send(data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data,compress)}ping(data){if(Buffer.isBuffer(data))return this.raw.ping(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.ping(data)}pong(data){if(Buffer.isBuffer(data))return this.raw.pong(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.pong(data)}publish(topic,data,compress){if(Buffer.isBuffer(data))return this.raw.publish(topic,data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress)}sendText;sendBinary;close;terminate;publishText;publishBinary;subscribe;unsubscribe;isSubscribed;cork;remoteAddress;binaryType;subscriptions;get readyState(){return this.raw.readyState}validator;["~types"];get id(){return this.data.id}}var createWSMessageParser=(parse2)=>{let parsers=typeof parse2==="function"?[parse2]:parse2;return async function(ws,message){if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===34||start===47||start===91||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message;else if(message==="true")message=!0;else if(message==="false")message=!1;else if(message==="null")message=null}if(parsers)for(let i=0;i<parsers.length;i++){let temp=parsers[i](ws,message);if(temp instanceof Promise)temp=await temp;if(temp!==void 0)return temp}return message}},createHandleWSResponse=(responseValidator)=>{let handleWSResponse=(ws,data)=>{if(data instanceof Promise)return data.then((data2)=>handleWSResponse(ws,data2));if(Buffer.isBuffer(data))return ws.send(data.toString());if(data===void 0)return;let validateResponse=responseValidator?responseValidator.provider==="standard"?(data2)=>responseValidator.schema["~standard"].validate(data2).issues:(data2)=>responseValidator.Check(data2)===!1:void 0,send=(datum)=>{if(validateResponse&&validateResponse(datum)===!1)return ws.send(new ValidationError("message",responseValidator,datum).message);if(typeof datum==="object")return ws.send(JSON.stringify(datum));ws.send(datum)};if(typeof data?.next!=="function")return void send(data);let init=data.next();if(init instanceof Promise)return(async()=>{let first=await init;if(validateResponse&&validateResponse(first))return ws.send(new ValidationError("message",responseValidator,first).message);if(send(first.value),!first.done)for await(let datum of data)send(datum)})();if(send(init.value),!init.done)for(let datum of data)send(datum)};return handleWSResponse};var optionalParam=/:.+?\?(?=\/|$)/,getPossibleParams=(path)=>{let match=optionalParam.exec(path);if(!match)return[path];let routes=[],head=path.slice(0,match.index),param=match[0].slice(0,-1),tail=path.slice(match.index+match[0].length);routes.push(head.slice(0,-1)),routes.push(head+param);for(let fragment of getPossibleParams(tail)){if(!fragment)continue;if(!fragment.startsWith("/:"))routes.push(head.slice(0,-1)+fragment);routes.push(head+param+fragment)}return routes},isHTMLBundle=(handle)=>{return typeof handle==="object"&&handle!==null&&(handle.toString()==="[object HTMLBundle]"||typeof handle.index==="string")},supportedMethods={GET:!0,HEAD:!0,OPTIONS:!0,DELETE:!0,PATCH:!0,POST:!0,PUT:!0},mapRoutes=(app)=>{if(!app.config.aot||app.config.systemRouter===!1)return;let routes={},add=(route,handler)=>{let path=encodeURI(route.path);if(routes[path]){if(!routes[path][route.method])routes[path][route.method]=handler}else routes[path]={[route.method]:handler}},tree=app.routeTree;for(let route of app.router.history){if(typeof route.handler!=="function")continue;let method=route.method;if(method==="GET"&&`WS_${route.path}`in tree||method==="WS"||route.path.charCodeAt(route.path.length-1)===42||!(method in supportedMethods))continue;if(method==="ALL"){if(!(`WS_${route.path}`in tree))routes[route.path]=route.hooks?.config?.mount?route.hooks.trace||app.event.trace||app.extender.higherOrderFunctions?createBunRouteHandler(app,route):route.hooks.mount||route.handler:route.handler;continue}let compiled,handler=app.config.precompile?createBunRouteHandler(app,route):(request)=>{if(compiled)return compiled(request);return(compiled=createBunRouteHandler(app,route))(request)};for(let path of getPossibleParams(route.path))add({method,path},handler)}return routes},mergeRoutes=(r1,r2)=>{if(!r2)return r1;for(let key of Object.keys(r2)){if(r1[key]===r2[key])continue;if(!r1[key]){r1[key]=r2[key];continue}if(r1[key]&&r2[key]){if(typeof r1[key]==="function"||r1[key]instanceof Response){r1[key]=r2[key];continue}r1[key]={...r1[key],...r2[key]}}}return r1},BunAdapter={...WebStandardAdapter,name:"bun",handler:{mapResponse:mapResponse2,mapEarlyResponse:mapEarlyResponse2,mapCompactResponse:mapCompactResponse2,createStaticHandler:createStaticHandler2,createNativeStaticHandler},composeHandler:{...WebStandardAdapter.composeHandler,headers:hasHeaderShorthand?`c.headers=c.request.headers.toJSON()
359
359
  `:`c.headers={}
360
360
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
361
- `},listen(app){return(options,callback)=>{if(typeof Bun>"u")throw Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw Error("Port must be a numeric value");options=parseInt(options)}let createStaticRoute=(iterator,{withAsync=!1}={})=>{let staticRoutes={},ops=[];for(let[path,route]of Object.entries(iterator))if(path=encodeURI(path),supportPerMethodInlineHandler){if(!route)continue;for(let[method,value]of Object.entries(route)){if(!value||!(method in supportedMethods))continue;if(value instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(value.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path][method]=awaited;if(isHTMLBundle(awaited))staticRoutes[path][method]=awaited}))}continue}if(!(value instanceof Response)&&!isHTMLBundle(value))continue;if(!staticRoutes[path])staticRoutes[path]={};staticRoutes[path][method]=value}}else{if(!route)continue;if(route instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(route.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path]=awaited}))}continue}if(!(route instanceof Response))continue;staticRoutes[path]=route}if(withAsync)return Promise.all(ops).then(()=>staticRoutes);return staticRoutes},serve=typeof options==="object"?{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},...options||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{},...options.websocket||{}},fetch:app.fetch}:{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch:app.fetch};if(app.server=Bun.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",async()=>{if(app.server){if(await app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(async()=>{app.config.aot,app.compile(),app.server?.reload({...serve,fetch:app.fetch,routes:mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response,{withAsync:!0}),mapRoutes(app)),app.config.serve?.routes)}),Bun?.gc(!1)})}},async stop(app,closeActiveConnections){if(app.server){if(await app.server.stop(closeActiveConnections),app.server=null,app.event.stop?.length)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",Error().stack)},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,messageValidator=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateMessage=messageValidator?messageValidator.provider==="standard"?(data)=>messageValidator.schema["~standard"].validate(data).issues:(data)=>messageValidator.Check(data)===!1:void 0,responseValidator=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("WS",path,async(context)=>{let server=context.server??app.server,{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=responseValidator,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse3=createHandleWSResponse(responseValidator),parseMessage=createWSMessageParser(parse2),_id;if(typeof options.beforeHandle==="function"){let result=options.beforeHandle(context);if(result instanceof Promise)await result}let errorHandlers=[...options.error?Array.isArray(options.error)?options.error:[options.error]:[],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)].filter((x)=>x),hasCustomErrorHandlers=errorHandlers.length>0,handleErrors=!hasCustomErrorHandlers?()=>{}:async(ws,error)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse3(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:responseValidator,ping(ws,data){options.ping?.(ws,data)},pong(ws,data){options.pong?.(ws,data)},open:async(ws)=>{try{await handleResponse3(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error){handleErrors(ws,error)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage&&validateMessage(message)){let validationError=new ValidationError("message",messageValidator,message);if(!hasCustomErrorHandlers)return void ws.send(validationError.message);return handleErrors(ws,validationError)}try{await handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error){handleErrors(ws,error)}},drain:async(ws)=>{try{await handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error){handleErrors(ws,error)}},close:async(ws,code,reason)=>{try{await handleResponse3(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error){handleErrors(ws,error)}}}}))return;return status(400,"Expected a websocket connection")},{...rest,websocket:options})}};import{TransformDecodeError as TransformDecodeError2}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{let schema=typeChecker.schema;if(!schema)return;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];if(!schema?.properties)return;for(let[key,keySchema]of Object.entries(schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler,defaultHeader=app.setHeaders;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set2={cookie:{},status:200,headers:defaultHeader?{...defaultHeader}:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,error:status,status,redirect}),hooks;try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse3(response2,set2),response2)return context.response=response2}let methodKey=request.method==="GET"&&request.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":request.method,handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find(methodKey,path)??app.router.dynamic.find("ALL",path);if(!handler)throw context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),new NotFoundError;let{handle,validator,content,route}=handler.store;hooks=handler.store.hooks;let body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}else{let contentType;if(request.body)contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn;if(typeof hook==="string")switch(hook){case"json":case"application/json":body=await request.json();break;case"text":case"text/plain":body=await request.text();break;case"urlencoded":case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"arrayBuffer":case"application/octet-stream":body=await request.arrayBuffer();break;case"formdata":case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}default:{let parser=app["~parser"][hook];if(parser){let temp=parser(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}break}}else{let temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta={domain:app.config.cookie?.domain??validator?.cookie?.config.domain,expires:app.config.cookie?.expires??validator?.cookie?.config.expires,httpOnly:app.config.cookie?.httpOnly??validator?.cookie?.config.httpOnly,maxAge:app.config.cookie?.maxAge??validator?.cookie?.config.maxAge,path:app.config.cookie?.path??validator?.cookie?.config.path,priority:app.config.cookie?.priority??validator?.cookie?.config.priority,partitioned:app.config.cookie?.partitioned??validator?.cookie?.config.partitioned,sameSite:app.config.cookie?.sameSite??validator?.cookie?.config.sameSite,secure:app.config.cookie?.secure??validator?.cookie?.config.secure,secrets:app.config.cookie?.secrets??validator?.cookie?.config.secrets,sign:app.config.cookie?.sign??validator?.cookie?.config.sign},cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="derive")Object.assign(context,response2)}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.query?.schema){let schema=validator.query.schema;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];let properties=schema.properties;for(let property of Object.keys(properties)){let value=properties[property];if((value.type==="array"||value.items?.type==="string")&&typeof context.query[property]==="string"&&context.query[property])context.query[property]=context.query[property].split(",")}}if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="resolve"){Object.assign(context,response2);continue}if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(!hooks.afterHandle?.length){let isCustomStatuResponse=response instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response=response.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response);response=temp}else throw new ValidationError("response",responseValidator,response);if(responseValidator?.Encode)response=responseValidator.Encode(response);if(responseValidator?.Clean)response=responseValidator.Clean(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let response2=hooks.afterHandle[i].fn(context);if(response2 instanceof Promise)response2=await response2;let isCustomStatuResponse=response2 instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response2.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response2=response2.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response2)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response2);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response2);response2=temp}else throw new ValidationError("response",responseValidator,response2);if(responseValidator?.Encode)context.response=response2=responseValidator.Encode(response2);if(responseValidator?.Clean)context.response=response2=responseValidator.Clean(response2);let result=mapEarlyResponse3(response2,context.set);if(result!==void 0)return context.response=result}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0){if(secret)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,secret)}else{let properties=validator?.cookie?.schema?.properties;if(secret)for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse3(context.response=response,context.set)}catch(error){let reportedError=error instanceof TransformDecodeError2&&error.error?error.error:error;return app.handleError(context,reportedError)}finally{let afterResponses=hooks?hooks.afterResponse:app.event.afterResponse;if(afterResponses)if(hasSetImmediate)setImmediate(async()=>{for(let afterResponse of afterResponses)await afterResponse.fn(context)});else Promise.resolve().then(async()=>{for(let afterResponse of afterResponses)await afterResponse.fn(context)})}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse3}=app["~adapter"].handler;return async(context,error)=>{let errorContext=Object.assign(context,{error,code:error.code});if(errorContext.set=context.set,typeof error?.toResponse==="function"&&!(error instanceof ValidationError)&&!(error instanceof TransformDecodeError2))try{let raw=error.toResponse();if(typeof raw?.then==="function")raw=await raw;if(raw instanceof Response)context.set.status=raw.status;context.response=raw}catch(toResponseError){}if(!context.response&&app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse3(response,context.set)}if(context.response){if(app.event.mapResponse)for(let i=0;i<app.event.mapResponse.length;i++){let response=app.event.mapResponse[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)context.response=response}return mapResponse3(context.response,context.set)}return context.set.status=error.status??500,mapResponse3(typeof error.cause==="string"?error.cause:error.message,context.set)}};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};"~Prefix"="";"~Singleton"=null;"~Definitions"=null;"~Metadata"=null;"~Ephemeral"=null;"~Volatile"=null;"~Routes"=null;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macro:{},higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){if(!this.global&&!this.scoped&&!this.local)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};standaloneValidator={global:null,scoped:null,local:null};event={};telemetry;router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new _({lazy:!0,onParam:import_fast_decode_uri_component4.default});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _({onParam:import_fast_decode_uri_component4.default});return this["~dynamic"]},static:{},response:{},history:[]};routeTree={};get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup(console.error,()=>{});return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(this.config={aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,encodeSchema:!0,normalize:!0,...config,prefix:config.prefix?config.prefix.charCodeAt(0)===47?config.prefix:`/${config.prefix}`:void 0,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this["~adapter"]=config.adapter??(typeof Bun<"u"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry={stack:Error().stack}}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(_env)===!1){let error=new ValidationError("env",model,_env);throw Error(error.all.map((x)=>x.summary).join(`
362
- `))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name),{models:this.definitions.type});return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,options){let skipPrefix=options?.skipPrefix??!1,allowMeta=options?.allowMeta??!1;localHook??={},this.applyMacro(localHook);let standaloneValidators=[];if(localHook.standaloneValidator)standaloneValidators=standaloneValidators.concat(localHook.standaloneValidator);if(this.standaloneValidator.local)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.local);if(this.standaloneValidator.scoped)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.scoped);if(this.standaloneValidator.global)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.global);if(path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let instanceValidator=this.validator.getCandidate(),cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,createValidator=()=>{let models=this.definitions.type,dynamic=!this.config.aot,normalize=this.config.normalize,modules=this.definitions.typebox,sanitize2=()=>this.config.sanitize,cookieValidator=()=>{if(cloned.cookie||standaloneValidators.find((x)=>x.cookie))return getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,normalize,config:cloned.cookie?.config??{},dynamic,models,validators:standaloneValidators.map((x)=>x.cookie),sanitize:sanitize2})};return shouldPrecompile?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:(()=>{let resolved=resolveSchema(cloned.body,models,modules);return resolved&&Kind7 in resolved&&(hasType("File",resolved)||hasType("Files",resolved))?coerceFormData():coercePrimitiveRoot()})(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:queryCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:(()=>{let resolved=resolveSchema(cloned.body,models,modules);return resolved&&Kind7 in resolved&&(hasType("File",resolved)||hasType("Files",resolved))?coerceFormData():coercePrimitiveRoot()})(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,normalize,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:queryCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}}};if(instanceValidator.body||instanceValidator.cookie||instanceValidator.headers||instanceValidator.params||instanceValidator.query||instanceValidator.response)localHook=mergeHook(localHook,instanceValidator);if(localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);let hooks=isNotEmpty(this.event)?mergeHook(this.event,localHookToLifeCycleStore(localHook)):{...lifeCycleToArray(localHookToLifeCycleStore(localHook))};if(standaloneValidators.length)Object.assign(hooks,{standaloneValidator:standaloneValidators});if(this.config.aot===!1){let validator=createValidator();this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(!this.config.strictPath){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,compile:void 0,hooks});return}let adapter=this["~adapter"].handler,nativeStaticHandler=typeof handle!=="function"?()=>{let context={redirect,request:this["~adapter"].isWebStandard?new Request(`http://ely.sia${path}`,{method}):void 0,server:null,set:{headers:Object.assign({},this.setHeaders)},status,store:this.store};try{this.event.request?.map((x)=>{if(typeof x.fn==="function")return x.fn(context);if(typeof x==="function")return x(context)})}catch(error){let res;if(context.error=error,this.event.error?.some((x)=>{if(typeof x.fn==="function")return res=x.fn(context);if(typeof x==="function")return res=x(context)}),res!==void 0)handle=res}let fn=adapter.createNativeStaticHandler?.(handle,hooks,context.set);return fn instanceof Promise?fn.then((fn2)=>{if(fn2)return fn2}):fn?.()}:void 0,useNativeStaticResponse=this.config.nativeStaticResponse===!0,addResponsePath=(path2)=>{if(!useNativeStaticResponse||!nativeStaticHandler)return;if(supportPerMethodInlineHandler)if(this.router.response[path2])this.router.response[path2][method]=nativeStaticHandler();else this.router.response[path2]={[method]:nativeStaticHandler()};else this.router.response[path2]=nativeStaticHandler()};addResponsePath(path);let _compiled,compile2=()=>{if(_compiled)return _compiled;let compiled=composeHandler({app:this,path,method,hooks,validator:createValidator(),handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference:this.inference});if(this.router.history[index])_compiled=this.router.history[index].composed=compiled;return compiled},oldIndex;if(`${method}_${path}`in this.routeTree)for(let i=0;i<this.router.history.length;i++){let route2=this.router.history[i];if(route2.path===path&&route2.method===method){oldIndex=i;break}}else this.routeTree[`${method}_${path}`]=this.router.history.length;let index=oldIndex??this.router.history.length,route=this.router.history,mainHandler=shouldPrecompile?compile2():(ctx)=>_compiled?_compiled(ctx):(route[index].composed=compile2())(ctx);if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0);else this.router.history.push(Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},localHook.webSocket?{websocket:localHook.websocket}:void 0));let handler={handler:shouldPrecompile?route[index].composed:void 0,compile(){return this.handler=compile2()}},staticRouter=this.router.static,isStaticPath=path.indexOf(":")===-1&&path.indexOf("*")===-1;if(method==="WS"){if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};return}if(this.router.http.add("WS",path,handler),!this.config.strictPath)this.router.http.add("WS",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add("WS",encoded,handler);return}if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};if(!this.config.strictPath)addResponsePath(getLoosePath(path))}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);addResponsePath(loosePath),this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add(method,encoded,handler),addResponsePath(encoded)}}setHeaders;headers(header){if(!header)return this;if(!this.setHeaders)this.setHeaders={};return this.setHeaders=mergeDeep(this.setHeaders,header),this}onStart(handler){return this.on("start",handler),this}onRequest(handler){return this.on("request",handler),this}onParse(options,handler){if(!handler){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,error){switch(typeof name){case"string":return error.prototype[ERROR_CODE]=name,this.definitions.error[name]=error,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error2]of Object.entries(name))error2.prototype[ERROR_CODE]=code,this.definitions.error[code]=error2;return this}onError(options,handler){if(!handler)return this.on("error",options);return this.on(options,"error",handler)}onStop(handler){return this.on("stop",handler),this}on(optionsOrType,typeOrHandlers,handlers){let type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")this.inference=sucrose({[type]:handles.map((x)=>x.fn)},this.inference,this.config.sucrose);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}as(type){if(promoteEvent(this.event.parse,type),promoteEvent(this.event.transform,type),promoteEvent(this.event.beforeHandle,type),promoteEvent(this.event.afterHandle,type),promoteEvent(this.event.mapResponse,type),promoteEvent(this.event.afterResponse,type),promoteEvent(this.event.trace,type),promoteEvent(this.event.error,type),type==="scoped"){if(this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null}else if(type==="global"){if(this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null;if(this.standaloneValidator.scoped!==null)this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null}return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance["~parser"]=this["~parser"],instance.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks})=>{if(path=(isSchema?"":this.config.prefix??"")+prefix+path,isSchema){let{body,headers,query,params,cookie,response,...hook}=schemaOrRun,localHook=hooks;this.applyMacro(hook);let hasStandaloneSchema=body||headers||query||params||cookie||response;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]],standaloneValidator:hook.standaloneValidator||localHook.standaloneValidator||hasStandaloneSchema?[...hook.standaloneValidator??[],...localHook.standaloneValidator??[],...hasStandaloneSchema?[{body,headers,query,params,cookie,response}]:[]]:void 0}),void 0)}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0})}),this}guard(hook,run){if(!run){if(typeof hook==="object"){if(this.applyMacro(hook),hook.detail)if(this.config.detail)this.config.detail=mergeDeep(Object.assign({},this.config.detail),hook.detail);else this.config.detail=hook.detail;if(hook.tags)if(!this.config.detail)this.config.detail={tags:hook.tags};else this.config.detail.tags=hook.tags;let type=hook.as??"local";if(hook.schema==="standalone"){if(!this.standaloneValidator[type])this.standaloneValidator[type]=[];let response=!hook?.response?void 0:typeof hook.response==="string"||(Kind7 in hook.response)||("~standard"in hook.response)?{200:hook.response}:hook?.response;this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie})}else this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie};if(hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);return this}return this.guard({},hook)}let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance.getServer=()=>this.getServer();let sandbox=run(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.getServer=()=>this.server,sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks:localHook})=>{let{body,headers,query,params,cookie,response,...guardHook}=hook,hasStandaloneSchema=body||headers||query||params||cookie||response;this.add(method,path,handler,mergeHook(guardHook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]],standaloneValidator:!hasStandaloneSchema?localHook.standaloneValidator:[...localHook.standaloneValidator??[],{body,headers,query,params,cookie,response}]}))}),this}use(plugin){if(!plugin)return this;if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(plugin instanceof Promise)return this.promisedModules.add(plugin.then((plugin2)=>{if(typeof plugin2==="function")return plugin2(this);if(plugin2 instanceof Elysia)return this._use(plugin2).compile();if(plugin2.constructor?.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor?.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor?.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks}of Object.values(plugin2.router.history))this.add(method,path,handler,hooks,void 0);if(plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let name=plugin.config.name,seed=plugin.config.seed;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin.standaloneValidator?.scoped)if(this.standaloneValidator.local)this.standaloneValidator.local=this.standaloneValidator.local.concat(plugin.standaloneValidator.scoped);else this.standaloneValidator.local=plugin.standaloneValidator.scoped;if(plugin.standaloneValidator?.global)if(this.standaloneValidator.global)this.standaloneValidator.global=this.standaloneValidator.global.concat(plugin.standaloneValidator.global);else this.standaloneValidator.global=plugin.standaloneValidator.global;if(isNotEmpty(plugin["~parser"]))this["~parser"]={...plugin["~parser"],...this["~parser"]};if(plugin.setHeaders)this.headers(plugin.setHeaders);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(!this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))this.extender.macro={...this.extender.macro,...plugin.extender.macro},this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else{if(isNotEmpty(plugin.extender.macro))this.extender.macro={...this.extender.macro,...plugin.extender.macro};if(plugin.extender.higherOrderFunctions.length)this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}if(plugin.extender.higherOrderFunctions.length){deduplicateChecksum(this.extender.higherOrderFunctions);let hofHashes=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let hof=this.extender.higherOrderFunctions[i];if(hof.checksum){if(hofHashes.includes(hof.checksum))this.extender.higherOrderFunctions.splice(i,1),i--;hofHashes.push(hof.checksum)}}hofHashes.length=0}if(this.inference=mergeInference(this.inference,plugin.inference),isNotEmpty(plugin.singleton.decorator))this.decorate(plugin.singleton.decorator);if(isNotEmpty(plugin.singleton.store))this.state(plugin.singleton.store);if(isNotEmpty(plugin.definitions.type))this.model(plugin.definitions.type);if(isNotEmpty(plugin.definitions.error))this.error(plugin.definitions.error);if(isNotEmpty(plugin.extender.macro))this.extender.macro={...this.extender.macro,...plugin.extender.macro};for(let{method,path,handler,hooks}of Object.values(plugin.router.history))this.add(method,path,handler,hooks);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))return this;if(this.dependencies[name].push(this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry?.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else if(isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));if(plugin.validator.global)this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global});if(plugin.validator.scoped)this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped});return this}macro(macroOrName,macro){if(typeof macroOrName==="string"&&!macro)throw Error("Macro function is required");if(typeof macroOrName==="string")this.extender.macro[macroOrName]=macro;else this.extender.macro={...this.extender.macro,...macroOrName};return this}applyMacro(localHook,appliable=localHook,{iteration=0,applied={}}={}){if(iteration>=16)return;let macro=this.extender.macro;for(let[key,value]of Object.entries(appliable)){if(key in macro===!1)continue;let macroHook=typeof macro[key]==="function"?macro[key](value):macro[key];if(!macroHook||typeof macro[key]==="object"&&value===!1)return;let seed=checksum(key+JSON.stringify(macroHook.seed??value));if(seed in applied)continue;applied[seed]=!0;for(let[k2,value2]of Object.entries(macroHook)){if(k2==="seed")continue;if(k2 in emptySchema){insertStandaloneValidator(localHook,k2,value2),delete localHook[key];continue}if(k2==="introspect"){value2?.(localHook),delete localHook[key];continue}if(k2==="detail"){if(!localHook.detail)localHook.detail={};localHook.detail=mergeDeep(localHook.detail,value2,{mergeArray:!0}),delete localHook[key];continue}if(k2 in macro){this.applyMacro(localHook,{[k2]:value2},{applied,iteration:iteration+1}),delete localHook[key];continue}if((k2==="derive"||k2==="resolve")&&typeof value2==="function")value2={fn:value2,subType:k2};switch(typeof localHook[k2]){case"function":localHook[k2]=[localHook[k2],value2];break;case"object":if(Array.isArray(localHook[k2]))localHook[k2].push(value2);else localHook[k2]=[localHook[k2],value2];break;case"undefined":localHook[k2]=value2;break}delete localHook[key]}}}mount(path,handleOrConfig,config){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw Error("Invalid handler")})(),handler2=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL","/*",handler2,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:run}}),this}let handle=handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw Error("Invalid handler")})(),length=path.length-(path.endsWith("*")?1:0),handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL",path,handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this.route("ALL",path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(!value||!isNotEmpty(value))return this;if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){let onlyTypebox=(a)=>{let res={};for(let key in a)if(!("~standard"in a[key]))res[key]=a[key];return res};switch(typeof name){case"object":let parsedTypebox={},kvs=Object.entries(name);if(!kvs.length)return this;for(let[key,value]of kvs){if(key in this.definitions.type)continue;if("~standard"in value)this.definitions.type[key]=value;else parsedTypebox[key]=this.definitions.type[key]=value,parsedTypebox[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedTypebox}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(onlyTypebox(result)),this;case"string":if(!model)break;if(this.definitions.type[name]=model,"~standard"in model)return this;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}if(!model)return this;if(this.definitions.type[name]=model,"~standard"in model)return this;return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[name]:model}),this}Ref(key){return t.Ref(key)}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].beforeCompile?.(this),this["~adapter"].isWebStandard){if(this._handle=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),Object.defineProperty(this,"fetch",{value:this._handle,configurable:!0,writable:!0}),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);get fetch(){let fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this);return Object.defineProperty(this,"fetch",{value:fetch,configurable:!0,writable:!0}),fetch}handleError=async(context,error)=>{return(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error)};listen=(options,callback)=>{return this["~adapter"].listen(this)(options,callback),this};stop=async(closeActiveConnections)=>{return await this["~adapter"].stop?.(this,closeActiveConnections),this};[Symbol.dispose]=()=>{if(this.server)this.stop()};get modules(){return this.promisedModules}}export{validationDetail,t,status,sse,serializeCookie,replaceUrlPath,replaceSchemaTypeFromManyOptions as replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,fileType,file,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidFileType,InvalidCookieSignature,InternalServerError,ElysiaFile,ElysiaCustomStatusResponse,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
361
+ `},listen(app){return(options,callback)=>{if(typeof Bun>"u")throw Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw Error("Port must be a numeric value");options=parseInt(options)}let createStaticRoute=(iterator,{withAsync=!1}={})=>{let staticRoutes={},ops=[];for(let[path,route]of Object.entries(iterator))if(path=encodeURI(path),supportPerMethodInlineHandler){if(!route)continue;for(let[method,value]of Object.entries(route)){if(!value||!(method in supportedMethods))continue;if(value instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(value.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path][method]=awaited;if(isHTMLBundle(awaited))staticRoutes[path][method]=awaited}))}continue}if(!(value instanceof Response)&&!isHTMLBundle(value))continue;if(!staticRoutes[path])staticRoutes[path]={};staticRoutes[path][method]=value}}else{if(!route)continue;if(route instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(route.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path]=awaited}))}continue}if(!(route instanceof Response))continue;staticRoutes[path]=route}if(withAsync)return Promise.all(ops).then(()=>staticRoutes);return staticRoutes},serve=typeof options==="object"?{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},...options||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{},...options.websocket||{}},fetch:app.fetch}:{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch:app.fetch};if(app.server=Bun.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",async()=>{if(app.server){if(await app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(async()=>{app.config.aot,app.compile(),app.server?.reload({...serve,fetch:app.fetch,routes:mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response,{withAsync:!0}),mapRoutes(app)),app.config.serve?.routes)}),Bun?.gc(!1)})}},async stop(app,closeActiveConnections){if(app.server){if(await app.server.stop(closeActiveConnections),app.server=null,app.event.stop?.length)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",Error().stack)},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,messageValidator=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateMessage=messageValidator?messageValidator.provider==="standard"?(data)=>messageValidator.schema["~standard"].validate(data).issues:(data)=>messageValidator.Check(data)===!1:void 0,responseValidator=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("WS",path,async(context)=>{let server=context.server??app.server,{set,path:path2,qi,headers,query,params}=context;if(context.validator=responseValidator,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set.headers,options.upgrade)}if(set.cookie&&isNotEmpty(set.cookie)){let cookie=serializeCookie(set.cookie);if(cookie)set.headers["set-cookie"]=cookie}if(set.headers["set-cookie"]&&Array.isArray(set.headers["set-cookie"]))set.headers=parseSetCookies(new Headers(set.headers),set.headers["set-cookie"]);let handleResponse3=createHandleWSResponse(responseValidator),parseMessage=createWSMessageParser(parse2),_id;if(typeof options.beforeHandle==="function"){let result=options.beforeHandle(context);if(result instanceof Promise)await result}let errorHandlers=[...options.error?Array.isArray(options.error)?options.error:[options.error]:[],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)].filter((x)=>x),hasCustomErrorHandlers=errorHandlers.length>0,handleErrors=!hasCustomErrorHandlers?()=>{}:async(ws,error)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse3(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set.headers)?set.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:responseValidator,ping(ws,data){options.ping?.(ws,data)},pong(ws,data){options.pong?.(ws,data)},open:async(ws)=>{try{await handleResponse3(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error){handleErrors(ws,error)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage&&validateMessage(message)){let validationError=new ValidationError("message",messageValidator,message);if(!hasCustomErrorHandlers)return void ws.send(validationError.message);return handleErrors(ws,validationError)}try{await handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error){handleErrors(ws,error)}},drain:async(ws)=>{try{await handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error){handleErrors(ws,error)}},close:async(ws,code,reason)=>{try{await handleResponse3(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error){handleErrors(ws,error)}}}}))return;return status(400,"Expected a websocket connection")},{...rest,websocket:options})}};import{TransformDecodeError as TransformDecodeError2}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{let schema=typeChecker.schema;if(!schema)return;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];if(!schema?.properties)return;for(let[key,keySchema]of Object.entries(schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler,defaultHeader=app.setHeaders;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set={cookie:{},status:200,headers:defaultHeader?{...defaultHeader}:{}},context=Object.assign({},app.singleton.decorator,{set,store:app.singleton.store,request,path,qi,error:status,status,redirect}),hooks;try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse3(response2,set),response2)return context.response=response2}let methodKey=request.method==="GET"&&request.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":request.method,handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find(methodKey,path)??app.router.dynamic.find("ALL",path);if(!handler)throw context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),new NotFoundError;let{handle,validator,content,route}=handler.store;if(hooks=handler.store.hooks,hooks.config?.mount)return await hooks.config.mount(request);let body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}else{let contentType;if(request.body)contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn;if(typeof hook==="string")switch(hook){case"json":case"application/json":body=await request.json();break;case"text":case"text/plain":body=await request.text();break;case"urlencoded":case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"arrayBuffer":case"application/octet-stream":body=await request.arrayBuffer();break;case"formdata":case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}default:{let parser=app["~parser"][hook];if(parser){let temp=parser(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}break}}else{let temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta={domain:app.config.cookie?.domain??validator?.cookie?.config.domain,expires:app.config.cookie?.expires??validator?.cookie?.config.expires,httpOnly:app.config.cookie?.httpOnly??validator?.cookie?.config.httpOnly,maxAge:app.config.cookie?.maxAge??validator?.cookie?.config.maxAge,path:app.config.cookie?.path??validator?.cookie?.config.path,priority:app.config.cookie?.priority??validator?.cookie?.config.priority,partitioned:app.config.cookie?.partitioned??validator?.cookie?.config.partitioned,sameSite:app.config.cookie?.sameSite??validator?.cookie?.config.sameSite,secure:app.config.cookie?.secure??validator?.cookie?.config.secure,secrets:app.config.cookie?.secrets??validator?.cookie?.config.secrets,sign:app.config.cookie?.sign??validator?.cookie?.config.sign},cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="derive")Object.assign(context,response2)}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.query?.schema){let schema=validator.query.schema;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];let properties=schema.properties;for(let property of Object.keys(properties)){let value=properties[property];if((value.type==="array"||value.items?.type==="string")&&typeof context.query[property]==="string"&&context.query[property])context.query[property]=context.query[property].split(",")}}if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="resolve"){Object.assign(context,response2);continue}if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(!hooks.afterHandle?.length){let isCustomStatuResponse=response instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response.code:set.status?typeof set.status==="string"?StatusMap[set.status]:set.status:200;if(isCustomStatuResponse)set.status=status2,response=response.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response);response=temp}else throw new ValidationError("response",responseValidator,response);if(responseValidator?.Encode)response=responseValidator.Encode(response);if(responseValidator?.Clean)response=responseValidator.Clean(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let response2=hooks.afterHandle[i].fn(context);if(response2 instanceof Promise)response2=await response2;let isCustomStatuResponse=response2 instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response2.code:set.status?typeof set.status==="string"?StatusMap[set.status]:set.status:200;if(isCustomStatuResponse)set.status=status2,response2=response2.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response2)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response2);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response2);response2=temp}else throw new ValidationError("response",responseValidator,response2);if(responseValidator?.Encode)context.response=response2=responseValidator.Encode(response2);if(responseValidator?.Clean)context.response=response2=responseValidator.Clean(response2);let result=mapEarlyResponse3(response2,context.set);if(result!==void 0)return context.response=result}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0){if(secret)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,secret)}else{let properties=validator?.cookie?.schema?.properties;if(secret)for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse3(context.response=response,context.set)}catch(error){let reportedError=error instanceof TransformDecodeError2&&error.error?error.error:error;return app.handleError(context,reportedError)}finally{let afterResponses=hooks?hooks.afterResponse:app.event.afterResponse;if(afterResponses)if(hasSetImmediate)setImmediate(async()=>{for(let afterResponse of afterResponses)await afterResponse.fn(context)});else Promise.resolve().then(async()=>{for(let afterResponse of afterResponses)await afterResponse.fn(context)})}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse3}=app["~adapter"].handler;return async(context,error)=>{let errorContext=Object.assign(context,{error,code:error.code});if(errorContext.set=context.set,typeof error?.toResponse==="function"&&!(error instanceof ValidationError)&&!(error instanceof TransformDecodeError2))try{let raw=error.toResponse();if(typeof raw?.then==="function")raw=await raw;if(raw instanceof Response)context.set.status=raw.status;context.response=raw}catch(toResponseError){}if(!context.response&&app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse3(response,context.set)}if(context.response){if(app.event.mapResponse)for(let i=0;i<app.event.mapResponse.length;i++){let response=app.event.mapResponse[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)context.response=response}return mapResponse3(context.response,context.set)}return context.set.status=error.status??500,mapResponse3(typeof error.cause==="string"?error.cause:error.message,context.set)}};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};"~Prefix"="";"~Singleton"=null;"~Definitions"=null;"~Metadata"=null;"~Ephemeral"=null;"~Volatile"=null;"~Routes"=null;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macro:{},higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){if(!this.global&&!this.scoped&&!this.local)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};standaloneValidator={global:null,scoped:null,local:null};event={};telemetry;router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new _({lazy:!0,onParam:import_fast_decode_uri_component4.default});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _({onParam:import_fast_decode_uri_component4.default});return this["~dynamic"]},static:{},response:{},history:[]};routeTree={};get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup(console.error,()=>{});return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(this.config={aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,encodeSchema:!0,normalize:!0,...config,prefix:config.prefix?config.prefix.charCodeAt(0)===47?config.prefix:`/${config.prefix}`:void 0,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this["~adapter"]=config.adapter??(typeof Bun<"u"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry={stack:Error().stack}}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(_env)===!1){let error=new ValidationError("env",model,_env);throw Error(error.all.map((x)=>x.summary).join(`
362
+ `))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name),{models:this.definitions.type});return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,options){let skipPrefix=options?.skipPrefix??!1,allowMeta=options?.allowMeta??!1;localHook??={},this.applyMacro(localHook);let standaloneValidators=[];if(localHook.standaloneValidator)standaloneValidators=standaloneValidators.concat(localHook.standaloneValidator);if(this.standaloneValidator.local)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.local);if(this.standaloneValidator.scoped)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.scoped);if(this.standaloneValidator.global)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.global);if(path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let instanceValidator=this.validator.getCandidate(),cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,createValidator=()=>{let models=this.definitions.type,dynamic=!this.config.aot,normalize=this.config.normalize,modules=this.definitions.typebox,sanitize2=()=>this.config.sanitize,cookieValidator=()=>{if(cloned.cookie||standaloneValidators.find((x)=>x.cookie))return getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,normalize,config:cloned.cookie?.config??{},dynamic,models,validators:standaloneValidators.map((x)=>x.cookie),sanitize:sanitize2})};return shouldPrecompile?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:(()=>{let resolved=resolveSchema(cloned.body,models,modules);return resolved&&Kind7 in resolved&&(hasType("File",resolved)||hasType("Files",resolved))?coerceFormData():coercePrimitiveRoot()})(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:queryCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:(()=>{let resolved=resolveSchema(cloned.body,models,modules);return resolved&&Kind7 in resolved&&(hasType("File",resolved)||hasType("Files",resolved))?coerceFormData():coercePrimitiveRoot()})(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,normalize,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:queryCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}}};if(instanceValidator.body||instanceValidator.cookie||instanceValidator.headers||instanceValidator.params||instanceValidator.query||instanceValidator.response)localHook=mergeHook(localHook,instanceValidator);if(localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);let hooks=isNotEmpty(this.event)?mergeHook(this.event,localHookToLifeCycleStore(localHook)):{...lifeCycleToArray(localHookToLifeCycleStore(localHook))};if(standaloneValidators.length)Object.assign(hooks,{standaloneValidator:standaloneValidators});if(this.config.aot===!1){let validator=createValidator();this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(!this.config.strictPath){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,compile:void 0,hooks});return}let adapter=this["~adapter"].handler,nativeStaticHandler=typeof handle!=="function"?()=>{let context={redirect,request:this["~adapter"].isWebStandard?new Request(`http://ely.sia${path}`,{method}):void 0,server:null,set:{headers:Object.assign({},this.setHeaders)},status,store:this.store};try{this.event.request?.map((x)=>{if(typeof x.fn==="function")return x.fn(context);if(typeof x==="function")return x(context)})}catch(error){let res;if(context.error=error,this.event.error?.some((x)=>{if(typeof x.fn==="function")return res=x.fn(context);if(typeof x==="function")return res=x(context)}),res!==void 0)handle=res}let fn=adapter.createNativeStaticHandler?.(handle,hooks,context.set);return fn instanceof Promise?fn.then((fn2)=>{if(fn2)return fn2}):fn?.()}:void 0,useNativeStaticResponse=this.config.nativeStaticResponse===!0,addResponsePath=(path2)=>{if(!useNativeStaticResponse||!nativeStaticHandler)return;if(supportPerMethodInlineHandler)if(this.router.response[path2])this.router.response[path2][method]=nativeStaticHandler();else this.router.response[path2]={[method]:nativeStaticHandler()};else this.router.response[path2]=nativeStaticHandler()};addResponsePath(path);let _compiled,compile2=()=>{if(_compiled)return _compiled;let compiled=composeHandler({app:this,path,method,hooks,validator:createValidator(),handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference:this.inference});if(this.router.history[index])_compiled=this.router.history[index].composed=compiled;return compiled},oldIndex;if(`${method}_${path}`in this.routeTree)for(let i=0;i<this.router.history.length;i++){let route2=this.router.history[i];if(route2.path===path&&route2.method===method){oldIndex=i;break}}else this.routeTree[`${method}_${path}`]=this.router.history.length;let index=oldIndex??this.router.history.length,route=this.router.history,mainHandler=shouldPrecompile?compile2():(ctx)=>_compiled?_compiled(ctx):(route[index].composed=compile2())(ctx);if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0);else this.router.history.push(Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},localHook.webSocket?{websocket:localHook.websocket}:void 0));let handler={handler:shouldPrecompile?route[index].composed:void 0,compile(){return this.handler=compile2()}},staticRouter=this.router.static,isStaticPath=path.indexOf(":")===-1&&path.indexOf("*")===-1;if(method==="WS"){if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};return}if(this.router.http.add("WS",path,handler),!this.config.strictPath)this.router.http.add("WS",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add("WS",encoded,handler);return}if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};if(!this.config.strictPath)addResponsePath(getLoosePath(path))}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);addResponsePath(loosePath),this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add(method,encoded,handler),addResponsePath(encoded)}}setHeaders;headers(header){if(!header)return this;if(!this.setHeaders)this.setHeaders={};return this.setHeaders=mergeDeep(this.setHeaders,header),this}onStart(handler){return this.on("start",handler),this}onRequest(handler){return this.on("request",handler),this}onParse(options,handler){if(!handler){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,error){switch(typeof name){case"string":return error.prototype[ERROR_CODE]=name,this.definitions.error[name]=error,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error2]of Object.entries(name))error2.prototype[ERROR_CODE]=code,this.definitions.error[code]=error2;return this}onError(options,handler){if(!handler)return this.on("error",options);return this.on(options,"error",handler)}onStop(handler){return this.on("stop",handler),this}on(optionsOrType,typeOrHandlers,handlers){let type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")this.inference=sucrose({[type]:handles.map((x)=>x.fn)},this.inference,this.config.sucrose);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}as(type){if(promoteEvent(this.event.parse,type),promoteEvent(this.event.transform,type),promoteEvent(this.event.beforeHandle,type),promoteEvent(this.event.afterHandle,type),promoteEvent(this.event.mapResponse,type),promoteEvent(this.event.afterResponse,type),promoteEvent(this.event.trace,type),promoteEvent(this.event.error,type),type==="scoped"){if(this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null}else if(type==="global"){if(this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null;if(this.standaloneValidator.scoped!==null)this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null}return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance["~parser"]=this["~parser"],instance.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks})=>{if(path=(isSchema?"":this.config.prefix??"")+prefix+path,isSchema){let{body,headers,query,params,cookie,response,...hook}=schemaOrRun,localHook=hooks;this.applyMacro(hook);let hasStandaloneSchema=body||headers||query||params||cookie||response;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]],standaloneValidator:hook.standaloneValidator||localHook.standaloneValidator||hasStandaloneSchema?[...hook.standaloneValidator??[],...localHook.standaloneValidator??[],...hasStandaloneSchema?[{body,headers,query,params,cookie,response}]:[]]:void 0}),void 0)}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0})}),this}guard(hook,run){if(!run){if(typeof hook==="object"){if(this.applyMacro(hook),hook.detail)if(this.config.detail)this.config.detail=mergeDeep(Object.assign({},this.config.detail),hook.detail);else this.config.detail=hook.detail;if(hook.tags)if(!this.config.detail)this.config.detail={tags:hook.tags};else this.config.detail.tags=hook.tags;let type=hook.as??"local";if(hook.schema==="standalone"){if(!this.standaloneValidator[type])this.standaloneValidator[type]=[];let response=!hook?.response?void 0:typeof hook.response==="string"||(Kind7 in hook.response)||("~standard"in hook.response)?{200:hook.response}:hook?.response;this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie})}else this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie};if(hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);return this}return this.guard({},hook)}let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance.getServer=()=>this.getServer();let sandbox=run(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.getServer=()=>this.server,sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks:localHook})=>{let{body,headers,query,params,cookie,response,...guardHook}=hook,hasStandaloneSchema=body||headers||query||params||cookie||response;this.add(method,path,handler,mergeHook(guardHook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]],standaloneValidator:!hasStandaloneSchema?localHook.standaloneValidator:[...localHook.standaloneValidator??[],{body,headers,query,params,cookie,response}]}))}),this}use(plugin){if(!plugin)return this;if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(plugin instanceof Promise)return this.promisedModules.add(plugin.then((plugin2)=>{if(typeof plugin2==="function")return plugin2(this);if(plugin2 instanceof Elysia)return this._use(plugin2).compile();if(plugin2.constructor?.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor?.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor?.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks}of Object.values(plugin2.router.history))this.add(method,path,handler,hooks,void 0);if(plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let name=plugin.config.name,seed=plugin.config.seed;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin.standaloneValidator?.scoped)if(this.standaloneValidator.local)this.standaloneValidator.local=this.standaloneValidator.local.concat(plugin.standaloneValidator.scoped);else this.standaloneValidator.local=plugin.standaloneValidator.scoped;if(plugin.standaloneValidator?.global)if(this.standaloneValidator.global)this.standaloneValidator.global=this.standaloneValidator.global.concat(plugin.standaloneValidator.global);else this.standaloneValidator.global=plugin.standaloneValidator.global;if(isNotEmpty(plugin["~parser"]))this["~parser"]={...plugin["~parser"],...this["~parser"]};if(plugin.setHeaders)this.headers(plugin.setHeaders);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(!this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))this.extender.macro={...this.extender.macro,...plugin.extender.macro},this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else{if(isNotEmpty(plugin.extender.macro))this.extender.macro={...this.extender.macro,...plugin.extender.macro};if(plugin.extender.higherOrderFunctions.length)this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}if(plugin.extender.higherOrderFunctions.length){deduplicateChecksum(this.extender.higherOrderFunctions);let hofHashes=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let hof=this.extender.higherOrderFunctions[i];if(hof.checksum){if(hofHashes.includes(hof.checksum))this.extender.higherOrderFunctions.splice(i,1),i--;hofHashes.push(hof.checksum)}}hofHashes.length=0}if(this.inference=mergeInference(this.inference,plugin.inference),isNotEmpty(plugin.singleton.decorator))this.decorate(plugin.singleton.decorator);if(isNotEmpty(plugin.singleton.store))this.state(plugin.singleton.store);if(isNotEmpty(plugin.definitions.type))this.model(plugin.definitions.type);if(isNotEmpty(plugin.definitions.error))this.error(plugin.definitions.error);if(isNotEmpty(plugin.extender.macro))this.extender.macro={...this.extender.macro,...plugin.extender.macro};for(let{method,path,handler,hooks}of Object.values(plugin.router.history))this.add(method,path,handler,hooks);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))return this;if(this.dependencies[name].push(this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry?.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else if(isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));if(plugin.validator.global)this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global});if(plugin.validator.scoped)this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped});return this}macro(macroOrName,macro){if(typeof macroOrName==="string"&&!macro)throw Error("Macro function is required");if(typeof macroOrName==="string")this.extender.macro[macroOrName]=macro;else this.extender.macro={...this.extender.macro,...macroOrName};return this}applyMacro(localHook,appliable=localHook,{iteration=0,applied={}}={}){if(iteration>=16)return;let macro=this.extender.macro;for(let[key,value]of Object.entries(appliable)){if(key in macro===!1)continue;let macroHook=typeof macro[key]==="function"?macro[key](value):macro[key];if(!macroHook||typeof macro[key]==="object"&&value===!1)return;let seed=checksum(key+JSON.stringify(macroHook.seed??value));if(seed in applied)continue;applied[seed]=!0;for(let[k2,value2]of Object.entries(macroHook)){if(k2==="seed")continue;if(k2 in emptySchema){insertStandaloneValidator(localHook,k2,value2),delete localHook[key];continue}if(k2==="introspect"){value2?.(localHook),delete localHook[key];continue}if(k2==="detail"){if(!localHook.detail)localHook.detail={};localHook.detail=mergeDeep(localHook.detail,value2,{mergeArray:!0}),delete localHook[key];continue}if(k2 in macro){this.applyMacro(localHook,{[k2]:value2},{applied,iteration:iteration+1}),delete localHook[key];continue}if((k2==="derive"||k2==="resolve")&&typeof value2==="function")value2={fn:value2,subType:k2};switch(typeof localHook[k2]){case"function":localHook[k2]=[localHook[k2],value2];break;case"object":if(Array.isArray(localHook[k2]))localHook[k2].push(value2);else localHook[k2]=[localHook[k2],value2];break;case"undefined":localHook[k2]=value2;break}delete localHook[key]}}}mount(path,handleOrConfig,config){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw Error("Invalid handler")})(),handler2=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL","/*",handler2,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:run}}),this}let handle=handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw Error("Invalid handler")})(),length=(typeof path==="string"&&this.config.prefix?this.config.prefix+path:path).length-(path.endsWith("*")?1:0),handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL",path,handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this.route("ALL",path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(!value||!isNotEmpty(value))return this;if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){let onlyTypebox=(a)=>{let res={};for(let key in a)if(!("~standard"in a[key]))res[key]=a[key];return res};switch(typeof name){case"object":let parsedTypebox={},kvs=Object.entries(name);if(!kvs.length)return this;for(let[key,value]of kvs){if(key in this.definitions.type)continue;if("~standard"in value)this.definitions.type[key]=value;else parsedTypebox[key]=this.definitions.type[key]=value,parsedTypebox[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedTypebox}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(onlyTypebox(result)),this;case"string":if(!model)break;if(this.definitions.type[name]=model,"~standard"in model)return this;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}if(!model)return this;if(this.definitions.type[name]=model,"~standard"in model)return this;return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[name]:model}),this}Ref(key){return t.Ref(key)}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].beforeCompile?.(this),this["~adapter"].isWebStandard){if(this._handle=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),Object.defineProperty(this,"fetch",{value:this._handle,configurable:!0,writable:!0}),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);get fetch(){let fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this);return Object.defineProperty(this,"fetch",{value:fetch,configurable:!0,writable:!0}),fetch}handleError=async(context,error)=>{return(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error)};listen=(options,callback)=>{return this["~adapter"].listen(this)(options,callback),this};stop=async(closeActiveConnections)=>{return await this["~adapter"].stop?.(this,closeActiveConnections),this};[Symbol.dispose]=()=>{if(this.server)this.stop()};get modules(){return this.promisedModules}}export{validationDetail,t,status,sse,serializeCookie,replaceUrlPath,replaceSchemaTypeFromManyOptions as replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,fileType,file,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidFileType,InvalidCookieSignature,InternalServerError,ElysiaFile,ElysiaCustomStatusResponse,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
363
363
 
364
- //# debugId=63329D9D99EEDD6864756E2164756E21
364
+ //# debugId=AABF164273C3275864756E2164756E21
365
365
  //# sourceMappingURL=index.js.map