elysia 1.2.16 → 1.2.18

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
@@ -320,8 +320,8 @@ if(!context.response)context.response=error.message??error
320
320
  `;for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse2=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`if(mr===undefined){mr=${isAsyncName(mapResponse2)?"await ":""}onMapResponse[${i}](context)
321
321
  if(mr!==undefined)error=context.response=mr}`,endUnit()}}return mapResponseReporter.resolve(),fnLiteral+=`
322
322
  return mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}`,Function("inject",fnLiteral)({app,mapResponse:app["~adapter"].handler.mapResponse,ERROR_CODE,ElysiaCustomStatusResponse,ELYSIA_TRACE:hasTrace?ELYSIA_TRACE:void 0,ELYSIA_REQUEST_ID:hasTrace?ELYSIA_REQUEST_ID:void 0,...adapter.inject})};import{TransformDecodeError}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{for(let[key,keySchema]of Object.entries(typeChecker.schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse2,mapEarlyResponse:mapEarlyResponse2}=app["~adapter"].handler;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set2={cookie:{},status:200,headers:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,error,redirect});try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse2(response2,set2),response2)return context.response=response2}let handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find("ALL",path);if(!handler)throw new NotFoundError;let{handle,hooks,validator,content,route}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}else{let contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn,temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta=Object.assign({},app.config?.cookie,validator?.cookie?.config),cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta?{secrets:cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets.join(","):void 0,sign:cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?typeof cookieMeta.sign==="string"?cookieMeta.sign:cookieMeta.sign.join(","):void 0}:void 0);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],operation=hook.fn(context);if(hook.subType==="derive")if(operation instanceof Promise)Object.assign(context,await operation);else Object.assign(context,operation);else if(operation instanceof Promise)await operation}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(hook.subType==="resolve"){if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse2(response2,context.set);if(result)return context.response=result}if(response2 instanceof Promise)Object.assign(context,await response2);else Object.assign(context,response2);continue}else if(response2 instanceof Promise)response2=await response2;if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse2(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(hooks.afterHandle)if(!hooks.afterHandle.length){let status=response instanceof ElysiaCustomStatusResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200,responseValidator=validator?.createResponse?.()?.[status];if(responseValidator?.Check(response)===!1)throw new ValidationError("response",responseValidator,response);else if(responseValidator?.Decode)response=responseValidator.Decode(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let newResponse=hooks.afterHandle[i].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;let result=mapEarlyResponse2(newResponse,context.set);if(result!==void 0){let responseValidator=validator?.response?.[result.status];if(responseValidator?.Check(result)===!1)throw new ValidationError("response",responseValidator,result);else if(responseValidator?.Decode)response=responseValidator.Decode(response);return context.response=result}}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,"${secret}");else{let properties=validator?.cookie?.schema?.properties;for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse2(context.response=response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;return app.handleError(context,reportedError)}finally{if(app.event.afterResponse)for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse2}=app["~adapter"].handler;return async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});if(errorContext.set=context.set,app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse2(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})}};var mime={aac:"audio/aac",abw:"application/x-abiword",ai:"application/postscript",arc:"application/octet-stream",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",dll:"application/octet-stream",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",mid:"audio/midi",midi:"audio/midi",mp2:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mpa:"video/mpeg",mpe:"video/mpeg",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",otf:"font/otf",png:"image/png",pdf:"application/pdf",ppt:"application/vnd.ms-powerpoint",rar:"application/x-rar-compressed",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"application/typescript",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/x-wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xlsx_OLD:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3gp_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp","3gp2":"video/3gpp2","3gp2_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp2","7z":"application/x-7z-compressed"},getFileExtension=(path)=>{let index=path.lastIndexOf(".");if(index===-1)return"";return path.slice(index+1)},file=(path)=>new ElysiaFile(path),createReadStream,stat;class ElysiaFile{path;value;stats;constructor(path){this.path=path;if(isBun2)this.value=Bun.file(path);else if(typeof window!=="undefined")console.warn("Browser environment does not support file");else if(!createReadStream||!stat)try{this.value=import("fs").then((fs)=>{return createReadStream=fs.createReadStream,fs.createReadStream(path)}),this.stats=import("fs/promises").then((fs)=>{return stat=fs.stat,fs.stat(path)})}catch{}else this.value=createReadStream(path),this.stats=stat(path)}get type(){return mime[getFileExtension(this.path)]||"application/octet-stream"}get length(){if(isBun2)return this.value.size;return this.stats?.then((x)=>x.size)??0}}import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};_routes={};_types={Prefix:"",Singleton:{},Definitions:{},Metadata:{}};_ephemeral={};_volatile={};singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macros:[],higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};event={};telemetry={stack:void 0};router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new Memoirist({lazy:!0});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new Memoirist;return this["~dynamic"]},static:{http:{static:{},map:{},all:""},ws:{}},history:[]};routeTree=new Map;get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,request:!1,route:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup;return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(config.nativeStaticResponse===void 0)config.nativeStaticResponse=!0;if(this.config={},this.applyConfig(config??{}),this["~adapter"]=config.adapter??(typeof Bun!=="undefined"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry.stack=new Error().stack}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0}).Check(_env)===!1){let error2=new ValidationError("env",model,_env);throw new Error(error2.all.map((x)=>x.summary).join(`
323
- `))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}applyMacro(localHook){if(this.extender.macros.length){let manage=createMacroManager({globalHook:this.event,localHook}),manager={events:{global:this.event,local:localHook},get onParse(){return manage("parse")},get onTransform(){return manage("transform")},get onBeforeHandle(){return manage("beforeHandle")},get onAfterHandle(){return manage("afterHandle")},get mapResponse(){return manage("mapResponse")},get onAfterResponse(){return manage("afterResponse")},get onError(){return manage("error")}};for(let macro of this.extender.macros)traceBackMacro(macro.fn(manager),localHook,manage)}}applyConfig(config){return this.config={prefix:"",aot:env2.ELYSIA_AOT!=="false",normalize:!0,...config,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name));return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,{allowMeta=!1,skipPrefix=!1}={allowMeta:!1,skipPrefix:!1}){if(localHook=compressHistoryHook(localHookToLifeCycleStore(localHook)),path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let models=this.definitions.type,dynamic=!this.config.aot,instanceValidator={...this.validator.getCandidate()},cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},cookieValidator=()=>cloned.cookie?getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,config:cloned.cookie?.config??{},dynamic,models}):void 0,normalize=this.config.normalize,modules=this.definitions.typebox,validator=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.schema===!0?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!this.config.normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize})}};if(localHook=mergeHook(localHook,compressHistoryHook(instanceValidator)),localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);this.applyMacro(localHook);let hooks=compressHistoryHook(mergeHook(this.event,localHook));if(this.config.aot===!1){this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(this.config.strictPath===!1){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,hooks});return}let shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,inference=cloneInference(this.inference),adapter=this["~adapter"].handler,staticHandler=typeof handle!=="function"&&typeof adapter.createStaticHandler==="function"?adapter.createStaticHandler(handle,hooks,this.setHeaders):void 0,nativeStaticHandler=typeof handle!=="function"?adapter.createNativeStaticHandler?.(handle,hooks,this.setHeaders):void 0;if(this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[path]=nativeStaticHandler();let compile=(asManifest=!1)=>composeHandler({app:this,path,method,hooks,validator,handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference,asManifest});if(this.routeTree.has(method+path))for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){let removed=this.router.history.splice(i,1)[0];if(removed&&this.routeTree.has(removed?.method+removed?.path))this.routeTree.delete(removed.method+removed.path)}}else this.routeTree.set(method+path,this.router.history.length);let history=this.router.history,index=this.router.history.length,mainHandler=shouldPrecompile?compile():(ctx)=>{let temp=(history[index].composed=compile())(ctx);return compile=void 0,temp};if(shouldPrecompile)compile=void 0;let isWebSocket=method==="$INTERNALWS";this.router.history.push(Object.assign({method,path,composed:mainHandler,handler:handle,hooks},localHook.webSocket?{websocket:localHook.websocket}:{}));let staticRouter=this.router.static.http,handler={handler:shouldPrecompile?mainHandler:void 0,compile(){return this.handler=compile()}};if(isWebSocket){if(this.router.http.add("ws",path,handler),!this.config.strictPath)this.router.http.add("ws",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(encoded!==path)this.router.http.add("ws",encoded,handler);return}if(path.indexOf(":")===-1&&path.indexOf("*")===-1){if(!staticRouter.map[path])staticRouter.map[path]={code:""};let ctx=staticHandler?"":"c";if(method==="ALL")staticRouter.map[path].all=`default:return ht[${index}].composed(${ctx})
323
+ `))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}applyMacro(localHook){if(this.extender.macros.length){let manage=createMacroManager({globalHook:this.event,localHook}),manager={events:{global:this.event,local:localHook},get onParse(){return manage("parse")},get onTransform(){return manage("transform")},get onBeforeHandle(){return manage("beforeHandle")},get onAfterHandle(){return manage("afterHandle")},get mapResponse(){return manage("mapResponse")},get onAfterResponse(){return manage("afterResponse")},get onError(){return manage("error")}};for(let macro of this.extender.macros)traceBackMacro(macro.fn(manager),localHook,manage)}}applyConfig(config){return this.config={prefix:"",aot:env2.ELYSIA_AOT!=="false",normalize:!0,...config,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name));return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,{allowMeta=!1,skipPrefix=!1}={allowMeta:!1,skipPrefix:!1}){if(localHook=compressHistoryHook(localHookToLifeCycleStore(localHook)),path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let models=this.definitions.type,dynamic=!this.config.aot,instanceValidator={...this.validator.getCandidate()},cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},cookieValidator=()=>cloned.cookie?getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,config:cloned.cookie?.config??{},dynamic,models}):void 0,normalize=this.config.normalize,modules=this.definitions.typebox,validator=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.schema===!0?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!this.config.normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize})}};if(localHook=mergeHook(localHook,compressHistoryHook(instanceValidator)),localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);this.applyMacro(localHook);let hooks=compressHistoryHook(mergeHook(this.event,localHook));if(this.config.aot===!1){this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(this.config.strictPath===!1){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,hooks});return}let shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,inference=cloneInference(this.inference),adapter=this["~adapter"].handler,staticHandler=typeof handle!=="function"&&typeof adapter.createStaticHandler==="function"?adapter.createStaticHandler(handle,hooks,this.setHeaders):void 0,nativeStaticHandler=typeof handle!=="function"?adapter.createNativeStaticHandler?.(handle,hooks,this.setHeaders):void 0;if(this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[path]=nativeStaticHandler();let compile=(asManifest=!1)=>composeHandler({app:this,path,method,hooks,validator,handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference,asManifest}),oldIndex;if(this.routeTree.has(method+path))for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){oldIndex=i;break}}else this.routeTree.set(method+path,this.router.history.length);let history=this.router.history,index=oldIndex??this.router.history.length,mainHandler=shouldPrecompile?compile():(ctx)=>{let temp=(history[index].composed=compile())(ctx);return compile=void 0,temp};if(shouldPrecompile)compile=void 0;let isWebSocket=method==="$INTERNALWS";if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,handler:handle,hooks},localHook.webSocket?{websocket:localHook.websocket}:{});else this.router.history.push(Object.assign({method,path,composed:mainHandler,handler:handle,hooks},localHook.webSocket?{websocket:localHook.websocket}:{}));let staticRouter=this.router.static.http,handler={handler:shouldPrecompile?mainHandler:void 0,compile(){return this.handler=compile()}};if(isWebSocket){if(this.router.http.add("ws",path,handler),!this.config.strictPath)this.router.http.add("ws",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(encoded!==path)this.router.http.add("ws",encoded,handler);return}if(path.indexOf(":")===-1&&path.indexOf("*")===-1){if(!staticRouter.map[path])staticRouter.map[path]={code:""};let ctx=staticHandler?"":"c";if(method==="ALL")staticRouter.map[path].all=`default:return ht[${index}].composed(${ctx})
324
324
  `;else staticRouter.map[path].code=`case '${method}':return ht[${index}].composed(${ctx})
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=async({request,path:path2})=>{if(request.method==="GET"||request.method==="HEAD"||!request.headers.get("content-type"))return run(new Request(replaceUrlPath(request.url,path2||"/"),{...request,method:request.method}));return run(new Request(replaceUrlPath(request.url,path2||"/"),{...request,method:request.method,body:await request.arrayBuffer()}))};return this.all("/*",handler2,{parse:"none"}),this}let length=path.length-(path.endsWith("*")?1:0);if(handle instanceof Elysia)handle=handle.compile().fetch;let handler=async({request,path:path2})=>{if(request.method==="GET"||request.method==="HEAD"||!request.headers.get("content-type"))return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{...request,method:request.method}));return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{...request,method:request.method,body:await request.arrayBuffer()}))};return this.all(path,handler,{type:"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};
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=1B08B1A91DA0D09B64756E2164756E21
327
+ //# debugId=D828E648F1209E1D64756E2164756E21