Comparing version 0.5.0-exp-230505.1731 to 0.5.0-exp-230506.2
@@ -5,3 +5,4 @@ import type { Elysia } from '.'; | ||
export declare const isFnUse: (keyword: string, fnLiteral: string) => boolean; | ||
export declare const composeHandler: ({ method, hooks, validator, handler, handleError, meta }: { | ||
export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta }: { | ||
path: string; | ||
method: HTTPMethod; | ||
@@ -8,0 +9,0 @@ hooks: RegisteredHook<any>; |
@@ -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,removeHostnameRegex as o,removeFragmentRegex as n,removePathRegex as c,removeQueryRegex as l}from"./utils";import{ParseError as i,NotFoundError as d,ValidationError as u,InternalServerError as f}from"./error";let p="AsyncFunction",h=e=>e.constructor.name===p,y=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=({method:o,hooks:n,validator:c,handler:l,handleError:m,meta:$})=>{let b="try {\n",w="string"==typeof n.type,q="GET"!==o&&(c.body||w||[l,...n.transform,...n.beforeHandle,...n.afterHandle].some(e=>isFnUse("body",e.toString()))),g=c.headers||[l,...n.transform,...n.beforeHandle,...n.afterHandle].some(e=>isFnUse("headers",e.toString()));g&&(b+="\n"+(y.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;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()))),E=y.headers||[m,...h.transform,...h.beforeHandle,...h.afterHandle].some(e=>isFnUse("headers",e.toString()));E&&(w+=u.toJSON?`c.headers = c.request.headers.toJSON() | ||
`:`c.headers = {} | ||
@@ -13,5 +13,12 @@ for (const key of c.request.headers.keys()) | ||
} | ||
`));let k=q||l.constructor.name===p||n.parse.length||n.afterHandle.find(h)||n.beforeHandle.find(h)||n.transform.find(h);if(q){let e=c?.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(w||e){if(b+=`try { | ||
`,e)switch(e.type){case"object":"URLEncoded"===e.elysiaMeta?b+="c.body = parseQuery(await c.request.text())":c.body.Code().includes("custom('File")?b+=`c.body = {} | ||
`);let g=y.query||[m,...h.transform,...h.beforeHandle,...h.afterHandle].some(e=>isFnUse("query",e.toString()));g&&(w+=`const url = c.request.url | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${10+f.length})) !== -1) { | ||
c.query = parseQuery(url.substring(c.query + 1)) | ||
} else { | ||
c.query = {} | ||
} | ||
`);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 = {} | ||
await c.request.formData().then((form) => { | ||
@@ -27,3 +34,3 @@ for (const key of form.keys()) { | ||
} | ||
})`:b+="c.body = JSON.parse(await c.request.text())";break;case"string":b+="c.body = await c.request.text()"}else switch(n.type){case"application/json":b+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":b+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":b+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":b+=`c.body = {} | ||
})`:w+="c.body = JSON.parse(await c.request.text())";break;case"string":w+="c.body = await c.request.text()"}else switch(h.type){case"application/json":w+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":w+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":w+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":w+=`c.body = {} | ||
@@ -38,14 +45,14 @@ for (const key of (await c.request.formData()).keys()) { | ||
else c.body[key] = value | ||
}`}b+=`} catch(error) { | ||
}`}w+=`} catch(error) { | ||
throw new ParseError() | ||
}`}else{if(b+="\n"+(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
}`}else{if(w+="\n"+(E?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
if (contentType) { | ||
const index = contentType.indexOf(';') | ||
if (index !== -1) contentType = contentType.substring(0, index) | ||
`,n.parse.length){b+=`let used = false | ||
`;for(let e=0;e<n.parse.length;e++){let r=`bo${e}`;b+=`if(!c.request.bodyUsed) { | ||
`,h.parse.length){w+=`let used = false | ||
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;w+=`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 } | ||
}`}b+="if (!used)"}b+=`switch (contentType) { | ||
}`}w+="if (!used)"}w+=`switch (contentType) { | ||
case 'application/json': | ||
@@ -79,3 +86,3 @@ c.body = JSON.parse(await c.request.text()) | ||
} | ||
`}}if(n?.transform)for(let e=0;e<n.transform.length;e++)b+=n.transform[e].constructor.name===p?`await transform[${e}](c);`:`transform[${e}](c);`;if(c&&(c.headers&&(b+=` | ||
`}}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) { | ||
@@ -88,27 +95,27 @@ throw new ValidationError( | ||
} | ||
`),c.params&&(b+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),c.query&&(b+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),c.body&&(b+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),n?.beforeHandle)for(let e=0;e<n.beforeHandle.length;e++){let r=`be${e}`;if(b+=(n.beforeHandle[e].constructor.name===p?`let ${r} = await beforeHandle[${e}](c); | ||
`),y.params&&(w+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),y.query&&(w+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),y.body&&(w+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),h?.beforeHandle)for(let e=0;e<h.beforeHandle.length;e++){let r=`be${e}`;if(w+=(h.beforeHandle[e].constructor.name===d?`let ${r} = await beforeHandle[${e}](c); | ||
`:`let ${r} = beforeHandle[${e}](c); | ||
`)+`if(${r} !== undefined) { | ||
`,n?.afterHandle)for(let e=0;e<n.afterHandle.length;e++){let t=`af${e}`;b+=(n.afterHandle[e].constructor.name===p?`const ${t} = await afterHandle[${e}](c, ${r}); | ||
`,h?.afterHandle)for(let e=0;e<h.afterHandle.length;e++){let t=`af${e}`;w+=(h.afterHandle[e].constructor.name===d?`const ${t} = await afterHandle[${e}](c, ${r}); | ||
`:`const ${t} = afterHandle[${e}](c, ${r}); | ||
`)+`if(${t} !== undefined) { ${r} = ${t} } | ||
`}c.response&&(b+=`if(response[c.set.status]?.Check(${r}) === false) { throw new ValidationError('response', response[c.set.status], ${r}) } | ||
`),b+=`return mapEarlyResponse(${r}, c.set)} | ||
`}if(n?.afterHandle.length){b+=l.constructor.name===p?`let r = await handler(c); | ||
`}y.response&&(w+=`if(response[c.set.status]?.Check(${r}) === false) { throw new ValidationError('response', response[c.set.status], ${r}) } | ||
`),w+=`return mapEarlyResponse(${r}, c.set)} | ||
`}if(h?.afterHandle.length){w+=m.constructor.name===d?`let r = await handler(c); | ||
`:`let r = handler(c); | ||
`;for(let e=0;e<n.afterHandle.length;e++){let r=`af${e}`;b+=n.afterHandle[e].constructor.name===p?`let ${r} = await afterHandle[${e}](c, r) | ||
`;for(let e=0;e<h.afterHandle.length;e++){let r=`af${e}`;w+=h.afterHandle[e].constructor.name===d?`let ${r} = await afterHandle[${e}](c, r) | ||
`:`let ${r} = afterHandle[${e}](c, r) | ||
`,c.response?b+=`if(response[c.set.status]?.Check(${r}) === false) { throw new ValidationError('response', response[c.set.status], ${r}) } | ||
`,y.response?w+=`if(response[c.set.status]?.Check(${r}) === false) { throw new ValidationError('response', response[c.set.status], ${r}) } | ||
${r} = mapEarlyResponse(${r}, c.set) | ||
if(${r}) return ${r}; | ||
`:b+=`if(${r}) return ${r}; | ||
`}c.response&&(b+=`if(response[c.set.status]?.Check(r) === false) { throw new ValidationError('response', response[c.set.status], r) } | ||
`),b+=`return mapResponse(r, c.set); | ||
`}else c.response?b+=(l.constructor.name===p?`const r = await handler(c); | ||
`:w+=`if(${r}) return ${r}; | ||
`}y.response&&(w+=`if(response[c.set.status]?.Check(r) === false) { throw new ValidationError('response', response[c.set.status], r) } | ||
`),w+=`return mapResponse(r, c.set); | ||
`}else y.response?w+=(m.constructor.name===d?`const r = await handler(c); | ||
`:`const r = handler(c); | ||
`)+`if(response[c.set.status]?.Check(r) === false) { throw new ValidationError('response', response[c.set.status], r) } | ||
`+"return mapResponse(r, c.set);":b+=l.constructor.name===p?"return handler(c).then((v) => mapResponse(v, c.set))":"return mapResponse(handler(c), c.set);";b+=` | ||
`+"return mapResponse(r, c.set);":w+=m.constructor.name===d?"return handler(c).then((v) => mapResponse(v, c.set))":"return mapResponse(handler(c), c.set);";w+=` | ||
} catch(error) { | ||
// Optimize this error return | ||
${k?"":"return (async () => {"} | ||
${x?"":"return (async () => {"} | ||
const set = c.set | ||
@@ -134,4 +141,4 @@ | ||
return handleError(c.request, error, set) | ||
${k?"":"})()"} | ||
}`,b=`const { | ||
${x?"":"})()"} | ||
}`,w=`const { | ||
handler, | ||
@@ -165,3 +172,3 @@ handleError, | ||
}, | ||
${$?` | ||
${b?` | ||
meta, | ||
@@ -172,32 +179,28 @@ SCHEMA, | ||
return ${k?"async":""} function(c) { | ||
${$?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""} | ||
${b} | ||
}`;let x=Function("hooks",b);return x({handler:l,hooks:n,validator:c,handleError:m,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:i,NotFoundError:d,ValidationError:u,InternalServerError:f},meta:$,SCHEMA:$?s:void 0,DEFS:$?a:void 0})};export const composeGeneralHandler=t=>{let s=t.decorators,a="";for(let e of Object.keys(s))a+=`,${e}: app.decorators.${e}`;let i=t.staticRouter,u="";for(let[e,r]of Object.entries(i.map))u+=`case '${e}': | ||
return ${x?"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}': | ||
switch(method) { | ||
${r}} | ||
`;let f=`const { | ||
`;let o=`const { | ||
app, | ||
app: { store, router, staticRouter }, | ||
parseQuery, | ||
${t.event.request.length?"mapEarlyResponse,":""} | ||
removeHostnameRegex: rHost, | ||
removeQueryRegex: rQuery, | ||
removePathRegex: rPath, | ||
removeFragmentRegex: rFrag, | ||
NotFoundError, | ||
mapStaticRoute | ||
${e.event.request.length?"mapEarlyResponse,":""} | ||
NotFoundError | ||
} = data | ||
const getPath = /\\/[^?#]+/g | ||
const notFound = new NotFoundError() | ||
${t.event.request.length?`const onRequest = app.event.request | ||
${e.event.request.length?`const onRequest = app.event.request | ||
const requestLength = app.event.request.length`:""} | ||
${i.variables} | ||
${s.variables} | ||
return function(request) { | ||
const ctx = { | ||
request, | ||
store, | ||
set: { | ||
@@ -207,10 +210,7 @@ headers: {}, | ||
}, | ||
params: {}, | ||
query: {}, | ||
request, | ||
store | ||
${a} | ||
params: {} | ||
${t} | ||
} | ||
${t.event.request.length?` | ||
${e.event.request.length?` | ||
try { | ||
@@ -228,26 +228,11 @@ for (let i = 0; i < requestLength; i++) { | ||
const { url, method } = request, | ||
i = url.indexOf('?', 11), | ||
f = url.indexOf('#', 12) | ||
getPath.lastIndex = 10 | ||
const url = request.url, | ||
method = request.method, | ||
path = getPath.exec(url)?.[0] ?? '/' | ||
let path; | ||
ctx.query = getPath.lastIndex | ||
if (i !== -1) { | ||
path = url.substring(url.indexOf('/', 10), i) | ||
if(f === -1) { | ||
ctx.query = parseQuery(url.substring(i + 1), i) | ||
} else { | ||
ctx.query = parseQuery(url.substring(i + 1, f), i) | ||
} | ||
} else { | ||
if(f === -1) { | ||
path = url.substring(url.indexOf('/', 10)) | ||
} else { | ||
path = url.substring(url.indexOf('/', 10), f) | ||
} | ||
} | ||
switch(path) { | ||
${u} | ||
${a} | ||
} | ||
@@ -267,2 +252,2 @@ | ||
return route.store(ctx) | ||
}`;return Function("data",f)({app:t,parseQuery:e,mapEarlyResponse:r,removeHostnameRegex:o,removeQueryRegex:l,removePathRegex:c,removeFragmentRegex:n,NotFoundError:d})}; | ||
}`;return Function("data",o)({app:e,mapEarlyResponse:r,NotFoundError:n})}; |
@@ -403,5 +403,5 @@ /// <reference types="bun-types" /> | ||
export { ws } from './ws'; | ||
export { SCHEMA, DEFS, EXPOSED, getSchemaValidator, mergeDeep, mergeHook, mergeObjectArray, getPath, getPathAndQuery, getResponseSchemaValidator } from './utils'; | ||
export { SCHEMA, DEFS, EXPOSED, getSchemaValidator, mergeDeep, mergeHook, mergeObjectArray, getPath, 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'; |
@@ -1,4 +0,4 @@ | ||
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 m{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 m={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)},f=i(this.event,a),v=c({method:e,hooks:f,validator:m,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}] | ||
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 m{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 m={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)},f=i(this.event,a),v=c({path:t,method:e,hooks:f,validator:m,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]||(this.staticRouter.map[t]=""),this.staticRouter.map[t]+=`case '${e}': | ||
`,this.staticRouter.map[t]+=`return st${r}(ctx) | ||
`}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 m;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 m;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="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${s.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(s)):globalThis[e]=this.server=Bun.serve(s)}else 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(()=>{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,getPathAndQuery,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{m as Elysia}; | ||
`}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 m;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 m;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{m as Elysia}; |
@@ -11,9 +11,4 @@ import { TSchema } from '@sinclair/typebox'; | ||
export declare const getPath: (url: string) => string; | ||
export declare const getPathAndQuery: (url: string) => string[]; | ||
export declare const removeHostnameRegex: RegExp; | ||
export declare const removeQueryRegex: RegExp; | ||
export declare const removePathRegex: RegExp; | ||
export declare const removeFragmentRegex: RegExp; | ||
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)};export const getPathAndQuery=e=>{let r=e.indexOf("?",11),t=e.indexOf("#",12);return -1!==r?-1!==t?[e.substring(e.indexOf("/",10),r),e.substring(r+1,t)]:[e.substring(e.indexOf("/",10),r),e.substring(r+1)]:-1!==t?[e.substring(e.indexOf("/",10),t),""]:[e.substring(e.indexOf("/",10)),""]};export const removeHostnameRegex=/^[a-z]+?:\/\/[^/]+/;export const removeQueryRegex=/\?.*?([\w=&%]+)/;export const removePathRegex=/^[^?]*(\?|$)/;export const removeFragmentRegex=/#(\S+)/;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(n=>{t(r[n])&&n in e?o[n]=mergeDeep(e[n],r[n]):Object.assign(o,{[n]:r[n]})}),o};export const getSchemaValidator=(e,t,o=!1)=>{if(!e||"string"==typeof e&&!(e in t))return;let n="string"==typeof e?t[e]:e;return"object"===n.type&&"additionalProperties"in n==!1&&(n.additionalProperties=o),r.Compile(n)};export const getResponseSchemaValidator=(t,o,n=!1)=>{if(!t||"string"==typeof t&&!(t in o))return;let s="string"==typeof t?o[t]:t;if(e in s)return{200:r.Compile(s)};let i={};return Object.keys(s).forEach(t=>{let a=s[t];if("string"==typeof a){if(a in o){let n=o[a];n.type,i[+t]=e in n?r.Compile(n):n}return}"object"===a.type&&"additionalProperties"in a==!1&&(a.additionalProperties=n),i[+t]=e in a?r.Compile(a):a}),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}};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}; |
{ | ||
"name": "elysia", | ||
"description": "Fast, and friendly Bun web framework", | ||
"version": "0.5.0-exp-230505.1731", | ||
"version": "0.5.0-exp-230506.0002", | ||
"author": { | ||
@@ -6,0 +6,0 @@ "name": "saltyAom", |
@@ -6,11 +6,4 @@ import type { Elysia } from '.' | ||
import { mapEarlyResponse, mapResponse } from './handler' | ||
import { SCHEMA, DEFS } from './utils' | ||
import { | ||
SCHEMA, | ||
DEFS, | ||
removeHostnameRegex, | ||
removeFragmentRegex, | ||
removePathRegex, | ||
removeQueryRegex | ||
} from './utils' | ||
import { | ||
ParseError, | ||
@@ -74,2 +67,3 @@ NotFoundError, | ||
export const composeHandler = ({ | ||
path, | ||
method, | ||
@@ -82,2 +76,3 @@ hooks, | ||
}: { | ||
path: string | ||
method: HTTPMethod | ||
@@ -115,4 +110,2 @@ hooks: RegisteredHook<any> | ||
if (hasHeaders) { | ||
fnLiteral += '\n' | ||
// This function is Bun specific | ||
@@ -136,2 +129,24 @@ // @ts-ignore | ||
const hasQuery = | ||
validator.query || | ||
[ | ||
handler, | ||
...hooks.transform, | ||
...hooks.beforeHandle, | ||
...hooks.afterHandle | ||
].some((fn) => isFnUse('query', fn.toString())) | ||
if (hasQuery) { | ||
fnLiteral += `const url = c.request.url | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${ | ||
10 + path.length | ||
})) !== -1) { | ||
c.query = parseQuery(url.substring(c.query + 1)) | ||
} else { | ||
c.query = {} | ||
} | ||
` | ||
} | ||
const maybeAsync = | ||
@@ -465,3 +480,2 @@ hasBody || | ||
${meta ? 'c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];' : ''} | ||
${fnLiteral} | ||
@@ -495,8 +509,6 @@ }` | ||
export const composeGeneralHandler = (app: Elysia<any>) => { | ||
// @ts-ignore | ||
const decorators = app.decorators | ||
let decoratorsLiteral = '' | ||
for (const key of Object.keys(decorators)) | ||
// @ts-ignore | ||
for (const key of Object.keys(app.decorators)) | ||
decoratorsLiteral += `,${key}: app.decorators.${key}` | ||
@@ -514,12 +526,7 @@ | ||
app: { store, router, staticRouter }, | ||
parseQuery, | ||
${app.event.request.length ? 'mapEarlyResponse,' : ''} | ||
removeHostnameRegex: rHost, | ||
removeQueryRegex: rQuery, | ||
removePathRegex: rPath, | ||
removeFragmentRegex: rFrag, | ||
NotFoundError, | ||
mapStaticRoute | ||
NotFoundError | ||
} = data | ||
const getPath = /\\/[^?#]+/g | ||
const notFound = new NotFoundError() | ||
@@ -538,2 +545,4 @@ | ||
const ctx = { | ||
request, | ||
store, | ||
set: { | ||
@@ -543,6 +552,3 @@ headers: {}, | ||
}, | ||
params: {}, | ||
query: {}, | ||
request, | ||
store | ||
params: {} | ||
${decoratorsLiteral} | ||
@@ -568,24 +574,9 @@ } | ||
const { url, method } = request, | ||
i = url.indexOf('?', 11), | ||
f = url.indexOf('#', 12) | ||
getPath.lastIndex = 10 | ||
const url = request.url, | ||
method = request.method, | ||
path = getPath.exec(url)?.[0] ?? '/' | ||
let path; | ||
ctx.query = getPath.lastIndex | ||
if (i !== -1) { | ||
path = url.substring(url.indexOf('/', 10), i) | ||
if(f === -1) { | ||
ctx.query = parseQuery(url.substring(i + 1), i) | ||
} else { | ||
ctx.query = parseQuery(url.substring(i + 1, f), i) | ||
} | ||
} else { | ||
if(f === -1) { | ||
path = url.substring(url.indexOf('/', 10)) | ||
} else { | ||
path = url.substring(url.indexOf('/', 10), f) | ||
} | ||
} | ||
switch(path) { | ||
@@ -616,10 +607,5 @@ ${switchMap} | ||
app, | ||
parseQuery, | ||
mapEarlyResponse, | ||
removeHostnameRegex, | ||
removeQueryRegex, | ||
removePathRegex, | ||
removeFragmentRegex, | ||
NotFoundError | ||
}) | ||
} |
@@ -206,2 +206,3 @@ import type { Serve, Server } from 'bun' | ||
const mainHandler = composeHandler({ | ||
path, | ||
method, | ||
@@ -2422,2 +2423,5 @@ hooks, | ||
const development = | ||
(process.env.ENV ?? process.env.NODE_ENV) !== 'production' | ||
const serve: Serve = | ||
@@ -2428,2 +2432,3 @@ typeof options === 'object' | ||
...options, | ||
development, | ||
fetch | ||
@@ -2536,3 +2541,2 @@ } | ||
getPath, | ||
getPathAndQuery, | ||
getResponseSchemaValidator | ||
@@ -2539,0 +2543,0 @@ } from './utils' |
@@ -77,28 +77,2 @@ import { Kind, TSchema } from '@sinclair/typebox' | ||
export const getPathAndQuery = (url: string) => { | ||
const i = url.indexOf('?', 11) | ||
const f = url.indexOf('#', 12) | ||
if (i !== -1) | ||
if (f !== -1) | ||
return [ | ||
url.substring(url.indexOf('/', 10), i), | ||
url.substring(i + 1, f) | ||
] | ||
else | ||
return [ | ||
url.substring(url.indexOf('/', 10), i), | ||
url.substring(i + 1) | ||
] | ||
if (f !== -1) return [url.substring(url.indexOf('/', 10), f), ''] | ||
return [url.substring(url.indexOf('/', 10)), ''] | ||
} | ||
export const removeHostnameRegex = /^[a-z]+?:\/\/[^/]+/ | ||
export const removeQueryRegex = /\?.*?([\w=&%]+)/ | ||
export const removePathRegex = /^[^?]*(\?|$)/ | ||
export const removeFragmentRegex = /#(\S+)/ | ||
const isObject = (item: any): item is Object => | ||
@@ -105,0 +79,0 @@ item && typeof item === 'object' && !Array.isArray(item) |
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
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
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
218967
5895
3
3