Socket
Socket
Sign inDemoInstall

elysia

Package Overview
Dependencies
Maintainers
1
Versions
410
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

elysia - npm Package Compare versions

Comparing version 0.5.2 to 0.5.3

5

dist/cjs/compose.d.ts
import type { Elysia } from '.';
import { SCHEMA, DEFS } from './utils';
import type { ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
import type { BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
import { TAnySchema } from '@sinclair/typebox';

@@ -8,3 +8,3 @@ export declare const hasReturn: (fnLiteral: string) => boolean;

export declare const findElysiaMeta: (type: string, schema: TAnySchema, found?: string[], parent?: string) => string[] | "root" | null;
export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta }: {
export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta, onRequest }: {
path: string;

@@ -17,4 +17,5 @@ method: HTTPMethod;

meta?: (Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof import("./utils").EXPOSED, {}>) | undefined;
onRequest: BeforeRequestHandler<any, any>[];
}) => ComposedHandler;
export declare const composeGeneralHandler: (app: Elysia<any>) => any;
export declare const composeErrorHandler: (app: Elysia<any>) => any;

127

dist/cjs/compose.js

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,r){for(var t in r)Object.defineProperty(e,t,{enumerable:!0,get:r[t]})}(exports,{hasReturn:function(){return i},isFnUse:function(){return l},findElysiaMeta:function(){return u},composeHandler:function(){return d},composeGeneralHandler:function(){return f},composeErrorHandler:function(){return p}});const e=require("fast-querystring"),r=require("./handler"),t=require("./utils"),n=require("./error"),o="AsyncFunction",s=e=>e.constructor.name===o,a=new Headers,c=RegExp(" (\\w+) = context","g"),i=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")},l=(e,r)=>{let t=r.slice(r.indexOf("(")+1,r.indexOf(")"));if(""===t)return!1;if(123===t.charCodeAt(0))return!!(t.includes(`{ ${e}`)||t.includes(`, ${e}`));if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let n=[t];for(let e of r.matchAll(c))n.push(e[1]);let o=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(o))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1},u=(e,r,t=[],n="")=>{if("object"===r.type){let o=r.properties;for(let r in o){let s=o[r],a=n?n+"."+r:r;if("object"===s.type){u(e,s,t,a);continue}if(s.anyOf){for(let r of s.anyOf)u(e,r,t,a);continue}s.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(n&&t.push(n),"root"):null},d=({path:c,method:d,hooks:f,validator:p,handler:y,handleError:h,meta:m})=>{let $="try {\n",b="string"==typeof f.type,E=p||"GET"!==d?[y,...f.transform,...f.beforeHandle,...f.afterHandle].map(e=>e.toString()):[],w="GET"!==d&&(p.body||b||E.some(e=>l("body",e))),q=p.headers||E.some(e=>l("headers",e));q&&($+=a.toJSON?`c.headers = c.request.headers.toJSON()
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,r){for(var t in r)Object.defineProperty(e,t,{enumerable:!0,get:r[t]})}(exports,{hasReturn:function(){return i},isFnUse:function(){return l},findElysiaMeta:function(){return u},composeHandler:function(){return f},composeGeneralHandler:function(){return d},composeErrorHandler:function(){return p}});const e=require("fast-querystring"),r=require("./handler"),t=require("./utils"),n=require("./error"),o="AsyncFunction",s=e=>e.constructor.name===o,a=new Headers,c=RegExp(" (\\w+) = context","g"),i=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")},l=(e,r)=>{let t=r.slice(r.indexOf("(")+1,r.indexOf(")"));if(""===t)return!1;if(123===t.charCodeAt(0))return!!(t.includes(`{ ${e}`)||t.includes(`, ${e}`));if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let n=[t];for(let e of r.matchAll(c))n.push(e[1]);let o=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(o))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1},u=(e,r,t=[],n="")=>{if("object"===r.type){let o=r.properties;for(let r in o){let s=o[r],a=n?n+"."+r:r;if("object"===s.type){u(e,s,t,a);continue}if(s.anyOf){for(let r of s.anyOf)u(e,r,t,a);continue}s.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(n&&t.push(n),"root"):null},f=({path:c,method:f,hooks:d,validator:p,handler:y,handleError:h,meta:m,onRequest:$})=>{let b="try {\n",E="string"==typeof d.type,w=p||"GET"!==f?[y,...d.transform,...d.beforeHandle,...d.afterHandle].map(e=>e.toString()):[],q="GET"!==f&&(p.body||E||w.some(e=>l("body",e))),g=p.headers||w.some(e=>l("headers",e));g&&(b+=a.toJSON?`c.headers = c.request.headers.toJSON()
`:`c.headers = {}

@@ -13,3 +13,3 @@ for (const key of c.request.headers.keys())

}
`);let g=p.query||E.some(e=>l("query",e));g&&($+=`const url = c.request.url
`);let k=p.query||w.some(e=>l("query",e));k&&(b+=`const url = c.request.url

@@ -21,3 +21,3 @@ if(c.query !== -1) {

}
`);let k=w||y.constructor.name===o||f.parse.length||f.afterHandle.find(s)||f.beforeHandle.find(s)||f.transform.find(s);if(w){let e=p?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(b||e){if(f.parse.length){$+=(q?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
`);let x=w.some(e=>l("set",e))||$.some(e=>l("set",e.toString())),H=q||y.constructor.name===o||d.parse.length||d.afterHandle.find(s)||d.beforeHandle.find(s)||d.transform.find(s);if(q){let e=p?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(E||e){if(d.parse.length){b+=(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
if (contentType) {

@@ -27,6 +27,6 @@ const index = contentType.indexOf(';')

`+`let used = false
`;for(let e=0;e<f.parse.length;e++){let r=`bo${e}`;0!==e&&($+=`if(!used) {
`),$+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(b+=`if(!used) {
`),b+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
if(${r} !== undefined) { c.body = ${r}; used = true }
`,0!==e&&($+="}")}$+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?$+="c.body = parseQuery(await c.request.text())":p.body.Code().includes("custom('File")?$+=`c.body = {}
`,0!==e&&(b+="}")}b+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?b+="c.body = parseQuery(await c.request.text())":p.body.Code().includes("custom('File")?b+=`c.body = {}

@@ -43,3 +43,3 @@ await c.request.formData().then((form) => {

}
})`:$+="c.body = JSON.parse(await c.request.text())":$+="c.body = await c.request.text()";else switch(f.type){case"application/json":$+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":$+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":$+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":$+=`c.body = {}
})`:b+="c.body = JSON.parse(await c.request.text())":b+="c.body = await c.request.text()";else switch(d.type){case"application/json":b+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":b+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":b+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":b+=`c.body = {}

@@ -54,11 +54,11 @@ for (const key of (await c.request.formData()).keys()) {

else c.body[key] = value
}`}f.parse.length&&($+="}}")}else{if($+="\n"+(q?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
}`}d.parse.length&&(b+="}}")}else{if(b+="\n"+(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
if (contentType) {
const index = contentType.indexOf(';')
if (index !== -1) contentType = contentType.substring(0, index)
`,f.parse.length){$+=`let used = false
`;for(let e=0;e<f.parse.length;e++){let r=`bo${e}`;0!==e&&($+=`if(!used) {
`),$+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
`,d.parse.length){b+=`let used = false
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(b+=`if(!used) {
`),b+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
if(${r} !== undefined) { c.body = ${r}; used = true }
`,0!==e&&($+="}")}$+="if (!used)"}$+=`switch (contentType) {
`,0!==e&&(b+="}")}b+="if (!used)"}b+=`switch (contentType) {
case 'application/json':

@@ -92,3 +92,3 @@ c.body = JSON.parse(await c.request.text())

}
`}$+="\n"}if(p.params){let e=u("Numeric",p.params.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.params.${r} = +c.params.${r};`;$+="\n"}}if(p.query){let e=u("Numeric",p.query.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.query.${r} = +c.query.${r};`;$+="\n"}}if(p.headers){let e=u("Numeric",p.headers.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.headers.${r} = +c.headers.${r};`;$+="\n"}}if(p.body){let e=u("Numeric",p.body.schema);if(e){switch(typeof e){case"string":$+="c.body = +c.body;";break;case"object":for(let r of e)$+=`c.body.${r} = +c.body.${r};`}$+="\n"}}if(f?.transform)for(let e=0;e<f.transform.length;e++){let r=f.transform[e];"derive"===r.$elysia?$+=f.transform[e].constructor.name===o?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:$+=f.transform[e].constructor.name===o?`await transform[${e}](c);`:`transform[${e}](c);`}if(p&&(p.headers&&($+=`
`}b+="\n"}if(p.params){let e=u("Numeric",p.params.schema);if(e){if("object"==typeof e)for(let r of e)b+=`c.params.${r} = +c.params.${r};`;b+="\n"}}if(p.query){let e=u("Numeric",p.query.schema);if(e){if("object"==typeof e)for(let r of e)b+=`c.query.${r} = +c.query.${r};`;b+="\n"}}if(p.headers){let e=u("Numeric",p.headers.schema);if(e){if("object"==typeof e)for(let r of e)b+=`c.headers.${r} = +c.headers.${r};`;b+="\n"}}if(p.body){let e=u("Numeric",p.body.schema);if(e){switch(typeof e){case"string":b+="c.body = +c.body;";break;case"object":for(let r of e)b+=`c.body.${r} = +c.body.${r};`}b+="\n"}}if(d?.transform)for(let e=0;e<d.transform.length;e++){let r=d.transform[e];"derive"===r.$elysia?b+=d.transform[e].constructor.name===o?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:b+=d.transform[e].constructor.name===o?`await transform[${e}](c);`:`transform[${e}](c);`}if(p&&(p.headers&&(b+=`
if (headers.Check(c.headers) === false) {

@@ -101,22 +101,22 @@ throw new ValidationError(

}
`),p.params&&($+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),p.query&&($+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),p.body&&($+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),f?.beforeHandle)for(let e=0;e<f.beforeHandle.length;e++){let r=`be${e}`,t=i(f.beforeHandle[e].toString());if(t){if($+=(f.beforeHandle[e].constructor.name===o?`let ${r} = await beforeHandle[${e}](c);
`),p.params&&(b+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),p.query&&(b+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),p.body&&(b+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),d?.beforeHandle)for(let e=0;e<d.beforeHandle.length;e++){let r=`be${e}`,t=i(d.beforeHandle[e].toString());if(t){if(b+=(d.beforeHandle[e].constructor.name===o?`let ${r} = await beforeHandle[${e}](c);
`:`let ${r} = beforeHandle[${e}](c);
`)+`if(${r} !== undefined) {
`,f?.afterHandle)for(let e=0;e<f.afterHandle.length;e++){let t=i(f.afterHandle[e].toString());if(t){let t=`af${e}`;$+=(f.afterHandle[e].constructor.name===o?`const ${t} = await afterHandle[${e}](c, ${r});
`,d?.afterHandle)for(let e=0;e<d.afterHandle.length;e++){let t=i(d.afterHandle[e].toString());if(t){let t=`af${e}`;b+=(d.afterHandle[e].constructor.name===o?`const ${t} = await afterHandle[${e}](c, ${r});
`:`const ${t} = afterHandle[${e}](c, ${r});
`)+`if(${t} !== undefined) { ${r} = ${t} }
`}else $+=f.afterHandle[e].constructor.name===o?`await afterHandle[${e}](c, ${r});
`}else b+=d.afterHandle[e].constructor.name===o?`await afterHandle[${e}](c, ${r});
`:`afterHandle[${e}](c, ${r});
`}p.response&&($+=`if(response[c.set.status]?.Check(${r}) === false) {
`}p.response&&(b+=`if(response[c.set.status]?.Check(${r}) === false) {
if(!(response instanceof Error))
throw new ValidationError('response', response[c.set.status], ${r})
}
`),$+=`return mapEarlyResponse(${r}, c.set)}
`}else $+=f.beforeHandle[e].constructor.name===o?`await beforeHandle[${e}](c);
`),b+=`return mapEarlyResponse(${r}, c.set)}
`}else b+=d.beforeHandle[e].constructor.name===o?`await beforeHandle[${e}](c);
`:`beforeHandle[${e}](c);
`}if(f?.afterHandle.length){$+=y.constructor.name===o?`let r = await handler(c);
`}if(d?.afterHandle.length){b+=y.constructor.name===o?`let r = await handler(c);
`:`let r = handler(c);
`;for(let e=0;e<f.afterHandle.length;e++){let r=`af${e}`,t=i(f.afterHandle[e].toString());t?($+=f.afterHandle[e].constructor.name===o?`let ${r} = await afterHandle[${e}](c, r)
`;for(let e=0;e<d.afterHandle.length;e++){let r=`af${e}`,t=i(d.afterHandle[e].toString());t?(b+=d.afterHandle[e].constructor.name===o?`let ${r} = await afterHandle[${e}](c, r)
`:`let ${r} = afterHandle[${e}](c, r)
`,p.response?$+=`if(response[c.set.status]?.Check(${r}) === false) {
`,p.response?b+=`if(response[c.set.status]?.Check(${r}) === false) {
if(!(response instanceof Error))

@@ -127,11 +127,12 @@ throw new ValidationError('response', response[c.set.status], ${r})

if(${r}) return ${r};
`:$+=`if(${r}) return ${r};
`):$+=f.afterHandle[e].constructor.name===o?`await afterHandle[${e}](c, r)
`:b+=`if(${r}) return ${r};
`):b+=d.afterHandle[e].constructor.name===o?`await afterHandle[${e}](c, r)
`:`afterHandle[${e}](c, r)
`}p.response&&($+=`if(response[c.set.status]?.Check(r) === false) {
`}p.response&&(b+=`if(response[c.set.status]?.Check(r) === false) {
if(!(response instanceof Error))
throw new ValidationError('response', response[c.set.status], r)
}
`),$+=`return mapResponse(r, c.set);
`}else p.response?$+=(y.constructor.name===o?`const r = await handler(c);
`),x?b+=`return mapResponse(r, c.set)
`:b+=`return mapCompactResponse(r)
`}else if(p.response)b+=(y.constructor.name===o?`const r = await handler(c);
`:`const r = handler(c);

@@ -142,7 +143,11 @@ `)+`if(response[c.set.status]?.Check(r) === false) {

}
`+"return mapResponse(r, c.set);":$+=y.constructor.name===o?"return mapResponse(await handler(c), c.set);":"return mapResponse(handler(c), c.set);";$+=`
`,x?b+=`return mapResponse(r, c.set)
`:b+=`return mapCompactResponse(r)
`;else{let e=y.constructor.name===o?"await handler(c) ":"handler(c)";x?b+=`return mapResponse(${e}, c.set)
`:b+=`return mapCompactResponse(${e})
`}b+=`
} catch(error) {
${k?"":"return (async () => {"}
${H?"":"return (async () => {"}
const set = c.set

@@ -152,3 +157,3 @@

${f.error.length?`for (let i = 0; i < handleErrors.length; i++) {
${d.error.length?`for (let i = 0; i < handleErrors.length; i++) {
let handled = handleErrors[i]({

@@ -167,4 +172,4 @@ request: c.request,

return handleError(c.request, error, set)
${k?"":"})()"}
}`,$=`const {
${H?"":"})()"}
}`,b=`const {
handler,

@@ -188,2 +193,3 @@ handleError,

mapResponse,
mapCompactResponse,
mapEarlyResponse,

@@ -207,11 +213,23 @@ mapErrorCode,

return ${k?"async":""} function(c) {
return ${H?"async":""} function(c) {
${m?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""}
${$}
}`;let x=Function("hooks",$);return x({handler:y,hooks:f,validator:p,handleError:h,utils:{mapResponse:r.mapResponse,mapEarlyResponse:r.mapEarlyResponse,parseQuery:e.parse},error:{ParseError:n.ParseError,NotFoundError:n.NotFoundError,ValidationError:n.ValidationError,InternalServerError:n.InternalServerError},meta:m,SCHEMA:m?t.SCHEMA:void 0,DEFS:m?t.DEFS:void 0})},f=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let o=e.staticRouter,s="";for(let[e,{code:r,all:t}]of Object.entries(o.map))s+=`case '${e}':
${b}
}`;let R=Function("hooks",b);return R({handler:y,hooks:d,validator:p,handleError:h,utils:{mapResponse:r.mapResponse,mapCompactResponse:r.mapCompactResponse,mapEarlyResponse:r.mapEarlyResponse,parseQuery:e.parse},error:{ParseError:n.ParseError,NotFoundError:n.NotFoundError,ValidationError:n.ValidationError,InternalServerError:n.InternalServerError},meta:m,SCHEMA:m?t.SCHEMA:void 0,DEFS:m?t.DEFS:void 0})},d=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:o,staticRouter:s}=e,a=`const route = find(method, path) ${o.root.ALL?'?? find("ALL", path)':""}
if (route === null)
return ${e.event.error.length?`handleError(
request,
notFound,
ctx.set
)`:`new Response(error404, {
status: 404
})`}
ctx.params = route.params
return route.store(ctx)`,c="";for(let[e,{code:r,all:t}]of Object.entries(s.map))c+=`case '${e}':
switch(method) {
${r}
${t}}
${t??"default:\n"+a}}
`;let a=e.router,c=`const {
`;let l=`const {
app,

@@ -227,3 +245,3 @@ app: { store, router, staticRouter },

${o.variables}
${s.variables}

@@ -245,3 +263,3 @@ const find = router.find.bind(router)

}
`;if(e.event.request.length){c+="try {";for(let r=0;r<e.event.request.length;r++){let t=i(e.event.request[r].toString());c+=t?`const response = mapEarlyResponse(
`;if(e.event.request.length){l+="try {";for(let r=0;r<e.event.request.length;r++){let t=i(e.event.request[r].toString());l+=t?`const response = mapEarlyResponse(
onRequest[${r}](ctx),

@@ -251,29 +269,16 @@ ctx.set

if (response) return response
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}c+=`} catch (error) {
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}l+=`} catch (error) {
return handleError(request, error, ctx.set)
}`}return c+=`
}`}return l+=`
const { url, method } = request,
s = url.indexOf('/', 12)
ctx.query = i = url.indexOf('?', s + 1),
s = url.indexOf('/', 12),
i = ctx.query = url.indexOf('?', s + 1),
path = i === -1 ? url.substring(s) : url.substring(s, i)
map: switch(path) {
${s}
switch(path) {
${c}
default: ${a}
}
const route = find(method, path) ${a.root.ALL?'?? find("ALL", path)':""}
if (route === null) {
return ${e.event.error.length?`handleError(
request,
notFound,
ctx.set
)`:`new Response(error404, {
status: 404
})`}
}
ctx.params = route.params
return route.store(ctx)
}`,e.handleError=p(e),Function("data",c)({app:e,mapEarlyResponse:r.mapEarlyResponse,NotFoundError:n.NotFoundError})},p=e=>{let t=`const {
}`,e.handleError=p(e),Function("data",l)({app:e,mapEarlyResponse:r.mapEarlyResponse,NotFoundError:n.NotFoundError})},p=e=>{let t=`const {
app: { event: { error: onError } },

@@ -280,0 +285,0 @@ mapResponse

@@ -6,2 +6,3 @@ /// <reference types="bun-types" />

export declare const mapResponse: (response: unknown, set: Context['set']) => Response;
export declare const mapCompactResponse: (response: unknown) => Response;
export declare const errorToResponse: (error: Error, headers?: HeadersInit) => Response;

@@ -1,1 +0,1 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,s){for(var r in s)Object.defineProperty(e,r,{enumerable:!0,get:s[r]})}(exports,{isNotEmpty:function(){return e},mapEarlyResponse:function(){return r},mapResponse:function(){return t},errorToResponse:function(){return n}});const e=e=>{for(let s in e)return!0;return!1},s=(e,s)=>{e.delete("Set-Cookie");for(let r=0;r<s.length;r++){let t=s[r].indexOf("=");e.append("Set-Cookie",`${s[r].slice(0,t)}=${s[r].slice(t+1)}`)}return e},r=(t,a)=>{if(e(a.headers)||200!==a.status||a.redirect)switch(a.redirect&&(a.headers.Location=a.redirect,a.status=302),a.headers["Set-Cookie"]&&Array.isArray(a.headers["Set-Cookie"])&&(a.headers=s(new Headers(a.headers),a.headers["Set-Cookie"])),typeof t){case"string":return new Response(t,{status:a.status,headers:a.headers});case"object":switch(t.constructor.name){case"Object":case"Array":case void 0:return Response.json(t,{status:a.status,headers:a.headers});case"Error":return n(t,a.headers);case"Response":for(let e in a.headers)t.headers.append(e,a.headers[e]);return t;case"Blob":default:return new Response(t,{status:a.status,headers:a.headers});case"Promise":return t.then(e=>{let s=r(e,a);if(void 0!==s)return s})}case"function":if(t instanceof Blob)return new Response(t,{status:a.status,headers:a.headers});for(let e in a.headers)t.headers.append(e,a.headers[e]);return t;case"number":case"boolean":return new Response(t.toString(),{status:a.status,headers:a.headers})}else switch(typeof t){case"string":return new Response(t);case"object":switch(t.constructor?.name){case"Object":case"Array":case void 0:return Response.json(t);case"Response":return t;case"Error":return n(t,a.headers);case"Blob":default:return new Response(t);case"Promise":return t.then(e=>{let s=r(e,a);if(void 0!==s)return s})}case"function":if(t instanceof Blob)return new Response(t);return t;case"number":case"boolean":return new Response(t.toString())}},t=(a,o)=>{if(e(o.headers)||200!==o.status||o.redirect)switch(o.redirect&&(o.headers.Location=o.redirect,o.status=302),o.headers["Set-Cookie"]&&Array.isArray(o.headers["Set-Cookie"])&&(o.headers=s(new Headers(o.headers),o.headers["Set-Cookie"])),typeof a){case"string":return new Response(a,{status:o.status,headers:o.headers});case"object":switch(a.constructor?.name){case"Object":case"Array":case void 0:return Response.json(a,{status:o.status,headers:o.headers});case"Error":return n(a,o.headers);case"Response":for(let e in o.headers)a.headers.append(e,o.headers[e]);return a;case"Blob":default:return new Response(a,{status:o.status,headers:o.headers});case"Promise":return a.then(e=>t(e,o))}case"function":if(a instanceof Blob)return new Response(a,{status:o.status,headers:o.headers});return a();case"number":case"boolean":return new Response(a.toString(),{status:o.status,headers:o.headers});case"undefined":return new Response("",{status:o.status,headers:o.headers});default:return new Response(a,{status:o.status,headers:o.headers})}else switch(typeof a){case"string":return new Response(a);case"object":switch(a.constructor?.name){case"Object":case"Array":case void 0:return Response.json(a);case"Response":return a;case"Error":return n(a,o.headers);case"Blob":default:return new Response(a);case"Promise":return a.then(e=>{let s=r(e,o);return void 0!==s?s:new Response("")})}case"function":if(a instanceof Blob)return new Response(a);return a();case"number":case"boolean":return new Response(a.toString());case"undefined":return new Response("");default:return new Response(a)}},n=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s});
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,r){for(var s in r)Object.defineProperty(e,s,{enumerable:!0,get:r[s]})}(exports,{isNotEmpty:function(){return e},mapEarlyResponse:function(){return s},mapResponse:function(){return n},mapCompactResponse:function(){return t},errorToResponse:function(){return o}});const e=e=>{for(let r in e)return!0;return!1},r=(e,r)=>{e.delete("Set-Cookie");for(let s=0;s<r.length;s++){let n=r[s].indexOf("=");e.append("Set-Cookie",`${r[s].slice(0,n)}=${r[s].slice(n+1)}`)}return e},s=(n,t)=>{if(e(t.headers)||200!==t.status||t.redirect)switch(t.redirect&&(t.headers.Location=t.redirect,t.status=302),t.headers["Set-Cookie"]&&Array.isArray(t.headers["Set-Cookie"])&&(t.headers=r(new Headers(t.headers),t.headers["Set-Cookie"])),n?.constructor?.name){case"String":case"Blob":return new Response(n,t);case"Object":case"Array":return Response.json(n,t);case void 0:if(!n)return;return Response.json(n,t);case"Response":for(let e in t.headers)n.headers.append(e,t.headers[e]);return n;case"Promise":return n.then(e=>{let r=s(e,t);if(void 0!==r)return r});case"Error":return o(n,t.headers);case"Function":return n();case"Number":case"Boolean":return new Response(n.toString(),t);default:return}else switch(n?.constructor?.name){case"String":case"Blob":return new Response(n);case"Object":case"Array":return Response.json(n);case void 0:if(!n)return new Response("");return Response.json(n);case"Response":return n;case"Promise":return n.then(e=>{let r=s(e,t);if(void 0!==r)return r});case"Error":return o(n,t.headers);case"Function":return n();case"Number":case"Boolean":return new Response(n.toString());default:return}},n=(s,t)=>{if(e(t.headers)||200!==t.status||t.redirect)switch(t.redirect&&(t.headers.Location=t.redirect,t.status=302),t.headers["Set-Cookie"]&&Array.isArray(t.headers["Set-Cookie"])&&(t.headers=r(new Headers(t.headers),t.headers["Set-Cookie"])),s?.constructor?.name){case"String":case"Blob":return new Response(s,{status:t.status,headers:t.headers});case"Object":case"Array":return Response.json(s,t);case void 0:if(!s)return new Response("",t);return Response.json(s,t);case"Response":for(let e in t.headers)s.headers.append(e,t.headers[e]);return s;case"Error":return o(s,t.headers);case"Promise":return s.then(e=>n(e,t));case"Function":return s();case"Number":case"Boolean":return new Response(s.toString(),t);default:return new Response(s,t)}else switch(s?.constructor?.name){case"String":case"Blob":return new Response(s);case"Object":case"Array":return Response.json(s);case void 0:if(!s)return new Response("");return Response.json(s);case"Response":default:return s;case"Error":return o(s);case"Promise":return s.then(e=>{let r=n(e,t);return void 0!==r?r:new Response("")});case"Function":return s();case"Number":case"Boolean":return new Response(s.toString())}},t=e=>{switch(e.constructor?.name){case"String":case"Blob":return new Response(e);case"Object":case"Array":return Response.json(e);case void 0:if(!e)return new Response("");return Response.json(e);case"Response":default:return e;case"Error":return o(e);case"Promise":return e.then(e=>{let r=t(e);return void 0!==r?r:new Response("")});case"Function":return e();case"Number":case"Boolean":return new Response(e.toString())}},o=(e,r)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:r});

@@ -1,4 +0,4 @@

function e(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,s=new WeakMap;return(e=function(e){return e?s:r})(t)}"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{default:function(){return h},Elysia:function(){return h},t:function(){return i.t},ws:function(){return a.ws},SCHEMA:function(){return r.SCHEMA},DEFS:function(){return r.DEFS},EXPOSED:function(){return r.EXPOSED},getSchemaValidator:function(){return r.getSchemaValidator},mergeDeep:function(){return r.mergeDeep},mergeHook:function(){return r.mergeHook},mergeObjectArray:function(){return r.mergeObjectArray},getResponseSchemaValidator:function(){return r.getResponseSchemaValidator},ParseError:function(){return n.ParseError},NotFoundError:function(){return n.NotFoundError},ValidationError:function(){return n.ValidationError},InternalServerError:function(){return n.InternalServerError}});const t=require("memoirist"),r=require("./utils"),s=require("./schema"),o=require("./compose"),a=require("./ws"),i=require("./custom-types"),n=require("./error");class h{config;store={};meta={[r.SCHEMA]:Object.create(null),[r.DEFS]:Object.create(null),[r.EXPOSED]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t.Memoirist;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}add(e,t,a,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.routes.push({method:e,path:t,handler:a,hooks:(0,r.mergeHook)({...this.event},i)});let h=this.meta[r.DEFS];if(i?.type)switch(i.type){case"text":i.type="text/plain";break;case"json":i.type="application/json";break;case"formdata":i.type="multipart/form-data";break;case"urlencoded":i.type="application/x-www-form-urlencoded"}(0,s.registerSchemaPath)({schema:this.meta[r.SCHEMA],contentType:i?.type,hook:i,method:e,path:t,models:this.meta[r.DEFS]});let u={body:(0,r.getSchemaValidator)(i?.body??this.$schema?.body,h),headers:(0,r.getSchemaValidator)(i?.headers??this.$schema?.headers,h,!0),params:(0,r.getSchemaValidator)(i?.params??this.$schema?.params,h),query:(0,r.getSchemaValidator)(i?.query??this.$schema?.query,h),response:(0,r.getResponseSchemaValidator)(i?.response??this.$schema?.response,h)},c=(0,r.mergeHook)(this.event,i),l=(0,o.composeHandler)({path:t,method:e,hooks:c,validator:u,handler:a,handleError:this.handleError,meta:n?this.meta:void 0});if(-1===t.indexOf(":")&&-1===t.indexOf("*")){let r=this.staticRouter.handlers.length;this.staticRouter.handlers.push(l),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}]
`,this.staticRouter.map[t]||(this.staticRouter.map[t]={code:"",all:"default: break map\n"}),"ALL"===e?this.staticRouter.map[t].all=`default: return st${r}(ctx)
function e(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,s=new WeakMap;return(e=function(e){return e?s:r})(t)}"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{default:function(){return h},Elysia:function(){return h},t:function(){return i.t},ws:function(){return a.ws},SCHEMA:function(){return r.SCHEMA},DEFS:function(){return r.DEFS},EXPOSED:function(){return r.EXPOSED},getSchemaValidator:function(){return r.getSchemaValidator},mergeDeep:function(){return r.mergeDeep},mergeHook:function(){return r.mergeHook},mergeObjectArray:function(){return r.mergeObjectArray},getResponseSchemaValidator:function(){return r.getResponseSchemaValidator},ParseError:function(){return n.ParseError},NotFoundError:function(){return n.NotFoundError},ValidationError:function(){return n.ValidationError},InternalServerError:function(){return n.InternalServerError}});const t=require("memoirist"),r=require("./utils"),s=require("./schema"),o=require("./compose"),a=require("./ws"),i=require("./custom-types"),n=require("./error");class h{config;store={};meta={[r.SCHEMA]:Object.create(null),[r.DEFS]:Object.create(null),[r.EXPOSED]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t.Memoirist;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}add(e,t,a,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.routes.push({method:e,path:t,handler:a,hooks:(0,r.mergeHook)({...this.event},i)});let h=this.meta[r.DEFS];if(i?.type)switch(i.type){case"text":i.type="text/plain";break;case"json":i.type="application/json";break;case"formdata":i.type="multipart/form-data";break;case"urlencoded":i.type="application/x-www-form-urlencoded"}(0,s.registerSchemaPath)({schema:this.meta[r.SCHEMA],contentType:i?.type,hook:i,method:e,path:t,models:this.meta[r.DEFS]});let u={body:(0,r.getSchemaValidator)(i?.body??this.$schema?.body,h),headers:(0,r.getSchemaValidator)(i?.headers??this.$schema?.headers,h,!0),params:(0,r.getSchemaValidator)(i?.params??this.$schema?.params,h),query:(0,r.getSchemaValidator)(i?.query??this.$schema?.query,h),response:(0,r.getResponseSchemaValidator)(i?.response??this.$schema?.response,h)},c=(0,r.mergeHook)(this.event,i),d=(0,o.composeHandler)({path:t,method:e,hooks:c,validator:u,handler:a,handleError:this.handleError,meta:n?this.meta:void 0,onRequest:this.event.request});if(-1===t.indexOf(":")&&-1===t.indexOf("*")){let r=this.staticRouter.handlers.length;this.staticRouter.handlers.push(d),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}]
`,this.staticRouter.map[t]||(this.staticRouter.map[t]={code:""}),"ALL"===e?this.staticRouter.map[t].all=`default: return st${r}(ctx)
`:this.staticRouter.map[t].code+=`case '${e}': return st${r}(ctx)
`}else this.router.add(e,t,l)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,s){let o=new h;o.store=this.store,this.wsRouter&&o.use((0,a.ws)());let i="object"==typeof t,n=(i?s:t)(o);return this.decorators=(0,r.mergeDeep)(this.decorators,o.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(o.routes).forEach(({method:s,path:a,handler:h,hooks:u})=>{if(i){let i=`${e}${a}`,c=o.wsRouter?.find("subscribe",i);if(c){let e=o.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this.add(s,i,h,(0,r.mergeHook)(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${a}`,i=o.wsRouter?.find("subscribe",t);if(i){let e=o.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(t,e[2])}this.add(s,t,h,(0,r.mergeHook)(u,{error:n.event.error}))}}),o.wsRouter&&this.wsRouter&&o.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let s=new h;s.store=this.store,this.wsRouter&&s.use((0,a.ws)());let o=t(s);return this.decorators=(0,r.mergeDeep)(this.decorators,s.decorators),o.event.request.length&&(this.event.request=[...this.event.request,...o.event.request]),this.model(o.meta[r.DEFS]),Object.values(s.routes).forEach(({method:t,path:a,handler:i,hooks:n})=>{let h=s.wsRouter?.find("subscribe",a);if(h){let e=s.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(t,a,i,(0,r.mergeHook)(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...o.event.error]:[n.error,...o.event.error]:o.event.error}))}),s.wsRouter&&this.wsRouter&&s.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),message:(0,r.getSchemaValidator)(t?.body,this.meta[r.DEFS]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=(0,r.mergeDeep)(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=(0,r.mergeDeep)(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(t){return this.use(async r=>{let{fn:s}=await Promise.resolve().then(()=>(function(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var s=e(r);if(s&&s.has(t))return s.get(t);var o={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if("default"!==i&&Object.prototype.hasOwnProperty.call(t,i)){var n=a?Object.getOwnPropertyDescriptor(t,i):null;n&&(n.get||n.set)?Object.defineProperty(o,i,n):o[i]=t[i]}return o.default=t,s&&s.set(t,o),o})(require("@elysiajs/fn")));return s({app:r,value:t,path:r.config.fn})})}schema(e){let t=this.meta[r.DEFS];return this.$schema={body:(0,r.getSchemaValidator)(e.body,t),headers:(0,r.getSchemaValidator)(e?.headers,t,!0),params:(0,r.getSchemaValidator)(e?.params,t),query:(0,r.getSchemaValidator)(e?.query,t),response:(0,r.getSchemaValidator)(e?.response,t)},this}compile(){return this.fetch=(0,o.composeGeneralHandler)(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=(0,o.composeGeneralHandler)(this))(e);handleError=async(e,t,r)=>(this.handleError=(0,o.composeErrorHandler)(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[r.DEFS]||(this.meta[r.DEFS][e]=t)}):this.meta[r.DEFS][e]=t,this}}
`}else this.router.add(e,t,d)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,s){let o=new h;o.store=this.store,this.wsRouter&&o.use((0,a.ws)());let i="object"==typeof t,n=(i?s:t)(o);return this.decorators=(0,r.mergeDeep)(this.decorators,o.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(o.routes).forEach(({method:s,path:a,handler:h,hooks:u})=>{if(i){let i=`${e}${a}`,c=o.wsRouter?.find("subscribe",i);if(c){let e=o.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this.add(s,i,h,(0,r.mergeHook)(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${a}`,i=o.wsRouter?.find("subscribe",t);if(i){let e=o.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(t,e[2])}this.add(s,t,h,(0,r.mergeHook)(u,{error:n.event.error}))}}),o.wsRouter&&this.wsRouter&&o.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let s=new h;s.store=this.store,this.wsRouter&&s.use((0,a.ws)());let o=t(s);return this.decorators=(0,r.mergeDeep)(this.decorators,s.decorators),o.event.request.length&&(this.event.request=[...this.event.request,...o.event.request]),this.model(o.meta[r.DEFS]),Object.values(s.routes).forEach(({method:t,path:a,handler:i,hooks:n})=>{let h=s.wsRouter?.find("subscribe",a);if(h){let e=s.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(t,a,i,(0,r.mergeHook)(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...o.event.error]:[n.error,...o.event.error]:o.event.error}))}),s.wsRouter&&this.wsRouter&&s.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),headers:e.request.headers.toJSON(),message:(0,r.getSchemaValidator)(t?.body,this.meta[r.DEFS]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=(0,r.mergeDeep)(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=(0,r.mergeDeep)(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(t){return this.use(async r=>{let{fn:s}=await Promise.resolve().then(()=>(function(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var s=e(r);if(s&&s.has(t))return s.get(t);var o={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if("default"!==i&&Object.prototype.hasOwnProperty.call(t,i)){var n=a?Object.getOwnPropertyDescriptor(t,i):null;n&&(n.get||n.set)?Object.defineProperty(o,i,n):o[i]=t[i]}return o.default=t,s&&s.set(t,o),o})(require("@elysiajs/fn")));return s({app:r,value:t,path:r.config.fn})})}schema(e){let t=this.meta[r.DEFS];return this.$schema={body:(0,r.getSchemaValidator)(e.body,t),headers:(0,r.getSchemaValidator)(e?.headers,t,!0),params:(0,r.getSchemaValidator)(e?.params,t),query:(0,r.getSchemaValidator)(e?.query,t),response:(0,r.getSchemaValidator)(e?.response,t)},this}compile(){return this.fetch=(0,o.composeGeneralHandler)(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=(0,o.composeGeneralHandler)(this))(e);handleError=async(e,t,r)=>(this.handleError=(0,o.composeErrorHandler)(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[r.DEFS]||(this.meta[r.DEFS][e]=t)}):this.meta[r.DEFS][e]=t,this}}
import type { Elysia } from '.';
import { SCHEMA, DEFS } from './utils';
import type { ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
import type { BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
import { TAnySchema } from '@sinclair/typebox';

@@ -8,3 +8,3 @@ export declare const hasReturn: (fnLiteral: string) => boolean;

export declare const findElysiaMeta: (type: string, schema: TAnySchema, found?: string[], parent?: string) => string[] | "root" | null;
export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta }: {
export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta, onRequest }: {
path: string;

@@ -17,4 +17,5 @@ method: HTTPMethod;

meta?: (Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof import("./utils").EXPOSED, {}>) | undefined;
onRequest: BeforeRequestHandler<any, any>[];
}) => ComposedHandler;
export declare const composeGeneralHandler: (app: Elysia<any>) => any;
export declare const composeErrorHandler: (app: Elysia<any>) => any;

@@ -1,2 +0,2 @@

import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t}from"./handler";import{SCHEMA as n,DEFS as s}from"./utils";import{ParseError as o,NotFoundError as a,ValidationError as c,InternalServerError as i}from"./error";let l="AsyncFunction",f=e=>e.constructor.name===l,d=new Headers,u=RegExp(" (\\w+) = context","g");export const hasReturn=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")};export const isFnUse=(e,r)=>{let t=r.slice(r.indexOf("(")+1,r.indexOf(")"));if(""===t)return!1;if(123===t.charCodeAt(0))return!!(t.includes(`{ ${e}`)||t.includes(`, ${e}`));if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let n=[t];for(let e of r.matchAll(u))n.push(e[1]);let s=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(s))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const findElysiaMeta=(e,r,t=[],n="")=>{if("object"===r.type){let s=r.properties;for(let r in s){let o=s[r],a=n?n+"."+r:r;if("object"===o.type){findElysiaMeta(e,o,t,a);continue}if(o.anyOf){for(let r of o.anyOf)findElysiaMeta(e,r,t,a);continue}o.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(n&&t.push(n),"root"):null};export const composeHandler=({path:u,method:p,hooks:y,validator:h,handler:m,handleError:$,meta:b})=>{let E="try {\n",w="string"==typeof y.type,q=h||"GET"!==p?[m,...y.transform,...y.beforeHandle,...y.afterHandle].map(e=>e.toString()):[],g="GET"!==p&&(h.body||w||q.some(e=>isFnUse("body",e))),x=h.headers||q.some(e=>isFnUse("headers",e));x&&(E+=d.toJSON?`c.headers = c.request.headers.toJSON()
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t,mapCompactResponse as n}from"./handler";import{SCHEMA as s,DEFS as o}from"./utils";import{ParseError as a,NotFoundError as c,ValidationError as i,InternalServerError as l}from"./error";let f="AsyncFunction",d=e=>e.constructor.name===f,u=new Headers,p=RegExp(" (\\w+) = context","g");export const hasReturn=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")};export const isFnUse=(e,r)=>{let t=r.slice(r.indexOf("(")+1,r.indexOf(")"));if(""===t)return!1;if(123===t.charCodeAt(0))return!!(t.includes(`{ ${e}`)||t.includes(`, ${e}`));if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let n=[t];for(let e of r.matchAll(p))n.push(e[1]);let s=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(s))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const findElysiaMeta=(e,r,t=[],n="")=>{if("object"===r.type){let s=r.properties;for(let r in s){let o=s[r],a=n?n+"."+r:r;if("object"===o.type){findElysiaMeta(e,o,t,a);continue}if(o.anyOf){for(let r of o.anyOf)findElysiaMeta(e,r,t,a);continue}o.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(n&&t.push(n),"root"):null};export const composeHandler=({path:p,method:y,hooks:h,validator:m,handler:$,handleError:b,meta:E,onRequest:w})=>{let q="try {\n",g="string"==typeof h.type,x=m||"GET"!==y?[$,...h.transform,...h.beforeHandle,...h.afterHandle].map(e=>e.toString()):[],k="GET"!==y&&(m.body||g||x.some(e=>isFnUse("body",e))),H=m.headers||x.some(e=>isFnUse("headers",e));H&&(q+=u.toJSON?`c.headers = c.request.headers.toJSON()
`:`c.headers = {}

@@ -13,3 +13,3 @@ for (const key of c.request.headers.keys())

}
`);let k=h.query||q.some(e=>isFnUse("query",e));k&&(E+=`const url = c.request.url
`);let R=m.query||x.some(e=>isFnUse("query",e));R&&(q+=`const url = c.request.url

@@ -21,3 +21,3 @@ if(c.query !== -1) {

}
`);let H=g||m.constructor.name===l||y.parse.length||y.afterHandle.find(f)||y.beforeHandle.find(f)||y.transform.find(f);if(g){let e=h?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(w||e){if(y.parse.length){E+=(x?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
`);let v=x.some(e=>isFnUse("set",e))||w.some(e=>isFnUse("set",e.toString())),O=k||$.constructor.name===f||h.parse.length||h.afterHandle.find(d)||h.beforeHandle.find(d)||h.transform.find(d);if(k){let e=m?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(g||e){if(h.parse.length){q+=(H?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
if (contentType) {

@@ -27,6 +27,6 @@ const index = contentType.indexOf(';')

`+`let used = false
`;for(let e=0;e<y.parse.length;e++){let r=`bo${e}`;0!==e&&(E+=`if(!used) {
`),E+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(q+=`if(!used) {
`),q+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
if(${r} !== undefined) { c.body = ${r}; used = true }
`,0!==e&&(E+="}")}E+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?E+="c.body = parseQuery(await c.request.text())":h.body.Code().includes("custom('File")?E+=`c.body = {}
`,0!==e&&(q+="}")}q+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?q+="c.body = parseQuery(await c.request.text())":m.body.Code().includes("custom('File")?q+=`c.body = {}

@@ -43,3 +43,3 @@ await c.request.formData().then((form) => {

}
})`:E+="c.body = JSON.parse(await c.request.text())":E+="c.body = await c.request.text()";else switch(y.type){case"application/json":E+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":E+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":E+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":E+=`c.body = {}
})`:q+="c.body = JSON.parse(await c.request.text())":q+="c.body = await c.request.text()";else switch(h.type){case"application/json":q+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":q+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":q+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":q+=`c.body = {}

@@ -54,11 +54,11 @@ for (const key of (await c.request.formData()).keys()) {

else c.body[key] = value
}`}y.parse.length&&(E+="}}")}else{if(E+="\n"+(x?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
}`}h.parse.length&&(q+="}}")}else{if(q+="\n"+(H?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
if (contentType) {
const index = contentType.indexOf(';')
if (index !== -1) contentType = contentType.substring(0, index)
`,y.parse.length){E+=`let used = false
`;for(let e=0;e<y.parse.length;e++){let r=`bo${e}`;0!==e&&(E+=`if(!used) {
`),E+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
`,h.parse.length){q+=`let used = false
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(q+=`if(!used) {
`),q+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
if(${r} !== undefined) { c.body = ${r}; used = true }
`,0!==e&&(E+="}")}E+="if (!used)"}E+=`switch (contentType) {
`,0!==e&&(q+="}")}q+="if (!used)"}q+=`switch (contentType) {
case 'application/json':

@@ -92,3 +92,3 @@ c.body = JSON.parse(await c.request.text())

}
`}E+="\n"}if(h.params){let e=findElysiaMeta("Numeric",h.params.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.params.${r} = +c.params.${r};`;E+="\n"}}if(h.query){let e=findElysiaMeta("Numeric",h.query.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.query.${r} = +c.query.${r};`;E+="\n"}}if(h.headers){let e=findElysiaMeta("Numeric",h.headers.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.headers.${r} = +c.headers.${r};`;E+="\n"}}if(h.body){let e=findElysiaMeta("Numeric",h.body.schema);if(e){switch(typeof e){case"string":E+="c.body = +c.body;";break;case"object":for(let r of e)E+=`c.body.${r} = +c.body.${r};`}E+="\n"}}if(y?.transform)for(let e=0;e<y.transform.length;e++){let r=y.transform[e];"derive"===r.$elysia?E+=y.transform[e].constructor.name===l?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:E+=y.transform[e].constructor.name===l?`await transform[${e}](c);`:`transform[${e}](c);`}if(h&&(h.headers&&(E+=`
`}q+="\n"}if(m.params){let e=findElysiaMeta("Numeric",m.params.schema);if(e){if("object"==typeof e)for(let r of e)q+=`c.params.${r} = +c.params.${r};`;q+="\n"}}if(m.query){let e=findElysiaMeta("Numeric",m.query.schema);if(e){if("object"==typeof e)for(let r of e)q+=`c.query.${r} = +c.query.${r};`;q+="\n"}}if(m.headers){let e=findElysiaMeta("Numeric",m.headers.schema);if(e){if("object"==typeof e)for(let r of e)q+=`c.headers.${r} = +c.headers.${r};`;q+="\n"}}if(m.body){let e=findElysiaMeta("Numeric",m.body.schema);if(e){switch(typeof e){case"string":q+="c.body = +c.body;";break;case"object":for(let r of e)q+=`c.body.${r} = +c.body.${r};`}q+="\n"}}if(h?.transform)for(let e=0;e<h.transform.length;e++){let r=h.transform[e];"derive"===r.$elysia?q+=h.transform[e].constructor.name===f?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:q+=h.transform[e].constructor.name===f?`await transform[${e}](c);`:`transform[${e}](c);`}if(m&&(m.headers&&(q+=`
if (headers.Check(c.headers) === false) {

@@ -101,22 +101,22 @@ throw new ValidationError(

}
`),h.params&&(E+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),h.query&&(E+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),h.body&&(E+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),y?.beforeHandle)for(let e=0;e<y.beforeHandle.length;e++){let r=`be${e}`,t=hasReturn(y.beforeHandle[e].toString());if(t){if(E+=(y.beforeHandle[e].constructor.name===l?`let ${r} = await beforeHandle[${e}](c);
`),m.params&&(q+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),m.query&&(q+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),m.body&&(q+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),h?.beforeHandle)for(let e=0;e<h.beforeHandle.length;e++){let r=`be${e}`,t=hasReturn(h.beforeHandle[e].toString());if(t){if(q+=(h.beforeHandle[e].constructor.name===f?`let ${r} = await beforeHandle[${e}](c);
`:`let ${r} = beforeHandle[${e}](c);
`)+`if(${r} !== undefined) {
`,y?.afterHandle)for(let e=0;e<y.afterHandle.length;e++){let t=hasReturn(y.afterHandle[e].toString());if(t){let t=`af${e}`;E+=(y.afterHandle[e].constructor.name===l?`const ${t} = await afterHandle[${e}](c, ${r});
`,h?.afterHandle)for(let e=0;e<h.afterHandle.length;e++){let t=hasReturn(h.afterHandle[e].toString());if(t){let t=`af${e}`;q+=(h.afterHandle[e].constructor.name===f?`const ${t} = await afterHandle[${e}](c, ${r});
`:`const ${t} = afterHandle[${e}](c, ${r});
`)+`if(${t} !== undefined) { ${r} = ${t} }
`}else E+=y.afterHandle[e].constructor.name===l?`await afterHandle[${e}](c, ${r});
`}else q+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, ${r});
`:`afterHandle[${e}](c, ${r});
`}h.response&&(E+=`if(response[c.set.status]?.Check(${r}) === false) {
`}m.response&&(q+=`if(response[c.set.status]?.Check(${r}) === false) {
if(!(response instanceof Error))
throw new ValidationError('response', response[c.set.status], ${r})
}
`),E+=`return mapEarlyResponse(${r}, c.set)}
`}else E+=y.beforeHandle[e].constructor.name===l?`await beforeHandle[${e}](c);
`),q+=`return mapEarlyResponse(${r}, c.set)}
`}else q+=h.beforeHandle[e].constructor.name===f?`await beforeHandle[${e}](c);
`:`beforeHandle[${e}](c);
`}if(y?.afterHandle.length){E+=m.constructor.name===l?`let r = await handler(c);
`}if(h?.afterHandle.length){q+=$.constructor.name===f?`let r = await handler(c);
`:`let r = handler(c);
`;for(let e=0;e<y.afterHandle.length;e++){let r=`af${e}`,t=hasReturn(y.afterHandle[e].toString());t?(E+=y.afterHandle[e].constructor.name===l?`let ${r} = await afterHandle[${e}](c, r)
`;for(let e=0;e<h.afterHandle.length;e++){let r=`af${e}`,t=hasReturn(h.afterHandle[e].toString());t?(q+=h.afterHandle[e].constructor.name===f?`let ${r} = await afterHandle[${e}](c, r)
`:`let ${r} = afterHandle[${e}](c, r)
`,h.response?E+=`if(response[c.set.status]?.Check(${r}) === false) {
`,m.response?q+=`if(response[c.set.status]?.Check(${r}) === false) {
if(!(response instanceof Error))

@@ -127,11 +127,12 @@ throw new ValidationError('response', response[c.set.status], ${r})

if(${r}) return ${r};
`:E+=`if(${r}) return ${r};
`):E+=y.afterHandle[e].constructor.name===l?`await afterHandle[${e}](c, r)
`:q+=`if(${r}) return ${r};
`):q+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, r)
`:`afterHandle[${e}](c, r)
`}h.response&&(E+=`if(response[c.set.status]?.Check(r) === false) {
`}m.response&&(q+=`if(response[c.set.status]?.Check(r) === false) {
if(!(response instanceof Error))
throw new ValidationError('response', response[c.set.status], r)
}
`),E+=`return mapResponse(r, c.set);
`}else h.response?E+=(m.constructor.name===l?`const r = await handler(c);
`),v?q+=`return mapResponse(r, c.set)
`:q+=`return mapCompactResponse(r)
`}else if(m.response)q+=($.constructor.name===f?`const r = await handler(c);
`:`const r = handler(c);

@@ -142,7 +143,11 @@ `)+`if(response[c.set.status]?.Check(r) === false) {

}
`+"return mapResponse(r, c.set);":E+=m.constructor.name===l?"return mapResponse(await handler(c), c.set);":"return mapResponse(handler(c), c.set);";E+=`
`,v?q+=`return mapResponse(r, c.set)
`:q+=`return mapCompactResponse(r)
`;else{let e=$.constructor.name===f?"await handler(c) ":"handler(c)";v?q+=`return mapResponse(${e}, c.set)
`:q+=`return mapCompactResponse(${e})
`}q+=`
} catch(error) {
${H?"":"return (async () => {"}
${O?"":"return (async () => {"}
const set = c.set

@@ -152,3 +157,3 @@

${y.error.length?`for (let i = 0; i < handleErrors.length; i++) {
${h.error.length?`for (let i = 0; i < handleErrors.length; i++) {
let handled = handleErrors[i]({

@@ -167,4 +172,4 @@ request: c.request,

return handleError(c.request, error, set)
${H?"":"})()"}
}`,E=`const {
${O?"":"})()"}
}`,q=`const {
handler,

@@ -188,2 +193,3 @@ handleError,

mapResponse,
mapCompactResponse,
mapEarlyResponse,

@@ -199,3 +205,3 @@ mapErrorCode,

},
${b?`
${E?`
meta,

@@ -208,11 +214,23 @@ SCHEMA,

return ${H?"async":""} function(c) {
${b?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""}
${E}
}`;let v=Function("hooks",E);return v({handler:m,hooks:y,validator:h,handleError:$,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:o,NotFoundError:a,ValidationError:c,InternalServerError:i},meta:b,SCHEMA:b?n:void 0,DEFS:b?s:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let n=e.staticRouter,s="";for(let[e,{code:r,all:t}]of Object.entries(n.map))s+=`case '${e}':
return ${O?"async":""} function(c) {
${E?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""}
${q}
}`;let C=Function("hooks",q);return C({handler:$,hooks:h,validator:m,handleError:b,utils:{mapResponse:t,mapCompactResponse:n,mapEarlyResponse:r,parseQuery:e},error:{ParseError:a,NotFoundError:c,ValidationError:i,InternalServerError:l},meta:E,SCHEMA:E?s:void 0,DEFS:E?o:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:n,staticRouter:s}=e,o=`const route = find(method, path) ${n.root.ALL?'?? find("ALL", path)':""}
if (route === null)
return ${e.event.error.length?`handleError(
request,
notFound,
ctx.set
)`:`new Response(error404, {
status: 404
})`}
ctx.params = route.params
return route.store(ctx)`,a="";for(let[e,{code:r,all:t}]of Object.entries(s.map))a+=`case '${e}':
switch(method) {
${r}
${t}}
${t??"default:\n"+o}}
`;let o=e.router,c=`const {
`;let i=`const {
app,

@@ -228,3 +246,3 @@ app: { store, router, staticRouter },

${n.variables}
${s.variables}

@@ -246,3 +264,3 @@ const find = router.find.bind(router)

}
`;if(e.event.request.length){c+="try {";for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());c+=t?`const response = mapEarlyResponse(
`;if(e.event.request.length){i+="try {";for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());i+=t?`const response = mapEarlyResponse(
onRequest[${r}](ctx),

@@ -252,29 +270,16 @@ ctx.set

if (response) return response
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}c+=`} catch (error) {
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}i+=`} catch (error) {
return handleError(request, error, ctx.set)
}`}return c+=`
}`}return i+=`
const { url, method } = request,
s = url.indexOf('/', 12)
ctx.query = i = url.indexOf('?', s + 1),
s = url.indexOf('/', 12),
i = ctx.query = url.indexOf('?', s + 1),
path = i === -1 ? url.substring(s) : url.substring(s, i)
map: switch(path) {
${s}
switch(path) {
${a}
default: ${o}
}
const route = find(method, path) ${o.root.ALL?'?? find("ALL", path)':""}
if (route === null) {
return ${e.event.error.length?`handleError(
request,
notFound,
ctx.set
)`:`new Response(error404, {
status: 404
})`}
}
ctx.params = route.params
return route.store(ctx)
}`,e.handleError=composeErrorHandler(e),Function("data",c)({app:e,mapEarlyResponse:r,NotFoundError:a})};export const composeErrorHandler=e=>{let r=`const {
}`,e.handleError=composeErrorHandler(e),Function("data",i)({app:e,mapEarlyResponse:r,NotFoundError:c})};export const composeErrorHandler=e=>{let r=`const {
app: { event: { error: onError } },

@@ -284,3 +289,3 @@ mapResponse

return ${e.event.error.find(e=>e.constructor.name===l)?"async":""} function(request, error, set) {`;for(let t=0;t<e.event.error.length;t++){let n=e.event.error[t],s=`${n.constructor.name===l?"await ":""}onError[${t}]({
return ${e.event.error.find(e=>e.constructor.name===f)?"async":""} function(request, error, set) {`;for(let t=0;t<e.event.error.length;t++){let n=e.event.error[t],s=`${n.constructor.name===f?"await ":""}onError[${t}]({
request,

@@ -287,0 +292,0 @@ code: error.code ?? 'UNKNOWN',

@@ -6,2 +6,3 @@ /// <reference types="bun-types" />

export declare const mapResponse: (response: unknown, set: Context['set']) => Response;
export declare const mapCompactResponse: (response: unknown) => Response;
export declare const errorToResponse: (error: Error, headers?: HeadersInit) => Response;

@@ -1,1 +0,1 @@

export const isNotEmpty=e=>{for(let s in e)return!0;return!1};let e=(e,s)=>{e.delete("Set-Cookie");for(let r=0;r<s.length;r++){let t=s[r].indexOf("=");e.append("Set-Cookie",`${s[r].slice(0,t)}=${s[r].slice(t+1)}`)}return e};export const mapEarlyResponse=(s,r)=>{if(isNotEmpty(r.headers)||200!==r.status||r.redirect)switch(r.redirect&&(r.headers.Location=r.redirect,r.status=302),r.headers["Set-Cookie"]&&Array.isArray(r.headers["Set-Cookie"])&&(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"])),typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":switch(s.constructor.name){case"Object":case"Array":case void 0:return Response.json(s,{status:r.status,headers:r.headers});case"Error":return errorToResponse(s,r.headers);case"Response":for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case"Blob":default:return new Response(s,{status:r.status,headers:r.headers});case"Promise":return s.then(e=>{let s=mapEarlyResponse(e,r);if(void 0!==s)return s})}case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers})}else switch(typeof s){case"string":return new Response(s);case"object":switch(s.constructor?.name){case"Object":case"Array":case void 0:return Response.json(s);case"Response":return s;case"Error":return errorToResponse(s,r.headers);case"Blob":default:return new Response(s);case"Promise":return s.then(e=>{let s=mapEarlyResponse(e,r);if(void 0!==s)return s})}case"function":if(s instanceof Blob)return new Response(s);return s;case"number":case"boolean":return new Response(s.toString())}};export const mapResponse=(s,r)=>{if(isNotEmpty(r.headers)||200!==r.status||r.redirect)switch(r.redirect&&(r.headers.Location=r.redirect,r.status=302),r.headers["Set-Cookie"]&&Array.isArray(r.headers["Set-Cookie"])&&(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"])),typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":switch(s.constructor?.name){case"Object":case"Array":case void 0:return Response.json(s,{status:r.status,headers:r.headers});case"Error":return errorToResponse(s,r.headers);case"Response":for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case"Blob":default:return new Response(s,{status:r.status,headers:r.headers});case"Promise":return s.then(e=>mapResponse(e,r))}case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});return s();case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers});case"undefined":return new Response("",{status:r.status,headers:r.headers});default:return new Response(s,{status:r.status,headers:r.headers})}else switch(typeof s){case"string":return new Response(s);case"object":switch(s.constructor?.name){case"Object":case"Array":case void 0:return Response.json(s);case"Response":return s;case"Error":return errorToResponse(s,r.headers);case"Blob":default:return new Response(s);case"Promise":return s.then(e=>{let s=mapEarlyResponse(e,r);return void 0!==s?s:new Response("")})}case"function":if(s instanceof Blob)return new Response(s);return s();case"number":case"boolean":return new Response(s.toString());case"undefined":return new Response("");default:return new Response(s)}};export const errorToResponse=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s});
export const isNotEmpty=e=>{for(let r in e)return!0;return!1};let e=(e,r)=>{e.delete("Set-Cookie");for(let s=0;s<r.length;s++){let n=r[s].indexOf("=");e.append("Set-Cookie",`${r[s].slice(0,n)}=${r[s].slice(n+1)}`)}return e};export const mapEarlyResponse=(r,s)=>{if(isNotEmpty(s.headers)||200!==s.status||s.redirect)switch(s.redirect&&(s.headers.Location=s.redirect,s.status=302),s.headers["Set-Cookie"]&&Array.isArray(s.headers["Set-Cookie"])&&(s.headers=e(new Headers(s.headers),s.headers["Set-Cookie"])),r?.constructor?.name){case"String":case"Blob":return new Response(r,s);case"Object":case"Array":return Response.json(r,s);case void 0:if(!r)return;return Response.json(r,s);case"Response":for(let e in s.headers)r.headers.append(e,s.headers[e]);return r;case"Promise":return r.then(e=>{let r=mapEarlyResponse(e,s);if(void 0!==r)return r});case"Error":return errorToResponse(r,s.headers);case"Function":return r();case"Number":case"Boolean":return new Response(r.toString(),s);default:return}else switch(r?.constructor?.name){case"String":case"Blob":return new Response(r);case"Object":case"Array":return Response.json(r);case void 0:if(!r)return new Response("");return Response.json(r);case"Response":return r;case"Promise":return r.then(e=>{let r=mapEarlyResponse(e,s);if(void 0!==r)return r});case"Error":return errorToResponse(r,s.headers);case"Function":return r();case"Number":case"Boolean":return new Response(r.toString());default:return}};export const mapResponse=(r,s)=>{if(isNotEmpty(s.headers)||200!==s.status||s.redirect)switch(s.redirect&&(s.headers.Location=s.redirect,s.status=302),s.headers["Set-Cookie"]&&Array.isArray(s.headers["Set-Cookie"])&&(s.headers=e(new Headers(s.headers),s.headers["Set-Cookie"])),r?.constructor?.name){case"String":case"Blob":return new Response(r,{status:s.status,headers:s.headers});case"Object":case"Array":return Response.json(r,s);case void 0:if(!r)return new Response("",s);return Response.json(r,s);case"Response":for(let e in s.headers)r.headers.append(e,s.headers[e]);return r;case"Error":return errorToResponse(r,s.headers);case"Promise":return r.then(e=>mapResponse(e,s));case"Function":return r();case"Number":case"Boolean":return new Response(r.toString(),s);default:return new Response(r,s)}else switch(r?.constructor?.name){case"String":case"Blob":return new Response(r);case"Object":case"Array":return Response.json(r);case void 0:if(!r)return new Response("");return Response.json(r);case"Response":default:return r;case"Error":return errorToResponse(r);case"Promise":return r.then(e=>{let r=mapResponse(e,s);return void 0!==r?r:new Response("")});case"Function":return r();case"Number":case"Boolean":return new Response(r.toString())}};export const mapCompactResponse=e=>{switch(e.constructor?.name){case"String":case"Blob":return new Response(e);case"Object":case"Array":return Response.json(e);case void 0:if(!e)return new Response("");return Response.json(e);case"Response":default:return e;case"Error":return errorToResponse(e);case"Promise":return e.then(e=>{let r=mapCompactResponse(e);return void 0!==r?r:new Response("")});case"Function":return e();case"Number":case"Boolean":return new Response(e.toString())}};export const errorToResponse=(e,r)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:r});

@@ -1,4 +0,4 @@

import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as i,getResponseSchemaValidator as a,mergeDeep as h}from"./utils";import{registerSchemaPath as n}from"./schema";import{composeErrorHandler as u,composeGeneralHandler as d,composeHandler as l}from"./compose";import{ws as c}from"./ws";export default class p{config;store={};meta={[t]:Object.create(null),[s]:Object.create(null),[r]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}add(e,r,h,u,{allowMeta:d=!1}={allowMeta:!1}){r=""===r?r:47===r.charCodeAt(0)?r:`/${r}`,this.routes.push({method:e,path:r,handler:h,hooks:o({...this.event},u)});let c=this.meta[s];if(u?.type)switch(u.type){case"text":u.type="text/plain";break;case"json":u.type="application/json";break;case"formdata":u.type="multipart/form-data";break;case"urlencoded":u.type="application/x-www-form-urlencoded"}n({schema:this.meta[t],contentType:u?.type,hook:u,method:e,path:r,models:this.meta[s]});let p={body:i(u?.body??this.$schema?.body,c),headers:i(u?.headers??this.$schema?.headers,c,!0),params:i(u?.params??this.$schema?.params,c),query:i(u?.query??this.$schema?.query,c),response:a(u?.response??this.$schema?.response,c)},f=o(this.event,u),m=l({path:r,method:e,hooks:f,validator:p,handler:h,handleError:this.handleError,meta:d?this.meta:void 0});if(-1===r.indexOf(":")&&-1===r.indexOf("*")){let t=this.staticRouter.handlers.length;this.staticRouter.handlers.push(m),this.staticRouter.variables+=`const st${t} = staticRouter.handlers[${t}]
`,this.staticRouter.map[r]||(this.staticRouter.map[r]={code:"",all:"default: break map\n"}),"ALL"===e?this.staticRouter.map[r].all=`default: return st${t}(ctx)
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as i,getResponseSchemaValidator as a,mergeDeep as h}from"./utils";import{registerSchemaPath as n}from"./schema";import{composeErrorHandler as u,composeGeneralHandler as d,composeHandler as l}from"./compose";import{ws as c}from"./ws";export default class p{config;store={};meta={[t]:Object.create(null),[s]:Object.create(null),[r]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}add(e,r,h,u,{allowMeta:d=!1}={allowMeta:!1}){r=""===r?r:47===r.charCodeAt(0)?r:`/${r}`,this.routes.push({method:e,path:r,handler:h,hooks:o({...this.event},u)});let c=this.meta[s];if(u?.type)switch(u.type){case"text":u.type="text/plain";break;case"json":u.type="application/json";break;case"formdata":u.type="multipart/form-data";break;case"urlencoded":u.type="application/x-www-form-urlencoded"}n({schema:this.meta[t],contentType:u?.type,hook:u,method:e,path:r,models:this.meta[s]});let p={body:i(u?.body??this.$schema?.body,c),headers:i(u?.headers??this.$schema?.headers,c,!0),params:i(u?.params??this.$schema?.params,c),query:i(u?.query??this.$schema?.query,c),response:a(u?.response??this.$schema?.response,c)},f=o(this.event,u),m=l({path:r,method:e,hooks:f,validator:p,handler:h,handleError:this.handleError,meta:d?this.meta:void 0,onRequest:this.event.request});if(-1===r.indexOf(":")&&-1===r.indexOf("*")){let t=this.staticRouter.handlers.length;this.staticRouter.handlers.push(m),this.staticRouter.variables+=`const st${t} = staticRouter.handlers[${t}]
`,this.staticRouter.map[r]||(this.staticRouter.map[r]={code:""}),"ALL"===e?this.staticRouter.map[r].all=`default: return st${t}(ctx)
`:this.staticRouter.map[r].code+=`case '${e}': return st${t}(ctx)
`}else this.router.add(e,r,m)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,r){let i=new p;i.store=this.store,this.wsRouter&&i.use(c());let a="object"==typeof t,n=(a?r:t)(i);return this.decorators=h(this.decorators,i.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(i.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(a){let a=`${e}${s}`,d=i.wsRouter?.find("subscribe",a);if(d){let e=i.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(r,a,h,o(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${s}`,a=i.wsRouter?.find("subscribe",t);if(a){let e=i.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this.add(r,t,h,o(u,{error:n.event.error}))}}),i.wsRouter&&this.wsRouter&&i.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let r=new p;r.store=this.store,this.wsRouter&&r.use(c());let i=t(r);return this.decorators=h(this.decorators,r.decorators),i.event.request.length&&(this.event.request=[...this.event.request,...i.event.request]),this.model(i.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:a,hooks:h})=>{let n=r.wsRouter?.find("subscribe",s);if(n){let e=r.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(s,e[2])}this.add(t,s,a,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...i.event.error]:[h.error,...i.event.error]:i.event.error}))}),r.wsRouter&&this.wsRouter&&r.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),message:i(t?.body,this.meta[s]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=h(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=h(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(e){return this.use(async t=>{let{fn:r}=await import("@elysiajs/fn");return r({app:t,value:e,path:t.config.fn})})}schema(e){let t=this.meta[s];return this.$schema={body:i(e.body,t),headers:i(e?.headers,t,!0),params:i(e?.params,t),query:i(e?.query,t),response:i(e?.response,t)},this}compile(){return this.fetch=d(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=d(this))(e);handleError=async(e,t,r)=>(this.handleError=u(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[s]||(this.meta[s][e]=t)}):this.meta[s][e]=t,this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{p as Elysia};
`}else this.router.add(e,r,m)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,r){let i=new p;i.store=this.store,this.wsRouter&&i.use(c());let a="object"==typeof t,n=(a?r:t)(i);return this.decorators=h(this.decorators,i.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(i.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(a){let a=`${e}${s}`,d=i.wsRouter?.find("subscribe",a);if(d){let e=i.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(r,a,h,o(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${s}`,a=i.wsRouter?.find("subscribe",t);if(a){let e=i.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this.add(r,t,h,o(u,{error:n.event.error}))}}),i.wsRouter&&this.wsRouter&&i.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let r=new p;r.store=this.store,this.wsRouter&&r.use(c());let i=t(r);return this.decorators=h(this.decorators,r.decorators),i.event.request.length&&(this.event.request=[...this.event.request,...i.event.request]),this.model(i.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:a,hooks:h})=>{let n=r.wsRouter?.find("subscribe",s);if(n){let e=r.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(s,e[2])}this.add(t,s,a,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...i.event.error]:[h.error,...i.event.error]:i.event.error}))}),r.wsRouter&&this.wsRouter&&r.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),headers:e.request.headers.toJSON(),message:i(t?.body,this.meta[s]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=h(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=h(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(e){return this.use(async t=>{let{fn:r}=await import("@elysiajs/fn");return r({app:t,value:e,path:t.config.fn})})}schema(e){let t=this.meta[s];return this.$schema={body:i(e.body,t),headers:i(e?.headers,t,!0),params:i(e?.params,t),query:i(e?.query,t),response:i(e?.response,t)},this}compile(){return this.fetch=d(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=d(this))(e);handleError=async(e,t,r)=>(this.handleError=u(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[s]||(this.meta[s][e]=t)}):this.meta[s][e]=t,this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{p as Elysia};
{
"name": "elysia",
"description": "Fast, and friendly Bun web framework",
"version": "0.5.2",
"version": "0.5.3",
"author": {

@@ -6,0 +6,0 @@ "name": "saltyAom",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc