Comparing version 0.5.1 to 0.5.2
@@ -203,3 +203,3 @@ "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() | ||
`;let a=`const { | ||
`;let a=e.router,c=`const { | ||
app, | ||
@@ -232,3 +232,3 @@ app: { store, router, staticRouter }, | ||
} | ||
`;if(e.event.request.length){a+="try {";for(let r=0;r<e.event.request.length;r++){let t=i(e.event.request[r].toString());a+=t?`const response = mapEarlyResponse( | ||
`;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( | ||
onRequest[${r}](ctx), | ||
@@ -238,8 +238,8 @@ ctx.set | ||
if (response) return response | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}a+=`} catch (error) { | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}c+=`} catch (error) { | ||
return handleError(request, error, ctx.set) | ||
}`}return a+=` | ||
}`}return c+=` | ||
const { url, method } = request, | ||
s = url.indexOf('/', 12) | ||
ctx.query = i = url.indexOf('?', s), | ||
ctx.query = i = url.indexOf('?', s + 1), | ||
path = i === -1 ? url.substring(s) : url.substring(s, i) | ||
@@ -251,3 +251,3 @@ | ||
const route = find(method, path) ?? find('ALL', path) | ||
const route = find(method, path) ${a.root.ALL?'?? find("ALL", path)':""} | ||
if (route === null) { | ||
@@ -266,3 +266,3 @@ return ${e.event.error.length?`handleError( | ||
return route.store(ctx) | ||
}`,e.handleError=p(e),Function("data",a)({app:e,mapEarlyResponse:r.mapEarlyResponse,NotFoundError:n.NotFoundError})},p=e=>{let t=`const { | ||
}`,e.handleError=p(e),Function("data",c)({app:e,mapEarlyResponse:r.mapEarlyResponse,NotFoundError:n.NotFoundError})},p=e=>{let t=`const { | ||
app: { event: { error: onError } }, | ||
@@ -269,0 +269,0 @@ mapResponse |
@@ -24,3 +24,3 @@ /// <reference types="bun-types" /> | ||
constructor(config?: Partial<ElysiaConfig>); | ||
private _addHandler; | ||
private add; | ||
onStart(handler: VoidLifeCycle<Instance>): this; | ||
@@ -364,3 +364,3 @@ onRequest<Route extends OverwritableTypeRoute = TypedRoute>(handler: BeforeRequestHandler<Route, Instance>): this; | ||
}>; | ||
state<const Key extends string | number | symbol, const Value>(name: Key, value: Value): Elysia<{ | ||
state<Key extends string | number | symbol, Value>(name: Key, value: Value): Elysia<{ | ||
store: Instance['store'] & { | ||
@@ -373,3 +373,3 @@ [key in Key]: Value; | ||
}>; | ||
state<const NewStore extends Record<string, unknown>>(store: NewStore): Elysia<{ | ||
state<NewStore extends Record<string, unknown>>(store: NewStore): Elysia<{ | ||
store: Instance['store'] & DeepWritable<NewStore>; | ||
@@ -376,0 +376,0 @@ request: Instance['request']; |
@@ -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 o.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"),a=require("./compose"),o=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}}_addHandler(e,t,o,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.routes.push({method:e,path:t,handler:o,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)},l=(0,r.mergeHook)(this.event,i),d=(0,a.composeHandler)({path:t,method:e,hooks:l,validator:u,handler:o,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(d),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}] | ||
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) | ||
`:this.staticRouter.map[t].code+=`case '${e}': return st${r}(ctx) | ||
`}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 a=new h;a.store=this.store,this.wsRouter&&a.use((0,o.ws)());let i="object"==typeof t,n=(i?s:t)(a);return this.decorators=(0,r.mergeDeep)(this.decorators,a.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(a.routes).forEach(({method:s,path:o,handler:h,hooks:u})=>{if(i){let i=`${e}${o}`,l=a.wsRouter?.find("subscribe",i);if(l){let e=a.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this._addHandler(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}${o}`,i=a.wsRouter?.find("subscribe",t);if(i){let e=a.wsRouter.history.find(([e,t])=>o===t);if(!e)return;return this.ws(t,e[2])}this._addHandler(s,t,h,(0,r.mergeHook)(u,{error:n.event.error}))}}),a.wsRouter&&this.wsRouter&&a.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,o.ws)());let a=t(s);return this.decorators=(0,r.mergeDeep)(this.decorators,s.decorators),a.event.request.length&&(this.event.request=[...this.event.request,...a.event.request]),this.model(a.meta[r.DEFS]),Object.values(s.routes).forEach(({method:t,path:o,handler:i,hooks:n})=>{let h=s.wsRouter?.find("subscribe",o);if(h){let e=s.wsRouter.history.find(([e,t])=>o===t);if(!e)return;return this.ws(o,e[2])}this._addHandler(t,o,i,(0,r.mergeHook)(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...a.event.error]:[n.error,...a.event.error]:a.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._addHandler("GET",e,t,r),this}post(e,t,r){return this._addHandler("POST",e,t,r),this}put(e,t,r){return this._addHandler("PUT",e,t,r),this}patch(e,t,r){return this._addHandler("PATCH",e,t,r),this}delete(e,t,r){return this._addHandler("DELETE",e,t,r),this}options(e,t,r){return this._addHandler("OPTIONS",e,t,r),this}all(e,t,r){return this._addHandler("ALL",e,t,r),this}head(e,t,r){return this._addHandler("HEAD",e,t,r),this}trace(e,t,r){return this._addHandler("TRACE",e,t,r),this}connect(e,t,r){return this._addHandler("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,...a}={config:{allowMeta:!1}}){return this._addHandler(e,t,r,a,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 a={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if("default"!==i&&Object.prototype.hasOwnProperty.call(t,i)){var n=o?Object.getOwnPropertyDescriptor(t,i):null;n&&(n.get||n.set)?Object.defineProperty(a,i,n):a[i]=t[i]}return a.default=t,s&&s.set(t,a),a})(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,a.composeGeneralHandler)(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=(0,a.composeGeneralHandler)(this))(e);handleError=async(e,t,r)=>(this.handleError=(0,a.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",a="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:${a.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(a)):globalThis[e]=this.server=Bun.serve(a)}else this.server=Bun.serve(a);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,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}} |
@@ -203,3 +203,3 @@ 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() | ||
`;let o=`const { | ||
`;let o=e.router,c=`const { | ||
app, | ||
@@ -232,3 +232,3 @@ app: { store, router, staticRouter }, | ||
} | ||
`;if(e.event.request.length){o+="try {";for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());o+=t?`const response = mapEarlyResponse( | ||
`;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( | ||
onRequest[${r}](ctx), | ||
@@ -238,8 +238,8 @@ ctx.set | ||
if (response) return response | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}o+=`} catch (error) { | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}c+=`} catch (error) { | ||
return handleError(request, error, ctx.set) | ||
}`}return o+=` | ||
}`}return c+=` | ||
const { url, method } = request, | ||
s = url.indexOf('/', 12) | ||
ctx.query = i = url.indexOf('?', s), | ||
ctx.query = i = url.indexOf('?', s + 1), | ||
path = i === -1 ? url.substring(s) : url.substring(s, i) | ||
@@ -251,3 +251,3 @@ | ||
const route = find(method, path) ?? find('ALL', path) | ||
const route = find(method, path) ${o.root.ALL?'?? find("ALL", path)':""} | ||
if (route === null) { | ||
@@ -266,3 +266,3 @@ return ${e.event.error.length?`handleError( | ||
return route.store(ctx) | ||
}`,e.handleError=composeErrorHandler(e),Function("data",o)({app:e,mapEarlyResponse:r,NotFoundError:a})};export const composeErrorHandler=e=>{let r=`const { | ||
}`,e.handleError=composeErrorHandler(e),Function("data",c)({app:e,mapEarlyResponse:r,NotFoundError:a})};export const composeErrorHandler=e=>{let r=`const { | ||
app: { event: { error: onError } }, | ||
@@ -269,0 +269,0 @@ mapResponse |
@@ -24,3 +24,3 @@ /// <reference types="bun-types" /> | ||
constructor(config?: Partial<ElysiaConfig>); | ||
private _addHandler; | ||
private add; | ||
onStart(handler: VoidLifeCycle<Instance>): this; | ||
@@ -364,3 +364,3 @@ onRequest<Route extends OverwritableTypeRoute = TypedRoute>(handler: BeforeRequestHandler<Route, Instance>): this; | ||
}>; | ||
state<const Key extends string | number | symbol, const Value>(name: Key, value: Value): Elysia<{ | ||
state<Key extends string | number | symbol, Value>(name: Key, value: Value): Elysia<{ | ||
store: Instance['store'] & { | ||
@@ -373,3 +373,3 @@ [key in Key]: Value; | ||
}>; | ||
state<const NewStore extends Record<string, unknown>>(store: NewStore): Elysia<{ | ||
state<NewStore extends Record<string, unknown>>(store: NewStore): Elysia<{ | ||
store: Instance['store'] & DeepWritable<NewStore>; | ||
@@ -376,0 +376,0 @@ request: Instance['request']; |
@@ -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 a,getResponseSchemaValidator as i,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}}_addHandler(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:a(u?.body??this.$schema?.body,c),headers:a(u?.headers??this.$schema?.headers,c,!0),params:a(u?.params??this.$schema?.params,c),query:a(u?.query??this.$schema?.query,c),response:i(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}] | ||
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) | ||
`: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 a=new p;a.store=this.store,this.wsRouter&&a.use(c());let i="object"==typeof t,n=(i?r:t)(a);return this.decorators=h(this.decorators,a.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(a.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(i){let i=`${e}${s}`,d=a.wsRouter?.find("subscribe",i);if(d){let e=a.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this._addHandler(r,i,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}`,i=a.wsRouter?.find("subscribe",t);if(i){let e=a.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this._addHandler(r,t,h,o(u,{error:n.event.error}))}}),a.wsRouter&&this.wsRouter&&a.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 a=t(r);return this.decorators=h(this.decorators,r.decorators),a.event.request.length&&(this.event.request=[...this.event.request,...a.event.request]),this.model(a.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:i,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._addHandler(t,s,i,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...a.event.error]:[h.error,...a.event.error]:a.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._addHandler("GET",e,t,r),this}post(e,t,r){return this._addHandler("POST",e,t,r),this}put(e,t,r){return this._addHandler("PUT",e,t,r),this}patch(e,t,r){return this._addHandler("PATCH",e,t,r),this}delete(e,t,r){return this._addHandler("DELETE",e,t,r),this}options(e,t,r){return this._addHandler("OPTIONS",e,t,r),this}all(e,t,r){return this._addHandler("ALL",e,t,r),this}head(e,t,r){return this._addHandler("HEAD",e,t,r),this}trace(e,t,r){return this._addHandler("TRACE",e,t,r),this}connect(e,t,r){return this._addHandler("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:a(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._addHandler(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:a(e.body,t),headers:a(e?.headers,t,!0),params:a(e?.params,t),query:a(e?.query,t),response:a(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(),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.1", | ||
"version": "0.5.2", | ||
"author": { | ||
@@ -125,3 +125,3 @@ "name": "saltyAom", | ||
"bumpp": "^9.1.0", | ||
"bun-types": "^0.5.8", | ||
"bun-types": "^0.6.2", | ||
"eslint": "^8.36.0", | ||
@@ -133,3 +133,3 @@ "expect-type": "^0.15.0", | ||
"peerDependencies": { | ||
"@sinclair/typebox": ">= 0.26.0", | ||
"@sinclair/typebox": ">= 0.28.10", | ||
"openapi-types": ">= 12.0.0", | ||
@@ -136,0 +136,0 @@ "typescript": ">= 5.0.0" |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
197717