Comparing version 0.5.0-exp-230506.1240 to 0.5.0-exp-230507.1507
@@ -1,2 +0,2 @@ | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t}from"./handler";import{SCHEMA as s,DEFS as a}from"./utils";import{ParseError as o,NotFoundError as n,ValidationError as c,InternalServerError as l}from"./error";let d="AsyncFunction",i=e=>e.constructor.name===d,u=new Headers;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.includes(`${t}.${e}`))return!0;let s=RegExp(" (\\w+) = context","g"),a=[t];for(let e of r.matchAll(s))a.push(e[1]);let o=RegExp(`{.*?} = (${a.join("|")})`,"g");for(let[t]of r.matchAll(o))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const composeHandler=({path:f,method:p,hooks:h,validator:y,handler:m,handleError:$,meta:b})=>{let w="try {\n",q="string"==typeof h.type,k="GET"!==p&&(y.body||q||[m,...h.transform,...h.beforeHandle,...h.afterHandle].some(e=>isFnUse("body",e.toString()))),g=y.headers||[m,...h.transform,...h.beforeHandle,...h.afterHandle].some(e=>isFnUse("headers",e.toString()));g&&(w+=u.toJSON?`c.headers = c.request.headers.toJSON() | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t}from"./handler";import{SCHEMA as s,DEFS as a}from"./utils";import{ParseError as o,NotFoundError as n,ValidationError as c,InternalServerError as l}from"./error";let d="AsyncFunction",i=e=>e.constructor.name===d,u=new Headers,f=RegExp(" (\\w+) = context","g");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 s=[t];for(let e of r.matchAll(f))s.push(e[1]);let a=RegExp(`{.*?} = (${s.join("|")})`,"g");for(let[t]of r.matchAll(a))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const composeHandler=({path:f,method:p,hooks:h,validator:y,handler:m,handleError:$,meta:b})=>{let w="try {\n",q="string"==typeof h.type,E=y||"GET"!==p?[m,...h.transform,...h.beforeHandle,...h.afterHandle].map(e=>e.toString()):[],k="GET"!==p&&(y.body||q||E.some(e=>isFnUse("body",e))),g=y.headers||E.some(e=>isFnUse("headers",e));g&&(w+=u.toJSON?`c.headers = c.request.headers.toJSON() | ||
`:`c.headers = {} | ||
@@ -13,5 +13,5 @@ for (const key of c.request.headers.keys()) | ||
} | ||
`);let E=y.query||[m,...h.transform,...h.beforeHandle,...h.afterHandle].some(e=>isFnUse("query",e.toString()));E&&(w+=`const url = c.request.url | ||
`);let x=y.query||E.some(e=>isFnUse("query",e));x&&(w+=`const url = c.request.url | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${10+f.length})) !== -1) { | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${11+f.length})) !== -1) { | ||
c.query = parseQuery(url.substring(c.query + 1)) | ||
@@ -21,4 +21,3 @@ } else { | ||
} | ||
`);let x=k||m.constructor.name===d||h.parse.length||h.afterHandle.find(i)||h.beforeHandle.find(i)||h.transform.find(i);if(k){let e=y?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let s of e.anyOf)if(s.type!==t){r=!0;break}r&&(e=void 0)}if(q||e){if(w+=`try { | ||
`,e)switch(e.type){case"object":"URLEncoded"===e.elysiaMeta?w+="c.body = parseQuery(await c.request.text())":y.body.Code().includes("custom('File")?w+=`c.body = {} | ||
`);let H=k||m.constructor.name===d||h.parse.length||h.afterHandle.find(i)||h.beforeHandle.find(i)||h.transform.find(i);if(k){let e=y?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let s of e.anyOf)if(s.type!==t){r=!0;break}r&&(e=void 0)}if(q||e){if(e)switch(e.type){case"object":"URLEncoded"===e.elysiaMeta?w+="c.body = parseQuery(await c.request.text())":y.body.Code().includes("custom('File")?w+=`c.body = {} | ||
@@ -45,5 +44,3 @@ await c.request.formData().then((form) => { | ||
else c.body[key] = value | ||
}`}w+=`} catch(error) { | ||
throw new ParseError() | ||
}`}else{if(w+="\n"+(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
}`}}else{if(w+="\n"+(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
if (contentType) { | ||
@@ -86,3 +83,3 @@ const index = contentType.indexOf(';') | ||
} | ||
`}}if(h?.transform)for(let e=0;e<h.transform.length;e++)w+=h.transform[e].constructor.name===d?`await transform[${e}](c);`:`transform[${e}](c);`;if(y&&(y.headers&&(w+=` | ||
`}w+="\n"}if(h?.transform)for(let e=0;e<h.transform.length;e++)w+=h.transform[e].constructor.name===d?`await transform[${e}](c);`:`transform[${e}](c);`;if(y&&(y.headers&&(w+=` | ||
if (headers.Check(c.headers) === false) { | ||
@@ -118,3 +115,5 @@ throw new ValidationError( | ||
} catch(error) { | ||
${x?"":"return (async () => {"} | ||
${q||y?.body?.schema?"if(!c.body) error = parseError":""} | ||
${H?"":"return (async () => {"} | ||
const set = c.set | ||
@@ -138,3 +137,3 @@ | ||
return handleError(c.request, error, set) | ||
${x?"":"})()"} | ||
${H?"":"})()"} | ||
}`,w=`const { | ||
@@ -175,6 +174,8 @@ handler, | ||
return ${x?"async":""} function(c) { | ||
const parseError = new ParseError() | ||
return ${H?"async":""} function(c) { | ||
${b?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""} | ||
${w} | ||
}`;let H=Function("hooks",w);return H({handler:m,hooks:h,validator:y,handleError:$,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:o,NotFoundError:n,ValidationError:c,InternalServerError:l},meta:b,SCHEMA:b?s:void 0,DEFS:b?a:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let s=e.staticRouter,a="";for(let[e,r]of Object.entries(s.map))a+=`case '${e}': | ||
}`;let v=Function("hooks",w);return v({handler:m,hooks:h,validator:y,handleError:$,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:o,NotFoundError:n,ValidationError:c,InternalServerError:l},meta:b,SCHEMA:b?s:void 0,DEFS:b?a:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let s=e.staticRouter,a="";for(let[e,r]of Object.entries(s.map))a+=`case '${e}': | ||
switch(method) { | ||
@@ -205,4 +206,3 @@ ${r}} | ||
status: 200 | ||
}, | ||
params: {} | ||
} | ||
${t} | ||
@@ -224,5 +224,4 @@ } | ||
getPath.lastIndex = 10 | ||
const url = request.url, | ||
method = request.method, | ||
getPath.lastIndex = 11 | ||
const { url, method } = request, | ||
path = getPath.exec(url)?.[0] ?? '/' | ||
@@ -229,0 +228,0 @@ |
@@ -403,5 +403,5 @@ /// <reference types="bun-types" /> | ||
export { ws } from './ws'; | ||
export { SCHEMA, DEFS, EXPOSED, getSchemaValidator, mergeDeep, mergeHook, mergeObjectArray, getPath, getResponseSchemaValidator } from './utils'; | ||
export { SCHEMA, DEFS, EXPOSED, getSchemaValidator, mergeDeep, mergeHook, mergeObjectArray, getResponseSchemaValidator } from './utils'; | ||
export { ParseError, NotFoundError, ValidationError, InternalServerError } from './error'; | ||
export type { Context, PreContext } from './context'; | ||
export type { Handler, RegisteredHook, BeforeRequestHandler, TypedRoute, OverwritableTypeRoute, ElysiaInstance, ElysiaConfig, HTTPMethod, ComposedHandler, InternalRoute, BodyParser, ErrorHandler, ErrorCode, TypedSchema, LocalHook, LocalHandler, LifeCycle, LifeCycleEvent, AfterRequestHandler, HookHandler, TypedSchemaToRoute, UnwrapSchema, LifeCycleStore, VoidLifeCycle, SchemaValidator, ExtractPath, IsPathParameter, IsAny, IsNever, UnknownFallback, WithArray, ObjectValues, MaybePromise, MergeIfNotNull, ElysiaDefaultMeta, TypedRouteToEden, AnyTypedSchema, DeepMergeTwoTypes } from './types'; | ||
export type { Handler, RegisteredHook, BeforeRequestHandler, TypedRoute, OverwritableTypeRoute, ElysiaInstance, ElysiaConfig, HTTPMethod, ComposedHandler, InternalRoute, BodyParser, ErrorHandler, ErrorCode, TypedSchema, LocalHook, LocalHandler, LifeCycle, LifeCycleEvent, AfterRequestHandler, HookHandler, TypedSchemaToRoute, UnwrapSchema, LifeCycleStore, VoidLifeCycle, SchemaValidator, ExtractPath, IsPathParameter, IsAny, IsNever, UnknownFallback, WithArray, ObjectValues, MaybePromise, MergeIfNotNull, ElysiaDefaultMeta, AnyTypedSchema, DeepMergeTwoTypes } from './types'; |
@@ -5,2 +5,2 @@ import{nanoid as e}from"nanoid";import{Memoirist as t}from"memoirist";import{mapResponse as r}from"./handler";import{SCHEMA as s,EXPOSED as a,DEFS as o,mergeHook as i,getSchemaValidator as n,getResponseSchemaValidator as h,mergeDeep as u}from"./utils";import{registerSchemaPath as d}from"./schema";import{composeGeneralHandler as l,composeHandler as c}from"./compose";import{ws as p}from"./ws";export default class f{config;store={};meta={[s]:Object.create(null),[o]:Object.create(null),[a]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t;routes=[];staticRouter={handlers:[],variables:"",map:{}};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e},this.fetch=l(this)}_addHandler(e,t,r,a,{allowMeta:u=!1}={allowMeta:!1}){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:i({...this.event},a)});let p=this.meta[o];if(a?.type)switch(a.type){case"text":a.type="text/plain";break;case"json":a.type="application/json";break;case"formdata":a.type="multipart/form-data";break;case"urlencoded":a.type="application/x-www-form-urlencoded"}d({schema:this.meta[s],contentType:a?.type,hook:a,method:e,path:t,models:this.meta[o]});let f={body:n(a?.schema?.body??this.$schema?.body,p),headers:n(a?.schema?.headers??this.$schema?.headers,p,!0),params:n(a?.schema?.params??this.$schema?.params,p),query:n(a?.schema?.query??this.$schema?.query,p),response:h(a?.schema?.response??this.$schema?.response,p)},m=i(this.event,a),v=c({path:t,method:e,hooks:m,validator:f,handler:r,handleError:this.handleError,meta:u?this.meta:void 0});if(-1===t.indexOf(":")&&-1===t.indexOf("*")){let r=this.staticRouter.handlers.length;this.staticRouter.handlers.push(v),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}] | ||
`,this.staticRouter.map[t]+=`return st${r}(ctx) | ||
`}else this.router.add(e,t,v);this.fetch=l(this)}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 s=new f;s.store=this.store,this.wsRouter&&s.use(p());let a="object"==typeof t,n=(a?r:t)(s);return this.decorators=u(this.decorators,s.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.setModel(n.meta[o]),Object.values(s.routes).forEach(({method:r,path:o,handler:h,hooks:u})=>{if(a){let a="/"===o?e:`${e}${o}`,d=s.wsRouter?.find("subscribe",a);if(d){let e=s.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this._addHandler(r,a,h,i(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="/"===o?e:`${e}${o}`,a=s.wsRouter?.find("subscribe",t);if(a){let e=s.wsRouter.history.find(([e,t])=>o===t);if(!e)return;return this.ws(t,e[2])}this._addHandler(r,t,h,i(u,{error:n.event.error}))}}),s.wsRouter&&this.wsRouter&&s.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 f;r.store=this.store,this.wsRouter&&r.use(p());let s=t(r);return this.decorators=u(this.decorators,r.decorators),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:a,handler:o,hooks:n})=>{let h=r.wsRouter?.find("subscribe",a);if(h){let e=r.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this._addHandler(t,a,o,i(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...s.event.error]:[n.error,...s.event.error]:s.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))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),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(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:n(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"},{parse:r.parse,beforeHandle:r.beforeHandle,transform:r.transform,schema:{headers:r.schema?.headers,params:r.schema?.params,query:r.schema?.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 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 this.use(async()=>{let{fn:t}=await import("@elysiajs/fn");return t({app:this,value:e,path:this.config.fn})})}schema(e){let t=this.meta[o];return this.$schema={body:n(e.body,t),headers:n(e?.headers,t,!0),params:n(e?.params,t),query:n(e?.query,t),response:n(e?.response,t)},this}handle=async e=>this.fetch(e);handleError=async(e,t,s)=>{for(let a=0;a<this.event.error.length;a++){let o=this.event.error[a]({request:e,code:t.code??"UNKNOWN",error:t,set:s});if(o instanceof Promise&&(o=await o),null!=o)return r(o,s)}return new Response(t.message,{headers:s.headers,status:t.status??500})};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.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)}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,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,getPath,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{f as Elysia}; | ||
`}else this.router.add(e,t,v);this.fetch=l(this)}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 s=new f;s.store=this.store,this.wsRouter&&s.use(p());let a="object"==typeof t,n=(a?r:t)(s);return this.decorators=u(this.decorators,s.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.setModel(n.meta[o]),Object.values(s.routes).forEach(({method:r,path:o,handler:h,hooks:u})=>{if(a){let a="/"===o?e:`${e}${o}`,d=s.wsRouter?.find("subscribe",a);if(d){let e=s.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this._addHandler(r,a,h,i(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="/"===o?e:`${e}${o}`,a=s.wsRouter?.find("subscribe",t);if(a){let e=s.wsRouter.history.find(([e,t])=>o===t);if(!e)return;return this.ws(t,e[2])}this._addHandler(r,t,h,i(u,{error:n.event.error}))}}),s.wsRouter&&this.wsRouter&&s.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 f;r.store=this.store,this.wsRouter&&r.use(p());let s=t(r);return this.decorators=u(this.decorators,r.decorators),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:a,handler:o,hooks:n})=>{let h=r.wsRouter?.find("subscribe",a);if(h){let e=r.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this._addHandler(t,a,o,i(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...s.event.error]:[n.error,...s.event.error]:s.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))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),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(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:n(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"},{parse:r.parse,beforeHandle:r.beforeHandle,transform:r.transform,schema:{headers:r.schema?.headers,params:r.schema?.params,query:r.schema?.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 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 this.use(async()=>{let{fn:t}=await import("@elysiajs/fn");return t({app:this,value:e,path:this.config.fn})})}schema(e){let t=this.meta[o];return this.$schema={body:n(e.body,t),headers:n(e?.headers,t,!0),params:n(e?.params,t),query:n(e?.query,t),response:n(e?.response,t)},this}handle=async e=>this.fetch(e);handleError=async(e,t,s)=>{for(let a=0;a<this.event.error.length;a++){let o=this.event.error[a]({request:e,code:t.code??"UNKNOWN",error:t,set:s});if(o instanceof Promise&&(o=await o),null!=o)return r(o,s)}return new Response(t.message,{headers:s.headers,status:t.status??500})};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.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)}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,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{f as Elysia}; |
@@ -6,2 +6,4 @@ import { type TSchema } from '@sinclair/typebox'; | ||
export declare const mapProperties: (name: string, schema: TSchema | string | undefined, models: Record<string, TSchema>) => any[]; | ||
export declare const capitalize: (word: string) => string; | ||
export declare const generateOperationId: (method: string, paths: string) => string; | ||
export declare const registerSchemaPath: ({ schema, contentType, path, method, hook, models }: { | ||
@@ -8,0 +10,0 @@ schema: Partial<OpenAPIV3.PathsObject>; |
@@ -1,1 +0,1 @@ | ||
import{Kind as e}from"@sinclair/typebox";import t from"lodash.clonedeep";export const toOpenAPIPath=e=>e.split("/").map(e=>e.startsWith(":")?`{${e.slice(1,e.length)}}`:e).join("/");export const mapProperties=(e,t,r)=>{if(void 0===t)return[];if("string"==typeof t){if(t in r)t=r[t];else throw Error(`Can't find model ${t}`)}return Object.entries(t?.properties??[]).map(([r,o])=>({...o,in:e,name:r,type:o?.type,required:t.required?.includes(r)??!1}))};let r=(e,t)=>{let r={};for(let o of e)r[o]={schema:"string"==typeof t?{$ref:`#/components/schemas/${t}`}:{...t}};return r};export const registerSchemaPath=({schema:o,contentType:s=["application/json","multipart/form-data","text/plain"],path:i,method:n,hook:p,models:a})=>{p&&(p=t(p)),i=toOpenAPIPath(i);let c="string"==typeof s?[s]:s??["application/json"],l=p?.schema?.body,m=p?.schema?.params,f=p?.schema?.headers,h=p?.schema?.query,d=p?.schema?.response;if("object"==typeof d){if(e in d){let{type:e,properties:t,required:o,...s}=d;d={200:{...s,description:s.description,content:r(c,"object"===e||"array"===e?{type:e,properties:t,required:o}:d)}}}else Object.entries(d).forEach(([e,t])=>{if("string"==typeof t){let{type:o,properties:s,required:i,...n}=a[t];d[e]={...n,description:n.description,content:r(c,t)}}else{let{type:o,properties:s,required:i,...n}=t;d[e]={...n,description:n.description,content:r(c,{type:o,properties:s,required:i})}}})}else if("string"==typeof d){let{type:e,properties:t,required:o,...s}=a[d];d={200:{...s,content:r(c,d)}}}let y=[...mapProperties("header",f,a),...mapProperties("path",m,a),...mapProperties("query",h,a)];o[i]={...o[i]?o[i]:{},[n.toLowerCase()]:{...f||m||h||l?{parameters:y}:{},...d?{responses:d}:{},...p?.schema?.detail,...l?{requestBody:{content:r(c,"string"==typeof l?{$ref:`#/components/schemas/${l}`}:l)}}:null}}}; | ||
import{Kind as e}from"@sinclair/typebox";import t from"lodash.clonedeep";export const toOpenAPIPath=e=>e.split("/").map(e=>e.startsWith(":")?`{${e.slice(1,e.length)}}`:e).join("/");export const mapProperties=(e,t,r)=>{if(void 0===t)return[];if("string"==typeof t){if(t in r)t=r[t];else throw Error(`Can't find model ${t}`)}return Object.entries(t?.properties??[]).map(([r,o])=>({...o,in:e,name:r,type:o?.type,required:t.required?.includes(r)??!1}))};let r=(e,t)=>{let r={};for(let o of e)r[o]={schema:"string"==typeof t?{$ref:`#/components/schemas/${t}`}:{...t}};return r};export const capitalize=e=>e.charAt(0).toUpperCase()+e.slice(1);export const generateOperationId=(e,t)=>{let r=e.toLowerCase();if("/"===t)return r+"Index";for(let e of t.split("/"))123===e.charCodeAt(0)?r+="By"+capitalize(e.slice(1,-1)):r+=capitalize(e);return r};export const registerSchemaPath=({schema:o,contentType:i=["application/json","multipart/form-data","text/plain"],path:n,method:s,hook:p,models:a})=>{p&&(p=t(p)),n=toOpenAPIPath(n);let c="string"==typeof i?[i]:i??["application/json"],l=p?.schema?.body,m=p?.schema?.params,d=p?.schema?.headers,f=p?.schema?.query,h=p?.schema?.response;if("object"==typeof h){if(e in h){let{type:e,properties:t,required:o,...i}=h;h={200:{...i,description:i.description,content:r(c,"object"===e||"array"===e?{type:e,properties:t,required:o}:h)}}}else Object.entries(h).forEach(([e,t])=>{if("string"==typeof t){let{type:o,properties:i,required:n,...s}=a[t];h[e]={...s,description:s.description,content:r(c,t)}}else{let{type:o,properties:i,required:n,...s}=t;h[e]={...s,description:s.description,content:r(c,{type:o,properties:i,required:n})}}})}else if("string"==typeof h){let{type:e,properties:t,required:o,...i}=a[h];h={200:{...i,content:r(c,h)}}}let y=[...mapProperties("header",d,a),...mapProperties("path",m,a),...mapProperties("query",f,a)];o[n]={...o[n]?o[n]:{},[s.toLowerCase()]:{...d||m||f||l?{parameters:y}:{},...h?{responses:h}:{},operationId:p?.schema?.detail?.operationId??generateOperationId(s,n),...p?.schema?.detail,...l?{requestBody:{content:r(c,"string"==typeof l?{$ref:`#/components/schemas/${l}`}:l)}}:null}}}; |
@@ -142,15 +142,2 @@ /// <reference types="bun-types" /> | ||
}; | ||
export type TypedRouteToEden<Schema extends TypedSchema = TypedSchema, Definitions extends TypedSchema<string> = ElysiaInstance['meta'][typeof DEFS], Path extends string = string, Catch = unknown> = { | ||
body: UnwrapSchema<Schema['body'], Definitions>; | ||
headers: UnwrapSchema<Schema['headers'], Definitions> extends infer Result extends Record<string, any> ? Result : undefined; | ||
query: UnwrapSchema<Schema['query'], Definitions> extends infer Result extends Record<string, any> ? Result : undefined; | ||
params: UnwrapSchema<Schema['params'], Definitions> extends infer Result extends Record<string, any> ? Result : Record<ExtractPath<Path>, string>; | ||
response: Schema['response'] extends TSchema | string ? { | ||
'200': UnwrapSchema<Schema['response'], Definitions, Catch>; | ||
} : Schema['response'] extends { | ||
[x in string]: TSchema | string; | ||
} ? { | ||
[key in keyof Schema['response']]: UnwrapSchema<Schema['response'][key], Definitions, Catch>; | ||
} : Catch; | ||
}; | ||
export type TypedWSRouteToEden<Schema extends TypedSchema = TypedSchema, Definitions extends TypedSchema<string> = ElysiaInstance['meta'][typeof DEFS], Path extends string = string, Catch = unknown> = TypedSchemaToEden<Schema, Definitions> extends infer Typed extends AnyTypedSchema ? { | ||
@@ -157,0 +144,0 @@ body: Typed['body']; |
@@ -9,6 +9,4 @@ import { TSchema } from '@sinclair/typebox'; | ||
export declare const mergeHook: (a: LocalHook<any, any> | LifeCycleStore<any>, b: LocalHook<any, any>) => RegisteredHook<any>; | ||
export declare const clone: <T extends Object | any[] = Object | any[]>(value: T) => T; | ||
export declare const getPath: (url: string) => string; | ||
export declare const mergeDeep: <A extends Object = Object, B extends Object = Object>(target: A, source: B) => DeepMergeTwoTypes<A, B>; | ||
export declare const getSchemaValidator: (s: TSchema | string | undefined, models: Record<string, TSchema>, additionalProperties?: boolean) => TypeCheck<TSchema> | undefined; | ||
export declare const getResponseSchemaValidator: (s: TypedSchema['response'] | undefined, models: Record<string, TSchema>, additionalProperties?: boolean) => Record<number, TypeCheck<any>> | undefined; |
@@ -1,1 +0,1 @@ | ||
import{Kind as e}from"@sinclair/typebox";import{TypeCompiler as r}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,headers: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??[]),type:e?.type||r?.type}};export const clone=e=>e;export const getPath=e=>{let r=e.indexOf("?",11),t=e.indexOf("#",12);return e.substring(e.indexOf("/",10),-1!==r?r:-1!==t?t:void 0)};let t=e=>e&&"object"==typeof e&&!Array.isArray(e);export const mergeDeep=(e,r)=>{let o=Object.assign({},e);return t(e)&&t(r)&&Object.keys(r).forEach(a=>{t(r[a])&&a in e?o[a]=mergeDeep(e[a],r[a]):Object.assign(o,{[a]:r[a]})}),o};export const getSchemaValidator=(e,t,o=!1)=>{if(!e||"string"==typeof e&&!(e in t))return;let a="string"==typeof e?t[e]:e;return"object"===a.type&&"additionalProperties"in a==!1&&(a.additionalProperties=o),r.Compile(a)};export const getResponseSchemaValidator=(t,o,a=!1)=>{if(!t||"string"==typeof t&&!(t in o))return;let n="string"==typeof t?o[t]:t;if(e in n)return{200:r.Compile(n)};let i={};return Object.keys(n).forEach(t=>{let s=n[t];if("string"==typeof s){if(s in o){let a=o[s];a.type,i[+t]=e in a?r.Compile(a):a}return}"object"===s.type&&"additionalProperties"in s==!1&&(s.additionalProperties=a),i[+t]=e in s?r.Compile(s):s}),i}; | ||
import{Kind as e}from"@sinclair/typebox";import{TypeCompiler as r}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,headers: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??[]),type:e?.type||r?.type}};let t=e=>e&&"object"==typeof e&&!Array.isArray(e);export const mergeDeep=(e,r)=>{let o=Object.assign({},e);return t(e)&&t(r)&&Object.keys(r).forEach(a=>{t(r[a])&&a in e?o[a]=mergeDeep(e[a],r[a]):Object.assign(o,{[a]:r[a]})}),o};export const getSchemaValidator=(e,t,o=!1)=>{if(!e||"string"==typeof e&&!(e in t))return;let a="string"==typeof e?t[e]:e;return"object"===a.type&&"additionalProperties"in a==!1&&(a.additionalProperties=o),r.Compile(a)};export const getResponseSchemaValidator=(t,o,a=!1)=>{if(!t||"string"==typeof t&&!(t in o))return;let i="string"==typeof t?o[t]:t;if(e in i)return{200:r.Compile(i)};let n={};return Object.keys(i).forEach(t=>{let s=i[t];if("string"==typeof s){if(s in o){let a=o[s];a.type,n[+t]=e in a?r.Compile(a):a}return}"object"===s.type&&"additionalProperties"in s==!1&&(s.additionalProperties=a),n[+t]=e in s?r.Compile(s):s}),n}; |
@@ -1,1 +0,1 @@ | ||
import{getPath as e}from"../utils";import{ValidationError as r}from"../error";export class ElysiaWS{raw;data;isSubscribed;constructor(e){this.raw=e,this.data=e.data,this.isSubscribed=e.isSubscribed}publish(e,r,s){return"object"==typeof r&&(r=JSON.stringify(r)),this.raw.publish(e,r,s),this}publishToSelf(e,r,s){return"object"==typeof r&&(r=JSON.stringify(r)),this.raw.publish(e,r,s),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=>t=>{t.wsRouter||(t.wsRouter=new Raikiri);let i=t.wsRouter;return t.config.serve||(t.config.serve={websocket:{...s,open(r){if(!r.data)return;let s=e(r?.data.request.url);if(!s)return;let t=i.find("subscribe",s)?.store;t&&t.open&&t.open(new ElysiaWS(r))},message(s,t){if(!s.data)return;let a=e(s?.data.request.url);if(!a)return;let u=i.find("subscribe",a)?.store;if(!u?.message)return;t=t.toString();let n=t.charCodeAt(0);if(47===n||123===n)try{t=JSON.parse(t)}catch(e){}else Number.isNaN(+t)||(t=+t);for(let e=0;e<s.data.transformMessage.length;e++){let r=s.data.transformMessage[e](t);void 0!==r&&(t=r)}if(!1===s.data.message?.Check(t))return void s.send(new r("message",s.data.message,t).cause);u.message(new ElysiaWS(s),t)},close(r,s,t){if(!r.data)return;let a=e(r?.data.request.url);if(!a)return;let u=i.find("subscribe",a)?.store;u&&u.close&&u.close(new ElysiaWS(r),s,t)},drain(r){if(!r.data)return;let s=e(r?.data.request.url);if(!s)return;let t=i.find("subscribe",s)?.store;t&&t.drain&&t.drain(new ElysiaWS(r))}}}),t.decorate("publish",t.server?.publish).onStart(e=>{e.decorators.publish=e.server?.publish})}; | ||
import{ValidationError as e}from"../error";export class ElysiaWS{raw;data;isSubscribed;constructor(e){this.raw=e,this.data=e.data,this.isSubscribed=e.isSubscribed}publish(e,s,r){return"object"==typeof s&&(s=JSON.stringify(s)),this.raw.publish(e,s,r),this}publishToSelf(e,s,r){return"object"==typeof s&&(s=JSON.stringify(s)),this.raw.publish(e,s,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=>r=>{r.wsRouter||(r.wsRouter=new Raikiri);let t=r.wsRouter,i=/\/[^?#]+/g;return r.config.serve||(r.config.serve={websocket:{...s,open(e){if(!e.data)return;i.lastIndex=9;let s=i.exec(e?.data.request.url)?.[0]??"/";if(!s)return;let r=t.find("subscribe",s)?.store;r&&r.open&&r.open(new ElysiaWS(e))},message(s,r){if(!s.data)return;i.lastIndex=9;let a=i.exec(s?.data.request.url)?.[0]??"/";if(!a)return;let n=t.find("subscribe",a)?.store;if(!n?.message)return;r=r.toString();let u=r.charCodeAt(0);if(47===u||123===u)try{r=JSON.parse(r)}catch(e){}else Number.isNaN(+r)||(r=+r);for(let e=0;e<s.data.transformMessage.length;e++){let t=s.data.transformMessage[e](r);void 0!==t&&(r=t)}if(!1===s.data.message?.Check(r))return void s.send(new e("message",s.data.message,r).cause);n.message(new ElysiaWS(s),r)},close(e,s,r){if(!e.data)return;i.lastIndex=9;let a=i.exec(e?.data.request.url)?.[0]??"/";if(!a)return;let n=t.find("subscribe",a)?.store;n&&n.close&&n.close(new ElysiaWS(e),s,r)},drain(e){if(!e.data)return;i.lastIndex=9;let s=i.exec(e?.data.request.url)?.[0]??"/";if(!s)return;let r=t.find("subscribe",s)?.store;r&&r.drain&&r.drain(new ElysiaWS(e))}}}),r.decorate("publish",r.server?.publish).onStart(e=>{e.decorators.publish=e.server?.publish})}; |
{ | ||
"name": "elysia", | ||
"description": "Fast, and friendly Bun web framework", | ||
"version": "0.5.0-exp-230506.1240", | ||
"version": "0.5.0-exp-230507.1507", | ||
"author": { | ||
@@ -128,2 +128,2 @@ "name": "saltyAom", | ||
} | ||
} | ||
} |
@@ -27,2 +27,4 @@ import type { Elysia } from '.' | ||
const findAliases = new RegExp(` (\\w+) = context`, 'g') | ||
export const isFnUse = (keyword: string, fnLiteral: string) => { | ||
@@ -48,7 +50,6 @@ const argument = fnLiteral.slice( | ||
// Match dot notation | ||
if (fnLiteral.includes(`${argument}.${keyword}`)) return true | ||
// Match dot notation and named access | ||
if (fnLiteral.match(new RegExp(`${argument}.(${keyword}|["${keyword}"])`))) | ||
return true | ||
const findAliases = new RegExp(` (\\w+) = context`, 'g') | ||
const aliases = [argument] | ||
@@ -88,2 +89,12 @@ for (const found of fnLiteral.matchAll(findAliases)) aliases.push(found[1]) | ||
const lifeCycleLiteral = | ||
validator || method !== 'GET' | ||
? [ | ||
handler, | ||
...hooks.transform, | ||
...hooks.beforeHandle, | ||
...hooks.afterHandle | ||
].map((x) => x.toString()) | ||
: [] | ||
const hasBody = | ||
@@ -93,17 +104,7 @@ method !== 'GET' && | ||
hasStrictContentType || | ||
[ | ||
handler, | ||
...hooks.transform, | ||
...hooks.beforeHandle, | ||
...hooks.afterHandle | ||
].some((fn) => isFnUse('body', fn.toString()))) | ||
lifeCycleLiteral.some((fn) => isFnUse('body', fn))) | ||
const hasHeaders = | ||
validator.headers || | ||
[ | ||
handler, | ||
...hooks.transform, | ||
...hooks.beforeHandle, | ||
...hooks.afterHandle | ||
].some((fn) => isFnUse('headers', fn.toString())) | ||
lifeCycleLiteral.some((fn) => isFnUse('headers', fn)) | ||
@@ -130,9 +131,3 @@ if (hasHeaders) { | ||
const hasQuery = | ||
validator.query || | ||
[ | ||
handler, | ||
...hooks.transform, | ||
...hooks.beforeHandle, | ||
...hooks.afterHandle | ||
].some((fn) => isFnUse('query', fn.toString())) | ||
validator.query || lifeCycleLiteral.some((fn) => isFnUse('query', fn)) | ||
@@ -143,3 +138,3 @@ if (hasQuery) { | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${ | ||
10 + path.length | ||
11 + path.length | ||
})) !== -1) { | ||
@@ -182,10 +177,8 @@ c.query = parseQuery(url.substring(c.query + 1)) | ||
if (hasStrictContentType || schema) { | ||
fnLiteral += `try {\n` | ||
if (schema) { | ||
switch (schema.type) { | ||
case 'object': | ||
if (schema.elysiaMeta === 'URLEncoded') | ||
if (schema.elysiaMeta === 'URLEncoded') { | ||
fnLiteral += `c.body = parseQuery(await c.request.text())` | ||
// Accept file which means it's formdata | ||
} // Accept file which means it's formdata | ||
else if ( | ||
@@ -246,6 +239,2 @@ validator.body!.Code().includes("custom('File") | ||
} | ||
fnLiteral += `} catch(error) { | ||
throw new ParseError() | ||
}` | ||
} else { | ||
@@ -308,2 +297,4 @@ fnLiteral += '\n' | ||
} | ||
fnLiteral += '\n' | ||
} | ||
@@ -416,2 +407,10 @@ | ||
} catch(error) { | ||
${ | ||
hasStrictContentType || | ||
// @ts-ignore | ||
validator?.body?.schema | ||
? `if(!c.body) error = parseError` | ||
: '' | ||
} | ||
${maybeAsync ? '' : 'return (async () => {'} | ||
@@ -443,2 +442,4 @@ const set = c.set | ||
// console.log(fnLiteral) | ||
fnLiteral = `const { | ||
@@ -483,2 +484,4 @@ handler, | ||
const parseError = new ParseError() | ||
return ${maybeAsync ? 'async' : ''} function(c) { | ||
@@ -553,4 +556,3 @@ ${meta ? 'c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];' : ''} | ||
status: 200 | ||
}, | ||
params: {} | ||
} | ||
${decoratorsLiteral} | ||
@@ -576,5 +578,4 @@ } | ||
getPath.lastIndex = 10 | ||
const url = request.url, | ||
method = request.method, | ||
getPath.lastIndex = 11 | ||
const { url, method } = request, | ||
path = getPath.exec(url)?.[0] ?? '/' | ||
@@ -581,0 +582,0 @@ |
@@ -2538,3 +2538,2 @@ import type { Serve, Server } from 'bun' | ||
mergeObjectArray, | ||
getPath, | ||
getResponseSchemaValidator | ||
@@ -2587,5 +2586,4 @@ } from './utils' | ||
ElysiaDefaultMeta, | ||
TypedRouteToEden, | ||
AnyTypedSchema, | ||
DeepMergeTwoTypes | ||
} from './types' |
@@ -61,2 +61,21 @@ import { Kind, type TSchema } from '@sinclair/typebox' | ||
export const capitalize = (word: string) => | ||
word.charAt(0).toUpperCase() + word.slice(1) | ||
export const generateOperationId = (method: string, paths: string) => { | ||
let operationId = method.toLowerCase() | ||
if (paths === '/') return operationId + 'Index' | ||
for (const path of paths.split('/')) { | ||
if (path.charCodeAt(0) === 123) { | ||
operationId += 'By' + capitalize(path.slice(1, -1)) | ||
} else { | ||
operationId += capitalize(path) | ||
} | ||
} | ||
return operationId | ||
} | ||
export const registerSchemaPath = ({ | ||
@@ -193,2 +212,5 @@ schema, | ||
: {}), | ||
operationId: | ||
hook?.schema?.detail?.operationId ?? | ||
generateOperationId(method, path), | ||
...hook?.schema?.detail, | ||
@@ -195,0 +217,0 @@ ...(bodySchema |
@@ -320,95 +320,4 @@ import type { Serve, Server } from 'bun' | ||
// export type MergeRouteSchema< | ||
// Schema extends TypedSchema, | ||
// Definitions extends ElysiaInstance['meta'][typeof DEFS], | ||
// Path extends string | ||
// > = TypedSchemaToRoute<Schema, Definitions> extends { | ||
// body: infer Body | ||
// params: infer Params | ||
// query: infer Query | ||
// headers: infer Headers | ||
// response: infer Response | ||
// } | ||
// ? { | ||
// body: Body | ||
// params: Params extends undefined | ||
// ? Record<ExtractPath<Path>, string> | ||
// : Params | ||
// query: Query | ||
// headers: Headers | ||
// response: Response | ||
// } | ||
// : // It's impossible to land here, create a fallback for type integrity | ||
// TypedSchemaToRoute<Schema, Definitions> | ||
// export type RouteToSchema< | ||
// Schema extends TypedSchema, | ||
// InstanceSchema extends ElysiaInstance['schema'], | ||
// Definitions extends ElysiaInstance['meta'][typeof DEFS], | ||
// Path extends string = string | ||
// > = MergeSchema<Schema, InstanceSchema> extends infer Typed extends TypedSchema | ||
// ? TypedSchemaToRoute<Typed, Definitions> extends { | ||
// body: infer Body | ||
// params: infer Params | ||
// query: infer Query | ||
// headers: infer Headers | ||
// response: infer Response | ||
// } | ||
// ? { | ||
// body: Body | ||
// params: Params extends undefined | ||
// ? Record<ExtractPath<Path>, string> | ||
// : Params | ||
// query: Query | ||
// headers: Headers | ||
// response: Response | ||
// } | ||
// : // It's impossible to land here, create a fallback for type integrity | ||
// TypedSchemaToRoute<Typed, Definitions> | ||
// : never | ||
export type FlattenObject<T> = {} & { [P in keyof T]: T[P] } | ||
export type TypedRouteToEden< | ||
Schema extends TypedSchema = TypedSchema, | ||
Definitions extends TypedSchema<string> = ElysiaInstance['meta'][typeof DEFS], | ||
Path extends string = string, | ||
Catch = unknown | ||
> = { | ||
body: UnwrapSchema<Schema['body'], Definitions> | ||
headers: UnwrapSchema< | ||
Schema['headers'], | ||
Definitions | ||
> extends infer Result extends Record<string, any> | ||
? Result | ||
: undefined | ||
query: UnwrapSchema< | ||
Schema['query'], | ||
Definitions | ||
> extends infer Result extends Record<string, any> | ||
? Result | ||
: undefined | ||
params: UnwrapSchema< | ||
Schema['params'], | ||
Definitions | ||
> extends infer Result extends Record<string, any> | ||
? Result | ||
: Record<ExtractPath<Path>, string> | ||
response: Schema['response'] extends TSchema | string | ||
? { | ||
'200': UnwrapSchema<Schema['response'], Definitions, Catch> | ||
} | ||
: Schema['response'] extends { | ||
[x in string]: TSchema | string | ||
} | ||
? { | ||
[key in keyof Schema['response']]: UnwrapSchema< | ||
Schema['response'][key], | ||
Definitions, | ||
Catch | ||
> | ||
} | ||
: Catch | ||
} | ||
export type TypedWSRouteToEden< | ||
@@ -415,0 +324,0 @@ Schema extends TypedSchema = TypedSchema, |
@@ -64,15 +64,2 @@ import { Kind, TSchema } from '@sinclair/typebox' | ||
export const clone = <T extends Object | any[] = Object | any[]>(value: T): T => | ||
[value][0] | ||
export const getPath = (url: string) => { | ||
const i = url.indexOf('?', 11) | ||
const f = url.indexOf('#', 12) | ||
return url.substring( | ||
url.indexOf('/', 10), | ||
i !== -1 ? i : f !== -1 ? f : undefined | ||
) | ||
} | ||
const isObject = (item: any): item is Object => | ||
@@ -79,0 +66,0 @@ item && typeof item === 'object' && !Array.isArray(item) |
import type { Server, ServerWebSocket, WebSocketHandler } from 'bun' | ||
import type { Elysia, Context } from '..' | ||
import { getPath, type DEFS } from '../utils' | ||
import { type DEFS } from '../utils' | ||
@@ -110,2 +110,3 @@ import type { ElysiaWSContext, WSTypedSchema } from './types' | ||
const router = app.wsRouter! | ||
const getPath = /\/[^?#]+/g | ||
@@ -119,5 +120,8 @@ if (!app.config.serve) | ||
const url = getPath( | ||
(ws?.data as unknown as Context).request.url | ||
) | ||
getPath.lastIndex = 9 | ||
const url = | ||
getPath.exec( | ||
(ws?.data as unknown as Context).request.url | ||
)?.[0] ?? '/' | ||
if (!url) return | ||
@@ -133,5 +137,8 @@ | ||
const url = getPath( | ||
(ws?.data as unknown as Context).request.url | ||
) | ||
getPath.lastIndex = 9 | ||
const url = | ||
getPath.exec( | ||
(ws?.data as unknown as Context).request.url | ||
)?.[0] ?? '/' | ||
if (!url) return | ||
@@ -187,5 +194,8 @@ | ||
const url = getPath( | ||
(ws?.data as unknown as Context).request.url | ||
) | ||
getPath.lastIndex = 9 | ||
const url = | ||
getPath.exec( | ||
(ws?.data as unknown as Context).request.url | ||
)?.[0] ?? '/' | ||
if (!url) return | ||
@@ -201,5 +211,8 @@ | ||
const url = getPath( | ||
(ws?.data as unknown as Context).request.url | ||
) | ||
getPath.lastIndex = 9 | ||
const url = | ||
getPath.exec( | ||
(ws?.data as unknown as Context).request.url | ||
)?.[0] ?? '/' | ||
if (!url) return | ||
@@ -206,0 +219,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
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
215990
5802