elysia 1.2.0-rc.2 → 1.2.0
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/bunfig.toml +2 -0
- package/dist/bun/index.d.ts +1 -0
- package/dist/bun/index.js +4 -4
- package/dist/bun/index.js.map +6 -6
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js +6 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +3 -1
- package/package.json +5 -5
package/bunfig.toml
ADDED
package/dist/bun/index.d.ts
CHANGED
|
@@ -1743,6 +1743,7 @@ export { ELYSIA_TRACE, type TraceEvent, type TraceListener, type TraceHandler, t
|
|
|
1743
1743
|
export { getSchemaValidator, mergeHook, mergeObjectArray, getResponseSchemaValidator, redirect, StatusMap, InvertedStatusMap, form, replaceSchemaType, replaceUrlPath, checksum, cloneInference, deduplicateChecksum, ELYSIA_FORM_DATA, ELYSIA_REQUEST_ID } from './utils';
|
|
1744
1744
|
export { error, mapValueError, ParseError, NotFoundError, ValidationError, InternalServerError, InvalidCookieSignature, ERROR_CODE } from './error';
|
|
1745
1745
|
export type { EphemeralType, CreateEden, ComposeElysiaResponse, ElysiaConfig, SingletonBase, DefinitionBase, RouteBase, Handler, ComposedHandler, InputSchema, LocalHook, MergeSchema, RouteSchema, UnwrapRoute, InternalRoute, HTTPMethod, SchemaValidator, VoidHandler, PreHandler, BodyHandler, OptionalHandler, AfterResponseHandler, ErrorHandler, AfterHandler, LifeCycleEvent, LifeCycleStore, LifeCycleType, MaybePromise, UnwrapSchema, Checksum, DocumentDecoration, InferContext, InferHandler, ResolvePath, MapResponse, MacroQueue, BaseMacro, MacroManager, BaseMacroFn, MacroToProperty, ResolveMacroContext, MergeElysiaInstances, MaybeArray, ModelValidator, MetadataBase, UnwrapBodySchema, UnwrapGroupGuardRoute, ModelValidatorError, ExcludeElysiaResponse, CoExist } from './types';
|
|
1746
|
+
export { env } from './universal/env';
|
|
1746
1747
|
export { file, ElysiaFile } from './universal/file';
|
|
1747
1748
|
export type { ElysiaAdapter } from './adapter';
|
|
1748
1749
|
export { TypeSystemPolicy } from '@sinclair/typebox/system';
|
package/dist/bun/index.js
CHANGED
|
@@ -30,7 +30,7 @@ const error404=new Response(error404Message,{status:404})
|
|
|
30
30
|
`,code:findDynamicRoute}}},composeError:{mapResponseContext:"",validationError:"return new Response(error.message,{headers:Object.assign({'content-type':'application/json'},set.headers),status:set.status})",unknownError:"return new Response(error.message,{headers:set.headers,status:error.status})"},listen(){return()=>{throw new Error("WebStandard does not support listen, you might want to export default Elysia.fetch instead")}}};var createNativeStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function"||handle instanceof Blob)return;let response=mapResponse(handle,{headers:setHeaders});if(hooks.parse.length===0&&hooks.transform.length===0&&hooks.beforeHandle.length===0&&hooks.afterHandle.length===0){if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain;charset=utf-8");return response.clone.bind(response)}};var websocket={open(ws){ws.data.open?.(ws)},message(ws,message){ws.data.message?.(ws,message)},drain(ws){ws.data.drain?.(ws)},close(ws,code,reason){ws.data.close?.(ws,code,reason)}};class ElysiaWS{raw;data;body;validator;["~types"];get id(){return this.data.id}constructor(raw,data,body=void 0){this.raw=raw;this.data=data;this.body=body;this.validator=raw.data?.validator,this.sendText=raw.sendText.bind(raw),this.sendBinary=raw.sendBinary.bind(raw),this.close=raw.close.bind(raw),this.terminate=raw.terminate.bind(raw),this.publishText=raw.publishText.bind(raw),this.publishBinary=raw.publishBinary.bind(raw),this.subscribe=raw.subscribe.bind(raw),this.unsubscribe=raw.unsubscribe.bind(raw),this.isSubscribed=raw.isSubscribed.bind(raw),this.cork=raw.cork.bind(raw),this.remoteAddress=raw.remoteAddress,this.binaryType=raw.binaryType,this.data=raw.data,this.send=this.send.bind(this),this.ping=this.ping.bind(this),this.pong=this.pong.bind(this),this.publish=this.publish.bind(this)}send(data,compress){if(Buffer.isBuffer(data))return this.raw.send(data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data,compress)}ping(data){if(Buffer.isBuffer(data))return this.raw.ping(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.ping(data)}pong(data){if(Buffer.isBuffer(data))return this.raw.pong(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.pong(data)}publish(topic,data,compress){if(Buffer.isBuffer(data))return this.raw.publish(topic,data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress)}sendText;sendBinary;close;terminate;publishText;publishBinary;subscribe;unsubscribe;isSubscribed;cork;remoteAddress;binaryType;get readyState(){return this.raw.readyState}}var createWSMessageParser=(parse2)=>{let parsers=typeof parse2==="function"?[parse2]:parse2;return async function parseMessage(ws,message){if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===47||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message}if(parsers)for(let i=0;i<parsers.length;i++){let temp=parsers[i](ws,message);if(temp instanceof Promise)temp=await temp;if(temp!==void 0)return temp}return message}},createHandleWSResponse=(validateResponse)=>{let handleWSResponse=(ws,data)=>{if(data instanceof Promise)return data.then((data2)=>handleWSResponse(ws,data2));if(Buffer.isBuffer(data))return ws.send(data.toString());if(data===void 0)return;let send=(datum)=>{if(validateResponse?.Check(datum)===!1)return ws.send(new ValidationError("message",validateResponse,datum).message);if(typeof datum==="object")return ws.send(JSON.stringify(datum));ws.send(datum)};if(typeof data?.next!=="function")return void send(data);let init=data.next();if(init instanceof Promise)return(async()=>{let first=await init;if(validateResponse?.Check(first)===!1)return ws.send(new ValidationError("message",validateResponse,first).message);if(send(first.value),!first.done)for await(let datum of data)send(datum)})();if(send(init.value),!init.done)for(let datum of data)send(datum)};return handleWSResponse};var BunAdapter={...WebStandardAdapter,name:"bun",handler:{...WebStandardAdapter.handler,createNativeStaticHandler},composeHandler:{...WebStandardAdapter.composeHandler,headers:hasHeaderShorthand?`c.headers = c.request.headers.toJSON()
|
|
31
31
|
`:`c.headers = {}
|
|
32
32
|
for (const [key, value] of c.request.headers.entries())c.headers[key] = value
|
|
33
|
-
`},listen(app){return(options,callback)=>{if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let fetch=app.fetch,serve=typeof options==="object"?{development:!isProduction,reusePort:!0,...app.config.serve||{},...options||{},static:app.router.static.http.static,websocket:{...app.config.websocket||{},...websocket||{}},fetch,error:app.outerErrorHandler}:{development:!isProduction,reusePort:!0,...app.config.serve||{},static:app.router.static.http.static,websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch,error:app.outerErrorHandler};app.server=Bun?.serve(serve);for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(this);if(callback)callback(app.server);process.on("beforeExit",()=>{if(app.server){app.server.stop(),app.server=null;for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(this)}}),app.promisedModules.then(()=>{Bun?.gc(!1)})}},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,validateMessage=getSchemaValidator(body,{models:app.definitions.type,normalize:app.config.normalize}),validateResponse=getSchemaValidator(response,{models:app.definitions.type,normalize:app.config.normalize});app.route("$INTERNALWS",path,async(context)=>{let server=app.getServer(),{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=validateResponse,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse=createHandleWSResponse(validateResponse),parseMessage=createWSMessageParser(parse2),_id;if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:validateResponse,ping(data){options.ping?.(data)},pong(data){options.pong?.(data)},open(ws){handleResponse(ws,options.open?.(new ElysiaWS(ws,context)))},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);handleResponse(ws,options.message?.(new ElysiaWS(ws,context,message),message))},drain(ws){handleResponse(ws,options.drain?.(new ElysiaWS(ws,context)))},close(ws,code,reason){handleResponse(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}}}))return;return set2.status=400,"Expected a websocket connection"},{...rest,websocket:options})}};import{Value as Value4}from"@sinclair/typebox/value";import{TypeBoxError}from"@sinclair/typebox";import fastDecode from"fast-decode-uri-component";var plusRegex=/\+/g;function parseQueryFromURL(input){let result={};if(typeof input!=="string")return result;let key="",value="",startingIndex=-1,equalityIndex=-1,flags=0,l=input.length;for(let i=0;i<l;i++)switch(input.charCodeAt(i)){case 38:let hasBothKeyValuePair=equalityIndex>startingIndex;if(!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=fastDecode(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=fastDecode(value)||value}result[key]=value}}key="",value="",startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=8;break;case 43:if(equalityIndex>startingIndex)flags|=4;else flags|=1;break;case 37:if(equalityIndex>startingIndex)flags|=8;else flags|=2;break}if(startingIndex<l){let hasBothKeyValuePair=equalityIndex>startingIndex;if(key=input.slice(startingIndex+1,hasBothKeyValuePair?equalityIndex:l),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=fastDecode(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,l),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=fastDecode(value)||value}result[key]=value}}}return result}var parseQuery=(input)=>{let result={};if(typeof input!=="string")return result;let inputLength=input.length,key="",value="",startingIndex=-1,equalityIndex=-1,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1,hasBothKeyValuePair=!1,c=0;for(let i=0;i<inputLength+1;i++){if(i!==inputLength)c=input.charCodeAt(i);else c=38;switch(c){case 38:{if(hasBothKeyValuePair=equalityIndex>startingIndex,!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(keyHasPlus)key=key.replace(plusRegex," ");if(shouldDecodeKey)key=fastDecode(key)||key;if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),valueHasPlus)value=value.replace(plusRegex," ");if(shouldDecodeValue)value=fastDecode(value)||value}let currentValue=result[key];if(currentValue===void 0)result[key]=value;else if(currentValue.pop)currentValue.push(value);else result[key]=[currentValue,value]}value="",startingIndex=i,equalityIndex=i,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1;break}case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else shouldDecodeValue=!0;break;case 43:if(equalityIndex>startingIndex)valueHasPlus=!0;else keyHasPlus=!0;break;case 37:if(equalityIndex>startingIndex)shouldDecodeValue=!0;else shouldDecodeKey=!0;break}}return result};import decodeURIComponent2 from"fast-decode-uri-component";var ELYSIA_TRACE=Symbol("ElysiaTrace"),createProcess=()=>{let{promise,resolve}=Promise.withResolvers(),{promise:end,resolve:resolveEnd}=Promise.withResolvers(),{promise:error2,resolve:resolveError}=Promise.withResolvers(),callbacks=[],callbacksEnd=[];return[(callback)=>{if(callback)callbacks.push(callback);return promise},(process2)=>{let processes=[],resolvers=[],groupError=null;for(let i=0;i<(process2.total??0);i++){let{promise:promise2,resolve:resolve2}=Promise.withResolvers(),{promise:end2,resolve:resolveEnd2}=Promise.withResolvers(),{promise:error3,resolve:resolveError2}=Promise.withResolvers(),callbacks2=[],callbacksEnd2=[];processes.push((callback)=>{if(callback)callbacks2.push(callback);return promise2}),resolvers.push((process3)=>{let result2={...process3,end:end2,error:error3,index:i,onStop(callback){if(callback)callbacksEnd2.push(callback);return end2}};resolve2(result2);for(let i2=0;i2<callbacks2.length;i2++)callbacks2[i2](result2);return(error4=null)=>{let end3=performance.now();if(error4)groupError=error4;let detail={end:end3,error:error4,get elapsed(){return end3-process3.begin}};for(let i2=0;i2<callbacksEnd2.length;i2++)callbacksEnd2[i2](detail);resolveEnd2(end3),resolveError2(error4)}})}let result={...process2,end,error:error2,onEvent(callback){for(let i=0;i<processes.length;i++)processes[i](callback)},onStop(callback){if(callback)callbacksEnd.push(callback);return end}};resolve(result);for(let i=0;i<callbacks.length;i++)callbacks[i](result);return{resolveChild:resolvers,resolve(error3=null){let end2=performance.now();if(!error3&&groupError)error3=groupError;let detail={end:end2,error:error3,get elapsed(){return end2-process2.begin}};for(let i=0;i<callbacksEnd.length;i++)callbacksEnd[i](detail);resolveEnd(end2),resolveError(error3)}}}]},createTracer=(traceListener)=>{return(context)=>{let[onRequest,resolveRequest]=createProcess(),[onParse,resolveParse]=createProcess(),[onTransform,resolveTransform]=createProcess(),[onBeforeHandle,resolveBeforeHandle]=createProcess(),[onHandle,resolveHandle]=createProcess(),[onAfterHandle,resolveAfterHandle]=createProcess(),[onError,resolveError]=createProcess(),[onMapResponse,resolveMapResponse]=createProcess(),[onAfterResponse,resolveAfterResponse]=createProcess();return traceListener({id:context[ELYSIA_REQUEST_ID],context,set:context.set,onRequest,onParse,onTransform,onBeforeHandle,onHandle,onAfterHandle,onMapResponse,onAfterResponse,onError}),{request:resolveRequest,parse:resolveParse,transform:resolveTransform,beforeHandle:resolveBeforeHandle,handle:resolveHandle,afterHandle:resolveAfterHandle,error:resolveError,mapResponse:resolveMapResponse,afterResponse:resolveAfterResponse}}};var TypeBoxSymbol={optional:Symbol.for("TypeBox.Optional"),kind:Symbol.for("TypeBox.Kind")},isOptional=(validator)=>{if(!validator)return!1;let schema=validator?.schema;return!!schema&&TypeBoxSymbol.optional in schema},defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}return!1},createReport=({context="c",trace,addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i}, reportChild${i}, reportErr${i}, reportErrChild${i};let trace${i} = ${context}[ELYSIA_TRACE]?.[${i}] ?? trace[${i}](${context});
|
|
33
|
+
`},listen(app){return(options,callback)=>{if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let fetch=app.fetch,serve=typeof options==="object"?{development:!isProduction,reusePort:!0,...app.config.serve||{},...options||{},static:app.router.static.http.static,websocket:{...app.config.websocket||{},...websocket||{}},fetch,error:app.outerErrorHandler}:{development:!isProduction,reusePort:!0,...app.config.serve||{},static:app.router.static.http.static,websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch,error:app.outerErrorHandler};app.server=Bun?.serve(serve);for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(this);if(callback)callback(app.server);process.on("beforeExit",()=>{if(app.server){app.server.stop(),app.server=null;for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(this)}}),app.promisedModules.then(()=>{Bun?.gc(!1)})}},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,validateMessage=getSchemaValidator(body,{models:app.definitions.type,normalize:app.config.normalize}),validateResponse=getSchemaValidator(response,{models:app.definitions.type,normalize:app.config.normalize});app.route("$INTERNALWS",path,async(context)=>{let server=app.getServer(),{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=validateResponse,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse=createHandleWSResponse(validateResponse),parseMessage=createWSMessageParser(parse2),_id;if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:validateResponse,ping(data){options.ping?.(data)},pong(data){options.pong?.(data)},open(ws){handleResponse(ws,options.open?.(new ElysiaWS(ws,context)))},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);handleResponse(ws,options.message?.(new ElysiaWS(ws,context,message),message))},drain(ws){handleResponse(ws,options.drain?.(new ElysiaWS(ws,context)))},close(ws,code,reason){handleResponse(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}}}))return;return set2.status=400,"Expected a websocket connection"},{...rest,websocket:options})}};var isBun2=typeof Bun!=="undefined";var env2=isBun2?Bun.env:typeof process!=="undefined"&&process?.env?process.env:{};import{Value as Value4}from"@sinclair/typebox/value";import{TypeBoxError}from"@sinclair/typebox";import fastDecode from"fast-decode-uri-component";var plusRegex=/\+/g;function parseQueryFromURL(input){let result={};if(typeof input!=="string")return result;let key="",value="",startingIndex=-1,equalityIndex=-1,flags=0,l=input.length;for(let i=0;i<l;i++)switch(input.charCodeAt(i)){case 38:let hasBothKeyValuePair=equalityIndex>startingIndex;if(!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=fastDecode(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=fastDecode(value)||value}result[key]=value}}key="",value="",startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=8;break;case 43:if(equalityIndex>startingIndex)flags|=4;else flags|=1;break;case 37:if(equalityIndex>startingIndex)flags|=8;else flags|=2;break}if(startingIndex<l){let hasBothKeyValuePair=equalityIndex>startingIndex;if(key=input.slice(startingIndex+1,hasBothKeyValuePair?equalityIndex:l),hasBothKeyValuePair||key.length>0){if(flags&1)key=key.replace(plusRegex," ");if(flags&2)key=fastDecode(key)||key;if(!result[key]){if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,l),flags&4)value=value.replace(plusRegex," ");if(flags&8)value=fastDecode(value)||value}result[key]=value}}}return result}var parseQuery=(input)=>{let result={};if(typeof input!=="string")return result;let inputLength=input.length,key="",value="",startingIndex=-1,equalityIndex=-1,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1,hasBothKeyValuePair=!1,c=0;for(let i=0;i<inputLength+1;i++){if(i!==inputLength)c=input.charCodeAt(i);else c=38;switch(c){case 38:{if(hasBothKeyValuePair=equalityIndex>startingIndex,!hasBothKeyValuePair)equalityIndex=i;if(key=input.slice(startingIndex+1,equalityIndex),hasBothKeyValuePair||key.length>0){if(keyHasPlus)key=key.replace(plusRegex," ");if(shouldDecodeKey)key=fastDecode(key)||key;if(hasBothKeyValuePair){if(value=input.slice(equalityIndex+1,i),valueHasPlus)value=value.replace(plusRegex," ");if(shouldDecodeValue)value=fastDecode(value)||value}let currentValue=result[key];if(currentValue===void 0)result[key]=value;else if(currentValue.pop)currentValue.push(value);else result[key]=[currentValue,value]}value="",startingIndex=i,equalityIndex=i,shouldDecodeKey=!1,shouldDecodeValue=!1,keyHasPlus=!1,valueHasPlus=!1;break}case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else shouldDecodeValue=!0;break;case 43:if(equalityIndex>startingIndex)valueHasPlus=!0;else keyHasPlus=!0;break;case 37:if(equalityIndex>startingIndex)shouldDecodeValue=!0;else shouldDecodeKey=!0;break}}return result};import decodeURIComponent2 from"fast-decode-uri-component";var ELYSIA_TRACE=Symbol("ElysiaTrace"),createProcess=()=>{let{promise,resolve}=Promise.withResolvers(),{promise:end,resolve:resolveEnd}=Promise.withResolvers(),{promise:error2,resolve:resolveError}=Promise.withResolvers(),callbacks=[],callbacksEnd=[];return[(callback)=>{if(callback)callbacks.push(callback);return promise},(process2)=>{let processes=[],resolvers=[],groupError=null;for(let i=0;i<(process2.total??0);i++){let{promise:promise2,resolve:resolve2}=Promise.withResolvers(),{promise:end2,resolve:resolveEnd2}=Promise.withResolvers(),{promise:error3,resolve:resolveError2}=Promise.withResolvers(),callbacks2=[],callbacksEnd2=[];processes.push((callback)=>{if(callback)callbacks2.push(callback);return promise2}),resolvers.push((process3)=>{let result2={...process3,end:end2,error:error3,index:i,onStop(callback){if(callback)callbacksEnd2.push(callback);return end2}};resolve2(result2);for(let i2=0;i2<callbacks2.length;i2++)callbacks2[i2](result2);return(error4=null)=>{let end3=performance.now();if(error4)groupError=error4;let detail={end:end3,error:error4,get elapsed(){return end3-process3.begin}};for(let i2=0;i2<callbacksEnd2.length;i2++)callbacksEnd2[i2](detail);resolveEnd2(end3),resolveError2(error4)}})}let result={...process2,end,error:error2,onEvent(callback){for(let i=0;i<processes.length;i++)processes[i](callback)},onStop(callback){if(callback)callbacksEnd.push(callback);return end}};resolve(result);for(let i=0;i<callbacks.length;i++)callbacks[i](result);return{resolveChild:resolvers,resolve(error3=null){let end2=performance.now();if(!error3&&groupError)error3=groupError;let detail={end:end2,error:error3,get elapsed(){return end2-process2.begin}};for(let i=0;i<callbacksEnd.length;i++)callbacksEnd[i](detail);resolveEnd(end2),resolveError(error3)}}}]},createTracer=(traceListener)=>{return(context)=>{let[onRequest,resolveRequest]=createProcess(),[onParse,resolveParse]=createProcess(),[onTransform,resolveTransform]=createProcess(),[onBeforeHandle,resolveBeforeHandle]=createProcess(),[onHandle,resolveHandle]=createProcess(),[onAfterHandle,resolveAfterHandle]=createProcess(),[onError,resolveError]=createProcess(),[onMapResponse,resolveMapResponse]=createProcess(),[onAfterResponse,resolveAfterResponse]=createProcess();return traceListener({id:context[ELYSIA_REQUEST_ID],context,set:context.set,onRequest,onParse,onTransform,onBeforeHandle,onHandle,onAfterHandle,onMapResponse,onAfterResponse,onError}),{request:resolveRequest,parse:resolveParse,transform:resolveTransform,beforeHandle:resolveBeforeHandle,handle:resolveHandle,afterHandle:resolveAfterHandle,error:resolveError,mapResponse:resolveMapResponse,afterResponse:resolveAfterResponse}}};var TypeBoxSymbol={optional:Symbol.for("TypeBox.Optional"),kind:Symbol.for("TypeBox.Kind")},isOptional=(validator)=>{if(!validator)return!1;let schema=validator?.schema;return!!schema&&TypeBoxSymbol.optional in schema},defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}return!1},createReport=({context="c",trace,addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i}, reportChild${i}, reportErr${i}, reportErrChild${i};let trace${i} = ${context}[ELYSIA_TRACE]?.[${i}] ?? trace[${i}](${context});
|
|
34
34
|
`);return(event,{name,total=0}={})=>{if(!name)name="anonymous";let reporter=event==="error"?"reportErr":"report";for(let i=0;i<trace.length;i++)addFn(`${reporter}${i} = trace${i}.${event}({id,event:'${event}',name:'${name}',begin:performance.now(),total:${total}})
|
|
35
35
|
`);return{resolve(){for(let i=0;i<trace.length;i++)addFn(`${reporter}${i}.resolve()
|
|
36
36
|
`)},resolveChild(name2){for(let i=0;i<trace.length;i++)addFn(`${reporter}Child${i}=${reporter}${i}.resolveChild?.shift()?.({id,event:'${event}',name:'${name2}',begin:performance.now()})
|
|
@@ -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})}};var isBun2=typeof Bun!=="undefined";var env2=isBun2?Bun.env:typeof process!=="undefined"&&process?.env?process.env:{};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})}};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(`
|
|
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
|
-
${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,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};
|
|
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=AC7C30C9C0CF527964756E2164756E21
|