Comparing version 0.6.14 to 0.6.15
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.errorToResponse = exports.mapCompactResponse = exports.mapResponse = exports.mapEarlyResponse = exports.isNotEmpty = void 0; | ||
const hasHeaderShorthand = 'toJSON' in new Headers(); | ||
const isNotEmpty = (obj) => { | ||
@@ -39,4 +40,13 @@ for (const x in obj) | ||
case 'Response': | ||
for (const key in set.headers) | ||
response.headers.append(key, set.headers[key]); | ||
const inherits = { ...set.headers }; | ||
if (hasHeaderShorthand) | ||
set.headers = response.headers.toJSON(); | ||
else | ||
for (const [key, value] of response.headers.entries()) | ||
if (!(key in set.headers)) | ||
set.headers[key] = value; | ||
for (const key in inherits) | ||
response.headers.append(key, inherits[key]); | ||
if (response.status !== set.status) | ||
set.status = response.status; | ||
return response; | ||
@@ -143,4 +153,11 @@ case 'Promise': | ||
case 'Response': | ||
for (const key in set.headers) | ||
response.headers.append(key, set.headers[key]); | ||
const inherits = { ...set.headers }; | ||
if (hasHeaderShorthand) | ||
set.headers = response.headers.toJSON(); | ||
else | ||
for (const [key, value] of response.headers.entries()) | ||
if (!(key in set.headers)) | ||
set.headers[key] = value; | ||
for (const key in inherits) | ||
response.headers.append(key, inherits[key]); | ||
return response; | ||
@@ -147,0 +164,0 @@ case 'Error': |
@@ -1,18 +0,18 @@ | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t,mapCompactResponse as s}from"./handler";import{NotFoundError as n,ValidationError as a,InternalServerError as o,ERROR_CODE as c}from"./error";let i=new Headers,l=RegExp(" (\\w+) = context","g");export const hasReturn=i=>{let l=i.indexOf(")");return 61===i.charCodeAt(l+2)&&123!==i.charCodeAt(l+5)||i.includes("return")};let f=i=>({composeValidation:(e,r=`c.${e}`)=>i?`c.set.status = 400; throw new ValidationError( | ||
'${e}', | ||
${e}, | ||
${r} | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t,mapCompactResponse as s}from"./handler";import{NotFoundError as n,ValidationError as a,InternalServerError as o,ERROR_CODE as c}from"./error";let i=new Headers,l=RegExp(" (\\w+) = context","g");export const hasReturn=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")};let f=e=>({composeValidation:(r,t=`c.${r}`)=>e?`c.set.status = 400; throw new ValidationError( | ||
'${r}', | ||
${r}, | ||
${t} | ||
)`:`c.set.status = 400; return new ValidationError( | ||
'${e}', | ||
${e}, | ||
${r} | ||
).toResponse(c.set.headers)`,composeResponseValidation:(e="r")=>i?`throw new ValidationError( | ||
'${r}', | ||
${r}, | ||
${t} | ||
).toResponse(c.set.headers)`,composeResponseValidation:(r="r")=>e?`throw new ValidationError( | ||
'response', | ||
response[c.set.status], | ||
${e} | ||
${r} | ||
)`:`return new ValidationError( | ||
'response', | ||
response[c.set.status], | ||
${e} | ||
).toResponse(c.set.headers)`});export const isFnUse=(i,f)=>{f=(f=f.trimStart()).replaceAll(/^async /g,"");let u=40===f.charCodeAt(0)||f.startsWith("function")?f.slice(f.indexOf("(")+1,f.indexOf(")")):f.slice(0,f.indexOf("=")-1);if(""===u)return!1;if(123===u.charCodeAt(0))return!!u.includes(i);if(f.match(RegExp(`${u}(.${i}|\\["${i}"\\])`)))return!0;let d=[u];for(let e of f.matchAll(l))d.push(e[1]);let p=RegExp(`{.*?} = (${d.join("|")})`,"g");for(let[e]of f.matchAll(p))if(e.includes(`{ ${i}`)||e.includes(`, ${i}`))return!0;return!1};export const findElysiaMeta=(i,l,f=[],u="")=>{if("object"===l.type){let e=l.properties;for(let r in e){let t=e[r],s=u?u+"."+r:r;if("object"===t.type){findElysiaMeta(i,t,f,s);continue}if(t.anyOf){for(let e of t.anyOf)findElysiaMeta(i,e,f,s);continue}t.elysiaMeta===i&&f.push(s)}return 0===f.length?null:f}return l?.elysiaMeta===i?(u&&f.push(u),"root"):null};let u=i=>{if(!i)return;let l=i?.schema;if(l&&"anyOf"in l){let e=!1,r=l.anyOf[0].type;for(let t of l.anyOf)if(t.type!==r){e=!0;break}if(!e)return r}},d=/(?:return|=>) \S*\(/g;export const isAsync=i=>{if("AsyncFunction"===i.constructor.name)return!0;let l=i.toString();return!!l.match(d)};export const composeHandler=({method:l,hooks:d,validator:p,handler:y,handleError:h,meta:$,onRequest:m,config:b})=>{let q=b.forceErrorEncapsulation||d.error.length>0||"undefined"==typeof Bun||d.onResponse.length>0,{composeValidation:g,composeResponseValidation:E}=f(q),R=d.onResponse.length?` | ||
${r} | ||
).toResponse(c.set.headers)`});export const isFnUse=(e,r)=>{r=(r=r.trimStart()).replaceAll(/^async /g,"");let t=40===r.charCodeAt(0)||r.startsWith("function")?r.slice(r.indexOf("(")+1,r.indexOf(")")):r.slice(0,r.indexOf("=")-1);if(""===t)return!1;if(123===t.charCodeAt(0))return!!t.includes(e);if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let s=[t];for(let e of r.matchAll(l))s.push(e[1]);let n=RegExp(`{.*?} = (${s.join("|")})`,"g");for(let[t]of r.matchAll(n))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const findElysiaMeta=(e,r,t=[],s="")=>{if("object"===r.type){let n=r.properties;for(let r in n){let a=n[r],o=s?s+"."+r:r;if("object"===a.type){findElysiaMeta(e,a,t,o);continue}if(a.anyOf){for(let r of a.anyOf)findElysiaMeta(e,r,t,o);continue}a.elysiaMeta===e&&t.push(o)}return 0===t.length?null:t}return r?.elysiaMeta===e?(s&&t.push(s),"root"):null};let u=e=>{if(!e)return;let r=e?.schema;if(r&&"anyOf"in r){let e=!1,t=r.anyOf[0].type;for(let s of r.anyOf)if(s.type!==t){e=!0;break}if(!e)return t}},d=/(?:return|=>) \S*\(/g;export const isAsync=e=>{if("AsyncFunction"===e.constructor.name)return!0;let r=e.toString();return!!r.match(d)};export const composeHandler=({method:l,hooks:d,validator:p,handler:y,handleError:h,meta:$,onRequest:m,config:b})=>{let q=b.forceErrorEncapsulation||d.error.length>0||"undefined"==typeof Bun||d.onResponse.length>0,{composeValidation:g,composeResponseValidation:E}=f(q),R=d.onResponse.length?` | ||
;(async () => {${d.onResponse.map((e,r)=>`await res${r}(c)`).join(";")}})(); | ||
@@ -206,6 +206,6 @@ `:"",w=q?"try {\n":"",x=p||"GET"!==l?[y,...d.transform,...d.beforeHandle,...d.afterHandle].map(e=>e.toString()):[],k="GET"!==l&&"none"!==d.type&&(!!p.body||!!d.type||x.some(e=>isFnUse("body",e))),H=p.headers||x.some(e=>isFnUse("headers",e));H&&(w+=i.toJSON?`c.headers = c.request.headers.toJSON() | ||
${w} | ||
}`;let C=Function("hooks",w);return C({handler:y,hooks:d,validator:p,handleError:h,utils:{mapResponse:t,mapCompactResponse:s,mapEarlyResponse:r,parseQuery:e},error:{NotFoundError:n,ValidationError:a,InternalServerError:o},meta:$,ERROR_CODE:c})};export const composeGeneralHandler=i=>{let l="";for(let e of Object.keys(i.decorators))l+=`,${e}: app.decorators.${e}`;let{router:f,staticRouter:u}=i,d=` | ||
const route = find(request.method, path) ${f.root.ALL?'?? find("ALL", path)':""} | ||
}`;let C=Function("hooks",w);return C({handler:y,hooks:d,validator:p,handleError:h,utils:{mapResponse:t,mapCompactResponse:s,mapEarlyResponse:r,parseQuery:e},error:{NotFoundError:n,ValidationError:a,InternalServerError:o},meta:$,ERROR_CODE:c})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:s,staticRouter:a}=e,o=` | ||
const route = find(request.method, path) ${s.root.ALL?'?? find("ALL", path)':""} | ||
if (route === null) | ||
return ${i.event.error.length?`handleError( | ||
return ${e.event.error.length?`handleError( | ||
request, | ||
@@ -220,8 +220,8 @@ notFound, | ||
return route.store(ctx)`,p="";for(let[e,{code:r,all:t}]of Object.entries(u.map))p+=`case '${e}': | ||
return route.store(ctx)`,c="";for(let[e,{code:r,all:t}]of Object.entries(a.map))c+=`case '${e}': | ||
switch(request.method) { | ||
${r} | ||
${t??`default: ${d}`}} | ||
${t??`default: ${o}`}} | ||
`;let y=`const { | ||
`;let i=`const { | ||
app, | ||
@@ -235,5 +235,5 @@ app: { store, router, staticRouter }, | ||
${i.event.request.length?"const onRequest = app.event.request":""} | ||
${e.event.request.length?"const onRequest = app.event.request":""} | ||
${u.variables} | ||
${a.variables} | ||
@@ -243,6 +243,6 @@ const find = router.find.bind(router) | ||
${i.event.error.length?"":"const error404 = notFound.message.toString()"} | ||
${e.event.error.length?"":"const error404 = notFound.message.toString()"} | ||
return function(request) { | ||
`;if(i.event.request.length){y+=` | ||
`;if(e.event.request.length){i+=` | ||
const ctx = { | ||
@@ -255,12 +255,12 @@ request, | ||
} | ||
${l} | ||
${t} | ||
} | ||
try { | ||
`;for(let e=0;e<i.event.request.length;e++){let r=hasReturn(i.event.request[e].toString());y+=r?`const response = mapEarlyResponse( | ||
onRequest[${e}](ctx), | ||
`;for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());i+=t?`const response = mapEarlyResponse( | ||
onRequest[${r}](ctx), | ||
ctx.set | ||
) | ||
if (response) return response | ||
`:`mapEarlyResponse(onRequest[${e}](ctx), ctx.set);`}y+=`} catch (error) { | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set);`}i+=`} catch (error) { | ||
return handleError(request, error, ctx.set) | ||
@@ -272,3 +272,3 @@ } | ||
i = ctx.qi = url.indexOf('?', s + 1), | ||
path = ctx.path = i === -1 ? url.substring(s) : url.substring(s, i);`}else y+=` | ||
path = ctx.path = i === -1 ? url.substring(s) : url.substring(s, i);`}else i+=` | ||
const url = request.url, | ||
@@ -290,11 +290,11 @@ s = url.indexOf('/', 11), | ||
} | ||
${l} | ||
}`;return y+=` | ||
${t} | ||
}`;return i+=` | ||
switch(path) { | ||
${p} | ||
${c} | ||
default: | ||
${d} | ||
${o} | ||
} | ||
}`,i.handleError=composeErrorHandler(i),Function("data",y)({app:i,mapEarlyResponse:r,NotFoundError:n})};export const composeErrorHandler=i=>{let l=`const { | ||
}`,e.handleError=composeErrorHandler(e),Function("data",i)({app:e,mapEarlyResponse:r,NotFoundError:n})};export const composeErrorHandler=e=>{let r=`const { | ||
app: { event: { error: onError, onResponse: res } }, | ||
@@ -305,3 +305,3 @@ mapResponse, | ||
return ${i.event.error.find(isAsync)?"async":""} function(request, error, set) {`;for(let e=0;e<i.event.error.length;e++){let r=i.event.error[e],t=`${isAsync(r)?"await ":""}onError[${e}]({ | ||
return ${e.event.error.find(isAsync)?"async":""} function(request, error, set) {`;for(let t=0;t<e.event.error.length;t++){let s=e.event.error[t],n=`${isAsync(s)?"await ":""}onError[${t}]({ | ||
request, | ||
@@ -311,4 +311,4 @@ code: error.code ?? error[ERROR_CODE] ?? 'UNKNOWN', | ||
set | ||
})`;hasReturn(r.toString())?l+=`const r${e} = ${t}; if(r${e} !== undefined) return mapResponse(r${e}, set) | ||
`:l+=t+"\n"}return Function("inject",l+=`if(error.constructor.name === "ValidationError") { | ||
})`;hasReturn(s.toString())?r+=`const r${t} = ${n}; if(r${t} !== undefined) return mapResponse(r${t}, set) | ||
`:r+=n+"\n"}return Function("inject",r+=`if(error.constructor.name === "ValidationError") { | ||
set.status = error.status ?? 400 | ||
@@ -322,2 +322,2 @@ return new Response( | ||
} | ||
}`)({app:i,mapResponse:t,ERROR_CODE:c})}; | ||
}`)({app:e,mapResponse:t,ERROR_CODE:c})}; |
@@ -1,1 +0,1 @@ | ||
import{Type as e}from"@sinclair/typebox";import{TypeSystem as t}from"@sinclair/typebox/system";try{t.Format("email",e=>/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e)),t.Format("uuid",e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)),t.Format("date",e=>!Number.isNaN(new Date(e).getTime())),t.Format("date-time",e=>!Number.isNaN(new Date(e).getTime()))}catch(i){}let i=i=>{if("string"==typeof i)switch(i.slice(-1)){case"k":return 1024*+i.slice(0,i.length-1);case"m":return 1048576*+i.slice(0,i.length-1);default:return+i}return i},r=(r,a)=>{if(!(a instanceof Blob)||r.minSize&&a.size<i(r.minSize)||r.maxSize&&a.size>i(r.maxSize))return!1;if(r.extension){if("string"==typeof r.extension){if(!a.type.startsWith(r.extension))return!1}else{for(let e=0;e<r.extension.length;e++)if(a.type.startsWith(r.extension[e]))return!0;return!1}}return!0};export const ElysiaType={Numeric:t.Type("Numeric",{}),File:t.Type("File",r),Files:t.Type("Files",(i,a)=>{if(!Array.isArray(a)||i.minItems&&a.length<i.minItems||i.maxItems&&a.length>i.maxItems)return!1;for(let e=0;e<a.length;e++)if(!r(i,a[e]))return!1;return!0})};e.Numeric=i=>e.Number({...i,elysiaMeta:"Numeric"}),e.URLEncoded=(i,r)=>e.Object(i,{...r,elysiaMeta:"URLEncoded"}),e.File=i=>ElysiaType.File({elysiaMeta:"File",default:"File",...i,extension:i?.type,type:"string",format:"binary"}),e.Files=i=>ElysiaType.Files({...i,elysiaMeta:"Files",default:"Files",extension:i?.type,type:"array",items:{...i,default:"Files",type:"string",format:"binary"}});export{e as t}; | ||
import{Type as e}from"@sinclair/typebox";import{TypeSystem as t}from"@sinclair/typebox/system";try{t.Format("email",e=>/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e)),t.Format("uuid",e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)),t.Format("date",e=>!Number.isNaN(new Date(e).getTime())),t.Format("date-time",e=>!Number.isNaN(new Date(e).getTime()))}catch(e){}let i=e=>{if("string"==typeof e)switch(e.slice(-1)){case"k":return 1024*+e.slice(0,e.length-1);case"m":return 1048576*+e.slice(0,e.length-1);default:return+e}return e},r=(e,t)=>{if(!(t instanceof Blob)||e.minSize&&t.size<i(e.minSize)||e.maxSize&&t.size>i(e.maxSize))return!1;if(e.extension){if("string"==typeof e.extension){if(!t.type.startsWith(e.extension))return!1}else{for(let i=0;i<e.extension.length;i++)if(t.type.startsWith(e.extension[i]))return!0;return!1}}return!0};export const ElysiaType={Numeric:t.Type("Numeric",{}),File:t.Type("File",r),Files:t.Type("Files",(e,t)=>{if(!Array.isArray(t)||e.minItems&&t.length<e.minItems||e.maxItems&&t.length>e.maxItems)return!1;for(let i=0;i<t.length;i++)if(!r(e,t[i]))return!1;return!0})};e.Numeric=t=>e.Number({...t,elysiaMeta:"Numeric"}),e.URLEncoded=(t,i)=>e.Object(t,{...i,elysiaMeta:"URLEncoded"}),e.File=e=>ElysiaType.File({elysiaMeta:"File",default:"File",...e,extension:e?.type,type:"string",format:"binary"}),e.Files=e=>ElysiaType.Files({...e,elysiaMeta:"Files",default:"Files",extension:e?.type,type:"array",items:{...e,default:"Files",type:"string",format:"binary"}});export{e as t}; |
@@ -1,1 +0,1 @@ | ||
import{NotFoundError as e,ValidationError as t,ERROR_CODE as a}from"./error";import{mapEarlyResponse as r,mapResponse as s}from"./handler";import{parse as n}from"fast-querystring";export const createDynamicHandler=o=>async a=>{let i;let l={status:200,headers:{}};o.decorators?((i=o.decorators).request=a,i.set=l,i.store=o.store):i={set:l,store:o.store,request:a};let f=a.url,c=f.indexOf("/",11),d=f.indexOf("?",c+1),w=-1===d?f.substring(c):f.substring(c,d);try{let c;for(let e=0;e<o.event.request.length;e++){let t=o.event.request[e],a=t(i);if(a instanceof Promise&&(a=await a),a=r(a,l))return a}let m=o.dynamicRouter.find(a.method,w)??o.dynamicRouter.find("ALL",w);if(!m)throw new e;let{handle:u,hooks:h,validator:p,content:y}=m.store;if("GET"!==a.method){if(y)switch(y){case"application/json":c=await a.json();break;case"text/plain":c=await a.text();break;case"application/x-www-form-urlencoded":c=n(await a.text());break;case"application/octet-stream":c=await a.arrayBuffer();break;case"multipart/form-data":c={};let e=await a.formData();for(let t of e.keys()){if(c[t])continue;let a=e.getAll(t);1===a.length?c[t]=a[0]:c[t]=a}}else{let e=a.headers.get("content-type");if(e){let t=e.indexOf(";");-1!==t&&(e=e.slice(0,t));for(let t=0;t<o.event.parse.length;t++){let a=o.event.parse[t](i,e);if(a instanceof Promise&&(a=await a),a){c=a;break}}if(void 0===c)switch(e){case"application/json":c=await a.json();break;case"text/plain":c=await a.text();break;case"application/x-www-form-urlencoded":c=n(await a.text());break;case"application/octet-stream":c=await a.arrayBuffer();break;case"multipart/form-data":c={};let r=await a.formData();for(let e of r.keys()){if(c[e])continue;let t=r.getAll(e);1===t.length?c[e]=t[0]:c[e]=t}}}}}i.body=c,i.params=m?.params||{},i.query=-1===d?{}:n(f.substring(d+1));for(let e=0;e<h.transform.length;e++){let t=h.transform[e](i);"derive"===h.transform[e].$elysia?t instanceof Promise?Object.assign(i,await t):Object.assign(i,t):t instanceof Promise&&await t}if(p){if(p.headers){let e={};for(let t in a.headers)e[t]=a.headers.get(t);if(!1===p.headers.Check(e))throw new t("header",p.headers,e)}if(p.params?.Check(i.params)===!1)throw new t("params",p.params,i.params);if(p.query?.Check(i.query)===!1)throw new t("query",p.query,i.query);if(p.body?.Check(c)===!1)throw new t("body",p.body,c)}for(let e=0;e<h.beforeHandle.length;e++){let t=h.beforeHandle[e](i);if(t instanceof Promise&&(t=await t),void 0!==t){for(let e=0;e<h.afterHandle.length;e++){let a=h.afterHandle[e](i,t);a instanceof Promise&&(a=await a),a&&(t=a)}let e=r(t,i.set);if(e)return e}}let g=u(i);if(g instanceof Promise&&(g=await g),h.afterHandle.length)for(let e=0;e<h.afterHandle.length;e++){let a=h.afterHandle[e](i,g);a instanceof Promise&&(a=await a);let s=r(a,i.set);if(void 0!==s){let e=p?.response?.[g.status];if(e?.Check(s)===!1)throw new t("response",e,s);return s}}else{let e=p?.response?.[g.status];if(e?.Check(g)===!1)throw new t("response",e,g)}return s(g,i.set)}catch(e){return e.status&&(l.status=e.status),o.handleError(a,e,l)}finally{for(let e of o.event.onResponse)await e(i)}};export const createDynamicErrorHandler=o=>async(e,t,r={headers:{}})=>{for(let n=0;n<o.event.error.length;n++){let i=o.event.error[n]({request:e,code:t.code??t[a]??"UNKNOWN",error:t,set:r});if(i instanceof Promise&&(i=await i),null!=i)return s(i,r)}return new Response("string"==typeof t.cause?t.cause:t.message,{headers:r.headers,status:t.status??500})}; | ||
import{NotFoundError as e,ValidationError as t,ERROR_CODE as a}from"./error";import{mapEarlyResponse as r,mapResponse as s}from"./handler";import{parse as n}from"fast-querystring";export const createDynamicHandler=a=>async o=>{let i;let l={status:200,headers:{}};a.decorators?((i=a.decorators).request=o,i.set=l,i.store=a.store):i={set:l,store:a.store,request:o};let f=o.url,c=f.indexOf("/",11),d=f.indexOf("?",c+1),w=-1===d?f.substring(c):f.substring(c,d);try{let c;for(let e=0;e<a.event.request.length;e++){let t=a.event.request[e],s=t(i);if(s instanceof Promise&&(s=await s),s=r(s,l))return s}let m=a.dynamicRouter.find(o.method,w)??a.dynamicRouter.find("ALL",w);if(!m)throw new e;let{handle:u,hooks:h,validator:p,content:y}=m.store;if("GET"!==o.method){if(y)switch(y){case"application/json":c=await o.json();break;case"text/plain":c=await o.text();break;case"application/x-www-form-urlencoded":c=n(await o.text());break;case"application/octet-stream":c=await o.arrayBuffer();break;case"multipart/form-data":c={};let e=await o.formData();for(let t of e.keys()){if(c[t])continue;let a=e.getAll(t);1===a.length?c[t]=a[0]:c[t]=a}}else{let e=o.headers.get("content-type");if(e){let t=e.indexOf(";");-1!==t&&(e=e.slice(0,t));for(let t=0;t<a.event.parse.length;t++){let r=a.event.parse[t](i,e);if(r instanceof Promise&&(r=await r),r){c=r;break}}if(void 0===c)switch(e){case"application/json":c=await o.json();break;case"text/plain":c=await o.text();break;case"application/x-www-form-urlencoded":c=n(await o.text());break;case"application/octet-stream":c=await o.arrayBuffer();break;case"multipart/form-data":c={};let r=await o.formData();for(let e of r.keys()){if(c[e])continue;let t=r.getAll(e);1===t.length?c[e]=t[0]:c[e]=t}}}}}i.body=c,i.params=m?.params||{},i.query=-1===d?{}:n(f.substring(d+1));for(let e=0;e<h.transform.length;e++){let t=h.transform[e](i);"derive"===h.transform[e].$elysia?t instanceof Promise?Object.assign(i,await t):Object.assign(i,t):t instanceof Promise&&await t}if(p){if(p.headers){let e={};for(let t in o.headers)e[t]=o.headers.get(t);if(!1===p.headers.Check(e))throw new t("header",p.headers,e)}if(p.params?.Check(i.params)===!1)throw new t("params",p.params,i.params);if(p.query?.Check(i.query)===!1)throw new t("query",p.query,i.query);if(p.body?.Check(c)===!1)throw new t("body",p.body,c)}for(let e=0;e<h.beforeHandle.length;e++){let t=h.beforeHandle[e](i);if(t instanceof Promise&&(t=await t),void 0!==t){for(let e=0;e<h.afterHandle.length;e++){let a=h.afterHandle[e](i,t);a instanceof Promise&&(a=await a),a&&(t=a)}let e=r(t,i.set);if(e)return e}}let g=u(i);if(g instanceof Promise&&(g=await g),h.afterHandle.length)for(let e=0;e<h.afterHandle.length;e++){let a=h.afterHandle[e](i,g);a instanceof Promise&&(a=await a);let s=r(a,i.set);if(void 0!==s){let e=p?.response?.[g.status];if(e?.Check(s)===!1)throw new t("response",e,s);return s}}else{let e=p?.response?.[g.status];if(e?.Check(g)===!1)throw new t("response",e,g)}return s(g,i.set)}catch(e){return e.status&&(l.status=e.status),a.handleError(o,e,l)}finally{for(let e of a.event.onResponse)await e(i)}};export const createDynamicErrorHandler=e=>async(t,r,n={headers:{}})=>{for(let o=0;o<e.event.error.length;o++){let i=e.event.error[o]({request:t,code:r.code??r[a]??"UNKNOWN",error:r,set:n});if(i instanceof Promise&&(i=await i),null!=i)return s(i,n)}return new Response("string"==typeof r.cause?r.cause:r.message,{headers:n.headers,status:r.status??500})}; |
import{Value as r}from"@sinclair/typebox/value";let e="undefined"!=typeof Bun?Bun.env:"undefined"!=typeof process?process?.env:void 0;export const ERROR_CODE=Symbol("ErrorCode");export const isProduction=(e?.NODE_ENV??e?.ENV)==="production";export class InternalServerError extends Error{code="NOT_FOUND";status=500;constructor(){super("INTERNAL_SERVER_ERROR")}}export class NotFoundError extends Error{code="NOT_FOUND";status=404;constructor(){super("NOT_FOUND")}}export class ParseError extends Error{code="PARSE";status=400;constructor(){super("PARSE")}}export class ValidationError extends Error{type;validator;value;code;status;constructor(e,t,o){let s=isProduction?void 0:t.Errors(o).First(),a=s?.schema.error?"function"==typeof s.schema.error?s.schema.error(e,t,o):s.schema.error:void 0,n=isProduction?a??`Invalid ${e??s?.schema.error??s?.message}`:a??`Invalid ${e}, '${s?.path?.slice(1)||"type"}': ${s?.message} | ||
Expected: `+JSON.stringify(r.Create(t.schema),null,2)+"\n\nFound: "+JSON.stringify(o,null,2);super(n),this.type=e,this.validator=t,this.value=o,this.code="VALIDATION",this.status=400,Object.setPrototypeOf(this,ValidationError.prototype)}get all(){return[...this.validator.Errors(this.value)]}get model(){return r.Create(this.validator.schema)}toResponse(e){return new Response(this.message,{status:400,headers:e})}} | ||
Expected: `+JSON.stringify(r.Create(t.schema),null,2)+"\n\nFound: "+JSON.stringify(o,null,2);super(n),this.type=e,this.validator=t,this.value=o,this.code="VALIDATION",this.status=400,Object.setPrototypeOf(this,ValidationError.prototype)}get all(){return[...this.validator.Errors(this.value)]}get model(){return r.Create(this.validator.schema)}toResponse(r){return new Response(this.message,{status:400,headers:r})}} |
@@ -1,1 +0,1 @@ | ||
export const isNotEmpty=e=>{for(let s in e)return!0;return!1};let e=(e,s)=>{e.delete("Set-Cookie");for(let r=0;r<s.length;r++){let n=s[r].indexOf("=");e.append("Set-Cookie",`${s[r].slice(0,n)}=${s[r].slice(n+1)}`)}return e};export const mapEarlyResponse=(s,r)=>{if(isNotEmpty(r.headers)||200!==r.status||r.redirect)switch(r.redirect&&(r.headers.Location=r.redirect,r.status=302),r.headers["Set-Cookie"]&&Array.isArray(r.headers["Set-Cookie"])&&(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"])),s?.constructor?.name){case"String":case"Blob":return new Response(s,r);case"Object":case"Array":return Response.json(s,r);case void 0:if(!s)return;return Response.json(s,r);case"Response":for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case"Promise":return s.then(e=>{let s=mapEarlyResponse(e,r);if(void 0!==s)return s});case"Error":return errorToResponse(s,r.headers);case"Function":return s();case"Number":case"Boolean":return new Response(s.toString(),r);default:if(s instanceof Response)return s;let n=JSON.stringify(s);if(123===n.charCodeAt(0))return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),r);return new Response(n,r)}else switch(s?.constructor?.name){case"String":case"Blob":return new Response(s);case"Object":case"Array":return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case void 0:if(!s)return new Response("");return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"Response":return s;case"Promise":return s.then(e=>{let s=mapEarlyResponse(e,r);if(void 0!==s)return s});case"Error":return errorToResponse(s,r.headers);case"Function":return s();case"Number":case"Boolean":return new Response(s.toString());default:if(s instanceof Response)return s;let t=JSON.stringify(s);if(123===t.charCodeAt(0))return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}});return new Response(t)}};export const mapResponse=(s,r)=>{if(isNotEmpty(r.headers)||200!==r.status||r.redirect)switch(r.redirect&&(r.headers.Location=r.redirect,r.status=302),r.headers["Set-Cookie"]&&Array.isArray(r.headers["Set-Cookie"])&&(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"])),s?.constructor?.name){case"String":case"Blob":return new Response(s,{status:r.status,headers:r.headers});case"Object":case"Array":return Response.json(s,r);case void 0:if(!s)return new Response("",r);return Response.json(s,r);case"Response":for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case"Error":return errorToResponse(s,r.headers);case"Promise":return s.then(e=>mapResponse(e,r));case"Function":return s();case"Number":case"Boolean":return new Response(s.toString(),r);default:if(s instanceof Response)return s;let n=JSON.stringify(s);if(123===n.charCodeAt(0))return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),r);return new Response(n,r)}else switch(s?.constructor?.name){case"String":case"Blob":return new Response(s);case"Object":case"Array":return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case void 0:if(!s)return new Response("");return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"Response":return s;case"Error":return errorToResponse(s);case"Promise":return s.then(e=>{let s=mapResponse(e,r);return void 0!==s?s:new Response("")});case"Function":return s();case"Number":case"Boolean":return new Response(s.toString());default:if(s instanceof Response)return s;let t=JSON.stringify(s);if(123===t.charCodeAt(0))return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}});return new Response(t)}};export const mapCompactResponse=e=>{switch(e?.constructor?.name){case"String":case"Blob":return new Response(e);case"Object":case"Array":return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}});case void 0:if(!e)return new Response("");return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}});case"Response":return e;case"Error":return errorToResponse(e);case"Promise":return e.then(e=>{let s=mapCompactResponse(e);return void 0!==s?s:new Response("")});case"Function":return e();case"Number":case"Boolean":return new Response(e.toString());default:if(e instanceof Response)return e;let s=JSON.stringify(e);if(123===s.charCodeAt(0))return new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"}});return new Response(s)}};export const errorToResponse=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s}); | ||
let e="toJSON"in new Headers;export const isNotEmpty=e=>{for(let s in e)return!0;return!1};let s=(e,s)=>{e.delete("Set-Cookie");for(let r=0;r<s.length;r++){let n=s[r].indexOf("=");e.append("Set-Cookie",`${s[r].slice(0,n)}=${s[r].slice(n+1)}`)}return e};export const mapEarlyResponse=(r,n)=>{if(isNotEmpty(n.headers)||200!==n.status||n.redirect)switch(n.redirect&&(n.headers.Location=n.redirect,n.status=302),n.headers["Set-Cookie"]&&Array.isArray(n.headers["Set-Cookie"])&&(n.headers=s(new Headers(n.headers),n.headers["Set-Cookie"])),r?.constructor?.name){case"String":case"Blob":return new Response(r,n);case"Object":case"Array":return Response.json(r,n);case void 0:if(!r)return;return Response.json(r,n);case"Response":let t={...n.headers};if(e)n.headers=r.headers.toJSON();else for(let[e,s]of r.headers.entries())e in n.headers||(n.headers[e]=s);for(let e in t)r.headers.append(e,t[e]);return r.status!==n.status&&(n.status=r.status),r;case"Promise":return r.then(e=>{let s=mapEarlyResponse(e,n);if(void 0!==s)return s});case"Error":return errorToResponse(r,n.headers);case"Function":return r();case"Number":case"Boolean":return new Response(r.toString(),n);default:if(r instanceof Response)return r;let o=JSON.stringify(r);if(123===o.charCodeAt(0))return n.headers["Content-Type"]||(n.headers["Content-Type"]="application/json"),new Response(JSON.stringify(r),n);return new Response(o,n)}else switch(r?.constructor?.name){case"String":case"Blob":return new Response(r);case"Object":case"Array":return new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}});case void 0:if(!r)return new Response("");return new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}});case"Response":return r;case"Promise":return r.then(e=>{let s=mapEarlyResponse(e,n);if(void 0!==s)return s});case"Error":return errorToResponse(r,n.headers);case"Function":return r();case"Number":case"Boolean":return new Response(r.toString());default:if(r instanceof Response)return r;let a=JSON.stringify(r);if(123===a.charCodeAt(0))return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}});return new Response(a)}};export const mapResponse=(r,n)=>{if(isNotEmpty(n.headers)||200!==n.status||n.redirect)switch(n.redirect&&(n.headers.Location=n.redirect,n.status=302),n.headers["Set-Cookie"]&&Array.isArray(n.headers["Set-Cookie"])&&(n.headers=s(new Headers(n.headers),n.headers["Set-Cookie"])),r?.constructor?.name){case"String":case"Blob":return new Response(r,{status:n.status,headers:n.headers});case"Object":case"Array":return Response.json(r,n);case void 0:if(!r)return new Response("",n);return Response.json(r,n);case"Response":let t={...n.headers};if(e)n.headers=r.headers.toJSON();else for(let[e,s]of r.headers.entries())e in n.headers||(n.headers[e]=s);for(let e in t)r.headers.append(e,t[e]);return r;case"Error":return errorToResponse(r,n.headers);case"Promise":return r.then(e=>mapResponse(e,n));case"Function":return r();case"Number":case"Boolean":return new Response(r.toString(),n);default:if(r instanceof Response)return r;let o=JSON.stringify(r);if(123===o.charCodeAt(0))return n.headers["Content-Type"]||(n.headers["Content-Type"]="application/json"),new Response(JSON.stringify(r),n);return new Response(o,n)}else switch(r?.constructor?.name){case"String":case"Blob":return new Response(r);case"Object":case"Array":return new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}});case void 0:if(!r)return new Response("");return new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}});case"Response":return r;case"Error":return errorToResponse(r);case"Promise":return r.then(e=>{let s=mapResponse(e,n);return void 0!==s?s:new Response("")});case"Function":return r();case"Number":case"Boolean":return new Response(r.toString());default:if(r instanceof Response)return r;let a=JSON.stringify(r);if(123===a.charCodeAt(0))return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}});return new Response(a)}};export const mapCompactResponse=e=>{switch(e?.constructor?.name){case"String":case"Blob":return new Response(e);case"Object":case"Array":return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}});case void 0:if(!e)return new Response("");return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}});case"Response":return e;case"Error":return errorToResponse(e);case"Promise":return e.then(e=>{let s=mapCompactResponse(e);return void 0!==s?s:new Response("")});case"Function":return e();case"Number":case"Boolean":return new Response(e.toString());default:if(e instanceof Response)return e;let s=JSON.stringify(e);if(123===s.charCodeAt(0))return new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"}});return new Response(s)}};export const errorToResponse=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s}); |
@@ -1,1 +0,1 @@ | ||
import{Kind as e}from"@sinclair/typebox";import{Value as r}from"@sinclair/typebox/value";import{TypeCompiler as o}from"@sinclair/typebox/compiler";export const mergeObjectArray=(t,a)=>{let s=[...Array.isArray(t)?t:[t]],n=[];for(let e of s)e.$elysiaChecksum&&n.push(e.$elysiaChecksum);for(let e of Array.isArray(a)?a:[a])n.includes(e?.$elysiaChecksum)||s.push(e);return s};export const mergeHook=(t,a)=>({body:a?.body??t?.body,headers:a?.headers??t?.headers,params:a?.params??t?.params,query:a?.query??t?.query,response:a?.response??t?.response,type:t?.type||a?.type,detail:mergeDeep(a?.detail??{},t?.detail??{}),parse:mergeObjectArray(t.parse??[],a?.parse??[]),transform:mergeObjectArray(t.transform??[],a?.transform??[]),beforeHandle:mergeObjectArray(t.beforeHandle??[],a?.beforeHandle??[]),afterHandle:mergeObjectArray(t.afterHandle??[],a?.afterHandle??[]),onResponse:mergeObjectArray(t.onResponse??[],a?.onResponse??[]),error:mergeObjectArray(t.error??[],a?.error??[])});let t=t=>t&&"object"==typeof t&&!Array.isArray(t);export const mergeDeep=(a,s)=>{let n=Object.assign({},a);return t(a)&&t(s)&&Object.keys(s).forEach(e=>{t(s[e])&&e in a?n[e]=mergeDeep(a[e],s[e]):Object.assign(n,{[e]:s[e]})}),n};export const getSchemaValidator=(t,{models:a={},additionalProperties:s=!1,dynamic:n=!1})=>{if(!t||"string"==typeof t&&!(t in a))return;let l="string"==typeof t?a[t]:t;return("object"===l.type&&"additionalProperties"in l==!1&&(l.additionalProperties=s),n)?{schema:l,references:"",checkFunc:()=>{},code:"",Check:e=>r.Check(l,e),Errors:e=>r.Errors(l,e),Code:()=>""}:o.Compile(l)};export const getResponseSchemaValidator=(t,{models:a={},additionalProperties:s=!1,dynamic:n=!1})=>{if(!t||"string"==typeof t&&!(t in a))return;let l="string"==typeof t?a[t]:t,p=e=>n?{schema:e,references:"",checkFunc:()=>{},code:"",Check:o=>r.Check(e,o),Errors:o=>r.Errors(e,o),Code:()=>""}:o.Compile(e);if(e in l)return{200:p(l)};let i={};return Object.keys(l).forEach(r=>{let o=l[r];if("string"==typeof o){if(o in a){let t=a[o];t.type,i[+r]=e in t?p(t):t}return}"object"===o.type&&"additionalProperties"in o==!1&&(o.additionalProperties=s),i[+r]=e in o?p(o):o}),i};export const checksum=t=>{let a=9;for(let e=0;e<t.length;)a=Math.imul(a^t.charCodeAt(e++),387420489);return a^a>>>9};export const mergeLifeCycle=(t,a,s)=>{let n=e=>(s&&(e.$elysiaChecksum=s),e);return{start:mergeObjectArray(t.start,("start"in a?a.start:[]).map(n)),request:mergeObjectArray(t.request,("request"in a?a.request:[]).map(n)),parse:mergeObjectArray(t.parse,a?.parse??[]).map(n),transform:mergeObjectArray(t.transform,(a?.transform??[]).map(n)),beforeHandle:mergeObjectArray(t.beforeHandle,(a?.beforeHandle??[]).map(n)),afterHandle:mergeObjectArray(t.afterHandle,(a?.afterHandle??[]).map(n)),onResponse:mergeObjectArray(t.onResponse,(a?.onResponse??[]).map(n)),error:mergeObjectArray(t.error,(a?.error??[]).map(n)),stop:mergeObjectArray(t.stop,("stop"in a?a.stop:[]).map(n))}};export const asGlobalHook=(t,a=!0)=>({...t,type:t?.type,detail:t?.detail,parse:asGlobal(t?.parse,a),transform:asGlobal(t?.transform,a),beforeHandle:asGlobal(t?.beforeHandle,a),afterHandle:asGlobal(t?.afterHandle,a),onResponse:asGlobal(t?.onResponse,a),error:asGlobal(t?.error,a)});export const asGlobal=(t,a=!0)=>t?"function"==typeof t?(a?t.$elysiaHookType="global":t.$elysiaHookType=void 0,t):t.map(e=>(a?e.$elysiaHookType="global":e.$elysiaHookType=void 0,e)):t;let a=t=>t?"function"==typeof t?"global"===t.$elysiaHookType?t:void 0:t.filter(e=>"global"===e.$elysiaHookType):t;export const filterGlobalHook=t=>({...t,type:t?.type,detail:t?.detail,parse:a(t?.parse),transform:a(t?.transform),beforeHandle:a(t?.beforeHandle),afterHandle:a(t?.afterHandle),onResponse:a(t?.onResponse),error:a(t?.error)}); | ||
import{Kind as e}from"@sinclair/typebox";import{Value as r}from"@sinclair/typebox/value";import{TypeCompiler as o}from"@sinclair/typebox/compiler";export const mergeObjectArray=(e,r)=>{let o=[...Array.isArray(e)?e:[e]],t=[];for(let e of o)e.$elysiaChecksum&&t.push(e.$elysiaChecksum);for(let e of Array.isArray(r)?r:[r])t.includes(e?.$elysiaChecksum)||o.push(e);return o};export const mergeHook=(e,r)=>({body:r?.body??e?.body,headers:r?.headers??e?.headers,params:r?.params??e?.params,query:r?.query??e?.query,response:r?.response??e?.response,type:e?.type||r?.type,detail:mergeDeep(r?.detail??{},e?.detail??{}),parse:mergeObjectArray(e.parse??[],r?.parse??[]),transform:mergeObjectArray(e.transform??[],r?.transform??[]),beforeHandle:mergeObjectArray(e.beforeHandle??[],r?.beforeHandle??[]),afterHandle:mergeObjectArray(e.afterHandle??[],r?.afterHandle??[]),onResponse:mergeObjectArray(e.onResponse??[],r?.onResponse??[]),error:mergeObjectArray(e.error??[],r?.error??[])});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,{models:t={},additionalProperties:a=!1,dynamic:s=!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=a),s)?{schema:n,references:"",checkFunc:()=>{},code:"",Check:e=>r.Check(n,e),Errors:e=>r.Errors(n,e),Code:()=>""}:o.Compile(n)};export const getResponseSchemaValidator=(t,{models:a={},additionalProperties:s=!1,dynamic:n=!1})=>{if(!t||"string"==typeof t&&!(t in a))return;let l="string"==typeof t?a[t]:t,p=e=>n?{schema:e,references:"",checkFunc:()=>{},code:"",Check:o=>r.Check(e,o),Errors:o=>r.Errors(e,o),Code:()=>""}:o.Compile(e);if(e in l)return{200:p(l)};let i={};return Object.keys(l).forEach(r=>{let o=l[r];if("string"==typeof o){if(o in a){let t=a[o];t.type,i[+r]=e in t?p(t):t}return}"object"===o.type&&"additionalProperties"in o==!1&&(o.additionalProperties=s),i[+r]=e in o?p(o):o}),i};export const checksum=e=>{let r=9;for(let o=0;o<e.length;)r=Math.imul(r^e.charCodeAt(o++),387420489);return r^r>>>9};export const mergeLifeCycle=(e,r,o)=>{let t=e=>(o&&(e.$elysiaChecksum=o),e);return{start:mergeObjectArray(e.start,("start"in r?r.start:[]).map(t)),request:mergeObjectArray(e.request,("request"in r?r.request:[]).map(t)),parse:mergeObjectArray(e.parse,r?.parse??[]).map(t),transform:mergeObjectArray(e.transform,(r?.transform??[]).map(t)),beforeHandle:mergeObjectArray(e.beforeHandle,(r?.beforeHandle??[]).map(t)),afterHandle:mergeObjectArray(e.afterHandle,(r?.afterHandle??[]).map(t)),onResponse:mergeObjectArray(e.onResponse,(r?.onResponse??[]).map(t)),error:mergeObjectArray(e.error,(r?.error??[]).map(t)),stop:mergeObjectArray(e.stop,("stop"in r?r.stop:[]).map(t))}};export const asGlobalHook=(e,r=!0)=>({...e,type:e?.type,detail:e?.detail,parse:asGlobal(e?.parse,r),transform:asGlobal(e?.transform,r),beforeHandle:asGlobal(e?.beforeHandle,r),afterHandle:asGlobal(e?.afterHandle,r),onResponse:asGlobal(e?.onResponse,r),error:asGlobal(e?.error,r)});export const asGlobal=(e,r=!0)=>e?"function"==typeof e?(r?e.$elysiaHookType="global":e.$elysiaHookType=void 0,e):e.map(e=>(r?e.$elysiaHookType="global":e.$elysiaHookType=void 0,e)):e;let a=e=>e?"function"==typeof e?"global"===e.$elysiaHookType?e:void 0:e.filter(e=>"global"===e.$elysiaHookType):e;export const filterGlobalHook=e=>({...e,type:e?.type,detail:e?.detail,parse:a(e?.parse),transform:a(e?.transform),beforeHandle:a(e?.beforeHandle),afterHandle:a(e?.afterHandle),onResponse:a(e?.onResponse),error:a(e?.error)}); |
@@ -1,1 +0,1 @@ | ||
import{Memoirist as e}from"memoirist";import{ValidationError as r}from"../error";let s=s=>{let t=s.indexOf("/",10),i=s.indexOf("?",t);return -1===i?s.slice(t):s.slice(t,i)};export class ElysiaWS{raw;data;isSubscribed;constructor(s){this.raw=s,this.data=s.data,this.isSubscribed=s.isSubscribed}publish(s,t,i){return"object"==typeof t&&(t=JSON.stringify(t)),this.raw.publish(s,t,i),this}publishToSelf(s,t,i){return"object"==typeof t&&(t=JSON.stringify(t)),this.raw.publish(s,t,i),this}send(s){return"object"==typeof s&&(s=JSON.stringify(s)),this.raw.send(s),this}subscribe(s){return this.raw.subscribe(s),this}unsubscribe(s){return this.raw.unsubscribe(s),this}cork(s){return this.raw.cork(s),this}close(){return this.raw.close(),this}}export const ws=t=>i=>{i.wsRouter||(i.wsRouter=new e);let a=i.wsRouter;return i.config.serve||(i.config.serve={websocket:{...t,open(e){if(!e.data)return;let r=s(e?.data.request.url);if(!r)return;let t=a.find("subscribe",r)?.store;t&&t.open&&t.open(new ElysiaWS(e))},message(e,t){if(!e.data)return;let i=s(e?.data.request.url);if(!i)return;let n=a.find("subscribe",i)?.store;if(!n?.message)return;t=t.toString();let u=t.charCodeAt(0);if(47===u||123===u)try{t=JSON.parse(t)}catch(e){}else Number.isNaN(+t)||(t=+t);for(let r=0;r<e.data.transformMessage.length;r++){let s=e.data.transformMessage[r](t);void 0!==s&&(t=s)}if(e.data.message?.Check(t)===!1)return void e.send(new r("message",e.data.message,t).cause);n.message(new ElysiaWS(e),t)},close(e,r,t){if(!e.data)return;let i=s(e?.data.request.url);if(!i)return;let n=a.find("subscribe",i)?.store;n&&n.close&&n.close(new ElysiaWS(e),r,t)},drain(e){if(!e.data)return;let r=s(e?.data.request.url);if(!r)return;let t=a.find("subscribe",r)?.store;t&&t.drain&&t.drain(new ElysiaWS(e))}}}),i.decorate("publish",i.server?.publish).onStart(e=>{e.decorators.publish=e.server?.publish})}; | ||
import{Memoirist as e}from"memoirist";import{ValidationError as r}from"../error";let s=e=>{let r=e.indexOf("/",10),s=e.indexOf("?",r);return -1===s?e.slice(r):e.slice(r,s)};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=t=>i=>{i.wsRouter||(i.wsRouter=new e);let a=i.wsRouter;return i.config.serve||(i.config.serve={websocket:{...t,open(e){if(!e.data)return;let r=s(e?.data.request.url);if(!r)return;let t=a.find("subscribe",r)?.store;t&&t.open&&t.open(new ElysiaWS(e))},message(e,t){if(!e.data)return;let i=s(e?.data.request.url);if(!i)return;let n=a.find("subscribe",i)?.store;if(!n?.message)return;t=t.toString();let u=t.charCodeAt(0);if(47===u||123===u)try{t=JSON.parse(t)}catch(e){}else Number.isNaN(+t)||(t=+t);for(let r=0;r<e.data.transformMessage.length;r++){let s=e.data.transformMessage[r](t);void 0!==s&&(t=s)}if(e.data.message?.Check(t)===!1)return void e.send(new r("message",e.data.message,t).cause);n.message(new ElysiaWS(e),t)},close(e,r,t){if(!e.data)return;let i=s(e?.data.request.url);if(!i)return;let n=a.find("subscribe",i)?.store;n&&n.close&&n.close(new ElysiaWS(e),r,t)},drain(e){if(!e.data)return;let r=s(e?.data.request.url);if(!r)return;let t=a.find("subscribe",r)?.store;t&&t.drain&&t.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.6.14", | ||
"version": "0.6.15", | ||
"author": { | ||
@@ -6,0 +6,0 @@ "name": "saltyAom", |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
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
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
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
4268229
53
26392
9