elysia 1.2.0 → 1.2.1
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.d.ts +1 -1
- package/dist/bun/index.js +2 -2
- package/dist/bun/index.js.map +6 -5
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/types.d.ts +9 -9
- package/dist/cjs/universal/file.js +3 -3
- package/dist/cjs/universal/fs.js +37 -0
- package/dist/index.d.ts +1 -1
- package/dist/types.d.ts +9 -9
- package/dist/universal/file.mjs +1 -1
- package/dist/universal/fs.d.ts +5 -0
- package/dist/universal/fs.mjs +12 -0
- package/package.json +1 -1
package/dist/bun/index.d.ts
CHANGED
|
@@ -1001,7 +1001,7 @@ export default class Elysia<const in out BasePath extends string = '', const in
|
|
|
1001
1001
|
macroFn: Metadata['macroFn'] & NewMacro;
|
|
1002
1002
|
parser: Metadata['parser'];
|
|
1003
1003
|
}, Routes, Ephemeral, Volatile>;
|
|
1004
|
-
macro<const NewMacro extends HookMacroFn
|
|
1004
|
+
macro<const NewMacro extends HookMacroFn<Metadata['schema'], Singleton, Definitions['error']>>(macro: NewMacro): Elysia<BasePath, Singleton, Definitions, {
|
|
1005
1005
|
schema: Metadata['schema'];
|
|
1006
1006
|
macro: Metadata['macro'] & Partial<MacroToProperty<NewMacro>>;
|
|
1007
1007
|
macroFn: Metadata['macroFn'] & NewMacro;
|
package/dist/bun/index.js
CHANGED
|
@@ -304,9 +304,9 @@ set.status = error.status??422
|
|
|
304
304
|
`+adapter.validationError+'}else{if(error.code&&typeof error.status==="number"){'+adapter.unknownError+"}";let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse.length,name:"context"});if(hooks.mapResponse.length)for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse2=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse2.fn.name);fnLiteral+=`context.response=error
|
|
305
305
|
error=${isAsyncName(mapResponse2)?"await ":""}onMapResponse[${i}](context)
|
|
306
306
|
`,endUnit()}return mapResponseReporter.resolve(),fnLiteral+=`
|
|
307
|
-
return mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}}`,Function("inject",fnLiteral)({app,mapResponse:app["~adapter"].handler.mapResponse,ERROR_CODE,ElysiaCustomStatusResponse,ELYSIA_TRACE,ELYSIA_REQUEST_ID,...adapter.inject})};import{TransformDecodeError}from"@sinclair/typebox/value";var 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,redirect});try{for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=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}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}else{let contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);context.contentType=contentType;for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn,temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}: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);for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],operation=hook.fn(context);if(hook.subType==="derive")if(operation instanceof Promise)Object.assign(context,await operation);else Object.assign(context,operation);else if(operation instanceof Promise)await operation}if(validator){if(validator.createHeaders?.()){let _header={};for(let key in request.headers)_header[key]=request.headers.get(key);if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(validator.createParams?.()?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.createQuery?.()?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(hook.subType==="resolve"){if(response2 instanceof ElysiaCustomStatusResponse){let result=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){context.response=response2;for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=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.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 context.response=mapResponse2(response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;if(reportedError.status)set2.status=reportedError.status;return app.handleError(context,reportedError)}finally{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse2}=app["~adapter"].handler;return async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});errorContext.set=context.set;for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse2(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})}};import{createReadStream,statSync}from"fs";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);class ElysiaFile{path;value;stats;constructor(path){this.path=path;if(isBun2)this.value=Bun.file(path);else this.value=createReadStream(path),this.stats=statSync(path)}get type(){return mime[getFileExtension(this.path)]||"application/octet-stream"}get length(){if(isBun2)return this.value.size;return this.stats?.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={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],mapResponse:[],afterResponse:[],trace:[],error:[],stop:[]};telemetry={stack:void 0};router={http:new Memoirist,ws:new Memoirist,dynamic:new Memoirist,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}"~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,{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(`
|
|
307
|
+
return mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}}`,Function("inject",fnLiteral)({app,mapResponse:app["~adapter"].handler.mapResponse,ERROR_CODE,ElysiaCustomStatusResponse,ELYSIA_TRACE,ELYSIA_REQUEST_ID,...adapter.inject})};import{TransformDecodeError}from"@sinclair/typebox/value";var 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,redirect});try{for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=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}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}else{let contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);context.contentType=contentType;for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn,temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}: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);for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],operation=hook.fn(context);if(hook.subType==="derive")if(operation instanceof Promise)Object.assign(context,await operation);else Object.assign(context,operation);else if(operation instanceof Promise)await operation}if(validator){if(validator.createHeaders?.()){let _header={};for(let key in request.headers)_header[key]=request.headers.get(key);if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(validator.createParams?.()?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.createQuery?.()?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(hook.subType==="resolve"){if(response2 instanceof ElysiaCustomStatusResponse){let result=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){context.response=response2;for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=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.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 context.response=mapResponse2(response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;if(reportedError.status)set2.status=reportedError.status;return app.handleError(context,reportedError)}finally{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse2}=app["~adapter"].handler;return async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});errorContext.set=context.set;for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse2(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})}};var fs=typeof process!=="undefined"&&env2.NODE_ENV?import.meta.require("fs"):{},noop=()=>{},createReadStream=fs.createReadStream??noop,statSync=fs.statSync??noop;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);class ElysiaFile{path;value;stats;constructor(path){this.path=path;if(isBun2)this.value=Bun.file(path);else this.value=createReadStream(path),this.stats=statSync(path)}get type(){return mime[getFileExtension(this.path)]||"application/octet-stream"}get length(){if(isBun2)return this.value.size;return this.stats?.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={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],mapResponse:[],afterResponse:[],trace:[],error:[],stop:[]};telemetry={stack:void 0};router={http:new Memoirist,ws:new Memoirist,dynamic:new Memoirist,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}"~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,{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(`
|
|
308
308
|
`))}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,schema]of Object.entries(this.definitions.type))models[name]=getSchemaValidator(schema);return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,{allowMeta=!1,skipPrefix=!1}={allowMeta:!1,skipPrefix:!1}){if(localHook=localHookToLifeCycleStore(localHook),path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let models=this.definitions.type,dynamic=!this.config.aot,instanceValidator={...this.validator.getCandidate()},cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},cookieValidator=()=>cloned.cookie?getCookieValidator({validator:cloned.cookie,defaultConfig:this.config.cookie,config:cloned.cookie?.config??{},dynamic,models}):void 0,normalize=this.config.normalize,validator=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.schema===!0?{body:getSchemaValidator(cloned.body,{dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()}),headers:getSchemaValidator(cloned.headers,{dynamic,models,additionalProperties:!this.config.normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),params:getSchemaValidator(cloned.params,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()}),query:getSchemaValidator(cloned.query,{dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{dynamic,models,normalize})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot()})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{dynamic,models,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions()})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{dynamic,models,normalize})}};if(localHook=mergeHook(localHook,instanceValidator),localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);this.applyMacro(localHook);let hooks=mergeHook(this.event,localHook);if(this.config.aot===!1){if(this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle}),this.config.strictPath===!1)this.router.dynamic.add(method,getLoosePath(path),{validator,hooks,content:localHook?.type,handle});this.router.history.push({method,path,composed:null,handler:handle,hooks,compile:handle});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,localHook:mergeHook(localHook),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)=>(history[index].composed=compile())(ctx),isWebSocket=method==="$INTERNALWS";this.router.history.push({method,path,composed:mainHandler,handler:handle,hooks,compile:()=>compile(),websocket:localHook.websocket});let staticRouter=this.router.static.http,handler={handler:shouldPrecompile?mainHandler:void 0,compile};if(isWebSocket){let loose=getLoosePath(path);if(path.indexOf(":")===-1&&path.indexOf("*")===-1)this.router.static.ws[path]=index;else if(this.router.ws.add("ws",path,handler),loose)this.router.ws.add("ws",loose,handler);return}if(path.indexOf(":")===-1&&path.indexOf("*")===-1){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})
|
|
309
309
|
`;else staticRouter.map[path].code=`case '${method}':return ht[${index}].composed(${ctx})
|
|
310
310
|
${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)}}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 type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")sucrose({[type]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start.push(fn);break;case"request":this.event.request.push(fn);break;case"parse":this.event.parse.push(fn);break;case"transform":this.event.transform.push(fn);break;case"derive":this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse.push(fn);break;case"trace":this.event.trace.push(fn);break;case"error":this.event.error.push(fn);break;case"stop":this.event.stop.push(fn);break}}return this}propagate(){return promoteEvent(this.event.parse),promoteEvent(this.event.transform),promoteEvent(this.event.beforeHandle),promoteEvent(this.event.afterHandle),promoteEvent(this.event.mapResponse),promoteEvent(this.event.afterResponse),promoteEvent(this.event.trace),promoteEvent(this.event.error),this}as(type){let castType={plugin:"scoped",scoped:"scoped",global:"global"}[type];if(promoteEvent(this.event.parse,castType),promoteEvent(this.event.transform,castType),promoteEvent(this.event.beforeHandle,castType),promoteEvent(this.event.afterHandle,castType),promoteEvent(this.event.mapResponse,castType),promoteEvent(this.event.afterResponse,castType),promoteEvent(this.event.trace,castType),promoteEvent(this.event.error,castType),type==="plugin")this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null;else if(type==="global")this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null;return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks})=>{if(path=(isSchema?"":this.config.prefix)+prefix+path,isSchema){let hook=schemaOrRun,localHook=hooks;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error||{},...sandbox.event.error||{}]:[localHook.error,...sandbox.event.error||{}]}))}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0})}),this}guard(hook,run){if(!run){if(typeof hook==="object"){this.applyMacro(hook);let type=hook.as??"local";if(this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie},hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);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);throw new Error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.')}).then((x)=>x.compile())),this;return this._use(plugin)}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks}of Object.values(plugin2.router.history))this.add(method,path,handler,mergeHook(hooks,{error:plugin2.event.error}));return plugin2.compile(),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((x)=>x.compile())),this;return instance}let{name,seed}=plugin.config;if(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"){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));return run(new Request(replaceUrlPath(request.url,path2||"/"),{...request,body:await request.arrayBuffer()}))};return this.all("/*",handler2,{type:"none"}),this}let length=path.length;if(handle instanceof Elysia)handle=handle.compile().fetch;let handler=async({request,path:path2})=>{if(request.method==="GET"||request.method==="HEAD"||!request.headers.get("content-type"))return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),request));return handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{...request,body:await request.arrayBuffer()}))};return this.all(path,handler,{type:"none"}),this.all(path+(path.endsWith("/")?"*":"/*"),handler,{type:"none"}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){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){switch(typeof name){case"object":return Object.entries(name).forEach(([key,value])=>{if(!(key in this.definitions.type))this.definitions.type[key]=value}),this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...name}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(result),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,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].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 Promise.all(this.promisedModules.promises)}}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};
|
|
311
311
|
|
|
312
|
-
//# debugId=
|
|
312
|
+
//# debugId=AD7231F5CB33E6EC64756E2164756E21
|