elysia 1.1.25 → 1.1.26
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 +738 -518
- package/dist/bun/index.js.map +4 -4
- package/dist/cjs/compose.js +20 -13
- package/dist/cjs/cookies.js +9 -2
- package/dist/cjs/dynamic-handle.js +9 -2
- package/dist/cjs/error.js +9 -2
- package/dist/cjs/handler.js +9 -2
- package/dist/cjs/index.js +21 -14
- package/dist/cjs/trace.js +9 -2
- package/dist/cjs/type-system.js +9 -2
- package/dist/cjs/utils.js +9 -2
- package/dist/cjs/ws/index.js +9 -2
- package/dist/compose.mjs +20 -13
- package/dist/cookies.mjs +9 -2
- package/dist/dynamic-handle.mjs +9 -2
- package/dist/error.mjs +9 -2
- package/dist/handler.mjs +9 -2
- package/dist/index.mjs +21 -14
- package/dist/trace.mjs +9 -2
- package/dist/type-system.mjs +9 -2
- package/dist/utils.mjs +9 -2
- package/dist/ws/index.mjs +9 -2
- package/package.json +1 -1
package/dist/bun/index.js
CHANGED
|
@@ -1,522 +1,742 @@
|
|
|
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_dist=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.parse=parse;exports.serialize=serialize;var cookieNameRegExp=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,cookieValueRegExp=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,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]*$/,__toString=Object.prototype.toString,NullObject=(()=>{let C=function(){};return C.prototype=Object.create(null),C})();function parse(str,options){let obj=new NullObject,len=str.length;if(len<2)return obj;let dec=options?.decode||decode,index=0;do{let eqIdx=str.indexOf("=",index);if(eqIdx===-1)break;let colonIdx=str.indexOf(";",index),endIdx=colonIdx===-1?len:colonIdx;if(eqIdx>endIdx){index=str.lastIndexOf(";",eqIdx-1)+1;continue}let keyStartIdx=startIndex(str,index,eqIdx),keyEndIdx=endIndex(str,eqIdx,keyStartIdx),key=str.slice(keyStartIdx,keyEndIdx);if(obj[key]===void 0){let valStartIdx=startIndex(str,eqIdx+1,endIdx),valEndIdx=endIndex(str,endIdx,valStartIdx),value=dec(str.slice(valStartIdx,valEndIdx));obj[key]=value}index=endIdx+1}while(index<len);return obj}function startIndex(str,index,max){do{let code=str.charCodeAt(index);if(code!==32&&code!==9)return index}while(++index<max);return max}function endIndex(str,index,min){while(index>min){let code=str.charCodeAt(--index);if(code!==32&&code!==9)return index+1}return min}function serialize(name,val,options){let enc=options?.encode||encodeURIComponent;if(!cookieNameRegExp.test(name))throw new TypeError(`argument name is invalid: ${name}`);let value=enc(val);if(!cookieValueRegExp.test(value))throw new TypeError(`argument val is invalid: ${val}`);let str=name+"="+value;if(!options)return str;if(options.maxAge!==void 0){if(!Number.isInteger(options.maxAge))throw new TypeError(`option maxAge is invalid: ${options.maxAge}`);str+="; Max-Age="+options.maxAge}if(options.domain){if(!domainValueRegExp.test(options.domain))throw new TypeError(`option domain is invalid: ${options.domain}`);str+="; Domain="+options.domain}if(options.path){if(!pathValueRegExp.test(options.path))throw new TypeError(`option path is invalid: ${options.path}`);str+="; Path="+options.path}if(options.expires){if(!isDate(options.expires)||!Number.isFinite(options.expires.valueOf()))throw new TypeError(`option expires is invalid: ${options.expires}`);str+="; Expires="+options.expires.toUTCString()}if(options.httpOnly)str+="; HttpOnly";if(options.secure)str+="; Secure";if(options.partitioned)str+="; Partitioned";if(options.priority)switch(typeof options.priority==="string"?options.priority.toLowerCase():options.sameSite){case"low":str+="; Priority=Low";break;case"medium":str+="; Priority=Medium";break;case"high":str+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${options.priority}`)}if(options.sameSite)switch(typeof options.sameSite==="string"?options.sameSite.toLowerCase():options.sameSite){case!0:case"strict":str+="; SameSite=Strict";break;case"lax":str+="; SameSite=Lax";break;case"none":str+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${options.sameSite}`)}return str}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 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(uri2){var percentPosition=uri2.indexOf("%");if(percentPosition===-1)return uri2;var length=uri2.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri2[percentPosition+1],4),low=hexCodeToInt(uri2[percentPosition+2],0),byte2=high|low,type=UTF8_DATA[byte2];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte2&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri2.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri2.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri2.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri2.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 U=(z,q)=>{let v=q?.length?{}:null;if(v)for(let K of q)v[K.part.charCodeAt(0)]=K;return{part:z,store:null,inert:v,params:null,wildcardStore:null}},_=(z,q)=>({...z,part:q}),$=(z)=>({name:z,store:null,inert:null});class Y{root={};history=[];static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/:.+?\?(?=\/|$)/g};add(z,q,v,{ignoreError:K=!1,ignoreHistory:V=!1}={}){if(typeof q!=="string")throw new TypeError("Route path must be a string");if(q==="")q="/";else if(q[0]!=="/")q=`/${q}`;let S=q[q.length-1]==="*",D=q.match(Y.regex.optionalParams);if(D){let F=q.replaceAll("?","");this.add(z,F,v,{ignoreError:K});for(let B=0;B<D.length;B++){let A=q.replace("/"+D[B],"");this.add(z,A,v,{ignoreError:!0})}return v}if(D)q=q.replaceAll("?","");if(this.history.find(([F,B,A])=>F===z&&B===q))return v;if(S||D&&q.charCodeAt(q.length-1)===63)q=q.slice(0,-1);if(!V)this.history.push([z,q,v]);let G=q.split(Y.regex.static),J=q.match(Y.regex.params)||[];if(G[G.length-1]==="")G.pop();let b;if(!this.root[z])b=this.root[z]=U("/");else b=this.root[z];let Q=0;for(let F=0;F<G.length;++F){let B=G[F];if(F>0){let A=J[Q++].slice(1);if(b.params===null)b.params=$(A);else if(b.params.name!==A)if(K)return v;else throw new Error(`Cannot create route "${q}" with parameter "${A}" because a route already exists with a different parameter name ("${b.params.name}") in the same location`);let O=b.params;if(O.inert===null){b=O.inert=U(B);continue}b=O.inert}for(let A=0;;){if(A===B.length){if(A<b.part.length){let O=_(b,b.part.slice(A));Object.assign(b,U(B,[O]))}break}if(A===b.part.length){if(b.inert===null)b.inert={};let O=b.inert[B.charCodeAt(A)];if(O){b=O,B=B.slice(A),A=0;continue}let X=U(B.slice(A));b.inert[B.charCodeAt(A)]=X,b=X;break}if(B[A]!==b.part[A]){let O=_(b,b.part.slice(A)),X=U(B.slice(A));Object.assign(b,U(b.part.slice(0,A),[O,X])),b=X;break}++A}}if(Q<J.length){let B=J[Q].slice(1);if(b.params===null)b.params=$(B);else if(b.params.name!==B)if(K)return v;else throw new Error(`Cannot create route "${q}" with parameter "${B}" because a route already exists with a different parameter name ("${b.params.name}") in the same location`);if(b.params.store===null)b.params.store=v;return b.params.store}if(S){if(b.wildcardStore===null)b.wildcardStore=v;return b.wildcardStore}if(b.store===null)b.store=v;return b.store}find(z,q){let v=this.root[z];if(!v)return null;return Z(q,q.length,v,0)}}var Z=(z,q,v,K)=>{let V=v.part,S=V.length,D=K+S;if(S>1){if(D>q)return null;if(S<15){for(let G=1,J=K+1;G<S;++G,++J)if(V.charCodeAt(G)!==z.charCodeAt(J))return null}else if(z.slice(K,D)!==V)return null}if(D===q){if(v.store!==null)return{store:v.store,params:{}};if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":""}};return null}if(v.inert!==null){let G=v.inert[z.charCodeAt(D)];if(G!==void 0){let J=Z(z,q,G,D);if(J!==null)return J}}if(v.params!==null){let{store:G,name:J,inert:b}=v.params,Q=z.indexOf("/",D);if(Q!==D){if(Q===-1||Q>=q){if(G!==null){let F={};return F[J]=z.substring(D,q),{store:G,params:F}}}else if(b!==null){let F=Z(z,q,b,Q);if(F!==null)return F.params[J]=z.substring(D,Q),F}}}if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":z.substring(D,q)}};return null};var hasReturn=(fn)=>{let fnLiteral=typeof fn==="object"?fn.fn.toString():typeof fn==="string"?fn.toString():fn,parenthesisEnd=fnLiteral.indexOf(")");if(fnLiteral.charCodeAt(parenthesisEnd+2)===61&&fnLiteral.charCodeAt(parenthesisEnd+5)!==123)return!0;return fnLiteral.includes("return")},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(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("\n",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("\n",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 newParameters=[];for(let p of parameters){if(p.indexOf(",")===-1){newParameters.push(p);continue}for(let q of p.split(","))newParameters.push(q.trim())}return parameters=newParameters,{hasParenthesis,parameters}},findParameterReference=(parameter,inference)=>{let{parameters,hasParenthesis}=retrieveRootParamters(parameter);if(!inference.query&¶meters.includes("query"))inference.query=!0;if(!inference.headers&¶meters.includes("headers"))inference.headers=!0;if(!inference.body&¶meters.includes("body"))inference.body=!0;if(!inference.cookie&¶meters.includes("cookie"))inference.cookie=!0;if(!inference.set&¶meters.includes("set"))inference.set=!0;if(!inference.server&¶meters.includes("server"))inference.server=!0;if(hasParenthesis)return`{ ${parameters.join(", ")} }`;return parameters.join(", ")},findEndIndex=(type,content,index)=>{let newLineIndex=content.indexOf(type+"\n",index),newTabIndex=content.indexOf(type+"\t",index),commaIndex=content.indexOf(type+",",index),semicolonIndex=content.indexOf(type+";",index),emptyIndex=content.indexOf(type+" ",index);return[newLineIndex,newTabIndex,commaIndex,semicolonIndex,emptyIndex].filter((i)=>i>0).sort((a,b)=>a-b)[0]||-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){let lastIndex=content.indexOf(" = "+type);if(lastIndex+3+type.length!==content.length)break;index=lastIndex}let part=content.slice(0,index),variable=part.slice(part.lastIndexOf(" ")+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.includes("..."))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)=>code.includes(alias+"."+type)||code.includes(alias+'["'+type+'"]')||code.includes(alias+"['"+type+"']");for(let alias of aliases){if(!alias)continue;if(alias.charCodeAt(0)===123){let parameters=retrieveRootParamters(alias).parameters;if(!inference.query&¶meters.includes("query"))inference.query=!0;if(!inference.headers&¶meters.includes("headers"))inference.headers=!0;if(!inference.body&¶meters.includes("body"))inference.body=!0;if(!inference.cookie&¶meters.includes("cookie"))inference.cookie=!0;if(!inference.set&¶meters.includes("set"))inference.set=!0;if(!inference.query&¶meters.includes("server"))inference.server=!0;continue}if(!inference.query&&access("query",alias))inference.query=!0;if(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.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server)break}return aliases};var isContextPassToFunction=(context,body,inference)=>{try{let captureFunction=new RegExp(`(?:\\w)\\((?:.*)?${context}`,"gs");captureFunction.test(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,!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}},sucrose=(lifeCycle,inference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1})=>{let events=[];if(lifeCycle.handler&&typeof lifeCycle.handler==="function")events.push(lifeCycle.handler);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);for(let e of events){if(!e)continue;let event="fn"in e?e.fn:e,[parameter,body,{isArrowReturn}]=separateFunction(event.toString()),rootParameters=findParameterReference(parameter,inference),mainParameter=extractMainParameter(rootParameters);if(mainParameter){let aliases=findAlias(mainParameter,body);if(aliases.splice(0,-1,mainParameter),!isContextPassToFunction(mainParameter,body,inference))inferBodyReference(body,aliases,inference);if(!inference.query&&body.includes("return "+mainParameter+".query"))inference.query=!0}if(inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server)break}return inference};import{Value as Value3}from"@sinclair/typebox/value";import{Kind as Kind2,TransformKind}from"@sinclair/typebox";import{Value as Value2}from"@sinclair/typebox/value";import{TypeCompiler as TypeCompiler3}from"@sinclair/typebox/compiler";import{Kind,TypeRegistry}from"@sinclair/typebox";import{TypeSystem}from"@sinclair/typebox/system";import{Type,FormatRegistry}from"@sinclair/typebox";import{TypeCompiler}from"@sinclair/typebox/compiler";import{Value}from"@sinclair/typebox/value";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 time(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 DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time=getTime(strictTimeZone);return function date_time(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}}import{TypeSystemPolicy,TypeSystem as TypeSystem2,TypeSystemDuplicateFormat,TypeSystemDuplicateTypeKind}from"@sinclair/typebox/system";import{TypeCompiler as TypeCompiler2,TypeCheck}from"@sinclair/typebox/compiler";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"))TypeSystem.Format("date",(value)=>{let temp=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"))TypeSystem.Format("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)TypeSystem.Format(formatName,(value)=>formatValue.test(value));else if(typeof formatValue==="function")TypeSystem.Format(formatName,formatValue)}});var t=Object.assign({},Type),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},validateFile=(options,value)=>{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"){if(!value.type.startsWith(options.extension))return!1}else{for(let i=0;i<options.extension.length;i++)if(value.type.startsWith(options.extension[i]))return!0;return!1}return!0},File2=TypeRegistry.Get("Files")??TypeSystem.Type("File",validateFile),Files=TypeRegistry.Get("Files")??TypeSystem.Type("Files",(options,value)=>{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});if(!FormatRegistry.Has("numeric"))FormatRegistry.Set("numeric",(value)=>!!value&&!isNaN(+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}});TypeRegistry.Set("UnionEnum",(schema,value)=>{return(typeof value==="number"||typeof value==="string"||value===null)&&schema.enum.includes(value)});var ElysiaType={Numeric:(property)=>{let schema=Type.Number(property);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&&!Value.Check(schema,number))throw new ValidationError("property",schema,number);return number}).Encode((value)=>value)},Date:(property)=>{let schema=Type.Date(property);return t.Transform(t.Union([Type.Date(property),t.String({format:"date",default:new Date().toISOString()}),t.String({format:"date-time",default:new Date().toISOString()})],property)).Decode((value)=>{if(value instanceof Date)return value;let date2=new Date(value);if(!Value.Check(schema,date2))throw new ValidationError("property",schema,date2);return date2}).Encode((value)=>{if(typeof value==="string")return new Date(value);return value})},BooleanString:(property)=>{let schema=Type.Boolean(property);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(property&&!Value.Check(schema,value))throw new ValidationError("property",schema,value);return value}).Encode((value)=>value)},ObjectString:(properties,options)=>{let schema=t.Object(properties,options),defaultValue=JSON.stringify(Value.Create(schema)),compiler;try{compiler=TypeCompiler.Compile(schema)}catch{}return t.Transform(t.Union([t.String({format:"ObjectString",default:defaultValue}),schema])).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==123)throw new ValidationError("property",schema,value);try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(compiler){if(!compiler.Check(value))throw new ValidationError("property",schema,value);return compiler.Decode(value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return Value.Decode(schema,value)}return value}).Encode((value)=>{if(typeof value==="string")try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return JSON.stringify(value)})},ArrayString:(children={},options)=>{let schema=t.Array(children,options),defaultValue=JSON.stringify(Value.Create(schema)),compiler;try{compiler=TypeCompiler.Compile(schema)}catch{}return t.Transform(t.Union([t.String({format:"ArrayString",default:defaultValue}),schema])).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==91)throw new ValidationError("property",schema,value);try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(compiler){if(!compiler.Check(value))throw new ValidationError("property",schema,value);return compiler.Decode(value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return Value.Decode(schema,value)}return value}).Encode((value)=>{if(typeof value==="string")try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return JSON.stringify(value)})},File:File2,Files:(options={})=>t.Transform(Files(options)).Decode((value)=>{if(Array.isArray(value))return value;return[value]}).Encode((value)=>value),Nullable:(schema)=>t.Union([schema,t.Null()]),MaybeEmpty:(schema)=>t.Union([schema,t.Null(),t.Undefined()]),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 new Error("This type does not support objects or arrays");return{default:values[0],...options,[Kind]:"UnionEnum",...type,enum:values}}};t.BooleanString=ElysiaType.BooleanString;t.ObjectString=ElysiaType.ObjectString;t.ArrayString=ElysiaType.ArrayString;t.Numeric=ElysiaType.Numeric;t.File=(arg={})=>ElysiaType.File({default:"File",...arg,extension:arg?.type,type:"string",format:"binary"});t.Files=(arg={})=>ElysiaType.Files({...arg,elysiaMeta:"Files",default:"Files",extension:arg?.type,type:"array",items:{...arg,default:"Files",type:"string",format:"binary"}});t.Nullable=(schema)=>ElysiaType.Nullable(schema);t.MaybeEmpty=ElysiaType.MaybeEmpty;t.Cookie=ElysiaType.Cookie;t.Date=ElysiaType.Date;t.UnionEnum=ElysiaType.UnionEnum;var import_cookie2=__toESM(require_dist(),1);var import_cookie=__toESM(require_dist(),1),import_fast_decode_uri_component=__toESM(require_fast_decode_uri_component(),1);class Cookie{name;jar;initial;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}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){this.setCookie.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)){let value=import_fast_decode_uri_component.default(v);if(sign===!0||sign?.includes(name)){if(!secrets)throw new Error("No secret is provided to cookie plugin");if(isStringKey){let temp=await unsignCookie(value,secrets);if(temp===!1)throw new InvalidCookieSignature(name);value=temp}else{let decoded=!0;for(let i=0;i<secrets.length;i++){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)};var hasHeaderShorthand="toJSON"in new Headers,isNotEmpty=(obj)=>{if(!obj)return!1;for(let x in obj)return!0;return!1},handleFile=(response,set2)=>{let size=response.size;if(!set2&&size||size&&set2&&set2.status!==206&&set2.status!==304&&set2.status!==412&&set2.status!==416){if(set2&&isNotEmpty(set2.headers)){if(set2.headers instanceof Headers){if(hasHeaderShorthand)set2.headers=set2.headers.toJSON();else for(let[key,value]of set2.headers.entries())if(key in set2.headers)set2.headers[key]=value}return new Response(response,{status:set2.status,headers:Object.assign({"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`},set2.headers)})}return new Response(response,{headers:{"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"}})}return new Response(response)},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},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_cookie2.serialize(key,typeof value==="object"?JSON.stringify(value):value+"",property))}if(set2.length===0)return;if(set2.length===1)return set2[0];return set2},handleStream=async(generator,set2,request)=>{let init=generator.next();if(init instanceof Promise)init=await init;if(init.done){if(set2)return mapResponse(init.value,set2,request);return mapCompactResponse(init.value,request)}return new Response(new ReadableStream({async start(controller){let end=!1;if(request?.signal.addEventListener("abort",()=>{end=!0;try{controller.close()}catch{}}),init.value!==void 0&&init.value!==null)if(typeof init.value==="object")try{controller.enqueue(Buffer.from(JSON.stringify(init.value)))}catch{controller.enqueue(Buffer.from(init.value.toString()))}else controller.enqueue(Buffer.from(init.value.toString()));for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(typeof chunk==="object")try{controller.enqueue(Buffer.from(JSON.stringify(chunk)))}catch{controller.enqueue(Buffer.from(chunk.toString()))}else controller.enqueue(Buffer.from(chunk.toString()));await new Promise((resolve)=>setTimeout(()=>resolve(),0))}try{controller.close()}catch{}}}),{...set2,headers:{"transfer-encoding":"chunked","content-type":"text/event-stream; charset=utf-8",...set2?.headers}})};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;yield decoder.decode(value)}}finally{reader.releaseLock()}}var mapResponse=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.redirect||set2.cookie){if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.redirect){if(set2.headers.Location=set2.redirect,!set2.status||set2.status<300||set2.status>=400)set2.status=302}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"]);switch(response?.constructor?.name){case"String":return new Response(response,set2);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response,set2);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse(response.response,set2,request);case"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,set2);case void 0:if(!response)return new Response("",set2);return Response.json(response,set2);case"Response":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 response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(response.status!==set2.status)set2.status=response.status;if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),set2,request);return response;case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>mapResponse(x,set2));case"Function":return mapResponse(response(),set2);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){let isCookieSet2=!1;if(set2.headers instanceof Headers)for(let key of set2.headers.keys())if(key==="set-cookie"){if(isCookieSet2)continue;isCookieSet2=!0;for(let cookie of set2.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(hasHeaderShorthand)set2.headers=response.headers.toJSON();else for(let[key,value]of response.headers.entries())if(key in set2.headers)set2.headers[key]=value;return response}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")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)}}else switch(response?.constructor?.name){case"String":return new Response(response);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse(response.response,set2,request);case"ReadableStream":return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),set2,request);return response;case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>{let r=mapCompactResponse(x,request);if(r!==void 0)return r;return new Response("")});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,set2);default:if(response instanceof Response)return response;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")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)}},mapEarlyResponse=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.redirect||set2.cookie){if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.redirect){if(set2.headers.Location=set2.redirect,!set2.status||set2.status<300||set2.status>=400)set2.status=302}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"]);switch(response?.constructor?.name){case"String":return new Response(response,set2);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response,set2);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,set2);case void 0:if(!response)return;return Response.json(response,set2);case"Response":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 response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(response.status!==set2.status)set2.status=response.status;if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),set2,request);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 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){let isCookieSet2=!1;if(set2.headers instanceof Headers)for(let key of set2.headers.keys())if(key==="set-cookie"){if(isCookieSet2)continue;isCookieSet2=!0;for(let cookie of set2.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(response.status!==set2.status)set2.status=response.status;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")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 new Response(response);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case"ReadableStream":return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(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")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);case"Blob":return handleFile(response);case"Array":return Response.json(response);case"Object":return Response.json(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case"ReadableStream":return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(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")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)=>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===0&&hooks.transform.length===0&&hooks.beforeHandle.length===0&&hooks.afterHandle.length===0)return response.clone.bind(response)},createNativeStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function"||handle instanceof Blob)return;let response=mapResponse(handle,{headers:setHeaders});if(hooks.parse.length===0&&hooks.transform.length===0&&hooks.beforeHandle.length===0&&hooks.afterHandle.length===0){if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain;charset=utf-8");return response.clone.bind(response)}};var 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().startsWith("[object ")&&v.toString()!=="[object Object]"||isNotEmpty(Object.getPrototypeOf(v)),isObject=(item)=>item&&typeof item==="object"&&!Array.isArray(item),mergeDeep=(target,source,{skipKeys,override=!0}={})=>{if(!isObject(target)||!isObject(source))return target;for(let[key,value]of Object.entries(source)){if(skipKeys?.includes(key))continue;if(!isObject(value)||!(key in target)||isClass(value)){if(override||!(key in target))target[key]=value;continue}target[key]=mergeDeep(target[key],value,{skipKeys,override})}return target},mergeCookie=(a,b)=>{let{properties:_2,...target}=a??{},{properties:__,...source}=b??{};return mergeDeep(target,source)},mergeObjectArray=(a=[],b=[])=>{if(!a)return[];if(!b)return a;let array=[],checksums=[];if(!Array.isArray(a))a=[a];if(!Array.isArray(b))b=[b];for(let item of a)if(array.push(item),item.checksum)checksums.push(item.checksum);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),{}),mergeResponse=(a,b)=>{let isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every(isNumericString);if(isRecordNumber(a)&&isRecordNumber(b))return{...a,...b};else if(a&&!isRecordNumber(a)&&isRecordNumber(b))return{200:a,...b};return b??a},mergeSchemaValidator=(a,b)=>{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)=>{return{...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(a?.beforeHandle,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)}},replaceSchemaType=(schema,options,root=!0)=>{if(!Array.isArray(options))return _replaceSchemaType(schema,options,root);for(let option of options)schema=_replaceSchemaType(schema,option,root);return schema},_replaceSchemaType=(schema,options,root=!0)=>{if(!schema)return schema;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind2];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,root);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,root);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,root);return schema}if(schema.not){for(let i=0;i<schema.not.length;i++)schema.not[i]=_replaceSchemaType(schema.not[i],options,root);return schema}let isRoot=root&&!!options.excludeRoot;if(schema[Kind2]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest),transform,composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,!1);return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,!1)};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.default=JSON.stringify(Value2.Create(t.Object(properties2))),value.properties=properties2;if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.default=JSON.stringify(Value2.Create(t.Array(items))),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,!1);return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,!1))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)for(let i=0;i<to.not.length;i++)to.not[i]=composeProperties(to.not[i]);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,!1);return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,!1))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind2]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)for(let i=0;i<to.not.length;i++)to.not[i]={...rest,...to.not[i]};properties[key]={...rest,..._replaceSchemaType(rest,options,!1)};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,!1);break;default:if(value.items)for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,!1);else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,!1);break}return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value2.Clean(schema,structuredClone(value))}catch{try{return Value2.Clean(schema,value)}catch{return value}}return value},getSchemaValidator=(s,{models={},dynamic=!1,normalize=!1,additionalProperties=!1,coerce=!1,additionalCoerce=[]}={})=>{if(!s)return;if(typeof s==="string"&&!(s in models))return;let schema=typeof s==="string"?models[s]:s;if(coerce||additionalCoerce)if(coerce)schema=replaceSchemaType(schema,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);else schema=replaceSchemaType(schema,[...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);if(schema.type==="object"&&"additionalProperties"in schema===!1)schema.additionalProperties=additionalProperties;if(dynamic){let validator={schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value2.Check(schema,value),Errors:(value)=>Value2.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value2.Decode(schema,value),Encode:(value)=>Value2.Encode(schema,value)};if(normalize&&schema.additionalProperties===!1)validator.Clean=createCleaner(schema);if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}return validator.parse=(v)=>{try{return validator.Decode(v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled=TypeCompiler3.Compile(schema,Object.values(models));if(compiled.Clean=createCleaner(schema),schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}return compiled.parse=(v)=>{try{return compiled.Decode(v)}catch(error){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},compiled},getResponseSchemaValidator=(s,{models={},dynamic=!1,normalize=!1,additionalProperties=!1})=>{if(!s)return;if(typeof s==="string"&&!(s in models))return;let maybeSchemaOrRecord=typeof s==="string"?models[s]:s,compile=(schema,references)=>{if(dynamic)return{schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value2.Check(schema,value),Errors:(value)=>Value2.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value2.Decode(schema,value),Encode:(value)=>Value2.Encode(schema,value)};let compiledValidator=TypeCompiler3.Compile(schema,references);if(normalize&&schema.additionalProperties===!1)compiledValidator.Clean=createCleaner(schema);return compiledValidator};if(Kind2 in maybeSchemaOrRecord){if("additionalProperties"in maybeSchemaOrRecord===!1)maybeSchemaOrRecord.additionalProperties=additionalProperties;return{200:compile(maybeSchemaOrRecord,Object.values(models))}}let record={};return Object.keys(maybeSchemaOrRecord).forEach((status)=>{let maybeNameOrSchema=maybeSchemaOrRecord[+status];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];schema.type==="object"&&"additionalProperties"in schema,record[+status]=Kind2 in schema?compile(schema,Object.values(models)):schema}return}if(maybeNameOrSchema.type==="object"&&"additionalProperties"in maybeNameOrSchema===!1)maybeNameOrSchema.additionalProperties=additionalProperties;record[+status]=Kind2 in maybeNameOrSchema?compile(maybeNameOrSchema,Object.values(models)):maybeNameOrSchema}),record},isBun=typeof Bun!=="undefined",hasHash=isBun&&typeof Bun.hash==="function",checksum=(s)=>{if(hasHash)return Bun.hash(s);let h=9;for(let i=0;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),387420489);return h=h^h>>>9},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,defaultConfig={},config,dynamic,models})=>{let cookieValidator=getSchemaValidator(validator,{dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions()});if(isNotEmpty(defaultConfig))if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie({}),{dynamic,models,additionalProperties:!0}),cookieValidator.config=defaultConfig;return cookieValidator},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(a.beforeHandle,injectChecksum(checksum2,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,"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(([k,v])=>[v,k]));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!=="string")throw new TypeError("Cookie value must be provided as a string.");if(secret===null)throw new 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"))},unsignCookie=async(input,secret)=>{if(typeof input!=="string")throw new TypeError("Signed cookie string must be provided.");if(secret===null)throw new TypeError("Secret key must be provided.");let tentativeValue=input.slice(0,input.lastIndexOf("."));return await signCookie(tentativeValue,secret)===input?tentativeValue:!1},traceBackMacro=(extension,property)=>{if(!extension||typeof extension!=="object"||!property)return;for(let[key,value]of Object.entries(property)){if(key in primitiveHookMap||!(key in extension))continue;let v=extension[key];if(typeof v==="function")v(value),delete property[key]}},createMacroManager=({globalHook,localHook})=>(stackName)=>(type,fn)=>{if(typeof type==="function")type={fn:type};if("fn"in type||Array.isArray(type)){if(!localHook[stackName])localHook[stackName]=[];if(typeof localHook[stackName]==="function")localHook[stackName]=[localHook[stackName]];if(Array.isArray(type))localHook[stackName]=localHook[stackName].concat(type);else localHook[stackName].push(type);return}let{insert="after",stack="local"}=type;if(typeof fn==="function")fn={fn};if(stack==="global")if(!Array.isArray(fn))if(insert==="before")globalHook[stackName].unshift(fn);else globalHook[stackName].push(fn);else if(insert==="before")globalHook[stackName]=fn.concat(globalHook[stackName]);else globalHook[stackName]=globalHook[stackName].concat(fn);else{if(!localHook[stackName])localHook[stackName]=[];if(typeof localHook[stackName]==="function")localHook[stackName]=[localHook[stackName]];if(!Array.isArray(fn))if(insert==="before")localHook[stackName].unshift(fn);else localHook[stackName].push(fn);else if(insert==="before")localHook[stackName]=fn.concat(localHook[stackName]);else localHook[stackName]=localHook[stackName].concat(fn)}},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;root=null;promises=[];constructor(onError=console.error){this.onError=onError}get size(){return this.promises.length}add(promise){return this.promises.push(promise),this.root||=this.drain(),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)=>{if(!fn)return fn;if(!Array.isArray(fn)){if(typeof fn==="function")return{fn};else if("fn"in fn)return fn}let fns=[];for(let x of fn)if(typeof x==="function")fns.push({fn:x});else if("fn"in x)fns.push(x);return fns},localHookToLifeCycleStore=(a)=>{return{...a,start:fnToContainer(a?.start),request:fnToContainer(a?.request),parse:fnToContainer(a?.parse),transform:fnToContainer(a?.transform),beforeHandle:fnToContainer(a?.beforeHandle),afterHandle:fnToContainer(a?.afterHandle),mapResponse:fnToContainer(a?.mapResponse),afterResponse:fnToContainer(a?.afterResponse),trace:fnToContainer(a?.trace),error:fnToContainer(a?.error),stop:fnToContainer(a?.stop)}},lifeCycleToFn=(a)=>{return{...a,start:a.start?.map((x)=>x.fn),request:a.request?.map((x)=>x.fn),parse:a.parse?.map((x)=>x.fn),transform:a.transform?.map((x)=>x.fn),beforeHandle:a.beforeHandle?.map((x)=>x.fn),afterHandle:a.afterHandle?.map((x)=>x.fn),afterResponse:a.afterResponse?.map((x)=>x.fn),mapResponse:a.mapResponse?.map((x)=>x.fn),trace:a.trace?.map((x)=>x.fn),error:a.error?.map((x)=>x.fn),stop:a.stop?.map((x)=>x.fn)}},cloneInference=(inference)=>({body:inference.body,cookie:inference.cookie,headers:inference.headers,query:inference.query,set:inference.set,server:inference.server}),redirect=(url,status=302)=>Response.redirect(url,status),ELYSIA_FORM_DATA=Symbol("ElysiaFormData"),ELYSIA_REQUEST_ID=Symbol("ElysiaRequestId"),form=(items)=>{let formData=new FormData;for(let[key,value]of Object.entries(items)){if(Array.isArray(value)){for(let v of value){if(value instanceof File)formData.append(key,value,value.name);formData.append(key,v)}continue}if(value instanceof File)formData.append(key,value,value.name);formData.append(key,value)}return formData},randomId=()=>crypto.getRandomValues(new Uint32Array(1))[0],deduplicateChecksum=(array)=>{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(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"};var env=typeof Bun!=="undefined"?Bun.env:typeof process!=="undefined"?process?.env:void 0,ERROR_CODE=Symbol("ElysiaErrorCode"),isProduction=(env?.NODE_ENV??env?.ENV)==="production";class ElysiaCustomStatusResponse{code;response;constructor(code,response){let res=response??(code in InvertedStatusMap?InvertedStatusMap[code]:code);this.code=StatusMap[code]??code,this.response=res}}var error=(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(){super("Failed to parse body")}}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=(error2)=>{if(!error2)return{summary:void 0};let{message,path,value,type}=error2,property=path.slice(1).replaceAll("/","."),isRoot=path==="";switch(type){case 42:return{...error2,summary:isRoot?"Value should not be provided":`Property '${property}' should not be provided`};case 45:return{...error2,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{...error2,summary:isRoot?"Value should be an email":`Property '${property}' should be ${format}`};case 54:return{...error2,summary:`${message.slice(0,9)} property '${property}' to be ${message.slice(8)} but found: ${value}`};case 62:let union=error2.schema.anyOf.map((x)=>`'${x?.format??x.type}'`).join(", ");return{...error2,summary:isRoot?`Value should be one of ${union}`:`Property '${property}' should be one of: ${union}`};default:return{summary:message,...error2}}};class ValidationError extends Error{type;validator;value;code="VALIDATION";status=422;constructor(type,validator,value){if(value&&typeof value==="object"&&value instanceof ElysiaCustomStatusResponse)value=value.response;let error2=isProduction?void 0:("Errors"in validator)?validator.Errors(value).First():Value3.Errors(validator,value).First(),customError=error2?.schema.error!==void 0?typeof error2.schema.error==="function"?error2.schema.error({type,validator,value,get errors(){return[...validator.Errors(value)].map(mapValueError)}}):error2.schema.error:void 0,accessor=error2?.path||"root",message="";if(customError!==void 0)message=typeof customError==="object"?JSON.stringify(customError):customError+"";else if(isProduction)message=JSON.stringify({type:"validation",on:type,summary:mapValueError(error2).summary,message:error2?.message,found:value});else{let schema=validator?.schema??validator,errors="Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value3.Errors(validator,value)].map(mapValueError),expected;try{expected=Value3.Create(schema)}catch(error3){expected={type:"Could not create expected value",message:error3?.message,error:error3}}message=JSON.stringify({type:"validation",on:type,summary:errors[0]?.summary,property:accessor,message:error2?.message,expected,found:value,errors},null,2)}super(message);this.type=type;this.validator=validator;this.value=value;Object.setPrototypeOf(this,ValidationError.prototype)}get all(){return"Errors"in this.validator?[...this.validator.Errors(this.value)].map(mapValueError):[...Value3.Errors(this.validator,this.value)].map(mapValueError)}static simplifyModel(validator){let model="schema"in validator?validator.schema:validator;try{return Value3.Create(model)}catch{return model}}get model(){return ValidationError.simplifyModel(this.validator)}toResponse(headers){return new Response(this.message,{status:400,headers:{...headers,"content-type":"application/json"}})}}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)}};class ElysiaWS{raw;data;validator;_validator;constructor(raw,data){this.raw=raw;this.data=data;if(this.validator=raw.data.validator,raw.data.id)this.id=raw.data.id;else this.id=randomId().toString()}get id(){return this.raw.data.id}set id(newID){this.raw.data.id=newID}get publish(){return(topic,data=void 0,compress)=>{if(this.validator?.Check(data)===!1)throw new ValidationError("message",this.validator,data);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress),this}}get send(){return(data)=>{if(this.validator?.Check(data)===!1)throw new ValidationError("message",this.validator,data);if(Buffer.isBuffer(data))return this.raw.send(data),this;if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data),this}}get subscribe(){return(room)=>{return this.raw.subscribe(room),this}}get unsubscribe(){return(room)=>{return this.raw.unsubscribe(room),this}}get cork(){return(callback)=>{return this.raw.cork(callback),this}}get close(){return()=>{return this.raw.close(),this}}get terminate(){return this.raw.terminate.bind(this.raw)}get isSubscribed(){return this.raw.isSubscribed.bind(this.raw)}get remoteAddress(){return this.raw.remoteAddress}}var version="1.1.25";import{Value as Value4}from"@sinclair/typebox/value";import{TypeBoxError}from"@sinclair/typebox";var import_fast_decode_uri_component2=__toESM(require_fast_decode_uri_component(),1),plusRegex=/\+/g;function parseQueryFromURL(input){let result={};if(typeof input!=="string")return result;let key="",value="",startingIndex=-1,equalityIndex=-1,flags=0,l=input.length;for(let i=0;i<l;i++)switch(input.charCodeAt(i)){case 38:let hasBothKeyValuePair=equalityIndex>startingIndex;if(!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=import_fast_decode_uri_component2.default(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=import_fast_decode_uri_component2.default(value)||value}result[key]=value}}key="",value="",startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=8;break;case 43:if(equalityIndex>startingIndex)flags|=4;else flags|=1;break;case 37:if(equalityIndex>startingIndex)flags|=8;else flags|=2;break}if(startingIndex<l){let hasBothKeyValuePair=equalityIndex>startingIndex;if(key=input.slice(startingIndex+1,hasBothKeyValuePair?equalityIndex:l),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=import_fast_decode_uri_component2.default(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,l),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=import_fast_decode_uri_component2.default(value)||value}result[key]=value}}}return result}var parseQuery=(input)=>{let result={};if(typeof input!=="string")return result;let inputLength=input.length,key="",value="",startingIndex=-1,equalityIndex=-1,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1,hasBothKeyValuePair=!1,c=0;for(let i=0;i<inputLength+1;i++){if(i!==inputLength)c=input.charCodeAt(i);else c=38;switch(c){case 38:{if(hasBothKeyValuePair=equalityIndex>startingIndex,!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(keyHasPlus)key=key.replace(plusRegex," ");if(shouldDecodeKey)key=import_fast_decode_uri_component2.default(key)||key;if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),valueHasPlus)value=value.replace(plusRegex," ");if(shouldDecodeValue)value=import_fast_decode_uri_component2.default(value)||value}let currentValue=result[key];if(currentValue===void 0)result[key]=value;else if(currentValue.pop)currentValue.push(value);else result[key]=[currentValue,value]}value="",startingIndex=i,equalityIndex=i,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1;break}case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else shouldDecodeValue=!0;break;case 43:if(equalityIndex>startingIndex)valueHasPlus=!0;else keyHasPlus=!0;break;case 37:if(equalityIndex>startingIndex)shouldDecodeValue=!0;else shouldDecodeKey=!0;break}}return result};var import_fast_decode_uri_component3=__toESM(require_fast_decode_uri_component(),1);var ELYSIA_TRACE=Symbol("ElysiaTrace"),createProcess=()=>{let{promise,resolve}=Promise.withResolvers(),{promise:end,resolve:resolveEnd}=Promise.withResolvers(),{promise:error2,resolve:resolveError}=Promise.withResolvers(),callbacks=[],callbacksEnd=[];return[(callback)=>{if(callback)callbacks.push(callback);return promise},(process2)=>{let processes=[],resolvers=[],groupError=null;for(let i=0;i<(process2.total??0);i++){let{promise:promise2,resolve:resolve2}=Promise.withResolvers(),{promise:end2,resolve:resolveEnd2}=Promise.withResolvers(),{promise:error3,resolve:resolveError2}=Promise.withResolvers(),callbacks2=[],callbacksEnd2=[];processes.push((callback)=>{if(callback)callbacks2.push(callback);return promise2}),resolvers.push((process3)=>{let result2={...process3,end:end2,error:error3,index:i,onStop(callback){if(callback)callbacksEnd2.push(callback);return end2}};resolve2(result2);for(let i2=0;i2<callbacks2.length;i2++)callbacks2[i2](result2);return(error4=null)=>{let end3=performance.now();if(error4)groupError=error4;let detail={end:end3,error:error4,get elapsed(){return end3-process3.begin}};for(let i2=0;i2<callbacksEnd2.length;i2++)callbacksEnd2[i2](detail);resolveEnd2(end3),resolveError2(error4)}})}let result={...process2,end,error:error2,onEvent(callback){for(let i=0;i<processes.length;i++)processes[i](callback)},onStop(callback){if(callback)callbacksEnd.push(callback);return end}};resolve(result);for(let i=0;i<callbacks.length;i++)callbacks[i](result);return{resolveChild:resolvers,resolve(error3=null){let end2=performance.now();if(!error3&&groupError)error3=groupError;let detail={end:end2,error:error3,get elapsed(){return end2-process2.begin}};for(let i=0;i<callbacksEnd.length;i++)callbacksEnd[i](detail);resolveEnd(end2),resolveError(error3)}}}]},createTracer=(traceListener)=>{return(context)=>{let[onRequest,resolveRequest]=createProcess(),[onParse,resolveParse]=createProcess(),[onTransform,resolveTransform]=createProcess(),[onBeforeHandle,resolveBeforeHandle]=createProcess(),[onHandle,resolveHandle]=createProcess(),[onAfterHandle,resolveAfterHandle]=createProcess(),[onError,resolveError]=createProcess(),[onMapResponse,resolveMapResponse]=createProcess(),[onAfterResponse,resolveAfterResponse]=createProcess();return traceListener({id:context[ELYSIA_REQUEST_ID],context,set:context.set,onRequest,onParse,onTransform,onBeforeHandle,onHandle,onAfterHandle,onMapResponse,onAfterResponse,onError}),{request:resolveRequest,parse:resolveParse,transform:resolveTransform,beforeHandle:resolveBeforeHandle,handle:resolveHandle,afterHandle:resolveAfterHandle,error:resolveError,mapResponse:resolveMapResponse,afterResponse:resolveAfterResponse}}};var headersHasToJSON=new Headers().toJSON,TypeBoxSymbol={optional:Symbol.for("TypeBox.Optional"),kind:Symbol.for("TypeBox.Kind")},isOptional=(validator)=>{if(!validator)return!1;let schema=validator?.schema;return!!schema&&TypeBoxSymbol.optional in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}return!1},createReport=({context="c",trace,addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i}, reportChild${i}, reportErr${i}, reportErrChild${i}; let trace${i} = ${context}[ELYSIA_TRACE]?.[${i}] ?? trace[${i}](${context});\n`);return(event,{name,total=0}={})=>{if(!name)name="anonymous";let reporter=event==="error"?"reportErr":"report";for(let i=0;i<trace.length;i++)addFn(`\n${reporter}${i} = trace${i}.${event}({id,event: '${event}',name: '${name}',begin: performance.now(),total: ${total}})\n`);return{resolve(){for(let i=0;i<trace.length;i++)addFn(`\n${reporter}${i}.resolve()\n`)},resolveChild(name2){for(let i=0;i<trace.length;i++)addFn(`${reporter}Child${i} = ${reporter}${i}.resolveChild?.shift()?.({id,event: '${event}',name: '${name2}',begin: performance.now()})\n`);return(binding)=>{for(let i=0;i<trace.length;i++)if(binding)addFn(`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
else
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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_dist=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.parse=parse;exports.serialize=serialize;var cookieNameRegExp=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,cookieValueRegExp=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,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]*$/,__toString=Object.prototype.toString,NullObject=(()=>{let C=function(){};return C.prototype=Object.create(null),C})();function parse(str,options){let obj=new NullObject,len=str.length;if(len<2)return obj;let dec=options?.decode||decode,index=0;do{let eqIdx=str.indexOf("=",index);if(eqIdx===-1)break;let colonIdx=str.indexOf(";",index),endIdx=colonIdx===-1?len:colonIdx;if(eqIdx>endIdx){index=str.lastIndexOf(";",eqIdx-1)+1;continue}let keyStartIdx=startIndex(str,index,eqIdx),keyEndIdx=endIndex(str,eqIdx,keyStartIdx),key=str.slice(keyStartIdx,keyEndIdx);if(obj[key]===void 0){let valStartIdx=startIndex(str,eqIdx+1,endIdx),valEndIdx=endIndex(str,endIdx,valStartIdx),value=dec(str.slice(valStartIdx,valEndIdx));obj[key]=value}index=endIdx+1}while(index<len);return obj}function startIndex(str,index,max){do{let code=str.charCodeAt(index);if(code!==32&&code!==9)return index}while(++index<max);return max}function endIndex(str,index,min){while(index>min){let code=str.charCodeAt(--index);if(code!==32&&code!==9)return index+1}return min}function serialize(name,val,options){let enc=options?.encode||encodeURIComponent;if(!cookieNameRegExp.test(name))throw new TypeError(`argument name is invalid: ${name}`);let value=enc(val);if(!cookieValueRegExp.test(value))throw new TypeError(`argument val is invalid: ${val}`);let str=name+"="+value;if(!options)return str;if(options.maxAge!==void 0){if(!Number.isInteger(options.maxAge))throw new TypeError(`option maxAge is invalid: ${options.maxAge}`);str+="; Max-Age="+options.maxAge}if(options.domain){if(!domainValueRegExp.test(options.domain))throw new TypeError(`option domain is invalid: ${options.domain}`);str+="; Domain="+options.domain}if(options.path){if(!pathValueRegExp.test(options.path))throw new TypeError(`option path is invalid: ${options.path}`);str+="; Path="+options.path}if(options.expires){if(!isDate(options.expires)||!Number.isFinite(options.expires.valueOf()))throw new TypeError(`option expires is invalid: ${options.expires}`);str+="; Expires="+options.expires.toUTCString()}if(options.httpOnly)str+="; HttpOnly";if(options.secure)str+="; Secure";if(options.partitioned)str+="; Partitioned";if(options.priority)switch(typeof options.priority==="string"?options.priority.toLowerCase():options.sameSite){case"low":str+="; Priority=Low";break;case"medium":str+="; Priority=Medium";break;case"high":str+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${options.priority}`)}if(options.sameSite)switch(typeof options.sameSite==="string"?options.sameSite.toLowerCase():options.sameSite){case!0:case"strict":str+="; SameSite=Strict";break;case"lax":str+="; SameSite=Lax";break;case"none":str+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${options.sameSite}`)}return str}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 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(uri2){var percentPosition=uri2.indexOf("%");if(percentPosition===-1)return uri2;var length=uri2.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri2[percentPosition+1],4),low=hexCodeToInt(uri2[percentPosition+2],0),byte2=high|low,type=UTF8_DATA[byte2];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte2&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri2.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri2.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri2.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri2.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 U=(z,q)=>{let v=q?.length?{}:null;if(v)for(let K of q)v[K.part.charCodeAt(0)]=K;return{part:z,store:null,inert:v,params:null,wildcardStore:null}},_=(z,q)=>({...z,part:q}),$=(z)=>({name:z,store:null,inert:null});class Y{root={};history=[];static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/:.+?\?(?=\/|$)/g};add(z,q,v,{ignoreError:K=!1,ignoreHistory:V=!1}={}){if(typeof q!=="string")throw new TypeError("Route path must be a string");if(q==="")q="/";else if(q[0]!=="/")q=`/${q}`;let S=q[q.length-1]==="*",D=q.match(Y.regex.optionalParams);if(D){let F=q.replaceAll("?","");this.add(z,F,v,{ignoreError:K});for(let B=0;B<D.length;B++){let A=q.replace("/"+D[B],"");this.add(z,A,v,{ignoreError:!0})}return v}if(D)q=q.replaceAll("?","");if(this.history.find(([F,B,A])=>F===z&&B===q))return v;if(S||D&&q.charCodeAt(q.length-1)===63)q=q.slice(0,-1);if(!V)this.history.push([z,q,v]);let G=q.split(Y.regex.static),J=q.match(Y.regex.params)||[];if(G[G.length-1]==="")G.pop();let b;if(!this.root[z])b=this.root[z]=U("/");else b=this.root[z];let Q=0;for(let F=0;F<G.length;++F){let B=G[F];if(F>0){let A=J[Q++].slice(1);if(b.params===null)b.params=$(A);else if(b.params.name!==A)if(K)return v;else throw new Error(`Cannot create route "${q}" with parameter "${A}" because a route already exists with a different parameter name ("${b.params.name}") in the same location`);let O=b.params;if(O.inert===null){b=O.inert=U(B);continue}b=O.inert}for(let A=0;;){if(A===B.length){if(A<b.part.length){let O=_(b,b.part.slice(A));Object.assign(b,U(B,[O]))}break}if(A===b.part.length){if(b.inert===null)b.inert={};let O=b.inert[B.charCodeAt(A)];if(O){b=O,B=B.slice(A),A=0;continue}let X=U(B.slice(A));b.inert[B.charCodeAt(A)]=X,b=X;break}if(B[A]!==b.part[A]){let O=_(b,b.part.slice(A)),X=U(B.slice(A));Object.assign(b,U(b.part.slice(0,A),[O,X])),b=X;break}++A}}if(Q<J.length){let B=J[Q].slice(1);if(b.params===null)b.params=$(B);else if(b.params.name!==B)if(K)return v;else throw new Error(`Cannot create route "${q}" with parameter "${B}" because a route already exists with a different parameter name ("${b.params.name}") in the same location`);if(b.params.store===null)b.params.store=v;return b.params.store}if(S){if(b.wildcardStore===null)b.wildcardStore=v;return b.wildcardStore}if(b.store===null)b.store=v;return b.store}find(z,q){let v=this.root[z];if(!v)return null;return Z(q,q.length,v,0)}}var Z=(z,q,v,K)=>{let V=v.part,S=V.length,D=K+S;if(S>1){if(D>q)return null;if(S<15){for(let G=1,J=K+1;G<S;++G,++J)if(V.charCodeAt(G)!==z.charCodeAt(J))return null}else if(z.slice(K,D)!==V)return null}if(D===q){if(v.store!==null)return{store:v.store,params:{}};if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":""}};return null}if(v.inert!==null){let G=v.inert[z.charCodeAt(D)];if(G!==void 0){let J=Z(z,q,G,D);if(J!==null)return J}}if(v.params!==null){let{store:G,name:J,inert:b}=v.params,Q=z.indexOf("/",D);if(Q!==D){if(Q===-1||Q>=q){if(G!==null){let F={};return F[J]=z.substring(D,q),{store:G,params:F}}}else if(b!==null){let F=Z(z,q,b,Q);if(F!==null)return F.params[J]=z.substring(D,Q),F}}}if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":z.substring(D,q)}};return null};var hasReturn=(fn)=>{let fnLiteral=typeof fn==="object"?fn.fn.toString():typeof fn==="string"?fn.toString():fn,parenthesisEnd=fnLiteral.indexOf(")");if(fnLiteral.charCodeAt(parenthesisEnd+2)===61&&fnLiteral.charCodeAt(parenthesisEnd+5)!==123)return!0;return fnLiteral.includes("return")},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(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(`
|
|
3
|
+
`,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(`
|
|
4
|
+
`,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 newParameters=[];for(let p of parameters){if(p.indexOf(",")===-1){newParameters.push(p);continue}for(let q of p.split(","))newParameters.push(q.trim())}return parameters=newParameters,{hasParenthesis,parameters}},findParameterReference=(parameter,inference)=>{let{parameters,hasParenthesis}=retrieveRootParamters(parameter);if(!inference.query&¶meters.includes("query"))inference.query=!0;if(!inference.headers&¶meters.includes("headers"))inference.headers=!0;if(!inference.body&¶meters.includes("body"))inference.body=!0;if(!inference.cookie&¶meters.includes("cookie"))inference.cookie=!0;if(!inference.set&¶meters.includes("set"))inference.set=!0;if(!inference.server&¶meters.includes("server"))inference.server=!0;if(hasParenthesis)return`{ ${parameters.join(", ")} }`;return parameters.join(", ")},findEndIndex=(type,content,index)=>{let newLineIndex=content.indexOf(type+`
|
|
5
|
+
`,index),newTabIndex=content.indexOf(type+"\t",index),commaIndex=content.indexOf(type+",",index),semicolonIndex=content.indexOf(type+";",index),emptyIndex=content.indexOf(type+" ",index);return[newLineIndex,newTabIndex,commaIndex,semicolonIndex,emptyIndex].filter((i)=>i>0).sort((a,b)=>a-b)[0]||-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){let lastIndex=content.indexOf(" = "+type);if(lastIndex+3+type.length!==content.length)break;index=lastIndex}let part=content.slice(0,index),variable=part.slice(part.lastIndexOf(" ")+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.includes("..."))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)=>code.includes(alias+"."+type)||code.includes(alias+'["'+type+'"]')||code.includes(alias+"['"+type+"']");for(let alias of aliases){if(!alias)continue;if(alias.charCodeAt(0)===123){let parameters=retrieveRootParamters(alias).parameters;if(!inference.query&¶meters.includes("query"))inference.query=!0;if(!inference.headers&¶meters.includes("headers"))inference.headers=!0;if(!inference.body&¶meters.includes("body"))inference.body=!0;if(!inference.cookie&¶meters.includes("cookie"))inference.cookie=!0;if(!inference.set&¶meters.includes("set"))inference.set=!0;if(!inference.query&¶meters.includes("server"))inference.server=!0;continue}if(!inference.query&&access("query",alias))inference.query=!0;if(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.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server)break}return aliases};var isContextPassToFunction=(context,body,inference)=>{try{let captureFunction=new RegExp(`(?:\\w)\\((?:.*)?${context}`,"gs");captureFunction.test(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,!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}},sucrose=(lifeCycle,inference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1})=>{let events=[];if(lifeCycle.handler&&typeof lifeCycle.handler==="function")events.push(lifeCycle.handler);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);for(let e of events){if(!e)continue;let event="fn"in e?e.fn:e,[parameter,body,{isArrowReturn}]=separateFunction(event.toString()),rootParameters=findParameterReference(parameter,inference),mainParameter=extractMainParameter(rootParameters);if(mainParameter){let aliases=findAlias(mainParameter,body);if(aliases.splice(0,-1,mainParameter),!isContextPassToFunction(mainParameter,body,inference))inferBodyReference(body,aliases,inference);if(!inference.query&&body.includes("return "+mainParameter+".query"))inference.query=!0}if(inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server)break}return inference};import{Value as Value3}from"@sinclair/typebox/value";import{Kind as Kind2,TransformKind}from"@sinclair/typebox";import{Value as Value2}from"@sinclair/typebox/value";import{TypeCompiler as TypeCompiler3}from"@sinclair/typebox/compiler";import{Kind,TypeRegistry}from"@sinclair/typebox";import{TypeSystem}from"@sinclair/typebox/system";import{Type,FormatRegistry}from"@sinclair/typebox";import{TypeCompiler}from"@sinclair/typebox/compiler";import{Value}from"@sinclair/typebox/value";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 time(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 DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time=getTime(strictTimeZone);return function date_time(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}}import{TypeSystemPolicy,TypeSystem as TypeSystem2,TypeSystemDuplicateFormat,TypeSystemDuplicateTypeKind}from"@sinclair/typebox/system";import{TypeCompiler as TypeCompiler2,TypeCheck}from"@sinclair/typebox/compiler";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"))TypeSystem.Format("date",(value)=>{let temp=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"))TypeSystem.Format("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)TypeSystem.Format(formatName,(value)=>formatValue.test(value));else if(typeof formatValue==="function")TypeSystem.Format(formatName,formatValue)}});var t=Object.assign({},Type),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},validateFile=(options,value)=>{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"){if(!value.type.startsWith(options.extension))return!1}else{for(let i=0;i<options.extension.length;i++)if(value.type.startsWith(options.extension[i]))return!0;return!1}return!0},File2=TypeRegistry.Get("Files")??TypeSystem.Type("File",validateFile),Files=TypeRegistry.Get("Files")??TypeSystem.Type("Files",(options,value)=>{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});if(!FormatRegistry.Has("numeric"))FormatRegistry.Set("numeric",(value)=>!!value&&!isNaN(+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}});TypeRegistry.Set("UnionEnum",(schema,value)=>{return(typeof value==="number"||typeof value==="string"||value===null)&&schema.enum.includes(value)});var ElysiaType={Numeric:(property)=>{let schema=Type.Number(property);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&&!Value.Check(schema,number))throw new ValidationError("property",schema,number);return number}).Encode((value)=>value)},Date:(property)=>{let schema=Type.Date(property);return t.Transform(t.Union([Type.Date(property),t.String({format:"date",default:new Date().toISOString()}),t.String({format:"date-time",default:new Date().toISOString()}),t.Number()],property)).Decode((value)=>{if(typeof value==="number"){let date3=new Date(value);if(!Value.Check(schema,date3))throw new ValidationError("property",schema,date3);return date3}if(value instanceof Date)return value;let date2=new Date(value);if(!Value.Check(schema,date2))throw new ValidationError("property",schema,date2);return date2}).Encode((value)=>{if(typeof value==="string")return new Date(value);return value})},BooleanString:(property)=>{let schema=Type.Boolean(property);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&&!Value.Check(schema,value))throw new ValidationError("property",schema,value);return value}).Encode((value)=>value)},ObjectString:(properties,options)=>{let schema=t.Object(properties,options),defaultValue=JSON.stringify(Value.Create(schema)),compiler;try{compiler=TypeCompiler.Compile(schema)}catch{}return t.Transform(t.Union([t.String({format:"ObjectString",default:defaultValue}),schema])).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==123)throw new ValidationError("property",schema,value);try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(compiler){if(!compiler.Check(value))throw new ValidationError("property",schema,value);return compiler.Decode(value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return Value.Decode(schema,value)}return value}).Encode((value)=>{if(typeof value==="string")try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return JSON.stringify(value)})},ArrayString:(children={},options)=>{let schema=t.Array(children,options),defaultValue=JSON.stringify(Value.Create(schema)),compiler;try{compiler=TypeCompiler.Compile(schema)}catch{}return t.Transform(t.Union([t.String({format:"ArrayString",default:defaultValue}),schema])).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==91)throw new ValidationError("property",schema,value);try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(compiler){if(!compiler.Check(value))throw new ValidationError("property",schema,value);return compiler.Decode(value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return Value.Decode(schema,value)}return value}).Encode((value)=>{if(typeof value==="string")try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(!Value.Check(schema,value))throw new ValidationError("property",schema,value);return JSON.stringify(value)})},File:File2,Files:(options={})=>t.Transform(Files(options)).Decode((value)=>{if(Array.isArray(value))return value;return[value]}).Encode((value)=>value),Nullable:(schema)=>t.Union([schema,t.Null()]),MaybeEmpty:(schema)=>t.Union([schema,t.Null(),t.Undefined()]),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 new Error("This type does not support objects or arrays");return{default:values[0],...options,[Kind]:"UnionEnum",...type,enum:values}}};t.BooleanString=ElysiaType.BooleanString;t.ObjectString=ElysiaType.ObjectString;t.ArrayString=ElysiaType.ArrayString;t.Numeric=ElysiaType.Numeric;t.File=(arg={})=>ElysiaType.File({default:"File",...arg,extension:arg?.type,type:"string",format:"binary"});t.Files=(arg={})=>ElysiaType.Files({...arg,elysiaMeta:"Files",default:"Files",extension:arg?.type,type:"array",items:{...arg,default:"Files",type:"string",format:"binary"}});t.Nullable=(schema)=>ElysiaType.Nullable(schema);t.MaybeEmpty=ElysiaType.MaybeEmpty;t.Cookie=ElysiaType.Cookie;t.Date=ElysiaType.Date;t.UnionEnum=ElysiaType.UnionEnum;var import_cookie2=__toESM(require_dist(),1);var import_cookie=__toESM(require_dist(),1),import_fast_decode_uri_component=__toESM(require_fast_decode_uri_component(),1);class Cookie{name;jar;initial;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}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){this.setCookie.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)){let value=import_fast_decode_uri_component.default(v);if(sign===!0||sign?.includes(name)){if(!secrets)throw new Error("No secret is provided to cookie plugin");if(isStringKey){let temp=await unsignCookie(value,secrets);if(temp===!1)throw new InvalidCookieSignature(name);value=temp}else{let decoded=!0;for(let i=0;i<secrets.length;i++){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)};var hasHeaderShorthand="toJSON"in new Headers,isNotEmpty=(obj)=>{if(!obj)return!1;for(let x in obj)return!0;return!1},handleFile=(response,set2)=>{let size=response.size;if(!set2&&size||size&&set2&&set2.status!==206&&set2.status!==304&&set2.status!==412&&set2.status!==416){if(set2&&isNotEmpty(set2.headers)){if(set2.headers instanceof Headers){if(hasHeaderShorthand)set2.headers=set2.headers.toJSON();else for(let[key,value]of set2.headers.entries())if(key in set2.headers)set2.headers[key]=value}return new Response(response,{status:set2.status,headers:Object.assign({"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`},set2.headers)})}return new Response(response,{headers:{"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"}})}return new Response(response)},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},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_cookie2.serialize(key,typeof value==="object"?JSON.stringify(value):value+"",property))}if(set2.length===0)return;if(set2.length===1)return set2[0];return set2},handleStream=async(generator,set2,request)=>{let init=generator.next();if(init instanceof Promise)init=await init;if(init.done){if(set2)return mapResponse(init.value,set2,request);return mapCompactResponse(init.value,request)}return new Response(new ReadableStream({async start(controller){let end=!1;if(request?.signal.addEventListener("abort",()=>{end=!0;try{controller.close()}catch{}}),init.value!==void 0&&init.value!==null)if(typeof init.value==="object")try{controller.enqueue(Buffer.from(JSON.stringify(init.value)))}catch{controller.enqueue(Buffer.from(init.value.toString()))}else controller.enqueue(Buffer.from(init.value.toString()));for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(typeof chunk==="object")try{controller.enqueue(Buffer.from(JSON.stringify(chunk)))}catch{controller.enqueue(Buffer.from(chunk.toString()))}else controller.enqueue(Buffer.from(chunk.toString()));await new Promise((resolve)=>setTimeout(()=>resolve(),0))}try{controller.close()}catch{}}}),{...set2,headers:{"transfer-encoding":"chunked","content-type":"text/event-stream; charset=utf-8",...set2?.headers}})};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;yield decoder.decode(value)}}finally{reader.releaseLock()}}var mapResponse=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.redirect||set2.cookie){if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.redirect){if(set2.headers.Location=set2.redirect,!set2.status||set2.status<300||set2.status>=400)set2.status=302}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"]);switch(response?.constructor?.name){case"String":return new Response(response,set2);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response,set2);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse(response.response,set2,request);case"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,set2);case void 0:if(!response)return new Response("",set2);return Response.json(response,set2);case"Response":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 response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(response.status!==set2.status)set2.status=response.status;if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),set2,request);return response;case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>mapResponse(x,set2));case"Function":return mapResponse(response(),set2);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){let isCookieSet2=!1;if(set2.headers instanceof Headers)for(let key of set2.headers.keys())if(key==="set-cookie"){if(isCookieSet2)continue;isCookieSet2=!0;for(let cookie of set2.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(hasHeaderShorthand)set2.headers=response.headers.toJSON();else for(let[key,value]of response.headers.entries())if(key in set2.headers)set2.headers[key]=value;return response}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")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)}}else switch(response?.constructor?.name){case"String":return new Response(response);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse(response.response,set2,request);case"ReadableStream":return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),set2,request);return response;case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>{let r=mapCompactResponse(x,request);if(r!==void 0)return r;return new Response("")});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,set2);default:if(response instanceof Response)return response;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")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)}},mapEarlyResponse=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.redirect||set2.cookie){if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.redirect){if(set2.headers.Location=set2.redirect,!set2.status||set2.status<300||set2.status>=400)set2.status=302}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"]);switch(response?.constructor?.name){case"String":return new Response(response,set2);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response,set2);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,set2);case void 0:if(!response)return;return Response.json(response,set2);case"Response":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 response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(response.status!==set2.status)set2.status=response.status;if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),set2,request);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 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){let isCookieSet2=!1;if(set2.headers instanceof Headers)for(let key of set2.headers.keys())if(key==="set-cookie"){if(isCookieSet2)continue;isCookieSet2=!0;for(let cookie of set2.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);if(response.status!==set2.status)set2.status=response.status;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")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 new Response(response);case"Blob":return handleFile(response,set2);case"Array":return Response.json(response);case"Object":return Response.json(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case"ReadableStream":return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(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")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);case"Blob":return handleFile(response);case"Array":return Response.json(response);case"Object":return Response.json(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case"ReadableStream":return request?.signal.addEventListener("abort",{handleEvent(){if(!request?.signal.aborted)response.cancel(request)}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(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")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)=>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===0&&hooks.transform.length===0&&hooks.beforeHandle.length===0&&hooks.afterHandle.length===0)return response.clone.bind(response)},createNativeStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function"||handle instanceof Blob)return;let response=mapResponse(handle,{headers:setHeaders});if(hooks.parse.length===0&&hooks.transform.length===0&&hooks.beforeHandle.length===0&&hooks.afterHandle.length===0){if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain;charset=utf-8");return response.clone.bind(response)}};var 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().startsWith("[object ")&&v.toString()!=="[object Object]"||isNotEmpty(Object.getPrototypeOf(v)),isObject=(item)=>item&&typeof item==="object"&&!Array.isArray(item),mergeDeep=(target,source,{skipKeys,override=!0}={})=>{if(!isObject(target)||!isObject(source))return target;for(let[key,value]of Object.entries(source)){if(skipKeys?.includes(key))continue;if(!isObject(value)||!(key in target)||isClass(value)){if(override||!(key in target))target[key]=value;continue}target[key]=mergeDeep(target[key],value,{skipKeys,override})}return target},mergeCookie=(a,b)=>{let{properties:_2,...target}=a??{},{properties:__,...source}=b??{};return mergeDeep(target,source)},mergeObjectArray=(a=[],b=[])=>{if(!a)return[];if(!b)return a;let array=[],checksums=[];if(!Array.isArray(a))a=[a];if(!Array.isArray(b))b=[b];for(let item of a)if(array.push(item),item.checksum)checksums.push(item.checksum);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),{}),mergeResponse=(a,b)=>{let isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every(isNumericString);if(isRecordNumber(a)&&isRecordNumber(b))return{...a,...b};else if(a&&!isRecordNumber(a)&&isRecordNumber(b))return{200:a,...b};return b??a},mergeSchemaValidator=(a,b)=>{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)=>{return{...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(a?.beforeHandle,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)}},replaceSchemaType=(schema,options,root=!0)=>{if(!Array.isArray(options))return _replaceSchemaType(schema,options,root);for(let option of options)schema=_replaceSchemaType(schema,option,root);return schema},_replaceSchemaType=(schema,options,root=!0)=>{if(!schema)return schema;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind2];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,root);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,root);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,root);return schema}if(schema.not){for(let i=0;i<schema.not.length;i++)schema.not[i]=_replaceSchemaType(schema.not[i],options,root);return schema}let isRoot=root&&!!options.excludeRoot;if(schema[Kind2]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest),transform,composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,!1);return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,!1)};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.default=JSON.stringify(Value2.Create(t.Object(properties2))),value.properties=properties2;if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.default=JSON.stringify(Value2.Create(t.Array(items))),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,!1);return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,!1))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)for(let i=0;i<to.not.length;i++)to.not[i]=composeProperties(to.not[i]);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,!1);return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,!1))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind2]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)for(let i=0;i<to.not.length;i++)to.not[i]={...rest,...to.not[i]};properties[key]={...rest,..._replaceSchemaType(rest,options,!1)};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,!1);break;default:if(value.items)for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,!1);else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,!1);break}return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value2.Clean(schema,structuredClone(value))}catch{try{return Value2.Clean(schema,value)}catch{return value}}return value},getSchemaValidator=(s,{models={},dynamic=!1,normalize=!1,additionalProperties=!1,coerce=!1,additionalCoerce=[]}={})=>{if(!s)return;if(typeof s==="string"&&!(s in models))return;let schema=typeof s==="string"?models[s]:s;if(coerce||additionalCoerce)if(coerce)schema=replaceSchemaType(schema,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);else schema=replaceSchemaType(schema,[...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);if(schema.type==="object"&&"additionalProperties"in schema===!1)schema.additionalProperties=additionalProperties;if(dynamic){let validator={schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value2.Check(schema,value),Errors:(value)=>Value2.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value2.Decode(schema,value),Encode:(value)=>Value2.Encode(schema,value)};if(normalize&&schema.additionalProperties===!1)validator.Clean=createCleaner(schema);if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}return validator.parse=(v)=>{try{return validator.Decode(v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled=TypeCompiler3.Compile(schema,Object.values(models));if(compiled.Clean=createCleaner(schema),schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}return compiled.parse=(v)=>{try{return compiled.Decode(v)}catch(error){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},compiled},getResponseSchemaValidator=(s,{models={},dynamic=!1,normalize=!1,additionalProperties=!1})=>{if(!s)return;if(typeof s==="string"&&!(s in models))return;let maybeSchemaOrRecord=typeof s==="string"?models[s]:s,compile=(schema,references)=>{if(dynamic)return{schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value2.Check(schema,value),Errors:(value)=>Value2.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value2.Decode(schema,value),Encode:(value)=>Value2.Encode(schema,value)};let compiledValidator=TypeCompiler3.Compile(schema,references);if(normalize&&schema.additionalProperties===!1)compiledValidator.Clean=createCleaner(schema);return compiledValidator};if(Kind2 in maybeSchemaOrRecord){if("additionalProperties"in maybeSchemaOrRecord===!1)maybeSchemaOrRecord.additionalProperties=additionalProperties;return{200:compile(maybeSchemaOrRecord,Object.values(models))}}let record={};return Object.keys(maybeSchemaOrRecord).forEach((status)=>{let maybeNameOrSchema=maybeSchemaOrRecord[+status];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];schema.type==="object"&&"additionalProperties"in schema,record[+status]=Kind2 in schema?compile(schema,Object.values(models)):schema}return}if(maybeNameOrSchema.type==="object"&&"additionalProperties"in maybeNameOrSchema===!1)maybeNameOrSchema.additionalProperties=additionalProperties;record[+status]=Kind2 in maybeNameOrSchema?compile(maybeNameOrSchema,Object.values(models)):maybeNameOrSchema}),record},isBun=typeof Bun!=="undefined",hasHash=isBun&&typeof Bun.hash==="function",checksum=(s)=>{if(hasHash)return Bun.hash(s);let h=9;for(let i=0;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),387420489);return h=h^h>>>9},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,defaultConfig={},config,dynamic,models})=>{let cookieValidator=getSchemaValidator(validator,{dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions()});if(isNotEmpty(defaultConfig))if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie({}),{dynamic,models,additionalProperties:!0}),cookieValidator.config=defaultConfig;return cookieValidator},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(a.beforeHandle,injectChecksum(checksum2,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,"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(([k,v])=>[v,k]));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!=="string")throw new TypeError("Cookie value must be provided as a string.");if(secret===null)throw new 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"))},unsignCookie=async(input,secret)=>{if(typeof input!=="string")throw new TypeError("Signed cookie string must be provided.");if(secret===null)throw new TypeError("Secret key must be provided.");let tentativeValue=input.slice(0,input.lastIndexOf("."));return await signCookie(tentativeValue,secret)===input?tentativeValue:!1},traceBackMacro=(extension,property)=>{if(!extension||typeof extension!=="object"||!property)return;for(let[key,value]of Object.entries(property)){if(key in primitiveHookMap||!(key in extension))continue;let v=extension[key];if(typeof v==="function")v(value),delete property[key]}},createMacroManager=({globalHook,localHook})=>(stackName)=>(type,fn)=>{if(typeof type==="function")type={fn:type};if("fn"in type||Array.isArray(type)){if(!localHook[stackName])localHook[stackName]=[];if(typeof localHook[stackName]==="function")localHook[stackName]=[localHook[stackName]];if(Array.isArray(type))localHook[stackName]=localHook[stackName].concat(type);else localHook[stackName].push(type);return}let{insert="after",stack="local"}=type;if(typeof fn==="function")fn={fn};if(stack==="global")if(!Array.isArray(fn))if(insert==="before")globalHook[stackName].unshift(fn);else globalHook[stackName].push(fn);else if(insert==="before")globalHook[stackName]=fn.concat(globalHook[stackName]);else globalHook[stackName]=globalHook[stackName].concat(fn);else{if(!localHook[stackName])localHook[stackName]=[];if(typeof localHook[stackName]==="function")localHook[stackName]=[localHook[stackName]];if(!Array.isArray(fn))if(insert==="before")localHook[stackName].unshift(fn);else localHook[stackName].push(fn);else if(insert==="before")localHook[stackName]=fn.concat(localHook[stackName]);else localHook[stackName]=localHook[stackName].concat(fn)}},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;root=null;promises=[];constructor(onError=console.error){this.onError=onError}get size(){return this.promises.length}add(promise){return this.promises.push(promise),this.root||=this.drain(),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)=>{if(!fn)return fn;if(!Array.isArray(fn)){if(typeof fn==="function")return{fn};else if("fn"in fn)return fn}let fns=[];for(let x of fn)if(typeof x==="function")fns.push({fn:x});else if("fn"in x)fns.push(x);return fns},localHookToLifeCycleStore=(a)=>{return{...a,start:fnToContainer(a?.start),request:fnToContainer(a?.request),parse:fnToContainer(a?.parse),transform:fnToContainer(a?.transform),beforeHandle:fnToContainer(a?.beforeHandle),afterHandle:fnToContainer(a?.afterHandle),mapResponse:fnToContainer(a?.mapResponse),afterResponse:fnToContainer(a?.afterResponse),trace:fnToContainer(a?.trace),error:fnToContainer(a?.error),stop:fnToContainer(a?.stop)}},lifeCycleToFn=(a)=>{return{...a,start:a.start?.map((x)=>x.fn),request:a.request?.map((x)=>x.fn),parse:a.parse?.map((x)=>x.fn),transform:a.transform?.map((x)=>x.fn),beforeHandle:a.beforeHandle?.map((x)=>x.fn),afterHandle:a.afterHandle?.map((x)=>x.fn),afterResponse:a.afterResponse?.map((x)=>x.fn),mapResponse:a.mapResponse?.map((x)=>x.fn),trace:a.trace?.map((x)=>x.fn),error:a.error?.map((x)=>x.fn),stop:a.stop?.map((x)=>x.fn)}},cloneInference=(inference)=>({body:inference.body,cookie:inference.cookie,headers:inference.headers,query:inference.query,set:inference.set,server:inference.server}),redirect=(url,status=302)=>Response.redirect(url,status),ELYSIA_FORM_DATA=Symbol("ElysiaFormData"),ELYSIA_REQUEST_ID=Symbol("ElysiaRequestId"),form=(items)=>{let formData=new FormData;for(let[key,value]of Object.entries(items)){if(Array.isArray(value)){for(let v of value){if(value instanceof File)formData.append(key,value,value.name);formData.append(key,v)}continue}if(value instanceof File)formData.append(key,value,value.name);formData.append(key,value)}return formData},randomId=()=>crypto.getRandomValues(new Uint32Array(1))[0],deduplicateChecksum=(array)=>{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(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"};var env=typeof Bun!=="undefined"?Bun.env:typeof process!=="undefined"?process?.env:void 0,ERROR_CODE=Symbol("ElysiaErrorCode"),isProduction=(env?.NODE_ENV??env?.ENV)==="production";class ElysiaCustomStatusResponse{code;response;constructor(code,response){let res=response??(code in InvertedStatusMap?InvertedStatusMap[code]:code);this.code=StatusMap[code]??code,this.response=res}}var error=(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(){super("Failed to parse body")}}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=(error2)=>{if(!error2)return{summary:void 0};let{message,path,value,type}=error2,property=path.slice(1).replaceAll("/","."),isRoot=path==="";switch(type){case 42:return{...error2,summary:isRoot?"Value should not be provided":`Property '${property}' should not be provided`};case 45:return{...error2,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{...error2,summary:isRoot?"Value should be an email":`Property '${property}' should be ${format}`};case 54:return{...error2,summary:`${message.slice(0,9)} property '${property}' to be ${message.slice(8)} but found: ${value}`};case 62:let union=error2.schema.anyOf.map((x)=>`'${x?.format??x.type}'`).join(", ");return{...error2,summary:isRoot?`Value should be one of ${union}`:`Property '${property}' should be one of: ${union}`};default:return{summary:message,...error2}}};class ValidationError extends Error{type;validator;value;code="VALIDATION";status=422;constructor(type,validator,value){if(value&&typeof value==="object"&&value instanceof ElysiaCustomStatusResponse)value=value.response;let error2=isProduction?void 0:("Errors"in validator)?validator.Errors(value).First():Value3.Errors(validator,value).First(),customError=error2?.schema.error!==void 0?typeof error2.schema.error==="function"?error2.schema.error({type,validator,value,get errors(){return[...validator.Errors(value)].map(mapValueError)}}):error2.schema.error:void 0,accessor=error2?.path||"root",message="";if(customError!==void 0)message=typeof customError==="object"?JSON.stringify(customError):customError+"";else if(isProduction)message=JSON.stringify({type:"validation",on:type,summary:mapValueError(error2).summary,message:error2?.message,found:value});else{let schema=validator?.schema??validator,errors="Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value3.Errors(validator,value)].map(mapValueError),expected;try{expected=Value3.Create(schema)}catch(error3){expected={type:"Could not create expected value",message:error3?.message,error:error3}}message=JSON.stringify({type:"validation",on:type,summary:errors[0]?.summary,property:accessor,message:error2?.message,expected,found:value,errors},null,2)}super(message);this.type=type;this.validator=validator;this.value=value;Object.setPrototypeOf(this,ValidationError.prototype)}get all(){return"Errors"in this.validator?[...this.validator.Errors(this.value)].map(mapValueError):[...Value3.Errors(this.validator,this.value)].map(mapValueError)}static simplifyModel(validator){let model="schema"in validator?validator.schema:validator;try{return Value3.Create(model)}catch{return model}}get model(){return ValidationError.simplifyModel(this.validator)}toResponse(headers){return new Response(this.message,{status:400,headers:{...headers,"content-type":"application/json"}})}}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)}};class ElysiaWS{raw;data;validator;_validator;constructor(raw,data){this.raw=raw;this.data=data;if(this.validator=raw.data.validator,raw.data.id)this.id=raw.data.id;else this.id=randomId().toString()}get id(){return this.raw.data.id}set id(newID){this.raw.data.id=newID}get publish(){return(topic,data=void 0,compress)=>{if(this.validator?.Check(data)===!1)throw new ValidationError("message",this.validator,data);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress),this}}get send(){return(data)=>{if(this.validator?.Check(data)===!1)throw new ValidationError("message",this.validator,data);if(Buffer.isBuffer(data))return this.raw.send(data),this;if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data),this}}get subscribe(){return(room)=>{return this.raw.subscribe(room),this}}get unsubscribe(){return(room)=>{return this.raw.unsubscribe(room),this}}get cork(){return(callback)=>{return this.raw.cork(callback),this}}get close(){return()=>{return this.raw.close(),this}}get terminate(){return this.raw.terminate.bind(this.raw)}get isSubscribed(){return this.raw.isSubscribed.bind(this.raw)}get remoteAddress(){return this.raw.remoteAddress}}var version="1.1.26";import{Value as Value4}from"@sinclair/typebox/value";import{TypeBoxError}from"@sinclair/typebox";var import_fast_decode_uri_component2=__toESM(require_fast_decode_uri_component(),1),plusRegex=/\+/g;function parseQueryFromURL(input){let result={};if(typeof input!=="string")return result;let key="",value="",startingIndex=-1,equalityIndex=-1,flags=0,l=input.length;for(let i=0;i<l;i++)switch(input.charCodeAt(i)){case 38:let hasBothKeyValuePair=equalityIndex>startingIndex;if(!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=import_fast_decode_uri_component2.default(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=import_fast_decode_uri_component2.default(value)||value}result[key]=value}}key="",value="",startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=8;break;case 43:if(equalityIndex>startingIndex)flags|=4;else flags|=1;break;case 37:if(equalityIndex>startingIndex)flags|=8;else flags|=2;break}if(startingIndex<l){let hasBothKeyValuePair=equalityIndex>startingIndex;if(key=input.slice(startingIndex+1,hasBothKeyValuePair?equalityIndex:l),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=import_fast_decode_uri_component2.default(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,l),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=import_fast_decode_uri_component2.default(value)||value}result[key]=value}}}return result}var parseQuery=(input)=>{let result={};if(typeof input!=="string")return result;let inputLength=input.length,key="",value="",startingIndex=-1,equalityIndex=-1,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1,hasBothKeyValuePair=!1,c=0;for(let i=0;i<inputLength+1;i++){if(i!==inputLength)c=input.charCodeAt(i);else c=38;switch(c){case 38:{if(hasBothKeyValuePair=equalityIndex>startingIndex,!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(keyHasPlus)key=key.replace(plusRegex," ");if(shouldDecodeKey)key=import_fast_decode_uri_component2.default(key)||key;if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),valueHasPlus)value=value.replace(plusRegex," ");if(shouldDecodeValue)value=import_fast_decode_uri_component2.default(value)||value}let currentValue=result[key];if(currentValue===void 0)result[key]=value;else if(currentValue.pop)currentValue.push(value);else result[key]=[currentValue,value]}value="",startingIndex=i,equalityIndex=i,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1;break}case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else shouldDecodeValue=!0;break;case 43:if(equalityIndex>startingIndex)valueHasPlus=!0;else keyHasPlus=!0;break;case 37:if(equalityIndex>startingIndex)shouldDecodeValue=!0;else shouldDecodeKey=!0;break}}return result};var import_fast_decode_uri_component3=__toESM(require_fast_decode_uri_component(),1);var ELYSIA_TRACE=Symbol("ElysiaTrace"),createProcess=()=>{let{promise,resolve}=Promise.withResolvers(),{promise:end,resolve:resolveEnd}=Promise.withResolvers(),{promise:error2,resolve:resolveError}=Promise.withResolvers(),callbacks=[],callbacksEnd=[];return[(callback)=>{if(callback)callbacks.push(callback);return promise},(process2)=>{let processes=[],resolvers=[],groupError=null;for(let i=0;i<(process2.total??0);i++){let{promise:promise2,resolve:resolve2}=Promise.withResolvers(),{promise:end2,resolve:resolveEnd2}=Promise.withResolvers(),{promise:error3,resolve:resolveError2}=Promise.withResolvers(),callbacks2=[],callbacksEnd2=[];processes.push((callback)=>{if(callback)callbacks2.push(callback);return promise2}),resolvers.push((process3)=>{let result2={...process3,end:end2,error:error3,index:i,onStop(callback){if(callback)callbacksEnd2.push(callback);return end2}};resolve2(result2);for(let i2=0;i2<callbacks2.length;i2++)callbacks2[i2](result2);return(error4=null)=>{let end3=performance.now();if(error4)groupError=error4;let detail={end:end3,error:error4,get elapsed(){return end3-process3.begin}};for(let i2=0;i2<callbacksEnd2.length;i2++)callbacksEnd2[i2](detail);resolveEnd2(end3),resolveError2(error4)}})}let result={...process2,end,error:error2,onEvent(callback){for(let i=0;i<processes.length;i++)processes[i](callback)},onStop(callback){if(callback)callbacksEnd.push(callback);return end}};resolve(result);for(let i=0;i<callbacks.length;i++)callbacks[i](result);return{resolveChild:resolvers,resolve(error3=null){let end2=performance.now();if(!error3&&groupError)error3=groupError;let detail={end:end2,error:error3,get elapsed(){return end2-process2.begin}};for(let i=0;i<callbacksEnd.length;i++)callbacksEnd[i](detail);resolveEnd(end2),resolveError(error3)}}}]},createTracer=(traceListener)=>{return(context)=>{let[onRequest,resolveRequest]=createProcess(),[onParse,resolveParse]=createProcess(),[onTransform,resolveTransform]=createProcess(),[onBeforeHandle,resolveBeforeHandle]=createProcess(),[onHandle,resolveHandle]=createProcess(),[onAfterHandle,resolveAfterHandle]=createProcess(),[onError,resolveError]=createProcess(),[onMapResponse,resolveMapResponse]=createProcess(),[onAfterResponse,resolveAfterResponse]=createProcess();return traceListener({id:context[ELYSIA_REQUEST_ID],context,set:context.set,onRequest,onParse,onTransform,onBeforeHandle,onHandle,onAfterHandle,onMapResponse,onAfterResponse,onError}),{request:resolveRequest,parse:resolveParse,transform:resolveTransform,beforeHandle:resolveBeforeHandle,handle:resolveHandle,afterHandle:resolveAfterHandle,error:resolveError,mapResponse:resolveMapResponse,afterResponse:resolveAfterResponse}}};var headersHasToJSON=new Headers().toJSON,TypeBoxSymbol={optional:Symbol.for("TypeBox.Optional"),kind:Symbol.for("TypeBox.Kind")},isOptional=(validator)=>{if(!validator)return!1;let schema=validator?.schema;return!!schema&&TypeBoxSymbol.optional in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}return!1},createReport=({context="c",trace,addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i}, reportChild${i}, reportErr${i}, reportErrChild${i}; let trace${i} = ${context}[ELYSIA_TRACE]?.[${i}] ?? trace[${i}](${context});
|
|
6
|
+
`);return(event,{name,total=0}={})=>{if(!name)name="anonymous";let reporter=event==="error"?"reportErr":"report";for(let i=0;i<trace.length;i++)addFn(`
|
|
7
|
+
${reporter}${i} = trace${i}.${event}({id,event: '${event}',name: '${name}',begin: performance.now(),total: ${total}})
|
|
8
|
+
`);return{resolve(){for(let i=0;i<trace.length;i++)addFn(`
|
|
9
|
+
${reporter}${i}.resolve()
|
|
10
|
+
`)},resolveChild(name2){for(let i=0;i<trace.length;i++)addFn(`${reporter}Child${i} = ${reporter}${i}.resolveChild?.shift()?.({id,event: '${event}',name: '${name2}',begin: performance.now()})
|
|
11
|
+
`);return(binding)=>{for(let i=0;i<trace.length;i++)if(binding)addFn(`
|
|
12
|
+
\tif (${binding} instanceof Error)
|
|
13
|
+
\t\t\t\t${reporter}Child${i}?.(${binding})
|
|
14
|
+
\t\telse
|
|
15
|
+
\t\t${reporter}Child${i}?.()
|
|
16
|
+
`);else addFn(`${reporter}Child${i}?.()
|
|
17
|
+
`)}}}}},composeValidationFactory=({injectResponse="",normalize=!1,validator})=>({composeValidation:(type,value=`c.${type}`)=>`c.set.status = 422; throw new ValidationError('${type}', validator.${type}, ${value})`,composeResponseValidation:(name="r")=>{let code=`
|
|
18
|
+
`+injectResponse+`
|
|
19
|
+
`;code+=`if(${name} instanceof ElysiaCustomStatusResponse) {
|
|
20
|
+
\t\t\tc.set.status = ${name}.code
|
|
21
|
+
\t\t\t${name} = ${name}.response
|
|
22
|
+
\t\t}
|
|
23
|
+
|
|
24
|
+
\t\tconst isResponse = ${name} instanceof Response
|
|
25
|
+
|
|
26
|
+
`,code+=`switch(c.set.status) {
|
|
27
|
+
`;for(let[status,value]of Object.entries(validator.response)){if(code+=`\tcase ${status}:
|
|
28
|
+
\t\t\t\tif (!isResponse) {
|
|
29
|
+
`,normalize&&"Clean"in value&&!hasAdditionalProperties(value))code+=`${name} = validator.response['${status}'].Clean(${name})
|
|
30
|
+
`;code+=`if(validator.response['${status}'].Check(${name}) === false) {
|
|
31
|
+
\t\t\t\t\tc.set.status = 422
|
|
32
|
+
|
|
33
|
+
\t\t\t\t\tthrow new ValidationError('response', validator.response['${status}'], ${name})
|
|
34
|
+
\t\t\t\t}
|
|
35
|
+
|
|
36
|
+
\t\t\t\tc.set.status = ${status}
|
|
37
|
+
\t\t\t}
|
|
38
|
+
|
|
39
|
+
\t\t\tbreak
|
|
40
|
+
|
|
41
|
+
`}return code+=`
|
|
42
|
+
}
|
|
43
|
+
`,code}}),KindSymbol=Symbol.for("TypeBox.Kind");var hasProperty=(expectedProperty,schema)=>{if(!schema)return;if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},TransformSymbol=Symbol.for("TypeBox.Transform"),hasTransform=(schema)=>{if(!schema)return;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasTransform(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasTransform(property.anyOf[i]))return!0}if(TransformSymbol in property)return!0}return!1}return TransformSymbol in schema||schema.properties&&TransformSymbol in schema.properties},matchFnReturn=/(?:return|=>) \S+\(/g,isAsyncName=(v)=>{return(v?.fn??v).constructor.name==="AsyncFunction"},isAsync=(v)=>{let fn=v?.fn??v;if(fn.constructor.name==="AsyncFunction")return!0;let literal=fn.toString();if(literal.includes("=> response.clone("))return!1;if(literal.includes("await"))return!0;if(literal.includes("async"))return!0;return!!literal.match(matchFnReturn)},isGenerator=(v)=>{let fn=v?.fn??v;return fn.constructor.name==="AsyncGeneratorFunction"||fn.constructor.name==="GeneratorFunction"},composeHandler=({app,path,method,localHook,hooks,validator,handler,allowMeta=!1,inference})=>{let isHandleFn=typeof handler==="function";if(!isHandleFn){if(handler=mapResponse(handler,{headers:app.setHeaders??{}}),hooks.parse.length===0&&hooks.transform.length===0&&hooks.beforeHandle.length===0&&hooks.afterHandle.length===0)return Function("a","return function () { return a.clone() }")(handler)}let handle=isHandleFn?"handler(c)":"handler",hasAfterResponse=hooks.afterResponse.length>0,hasTrace=hooks.trace.length>0,fnLiteral="";if(inference=sucrose(Object.assign(localHook,{handler}),inference),inference.server)fnLiteral+=`
|
|
44
|
+
Object.defineProperty(c, 'server', {
|
|
45
|
+
\t\t\tget: function() { return getServer() }
|
|
46
|
+
\t\t})
|
|
47
|
+
`;if(inference.body)fnLiteral+=`let isParsing = false
|
|
48
|
+
`;validator.createBody?.(),validator.createQuery?.(),validator.createHeaders?.(),validator.createParams?.(),validator.createCookie?.(),validator.createResponse?.();let hasQuery=inference.query||!!validator.query,hasBody=method!=="$INTERNALWS"&&method!=="GET"&&method!=="HEAD"&&(inference.body||!!validator.body||hooks.parse.length),defaultHeaders=app.setHeaders,hasDefaultHeaders=defaultHeaders&&!!Object.keys(defaultHeaders).length,hasHeaders=inference.headers||validator.headers,hasCookie=inference.cookie||!!validator.cookie,cookieValidator=hasCookie?getCookieValidator({validator:validator.cookie,defaultConfig:app.config.cookie,dynamic:!!app.config.aot,config:validator.cookie?.config??{},models:app.definitions.type}):void 0,cookieMeta=cookieValidator?.config,encodeCookie="";if(cookieMeta?.sign){if(!cookieMeta.secrets)throw new Error(`t.Cookie required secret which is not set in (${method}) ${path}.`);let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(encodeCookie+=`const _setCookie = c.set.cookie
|
|
49
|
+
\t\tif(_setCookie) {`,cookieMeta.sign===!0)encodeCookie+=`for(const [key, cookie] of Object.entries(_setCookie)) {
|
|
50
|
+
\t\t\t\tc.set.cookie[key].value = await signCookie(cookie.value, '${secret}')
|
|
51
|
+
\t\t\t}`;else for(let name of cookieMeta.sign)encodeCookie+=`if(_setCookie['${name}']?.value) { c.set.cookie['${name}'].value = await signCookie(_setCookie['${name}'].value, '${secret}') }
|
|
52
|
+
`;encodeCookie+=`}
|
|
53
|
+
`}let normalize=app.config.normalize,{composeValidation,composeResponseValidation}=composeValidationFactory({normalize,validator});if(hasHeaders)fnLiteral+=headersHasToJSON?`c.headers = c.request.headers.toJSON()
|
|
54
|
+
`:`c.headers = {}
|
|
27
55
|
for (const [key, value] of c.request.headers.entries())
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
56
|
+
\t\t\t\t\tc.headers[key] = value
|
|
57
|
+
\t\t\t\t`;if(hasCookie){let get=(name,defaultValue)=>{let value=cookieMeta?.[name]??defaultValue;if(!value)return typeof defaultValue==="string"?`${name}: "${defaultValue}",`:`${name}: ${defaultValue},`;if(typeof value==="string")return`${name}: '${value}',`;if(value instanceof Date)return`${name}: new Date(${value.getTime()}),`;return`${name}: ${value},`},options=cookieMeta?`{
|
|
58
|
+
\t\t\tsecrets: ${cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?`'${cookieMeta.secrets}'`:"["+cookieMeta.secrets.reduce((a,b)=>a+`'${b}',`,"")+"]":"undefined"},
|
|
59
|
+
\t\t\tsign: ${cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?"["+cookieMeta.sign.reduce((a,b)=>a+`'${b}',`,"")+"]":"undefined"},
|
|
60
|
+
\t\t\t${get("domain")}
|
|
61
|
+
\t\t\t${get("expires")}
|
|
62
|
+
\t\t\t${get("httpOnly")}
|
|
63
|
+
\t\t\t${get("maxAge")}
|
|
64
|
+
\t\t\t${get("path","/")}
|
|
65
|
+
\t\t\t${get("priority")}
|
|
66
|
+
\t\t\t${get("sameSite")}
|
|
67
|
+
\t\t\t${get("secure")}
|
|
68
|
+
\t\t}`:"undefined";if(hasHeaders)fnLiteral+=`
|
|
69
|
+
c.cookie = await parseCookie(c.set, c.headers.cookie, ${options})
|
|
70
|
+
`;else fnLiteral+=`
|
|
71
|
+
c.cookie = await parseCookie(c.set, c.request.headers.get('cookie'), ${options})
|
|
72
|
+
`}if(hasQuery){let destructured=[];if(validator.query&&validator.query.schema.type==="object"){let properties=validator.query.schema.properties;if(!hasAdditionalProperties(validator.query))for(let[key,_value]of Object.entries(properties)){let value=_value;if(value&&TypeBoxSymbol.optional in value&&value.type==="array"&&value.items)value=value.items;let{type,anyOf}=value,isArray=type==="array"||anyOf?.some((v)=>v.type==="string"&&v.format==="ArrayString");destructured.push({key,isArray,isNestedObjectArray:isArray&&value.items?.type==="object"||!!value.items?.anyOf?.some((x)=>x.type==="object"||x.type==="array"),isObject:type==="object"||anyOf?.some((v)=>v.type==="string"&&v.format==="ArrayString"),anyOf:!!anyOf})}}if(!destructured.length)fnLiteral+=`if(c.qi === -1) {
|
|
73
|
+
\t\t\t\tc.query = {}
|
|
74
|
+
\t\t\t} else {
|
|
75
|
+
\t\t\t\tc.query = parseQueryFromURL(c.url.slice(c.qi + 1))
|
|
76
|
+
\t\t\t}`;else fnLiteral+=`if(c.qi !== -1) {
|
|
77
|
+
\t\t\t\tlet url = '&' + decodeURIComponent(c.url.slice(c.qi + 1))
|
|
78
|
+
|
|
79
|
+
\t\t\t\t${destructured.map(({key,isArray,isObject:isObject2,isNestedObjectArray,anyOf},index)=>{let init=`${index===0?"let":""} memory = url.indexOf('&${key}=')
|
|
80
|
+
\t\t\t\t\t\t\tlet a${index}
|
|
81
|
+
`;if(isArray)return init+(isNestedObjectArray?`while (memory !== -1) {
|
|
82
|
+
\t\t\t\t\t\t\t\t\t\t\tconst start = memory + ${key.length+2}
|
|
83
|
+
\t\t\t\t\t\t\t\t\t\t\tmemory = url.indexOf('&', start)
|
|
84
|
+
|
|
85
|
+
\t\t\t\t\t\t\t\t\t\t\tif(a${index} === undefined)
|
|
86
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index} = ''
|
|
87
|
+
\t\t\t\t\t\t\t\t\t\t\telse
|
|
88
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index} += ','
|
|
89
|
+
|
|
90
|
+
\t\t\t\t\t\t\t\t\t\t\tlet temp
|
|
91
|
+
|
|
92
|
+
\t\t\t\t\t\t\t\t\t\t\tif(memory === -1) temp = url.slice(start).replace(/\\+|%20/g, ' ')
|
|
93
|
+
\t\t\t\t\t\t\t\t\t\t\telse temp = url.slice(start, memory).replace(/\\+|%20/g, ' ')
|
|
94
|
+
|
|
95
|
+
\t\t\t\t\t\t\t\t\t\t\tconst charCode = temp.charCodeAt(0)
|
|
96
|
+
\t\t\t\t\t\t\t\t\t\t\tif(charCode !== 91 && charCode !== 123)
|
|
97
|
+
\t\t\t\t\t\t\t\t\t\t\t\ttemp = '"' + temp + '"'
|
|
98
|
+
|
|
99
|
+
\t\t\t\t\t\t\t\t\t\t\ta${index} += temp
|
|
100
|
+
|
|
101
|
+
\t\t\t\t\t\t\t\t\t\t\tif(memory === -1) break
|
|
102
|
+
|
|
103
|
+
\t\t\t\t\t\t\t\t\t\t\tmemory = url.indexOf('&${key}=', memory)
|
|
104
|
+
\t\t\t\t\t\t\t\t\t\t\tif(memory === -1) break
|
|
105
|
+
\t\t\t\t\t\t\t\t\t\t}
|
|
106
|
+
|
|
107
|
+
\t\t\t\t\t\t\t\t\t\ttry {
|
|
108
|
+
\t\t\t\t\t\t\t\t\t\t if(a${index}.charCodeAt(0) === 91)
|
|
109
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index} = JSON.parse(a${index})
|
|
110
|
+
\t\t\t\t\t\t\t\t\t\t\telse
|
|
111
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index} = JSON.parse('[' + a${index} + ']')
|
|
112
|
+
\t\t\t\t\t\t\t\t\t\t} catch {}
|
|
113
|
+
`:`while (memory !== -1) {
|
|
114
|
+
\t\t\t\t\t\t\t\t\t\t\tconst start = memory + ${key.length+2}
|
|
115
|
+
\t\t\t\t\t\t\t\t\t\t\tmemory = url.indexOf('&', start)
|
|
116
|
+
|
|
117
|
+
\t\t\t\t\t\t\t\t\t\t\tif(a${index} === undefined)
|
|
118
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index} = []
|
|
119
|
+
|
|
120
|
+
\t\t\t\t\t\t\t\t\t\t\tif(memory === -1) {
|
|
121
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index}.push(url.slice(start).replace(/\\+|%20/g, ' '))
|
|
122
|
+
\t\t\t\t\t\t\t\t\t\t\t\tbreak
|
|
123
|
+
\t\t\t\t\t\t\t\t\t\t\t}
|
|
124
|
+
\t\t\t\t\t\t\t\t\t\t\telse a${index}.push(url.slice(start, memory).replace(/\\+|%20/g, ' '))
|
|
125
|
+
|
|
126
|
+
\t\t\t\t\t\t\t\t\t\t\tmemory = url.indexOf('&${key}=', memory)
|
|
127
|
+
\t\t\t\t\t\t\t\t\t\t\tif(memory === -1) break
|
|
128
|
+
\t\t\t\t\t\t\t\t\t\t}
|
|
129
|
+
`);if(isObject2)return init+`if (memory !== -1) {
|
|
130
|
+
\t\t\t\t\t\t\t\t\t\tconst start = memory + ${key.length+2}
|
|
131
|
+
\t\t\t\t\t\t\t\t\t\tmemory = url.indexOf('&', start)
|
|
132
|
+
|
|
133
|
+
\t\t\t\t\t\t\t\t\t\tif(memory === -1) a${index} = url.slice(start).replace(/\\+|%20/g, ' ')
|
|
134
|
+
\t\t\t\t\t\t\t\t\t\telse a${index} = url.slice(start, memory).replace(/\\+|%20/g, ' ')
|
|
135
|
+
|
|
136
|
+
\t\t\t\t\t\t\t\t\t\tif (a${index} !== undefined) {
|
|
137
|
+
\t\t\t\t\t\t\t\t\t\t\ttry {
|
|
138
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index} = JSON.parse(a${index})
|
|
139
|
+
\t\t\t\t\t\t\t\t\t\t\t} catch {}
|
|
140
|
+
\t\t\t\t\t\t\t\t\t\t}
|
|
141
|
+
\t\t\t\t\t\t\t\t\t}`;return init+`if (memory !== -1) {
|
|
142
|
+
\t\t\t\t\t\t\t\t\t\tconst start = memory + ${key.length+2}
|
|
143
|
+
\t\t\t\t\t\t\t\t\t\tmemory = url.indexOf('&', start)
|
|
144
|
+
|
|
145
|
+
\t\t\t\t\t\t\t\t\t\tif(memory === -1) a${index} = url.slice(start).replace(/\\+|%20/g, ' ')
|
|
146
|
+
\t\t\t\t\t\t\t\t\t\telse {
|
|
147
|
+
\t\t\t\t\t\t\t\t\t\t\ta${index} = url.slice(start, memory).replace(/\\+|%20/g, ' ')
|
|
148
|
+
|
|
149
|
+
\t\t\t\t\t\t\t\t\t\t\t${anyOf?`
|
|
150
|
+
\t\t\t\t\t\t\t\t\t\t\tlet deepMemory = url.indexOf('&${key}=', memory)
|
|
151
|
+
|
|
152
|
+
\t\t\t\t\t\t\t\t\t\t\tif(deepMemory !== -1) {
|
|
153
|
+
\t\t\t\t\t\t\t\t\t\t\t\ta${index} = [a${index}]
|
|
154
|
+
\t\t\t\t\t\t\t\t\t\t\t\tlet first = true
|
|
155
|
+
|
|
156
|
+
\t\t\t\t\t\t\t\t\t\t\t\twhile(true) {
|
|
157
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tconst start = deepMemory + ${key.length+2}
|
|
158
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tif(first)
|
|
159
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\t\tfirst = false
|
|
160
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\telse
|
|
161
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeepMemory = url.indexOf('&', start)
|
|
162
|
+
|
|
163
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tlet value
|
|
164
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tif(deepMemory === -1) value = url.slice(start).replace(/\\+|%20/g, ' ')
|
|
165
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\telse value = url.slice(start, deepMemory).replace(/\\+|%20/g, ' ')
|
|
166
|
+
|
|
167
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tconst vStart = value.charCodeAt(0)
|
|
168
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tconst vEnd = value.charCodeAt(value.length - 1)
|
|
169
|
+
|
|
170
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tif((vStart === 91 && vEnd === 93) || (vStart === 123 && vEnd === 125))
|
|
171
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry {
|
|
172
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta${index}.push(JSON.parse(value))
|
|
173
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\t\t} catch {
|
|
174
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\t\t \ta${index}.push(value)
|
|
175
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\t\t}
|
|
176
|
+
|
|
177
|
+
\t\t\t\t\t\t\t\t\t\t\t\t\tif(deepMemory === -1) break
|
|
178
|
+
\t\t\t\t\t\t\t\t\t\t\t\t}
|
|
179
|
+
\t\t\t\t\t\t\t\t\t\t\t}
|
|
180
|
+
\t\t\t\t\t\t\t\t\t\t\t\t`:""}
|
|
181
|
+
\t\t\t\t\t\t\t\t\t\t}
|
|
182
|
+
\t\t\t\t\t\t\t\t\t}`}).join(`
|
|
183
|
+
`)}
|
|
184
|
+
|
|
185
|
+
\t\t\t\tc.query = {
|
|
186
|
+
\t\t\t\t\t${destructured.map(({key},index)=>`'${key}': a${index}`).join(", ")}
|
|
187
|
+
\t\t\t\t}
|
|
188
|
+
\t\t\t} else {
|
|
189
|
+
\t\t\t\tc.query = {}
|
|
190
|
+
\t\t\t}`}if(hasTrace)fnLiteral+=`
|
|
191
|
+
const id = c[ELYSIA_REQUEST_ID]
|
|
192
|
+
`;let report=createReport({trace:hooks.trace,addFn:(word)=>{fnLiteral+=word}});fnLiteral+=`
|
|
193
|
+
try {
|
|
194
|
+
`;let isAsyncHandler=typeof handler==="function"&&isAsync(handler),saveResponse=hasTrace||hooks.afterResponse.length>0?"c.response = ":"",maybeAsync=hasCookie||hasBody||isAsyncHandler||hooks.parse.length>0||hooks.afterHandle.some(isAsync)||hooks.beforeHandle.some(isAsync)||hooks.transform.some(isAsync)||hooks.mapResponse.some(isAsync),maybeStream=(typeof handler==="function"?isGenerator(handler):!1)||hooks.beforeHandle.some(isGenerator)||hooks.afterHandle.some(isGenerator)||hooks.transform.some(isGenerator),hasSet=inference.cookie||inference.set||hasHeaders||hasTrace||validator.response||isHandleFn&&hasDefaultHeaders||maybeStream,requestMapper=", c.request";fnLiteral+=`c.route = \`${path}\`
|
|
195
|
+
`;let parseReporter=report("parse",{total:hooks.parse.length});if(hasBody){let hasBodyInference=hooks.parse.length||inference.body||validator.body;if(fnLiteral+=`isParsing = true
|
|
196
|
+
`,hooks.type&&!hooks.parse.length)switch(hooks.type){case"json":case"application/json":if(isOptional(validator.body))fnLiteral+="try { c.body = await c.request.json() } catch {}";else fnLiteral+="c.body = await c.request.json()";break;case"text":case"text/plain":fnLiteral+=`c.body = await c.request.text()
|
|
197
|
+
`;break;case"urlencoded":case"application/x-www-form-urlencoded":fnLiteral+=`c.body = parseQuery(await c.request.text())
|
|
198
|
+
`;break;case"arrayBuffer":case"application/octet-stream":fnLiteral+=`c.body = await c.request.arrayBuffer()
|
|
199
|
+
`;break;case"formdata":case"multipart/form-data":if(fnLiteral+=`c.body = {}
|
|
200
|
+
`,isOptional(validator.body))fnLiteral+="let form; try { form = await c.request.formData() } catch {}";else fnLiteral+="const form = await c.request.formData()";fnLiteral+=`
|
|
201
|
+
if(form)
|
|
202
|
+
\t\t\t\t\t\tfor (const key of form.keys()) {
|
|
203
|
+
\t\t\t\t\t\t\tif (c.body[key])
|
|
204
|
+
\t\t\t\t\t\t\t\tcontinue
|
|
205
|
+
|
|
206
|
+
\t\t\t\t\t\t\tconst value = form.getAll(key)
|
|
207
|
+
\t\t\t\t\t\t\tif (value.length === 1)
|
|
208
|
+
\t\t\t\t\t\t\t\tc.body[key] = value[0]
|
|
209
|
+
\t\t\t\t\t\t\telse c.body[key] = value
|
|
210
|
+
\t\t\t\t\t\t} else form = {}
|
|
211
|
+
`;break}else if(hasBodyInference){if(fnLiteral+=`
|
|
212
|
+
`,fnLiteral+=hasHeaders?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')",fnLiteral+=`
|
|
213
|
+
\t\t\t\tif (contentType) {
|
|
214
|
+
\t\t\t\t\tconst index = contentType.indexOf(';')
|
|
215
|
+
\t\t\t\t\tif (index !== -1) contentType = contentType.substring(0, index)
|
|
216
|
+
|
|
217
|
+
\t\t\t\t\tc.contentType = contentType
|
|
218
|
+
`,hooks.parse.length){fnLiteral+=`let used = false
|
|
219
|
+
`;let reporter=report("parse",{total:hooks.parse.length});for(let i=0;i<hooks.parse.length;i++){let endUnit=reporter.resolveChild(hooks.parse[i].fn.name),name=`bo${i}`;if(i!==0)fnLiteral+=`if(!used) {
|
|
220
|
+
`;if(fnLiteral+=`let ${name} = parse[${i}](c, contentType)
|
|
221
|
+
`,fnLiteral+=`if(${name} instanceof Promise) ${name} = await ${name}
|
|
222
|
+
`,fnLiteral+=`if(${name} !== undefined) { c.body = ${name}; used = true }
|
|
223
|
+
`,endUnit(),i!==0)fnLiteral+="}"}reporter.resolve()}if(fnLiteral+=`
|
|
224
|
+
delete c.contentType
|
|
225
|
+
`,hooks.parse.length)fnLiteral+="if (!used) {";if(hooks.type&&!Array.isArray(hooks.type))switch(hooks.type){case"json":case"application/json":if(isOptional(validator.body))fnLiteral+="try { c.body = await c.request.json() } catch {}";else fnLiteral+="c.body = await c.request.json()";break;case"text":case"text/plain":fnLiteral+=`c.body = await c.request.text()
|
|
226
|
+
`;break;case"urlencoded":case"application/x-www-form-urlencoded":fnLiteral+=`c.body = parseQuery(await c.request.text())
|
|
227
|
+
`;break;case"arrayBuffer":case"application/octet-stream":fnLiteral+=`c.body = await c.request.arrayBuffer()
|
|
228
|
+
`;break;case"formdata":case"multipart/form-data":fnLiteral+=`c.body = {}
|
|
229
|
+
|
|
230
|
+
\t\t\t\t\t\t\tconst form = await c.request.formData()
|
|
231
|
+
\t\t\t\t\t\t\tfor (const key of form.keys()) {
|
|
232
|
+
\t\t\t\t\t\t\t\tif (c.body[key])
|
|
233
|
+
\t\t\t\t\t\t\t\t\tcontinue
|
|
234
|
+
|
|
235
|
+
\t\t\t\t\t\t\t\tconst value = form.getAll(key)
|
|
236
|
+
\t\t\t\t\t\t\t\tif (value.length === 1)
|
|
237
|
+
\t\t\t\t\t\t\t\t\tc.body[key] = value[0]
|
|
238
|
+
\t\t\t\t\t\t\t\telse c.body[key] = value
|
|
239
|
+
\t\t\t\t\t\t\t}
|
|
240
|
+
`;break}else fnLiteral+=`
|
|
241
|
+
\t\t\t\t\tswitch (contentType) {
|
|
242
|
+
\t\t\t\t\t\tcase 'application/json':
|
|
243
|
+
\t\t\t\t\t\t\t${isOptional(validator.body)?"try { c.body = await c.request.json() } catch {}":"c.body = await c.request.json()"}
|
|
244
|
+
\t\t\t\t\t\t\tbreak
|
|
245
|
+
|
|
246
|
+
\t\t\t\t\t\tcase 'text/plain':
|
|
247
|
+
\t\t\t\t\t\t\tc.body = await c.request.text()
|
|
248
|
+
\t\t\t\t\t\t\tbreak
|
|
249
|
+
|
|
250
|
+
\t\t\t\t\t\tcase 'application/x-www-form-urlencoded':
|
|
251
|
+
\t\t\t\t\t\t\tc.body = parseQuery(await c.request.text())
|
|
252
|
+
\t\t\t\t\t\t\tbreak
|
|
253
|
+
|
|
254
|
+
\t\t\t\t\t\tcase 'application/octet-stream':
|
|
255
|
+
\t\t\t\t\t\t\tc.body = await c.request.arrayBuffer();
|
|
256
|
+
\t\t\t\t\t\t\tbreak
|
|
257
|
+
|
|
258
|
+
\t\t\t\t\t\tcase 'multipart/form-data':
|
|
259
|
+
\t\t\t\t\t\t\tc.body = {}
|
|
260
|
+
|
|
261
|
+
\t\t\t\t\t\t\tconst form = await c.request.formData()
|
|
262
|
+
\t\t\t\t\t\t\tfor (const key of form.keys()) {
|
|
263
|
+
\t\t\t\t\t\t\t\tif (c.body[key])
|
|
264
|
+
\t\t\t\t\t\t\t\t\tcontinue
|
|
265
|
+
|
|
266
|
+
\t\t\t\t\t\t\t\tconst value = form.getAll(key)
|
|
267
|
+
\t\t\t\t\t\t\t\tif (value.length === 1)
|
|
268
|
+
\t\t\t\t\t\t\t\t\tc.body[key] = value[0]
|
|
269
|
+
\t\t\t\t\t\t\t\telse c.body[key] = value
|
|
270
|
+
\t\t\t\t\t\t\t}
|
|
271
|
+
|
|
272
|
+
\t\t\t\t\t\t\tbreak
|
|
273
|
+
\t\t\t\t\t}`;if(hooks.parse.length)fnLiteral+="}";fnLiteral+=`}
|
|
274
|
+
`}fnLiteral+=`
|
|
275
|
+
isParsing = false
|
|
276
|
+
`}if(parseReporter.resolve(),hooks?.transform){let reporter=report("transform",{total:hooks.transform.length});if(hooks.transform.length)fnLiteral+=`
|
|
277
|
+
let transformed
|
|
278
|
+
`;for(let i=0;i<hooks.transform.length;i++){let transform=hooks.transform[i],endUnit=reporter.resolveChild(transform.fn.name);if(fnLiteral+=isAsync(transform)?`transformed = await transform[${i}](c)
|
|
279
|
+
`:`transformed = transform[${i}](c)
|
|
280
|
+
`,transform.subType==="mapDerive")fnLiteral+=`if(transformed instanceof ElysiaCustomStatusResponse)
|
|
281
|
+
\t\t\t\t\tthrow transformed
|
|
282
|
+
\t\t\t\telse {
|
|
283
|
+
\t\t\t\t\ttransformed.request = c.request
|
|
284
|
+
\t\t\t\t\ttransformed.store = c.store
|
|
285
|
+
\t\t\t\t\ttransformed.qi = c.qi
|
|
286
|
+
\t\t\t\t\ttransformed.path = c.path
|
|
287
|
+
\t\t\t\t\ttransformed.url = c.url
|
|
288
|
+
\t\t\t\t\ttransformed.redirect = c.redirect
|
|
289
|
+
\t\t\t\t\ttransformed.set = c.set
|
|
290
|
+
\t\t\t\t\ttransformed.error = c.error
|
|
291
|
+
|
|
292
|
+
\t\t\t\t\tc = transformed
|
|
293
|
+
\t\t\t}`;else fnLiteral+=`if(transformed instanceof ElysiaCustomStatusResponse)
|
|
294
|
+
\t\t\t\t\tthrow transformed
|
|
295
|
+
\t\t\t\telse
|
|
296
|
+
\t\t\t\t\tObject.assign(c, transformed)
|
|
297
|
+
`;endUnit()}reporter.resolve()}if(validator){if(fnLiteral+=`
|
|
298
|
+
`,validator.headers){if(normalize&&"Clean"in validator.headers&&!hasAdditionalProperties(validator.headers))fnLiteral+=`c.headers = validator.headers.Clean(c.headers);
|
|
299
|
+
`;if(hasProperty("default",validator.headers.schema))for(let[key,value]of Object.entries(Value4.Default(validator.headers.schema,{}))){let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(parsed!==void 0)fnLiteral+=`c.headers['${key}'] ??= ${parsed}
|
|
300
|
+
`}if(isOptional(validator.headers))fnLiteral+="if(isNotEmpty(c.headers)) {";if(fnLiteral+=`if(validator.headers.Check(c.headers) === false) {
|
|
301
|
+
\t\t\t\t${composeValidation("headers")}
|
|
302
|
+
\t\t\t}`,hasTransform(validator.headers.schema))fnLiteral+=`c.headers = validator.headers.Decode(c.headers)
|
|
303
|
+
`;if(isOptional(validator.headers))fnLiteral+="}"}if(validator.params){if(hasProperty("default",validator.params.schema))for(let[key,value]of Object.entries(Value4.Default(validator.params.schema,{}))){let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(parsed!==void 0)fnLiteral+=`c.params['${key}'] ??= ${parsed}
|
|
304
|
+
`}if(fnLiteral+=`if(validator.params.Check(c.params) === false) {
|
|
305
|
+
\t\t\t\t${composeValidation("params")}
|
|
306
|
+
\t\t\t}`,hasTransform(validator.params.schema))fnLiteral+=`
|
|
307
|
+
c.params = validator.params.Decode(c.params)
|
|
308
|
+
`}if(validator.query){if(normalize&&"Clean"in validator.query&&!hasAdditionalProperties(validator.query))fnLiteral+=`c.query = validator.query.Clean(c.query);
|
|
309
|
+
`;if(hasProperty("default",validator.query.schema))for(let[key,value]of Object.entries(Value4.Default(validator.query.schema,{}))){let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(parsed!==void 0)fnLiteral+=`if(c.query['${key}'] === undefined) c.query['${key}'] = ${parsed}
|
|
310
|
+
`}if(isOptional(validator.query))fnLiteral+="if(isNotEmpty(c.query)) {";if(fnLiteral+=`if(validator.query.Check(c.query) === false) {
|
|
311
|
+
\t\t${composeValidation("query")}
|
|
312
|
+
\t\t\t}`,hasTransform(validator.query.schema))fnLiteral+=`
|
|
313
|
+
c.query = validator.query.Decode(Object.assign({}, c.query))
|
|
314
|
+
`;if(isOptional(validator.query))fnLiteral+="}"}if(validator.body){if(normalize&&"Clean"in validator.body&&!hasAdditionalProperties(validator.body))fnLiteral+=`c.body = validator.body.Clean(c.body);
|
|
315
|
+
`;let doesHaveTransform=hasTransform(validator.body.schema);if(doesHaveTransform||isOptional(validator.body))fnLiteral+=`
|
|
316
|
+
const isNotEmptyObject = c.body && (typeof c.body === "object" && isNotEmpty(c.body))
|
|
317
|
+
`;if(hasProperty("default",validator.body.schema)){let value=Value4.Default(validator.body.schema,validator.body.schema.type==="object"?{}:void 0),parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(fnLiteral+=`if(validator.body.Check(c.body) === false) {
|
|
318
|
+
\t\t\t\t\tif (typeof c.body === 'object') {
|
|
319
|
+
\t\t\t\t\t\tc.body = Object.assign(${parsed}, c.body)
|
|
320
|
+
\t\t\t\t\t} else { c.body = ${parsed} }`,isOptional(validator.body))fnLiteral+=`
|
|
321
|
+
\t\t\t\t\t if(isNotEmptyObject && validator.body.Check(c.body) === false) {
|
|
322
|
+
\t\t\t\t${composeValidation("body")}
|
|
323
|
+
\t\t\t}
|
|
240
324
|
}`;else fnLiteral+=`
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
325
|
+
\t\t\t\tif(validator.body.Check(c.body) === false) {
|
|
326
|
+
\t\t\t\t${composeValidation("body")}
|
|
327
|
+
\t\t\t}
|
|
244
328
|
}`}else if(isOptional(validator.body))fnLiteral+=`if(isNotEmptyObject && validator.body.Check(c.body) === false) {
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
error = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i}](context)\n`,endUnit()}return mapResponseReporter.resolve(),fnLiteral+=`\nreturn mapResponse(${saveResponse} error, set, context.request)\n}\n}`,Function("inject",fnLiteral)({app,mapResponse,ERROR_CODE,ElysiaCustomStatusResponse,ELYSIA_TRACE,ELYSIA_REQUEST_ID})};import{TransformDecodeError}from"@sinclair/typebox/value";var createDynamicHandler=(app)=>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:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,redirect});try{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=mapEarlyResponse(response2,set2),response2)return context.response=response2}let handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find("ALL",path);if(!handler)throw new NotFoundError;let{handle,hooks,validator,content}=handler.store,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=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);context.contentType=contentType;for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn,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.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQueryFromURL(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta=Object.assign({},app.config?.cookie,validator?.cookie?.config),cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta?{secrets:cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets.join(","):void 0,sign:cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?typeof cookieMeta.sign==="string"?cookieMeta.sign:cookieMeta.sign.join(","):void 0}:void 0);for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],operation=hook.fn(context);if(hook.subType==="derive")if(operation instanceof Promise)Object.assign(context,await operation);else Object.assign(context,operation);else if(operation instanceof Promise)await operation}if(validator){if(validator.createHeaders?.()){let _header={};for(let key in request.headers)_header[key]=request.headers.get(key);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(validator.createParams?.()?.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.createQuery?.()?.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)}for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(hook.subType==="resolve"){if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse(response2,context.set);if(result)return context.response=result}if(response2 instanceof Promise)Object.assign(context,await response2);else Object.assign(context,response2);continue}else if(response2 instanceof Promise)response2=await response2;if(response2!==void 0){context.response=response2;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=mapEarlyResponse(response2,context.set);if(result)return context.response=result}}let response=handle(context);if(response instanceof Promise)response=await response;if(!hooks.afterHandle.length){let status=response instanceof ElysiaCustomStatusResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200,responseValidator=validator?.createResponse?.()?.[status];if(responseValidator?.Check(response)===!1)throw new ValidationError("response",responseValidator,response);else if(responseValidator?.Decode)response=responseValidator.Decode(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let newResponse=hooks.afterHandle[i].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;let result=mapEarlyResponse(newResponse,context.set);if(result!==void 0){let responseValidator=validator?.response?.[result.status];if(responseValidator?.Check(result)===!1)throw new ValidationError("response",responseValidator,result);else if(responseValidator?.Decode)response=responseValidator.Decode(response);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)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;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 context.response=mapResponse(response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;if(reportedError.status)set2.status=reportedError.status;return app.handleError(context,reportedError)}finally{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)}},createDynamicErrorHandler=(app)=>async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});errorContext.set=context.set;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=mapResponse(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};_routes={};_types={Prefix:"",Scoped:!1,Singleton:{},Definitions:{},Metadata:{}};_ephemeral={};_volatile={};static version=version;version=version;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}get _scoped(){return this.config.scoped}definitions={type:{},error:{}};extender={macros:[],higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],mapResponse:[],afterResponse:[],trace:[],error:[],stop:[]};telemetry={stack:void 0};router={http:new Y,ws:new Y,dynamic:new Y,static:{http:{static:{},handlers:[],map:{},all:""},ws:{}},history:[]};routeTree=new Map;get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1};getServer(){return this.server}_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup;return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(config.nativeStaticResponse===void 0)config.nativeStaticResponse=!0;if(this.config={},this.applyConfig(config??{}),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry.stack=new Error().stack}env(model,env2=Bun?.env??process.env){if(getSchemaValidator(model,{dynamic:!0,additionalProperties:!0,coerce:!0}).Check(env2)===!1){let error2=new ValidationError("env",model,env2);throw new Error(error2.all.map((x)=>x.summary).join("\n"))}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}applyMacro(localHook){if(this.extender.macros.length){let manage=createMacroManager({globalHook:this.event,localHook}),manager={events:{global:this.event,local:localHook},onParse:manage("parse"),onTransform:manage("transform"),onBeforeHandle:manage("beforeHandle"),onAfterHandle:manage("afterHandle"),mapResponse:manage("mapResponse"),onAfterResponse:manage("afterResponse"),onError:manage("error")};for(let macro of this.extender.macros)traceBackMacro(macro.fn(manager),localHook)}}applyConfig(config){return this.config={prefix:"",aot:!0,strictPath:!1,global:!1,analytic:!1,normalize:!0,...config,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this}get models(){let models={};for(let[name,schema]of Object.entries(this.definitions.type))models[name]=getSchemaValidator(schema);return models}add(method,path,handle,localHook,{allowMeta=!1,skipPrefix=!1}={allowMeta:!1,skipPrefix:!1}){if(localHook=localHookToLifeCycleStore(localHook),path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix&&!this.config.scoped)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 models=this.definitions.type,dynamic=!this.config.aot,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},cookieValidator=()=>cloned.cookie?getCookieValidator({validator:cloned.cookie,defaultConfig:this.config.cookie,config:cloned.cookie?.config??{},dynamic,models}):void 0,normalize=this.config.normalize,validator=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.schema===!0?{body:getSchemaValidator(cloned.body,{dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()}),headers:getSchemaValidator(cloned.headers,{dynamic,models,additionalProperties:!this.config.normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),params:getSchemaValidator(cloned.params,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()}),query:getSchemaValidator(cloned.query,{dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{dynamic,models,normalize})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{dynamic,models,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{dynamic,models,normalize})}},loosePath=path.endsWith("/")?path.slice(0,path.length-1):path+"/";if(localHook=mergeHook(localHook,instanceValidator),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);this.applyMacro(localHook);let hooks=mergeHook(this.event,localHook);if(this.config.aot===!1){if(this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle}),this.config.strictPath===!1)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle});this.router.history.push({method,path,composed:null,handler:handle,hooks});return}let shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,inference=cloneInference(this.inference),staticHandler=typeof handle!=="function"?createStaticHandler(handle,hooks,this.setHeaders):void 0,nativeStaticHandler=typeof handle!=="function"?createNativeStaticHandler(handle,hooks,this.setHeaders):void 0;if(this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[path]=nativeStaticHandler();let compile=()=>composeHandler({app:this,path,method,localHook:mergeHook(localHook),hooks,validator,handler:handle,allowMeta,inference}),mainHandler=shouldPrecompile?compile():(context)=>{return compile()(context)},routeIndex=this.router.history.length;if(this.routeTree.has(method+path))for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){let removed=this.router.history.splice(i,1)[0];if(removed&&this.routeTree.has(removed?.method+removed?.path))this.routeTree.delete(removed.method+removed.path)}}else this.routeTree.set(method+path,routeIndex);this.router.history.push({method,path,composed:mainHandler,handler:handle,hooks});let staticRouter=this.router.static.http,handler={handler:shouldPrecompile?mainHandler:void 0,compile};if(method==="$INTERNALWS"){let loose=this.config.strictPath?void 0:path.endsWith("/")?path.slice(0,path.length-1):path+"/";if(path.indexOf(":")===-1&&path.indexOf("*")===-1){let index=staticRouter.handlers.length;if(staticRouter.handlers.push((ctx)=>(staticRouter.handlers[index]=compile())(ctx)),this.router.static.ws[path]=index,loose)this.router.static.ws[loose]=index}else if(this.router.ws.add("ws",path,handler),loose)this.router.ws.add("ws",loose,handler);return}if(path.indexOf(":")===-1&&path.indexOf("*")===-1){let index=staticRouter.handlers.length;if(staticRouter.handlers.push(staticHandler??((ctx2)=>(staticRouter.handlers[index]=compile())(ctx2))),!staticRouter.map[path])staticRouter.map[path]={code:""};let ctx=staticHandler?"":"ctx";if(method==="ALL")staticRouter.map[path].all=`default: return st[${index}](${ctx})\n`;else staticRouter.map[path].code=`case '${method}': return st[${index}](${ctx})\n${staticRouter.map[path].code}`;if(!this.config.strictPath){if(!staticRouter.map[loosePath])staticRouter.map[loosePath]={code:""};if(this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[loosePath]=nativeStaticHandler();if(method==="ALL")staticRouter.map[loosePath].all=`default: return st[${index}](${ctx})\n`;else staticRouter.map[loosePath].code=`case '${method}': return st[${index}](${ctx})\n${staticRouter.map[loosePath].code}`}}else if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath2=path.endsWith("/")?path.slice(0,path.length-1):path+"/";if(this.config.nativeStaticResponse===!0&&staticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[loosePath2]=staticHandler();this.router.http.add(method,loosePath2,handler)}}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)return this.on("parse",options);return this.on(options,"parse",handler)}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,error2){switch(typeof name){case"string":return error2.prototype[ERROR_CODE]=name,this.definitions.error[name]=error2,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error3]of Object.entries(name))error3.prototype[ERROR_CODE]=code,this.definitions.error[code]=error3;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)handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local";if(type!=="trace")sucrose({[type]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start.push(fn);break;case"request":this.event.request.push(fn);break;case"parse":this.event.parse.push(fn);break;case"transform":this.event.transform.push(fn);break;case"beforeHandle":this.event.beforeHandle.push(fn);break;case"afterHandle":this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse.push(fn);break;case"trace":this.event.trace.push(fn);break;case"error":this.event.error.push(fn);break;case"stop":this.event.stop.push(fn);break}}return this}propagate(){return promoteEvent(this.event.parse),promoteEvent(this.event.transform),promoteEvent(this.event.beforeHandle),promoteEvent(this.event.afterHandle),promoteEvent(this.event.mapResponse),promoteEvent(this.event.afterResponse),promoteEvent(this.event.trace),promoteEvent(this.event.error),this}as(type){let castType={plugin:"scoped",global:"global"}[type];if(promoteEvent(this.event.parse,castType),promoteEvent(this.event.transform,castType),promoteEvent(this.event.beforeHandle,castType),promoteEvent(this.event.afterHandle,castType),promoteEvent(this.event.mapResponse,castType),promoteEvent(this.event.afterResponse,castType),promoteEvent(this.event.trace,castType),promoteEvent(this.event.error,castType),type==="plugin")this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null;else if(type==="global")this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=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};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 hook=schemaOrRun,localHook=hooks;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||{}]}))}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0})}),this}guard(hook,run){if(!run){if(typeof hook==="object"){this.applyMacro(hook);let type=hook.as??"local";if(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},hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);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);if(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;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};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})=>{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||[]]}))}),this}use(plugin,options){if(options?.scoped)return this.guard({},(app)=>app.use(plugin));if(Array.isArray(plugin)){let current=this;for(let p of plugin)current=this.use(p);return current}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(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);throw new Error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.')}).then((x)=>x.compile())),this;return this._use(plugin)}_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.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,mergeHook(hooks,{error:plugin2.event.error}));return plugin2.compile(),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((x)=>x.compile())),this;return instance}let{name,seed}=plugin.config;plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.model(this.definitions.type),plugin.error(this.definitions.error);let isScoped=plugin.config.scoped;if(isScoped){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;this.dependencies[name].push(!this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry.stack,routes:plugin.router.history,decorators:plugin.singleton.decorator,store:plugin.singleton.store,type:plugin.definitions.type,error:plugin.definitions.error,derive:plugin.event.transform.filter((x)=>x.subType==="derive").map((x)=>({fn:x.fn.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform.filter((x)=>x.subType==="derive").map((x)=>({fn:x.fn.toString(),stack:new Error().stack??""}))})}plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);let macroHashes=[];for(let i=0;i<plugin.extender.macros.length;i++){let macro=this.extender.macros[i];if(macroHashes.includes(macro.checksum))plugin.extender.macros.splice(i,1),i--;macroHashes.push(macro.checksum)}if(plugin.onRequest((context)=>{Object.assign(context,this.singleton.decorator),Object.assign(context.store,this.singleton.store)}),plugin.event.trace.length)plugin.event.trace.push(...plugin.event.trace);if(!plugin.config.prefix)console.warn("It's recommended to use scoped instance with a prefix to prevent collision routing with other instance.");if(plugin.event.error.length)plugin.event.error.push(...this.event.error);if(plugin.config.aot)plugin.compile();if(isScoped===!0&&plugin.config.prefix){this.mount(plugin.config.prefix+"/",plugin.fetch);for(let route of plugin.router.history)this.routeTree.set(route.method+`${plugin.config.prefix}${route.path}`,this.router.history.length),this.router.history.push({...route,path:`${plugin.config.prefix}${route.path}`,hooks:mergeHook(route.hooks,{error:this.event.error})})}else{this.mount(plugin.fetch);for(let route of plugin.router.history)this.routeTree.set(route.method+`${plugin.config.prefix}${route.path}`,this.router.history.length),this.router.history.push({...route,path:`${plugin.config.prefix}${route.path}`,hooks:mergeHook(route.hooks,{error:this.event.error})})}return this}else{if(this.headers(plugin.setHeaders),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.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else this.extender.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions);deduplicateChecksum(this.extender.macros),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)}}this.inference={body:this.inference.body||plugin.inference.body,cookie:this.inference.cookie||plugin.inference.cookie,headers:this.inference.headers||plugin.inference.headers,query:this.inference.query||plugin.inference.query,set:this.inference.set||plugin.inference.set,server:this.inference.server||plugin.inference.server}}this.decorate(plugin.singleton.decorator),this.state(plugin.singleton.store),this.model(plugin.definitions.type),this.error(plugin.definitions.error),plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);for(let{method,path,handler,hooks}of Object.values(plugin.router.history))this.add(method,path,handler,mergeHook(hooks,{error:plugin.event.error}));if(!isScoped)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;this.dependencies[name].push(!this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}:{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,type:plugin.definitions.type,error:plugin.definitions.error,derive:plugin.event.transform.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:new Error().stack??""}))}),this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));return this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global}),this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped}),this}macro(macro){let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:macro.toString()})),fn:macro};return this.extender.macros.push(hook),this}mount(path,handle){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handle instanceof Elysia?handle.compile().fetch:handle,handler2=async({request,path:path2})=>{if(request.method==="GET"||request.method==="HEAD"||!request.headers.get("content-type"))return run(new Request(replaceUrlPath(request.url,path2||"/"),request));return run(new Request(replaceUrlPath(request.url,path2||"/"),{...request,body:await request.arrayBuffer()}))};return this.all("/*",handler2,{type:"none"}),this}let length=path.length;if(handle instanceof Elysia)handle=handle.compile().fetch;let handler=async({request,path:path2})=>{if(request.method==="GET"||request.method==="HEAD"||!request.headers.get("content-type"))return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),request));return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{...request,body:await request.arrayBuffer()}))};return this.all(path,handler,{type:"none"}),this.all(path+(path.endsWith("/")?"*":"/*"),handler,{type:"none"}),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){let transform=options.transformMessage?Array.isArray(options.transformMessage)?options.transformMessage:[options.transformMessage]:void 0,server=null,validateMessage=getSchemaValidator(options?.body,{models:this.definitions.type,normalize:this.config.normalize}),validateResponse=getSchemaValidator(options?.response,{models:this.definitions.type,normalize:this.config.normalize}),parseMessage=(message)=>{if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===47||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message}if(transform?.length)for(let i=0;i<transform.length;i++){let temp=transform[i](message);if(temp!==void 0)message=temp}return message};return this.route("$INTERNALWS",path,(context)=>{let{set:set2,path:path2,qi,headers,query,params}=context;if(server===null)server=this.getServer();if(server?.upgrade(context.request,{headers:typeof options.upgrade==="function"?options.upgrade(context):options.upgrade,data:{validator:validateResponse,open(ws){options.open?.(new ElysiaWS(ws,context))},message:(ws,msg)=>{let message=parseMessage(msg);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);options.message?.(new ElysiaWS(ws,context),message)},drain(ws){options.drain?.(new ElysiaWS(ws,context))},close(ws,code,reason){options.close?.(new ElysiaWS(ws,context),code,reason)}}}))return;return set2.status=400,"Expected a websocket connection"},{beforeHandle:options.beforeHandle,transform:options.transform,headers:options.headers,params:options.params,query:options.query}),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(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){switch(typeof name){case"object":return Object.entries(name).forEach(([key,value])=>{if(!(key in this.definitions.type))this.definitions.type[key]=value}),this;case"function":return this.definitions.type=name(this.definitions.type),this}return this.definitions.type[name]=model,this}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.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error2)=>(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error2);outerErrorHandler=(error2)=>new Response(error2.message||error2.name||"Error",{status:error2?.status??500});listen=(options,callback)=>{if(typeof Bun==="undefined")throw new 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(this.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let fetch=this.fetch,serve=typeof options==="object"?{development:!isProduction,reusePort:!0,...this.config.serve||{},...options||{},static:this.router.static.http.static,websocket:{...this.config.websocket||{},...websocket||{}},fetch,error:this.outerErrorHandler}:{development:!isProduction,reusePort:!0,...this.config.serve||{},static:this.router.static.http.static,websocket:{...this.config.websocket||{},...websocket||{}},port:options,fetch,error:this.outerErrorHandler};this.server=Bun?.serve(serve);for(let i=0;i<this.event.start.length;i++)this.event.start[i].fn(this);if(callback)callback(this.server);return process.on("beforeExit",()=>{if(this.server){this.server.stop(),this.server=null;for(let i=0;i<this.event.stop.length;i++)this.event.stop[i].fn(this)}}),this.promisedModules.then(()=>{Bun?.gc(!1)}),this};stop=async(closeActiveConnections)=>{if(!this.server)throw new Error("Elysia isn't running. Call `app.listen` to start the server.");if(this.server){if(this.server.stop(closeActiveConnections),this.server=null,this.event.stop.length)for(let i=0;i<this.event.stop.length;i++)this.event.stop[i].fn(this)}};get modules(){return Promise.all(this.promisedModules.promises)}}export{t,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,mapResponse,mapEarlyResponse,mapCompactResponse,getSchemaValidator,getResponseSchemaValidator,form,error,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidCookieSignature,InternalServerError,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
|
|
521
|
-
|
|
522
|
-
|
|
329
|
+
\t\t\t${composeValidation("body")}
|
|
330
|
+
\t\t}`;else fnLiteral+=`if(validator.body.Check(c.body) === false) {
|
|
331
|
+
\t\t\t${composeValidation("body")}
|
|
332
|
+
\t\t}`;if(doesHaveTransform)fnLiteral+=`
|
|
333
|
+
if(isNotEmptyObject) c.body = validator.body.Decode(c.body)
|
|
334
|
+
`}if(isNotEmpty(cookieValidator?.schema?.properties??cookieValidator?.schema?.schema??{})){if(fnLiteral+=`const cookieValue = {}
|
|
335
|
+
\t\t\tfor(const [key, value] of Object.entries(c.cookie))
|
|
336
|
+
\t\t\t\tcookieValue[key] = value.value
|
|
337
|
+
`,hasProperty("default",cookieValidator.schema))for(let[key,value]of Object.entries(Value4.Default(cookieValidator.schema,{})))fnLiteral+=`cookieValue['${key}'] = ${typeof value==="object"?JSON.stringify(value):value}
|
|
338
|
+
`;if(isOptional(validator.cookie))fnLiteral+="if(isNotEmpty(c.cookie)) {";if(fnLiteral+=`if(validator.cookie.Check(cookieValue) === false) {
|
|
339
|
+
\t\t\t\t${composeValidation("cookie","cookieValue")}
|
|
340
|
+
\t\t\t}`,hasTransform(validator.cookie.schema))fnLiteral+=`
|
|
341
|
+
for(const [key, value] of Object.entries(validator.cookie.Decode(cookieValue)))
|
|
342
|
+
\t\t\t\t\tc.cookie[key].value = value
|
|
343
|
+
`;if(isOptional(validator.cookie))fnLiteral+="}"}}if(hooks?.beforeHandle){let reporter=report("beforeHandle",{total:hooks.beforeHandle.length}),hasResolve=!1;for(let i=0;i<hooks.beforeHandle.length;i++){let beforeHandle=hooks.beforeHandle[i],endUnit=reporter.resolveChild(beforeHandle.fn.name),returning=hasReturn(beforeHandle);if(beforeHandle.subType==="resolve"||beforeHandle.subType==="mapResolve"){if(!hasResolve)hasResolve=!0,fnLiteral+=`
|
|
344
|
+
let resolved
|
|
345
|
+
`;if(fnLiteral+=isAsync(beforeHandle)?`resolved = await beforeHandle[${i}](c);
|
|
346
|
+
`:`resolved = beforeHandle[${i}](c);
|
|
347
|
+
`,beforeHandle.subType==="mapResolve")fnLiteral+=`if(resolved instanceof ElysiaCustomStatusResponse)
|
|
348
|
+
\t\t\t\t\t\tthrow resolved
|
|
349
|
+
\t\t\t\t\telse {
|
|
350
|
+
\t\t\t\t\t\tresolved.request = c.request
|
|
351
|
+
\t\t\t\t\t\tresolved.store = c.store
|
|
352
|
+
\t\t\t\t\t\tresolved.qi = c.qi
|
|
353
|
+
\t\t\t\t\t\tresolved.path = c.path
|
|
354
|
+
\t\t\t\t\t\tresolved.url = c.url
|
|
355
|
+
\t\t\t\t\t\tresolved.redirect = c.redirect
|
|
356
|
+
\t\t\t\t\t\tresolved.set = c.set
|
|
357
|
+
\t\t\t\t\t\tresolved.error = c.error
|
|
358
|
+
|
|
359
|
+
\t\t\t\t\t\tc = resolved
|
|
360
|
+
\t\t\t\t\t}`;else fnLiteral+=`if(resolved instanceof ElysiaCustomStatusResponse)
|
|
361
|
+
\t\t\t\t\t\tthrow resolved
|
|
362
|
+
\t\t\t\t\telse
|
|
363
|
+
\t\t\t\t\t\tObject.assign(c, resolved)
|
|
364
|
+
`}else if(!returning)fnLiteral+=isAsync(beforeHandle)?`await beforeHandle[${i}](c);
|
|
365
|
+
`:`beforeHandle[${i}](c);
|
|
366
|
+
`,endUnit();else{if(fnLiteral+=isAsync(beforeHandle)?`be = await beforeHandle[${i}](c);
|
|
367
|
+
`:`be = beforeHandle[${i}](c);
|
|
368
|
+
`,endUnit("be"),fnLiteral+=`if(be !== undefined) {
|
|
369
|
+
`,reporter.resolve(),hooks.afterHandle?.length){report("handle",{name:isHandleFn?handler.name:void 0}).resolve();let reporter2=report("afterHandle",{total:hooks.afterHandle.length});for(let i2=0;i2<hooks.afterHandle.length;i2++){let hook=hooks.afterHandle[i2],returning2=hasReturn(hook),endUnit2=reporter2.resolveChild(hook.fn.name);if(fnLiteral+=`c.response = be
|
|
370
|
+
`,!returning2)fnLiteral+=isAsync(hook.fn)?`await afterHandle[${i2}](c, be)
|
|
371
|
+
`:`afterHandle[${i2}](c, be)
|
|
372
|
+
`;else fnLiteral+=isAsync(hook.fn)?`af = await afterHandle[${i2}](c)
|
|
373
|
+
`:`af = afterHandle[${i2}](c)
|
|
374
|
+
`,fnLiteral+=`if(af !== undefined) { c.response = be = af }
|
|
375
|
+
`;endUnit2("af")}reporter2.resolve()}if(validator.response)fnLiteral+=composeResponseValidation("be");let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse.length});if(hooks.mapResponse.length){fnLiteral+=`
|
|
376
|
+
c.response = be
|
|
377
|
+
`;for(let i2=0;i2<hooks.mapResponse.length;i2++){let mapResponse2=hooks.mapResponse[i2],endUnit2=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`
|
|
378
|
+
if(mr === undefined) {
|
|
379
|
+
\t\t\t\t\t\t\tmr = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i2}](c)
|
|
380
|
+
\t\t\t\t\t\t\tif(mr !== undefined) be = c.response = mr
|
|
381
|
+
\t\t\t\t\t\t}
|
|
382
|
+
`,endUnit2()}}mapResponseReporter.resolve(),fnLiteral+=encodeCookie,fnLiteral+=`return mapEarlyResponse(${saveResponse} be, c.set ${requestMapper})}
|
|
383
|
+
`}}reporter.resolve()}if(hooks?.afterHandle.length){let handleReporter=report("handle",{name:isHandleFn?handler.name:void 0});if(hooks.afterHandle.length)fnLiteral+=isAsyncHandler?`let r = c.response = await ${handle};
|
|
384
|
+
`:`let r = c.response = ${handle};
|
|
385
|
+
`;else fnLiteral+=isAsyncHandler?`let r = await ${handle};
|
|
386
|
+
`:`let r = ${handle};
|
|
387
|
+
`;handleReporter.resolve();let reporter=report("afterHandle",{total:hooks.afterHandle.length});for(let i=0;i<hooks.afterHandle.length;i++){let hook=hooks.afterHandle[i],returning=hasReturn(hook),endUnit=reporter.resolveChild(hook.fn.name);if(!returning)fnLiteral+=isAsync(hook.fn)?`await afterHandle[${i}](c)
|
|
388
|
+
`:`afterHandle[${i}](c)
|
|
389
|
+
`,endUnit();else if(fnLiteral+=isAsync(hook.fn)?`af = await afterHandle[${i}](c)
|
|
390
|
+
`:`af = afterHandle[${i}](c)
|
|
391
|
+
`,endUnit("af"),validator.response)fnLiteral+="if(af !== undefined) {",reporter.resolve(),fnLiteral+=composeResponseValidation("af"),fnLiteral+="c.response = af }";else fnLiteral+="if(af !== undefined) {",reporter.resolve(),fnLiteral+=`c.response = af}
|
|
392
|
+
`}if(reporter.resolve(),fnLiteral+=`r = c.response
|
|
393
|
+
`,validator.response)fnLiteral+=composeResponseValidation();fnLiteral+=encodeCookie;let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse.length});if(hooks.mapResponse.length)for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse2=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`
|
|
394
|
+
mr = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i}](c)
|
|
395
|
+
\t\t\t\tif(mr !== undefined) r = c.response = mr
|
|
396
|
+
`,endUnit()}if(mapResponseReporter.resolve(),hasSet)fnLiteral+=`return mapResponse(${saveResponse} r, c.set ${requestMapper})
|
|
397
|
+
`;else fnLiteral+=`return mapCompactResponse(${saveResponse} r ${requestMapper})
|
|
398
|
+
`}else{let handleReporter=report("handle",{name:isHandleFn?handler.name:void 0});if(validator.response||hooks.mapResponse.length){if(fnLiteral+=isAsyncHandler?`let r = await ${handle};
|
|
399
|
+
`:`let r = ${handle};
|
|
400
|
+
`,handleReporter.resolve(),validator.response)fnLiteral+=composeResponseValidation();report("afterHandle").resolve();let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse.length});if(hooks.mapResponse.length){fnLiteral+=`
|
|
401
|
+
c.response = r
|
|
402
|
+
`;for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse2=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`
|
|
403
|
+
if(mr === undefined) {
|
|
404
|
+
\t\t\t\t\t\tmr = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i}](c)
|
|
405
|
+
\t\t\t\t\tif(mr !== undefined) r = c.response = mr
|
|
406
|
+
\t\t\t\t\t}
|
|
407
|
+
`,endUnit()}}if(mapResponseReporter.resolve(),fnLiteral+=encodeCookie,handler instanceof Response)fnLiteral+=inference.set?`if(
|
|
408
|
+
\t\t\t\t\tisNotEmpty(c.set.headers) ||
|
|
409
|
+
\t\t\t\t\tc.set.status !== 200 ||
|
|
410
|
+
\t\t\t\t\tc.set.redirect ||
|
|
411
|
+
\t\t\t\t\tc.set.cookie
|
|
412
|
+
\t\t\t\t)
|
|
413
|
+
\t\t\t\t\treturn mapResponse(${saveResponse} ${handle}.clone(), c.set ${requestMapper})
|
|
414
|
+
\t\t\t\telse
|
|
415
|
+
\t\t\t\t\treturn ${handle}.clone()`:`return ${handle}.clone()`,fnLiteral+=`
|
|
416
|
+
`;else if(hasSet)fnLiteral+=`return mapResponse(${saveResponse} r, c.set ${requestMapper})
|
|
417
|
+
`;else fnLiteral+=`return mapCompactResponse(${saveResponse} r ${requestMapper})
|
|
418
|
+
`}else if(hasCookie||hasTrace){fnLiteral+=isAsyncHandler?`let r = await ${handle};
|
|
419
|
+
`:`let r = ${handle};
|
|
420
|
+
`,handleReporter.resolve(),report("afterHandle").resolve();let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse.length});if(hooks.mapResponse.length){fnLiteral+=`
|
|
421
|
+
c.response = r
|
|
422
|
+
`;for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse2=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`
|
|
423
|
+
if(mr === undefined) {
|
|
424
|
+
\t\t\t\t\t\t\tmr = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i}](c)
|
|
425
|
+
\t\t\t\t\t\tif(mr !== undefined) r = c.response = mr
|
|
426
|
+
\t\t\t\t\t\t}
|
|
427
|
+
`,endUnit()}}if(mapResponseReporter.resolve(),fnLiteral+=encodeCookie,hasSet)fnLiteral+=`return mapResponse(${saveResponse} r, c.set ${requestMapper})
|
|
428
|
+
`;else fnLiteral+=`return mapCompactResponse(${saveResponse} r ${requestMapper})
|
|
429
|
+
`}else{handleReporter.resolve();let handled=isAsyncHandler?`await ${handle}`:handle;if(report("afterHandle").resolve(),handler instanceof Response)fnLiteral+=inference.set?`if(
|
|
430
|
+
\t\t\t\t\tisNotEmpty(c.set.headers) ||
|
|
431
|
+
\t\t\t\t\tc.set.status !== 200 ||
|
|
432
|
+
\t\t\t\t\tc.set.redirect ||
|
|
433
|
+
\t\t\t\t\tc.set.cookie
|
|
434
|
+
\t\t\t\t)
|
|
435
|
+
\t\t\t\t\treturn mapResponse(${saveResponse} ${handle}.clone(), c.set ${requestMapper})
|
|
436
|
+
\t\t\t\telse
|
|
437
|
+
\t\t\t\t\treturn ${handle}.clone()`:`return ${handle}.clone()`,fnLiteral+=`
|
|
438
|
+
`;else if(hasSet)fnLiteral+=`return mapResponse(${saveResponse} ${handled}, c.set ${requestMapper})
|
|
439
|
+
`;else fnLiteral+=`return mapCompactResponse(${saveResponse} ${handled} ${requestMapper})
|
|
440
|
+
`}}if(fnLiteral+=`
|
|
441
|
+
} catch(error) {`,hasBody)fnLiteral+=`
|
|
442
|
+
if(isParsing) error = new ParseError()
|
|
443
|
+
`;if(!maybeAsync)fnLiteral+=`
|
|
444
|
+
return (async () => {
|
|
445
|
+
`;if(fnLiteral+=`
|
|
446
|
+
const set = c.set
|
|
447
|
+
if (!set.status || set.status < 300) set.status = error?.status || 500
|
|
448
|
+
`,hasTrace)for(let i=0;i<hooks.trace.length;i++)fnLiteral+=`report${i}?.resolve(error);reportChild${i}?.(error);
|
|
449
|
+
`;let errorReporter=report("error",{total:hooks.error.length});if(hooks.error.length){fnLiteral+=`
|
|
450
|
+
\t\t\t\tc.error = error
|
|
451
|
+
\t\t\t\tif(error instanceof TypeBoxError) {
|
|
452
|
+
\t\t\t\t\tc.code = "VALIDATION"
|
|
453
|
+
\t\t\t\t\tc.set.status = 422
|
|
454
|
+
\t\t\t\t} else
|
|
455
|
+
\t\t\t\t\tc.code = error.code ?? error[ERROR_CODE] ?? "UNKNOWN"
|
|
456
|
+
\t\t\t\tlet er
|
|
457
|
+
\t\t\t`;for(let i=0;i<hooks.error.length;i++){let endUnit=errorReporter.resolveChild(hooks.error[i].fn.name);if(isAsync(hooks.error[i]))fnLiteral+=`
|
|
458
|
+
er = await handleErrors[${i}](c)
|
|
459
|
+
`;else fnLiteral+=`
|
|
460
|
+
er = handleErrors[${i}](c)
|
|
461
|
+
if (er instanceof Promise) er = await er
|
|
462
|
+
`;endUnit();let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse.length});if(hooks.mapResponse.length)for(let i2=0;i2<hooks.mapResponse.length;i2++){let mapResponse2=hooks.mapResponse[i2],endUnit2=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`
|
|
463
|
+
c.response = er
|
|
464
|
+
|
|
465
|
+
\t\t\t\t\t\t\ter = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i2}](c)
|
|
466
|
+
\t\t\t\t\t\t\tif(er instanceof Promise) er = await er
|
|
467
|
+
`,endUnit2()}if(mapResponseReporter.resolve(),fnLiteral+=`er = mapEarlyResponse(er, set ${requestMapper})
|
|
468
|
+
`,fnLiteral+="if (er) {",hasTrace){for(let i2=0;i2<hooks.trace.length;i2++)fnLiteral+=`
|
|
469
|
+
report${i2}.resolve()
|
|
470
|
+
`;errorReporter.resolve()}fnLiteral+=`return er
|
|
471
|
+
}
|
|
472
|
+
`}}if(errorReporter.resolve(),fnLiteral+=`return handleError(c, error, true)
|
|
473
|
+
`,!maybeAsync)fnLiteral+="})()";if(fnLiteral+="}",hasAfterResponse||hasTrace){if(fnLiteral+=" finally { ",!maybeAsync)fnLiteral+=";(async () => {";let reporter=report("afterResponse",{total:hooks.afterResponse.length});if(hasAfterResponse)for(let i=0;i<hooks.afterResponse.length;i++){let endUnit=reporter.resolveChild(hooks.afterResponse[i].fn.name);fnLiteral+=`
|
|
474
|
+
await afterResponse[${i}](c);
|
|
475
|
+
`,endUnit()}if(reporter.resolve(),!maybeAsync)fnLiteral+="})();";fnLiteral+="}"}fnLiteral=`const {
|
|
476
|
+
\t\thandler,
|
|
477
|
+
\t\thandleError,
|
|
478
|
+
\t\thooks: {
|
|
479
|
+
\t\t\ttransform,
|
|
480
|
+
\t\t\tresolve,
|
|
481
|
+
\t\t\tbeforeHandle,
|
|
482
|
+
\t\t\tafterHandle,
|
|
483
|
+
\t\t\tmapResponse: onMapResponse,
|
|
484
|
+
\t\t\tparse,
|
|
485
|
+
\t\t\terror: handleErrors,
|
|
486
|
+
\t\t\tafterResponse,
|
|
487
|
+
\t\t\ttrace: _trace
|
|
488
|
+
\t\t},
|
|
489
|
+
\t\tvalidator,
|
|
490
|
+
\t\tutils: {
|
|
491
|
+
\t\t\tmapResponse,
|
|
492
|
+
\t\t\tmapCompactResponse,
|
|
493
|
+
\t\t\tmapEarlyResponse,
|
|
494
|
+
\t\t\tparseQuery,
|
|
495
|
+
\t\t\tparseQueryFromURL,
|
|
496
|
+
\t\t\tisNotEmpty
|
|
497
|
+
\t\t},
|
|
498
|
+
\t\terror: {
|
|
499
|
+
\t\t\tNotFoundError,
|
|
500
|
+
\t\t\tValidationError,
|
|
501
|
+
\t\t\tInternalServerError,
|
|
502
|
+
\t\t\tParseError
|
|
503
|
+
\t\t},
|
|
504
|
+
\t\tschema,
|
|
505
|
+
\t\tdefinitions,
|
|
506
|
+
\t\tERROR_CODE,
|
|
507
|
+
\t\tparseCookie,
|
|
508
|
+
\t\tsignCookie,
|
|
509
|
+
\t\tdecodeURIComponent,
|
|
510
|
+
\t\tElysiaCustomStatusResponse,
|
|
511
|
+
\t\tELYSIA_TRACE,
|
|
512
|
+
\t\tELYSIA_REQUEST_ID,
|
|
513
|
+
\t\tgetServer,
|
|
514
|
+
\t\tTypeBoxError
|
|
515
|
+
\t} = hooks
|
|
516
|
+
|
|
517
|
+
\tconst trace = _trace.map(x => typeof x === 'function' ? x : x.fn)
|
|
518
|
+
|
|
519
|
+
\treturn ${maybeAsync?"async":""} function handle(c) {
|
|
520
|
+
\t\t${hooks.beforeHandle.length?"let be":""}
|
|
521
|
+
\t\t${hooks.afterHandle.length?"let af":""}
|
|
522
|
+
\t\t${hooks.mapResponse.length?"let mr":""}
|
|
523
|
+
|
|
524
|
+
\t\t${allowMeta?"c.schema = schema; c.defs = definitions":""}
|
|
525
|
+
\t\t${fnLiteral}
|
|
526
|
+
\t}`;try{return Function("hooks",fnLiteral)({handler,hooks:lifeCycleToFn(hooks),validator,handleError:app.handleError,utils:{mapResponse,mapCompactResponse,mapEarlyResponse,parseQuery,parseQueryFromURL,isNotEmpty},error:{NotFoundError,ValidationError,InternalServerError,ParseError},schema:app.router.history,definitions:app.definitions.type,ERROR_CODE,parseCookie,signCookie,decodeURIComponent:import_fast_decode_uri_component3.default,ElysiaCustomStatusResponse,ELYSIA_TRACE,ELYSIA_REQUEST_ID,getServer:()=>app.getServer(),TypeBoxError})}catch{let debugHooks=lifeCycleToFn(hooks);console.log("[Composer] failed to generate optimized handler"),console.log("Please report the following to SaltyAom privately as it may include sensitive information about your codebase:"),console.log("---"),console.log({handler:typeof handler==="function"?handler.toString():handler,hooks:{...debugHooks,transform:debugHooks?.transform?.map?.((x)=>x.toString()),resolve:debugHooks?.resolve?.map?.((x)=>x.toString()),beforeHandle:debugHooks?.beforeHandle?.map?.((x)=>x.toString()),afterHandle:debugHooks?.afterHandle?.map?.((x)=>x.toString()),mapResponse:debugHooks?.mapResponse?.map?.((x)=>x.toString()),parse:debugHooks?.parse?.map?.((x)=>x.toString()),error:debugHooks?.error?.map?.((x)=>x.toString()),afterResponse:debugHooks?.afterResponse?.map?.((x)=>x.toString()),stop:debugHooks?.stop?.map?.((x)=>x.toString())},validator,definitions:app.definitions.type}),console.log("---"),process.exit(1)}},composeGeneralHandler=(app)=>{let standardHostname=app.config.handler?.standardHostname??!0,decoratorsLiteral="",fnLiteral="",defaultHeaders=app.setHeaders;for(let key of Object.keys(app.singleton.decorator))decoratorsLiteral+=`,${key}: app.singleton.decorator.${key}`;let router=app.router,hasTrace=app.event.trace.length>0,findDynamicRoute=`
|
|
527
|
+
\tconst route = router.find(request.method, path) ${router.http.root.ALL?'?? router.find("ALL", path)':""}
|
|
528
|
+
|
|
529
|
+
\tif (route === null)
|
|
530
|
+
\t\treturn ${app.event.error.length?"app.handleError(ctx, notFound)":app.event.request.length?`new Response(error404Message, {
|
|
531
|
+
\t\t\t\t\tstatus: ctx.set.status === 200 ? 404 : ctx.set.status,
|
|
532
|
+
\t\t\t\t\theaders: ctx.set.headers
|
|
533
|
+
\t\t\t\t})`:"error404.clone()"}
|
|
534
|
+
|
|
535
|
+
\tctx.params = route.params
|
|
536
|
+
`;findDynamicRoute+=`if(route.store.handler) return route.store.handler(ctx)
|
|
537
|
+
\treturn (route.store.handler = route.store.compile())(ctx)
|
|
538
|
+
`;let switchMap="";for(let[path,{code,all,static:staticFn}]of Object.entries(router.static.http.map)){if(staticFn)switchMap+=`case '${path}':
|
|
539
|
+
switch(request.method) {
|
|
540
|
+
${code}
|
|
541
|
+
${all??"default: break map"}}
|
|
542
|
+
|
|
543
|
+
`;switchMap+=`case '${path}':
|
|
544
|
+
switch(request.method) {
|
|
545
|
+
${code}
|
|
546
|
+
${all??"default: break map"}}
|
|
547
|
+
|
|
548
|
+
`}let maybeAsync=app.event.request.some(isAsync);if(fnLiteral+=`const {
|
|
549
|
+
\t\tapp,
|
|
550
|
+
\t\tmapEarlyResponse,
|
|
551
|
+
\t\tNotFoundError,
|
|
552
|
+
\t\trandomId,
|
|
553
|
+
\t\thandleError,
|
|
554
|
+
\t\terror,
|
|
555
|
+
\t\tredirect,
|
|
556
|
+
\t\tELYSIA_TRACE,
|
|
557
|
+
\t\tELYSIA_REQUEST_ID,
|
|
558
|
+
\t\tgetServer
|
|
559
|
+
\t} = data
|
|
560
|
+
|
|
561
|
+
\tconst store = app.singleton.store
|
|
562
|
+
\tconst staticRouter = app.router.static.http
|
|
563
|
+
\tconst st = staticRouter.handlers
|
|
564
|
+
\tconst wsRouter = app.router.ws
|
|
565
|
+
\tconst router = app.router.http
|
|
566
|
+
\tconst trace = app.event.trace.map(x => typeof x === 'function' ? x : x.fn)
|
|
567
|
+
|
|
568
|
+
\tconst notFound = new NotFoundError()
|
|
569
|
+
\tconst hoc = app.extender.higherOrderFunctions.map(x => x.fn)
|
|
570
|
+
|
|
571
|
+
\t${app.event.request.length?"const onRequest = app.event.request.map(x => x.fn)":""}
|
|
572
|
+
\t${app.event.error.length?"":`
|
|
573
|
+
const error404Message = notFound.message.toString()
|
|
574
|
+
\tconst error404 = new Response(error404Message, { status: 404 });
|
|
575
|
+
`}
|
|
576
|
+
|
|
577
|
+
\t${app.event.trace.length?`const ${app.event.trace.map((_2,i)=>`tr${i} = app.event.trace[${i}].fn`).join(",")}`:""}
|
|
578
|
+
|
|
579
|
+
\t${maybeAsync?"async":""} function map(request) {
|
|
580
|
+
`,app.event.request.length)fnLiteral+="let re";if(fnLiteral+=`
|
|
581
|
+
const url = request.url
|
|
582
|
+
\t\tconst s = url.indexOf('/', ${standardHostname?11:7})
|
|
583
|
+
\t\tconst qi = url.indexOf('?', s + 1)
|
|
584
|
+
\t\tlet path
|
|
585
|
+
\t\tif(qi === -1)
|
|
586
|
+
\t\t\tpath = url.substring(s)
|
|
587
|
+
\t\telse
|
|
588
|
+
\t\t\tpath = url.substring(s, qi)
|
|
589
|
+
`,fnLiteral+=`${hasTrace?"const id = randomId()":""}
|
|
590
|
+
\t\tconst ctx = {
|
|
591
|
+
\t\t\trequest,
|
|
592
|
+
\t\t\tstore,
|
|
593
|
+
\t\t\tqi,
|
|
594
|
+
\t\t\tpath,
|
|
595
|
+
\t\t\turl,
|
|
596
|
+
\t\t\tredirect,
|
|
597
|
+
\t\t\tset: {
|
|
598
|
+
\t\t\t\theaders: ${Object.keys(defaultHeaders??{}).length?"Object.assign({}, app.setHeaders)":"{}"},
|
|
599
|
+
\t\t\t\tstatus: 200
|
|
600
|
+
\t\t\t},
|
|
601
|
+
\t\t\terror
|
|
602
|
+
\t\t\t${app.inference.server?`, get server() {
|
|
603
|
+
\t\t\t\t\t\t\treturn getServer()
|
|
604
|
+
\t\t\t\t\t\t}`:""}
|
|
605
|
+
\t\t\t${hasTrace?",[ELYSIA_REQUEST_ID]: id":""}
|
|
606
|
+
\t\t\t${decoratorsLiteral}
|
|
607
|
+
\t\t}
|
|
608
|
+
`,app.event.trace.length)fnLiteral+=`
|
|
609
|
+
ctx[ELYSIA_TRACE] = [${app.event.trace.map((_2,i)=>`tr${i}(ctx)`).join(",")}]
|
|
610
|
+
`;let reporter=createReport({context:"ctx",trace:app.event.trace,addFn(word){fnLiteral+=word}})("request",{attribute:"ctx",total:app.event.request.length});if(app.event.request.length){fnLiteral+=`
|
|
611
|
+
try {
|
|
612
|
+
`;for(let i=0;i<app.event.request.length;i++){let hook=app.event.request[i],withReturn=hasReturn(hook),maybeAsync2=isAsync(hook),endUnit=reporter.resolveChild(app.event.request[i].fn.name);if(withReturn)fnLiteral+=`re = mapEarlyResponse(
|
|
613
|
+
\t\t\t\t\t${maybeAsync2?"await":""} onRequest[${i}](ctx),
|
|
614
|
+
\t\t\t\t\tctx.set,
|
|
615
|
+
\t\t\t\t\trequest
|
|
616
|
+
\t\t\t\t)
|
|
617
|
+
`,endUnit("re"),fnLiteral+=`if(re !== undefined) return re
|
|
618
|
+
`;else fnLiteral+=`${maybeAsync2?"await":""} onRequest[${i}](ctx)
|
|
619
|
+
`,endUnit()}fnLiteral+=`} catch (error) {
|
|
620
|
+
\t\t\treturn app.handleError(ctx, error)
|
|
621
|
+
\t\t}`}reporter.resolve();let wsPaths=app.router.static.ws,wsRouter=app.router.ws;if(Object.keys(wsPaths).length||wsRouter.history.length){fnLiteral+=`
|
|
622
|
+
\t\t\tif(request.method === 'GET') {
|
|
623
|
+
\t\t\t\tswitch(path) {`;for(let[path,index]of Object.entries(wsPaths))fnLiteral+=`
|
|
624
|
+
\t\t\t\t\tcase '${path}':
|
|
625
|
+
\t\t\t\t\t\tif(request.headers.get('upgrade') === 'websocket')
|
|
626
|
+
\t\t\t\t\t\t\treturn st[${index}](ctx)
|
|
627
|
+
|
|
628
|
+
\t\t\t\t\t\tbreak`;fnLiteral+=`
|
|
629
|
+
\t\t\t\tdefault:
|
|
630
|
+
\t\t\t\t\tif(request.headers.get('upgrade') === 'websocket') {
|
|
631
|
+
\t\t\t\t\t\tconst route = wsRouter.find('ws', path)
|
|
632
|
+
|
|
633
|
+
\t\t\t\t\t\tif(route) {
|
|
634
|
+
\t\t\t\t\t\t\tctx.params = route.params
|
|
635
|
+
|
|
636
|
+
\t\t\t\t\t\t\tif(route.store.handler)
|
|
637
|
+
\t\t\t\t\t\t\t return route.store.handler(ctx)
|
|
638
|
+
|
|
639
|
+
\t\t\t\t\t\t\treturn (route.store.handler = route.store.compile())(ctx)
|
|
640
|
+
\t\t\t\t\t\t}
|
|
641
|
+
\t\t\t\t\t}
|
|
642
|
+
|
|
643
|
+
\t\t\t\t\tbreak
|
|
644
|
+
\t\t\t}
|
|
645
|
+
\t\t}
|
|
646
|
+
`}if(fnLiteral+=`
|
|
647
|
+
\t\tmap: switch(path) {
|
|
648
|
+
\t\t\t${switchMap}
|
|
649
|
+
|
|
650
|
+
\t\t\tdefault:
|
|
651
|
+
\t\t\t\tbreak
|
|
652
|
+
\t\t}
|
|
653
|
+
|
|
654
|
+
\t\t${findDynamicRoute}
|
|
655
|
+
\t}
|
|
656
|
+
`,app.extender.higherOrderFunctions.length){let handler="map";for(let i=0;i<app.extender.higherOrderFunctions.length;i++)handler=`hoc[${i}](${handler}, request)`;fnLiteral+=`return function hocMap(request) { return ${handler}(request) }`}else fnLiteral+="return map";let handleError=composeErrorHandler(app);return app.handleError=handleError,Function("data",fnLiteral)({app,mapEarlyResponse,NotFoundError,randomId,handleError,error,redirect,ELYSIA_TRACE,ELYSIA_REQUEST_ID,getServer:()=>app.getServer()})},composeErrorHandler=(app)=>{let hooks=app.event,fnLiteral="";fnLiteral+=`const {
|
|
657
|
+
\t\tapp: { event: { error: onErrorContainer, afterResponse: resContainer, mapResponse: _onMapResponse, trace: _trace } },
|
|
658
|
+
\t\tmapResponse,
|
|
659
|
+
\t\tERROR_CODE,
|
|
660
|
+
\t\tElysiaCustomStatusResponse,
|
|
661
|
+
\t\tELYSIA_TRACE,
|
|
662
|
+
\t\tELYSIA_REQUEST_ID
|
|
663
|
+
\t} = inject
|
|
664
|
+
|
|
665
|
+
\tconst trace = _trace.map(x => typeof x === 'function' ? x : x.fn)
|
|
666
|
+
\tconst onMapResponse = []
|
|
667
|
+
|
|
668
|
+
\tfor(let i = 0; i < _onMapResponse.length; i++)
|
|
669
|
+
\t\tonMapResponse.push(_onMapResponse[i].fn ?? _onMapResponse[i])
|
|
670
|
+
|
|
671
|
+
\tdelete _onMapResponse
|
|
672
|
+
|
|
673
|
+
\tconst onError = onErrorContainer.map(x => x.fn)
|
|
674
|
+
\tconst res = resContainer.map(x => x.fn)
|
|
675
|
+
|
|
676
|
+
\treturn ${app.event.error.find(isAsync)||app.event.mapResponse.find(isAsync)?"async":""} function(context, error, skipGlobal) {`;let hasTrace=app.event.trace.length>0;if(hasTrace)fnLiteral+=`
|
|
677
|
+
const id = context[ELYSIA_REQUEST_ID]
|
|
678
|
+
`;let report=createReport({context:"context",trace:hooks.trace,addFn:(word)=>{fnLiteral+=word}});fnLiteral+=`
|
|
679
|
+
\t\tconst set = context.set
|
|
680
|
+
\t\tlet r
|
|
681
|
+
|
|
682
|
+
\t\tif(!context.code)
|
|
683
|
+
\t\t\tcontext.code = error.code ?? error[ERROR_CODE]
|
|
684
|
+
|
|
685
|
+
\t\tif(!(context.error instanceof Error))
|
|
686
|
+
\t\t\tcontext.error = error
|
|
687
|
+
|
|
688
|
+
\t\tif(error instanceof ElysiaCustomStatusResponse) {
|
|
689
|
+
\t\t\terror.status = error.code
|
|
690
|
+
\t\t\terror.message = error.response
|
|
691
|
+
\t\t}
|
|
692
|
+
`;let saveResponse=hasTrace||hooks.afterResponse.length>0||hooks.afterResponse.length>0?"context.response = ":"";for(let i=0;i<app.event.error.length;i++){let handler=app.event.error[i],response=`${isAsync(handler)?"await ":""}onError[${i}](context)`;if(fnLiteral+=`
|
|
693
|
+
if(skipGlobal !== true) {
|
|
694
|
+
`,hasReturn(handler)){fnLiteral+=`r = ${response}; if(r !== undefined) {
|
|
695
|
+
\t\t\t\tif(r instanceof Response) return r
|
|
696
|
+
|
|
697
|
+
\t\t\t\tif(r instanceof ElysiaCustomStatusResponse) {
|
|
698
|
+
\t\t\t\t\terror.status = error.code
|
|
699
|
+
\t\t\t\t\terror.message = error.response
|
|
700
|
+
\t\t\t\t}
|
|
701
|
+
|
|
702
|
+
\t\t\t\tif(set.status === 200) set.status = error.status
|
|
703
|
+
`;let mapResponseReporter2=report("mapResponse",{total:hooks.mapResponse.length,name:"context"});if(hooks.mapResponse.length)for(let i2=0;i2<hooks.mapResponse.length;i2++){let mapResponse2=hooks.mapResponse[i2],endUnit=mapResponseReporter2.resolveChild(mapResponse2.fn.name);fnLiteral+=`
|
|
704
|
+
context.response = r
|
|
705
|
+
\t\t\t\t\t\tr = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i2}](context)
|
|
706
|
+
`,endUnit()}mapResponseReporter2.resolve(),fnLiteral+=`return mapResponse(${saveResponse} r, set, context.request)}
|
|
707
|
+
`}else fnLiteral+=response+`
|
|
708
|
+
`;fnLiteral+=`
|
|
709
|
+
}
|
|
710
|
+
`}fnLiteral+=`if(error.constructor.name === "ValidationError" || error.constructor.name === "TransformDecodeError") {
|
|
711
|
+
\t const reportedError = error.error ?? error
|
|
712
|
+
\t\tset.status = reportedError.status ?? 422
|
|
713
|
+
\t\treturn new Response(
|
|
714
|
+
\t\t\treportedError.message,
|
|
715
|
+
\t\t\t{
|
|
716
|
+
\t\t\t\theaders: Object.assign(
|
|
717
|
+
\t\t\t\t\t{ 'content-type': 'application/json'},
|
|
718
|
+
\t\t\t\t\tset.headers
|
|
719
|
+
\t\t\t\t),
|
|
720
|
+
\t\t\t\tstatus: set.status
|
|
721
|
+
\t\t\t}
|
|
722
|
+
\t\t)
|
|
723
|
+
\t} else {
|
|
724
|
+
\t\tif(error.code && typeof error.status === "number")
|
|
725
|
+
\t\t\treturn new Response(
|
|
726
|
+
\t\t\t\terror.message,
|
|
727
|
+
\t\t\t\t{ headers: set.headers, status: error.status }
|
|
728
|
+
\t\t\t)
|
|
729
|
+
`;let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse.length,name:"context"});if(hooks.mapResponse.length)for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse2=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`
|
|
730
|
+
context.response = error
|
|
731
|
+
\t\t\terror = ${isAsyncName(mapResponse2)?"await":""} onMapResponse[${i}](context)
|
|
732
|
+
`,endUnit()}return mapResponseReporter.resolve(),fnLiteral+=`
|
|
733
|
+
return mapResponse(${saveResponse} error, set, context.request)
|
|
734
|
+
}
|
|
735
|
+
}`,Function("inject",fnLiteral)({app,mapResponse,ERROR_CODE,ElysiaCustomStatusResponse,ELYSIA_TRACE,ELYSIA_REQUEST_ID})};import{TransformDecodeError}from"@sinclair/typebox/value";var createDynamicHandler=(app)=>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:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,redirect});try{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=mapEarlyResponse(response2,set2),response2)return context.response=response2}let handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find("ALL",path);if(!handler)throw new NotFoundError;let{handle,hooks,validator,content}=handler.store,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=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);context.contentType=contentType;for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn,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.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQueryFromURL(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta=Object.assign({},app.config?.cookie,validator?.cookie?.config),cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta?{secrets:cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets.join(","):void 0,sign:cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?typeof cookieMeta.sign==="string"?cookieMeta.sign:cookieMeta.sign.join(","):void 0}:void 0);for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],operation=hook.fn(context);if(hook.subType==="derive")if(operation instanceof Promise)Object.assign(context,await operation);else Object.assign(context,operation);else if(operation instanceof Promise)await operation}if(validator){if(validator.createHeaders?.()){let _header={};for(let key in request.headers)_header[key]=request.headers.get(key);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(validator.createParams?.()?.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.createQuery?.()?.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)}for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(hook.subType==="resolve"){if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse(response2,context.set);if(result)return context.response=result}if(response2 instanceof Promise)Object.assign(context,await response2);else Object.assign(context,response2);continue}else if(response2 instanceof Promise)response2=await response2;if(response2!==void 0){context.response=response2;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=mapEarlyResponse(response2,context.set);if(result)return context.response=result}}let response=handle(context);if(response instanceof Promise)response=await response;if(!hooks.afterHandle.length){let status=response instanceof ElysiaCustomStatusResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200,responseValidator=validator?.createResponse?.()?.[status];if(responseValidator?.Check(response)===!1)throw new ValidationError("response",responseValidator,response);else if(responseValidator?.Decode)response=responseValidator.Decode(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let newResponse=hooks.afterHandle[i].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;let result=mapEarlyResponse(newResponse,context.set);if(result!==void 0){let responseValidator=validator?.response?.[result.status];if(responseValidator?.Check(result)===!1)throw new ValidationError("response",responseValidator,result);else if(responseValidator?.Decode)response=responseValidator.Decode(response);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)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;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 context.response=mapResponse(response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;if(reportedError.status)set2.status=reportedError.status;return app.handleError(context,reportedError)}finally{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)}},createDynamicErrorHandler=(app)=>async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});errorContext.set=context.set;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=mapResponse(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};_routes={};_types={Prefix:"",Scoped:!1,Singleton:{},Definitions:{},Metadata:{}};_ephemeral={};_volatile={};static version=version;version=version;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}get _scoped(){return this.config.scoped}definitions={type:{},error:{}};extender={macros:[],higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],mapResponse:[],afterResponse:[],trace:[],error:[],stop:[]};telemetry={stack:void 0};router={http:new Y,ws:new Y,dynamic:new Y,static:{http:{static:{},handlers:[],map:{},all:""},ws:{}},history:[]};routeTree=new Map;get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1};getServer(){return this.server}_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup;return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(config.nativeStaticResponse===void 0)config.nativeStaticResponse=!0;if(this.config={},this.applyConfig(config??{}),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry.stack=new Error().stack}env(model,env2=Bun?.env??process.env){if(getSchemaValidator(model,{dynamic:!0,additionalProperties:!0,coerce:!0}).Check(env2)===!1){let error2=new ValidationError("env",model,env2);throw new Error(error2.all.map((x)=>x.summary).join(`
|
|
736
|
+
`))}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}applyMacro(localHook){if(this.extender.macros.length){let manage=createMacroManager({globalHook:this.event,localHook}),manager={events:{global:this.event,local:localHook},onParse:manage("parse"),onTransform:manage("transform"),onBeforeHandle:manage("beforeHandle"),onAfterHandle:manage("afterHandle"),mapResponse:manage("mapResponse"),onAfterResponse:manage("afterResponse"),onError:manage("error")};for(let macro of this.extender.macros)traceBackMacro(macro.fn(manager),localHook)}}applyConfig(config){return this.config={prefix:"",aot:!0,strictPath:!1,global:!1,analytic:!1,normalize:!0,...config,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this}get models(){let models={};for(let[name,schema]of Object.entries(this.definitions.type))models[name]=getSchemaValidator(schema);return models}add(method,path,handle,localHook,{allowMeta=!1,skipPrefix=!1}={allowMeta:!1,skipPrefix:!1}){if(localHook=localHookToLifeCycleStore(localHook),path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix&&!this.config.scoped)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 models=this.definitions.type,dynamic=!this.config.aot,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},cookieValidator=()=>cloned.cookie?getCookieValidator({validator:cloned.cookie,defaultConfig:this.config.cookie,config:cloned.cookie?.config??{},dynamic,models}):void 0,normalize=this.config.normalize,validator=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.schema===!0?{body:getSchemaValidator(cloned.body,{dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()}),headers:getSchemaValidator(cloned.headers,{dynamic,models,additionalProperties:!this.config.normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),params:getSchemaValidator(cloned.params,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()}),query:getSchemaValidator(cloned.query,{dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{dynamic,models,normalize})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{dynamic,models,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{dynamic,models,normalize})}},loosePath=path.endsWith("/")?path.slice(0,path.length-1):path+"/";if(localHook=mergeHook(localHook,instanceValidator),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);this.applyMacro(localHook);let hooks=mergeHook(this.event,localHook);if(this.config.aot===!1){if(this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle}),this.config.strictPath===!1)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle});this.router.history.push({method,path,composed:null,handler:handle,hooks});return}let shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,inference=cloneInference(this.inference),staticHandler=typeof handle!=="function"?createStaticHandler(handle,hooks,this.setHeaders):void 0,nativeStaticHandler=typeof handle!=="function"?createNativeStaticHandler(handle,hooks,this.setHeaders):void 0;if(this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[path]=nativeStaticHandler();let compile=()=>composeHandler({app:this,path,method,localHook:mergeHook(localHook),hooks,validator,handler:handle,allowMeta,inference}),mainHandler=shouldPrecompile?compile():(context)=>{return compile()(context)},routeIndex=this.router.history.length;if(this.routeTree.has(method+path))for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){let removed=this.router.history.splice(i,1)[0];if(removed&&this.routeTree.has(removed?.method+removed?.path))this.routeTree.delete(removed.method+removed.path)}}else this.routeTree.set(method+path,routeIndex);this.router.history.push({method,path,composed:mainHandler,handler:handle,hooks});let staticRouter=this.router.static.http,handler={handler:shouldPrecompile?mainHandler:void 0,compile};if(method==="$INTERNALWS"){let loose=this.config.strictPath?void 0:path.endsWith("/")?path.slice(0,path.length-1):path+"/";if(path.indexOf(":")===-1&&path.indexOf("*")===-1){let index=staticRouter.handlers.length;if(staticRouter.handlers.push((ctx)=>(staticRouter.handlers[index]=compile())(ctx)),this.router.static.ws[path]=index,loose)this.router.static.ws[loose]=index}else if(this.router.ws.add("ws",path,handler),loose)this.router.ws.add("ws",loose,handler);return}if(path.indexOf(":")===-1&&path.indexOf("*")===-1){let index=staticRouter.handlers.length;if(staticRouter.handlers.push(staticHandler??((ctx2)=>(staticRouter.handlers[index]=compile())(ctx2))),!staticRouter.map[path])staticRouter.map[path]={code:""};let ctx=staticHandler?"":"ctx";if(method==="ALL")staticRouter.map[path].all=`default: return st[${index}](${ctx})
|
|
737
|
+
`;else staticRouter.map[path].code=`case '${method}': return st[${index}](${ctx})
|
|
738
|
+
${staticRouter.map[path].code}`;if(!this.config.strictPath){if(!staticRouter.map[loosePath])staticRouter.map[loosePath]={code:""};if(this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[loosePath]=nativeStaticHandler();if(method==="ALL")staticRouter.map[loosePath].all=`default: return st[${index}](${ctx})
|
|
739
|
+
`;else staticRouter.map[loosePath].code=`case '${method}': return st[${index}](${ctx})
|
|
740
|
+
${staticRouter.map[loosePath].code}`}}else if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath2=path.endsWith("/")?path.slice(0,path.length-1):path+"/";if(this.config.nativeStaticResponse===!0&&staticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[loosePath2]=staticHandler();this.router.http.add(method,loosePath2,handler)}}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)return this.on("parse",options);return this.on(options,"parse",handler)}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,error2){switch(typeof name){case"string":return error2.prototype[ERROR_CODE]=name,this.definitions.error[name]=error2,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error3]of Object.entries(name))error3.prototype[ERROR_CODE]=code,this.definitions.error[code]=error3;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)handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local";if(type!=="trace")sucrose({[type]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start.push(fn);break;case"request":this.event.request.push(fn);break;case"parse":this.event.parse.push(fn);break;case"transform":this.event.transform.push(fn);break;case"beforeHandle":this.event.beforeHandle.push(fn);break;case"afterHandle":this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse.push(fn);break;case"trace":this.event.trace.push(fn);break;case"error":this.event.error.push(fn);break;case"stop":this.event.stop.push(fn);break}}return this}propagate(){return promoteEvent(this.event.parse),promoteEvent(this.event.transform),promoteEvent(this.event.beforeHandle),promoteEvent(this.event.afterHandle),promoteEvent(this.event.mapResponse),promoteEvent(this.event.afterResponse),promoteEvent(this.event.trace),promoteEvent(this.event.error),this}as(type){let castType={plugin:"scoped",global:"global"}[type];if(promoteEvent(this.event.parse,castType),promoteEvent(this.event.transform,castType),promoteEvent(this.event.beforeHandle,castType),promoteEvent(this.event.afterHandle,castType),promoteEvent(this.event.mapResponse,castType),promoteEvent(this.event.afterResponse,castType),promoteEvent(this.event.trace,castType),promoteEvent(this.event.error,castType),type==="plugin")this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null;else if(type==="global")this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=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};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 hook=schemaOrRun,localHook=hooks;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||{}]}))}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0})}),this}guard(hook,run){if(!run){if(typeof hook==="object"){this.applyMacro(hook);let type=hook.as??"local";if(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},hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);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);if(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;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};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})=>{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||[]]}))}),this}use(plugin,options){if(options?.scoped)return this.guard({},(app)=>app.use(plugin));if(Array.isArray(plugin)){let current=this;for(let p of plugin)current=this.use(p);return current}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(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);throw new Error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.')}).then((x)=>x.compile())),this;return this._use(plugin)}_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.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,mergeHook(hooks,{error:plugin2.event.error}));return plugin2.compile(),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((x)=>x.compile())),this;return instance}let{name,seed}=plugin.config;plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.model(this.definitions.type),plugin.error(this.definitions.error);let isScoped=plugin.config.scoped;if(isScoped){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;this.dependencies[name].push(!this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry.stack,routes:plugin.router.history,decorators:plugin.singleton.decorator,store:plugin.singleton.store,type:plugin.definitions.type,error:plugin.definitions.error,derive:plugin.event.transform.filter((x)=>x.subType==="derive").map((x)=>({fn:x.fn.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform.filter((x)=>x.subType==="derive").map((x)=>({fn:x.fn.toString(),stack:new Error().stack??""}))})}plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);let macroHashes=[];for(let i=0;i<plugin.extender.macros.length;i++){let macro=this.extender.macros[i];if(macroHashes.includes(macro.checksum))plugin.extender.macros.splice(i,1),i--;macroHashes.push(macro.checksum)}if(plugin.onRequest((context)=>{Object.assign(context,this.singleton.decorator),Object.assign(context.store,this.singleton.store)}),plugin.event.trace.length)plugin.event.trace.push(...plugin.event.trace);if(!plugin.config.prefix)console.warn("It's recommended to use scoped instance with a prefix to prevent collision routing with other instance.");if(plugin.event.error.length)plugin.event.error.push(...this.event.error);if(plugin.config.aot)plugin.compile();if(isScoped===!0&&plugin.config.prefix){this.mount(plugin.config.prefix+"/",plugin.fetch);for(let route of plugin.router.history)this.routeTree.set(route.method+`${plugin.config.prefix}${route.path}`,this.router.history.length),this.router.history.push({...route,path:`${plugin.config.prefix}${route.path}`,hooks:mergeHook(route.hooks,{error:this.event.error})})}else{this.mount(plugin.fetch);for(let route of plugin.router.history)this.routeTree.set(route.method+`${plugin.config.prefix}${route.path}`,this.router.history.length),this.router.history.push({...route,path:`${plugin.config.prefix}${route.path}`,hooks:mergeHook(route.hooks,{error:this.event.error})})}return this}else{if(this.headers(plugin.setHeaders),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.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else this.extender.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions);deduplicateChecksum(this.extender.macros),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)}}this.inference={body:this.inference.body||plugin.inference.body,cookie:this.inference.cookie||plugin.inference.cookie,headers:this.inference.headers||plugin.inference.headers,query:this.inference.query||plugin.inference.query,set:this.inference.set||plugin.inference.set,server:this.inference.server||plugin.inference.server}}this.decorate(plugin.singleton.decorator),this.state(plugin.singleton.store),this.model(plugin.definitions.type),this.error(plugin.definitions.error),plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);for(let{method,path,handler,hooks}of Object.values(plugin.router.history))this.add(method,path,handler,mergeHook(hooks,{error:plugin.event.error}));if(!isScoped)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;this.dependencies[name].push(!this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}:{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,type:plugin.definitions.type,error:plugin.definitions.error,derive:plugin.event.transform.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:new Error().stack??""}))}),this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));return this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global}),this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped}),this}macro(macro){let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:macro.toString()})),fn:macro};return this.extender.macros.push(hook),this}mount(path,handle){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handle instanceof Elysia?handle.compile().fetch:handle,handler2=async({request,path:path2})=>{if(request.method==="GET"||request.method==="HEAD"||!request.headers.get("content-type"))return run(new Request(replaceUrlPath(request.url,path2||"/"),request));return run(new Request(replaceUrlPath(request.url,path2||"/"),{...request,body:await request.arrayBuffer()}))};return this.all("/*",handler2,{type:"none"}),this}let length=path.length;if(handle instanceof Elysia)handle=handle.compile().fetch;let handler=async({request,path:path2})=>{if(request.method==="GET"||request.method==="HEAD"||!request.headers.get("content-type"))return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),request));return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{...request,body:await request.arrayBuffer()}))};return this.all(path,handler,{type:"none"}),this.all(path+(path.endsWith("/")?"*":"/*"),handler,{type:"none"}),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){let transform=options.transformMessage?Array.isArray(options.transformMessage)?options.transformMessage:[options.transformMessage]:void 0,server=null,validateMessage=getSchemaValidator(options?.body,{models:this.definitions.type,normalize:this.config.normalize}),validateResponse=getSchemaValidator(options?.response,{models:this.definitions.type,normalize:this.config.normalize}),parseMessage=(message)=>{if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===47||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message}if(transform?.length)for(let i=0;i<transform.length;i++){let temp=transform[i](message);if(temp!==void 0)message=temp}return message};return this.route("$INTERNALWS",path,(context)=>{let{set:set2,path:path2,qi,headers,query,params}=context;if(server===null)server=this.getServer();if(server?.upgrade(context.request,{headers:typeof options.upgrade==="function"?options.upgrade(context):options.upgrade,data:{validator:validateResponse,open(ws){options.open?.(new ElysiaWS(ws,context))},message:(ws,msg)=>{let message=parseMessage(msg);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);options.message?.(new ElysiaWS(ws,context),message)},drain(ws){options.drain?.(new ElysiaWS(ws,context))},close(ws,code,reason){options.close?.(new ElysiaWS(ws,context),code,reason)}}}))return;return set2.status=400,"Expected a websocket connection"},{beforeHandle:options.beforeHandle,transform:options.transform,headers:options.headers,params:options.params,query:options.query}),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(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){switch(typeof name){case"object":return Object.entries(name).forEach(([key,value])=>{if(!(key in this.definitions.type))this.definitions.type[key]=value}),this;case"function":return this.definitions.type=name(this.definitions.type),this}return this.definitions.type[name]=model,this}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.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error2)=>(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error2);outerErrorHandler=(error2)=>new Response(error2.message||error2.name||"Error",{status:error2?.status??500});listen=(options,callback)=>{if(typeof Bun==="undefined")throw new 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(this.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let fetch=this.fetch,serve=typeof options==="object"?{development:!isProduction,reusePort:!0,...this.config.serve||{},...options||{},static:this.router.static.http.static,websocket:{...this.config.websocket||{},...websocket||{}},fetch,error:this.outerErrorHandler}:{development:!isProduction,reusePort:!0,...this.config.serve||{},static:this.router.static.http.static,websocket:{...this.config.websocket||{},...websocket||{}},port:options,fetch,error:this.outerErrorHandler};this.server=Bun?.serve(serve);for(let i=0;i<this.event.start.length;i++)this.event.start[i].fn(this);if(callback)callback(this.server);return process.on("beforeExit",()=>{if(this.server){this.server.stop(),this.server=null;for(let i=0;i<this.event.stop.length;i++)this.event.stop[i].fn(this)}}),this.promisedModules.then(()=>{Bun?.gc(!1)}),this};stop=async(closeActiveConnections)=>{if(!this.server)throw new Error("Elysia isn't running. Call `app.listen` to start the server.");if(this.server){if(this.server.stop(closeActiveConnections),this.server=null,this.event.stop.length)for(let i=0;i<this.event.stop.length;i++)this.event.stop[i].fn(this)}};get modules(){return Promise.all(this.promisedModules.promises)}}export{t,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,mapResponse,mapEarlyResponse,mapCompactResponse,getSchemaValidator,getResponseSchemaValidator,form,error,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidCookieSignature,InternalServerError,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
|
|
741
|
+
|
|
742
|
+
//# debugId=50C4F143C2AECBE164756E2164756E21
|