elysia 1.2.21 → 1.2.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bun/index.js CHANGED
@@ -2,7 +2,7 @@
2
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 __require=import.meta.require;import{Memoirist}from"memoirist";import{TypeRegistry,Type,FormatRegistry}from"@sinclair/typebox";import{Kind as Kind2,Unsafe}from"@sinclair/typebox";import{TypeCompiler as TypeCompiler2}from"@sinclair/typebox/compiler";import{Value as Value3}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{Value as Value2}from"@sinclair/typebox/value";import{Kind,TransformKind}from"@sinclair/typebox";import{Value}from"@sinclair/typebox/value";import{TypeCompiler}from"@sinclair/typebox/compiler";var hasHeaderShorthand="toJSON"in new Headers,replaceUrlPath=(url,pathname)=>{let urlObject=new URL(url);return urlObject.pathname=pathname,urlObject.toString()},isClass=(v)=>typeof v==="function"&&/^\s*class\s+/.test(v.toString())||v.toString&&v.toString().startsWith("[object ")&&v.toString()!=="[object Object]"||isNotEmpty(Object.getPrototypeOf(v)),isObject=(item)=>item&&typeof item==="object"&&!Array.isArray(item),mergeDeep=(target,source,{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 v=mergeDeep(Object.assign({},a),b,{skipKeys:["properties"]});if("properties"in v)delete v.properties;return v},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 Object.assign(a,b);else if(a&&!isRecordNumber(a)&&isRecordNumber(b))return Object.assign({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)=>{let{resolve:resolveA,...restA}=a??{},{resolve:resolveB,...restB}=b??{};return{...restA,...restB,body:b?.body??a?.body,headers:b?.headers??a?.headers,params:b?.params??a?.params,query:b?.query??a?.query,cookie:b?.cookie??a?.cookie,response:mergeResponse(a?.response,b?.response),type:a?.type||b?.type,detail:mergeDeep(b?.detail??{},a?.detail??{}),parse:mergeObjectArray(a?.parse,b?.parse),transform:mergeObjectArray(a?.transform,b?.transform),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(resolveA,"resolve"),a?.beforeHandle),mergeObjectArray(fnToContainer(resolveB,"resolve"),b?.beforeHandle)),afterHandle:mergeObjectArray(a?.afterHandle,b?.afterHandle),mapResponse:mergeObjectArray(a?.mapResponse,b?.mapResponse),afterResponse:mergeObjectArray(a?.afterResponse,b?.afterResponse),trace:mergeObjectArray(a?.trace,b?.trace),error:mergeObjectArray(a?.error,b?.error)}},replaceSchemaType=(schema,options,root=!0)=>{if(!Array.isArray(options))return options.original=schema,_replaceSchemaType(schema,options,root);for(let option of options)option.original=schema,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[Kind];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)return _replaceSchemaType(schema.not,options,root);let isRoot=root&&!!options.excludeRoot;if(schema[Kind]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest);if(!to)return schema;let 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(Value.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(Value.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)to.not=composeProperties(to.not);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[Kind]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(!to)return schema;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)to.not={...rest,...to.not};properties[key]={...rest,..._replaceSchemaType(rest,options,!1)};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,!1);break;default:if(Array.isArray(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);else if(value.type==="array")value.items=_replaceSchemaType(value.items,options,!1);break}return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value.Clean(schema,structuredClone(value))}catch{try{return Value.Clean(schema,value)}catch{return value}}return value},getSchemaValidator=(s,{models={},dynamic=!1,modules,normalize=!1,additionalProperties=!1,coerce=!1,additionalCoerce=[]}={modules:t.Module({})})=>{if(!s)return;let schema;if(typeof s!=="string")schema=s;else{let isArray=s.endsWith("[]"),key=isArray?s.substring(0,s.length-2):s;if(schema=modules.Import(key)??models[key],isArray)schema=t.Array(schema)}if(!schema)return;if(coerce||additionalCoerce)if(coerce)schema=replaceSchemaType(schema,[{from:t.Ref(""),to:(options)=>modules.Import(options.$ref)},{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,[{from:t.Ref(""),to:(options)=>modules.Import(options.$ref)},...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)=>Value.Check(schema,value),Errors:(value)=>Value.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value.Decode(schema,value),Encode:(value)=>Value.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=TypeCompiler.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={},modules,dynamic=!1,normalize=!1,additionalProperties=!1})=>{if(!s)return;let maybeSchemaOrRecord;if(typeof s!=="string")maybeSchemaOrRecord=s;else{let isArray=s.endsWith("[]"),key=isArray?s.substring(0,s.length-2):s;if(maybeSchemaOrRecord=modules.Import(key)??models[key],isArray)maybeSchemaOrRecord=t.Array(maybeSchemaOrRecord)}if(!maybeSchemaOrRecord)return;let compile=(schema,references)=>{if(dynamic)return{schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value.Check(schema,value),Errors:(value)=>Value.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value.Decode(schema,value),Encode:(value)=>Value.Encode(schema,value)};let compiledValidator=TypeCompiler.Compile(schema,references);if(normalize&&schema.additionalProperties===!1)compiledValidator.Clean=createCleaner(schema);return compiledValidator},modelValues=Object.values(models);if(Kind in maybeSchemaOrRecord){if("additionalProperties"in maybeSchemaOrRecord===!1)maybeSchemaOrRecord.additionalProperties=additionalProperties;return{200:compile(maybeSchemaOrRecord,modelValues)}}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]=Kind in schema?compile(schema,modelValues):schema}return}if(maybeNameOrSchema.type==="object"&&"additionalProperties"in maybeNameOrSchema===!1)maybeNameOrSchema.additionalProperties=additionalProperties;record[+status]=Kind in maybeNameOrSchema?compile(maybeNameOrSchema,modelValues):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,modules,defaultConfig={},config,dynamic,models})=>{let cookieValidator=getSchemaValidator(validator,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions()});if(isNotEmpty(defaultConfig))if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie({}),{modules,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(mergeObjectArray(fnToContainer(a.resolve,"resolve"),a.beforeHandle),injectChecksum(checksum2,mergeObjectArray(fnToContainer(b?.resolve,"resolve"),b?.beforeHandle))),afterHandle:mergeObjectArray(a.afterHandle,injectChecksum(checksum2,b?.afterHandle)),mapResponse:mergeObjectArray(a.mapResponse,injectChecksum(checksum2,b?.mapResponse)),afterResponse:mergeObjectArray(a.afterResponse,injectChecksum(checksum2,b?.afterResponse)),trace:mergeObjectArray(a.trace,injectChecksum(checksum2,b?.trace)),error:mergeObjectArray(a.error,injectChecksum(checksum2,b?.error)),stop:mergeObjectArray(a.stop,injectChecksum(checksum2,b?.stop))}},asHookType=(fn,inject,{skipIfHasType=!1}={})=>{if(!fn)return fn;if(!Array.isArray(fn)){if(skipIfHasType)fn.scope??=inject;else fn.scope=inject;return fn}for(let x of fn)if(skipIfHasType)x.scope??=inject;else x.scope=inject;return fn},filterGlobal=(fn)=>{if(!fn)return fn;if(!Array.isArray(fn))switch(fn.scope){case"global":case"scoped":return{...fn};default:return{fn}}let array=[];for(let x of fn)switch(x.scope){case"global":case"scoped":array.push({...x});break}return array},filterGlobalHook=(hook)=>{return{...hook,type:hook?.type,detail:hook?.detail,parse:filterGlobal(hook?.parse),transform:filterGlobal(hook?.transform),beforeHandle:filterGlobal(hook?.beforeHandle),afterHandle:filterGlobal(hook?.afterHandle),mapResponse:filterGlobal(hook?.mapResponse),afterResponse:filterGlobal(hook?.afterResponse),error:filterGlobal(hook?.error),trace:filterGlobal(hook?.trace)}},StatusMap={Continue:100,"Switching Protocols":101,Processing:102,"Early Hints":103,OK:200,Created:201,Accepted:202,"Non-Authoritative Information":203,"No Content":204,"Reset Content":205,"Partial Content":206,"Multi-Status":207,"Already Reported":208,"Multiple Choices":300,"Moved Permanently":301,Found:302,"See Other":303,"Not Modified":304,"Temporary Redirect":307,"Permanent Redirect":308,"Bad Request":400,Unauthorized:401,"Payment Required":402,Forbidden:403,"Not Found":404,"Method Not Allowed":405,"Not Acceptable":406,"Proxy Authentication Required":407,"Request Timeout":408,Conflict:409,Gone:410,"Length Required":411,"Precondition Failed":412,"Payload Too Large":413,"URI Too Long":414,"Unsupported Media Type":415,"Range Not Satisfiable":416,"Expectation Failed":417,"I'm a teapot":418,"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,manage)=>{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"){let hook=v(value);if(typeof hook==="object")for(let[k,v2]of Object.entries(hook))manage(k)({fn:v2})}delete property[key]}},createMacroManager=({globalHook,localHook})=>(stackName)=>(type,fn)=>{if(typeof type==="function")type={fn:type};if(stackName==="resolve")type={...type,subType:"resolve"};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,subType)=>{if(!fn)return fn;if(!Array.isArray(fn)){if(typeof fn==="function"||typeof fn==="string")return subType?{fn,subType}:{fn};else if("fn"in fn)return fn}let fns=[];for(let x of fn)if(typeof x==="function"||typeof x==="string")fns.push(subType?{fn:x,subType}:{fn:x});else if("fn"in x)fns.push(x);return fns},localHookToLifeCycleStore=(a)=>{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)=>{let hook={};if(a.start?.map)hook.start=a.start.map((x)=>x.fn);if(a.request?.map)hook.request=a.request.map((x)=>x.fn);if(a.parse?.map)hook.parse=a.parse.map((x)=>x.fn);if(a.transform?.map)hook.transform=a.transform.map((x)=>x.fn);if(a.beforeHandle?.map)hook.beforeHandle=a.beforeHandle.map((x)=>x.fn);if(a.afterHandle?.map)hook.afterHandle=a.afterHandle.map((x)=>x.fn);if(a.mapResponse?.map)hook.mapResponse=a.mapResponse.map((x)=>x.fn);if(a.afterResponse?.map)hook.afterResponse=a.afterResponse.map((x)=>x.fn);if(a.trace?.map)hook.trace=a.trace.map((x)=>x.fn);if(a.error?.map)hook.error=a.error.map((x)=>x.fn);if(a.stop?.map)hook.stop=a.stop.map((x)=>x.fn);return hook},cloneInference=(inference)=>({body:inference.body,cookie:inference.cookie,headers:inference.headers,query:inference.query,set:inference.set,server:inference.server,request:inference.request,route:inference.route}),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=()=>{let uuid=crypto.randomUUID();return uuid.slice(0,8)+uuid.slice(24,32)},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(!events)return;if(as==="scoped"){for(let event of events)if("scope"in event&&event.scope==="local")event.scope="scoped";return}for(let event of events)if("scope"in event)event.scope="global"},getLoosePath=(path)=>{if(path.charCodeAt(path.length-1)===47)return path.slice(0,path.length-1);return path+"/"},isNotEmpty=(obj)=>{if(!obj)return!1;for(let x in obj)return!0;return!1},isEmptyHookProperty=(prop)=>{if(Array.isArray(prop))return prop.length===0;return!prop},compressHistoryHook=(hook)=>{let history={...hook};if(isEmptyHookProperty(hook.afterHandle))delete history.afterHandle;if(isEmptyHookProperty(hook.afterResponse))delete history.afterResponse;if(isEmptyHookProperty(hook.beforeHandle))delete history.beforeHandle;if(isEmptyHookProperty(hook.error))delete history.error;if(isEmptyHookProperty(hook.mapResponse))delete history.mapResponse;if(isEmptyHookProperty(hook.parse))delete history.parse;if(isEmptyHookProperty(hook.request))delete history.request;if(isEmptyHookProperty(hook.start))delete history.start;if(isEmptyHookProperty(hook.stop))delete history.stop;if(isEmptyHookProperty(hook.trace))delete history.trace;if(isEmptyHookProperty(hook.transform))delete history.transform;if(!history.type)delete history.type;if(history.detail&&!Object.keys(history.detail).length)delete history.detail;if(!history.body)delete history.body;if(!history.cookie)delete history.cookie;if(!history.headers)delete history.headers;if(!history.query)delete history.query;if(!history.params)delete history.params;if(!history.response)delete history.response;return history};var encodePath=(path,{dynamic=!1}={})=>{let encoded=encodeURIComponent(path).replace(/%2F/g,"/");if(dynamic)encoded=encoded.replace(/%3A/g,":").replace(/%3F/g,"?");return encoded};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("Bad Request")}}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():Value2.Errors(validator,value).First(),customError=error2?.schema?.message||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):[...Value2.Errors(validator,value)].map(mapValueError),expected;try{expected=Value2.Create(schema)}catch(error3){expected={type:"Could not create expected value",message:error3?.message,error:error3}}message=JSON.stringify({type:"validation",on:type,summary:mapValueError(error2).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):[...Value2.Errors(this.validator,this.value)].map(mapValueError)}static simplifyModel(validator){let model="schema"in validator?validator.schema:validator;try{return Value2.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"}})}}import{TypeSystemPolicy,TypeSystem,TypeSystemDuplicateFormat,TypeSystemDuplicateTypeKind}from"@sinclair/typebox/system";import{TypeRegistry as TypeRegistry2,FormatRegistry as FormatRegistry2}from"@sinclair/typebox";import{TypeCompiler as TypeCompiler3,TypeCheck as TypeCheck2}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"))FormatRegistry.Set("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"))FormatRegistry.Set("date-time",(value)=>{let temp=value.replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDateTime(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});Object.entries(fullFormats).forEach((formatEntry)=>{let[formatName,formatValue]=formatEntry;if(!FormatRegistry.Has(formatName)){if(formatValue instanceof RegExp)FormatRegistry.Set(formatName,(value)=>formatValue.test(value));else if(typeof formatValue==="function")FormatRegistry.Set(formatName,formatValue)}});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},checkFileExtension=(type,extension)=>{if(type.startsWith(extension))return!0;return extension.charCodeAt(extension.length-1)===42&&extension.charCodeAt(extension.length-2)===47&&type.startsWith(extension.slice(0,-1))},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")return checkFileExtension(value.type,options.extension);for(let i=0;i<options.extension.length;i++)if(checkFileExtension(value.type,options.extension[i]))return!0;return!1}return!0},File2=getOrSetType("File",validateFile),Files=getOrSetType("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("integer"))FormatRegistry.Set("integer",(value)=>!!value&&Number.isInteger(+value));if(!FormatRegistry.Has("boolean"))FormatRegistry.Set("boolean",(value)=>value==="true"||value==="false");if(!FormatRegistry.Has("ObjectString"))FormatRegistry.Set("ObjectString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});if(!FormatRegistry.Has("ArrayString"))FormatRegistry.Set("ArrayString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});if(!TypeRegistry.Has("UnionEnum"))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&&!Value3.Check(schema,number))throw new ValidationError("property",schema,number);return number}).Encode((value)=>value)},Integer:(property)=>{let schema=Type.Integer(property);return t.Transform(t.Union([t.String({format:"integer",default:0}),Type.Integer(property)],property)).Decode((value)=>{let number=+value;if(!Value3.Check(schema,number))throw new ValidationError("property",schema,number);return number}).Encode((value)=>value)},Date:(property)=>{let schema=Type.Date(property),_default=property?.default?new Date(property.default):void 0;return t.Transform(t.Union([Type.Date(property),t.String({format:"date",default:_default?.toISOString()}),t.String({format:"date-time",default:_default?.toISOString()}),t.Number({default:_default?.getTime()})],property)).Decode((value)=>{if(typeof value==="number"){let date3=new Date(value);if(!Value3.Check(schema,date3))throw new ValidationError("property",schema,date3);return date3}if(value instanceof Date)return value;let date2=new Date(value);if(!date2||isNaN(date2.getTime()))throw new ValidationError("property",schema,date2);if(!Value3.Check(schema,date2))throw new ValidationError("property",schema,date2);return date2}).Encode((value)=>value.toISOString())},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&&!Value3.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(Value3.Create(schema)),compiler;try{compiler=TypeCompiler2.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(!Value3.Check(schema,value))throw new ValidationError("property",schema,value);return Value3.Decode(schema,value)}return value}).Encode((value)=>{if(typeof value==="string")try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(!Value3.Check(schema,value))throw new ValidationError("property",schema,value);return JSON.stringify(value)})},ArrayString:(children=t.String(),options)=>{let schema=t.Array(children,options),compiler;try{compiler=TypeCompiler2.Compile(schema)}catch{}let decode=(value,isProperty=!1)=>{if(value.charCodeAt(0)===91){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(!Value3.Check(schema,value))throw new ValidationError("property",schema,value);return Value3.Decode(schema,value)}if(value.indexOf(",")!==-1){let newValue=value.split(",").map((v)=>v.trim());if(compiler){if(!compiler.Check(newValue))throw new ValidationError("property",schema,value);return compiler.Decode(newValue)}if(!Value3.Check(schema,newValue))throw new ValidationError("property",schema,newValue);return Value3.Decode(schema,newValue)}if(isProperty)return value;throw new ValidationError("property",schema,value)};return t.Transform(t.Union([t.String({format:"ArrayString",default:options?.default}),schema])).Decode((value)=>{if(Array.isArray(value)){let values=[];for(let i=0;i<value.length;i++){let v=value[i];if(typeof v==="string"){let t2=decode(v,!0);if(Array.isArray(t2))values=values.concat(t2);else values.push(t2);continue}values.push(v)}return values}if(typeof value==="string")return decode(value);return value}).Encode((value)=>{if(typeof value==="string")try{value=JSON.parse(value)}catch{throw new ValidationError("property",schema,value)}if(!Value3.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,options)=>t.Union([schema,t.Null()],options),MaybeEmpty:(schema,options)=>t.Union([schema,t.Null(),t.Undefined()],options),Cookie:(properties,{domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign,...options}={})=>{let v=t.Object(properties,options);return v.config={domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign},v},UnionEnum:(values,options={})=>{let type=values.every((value)=>typeof value==="string")?{type:"string"}:values.every((value)=>typeof value==="number")?{type:"number"}:values.every((value)=>value===null)?{type:"null"}:{};if(values.some((x)=>typeof x==="object"&&x!==null))throw new Error("This type does not support objects or arrays");return{default:values[0],...options,[Kind2]:"UnionEnum",...type,enum:values}}};t.BooleanString=ElysiaType.BooleanString;t.ObjectString=ElysiaType.ObjectString;t.ArrayString=ElysiaType.ArrayString;t.Numeric=ElysiaType.Numeric;t.Integer=ElysiaType.Integer;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;function getOrSetType(kind,func){if(!TypeRegistry.Has(kind))TypeRegistry.Set(kind,func);return(options={})=>Unsafe({...options,[Kind2]:kind})}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(/^(\w+)=>/g.test(code)){if(index=code.indexOf("=>"),index!==-1){let body=code.slice(index+2);if(body.charCodeAt(0)===32)body=body.trimStart();return[code.slice(0,index),body,{isArrowReturn:body.charCodeAt(0)!==123}]}}if(code.startsWith("function")){index=code.indexOf("(");let end=code.indexOf(")");return[code.slice(index+1,end),code.slice(end+2),{isArrowReturn:!1}]}let start=code.indexOf("(");if(start!==-1){let sep=code.indexOf(`
3
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
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&&parameters.includes("query"))inference.query=!0;if(!inference.headers&&parameters.includes("headers"))inference.headers=!0;if(!inference.body&&parameters.includes("body"))inference.body=!0;if(!inference.cookie&&parameters.includes("cookie"))inference.cookie=!0;if(!inference.set&&parameters.includes("set"))inference.set=!0;if(!inference.server&&parameters.includes("server"))inference.server=!0;if(!inference.request&&parameters.includes("request"))inference.request=!0;if(!inference.route&&parameters.includes("route"))inference.route=!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)index=findEndIndex("="+type,content);if(index===-1){let lastIndex=content.indexOf(" = "+type);if(lastIndex===-1)lastIndex=content.indexOf("="+type);if(lastIndex+3+type.length!==content.length)break;index=lastIndex}let part=content.slice(0,index),lastPart=part.lastIndexOf(" "),variable=part.slice(lastPart!==-1?lastPart+1:-1);if(variable==="}"){let[start,end]=bracketPairRangeReverse(part);aliases.push(removeColonAlias(content.slice(start,end))),content=content.slice(index+3+type.length);continue}while(variable.charCodeAt(0)===44)variable=variable.slice(1);while(variable.charCodeAt(0)===9)variable=variable.slice(1);if(!variable.includes("("))aliases.push(variable);content=content.slice(index+3+type.length)}for(let alias of aliases){if(alias.charCodeAt(0)===123)continue;let deepAlias=findAlias(alias,body);if(deepAlias.length>0)aliases.push(...deepAlias)}return aliases},extractMainParameter=(parameter)=>{if(!parameter)return;if(parameter.charCodeAt(0)!==123)return parameter;if(parameter=parameter.slice(2,-2),!parameter.includes(",")){if(parameter.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&&parameters.includes("query"))inference.query=!0;if(!inference.headers&&parameters.includes("headers"))inference.headers=!0;if(!inference.body&&parameters.includes("body"))inference.body=!0;if(!inference.cookie&&parameters.includes("cookie"))inference.cookie=!0;if(!inference.set&&parameters.includes("set"))inference.set=!0;if(!inference.query&&parameters.includes("server"))inference.server=!0;if(!inference.request&&parameters.includes("request"))inference.request=!0;if(!inference.route&&parameters.includes("route"))inference.route=!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&&inference.server&&inference.route)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,inference.route=!0,inference.request=!0,!0;return!1}catch(error2){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,request:!1,route:!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;if(typeof event!=="function")continue;let[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&&inference.request&&inference.route)break}return inference};import{parse,serialize}from"cookie";var hex=[];for(let i=48;i<58;i++)hex[i]=i-48;for(let i=0;i<6;i++)hex[i+65]=hex[i+97]=i+10;var calcHex=(a,b)=>{if(a in hex&&b in hex)return hex[a]<<4|hex[b];return 255},type=[...new Array(128).fill(0),...new Array(16).fill(1),...new Array(16).fill(2),...new Array(32).fill(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],next=[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],mask=type.map((val)=>[127,63,63,63,0,31,15,15,15,7,7,7][val]),decode=(url)=>{let percentPosition=url.indexOf("%");if(percentPosition===-1)return url;let end=url.length-3;if(percentPosition>end)return null;let decoded="",start=0,codepoint=0,startOfOctets=percentPosition,state=12,byte2;for(;;){if(byte2=calcHex(url.charCodeAt(percentPosition+1),url.charCodeAt(percentPosition+2)),state=next[state+type[byte2]],state===0)return null;if(state===12){if(decoded+=url.substring(start,startOfOctets),codepoint=codepoint<<6|byte2&mask[byte2],codepoint>65535)decoded+=String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023));else decoded+=String.fromCharCode(codepoint);if(start=percentPosition+3,percentPosition=url.indexOf("%",start),percentPosition===-1)return decoded+url.substring(start);if(percentPosition>end)return null;startOfOctets=percentPosition,codepoint=0}else{if(percentPosition+=3,percentPosition>end||url.charCodeAt(percentPosition)!==37)return null;codepoint=codepoint<<6|byte2&mask[byte2]}}};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(_,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=parse(cookieString);for(let[name,v]of Object.entries(cookies)){if(v===void 0)continue;let value=decode(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)},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(serialize(key,typeof value==="object"?JSON.stringify(value):value+"",property))}if(set2.length===0)return;if(set2.length===1)return set2[0];return set2};var 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){if(set2.headers instanceof Headers){let setHeaders={"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"};if(hasHeaderShorthand)setHeaders=set2.headers.toJSON();else{setHeaders={};for(let[key,value]of set2.headers.entries())if(key in set2.headers)setHeaders[key]=value}return new Response(response,{status:set2.status,headers:setHeaders})}if(isNotEmpty(set2.headers))return new Response(response,{status:set2.status,headers:Object.assign({"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"},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},responseToSetHeaders=(response,set2)=>{if(set2?.headers){if(response){if(hasHeaderShorthand)Object.assign(set2.headers,response.headers.toJSON());else for(let[key,value]of response.headers.entries())if(key in set2.headers)set2.headers[key]=value}if(set2.status===200)set2.status=response.status;if(set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}if(!response)return{headers:{},status:set2?.status??200};if(hasHeaderShorthand){if(set2={headers:response.headers.toJSON(),status:set2?.status??200},set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}set2={headers:{},status:set2?.status??200};for(let[key,value]of response.headers.entries()){if(key==="content-encoding")continue;if(key in set2.headers)set2.headers[key]=value}return set2},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)}if(set2?.headers){if(!set2.headers["transfer-encoding"])set2.headers["transfer-encoding"]="chunked";if(!set2.headers["content-type"])set2.headers["content-type"]="text/event-stream; charset=utf-8"}else set2={status:200,headers:{"content-type":"text/event-stream; charset=utf-8","transfer-encoding":"chunked"}};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)};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 handleSet=(set2)=>{if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"])},mergeResponseWithSetHeaders=(response,set2)=>{if(response.status!==set2.status&&set2.status!==200&&(response.status<=300||response.status>400))response=new Response(response.body,{headers:response.headers,status:set2.status});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]);return response},mapResponse=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return Response.json(response,set2);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(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&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);case void 0:if(!response)return new Response("",set2);return Response.json(response,set2);case"Response":if(response=mergeResponseWithSetHeaders(response,set2),!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);return response;case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>mapResponse(x,set2,request));case"Function":return mapResponse(response(),set2,request);case"Number":case"Boolean":return new Response(response.toString(),set2);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response,set2);default:if(response instanceof Response){if(response=mergeResponseWithSetHeaders(response,set2),response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);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)}if(response instanceof Response&&!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);return mapCompactResponse(response,request)},mapEarlyResponse=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return Response.json(response,set2);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(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&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);case void 0:if(!response)return;return Response.json(response,set2);case"Response":if(response=mergeResponseWithSetHeaders(response,set2),!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);return response;case"Promise":return response.then((x)=>mapEarlyResponse(x,set2));case"Error":return errorToResponse(response,set2);case"Function":return mapEarlyResponse(response(),set2);case"Number":case"Boolean":return new Response(response.toString(),set2);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);default:if(response instanceof Response){if(response=mergeResponseWithSetHeaders(response,set2),response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);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"Array":case"Object":return Response.json(response,set2);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(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&&!request?.signal?.aborted)response.cancel()}},{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.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response),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 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"Object":case"Array":return Response.json(response);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{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),responseToSetHeaders(response),request);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=(error2,set2)=>new Response(JSON.stringify({name:error2?.name,message:error2?.message,cause:error2?.cause}),{status:set2?.status!==200?set2?.status??500:500,headers:set2?.headers}),createStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return response.clone.bind(response)};var WebStandardAdapter={name:"web-standard",isWebStandard:!0,handler:{mapResponse,mapEarlyResponse,mapCompactResponse,createStaticHandler},composeHandler:{mapResponseContext:"c.request",preferWebstandardHeaders:!0,headers:`c.headers = {}
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)index=findEndIndex("="+type,content);if(index===-1){let lastIndex=content.indexOf(" = "+type);if(lastIndex===-1)lastIndex=content.indexOf("="+type);if(lastIndex+3+type.length!==content.length)break;index=lastIndex}let part=content.slice(0,index),lastPart=part.lastIndexOf(" "),variable=part.slice(lastPart!==-1?lastPart+1:-1);if(variable==="}"){let[start,end]=bracketPairRangeReverse(part);aliases.push(removeColonAlias(content.slice(start,end))),content=content.slice(index+3+type.length);continue}while(variable.charCodeAt(0)===44)variable=variable.slice(1);while(variable.charCodeAt(0)===9)variable=variable.slice(1);if(!variable.includes("("))aliases.push(variable);content=content.slice(index+3+type.length)}for(let alias of aliases){if(alias.charCodeAt(0)===123)continue;let deepAlias=findAlias(alias,body);if(deepAlias.length>0)aliases.push(...deepAlias)}return aliases},extractMainParameter=(parameter)=>{if(!parameter)return;if(parameter.charCodeAt(0)!==123)return parameter;if(parameter=parameter.slice(2,-2),!parameter.includes(",")){if(parameter.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&&parameters.includes("query"))inference.query=!0;if(!inference.headers&&parameters.includes("headers"))inference.headers=!0;if(!inference.body&&parameters.includes("body"))inference.body=!0;if(!inference.cookie&&parameters.includes("cookie"))inference.cookie=!0;if(!inference.set&&parameters.includes("set"))inference.set=!0;if(!inference.query&&parameters.includes("server"))inference.server=!0;if(!inference.request&&parameters.includes("request"))inference.request=!0;if(!inference.route&&parameters.includes("route"))inference.route=!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&&inference.server&&inference.route)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,inference.route=!0,inference.request=!0,!0;return!1}catch(error2){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,request:!1,route:!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;if(typeof event!=="function")continue;let[parameter,body,{isArrowReturn}]=separateFunction(event.toString()),rootParameters=findParameterReference(parameter,inference),mainParameter=extractMainParameter(rootParameters);if(mainParameter){let aliases=findAlias(mainParameter,body.slice(1,-1));aliases.splice(0,-1,mainParameter);let code=body;if(code.charCodeAt(0)===123&&code.charCodeAt(body.length-1)===125)code=code.slice(1,-1);if(!isContextPassToFunction(mainParameter,code,inference))inferBodyReference(code,aliases,inference);if(!inference.query&&code.includes("return "+mainParameter+".query"))inference.query=!0}if(inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server&&inference.request&&inference.route)break}return inference};import{parse,serialize}from"cookie";var hex=[];for(let i=48;i<58;i++)hex[i]=i-48;for(let i=0;i<6;i++)hex[i+65]=hex[i+97]=i+10;var calcHex=(a,b)=>{if(a in hex&&b in hex)return hex[a]<<4|hex[b];return 255},type=[...new Array(128).fill(0),...new Array(16).fill(1),...new Array(16).fill(2),...new Array(32).fill(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],next=[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],mask=type.map((val)=>[127,63,63,63,0,31,15,15,15,7,7,7][val]),decode=(url)=>{let percentPosition=url.indexOf("%");if(percentPosition===-1)return url;let end=url.length-3;if(percentPosition>end)return null;let decoded="",start=0,codepoint=0,startOfOctets=percentPosition,state=12,byte2;for(;;){if(byte2=calcHex(url.charCodeAt(percentPosition+1),url.charCodeAt(percentPosition+2)),state=next[state+type[byte2]],state===0)return null;if(state===12){if(decoded+=url.substring(start,startOfOctets),codepoint=codepoint<<6|byte2&mask[byte2],codepoint>65535)decoded+=String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023));else decoded+=String.fromCharCode(codepoint);if(start=percentPosition+3,percentPosition=url.indexOf("%",start),percentPosition===-1)return decoded+url.substring(start);if(percentPosition>end)return null;startOfOctets=percentPosition,codepoint=0}else{if(percentPosition+=3,percentPosition>end||url.charCodeAt(percentPosition)!==37)return null;codepoint=codepoint<<6|byte2&mask[byte2]}}};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(_,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=parse(cookieString);for(let[name,v]of Object.entries(cookies)){if(v===void 0)continue;let value=decode(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)},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(serialize(key,typeof value==="object"?JSON.stringify(value):value+"",property))}if(set2.length===0)return;if(set2.length===1)return set2[0];return set2};var 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){if(set2.headers instanceof Headers){let setHeaders={"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"};if(hasHeaderShorthand)setHeaders=set2.headers.toJSON();else{setHeaders={};for(let[key,value]of set2.headers.entries())if(key in set2.headers)setHeaders[key]=value}return new Response(response,{status:set2.status,headers:setHeaders})}if(isNotEmpty(set2.headers))return new Response(response,{status:set2.status,headers:Object.assign({"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"},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},responseToSetHeaders=(response,set2)=>{if(set2?.headers){if(response){if(hasHeaderShorthand)Object.assign(set2.headers,response.headers.toJSON());else for(let[key,value]of response.headers.entries())if(key in set2.headers)set2.headers[key]=value}if(set2.status===200)set2.status=response.status;if(set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}if(!response)return{headers:{},status:set2?.status??200};if(hasHeaderShorthand){if(set2={headers:response.headers.toJSON(),status:set2?.status??200},set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}set2={headers:{},status:set2?.status??200};for(let[key,value]of response.headers.entries()){if(key==="content-encoding")continue;if(key in set2.headers)set2.headers[key]=value}return set2},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)}if(set2?.headers){if(!set2.headers["transfer-encoding"])set2.headers["transfer-encoding"]="chunked";if(!set2.headers["content-type"])set2.headers["content-type"]="text/event-stream; charset=utf-8"}else set2={status:200,headers:{"content-type":"text/event-stream; charset=utf-8","transfer-encoding":"chunked"}};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)};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 handleSet=(set2)=>{if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"])},mergeResponseWithSetHeaders=(response,set2)=>{if(response.status!==set2.status&&set2.status!==200&&(response.status<=300||response.status>400))response=new Response(response.body,{headers:response.headers,status:set2.status});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]);return response},mapResponse=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return Response.json(response,set2);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(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&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);case void 0:if(!response)return new Response("",set2);return Response.json(response,set2);case"Response":if(response=mergeResponseWithSetHeaders(response,set2),!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);return response;case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>mapResponse(x,set2,request));case"Function":return mapResponse(response(),set2,request);case"Number":case"Boolean":return new Response(response.toString(),set2);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response,set2);default:if(response instanceof Response){if(response=mergeResponseWithSetHeaders(response,set2),response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);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)}if(response instanceof Response&&!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);return mapCompactResponse(response,request)},mapEarlyResponse=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return Response.json(response,set2);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(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&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);case void 0:if(!response)return;return Response.json(response,set2);case"Response":if(response=mergeResponseWithSetHeaders(response,set2),!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);return response;case"Promise":return response.then((x)=>mapEarlyResponse(x,set2));case"Error":return errorToResponse(response,set2);case"Function":return mapEarlyResponse(response(),set2);case"Number":case"Boolean":return new Response(response.toString(),set2);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);default:if(response instanceof Response){if(response=mergeResponseWithSetHeaders(response,set2),response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);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"Array":case"Object":return Response.json(response,set2);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(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&&!request?.signal?.aborted)response.cancel()}},{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.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response),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 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"Object":case"Array":return Response.json(response);case"ElysiaFile":return handleFile(response.value);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{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),responseToSetHeaders(response),request);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=(error2,set2)=>new Response(JSON.stringify({name:error2?.name,message:error2?.message,cause:error2?.cause}),{status:set2?.status!==200?set2?.status??500:500,headers:set2?.headers}),createStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return response.clone.bind(response)};var WebStandardAdapter={name:"web-standard",isWebStandard:!0,handler:{mapResponse,mapEarlyResponse,mapCompactResponse,createStaticHandler},composeHandler:{mapResponseContext:"c.request",preferWebstandardHeaders:!0,headers:`c.headers = {}
6
6
  for (const [key, value] of c.request.headers.entries())c.headers[key] = value
7
7
  `,parser:{json(isOptional){if(isOptional)return`try{c.body=await c.request.json()}catch{}
8
8
  `;return`c.body=await c.request.json()
@@ -27,7 +27,7 @@ if(route){c.params=route.params
27
27
  if(route.store.handler)return route.store.handler(c)
28
28
  return (route.store.handler=route.store.compile())(c)}}break}}`}return fnLiteral},error404(hasEventHook,hasErrorHook){let findDynamicRoute="if(route===null)return ";if(hasErrorHook)findDynamicRoute+=`app.handleError(c,notFound,false,${this.parameters})`;else findDynamicRoute+=hasEventHook?"new Response(error404Message,{status:c.set.status===200?404:c.set.status,headers:c.set.headers})":"error404.clone()";return{declare:hasErrorHook?"":`const error404Message=notFound.message.toString()
29
29
  const error404=new Response(error404Message,{status:404})
30
- `,code:findDynamicRoute}}},composeError:{mapResponseContext:"",validationError:"return new Response(error.message,{headers:Object.assign({'content-type':'application/json'},set.headers),status:set.status})",unknownError:"return new Response(error.message,{headers:set.headers,status:error.status??set.status??500})"},listen(){return()=>{throw new Error("WebStandard does not support listen, you might want to export default Elysia.fetch instead")}}};var createNativeStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function"||handle instanceof Blob)return;if(typeof handle==="object"&&handle?.toString()==="[object HTMLBundle]")return()=>handle;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length){if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain;charset=utf-8");return response.clone.bind(response)}};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;body;validator;["~types"];get id(){return this.data.id}constructor(raw,data,body=void 0){this.raw=raw;this.data=data;this.body=body;this.validator=raw.data?.validator,this.sendText=raw.sendText.bind(raw),this.sendBinary=raw.sendBinary.bind(raw),this.close=raw.close.bind(raw),this.terminate=raw.terminate.bind(raw),this.publishText=raw.publishText.bind(raw),this.publishBinary=raw.publishBinary.bind(raw),this.subscribe=raw.subscribe.bind(raw),this.unsubscribe=raw.unsubscribe.bind(raw),this.isSubscribed=raw.isSubscribed.bind(raw),this.cork=raw.cork.bind(raw),this.remoteAddress=raw.remoteAddress,this.binaryType=raw.binaryType,this.data=raw.data,this.send=this.send.bind(this),this.ping=this.ping.bind(this),this.pong=this.pong.bind(this),this.publish=this.publish.bind(this)}send(data,compress){if(Buffer.isBuffer(data))return this.raw.send(data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data,compress)}ping(data){if(Buffer.isBuffer(data))return this.raw.ping(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.ping(data)}pong(data){if(Buffer.isBuffer(data))return this.raw.pong(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.pong(data)}publish(topic,data,compress){if(Buffer.isBuffer(data))return this.raw.publish(topic,data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress)}sendText;sendBinary;close;terminate;publishText;publishBinary;subscribe;unsubscribe;isSubscribed;cork;remoteAddress;binaryType;get readyState(){return this.raw.readyState}}var createWSMessageParser=(parse2)=>{let parsers=typeof parse2==="function"?[parse2]:parse2;return async function parseMessage(ws,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(parsers)for(let i=0;i<parsers.length;i++){let temp=parsers[i](ws,message);if(temp instanceof Promise)temp=await temp;if(temp!==void 0)return temp}return message}},createHandleWSResponse=(validateResponse)=>{let handleWSResponse=(ws,data)=>{if(data instanceof Promise)return data.then((data2)=>handleWSResponse(ws,data2));if(Buffer.isBuffer(data))return ws.send(data.toString());if(data===void 0)return;let send=(datum)=>{if(validateResponse?.Check(datum)===!1)return ws.send(new ValidationError("message",validateResponse,datum).message);if(typeof datum==="object")return ws.send(JSON.stringify(datum));ws.send(datum)};if(typeof data?.next!=="function")return void send(data);let init=data.next();if(init instanceof Promise)return(async()=>{let first=await init;if(validateResponse?.Check(first)===!1)return ws.send(new ValidationError("message",validateResponse,first).message);if(send(first.value),!first.done)for await(let datum of data)send(datum)})();if(send(init.value),!init.done)for(let datum of data)send(datum)};return handleWSResponse};var BunAdapter={...WebStandardAdapter,name:"bun",handler:{...WebStandardAdapter.handler,createNativeStaticHandler},composeHandler:{...WebStandardAdapter.composeHandler,headers:hasHeaderShorthand?`c.headers = c.request.headers.toJSON()
30
+ `,code:findDynamicRoute}}},composeError:{mapResponseContext:"",validationError:"return new Response(error.message,{headers:Object.assign({'content-type':'application/json'},set.headers),status:set.status})",unknownError:"return new Response(error.message,{headers:set.headers,status:error.status??set.status??500})"},listen(){return()=>{throw new Error("WebStandard does not support listen, you might want to export default Elysia.fetch instead")}}};var createNativeStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function"||handle instanceof Blob)return;if(typeof handle==="object"&&handle?.toString()==="[object HTMLBundle]")return()=>handle;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length){if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain;charset=utf-8");return response.clone.bind(response)}};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;body;validator;["~types"];get id(){return this.data.id}constructor(raw,data,body=void 0){this.raw=raw;this.data=data;this.body=body;this.validator=raw.data?.validator,this.sendText=raw.sendText.bind(raw),this.sendBinary=raw.sendBinary.bind(raw),this.close=raw.close.bind(raw),this.terminate=raw.terminate.bind(raw),this.publishText=raw.publishText.bind(raw),this.publishBinary=raw.publishBinary.bind(raw),this.subscribe=raw.subscribe.bind(raw),this.unsubscribe=raw.unsubscribe.bind(raw),this.isSubscribed=raw.isSubscribed.bind(raw),this.cork=raw.cork.bind(raw),this.remoteAddress=raw.remoteAddress,this.binaryType=raw.binaryType,this.data=raw.data,this.send=this.send.bind(this),this.ping=this.ping.bind(this),this.pong=this.pong.bind(this),this.publish=this.publish.bind(this)}send(data,compress){if(Buffer.isBuffer(data))return this.raw.send(data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data,compress)}ping(data){if(Buffer.isBuffer(data))return this.raw.ping(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.ping(data)}pong(data){if(Buffer.isBuffer(data))return this.raw.pong(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.pong(data)}publish(topic,data,compress){if(Buffer.isBuffer(data))return this.raw.publish(topic,data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress)}sendText;sendBinary;close;terminate;publishText;publishBinary;subscribe;unsubscribe;isSubscribed;cork;remoteAddress;binaryType;get readyState(){return this.raw.readyState}}var createWSMessageParser=(parse2)=>{let parsers=typeof parse2==="function"?[parse2]:parse2;return async function parseMessage(ws,message){if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===34||start===47||start===91||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message;else if(message==="true")message=!0;else if(message==="false")message=!1;else if(message==="null")message=null}if(parsers)for(let i=0;i<parsers.length;i++){let temp=parsers[i](ws,message);if(temp instanceof Promise)temp=await temp;if(temp!==void 0)return temp}return message}},createHandleWSResponse=(validateResponse)=>{let handleWSResponse=(ws,data)=>{if(data instanceof Promise)return data.then((data2)=>handleWSResponse(ws,data2));if(Buffer.isBuffer(data))return ws.send(data.toString());if(data===void 0)return;let send=(datum)=>{if(validateResponse?.Check(datum)===!1)return ws.send(new ValidationError("message",validateResponse,datum).message);if(typeof datum==="object")return ws.send(JSON.stringify(datum));ws.send(datum)};if(typeof data?.next!=="function")return void send(data);let init=data.next();if(init instanceof Promise)return(async()=>{let first=await init;if(validateResponse?.Check(first)===!1)return ws.send(new ValidationError("message",validateResponse,first).message);if(send(first.value),!first.done)for await(let datum of data)send(datum)})();if(send(init.value),!init.done)for(let datum of data)send(datum)};return handleWSResponse};var BunAdapter={...WebStandardAdapter,name:"bun",handler:{...WebStandardAdapter.handler,createNativeStaticHandler},composeHandler:{...WebStandardAdapter.composeHandler,headers:hasHeaderShorthand?`c.headers = c.request.headers.toJSON()
31
31
  `:`c.headers = {}
32
32
  for (const [key, value] of c.request.headers.entries())c.headers[key] = value
33
33
  `},listen(app){return(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(app.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let fetch=app.fetch,serve=typeof options==="object"?{development:!isProduction,reusePort:!0,...app.config.serve||{},...options||{},static:{...app.router.static.http.static,...app.config.serve?.static},websocket:{...app.config.websocket||{},...websocket||{}},fetch,error:app.outerErrorHandler}:{development:!isProduction,reusePort:!0,...app.config.serve||{},static:app.router.static.http.static,websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch,error:app.outerErrorHandler};if(app.server=Bun?.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",()=>{if(app.server){if(app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(()=>{Bun?.gc(!1)})}},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,validateMessage=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateResponse=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("$INTERNALWS",path,async(context)=>{let server=app.getServer(),{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=validateResponse,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse=createHandleWSResponse(validateResponse),parseMessage=createWSMessageParser(parse2),_id,errorHandlers=[...Array.isArray(options.error)?options.error:[options.error],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)],handleErrors=!errorHandlers.length?()=>{}:async(ws,error2)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error:error2}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:validateResponse,ping(data){options.ping?.(data)},pong(data){options.pong?.(data)},open(ws){try{handleResponse(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);try{handleResponse(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error2){handleErrors(ws,error2)}},drain(ws){try{handleResponse(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},close(ws,code,reason){try{handleResponse(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error2){handleErrors(ws,error2)}}}}))return;return set2.status=400,"Expected a websocket connection"},{...rest,websocket:options})}};var isBun2=typeof Bun!=="undefined";var env2=isBun2?Bun.env:typeof process!=="undefined"&&process?.env?process.env:{};import{Value as Value4}from"@sinclair/typebox/value";import{Kind as Kind3,TypeBoxError}from"@sinclair/typebox";var 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=decode(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=decode(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=decode(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,l),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=decode(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=decode(key)||key;if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),valueHasPlus)value=value.replace(plusRegex," ");if(shouldDecodeValue)value=decode(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 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 TypeBoxSymbol={optional:Symbol.for("TypeBox.Optional"),kind:Symbol.for("TypeBox.Kind")},isOptional=(validator)=>{if(!validator)return!1;let schema=validator?.schema;if(schema?.[TypeBoxSymbol.kind]==="Import")return validator.References().some(isOptional);return!!schema&&TypeBoxSymbol.optional in schema},allocateIf=(value,condition)=>condition?value:"",defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema[TypeBoxSymbol.kind]==="Import"&&_schema.References())return _schema.References().some(hasAdditionalProperties);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});
@@ -40,11 +40,11 @@ for (const [key, value] of c.request.headers.entries())c.headers[key] = value
40
40
  ${name}=${name}.response}const isResponse=${name} instanceof Response
41
41
  switch(c.set.status){`;for(let[status,value]of Object.entries(validator.response)){if(code+=`
42
42
  case ${status}:if(!isResponse){`,normalize&&"Clean"in value&&!hasAdditionalProperties(value))code+=`${name}=validator.response['${status}'].Clean(${name})
43
- `;if(code+=`if(validator.response['${status}'].Check(${name})===false){c.set.status=422
43
+ `;if(encodeSchema&&(value.hasTransform||typeof value.Decode==="function"))code+=`${name}=validator.response['${status}'].Encode(${name})
44
+ `;code+=`if(validator.response['${status}'].Check(${name})===false){c.set.status=422
44
45
  throw new ValidationError('response',validator.response['${status}'],${name})}c.set.status = ${status}}
45
- `,encodeSchema&&(value.hasTransform||typeof value.Decode==="function"))code+=`${name}=validator.response['${status}'].Encode(${name})
46
- `;code+=`break
47
- `}return code+"}"}}),KindSymbol=Symbol.for("TypeBox.Kind");var hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[TypeBoxSymbol.kind]==="Import")return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));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");var hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs)return hasTransform(schema.$defs[schema.$ref]);if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}return!1}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;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;if(literal.includes("=>response.clone("))return!1;return!!literal.match(matchFnReturn)},isGenerator=(v)=>{let fn=v?.fn??v;return fn.constructor.name==="AsyncGeneratorFunction"||fn.constructor.name==="GeneratorFunction"},composeHandler=({app,path,method,hooks,validator,handler,allowMeta=!1,inference,asManifest=!1})=>{let adapter=app["~adapter"].composeHandler,adapterHandler=app["~adapter"].handler,isHandleFn=typeof handler==="function";if(!isHandleFn){if(handler=adapterHandler.mapResponse(handler,{headers:app.setHeaders??{}}),hooks.parse?.length&&hooks.transform?.length&&hooks.beforeHandle?.length&&hooks.afterHandle?.length){if(handler instanceof Response)return Function("a","return function(){return a.clone()}")(handler);return Function("a","return function(){return a}")(handler)}}let handle=isHandleFn?"handler(c)":"handler",hasAfterResponse=!!hooks.afterResponse?.length,hasTrace=!!hooks.trace?.length,fnLiteral="";if(inference=sucrose(Object.assign({},hooks,{handler}),inference),adapter.declare){let literal=adapter.declare(inference);if(literal)fnLiteral+=literal}if(inference.server)fnLiteral+=`Object.defineProperty(c,'server',{get:function(){return getServer()}})
46
+ `,code+=`break
47
+ `}return code+"}"}}),KindSymbol=Symbol.for("TypeBox.Kind");var hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[TypeBoxSymbol.kind]==="Import")return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));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");var hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformSymbol in schema},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;if(literal.includes("=>response.clone("))return!1;return!!literal.match(matchFnReturn)},isGenerator=(v)=>{let fn=v?.fn??v;return fn.constructor.name==="AsyncGeneratorFunction"||fn.constructor.name==="GeneratorFunction"},composeHandler=({app,path,method,hooks,validator,handler,allowMeta=!1,inference,asManifest=!1})=>{let adapter=app["~adapter"].composeHandler,adapterHandler=app["~adapter"].handler,isHandleFn=typeof handler==="function";if(!isHandleFn){if(handler=adapterHandler.mapResponse(handler,{headers:app.setHeaders??{}}),hooks.parse?.length&&hooks.transform?.length&&hooks.beforeHandle?.length&&hooks.afterHandle?.length){if(handler instanceof Response)return Function("a","return function(){return a.clone()}")(handler);return Function("a","return function(){return a}")(handler)}}let handle=isHandleFn?"handler(c)":"handler",hasAfterResponse=!!hooks.afterResponse?.length,hasTrace=!!hooks.trace?.length,fnLiteral="";if(inference=sucrose(Object.assign({},hooks,{handler}),inference),adapter.declare){let literal=adapter.declare(inference);if(literal)fnLiteral+=literal}if(inference.server)fnLiteral+=`Object.defineProperty(c,'server',{get:function(){return getServer()}})
48
48
  `;validator.createBody?.(),validator.createQuery?.(),validator.createHeaders?.(),validator.createParams?.(),validator.createCookie?.(),validator.createResponse?.();let hasValidation=validator.body||validator.headers||validator.params||validator.query||validator.cookie||validator.response,hasQuery=inference.query||!!validator.query,requestNoBody=hooks.parse?.length===1&&hooks.parse[0].fn==="none",hasBody=method!=="$INTERNALWS"&&method!=="GET"&&method!=="HEAD"&&(inference.body||!!validator.body||!!hooks.parse?.length)&&!requestNoBody;if(hasBody)fnLiteral+=`let isParsing=false
49
49
  `;let defaultHeaders=app.setHeaders,hasDefaultHeaders=defaultHeaders&&!!Object.keys(defaultHeaders).length,hasHeaders=inference.headers||validator.headers||adapter.preferWebstandardHeaders!==!0&&inference.body,hasCookie=inference.cookie||!!validator.cookie,cookieValidator=hasCookie?getCookieValidator({modules:app.definitions.typebox,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
50
50
  if(_setCookie){`,cookieMeta.sign===!0)encodeCookie+=`for(const [key, cookie] of Object.entries(_setCookie)){c.set.cookie[key].value=await signCookie(cookie.value,'${secret}')}`;else for(let name of cookieMeta.sign)encodeCookie+=`if(_setCookie['${name}']?.value){c.set.cookie['${name}'].value=await signCookie(_setCookie['${name}'].value,'${secret}')}`;encodeCookie+=`}
@@ -324,4 +324,4 @@ return mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}`,Func
324
324
  `;else staticRouter.map[path].code=`case '${method}':return ht[${index}].composed(${ctx})
325
325
  ${staticRouter.map[path].code}`;if(!this.config.strictPath&&this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[getLoosePath(path)]=nativeStaticHandler()}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);if(this.config.nativeStaticResponse===!0&&staticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[loosePath]=staticHandler();this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded){if(this.router.http.add(method,encoded,handler),this.config.nativeStaticResponse===!0&&staticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[encoded]=staticHandler();this.router.http.add(method,encoded,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){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,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 type2;switch(typeof optionsOrType){case"string":type2=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type2=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type2==="resolve"||type2==="derive")handle.subType=type2;if(type2!=="trace")sucrose({[type2]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type2){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}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(type2){let castType={plugin:"scoped",scoped:"scoped",global:"global"}[type2];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),type2==="plugin")this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null;else if(type2==="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 type2=hook.as??"local";if(this.validator[type2]={body:hook.body??this.validator[type2]?.body,headers:hook.headers??this.validator[type2]?.headers,params:hook.params??this.validator[type2]?.params,query:hook.query??this.validator[type2]?.query,response:hook.response??this.validator[type2]?.response,cookie:hook.cookie??this.validator[type2]?.cookie},hook.parse)this.on({as:type2},"parse",hook.parse);if(hook.transform)this.on({as:type2},"transform",hook.transform);if(hook.derive)this.on({as:type2},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type2},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type2},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type2},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type2},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type2},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type2},"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(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}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(plugin2.constructor.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error2){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error2}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.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}));if(plugin2.compile(),plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let{name,seed}=plugin.config;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.model(this.definitions.type),plugin.error(this.definitions.error),this["~parser"]={...plugin["~parser"],...this["~parser"]},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,request:this.inference.request||plugin.inference.request,route:this.inference.route||plugin.inference.route},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(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,stack:plugin.telemetry.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:new Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),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){if(typeof macro==="function"){let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:macro.toString()})),fn:macro};this.extender.macros.push(hook)}else if(typeof macro==="object"){for(let name of Object.keys(macro))if(typeof macro[name]==="object"){let actualValue={...macro[name]};macro[name]=(v)=>{if(v===!0)return actualValue}}let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:Object.entries(macro).map(([k,v])=>`${k}+${v}`).join(",")})),fn:()=>macro};this.extender.macros.push(hook)}return 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=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.all("/*",handler2,{parse:"none"}),this}if(!handle)return this;let length=path.length-(path.endsWith("*")?1:0);if(handle instanceof Elysia)handle=handle.compile().fetch;let handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.all(path,handler,{parse:"none"}),this.all(path+(path.endsWith("/")?"*":"/*"),handler,{parse:"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){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){let coerce=(schema)=>replaceSchemaType(schema,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0}]);switch(typeof name){case"object":let parsedSchemas={},kvs=Object.entries(name);for(let[key,value]of kvs){if(key in this.definitions.type)continue;parsedSchemas[key]=this.definitions.type[key]=coerce(value),parsedSchemas[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedSchemas}),this;case"function":let result=coerce(name(this.definitions.type));return this.definitions.type=result,this.definitions.typebox=t.Module(result),this;case"string":if(!model)break;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[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,type2,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=(type3)=>{let store={};switch(type3){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(type2)?type2:[type2];for(let type3 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type3);return this}prefix(type2,word){return this.affix("prefix",type2,word)}suffix(type2,word){return this.affix("suffix",type2,word)}compile(){if(this["~adapter"].isWebStandard){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}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error2)=>{return(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)=>{return this["~adapter"].listen(this)(options,callback),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 this.promisedModules}}export{t,serializeCookie,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,file,error,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidCookieSignature,InternalServerError,ElysiaFile,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
326
326
 
327
- //# debugId=7B771E2CCAD9D44064756E2164756E21
327
+ //# debugId=B27DE94378765A2E64756E2164756E21