Comparing version 0.4.0-exp-230319.1936 to 0.4.0-exp-230322.29
@@ -1,2 +0,2 @@ | ||
import type { Elysia } from '.'; | ||
import { Elysia } from '.'; | ||
import type { HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types'; | ||
@@ -3,0 +3,0 @@ export declare const composeHandler: ({ method, hooks, validator, handler, handleError }: { |
@@ -1,2 +0,2 @@ | ||
import{parse as e}from"fast-querystring";import{deserialize as r}from"superjson";import{createValidationError as a}from"./utils";import{mapEarlyResponse as t,mapResponse as n}from"./handler";import{mapErrorCode as o}from"./error";let s="AsyncFunction",c=e=>e.constructor.name===s;export const composeHandler=({method:l,hooks:d,validator:i,handler:f,handleError:p})=>{let u="try {\n",m="GET"!==l||f.constructor.name===s||d.parse.length||d.afterHandle.find(c)||d.beforeHandle.find(c)||d.transform.find(c);if(m){if(u+=` | ||
import{parse as e}from"fast-querystring";import{deserialize as r}from"superjson";import{createValidationError as a}from"./utils";import{mapEarlyResponse as t,mapResponse as o}from"./handler";import{mapErrorCode as s}from"./error";let n="AsyncFunction",c=e=>e.constructor.name===n;export const composeHandler=({method:l,hooks:i,validator:f,handler:p,handleError:u})=>{let h="try {\n",y="GET"!==l||p.constructor.name===n||i.parse.length||i.afterHandle.find(c)||i.beforeHandle.find(c)||i.transform.find(c);if(y){if(h+=` | ||
let contentType = c.request.headers.get('content-type'); | ||
@@ -7,8 +7,8 @@ | ||
if (index !== -1) contentType = contentType.slice(0, index); | ||
`,d.parse.length){u+=`used = false | ||
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;u+=`if(!c.request.bodyUsed) { | ||
`,i.parse.length){h+=`used = false | ||
`;for(let e=0;e<i.parse.length;e++){let r=`bo${e}`;h+=`if(!c.request.bodyUsed) { | ||
let ${r} = parse[${e}](c, contentType); | ||
if(${r} instanceof Promise) ${r} = await ${r} | ||
if(${r} !== undefined) { c.body = ${r}; used = true } | ||
}`}u+="if (!used)"}u+=`switch (contentType) { | ||
}`}h+="if (!used)"}h+=`switch (contentType) { | ||
case 'application/json': | ||
@@ -49,3 +49,3 @@ c.body = await c.request.json() | ||
`.replace(/\t/g,"")+`}} | ||
`}if(d?.transform)for(let e=0;e<d.transform.length;e++)u+=d.transform[e].constructor.name===s?`await transform[${e}](c);`:`transform[${e}](c);`;if(i&&(i.headers&&(u+=` | ||
`}if(i?.transform)for(let e=0;e<i.transform.length;e++)h+=i.transform[e].constructor.name===n?`await transform[${e}](c);`:`transform[${e}](c);`;if(f&&(f.headers&&(h+=` | ||
const _header = {} | ||
@@ -55,3 +55,3 @@ for (const key of c.request.headers.keys()) | ||
if (headers.Check(_header) === false) { | ||
if (headersCheck(_header) === false) { | ||
throw createValidationError( | ||
@@ -63,18 +63,18 @@ 'header', | ||
} | ||
`.replace(/\t/g,"")),i.params&&(u+="if(params.Check(c.params) === false) { throw createValidationError('params', params, c.params) }"),i.query&&(u+="if(query.Check(c.query) === false) { throw createValidationError('params', query, c.query) }"),i.body&&(u+="if(body.Check(c.body) === false) { throw createValidationError('body', body, c.body) }")),d?.beforeHandle)for(let e=0;e<d.beforeHandle.length;e++){let r=`be${e}`;if(u+=(d.beforeHandle[e].constructor.name===s?`let ${r} = await beforeHandle[${e}](c); | ||
`.replace(/\t/g,"")),f.params&&(h+="if(paramsCheck(c.params) === false) { throw createValidationError('params', params, c.params) }"),f.query&&(h+="if(queryCheck(c.query) === false) { throw createValidationError('params', query, c.query) }"),f.body&&(h+="if(bodyCheck(c.body) === false) { throw createValidationError('body', body, c.body) }")),i?.beforeHandle)for(let e=0;e<i.beforeHandle.length;e++){let r=`be${e}`;if(h+=(i.beforeHandle[e].constructor.name===n?`let ${r} = await beforeHandle[${e}](c); | ||
`:`let ${r} = beforeHandle[${e}](c); | ||
`)+`if(${r} !== undefined) { | ||
`,d?.afterHandle)for(let e=0;e<d.afterHandle.length;e++){let a=`af${e}`;u+=(d.afterHandle[e].constructor.name===s?`const ${a} = await afterHandle[${e}](c, ${r}); | ||
`,i?.afterHandle)for(let e=0;e<i.afterHandle.length;e++){let a=`af${e}`;h+=(i.afterHandle[e].constructor.name===n?`const ${a} = await afterHandle[${e}](c, ${r}); | ||
`:`const ${a} = afterHandle[${e}](c, ${r}); | ||
`)+`if(${a} !== undefined) { ${r} = ${a} } | ||
`}u+=`return mapEarlyResponse(${r}, c.set)} | ||
`}if(d?.afterHandle.length){u+=f.constructor.name===s?`let r = await handler(c); | ||
`}h+=`return mapEarlyResponse(${r}, c.set)} | ||
`}if(i?.afterHandle.length){h+=p.constructor.name===n?`let r = await handler(c); | ||
`:`let r = handler(c); | ||
`;for(let e=0;e<d.afterHandle.length;e++){let r=`af${e}`;u+=(d.afterHandle[e].constructor.name===s?`const ${r} = mapEarlyResponse(await afterHandle[${e}](c, r), c.set); | ||
`;for(let e=0;e<i.afterHandle.length;e++){let r=`af${e}`;h+=(i.afterHandle[e].constructor.name===n?`const ${r} = mapEarlyResponse(await afterHandle[${e}](c, r), c.set); | ||
`:`const ${r} = mapEarlyResponse(afterHandle[${e}](c, r), c.set); | ||
`)+`if(${r}) return ${r}; | ||
`}u+=`return mapResponse(r, c.set); | ||
`}else u+=f.constructor.name===s?"return mapResponse(await handler(c), c.set);":"return mapResponse(handler(c), c.set);";u+=` | ||
`}h+=`return mapResponse(r, c.set); | ||
`}else h+=p.constructor.name===n?"return mapResponse(await handler(c), c.set);":"return mapResponse(handler(c), c.set);";h+=` | ||
} catch(error) { | ||
${m?"":"return (async () => {"} | ||
${y?"":"return (async () => {"} | ||
const set = c.set | ||
@@ -102,4 +102,4 @@ | ||
return handleError(c.request, error, set) | ||
${m?"":"})()"} | ||
}`,u=`const { | ||
${y?"":"})()"} | ||
}`,h=`const { | ||
handler, | ||
@@ -121,2 +121,9 @@ handleError, | ||
}, | ||
validatorAot: { | ||
bodyCheck, | ||
headersCheck, | ||
paramsCheck, | ||
queryCheck, | ||
responseCheck, | ||
}, | ||
utils: { | ||
@@ -132,2 +139,2 @@ createValidationError, | ||
return ${m?"async":""} function(c) {${u}}`.replace(/\t/g,"");let y=Function("hooks",u);return y({handler:f,hooks:d,validator:i,handleError:p,utils:{createValidationError:a,superjsonDeserialize:r,mapResponse:n,mapEarlyResponse:t,mapErrorCode:o,parseQuery:e}})}; | ||
return ${y?"async":""} function(c) {${h}}`.replace(/\t/g,"");let m=Function("hooks",h);return m({handler:p,hooks:i,validator:f,validatorAot:{bodyCheck:d(f.body),headersCheck:d(f.headers),paramsCheck:d(f.params),queryCheck:d(f.query),responseCheck:d(f.response)},handleError:u,utils:{createValidationError:a,superjsonDeserialize:r,mapResponse:o,mapEarlyResponse:t,mapErrorCode:s,parseQuery:e}})};let d=e=>{if(!e)return;let r=e.Code();return r.includes("custom(")?r=>e.Check(r):Function(e.Code())()}; |
@@ -6,3 +6,3 @@ /// <reference types="bun-types" /> | ||
export type Permission = typeof permission; | ||
export declare const permission: <T, Key extends JoinKeys<FunctionProperties<T>, ""> = JoinKeys<FunctionProperties<T>, "">>({ value, allow, deny, check }: { | ||
export declare const permission: <T, Key extends JoinKeys<FunctionProperties<T>> = JoinKeys<FunctionProperties<T>>>({ value, allow, deny, check }: { | ||
value: T; | ||
@@ -9,0 +9,0 @@ allow?: Key[] | undefined; |
@@ -214,3 +214,2 @@ /// <reference types="bun-types" /> | ||
}>>(schema: Schema): NewInstance; | ||
private bodyParser; | ||
handle: (request: Request) => Promise<Response>; | ||
@@ -217,0 +216,0 @@ innerHandle: (request: Request) => MaybePromise<Response>; |
@@ -1,1 +0,1 @@ | ||
import{nanoid as e}from"nanoid";import{Raikiri as t}from"raikiri";import{parse as r}from"fast-querystring";import{mapResponse as s,mapEarlyResponse as a}from"./handler";import{permission as n}from"./fn";import{SCHEMA as h,EXPOSED as i,DEFS as o,clone as u,mergeHook as d,mergeDeep as l,getSchemaValidator as m,getResponseSchemaValidator as c,mapPathnameAndQueryRegEx as p}from"./utils";import{registerSchemaPath as f}from"./schema";import{mapErrorCode as v,mapErrorStatus as g}from"./error";import{runFn as y}from"./fn";import{composeHandler as b}from"./compose";export default class H{store={};meta={[h]:Object.create(null),[o]:Object.create(null),[i]:Object.create(null)};decorators={[h]:this.meta[h],[o]:this.meta[o],store:this.store};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t;routes=[];lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}_addHandler(e,t,r,s){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:d(u(this.event),s)});let a=this.meta[o],n=m(s?.schema?.body??this.$schema?.body,a),i=m(s?.schema?.headers??this.$schema?.headers,a,!0),l=m(s?.schema?.params??this.$schema?.params,a),p=m(s?.schema?.query??this.$schema?.query,a),v=c(s?.schema?.response??this.$schema?.response,a);f({schema:this.meta[h],contentType:s?.schema?.contentType,hook:s,method:e,path:t,models:this.meta[o]});let g=d(u(this.event),s),y={handle:b({method:e,hooks:g,validator:{body:n,headers:i,params:l,query:p,response:v},handler:r,handleError:this.handleError}),onError:g.error};this.router.add(e,t,y)}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){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),this.setModel(s.meta[o]),Object.values(r.routes).forEach(({method:t,path:r,handler:a,hooks:n})=>{"/"===r?this._addHandler(t,e,a,d(n,{error:s.event.error})):this._addHandler(t,`${e}${r}`,a,d(n,{error:s.event.error}))}),this}guard(e,t){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),this.setModel(s.meta[o]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,d(e,a))}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),this):t}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(t,r){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",t,r),this.get(t,t=>{if(!this.server.upgrade(t.request,{headers:"function"==typeof r.headers?r.headers(t):r.headers,data:{...t,id:e(),message:m(r.schema?.body,this.meta[o]),transformMessage:r.transform?Array.isArray(r.transformMessage)?r.transformMessage:[r.transformMessage]:[]}}))return t.set.status=400,"Expected a websocket connection"},{beforeHandle:r.beforeHandle,transform:r.transform,schema:{headers:r.schema?.headers,params:r.schema?.params,query:r.schema?.query}}),this}route(e,t,r,s){return this._addHandler(e,t,r,s),this}state(e,t){return e in this.store||(this.store[e]=t),this}decorate(e,t){return e in this.decorators||(this.decorators[e]=t),this}derive(e){return"AsyncFunction"===e.constructor.name?this.onTransform(async t=>{Object.assign(t,await e(t))}):this.onTransform(t=>{Object.assign(t,e(t))})}fn(e){return 0===Object.keys(this.meta[i]).length&&this.post(this.config.fn??"/~fn",async e=>y(e,this.meta[i])),this.meta[i]=l(this.meta[i],"function"==typeof e?e({...this.decorators,store:this.store,permission:n}):e),this}schema(e){let t=this.meta[o];return this.$schema={body:m(e.body,t),headers:m(e?.headers,t,!0),params:m(e?.params,t),query:m(e?.query,t),response:m(e?.response,t)},this}bodyParser=this.event.parse;handle=async e=>this.innerHandle(e);innerHandle=e=>{let t=this.decorators;if(t.request=e,t.set={status:200,headers:{}},this.event.request.length)try{for(let e=0;e<this.event.request.length;e++){let r=this.event.request[e](t);if(r=a(r,t.set))return r}}catch(r){return this.handleError(e,r,t.set)}let s=e.url.match(p),n=this.router.match(e.method,s[1])??this.router.match("ALL",s[1]);return n?.store?(t.params=n.params,s[2]?t.query=r(s[2]):t.query={},n.store.handle(t)):this.handleError(e,Error("NOT_FOUND"),t.set)};handleError=async(e,t,r={headers:{}})=>{for(let a=0;a<this.event.error.length;a++){let n=this.event.error[a]({request:e,code:v(t.message),error:t,set:r});if(n instanceof Promise&&(n=await n),null!=n)return s(n,r)}return new Response("string"==typeof t.cause?t.cause:t.message,{headers:r.headers,status:g(v(t.message))})};listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if("string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.innerHandle,s="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r},a=`$$Elysia:${s.port}`;globalThis[a]?(this.server=globalThis[a],this.server.reload(s)):globalThis[a]=this.server=Bun.serve(s);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(()=>{this.server.pendingRequests||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)}setModel(e){return Object.entries(e).forEach(([e,t])=>{e in this.meta[o]||(this.meta[o][e]=t)}),this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx}from"./utils";export{H as Elysia,n as permission}; | ||
import{nanoid as e}from"nanoid";import{Raikiri as t}from"raikiri";import{parse as r}from"fast-querystring";import{mapResponse as s,mapEarlyResponse as a}from"./handler";import{permission as n}from"./fn";import{SCHEMA as h,EXPOSED as i,DEFS as o,clone as u,mergeHook as d,mergeDeep as l,getSchemaValidator as m,getResponseSchemaValidator as c,mapPathnameAndQueryRegEx as p}from"./utils";import{registerSchemaPath as f}from"./schema";import{mapErrorCode as v,mapErrorStatus as g}from"./error";import{runFn as y}from"./fn";import{composeHandler as b}from"./compose";export default class H{config;store={};meta={[h]:Object.create(null),[o]:Object.create(null),[i]:Object.create(null)};decorators={[h]:this.meta[h],[o]:this.meta[o],store:this.store};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t;routes=[];wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}_addHandler(e,t,r,s){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:d(u(this.event),s)});let a=this.meta[o],n=m(s?.schema?.body??this.$schema?.body,a),i=m(s?.schema?.headers??this.$schema?.headers,a,!0),l=m(s?.schema?.params??this.$schema?.params,a),p=m(s?.schema?.query??this.$schema?.query,a),v=c(s?.schema?.response??this.$schema?.response,a);f({schema:this.meta[h],contentType:s?.schema?.contentType,hook:s,method:e,path:t,models:this.meta[o]});let g=d(u(this.event),s),y={handle:b({method:e,hooks:g,validator:{body:n,headers:i,params:l,query:p,response:v},handler:r,handleError:this.handleError}),onError:g.error};this.router.add(e,t,y)}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){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),this.setModel(s.meta[o]),Object.values(r.routes).forEach(({method:t,path:r,handler:a,hooks:n})=>{"/"===r?this._addHandler(t,e,a,d(n,{error:s.event.error})):this._addHandler(t,`${e}${r}`,a,d(n,{error:s.event.error}))}),this}guard(e,t){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),this.setModel(s.meta[o]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,d(e,a))}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),this):t}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(t,r){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",t,r),this.get(t,t=>{if(!this.server.upgrade(t.request,{headers:"function"==typeof r.headers?r.headers(t):r.headers,data:{...t,id:e(),message:m(r.schema?.body,this.meta[o]),transformMessage:r.transform?Array.isArray(r.transformMessage)?r.transformMessage:[r.transformMessage]:[]}}))return t.set.status=400,"Expected a websocket connection"},{beforeHandle:r.beforeHandle,transform:r.transform,schema:{headers:r.schema?.headers,params:r.schema?.params,query:r.schema?.query}}),this}route(e,t,r,s){return this._addHandler(e,t,r,s),this}state(e,t){return e in this.store||(this.store[e]=t),this}decorate(e,t){return e in this.decorators||(this.decorators[e]=t),this}derive(e){return"AsyncFunction"===e.constructor.name?this.onTransform(async t=>{Object.assign(t,await e(t))}):this.onTransform(t=>{Object.assign(t,e(t))})}fn(e){return 0===Object.keys(this.meta[i]).length&&this.post(this.config.fn??"/~fn",async e=>y(e,this.meta[i])),this.meta[i]=l(this.meta[i],"function"==typeof e?e({...this.decorators,store:this.store,permission:n}):e),this}schema(e){let t=this.meta[o];return this.$schema={body:m(e.body,t),headers:m(e?.headers,t,!0),params:m(e?.params,t),query:m(e?.query,t),response:m(e?.response,t)},this}handle=async e=>this.innerHandle(e);innerHandle=e=>{let t=this.decorators;if(t.request=e,t.set={status:200,headers:{}},this.event.request.length)try{for(let e=0;e<this.event.request.length;e++){let r=a(this.event.request[e](t),t.set);if(void 0!==r)return r}}catch(r){return this.handleError(e,r,t.set)}let s=e.url.match(p),n=this.router.match(e.method,s[1])??this.router.match("ALL",s[1]);return n?(t.params=n.params,s[2]?t.query=r(s[2]):t.query={},n.store.handle(t)):this.handleError(e,Error("NOT_FOUND"),t.set)};handleError=async(e,t,r={headers:{}})=>{for(let a=0;a<this.event.error.length;a++){let n=this.event.error[a]({request:e,code:v(t.message),error:t,set:r});if(n instanceof Promise&&(n=await n),null!=n)return s(n,r)}return new Response("string"==typeof t.cause?t.cause:t.message,{headers:r.headers,status:g(v(t.message))})};listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if("string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.innerHandle,s="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r},a=`$$Elysia:${s.port}`;globalThis[a]?(this.server=globalThis[a],this.server.reload(s)):globalThis[a]=this.server=Bun.serve(s);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(()=>{this.server.pendingRequests||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)}setModel(e){return Object.entries(e).forEach(([e,t])=>{e in this.meta[o]||(this.meta[o][e]=t)}),this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx}from"./utils";export{H as Elysia,n as permission}; |
@@ -1,1 +0,1 @@ | ||
import{Kind as e,Type as r}from"@sinclair/typebox";import{TypeCompiler as t}from"@sinclair/typebox/compiler";export const SCHEMA=Symbol("schema");export const DEFS=Symbol("definitions");export const EXPOSED=Symbol("exposed");export const mergeObjectArray=(e,r)=>[...Array.isArray(e)?e:[e],...Array.isArray(r)?r:[r]];export const mergeHook=(e,r)=>{let t="schema"in e?e.schema:null,o=r&&"schema"in r?r.schema:null;return{schema:t||o?{body:o?.body??t?.body,header:o?.headers??t?.headers,params:o?.params??t?.params,query:o?.query??t?.query,response:o?.response??t?.response,detail:mergeDeep(o?.detail??{},t?.detail??{})}:void 0,transform:mergeObjectArray(e.transform??[],r?.transform??[]),beforeHandle:mergeObjectArray(e.beforeHandle??[],r?.beforeHandle??[]),parse:mergeObjectArray(e.parse??[],r?.parse??[]),afterHandle:mergeObjectArray(e.afterHandle??[],r?.afterHandle??[]),error:mergeObjectArray(e.error??[],r?.error??[])}};export const clone=e=>e;export const mapPathnameAndQueryRegEx=/:\/\/[^/]+([^#?]+)(?:\?([^#]+))?/;let o=e=>e&&"object"==typeof e&&!Array.isArray(e);export const mergeDeep=(e,r)=>{let t=Object.assign({},e);return o(e)&&o(r)&&Object.keys(r).forEach(a=>{o(r[a])&&a in e?t[a]=mergeDeep(e[a],r[a]):Object.assign(t,{[a]:r[a]})}),t};export const createValidationError=(e,r,t)=>{let o=r.Errors(t).next().value;return Error("VALIDATION",{cause:`Invalid ${e}: '${o?.path?.slice(1)||"root"}'. ${o.message}`})};export const getSchemaValidator=(e,r,o=!1)=>{if(!e||"string"==typeof e&&!(e in r))return;let a="string"==typeof e?r[e]:e;return"object"===a.type&&"additionalProperties"in a==!1&&(a.additionalProperties=o),t.Compile(a)};export const getResponseSchemaValidator=(o,a,n=!1)=>{if(!o||"string"==typeof o&&!(o in a))return;let s="string"==typeof o?a[o]:o,i=e in s?s:r.Union(Object.keys(s).map(e=>{let r=s[e];if("string"==typeof r){if(r in a){let e=a[r];return e}return}return r}).filter(e=>e));"object"===i.type&&"additionalProperties"in i==!1&&(i.additionalProperties=n);try{return t.Compile(i)}catch(e){return s}}; | ||
import{Kind as e,Type as r}from"@sinclair/typebox";import{TypeCompiler as t}from"@sinclair/typebox/compiler";export const SCHEMA=Symbol("schema");export const DEFS=Symbol("definitions");export const EXPOSED=Symbol("exposed");export const mergeObjectArray=(e,r)=>[...Array.isArray(e)?e:[e],...Array.isArray(r)?r:[r]];export const mergeHook=(e,r)=>{let t="schema"in e?e.schema:null,o=r&&"schema"in r?r.schema:null;return{schema:t||o?{body:o?.body??t?.body,header:o?.headers??t?.headers,params:o?.params??t?.params,query:o?.query??t?.query,response:o?.response??t?.response,detail:mergeDeep(o?.detail??{},t?.detail??{})}:void 0,transform:mergeObjectArray(e.transform??[],r?.transform??[]),beforeHandle:mergeObjectArray(e.beforeHandle??[],r?.beforeHandle??[]),parse:mergeObjectArray(e.parse??[],r?.parse??[]),afterHandle:mergeObjectArray(e.afterHandle??[],r?.afterHandle??[]),error:mergeObjectArray(e.error??[],r?.error??[])}};export const clone=e=>e;export const mapPathnameAndQueryRegEx=/:\/\/[^/]+([^#?]+)(?:\?([^#]+))?/;let o=e=>e&&"object"==typeof e&&!Array.isArray(e);export const mergeDeep=(e,r)=>{let t=Object.assign({},e);return o(e)&&o(r)&&Object.keys(r).forEach(a=>{o(r[a])&&a in e?t[a]=mergeDeep(e[a],r[a]):Object.assign(t,{[a]:r[a]})}),t};export const createValidationError=(e,r,t)=>{let o=r.Errors(t).First();return Error("VALIDATION",{cause:`Invalid ${e}: '${o?.path?.slice(1)||"root"}'. ${o?.message}`})};export const getSchemaValidator=(e,r,o=!1)=>{if(!e||"string"==typeof e&&!(e in r))return;let a="string"==typeof e?r[e]:e;return"object"===a.type&&"additionalProperties"in a==!1&&(a.additionalProperties=o),t.Compile(a)};export const getResponseSchemaValidator=(o,a,n=!1)=>{if(!o||"string"==typeof o&&!(o in a))return;let s="string"==typeof o?a[o]:o,i=e in s?s:r.Union(Object.keys(s).map(e=>{let r=s[e];if("string"==typeof r){if(r in a){let e=a[r];return e}return}return r}).filter(e=>e));"object"===i.type&&"additionalProperties"in i==!1&&(i.additionalProperties=n);try{return t.Compile(i)}catch(e){return s}}; |
@@ -23,3 +23,3 @@ /// <reference types="bun-types" /> | ||
request: { | ||
publish: (topic: string, data: string | ArrayBuffer | import("bun").ArrayBufferView, compress?: boolean | undefined) => number; | ||
publish: (topic: string, data: string | ArrayBuffer | SharedArrayBuffer | import("bun").ArrayBufferView, compress?: boolean | undefined) => number; | ||
}; | ||
@@ -26,0 +26,0 @@ schema: {}; |
@@ -1,1 +0,1 @@ | ||
import{Raikiri as e}from"raikiri";import{createValidationError as t,mapPathnameAndQueryRegEx as r}from"../utils";export class ElysiaWS{constructor(e){this.raw=e,this.data=e.data,this.isSubscribed=e.isSubscribed}publish(e,t,r){return"object"==typeof t&&(t=JSON.stringify(t)),this.raw.publish(e,t,r),this}publishToSelf(e,t,r){return"object"==typeof t&&(t=JSON.stringify(t)),this.raw.publish(e,t,r),this}send(e){return"object"==typeof e&&(e=JSON.stringify(e)),this.raw.send(e),this}subscribe(e){return this.raw.subscribe(e),this}unsubscribe(e){return this.raw.unsubscribe(e),this}cork(e){return this.raw.cork(e),this}close(){return this.raw.close(),this}}export const ws=s=>i=>{i.wsRouter||(i.wsRouter=new e);let a=i.wsRouter;return i.config.serve||(i.config.serve={websocket:{...s,open(e){if(!e.data)return;let t=e?.data.request.url.match(r)?.[1];if(!t)return;let s=a.match("subscribe",t)?.store;s&&s.open&&s.open(new ElysiaWS(e))},message(e,s){if(!e.data)return;let i=e?.data.request.url.match(r)?.[1];if(!i)return;let u=a.match("subscribe",i)?.store;if(!u?.message)return;s=s.toString();let o=s.charCodeAt(0);if(47===o||123===o)try{s=JSON.parse(s)}catch(e){}else Number.isNaN(+s)||(s=+s);for(let t=0;t<e.data.transformMessage.length;t++){let r=e.data.transformMessage[t](s);void 0!==r&&(s=r)}if(!1===e.data.message?.Check(s))return void e.send(t("message",e.data.message,s).cause);u.message(new ElysiaWS(e),s)},close(e,t,s){if(!e.data)return;let i=e?.data.request.url.match(r)?.[1];if(!i)return;let u=a.match("subscribe",i)?.store;u&&u.close&&u.close(new ElysiaWS(e),t,s)},drain(e){if(!e.data)return;let t=e?.data.request.url.match(r)?.[1];if(!t)return;let s=a.match("subscribe",t)?.store;s&&s.drain&&s.drain(new ElysiaWS(e))}}}),i.decorate("publish",i.server?.publish).onStart(e=>{e.decorators.publish=e.server?.publish})}; | ||
import{Raikiri as e}from"raikiri";import{createValidationError as t,mapPathnameAndQueryRegEx as r}from"../utils";export class ElysiaWS{raw;data;isSubscribed;constructor(e){this.raw=e,this.data=e.data,this.isSubscribed=e.isSubscribed}publish(e,t,r){return"object"==typeof t&&(t=JSON.stringify(t)),this.raw.publish(e,t,r),this}publishToSelf(e,t,r){return"object"==typeof t&&(t=JSON.stringify(t)),this.raw.publish(e,t,r),this}send(e){return"object"==typeof e&&(e=JSON.stringify(e)),this.raw.send(e),this}subscribe(e){return this.raw.subscribe(e),this}unsubscribe(e){return this.raw.unsubscribe(e),this}cork(e){return this.raw.cork(e),this}close(){return this.raw.close(),this}}export const ws=s=>i=>{i.wsRouter||(i.wsRouter=new e);let a=i.wsRouter;return i.config.serve||(i.config.serve={websocket:{...s,open(e){if(!e.data)return;let t=e?.data.request.url.match(r)?.[1];if(!t)return;let s=a.match("subscribe",t)?.store;s&&s.open&&s.open(new ElysiaWS(e))},message(e,s){if(!e.data)return;let i=e?.data.request.url.match(r)?.[1];if(!i)return;let u=a.match("subscribe",i)?.store;if(!u?.message)return;s=s.toString();let o=s.charCodeAt(0);if(47===o||123===o)try{s=JSON.parse(s)}catch(e){}else Number.isNaN(+s)||(s=+s);for(let t=0;t<e.data.transformMessage.length;t++){let r=e.data.transformMessage[t](s);void 0!==r&&(s=r)}if(!1===e.data.message?.Check(s))return void e.send(t("message",e.data.message,s).cause);u.message(new ElysiaWS(e),s)},close(e,t,s){if(!e.data)return;let i=e?.data.request.url.match(r)?.[1];if(!i)return;let u=a.match("subscribe",i)?.store;u&&u.close&&u.close(new ElysiaWS(e),t,s)},drain(e){if(!e.data)return;let t=e?.data.request.url.match(r)?.[1];if(!t)return;let s=a.match("subscribe",t)?.store;s&&s.drain&&s.drain(new ElysiaWS(e))}}}),i.decorate("publish",i.server?.publish).onStart(e=>{e.decorators.publish=e.server?.publish})}; |
{ | ||
"name": "elysia", | ||
"description": "Fast, and friendly Bun web framework", | ||
"version": "0.4.0-exp-230319.1936", | ||
"version": "0.4.0-exp-230322.0029", | ||
"author": { | ||
@@ -94,22 +94,22 @@ "name": "saltyAom", | ||
"dependencies": { | ||
"@sinclair/typebox": "^0.25.24", | ||
"@sinclair/typebox": "0.26.0", | ||
"fast-querystring": "^1.1.1", | ||
"nanoid": "^4.0.1", | ||
"openapi-types": "^12.1.0", | ||
"raikiri": "0.1.0-beta.1", | ||
"raikiri": "0.1.0-beta.2", | ||
"superjson": "^1.12.2" | ||
}, | ||
"devDependencies": { | ||
"@swc/cli": "^0.1.60", | ||
"@swc/core": "^1.3.32", | ||
"@types/node": "^18.11.18", | ||
"@typescript-eslint/eslint-plugin": "^5.48.2", | ||
"@typescript-eslint/parser": "^5.48.2", | ||
"bun-types": "^0.5.7", | ||
"eslint": "^8.32.0", | ||
"@swc/cli": "^0.1.62", | ||
"@swc/core": "^1.3.41", | ||
"@types/node": "^18.15.5", | ||
"@typescript-eslint/eslint-plugin": "^5.56.0", | ||
"@typescript-eslint/parser": "^5.56.0", | ||
"bun-types": "^0.5.8", | ||
"eslint": "^8.36.0", | ||
"rimraf": "^3.0.2", | ||
"typescript": "^4.9.4" | ||
"typescript": "^5.0.2" | ||
}, | ||
"peerDependencies": { | ||
"@sinclair/typebox": ">= 0.25.24", | ||
"@sinclair/typebox": ">= 0.26.0", | ||
"openapi-types": ">= 12.0.0" | ||
@@ -116,0 +116,0 @@ }, |
@@ -7,3 +7,3 @@ import { parse as parseQuery } from 'fast-querystring' | ||
import type { Elysia } from '.' | ||
import { Elysia } from '.' | ||
import type { | ||
@@ -16,2 +16,3 @@ HTTPMethod, | ||
import { mapErrorCode } from './error' | ||
import { TypeCheck } from '@sinclair/typebox/compiler' | ||
@@ -124,3 +125,3 @@ const ASYNC_FN = 'AsyncFunction' | ||
if (headers.Check(_header) === false) { | ||
if (headersCheck(_header) === false) { | ||
throw createValidationError( | ||
@@ -135,9 +136,9 @@ 'header', | ||
if (validator.params) | ||
fnLiteral += `if(params.Check(c.params) === false) { throw createValidationError('params', params, c.params) }` | ||
fnLiteral += `if(paramsCheck(c.params) === false) { throw createValidationError('params', params, c.params) }` | ||
if (validator.query) | ||
fnLiteral += `if(query.Check(c.query) === false) { throw createValidationError('params', query, c.query) }` | ||
fnLiteral += `if(queryCheck(c.query) === false) { throw createValidationError('params', query, c.query) }` | ||
if (validator.body) | ||
fnLiteral += `if(body.Check(c.body) === false) { throw createValidationError('body', body, c.body) }` | ||
fnLiteral += `if(bodyCheck(c.body) === false) { throw createValidationError('body', body, c.body) }` | ||
} | ||
@@ -242,2 +243,9 @@ | ||
}, | ||
validatorAot: { | ||
bodyCheck, | ||
headersCheck, | ||
paramsCheck, | ||
queryCheck, | ||
responseCheck, | ||
}, | ||
utils: { | ||
@@ -258,4 +266,2 @@ createValidationError, | ||
// console.log(fnLiteral) | ||
const createHandler = Function('hooks', fnLiteral) | ||
@@ -267,2 +273,9 @@ | ||
validator, | ||
validatorAot: { | ||
bodyCheck: createTypeboxAot(validator.body), | ||
headersCheck: createTypeboxAot(validator.headers), | ||
paramsCheck: createTypeboxAot(validator.params), | ||
queryCheck: createTypeboxAot(validator.query), | ||
responseCheck: createTypeboxAot(validator.response) | ||
}, | ||
handleError, | ||
@@ -279,1 +292,10 @@ utils: { | ||
} | ||
const createTypeboxAot = (a: TypeCheck<any> | undefined) => { | ||
if (!a) return | ||
const fnLiteral = a.Code() | ||
if (fnLiteral.includes('custom(')) return (param: any) => a.Check(param) | ||
return new Function(a.Code())() | ||
} |
@@ -1592,6 +1592,9 @@ import type { Serve, Server } from 'bun' | ||
private bodyParser = this.event.parse | ||
handle = async (request: Request) => this.innerHandle(request) | ||
/** | ||
* Handle can be either sync or async to save performance. | ||
* | ||
* Beside for benchmark purpose, please use 'handle' instead. | ||
*/ | ||
innerHandle = (request: Request): MaybePromise<Response> => { | ||
@@ -1608,6 +1611,7 @@ const context: Context = this.decorators as any as Context | ||
for (let i = 0; i < this.event.request.length; i++) { | ||
let response = this.event.request[i](context) | ||
response = mapEarlyResponse(response, context.set) | ||
if (response) return response | ||
const response = mapEarlyResponse( | ||
this.event.request[i](context), | ||
context.set | ||
) | ||
if (response !== undefined) return response | ||
} | ||
@@ -1619,3 +1623,2 @@ } catch (error) { | ||
const fracture = request.url.match(mapPathnameAndQueryRegEx)! | ||
const route = | ||
@@ -1625,3 +1628,3 @@ this.router.match(request.method, fracture[1]) ?? | ||
if (!route?.store) | ||
if (!route) | ||
return this.handleError( | ||
@@ -1628,0 +1631,0 @@ request, |
@@ -105,7 +105,7 @@ import { Kind, TSchema, Type } from '@sinclair/typebox' | ||
) => { | ||
const error = validator.Errors(value).next().value as ValueError | ||
const error = validator.Errors(value).First() | ||
return new Error('VALIDATION', { | ||
cause: `Invalid ${type}: '${error?.path?.slice(1) || 'root'}'. ${ | ||
error.message | ||
error?.message | ||
}` | ||
@@ -112,0 +112,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
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
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
173833
4649
3
+ Added@sinclair/typebox@0.26.0(transitive)
+ Addedraikiri@0.1.0-beta.2(transitive)
- Removed@sinclair/typebox@0.25.24(transitive)
- Removedraikiri@0.1.0-beta.1(transitive)
Updated@sinclair/typebox@0.26.0
Updatedraikiri@0.1.0-beta.2