elysia 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/compose.d.ts +4 -3
- package/dist/cjs/compose.js +109 -80
- package/dist/cjs/error.d.ts +2 -0
- package/dist/cjs/error.js +1 -1
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/types.d.ts +1 -0
- package/dist/cjs/ws/index.d.ts +1 -1
- package/dist/compose.d.ts +4 -3
- package/dist/compose.js +109 -80
- package/dist/error.d.ts +2 -0
- package/dist/error.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -2
- package/dist/types.d.ts +1 -0
- package/dist/ws/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/cjs/compose.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { Elysia } from '.';
|
|
2
2
|
import { SCHEMA, DEFS } from './utils';
|
|
3
|
-
import type { BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
|
|
4
|
-
import { TAnySchema } from '@sinclair/typebox';
|
|
3
|
+
import type { ElysiaConfig, BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
|
|
4
|
+
import type { TAnySchema } from '@sinclair/typebox';
|
|
5
5
|
export declare const hasReturn: (fnLiteral: string) => boolean;
|
|
6
6
|
export declare const isFnUse: (keyword: string, fnLiteral: string) => boolean;
|
|
7
7
|
export declare const findElysiaMeta: (type: string, schema: TAnySchema, found?: string[], parent?: string) => string[] | "root" | null;
|
|
8
|
-
export declare const composeHandler: ({
|
|
8
|
+
export declare const composeHandler: ({ method, hooks, validator, handler, handleError, meta, onRequest, config }: {
|
|
9
9
|
path: string;
|
|
10
10
|
method: HTTPMethod;
|
|
11
11
|
hooks: RegisteredHook<any>;
|
|
@@ -14,6 +14,7 @@ export declare const composeHandler: ({ path, method, hooks, validator, handler,
|
|
|
14
14
|
handleError: Elysia['handleError'];
|
|
15
15
|
meta?: (Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof import("./utils").EXPOSED, {}>) | undefined;
|
|
16
16
|
onRequest: BeforeRequestHandler<any, any>[];
|
|
17
|
+
config: ElysiaConfig;
|
|
17
18
|
}) => ComposedHandler;
|
|
18
19
|
export declare const composeGeneralHandler: (app: Elysia<any>) => any;
|
|
19
20
|
export declare const composeErrorHandler: (app: Elysia<any>) => any;
|
package/dist/cjs/compose.js
CHANGED
|
@@ -1,31 +1,42 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,r){for(var t in r)Object.defineProperty(e,t,{enumerable:!0,get:r[t]})}(exports,{hasReturn:function(){return
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,r){for(var t in r)Object.defineProperty(e,t,{enumerable:!0,get:r[t]})}(exports,{hasReturn:function(){return l},isFnUse:function(){return u},findElysiaMeta:function(){return f},composeHandler:function(){return d},composeGeneralHandler:function(){return p},composeErrorHandler:function(){return y}});const e=require("fast-querystring"),r=require("./handler"),t=require("./utils"),n=require("./error"),s="AsyncFunction",o=e=>e.constructor.name===s,a=new Headers,c=RegExp(" (\\w+) = context","g"),l=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")},i=e=>({composeValidation:(r,t=`c.${r}`)=>e?`throw new ValidationError(
|
|
2
|
+
'${r}',
|
|
3
|
+
${r},
|
|
4
|
+
${t}
|
|
5
|
+
)`:`return new ValidationError(
|
|
6
|
+
'${r}',
|
|
7
|
+
${r},
|
|
8
|
+
${t}
|
|
9
|
+
).toResponse(c.set.headers)`,composeResponseValidation:(r="r")=>e?`throw new ValidationError(
|
|
10
|
+
'response',
|
|
11
|
+
response[c.set.status],
|
|
12
|
+
${r}
|
|
13
|
+
)`:`return new ValidationError(
|
|
14
|
+
'response',
|
|
15
|
+
response[c.set.status],
|
|
16
|
+
${r}
|
|
17
|
+
).toResponse(c.set.headers)`}),u=(e,r)=>{let t=r.slice(r.indexOf("(")+1,r.indexOf(")"));if(""===t)return!1;if(123===t.charCodeAt(0))return!!(t.includes(`{ ${e}`)||t.includes(`, ${e}`));if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let n=[t];for(let e of r.matchAll(c))n.push(e[1]);let s=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(s))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1},f=(e,r,t=[],n="")=>{if("object"===r.type){let s=r.properties;for(let r in s){let o=s[r],a=n?n+"."+r:r;if("object"===o.type){f(e,o,t,a);continue}if(o.anyOf){for(let r of o.anyOf)f(e,r,t,a);continue}o.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(n&&t.push(n),"root"):null},d=({method:c,hooks:d,validator:p,handler:y,handleError:$,meta:h,onRequest:m,config:b})=>{let E=b.forceErrorEncapsulation||d.error.length>0||void 0===Bun,{composeValidation:q,composeResponseValidation:g}=i(E),w=E?"try {\n":"",x="string"==typeof d.type,k=p||"GET"!==c?[y,...d.transform,...d.beforeHandle,...d.afterHandle].map(e=>e.toString()):[],H="GET"!==c&&(p.body||x||k.some(e=>u("body",e))),R=p.headers||k.some(e=>u("headers",e));R&&(w+=a.toJSON?`c.headers = c.request.headers.toJSON()
|
|
2
18
|
`:`c.headers = {}
|
|
3
19
|
for (const key of c.request.headers.keys())
|
|
4
20
|
h[key] = c.request.headers.get(key)
|
|
5
21
|
|
|
6
|
-
if (headers.Check(
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
headers,
|
|
10
|
-
h
|
|
11
|
-
)
|
|
12
|
-
}
|
|
13
|
-
`);let k=p.query||w.some(e=>l("query",e));k&&(b+=`const url = c.request.url
|
|
22
|
+
if (headers.Check(c.headers) === false)
|
|
23
|
+
${q("headers")}
|
|
24
|
+
`);let v=p.query||k.some(e=>u("query",e));v&&(w+=`const url = c.request.url
|
|
14
25
|
|
|
15
26
|
if(c.query !== -1) {
|
|
16
27
|
c.query = parseQuery(url.substring(c.query + 1))
|
|
17
28
|
} else {
|
|
18
29
|
c.query = {}
|
|
19
30
|
}
|
|
20
|
-
`);let
|
|
31
|
+
`);let O=k.some(e=>u("set",e))||m.some(e=>u("set",e.toString())),S=H||y.constructor.name===s||d.parse.length||d.afterHandle.find(o)||d.beforeHandle.find(o)||d.transform.find(o);if(H){let e=p?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(x||e){if(d.parse.length){w+=(R?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
|
|
21
32
|
if (contentType) {
|
|
22
33
|
const index = contentType.indexOf(';')
|
|
23
34
|
if (index !== -1) contentType = contentType.substring(0, index)
|
|
24
35
|
`+`let used = false
|
|
25
|
-
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(
|
|
26
|
-
`),
|
|
36
|
+
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(w+=`if(!used) {
|
|
37
|
+
`),w+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
|
|
27
38
|
if(${r} !== undefined) { c.body = ${r}; used = true }
|
|
28
|
-
`,0!==e&&(
|
|
39
|
+
`,0!==e&&(w+="}")}w+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?w+="c.body = parseQuery(await c.request.text())":p.body.Code().includes("custom('File")?w+=`c.body = {}
|
|
29
40
|
|
|
30
41
|
await c.request.formData().then((form) => {
|
|
31
42
|
for (const key of form.keys()) {
|
|
@@ -37,7 +48,7 @@
|
|
|
37
48
|
c.body[key] = value[0]
|
|
38
49
|
else c.body[key] = value
|
|
39
50
|
}
|
|
40
|
-
})`:
|
|
51
|
+
})`:w+="c.body = JSON.parse(await c.request.text())":w+="c.body = await c.request.text()";else switch(d.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 = {}
|
|
41
52
|
|
|
42
53
|
for (const key of (await c.request.formData()).keys()) {
|
|
43
54
|
if (c.body[key])
|
|
@@ -47,15 +58,15 @@
|
|
|
47
58
|
if (value.length === 1)
|
|
48
59
|
c.body[key] = value[0]
|
|
49
60
|
else c.body[key] = value
|
|
50
|
-
}`}d.parse.length&&(
|
|
61
|
+
}`}d.parse.length&&(w+="}}")}else{if(w+="\n"+(R?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
|
|
51
62
|
if (contentType) {
|
|
52
63
|
const index = contentType.indexOf(';')
|
|
53
64
|
if (index !== -1) contentType = contentType.substring(0, index)
|
|
54
|
-
`,d.parse.length){
|
|
55
|
-
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(
|
|
56
|
-
`),
|
|
65
|
+
`,d.parse.length){w+=`let used = false
|
|
66
|
+
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(w+=`if(!used) {
|
|
67
|
+
`),w+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
|
|
57
68
|
if(${r} !== undefined) { c.body = ${r}; used = true }
|
|
58
|
-
`,0!==e&&(
|
|
69
|
+
`,0!==e&&(w+="}")}w+="if (!used)"}w+=`switch (contentType) {
|
|
59
70
|
case 'application/json':
|
|
60
71
|
c.body = JSON.parse(await c.request.text())
|
|
61
72
|
break
|
|
@@ -84,63 +95,59 @@
|
|
|
84
95
|
break
|
|
85
96
|
}
|
|
86
97
|
}
|
|
87
|
-
`}
|
|
98
|
+
`}w+="\n"}if(p.params){let e=f("Numeric",p.params.schema);if(e){if("object"==typeof e)for(let r of e)w+=`c.params.${r} = +c.params.${r};`;w+="\n"}}if(p.query){let e=f("Numeric",p.query.schema);if(e){if("object"==typeof e)for(let r of e)w+=`c.query.${r} = +c.query.${r};`;w+="\n"}}if(p.headers){let e=f("Numeric",p.headers.schema);if(e){if("object"==typeof e)for(let r of e)w+=`c.headers.${r} = +c.headers.${r};`;w+="\n"}}if(p.body){let e=f("Numeric",p.body.schema);if(e){switch(typeof e){case"string":w+="c.body = +c.body;";break;case"object":for(let r of e)w+=`c.body.${r} = +c.body.${r};`}w+="\n"}}if(d?.transform)for(let e=0;e<d.transform.length;e++){let r=d.transform[e];"derive"===r.$elysia?w+=d.transform[e].constructor.name===s?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:w+=d.transform[e].constructor.name===s?`await transform[${e}](c);`:`transform[${e}](c);`}if(p&&(p.headers&&(w+=`
|
|
88
99
|
if (headers.Check(c.headers) === false) {
|
|
89
|
-
|
|
90
|
-
'header',
|
|
91
|
-
headers,
|
|
92
|
-
c.headers
|
|
93
|
-
)
|
|
100
|
+
${q("headers")}
|
|
94
101
|
}
|
|
95
|
-
`),p.params&&(
|
|
102
|
+
`),p.params&&(w+=`if(params.Check(c.params) === false) { ${q("params")} }`),p.query&&(w+=`if(query.Check(c.query) === false) { ${q("query")} }`),p.body&&(w+=`if(body.Check(c.body) === false) { ${q("body")} }`)),d?.beforeHandle)for(let e=0;e<d.beforeHandle.length;e++){let r=`be${e}`,t=l(d.beforeHandle[e].toString());if(t){if(w+=(d.beforeHandle[e].constructor.name===s?`let ${r} = await beforeHandle[${e}](c);
|
|
96
103
|
`:`let ${r} = beforeHandle[${e}](c);
|
|
97
104
|
`)+`if(${r} !== undefined) {
|
|
98
|
-
`,d?.afterHandle)for(let e=0;e<d.afterHandle.length;e++){let t=
|
|
105
|
+
`,d?.afterHandle)for(let e=0;e<d.afterHandle.length;e++){let t=l(d.afterHandle[e].toString());if(t){let t=`af${e}`;w+=(d.afterHandle[e].constructor.name===s?`const ${t} = await afterHandle[${e}](c, ${r});
|
|
99
106
|
`:`const ${t} = afterHandle[${e}](c, ${r});
|
|
100
107
|
`)+`if(${t} !== undefined) { ${r} = ${t} }
|
|
101
|
-
`}else
|
|
108
|
+
`}else w+=d.afterHandle[e].constructor.name===s?`await afterHandle[${e}](c, ${r});
|
|
102
109
|
`:`afterHandle[${e}](c, ${r});
|
|
103
|
-
`}p.response&&(
|
|
110
|
+
`}p.response&&(w+=`if(response[c.set.status]?.Check(${r}) === false) {
|
|
104
111
|
if(!(response instanceof Error))
|
|
105
|
-
|
|
112
|
+
${g(r)}
|
|
106
113
|
}
|
|
107
|
-
`),
|
|
108
|
-
`}else
|
|
114
|
+
`),w+=`return mapEarlyResponse(${r}, c.set)}
|
|
115
|
+
`}else w+=d.beforeHandle[e].constructor.name===s?`await beforeHandle[${e}](c);
|
|
109
116
|
`:`beforeHandle[${e}](c);
|
|
110
|
-
`}if(d?.afterHandle.length){
|
|
117
|
+
`}if(d?.afterHandle.length){w+=y.constructor.name===s?`let r = await handler(c);
|
|
111
118
|
`:`let r = handler(c);
|
|
112
|
-
`;for(let e=0;e<d.afterHandle.length;e++){let r=`af${e}`,t=
|
|
119
|
+
`;for(let e=0;e<d.afterHandle.length;e++){let r=`af${e}`,t=l(d.afterHandle[e].toString());t?(w+=d.afterHandle[e].constructor.name===s?`let ${r} = await afterHandle[${e}](c, r)
|
|
113
120
|
`:`let ${r} = afterHandle[${e}](c, r)
|
|
114
|
-
`,p.response?
|
|
121
|
+
`,p.response?w+=`if(response[c.set.status]?.Check(${r}) === false) {
|
|
115
122
|
if(!(response instanceof Error))
|
|
116
|
-
|
|
123
|
+
${g(r)}
|
|
117
124
|
}
|
|
118
125
|
${r} = mapEarlyResponse(${r}, c.set)
|
|
119
126
|
if(${r}) return ${r};
|
|
120
|
-
`:
|
|
121
|
-
`):
|
|
127
|
+
`:w+=`if(${r}) return ${r};
|
|
128
|
+
`):w+=d.afterHandle[e].constructor.name===s?`await afterHandle[${e}](c, r)
|
|
122
129
|
`:`afterHandle[${e}](c, r)
|
|
123
|
-
`}p.response&&(
|
|
130
|
+
`}p.response&&(w+=`if(response[c.set.status]?.Check(r) === false) {
|
|
124
131
|
if(!(response instanceof Error))
|
|
125
|
-
|
|
132
|
+
${g()}
|
|
126
133
|
}
|
|
127
|
-
`),
|
|
128
|
-
`:
|
|
129
|
-
`}else if(p.response)
|
|
134
|
+
`),O?w+=`return mapResponse(r, c.set)
|
|
135
|
+
`:w+=`return mapCompactResponse(r)
|
|
136
|
+
`}else if(p.response)w+=(y.constructor.name===s?`const r = await handler(c);
|
|
130
137
|
`:`const r = handler(c);
|
|
131
138
|
`)+`if(response[c.set.status]?.Check(r) === false) {
|
|
132
139
|
if(!(response instanceof Error))
|
|
133
|
-
|
|
140
|
+
${g()}
|
|
134
141
|
}
|
|
135
|
-
`,
|
|
136
|
-
`:
|
|
137
|
-
`;else{let e=y.constructor.name===
|
|
138
|
-
`:
|
|
139
|
-
`}
|
|
142
|
+
`,O?w+=`return mapResponse(r, c.set)
|
|
143
|
+
`:w+=`return mapCompactResponse(r)
|
|
144
|
+
`;else{let e=y.constructor.name===s?"await handler(c) ":"handler(c)";O?w+=`return mapResponse(${e}, c.set)
|
|
145
|
+
`:w+=`return mapCompactResponse(${e})
|
|
146
|
+
`}E&&(w+=`
|
|
140
147
|
} catch(error) {
|
|
141
148
|
|
|
142
149
|
|
|
143
|
-
${
|
|
150
|
+
${S?"":"return (async () => {"}
|
|
144
151
|
const set = c.set
|
|
145
152
|
|
|
146
153
|
if (!set.status || set.status < 300) set.status = 500
|
|
@@ -159,8 +166,8 @@ if(${r}) return ${r};
|
|
|
159
166
|
}`:""}
|
|
160
167
|
|
|
161
168
|
return handleError(c.request, error, set)
|
|
162
|
-
${
|
|
163
|
-
}
|
|
169
|
+
${S?"":"})()"}
|
|
170
|
+
}`),w=`const {
|
|
164
171
|
handler,
|
|
165
172
|
handleError,
|
|
166
173
|
hooks: {
|
|
@@ -181,7 +188,6 @@ if(${r}) return ${r};
|
|
|
181
188
|
mapResponse,
|
|
182
189
|
mapCompactResponse,
|
|
183
190
|
mapEarlyResponse,
|
|
184
|
-
mapErrorCode,
|
|
185
191
|
parseQuery
|
|
186
192
|
},
|
|
187
193
|
error: {
|
|
@@ -190,7 +196,7 @@ if(${r}) return ${r};
|
|
|
190
196
|
ValidationError,
|
|
191
197
|
InternalServerError
|
|
192
198
|
},
|
|
193
|
-
${
|
|
199
|
+
${h?`
|
|
194
200
|
meta,
|
|
195
201
|
SCHEMA,
|
|
196
202
|
DEFS,`:""}
|
|
@@ -198,10 +204,11 @@ if(${r}) return ${r};
|
|
|
198
204
|
|
|
199
205
|
const parseError = new ParseError()
|
|
200
206
|
|
|
201
|
-
return ${
|
|
202
|
-
${
|
|
203
|
-
${
|
|
204
|
-
}`;let
|
|
207
|
+
return ${S?"async":""} function(c) {
|
|
208
|
+
${h?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""}
|
|
209
|
+
${w}
|
|
210
|
+
}`;let C=Function("hooks",w);return C({handler:y,hooks:d,validator:p,handleError:$,utils:{mapResponse:r.mapResponse,mapCompactResponse:r.mapCompactResponse,mapEarlyResponse:r.mapEarlyResponse,parseQuery:e.parse},error:{ParseError:n.ParseError,NotFoundError:n.NotFoundError,ValidationError:n.ValidationError,InternalServerError:n.InternalServerError},meta:h,SCHEMA:h?t.SCHEMA:void 0,DEFS:h?t.DEFS:void 0})},p=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:s,staticRouter:o}=e,a=`
|
|
211
|
+
const route = find(request.method, path) ${s.root.ALL?'?? find("ALL", path)':""}
|
|
205
212
|
if (route === null)
|
|
206
213
|
return ${e.event.error.length?`handleError(
|
|
207
214
|
request,
|
|
@@ -213,12 +220,12 @@ if(${r}) return ${r};
|
|
|
213
220
|
|
|
214
221
|
ctx.params = route.params
|
|
215
222
|
|
|
216
|
-
return route.store(ctx)`,c="";for(let[e,{code:r,all:t}]of Object.entries(
|
|
217
|
-
switch(method) {
|
|
223
|
+
return route.store(ctx)`,c="";for(let[e,{code:r,all:t}]of Object.entries(o.map))c+=`case '${e}':
|
|
224
|
+
switch(request.method) {
|
|
218
225
|
${r}
|
|
219
|
-
${t
|
|
226
|
+
${t??`default: ${a}`}}
|
|
220
227
|
|
|
221
|
-
`;let
|
|
228
|
+
`;let i=`const {
|
|
222
229
|
app,
|
|
223
230
|
app: { store, router, staticRouter },
|
|
224
231
|
${e.event.request.length?"mapEarlyResponse,":""}
|
|
@@ -229,7 +236,7 @@ ${t??"default:\n"+a}}
|
|
|
229
236
|
|
|
230
237
|
${e.event.request.length?"const onRequest = app.event.request":""}
|
|
231
238
|
|
|
232
|
-
${
|
|
239
|
+
${o.variables}
|
|
233
240
|
|
|
234
241
|
const find = router.find.bind(router)
|
|
235
242
|
const handleError = app.handleError.bind(this)
|
|
@@ -237,43 +244,65 @@ ${t??"default:\n"+a}}
|
|
|
237
244
|
${e.event.error.length?"":"const error404 = notFound.message.toString()"}
|
|
238
245
|
|
|
239
246
|
return function(request) {
|
|
247
|
+
`;if(e.event.request.length){i+=`
|
|
248
|
+
const ctx = {
|
|
249
|
+
request,
|
|
250
|
+
store,
|
|
251
|
+
set: {
|
|
252
|
+
headers: {},
|
|
253
|
+
status: 200
|
|
254
|
+
}
|
|
255
|
+
${t}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
try {
|
|
259
|
+
`;for(let r=0;r<e.event.request.length;r++){let t=l(e.event.request[r].toString());i+=t?`const response = mapEarlyResponse(
|
|
260
|
+
onRequest[${r}](ctx),
|
|
261
|
+
ctx.set
|
|
262
|
+
)
|
|
263
|
+
if (response) return response
|
|
264
|
+
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}i+=`} catch (error) {
|
|
265
|
+
return handleError(request, error, ctx.set)
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const url = request.url,
|
|
269
|
+
s = url.indexOf('/', 12),
|
|
270
|
+
i = ctx.query = url.indexOf('?', s + 1),
|
|
271
|
+
path = i === -1 ? url.substring(s) : url.substring(s, i);`}else i+=`
|
|
272
|
+
const url = request.url,
|
|
273
|
+
s = url.indexOf('/', 12)
|
|
274
|
+
|
|
240
275
|
const ctx = {
|
|
241
276
|
request,
|
|
242
277
|
store,
|
|
278
|
+
query: url.indexOf('?', s + 1),
|
|
243
279
|
set: {
|
|
244
280
|
headers: {},
|
|
245
281
|
status: 200
|
|
246
282
|
}
|
|
247
283
|
${t}
|
|
248
284
|
}
|
|
249
|
-
`;if(e.event.request.length){l+="try {";for(let r=0;r<e.event.request.length;r++){let t=i(e.event.request[r].toString());l+=t?`const response = mapEarlyResponse(
|
|
250
|
-
onRequest[${r}](ctx),
|
|
251
|
-
ctx.set
|
|
252
|
-
)
|
|
253
|
-
if (response) return response
|
|
254
|
-
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}l+=`} catch (error) {
|
|
255
|
-
return handleError(request, error, ctx.set)
|
|
256
|
-
}`}return l+=`
|
|
257
|
-
const { url, method } = request,
|
|
258
|
-
s = url.indexOf('/', 12),
|
|
259
|
-
i = ctx.query = url.indexOf('?', s + 1),
|
|
260
|
-
path = i === -1 ? url.substring(s) : url.substring(s, i)
|
|
261
285
|
|
|
286
|
+
const path =
|
|
287
|
+
ctx.query === -1
|
|
288
|
+
? url.substring(s)
|
|
289
|
+
: url.substring(s, ctx.query);`;return i+=`
|
|
262
290
|
switch(path) {
|
|
263
291
|
${c}
|
|
264
292
|
|
|
265
|
-
default:
|
|
293
|
+
default:
|
|
294
|
+
${a}
|
|
266
295
|
}
|
|
267
|
-
}`,e.handleError=
|
|
296
|
+
}`,e.handleError=y(e),Function("data",i)({app:e,mapEarlyResponse:r.mapEarlyResponse,NotFoundError:n.NotFoundError})},y=e=>{let t=`const {
|
|
268
297
|
app: { event: { error: onError } },
|
|
269
298
|
mapResponse
|
|
270
299
|
} = inject
|
|
271
300
|
|
|
272
|
-
return ${e.event.error.find(e=>e.constructor.name===
|
|
301
|
+
return ${e.event.error.find(e=>e.constructor.name===s)?"async":""} function(request, error, set) {`;for(let r=0;r<e.event.error.length;r++){let n=e.event.error[r],o=`${n.constructor.name===s?"await ":""}onError[${r}]({
|
|
273
302
|
request,
|
|
274
303
|
code: error.code ?? 'UNKNOWN',
|
|
275
304
|
error,
|
|
276
305
|
set
|
|
277
|
-
})`;
|
|
278
|
-
`:t+=
|
|
306
|
+
})`;l(n.toString())?t+=`const r${r} = ${o}; if(r${r} !== null) return mapResponse(r${r}, set)
|
|
307
|
+
`:t+=o+"\n"}return Function("inject",t+=`return new Response(error.message, { headers: set.headers, status: error.status ?? 500 })
|
|
279
308
|
}`)({app:e,mapResponse:r.mapResponse})};
|
package/dist/cjs/error.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bun-types" />
|
|
1
2
|
import type { TypeCheck } from '@sinclair/typebox/compiler';
|
|
2
3
|
export declare class InternalServerError extends Error {
|
|
3
4
|
code: string;
|
|
@@ -21,4 +22,5 @@ export declare class ValidationError extends Error {
|
|
|
21
22
|
status: number;
|
|
22
23
|
constructor(type: string, validator: TypeCheck<any>, value: unknown);
|
|
23
24
|
get all(): import("@sinclair/typebox/compiler").ValueError[];
|
|
25
|
+
toResponse(headers?: Record<string, any>): Response;
|
|
24
26
|
}
|
package/dist/cjs/error.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(r,t){for(var e in t)Object.defineProperty(r,e,{enumerable:!0,get:t[e]})}(exports,{InternalServerError:function(){return r},NotFoundError:function(){return t},ParseError:function(){return e},ValidationError:function(){return s}});class r extends Error{code="NOT_FOUND";status=500;constructor(){super("INTERNAL_SERVER_ERROR")}}class t extends Error{code="NOT_FOUND";status=404;constructor(){super("NOT_FOUND")}}class e extends Error{code="PARSE";status=400;constructor(){super("PARSE")}}class s extends Error{validator;value;code;status;constructor(r,t,e){let s=t.Errors(e).First();super(`Invalid ${r}: '${s?.path?.slice(1)||"root"}'. ${s?.message}`),this.validator=t,this.value=e,this.code="VALIDATION",this.status=400}get all(){return[...this.validator.Errors(this.value)]}}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(r,t){for(var e in t)Object.defineProperty(r,e,{enumerable:!0,get:t[e]})}(exports,{InternalServerError:function(){return r},NotFoundError:function(){return t},ParseError:function(){return e},ValidationError:function(){return s}});class r extends Error{code="NOT_FOUND";status=500;constructor(){super("INTERNAL_SERVER_ERROR")}}class t extends Error{code="NOT_FOUND";status=404;constructor(){super("NOT_FOUND")}}class e extends Error{code="PARSE";status=400;constructor(){super("PARSE")}}class s extends Error{validator;value;code;status;constructor(r,t,e){let s=t.Errors(e).First();super(`Invalid ${r}: '${s?.path?.slice(1)||"root"}'. ${s?.message}`),this.validator=t,this.value=e,this.code="VALIDATION",this.status=400}get all(){return[...this.validator.Errors(this.value)]}toResponse(r){return new Response(this.message,{status:400,headers:r})}}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -418,6 +418,7 @@ export default class Elysia<Instance extends ElysiaInstance = ElysiaInstance> {
|
|
|
418
418
|
handle: (request: Request) => Promise<Response>;
|
|
419
419
|
fetch: (request: Request) => MaybePromise<Response>;
|
|
420
420
|
handleError: (request: Request, error: Error | ValidationError | ParseError | NotFoundError | InternalServerError, set: Context['set']) => Promise<any>;
|
|
421
|
+
private outerErrorHandler;
|
|
421
422
|
listen: (options: string | number | Partial<Serve>, callback?: ListenCallback) => this;
|
|
422
423
|
stop: () => Promise<void>;
|
|
423
424
|
get modules(): Promise<Elysia<any>[]>;
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function e(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,s=new WeakMap;return(e=function(e){return e?s:r})(t)}"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{default:function(){return h},Elysia:function(){return h},t:function(){return i.t},ws:function(){return a.ws},SCHEMA:function(){return r.SCHEMA},DEFS:function(){return r.DEFS},EXPOSED:function(){return r.EXPOSED},getSchemaValidator:function(){return r.getSchemaValidator},mergeDeep:function(){return r.mergeDeep},mergeHook:function(){return r.mergeHook},mergeObjectArray:function(){return r.mergeObjectArray},getResponseSchemaValidator:function(){return r.getResponseSchemaValidator},ParseError:function(){return n.ParseError},NotFoundError:function(){return n.NotFoundError},ValidationError:function(){return n.ValidationError},InternalServerError:function(){return n.InternalServerError}});const t=require("memoirist"),r=require("./utils"),s=require("./schema"),o=require("./compose"),a=require("./ws"),i=require("./custom-types"),n=require("./error");class h{config;store={};meta={[r.SCHEMA]:Object.create(null),[r.DEFS]:Object.create(null),[r.EXPOSED]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t.Memoirist;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}add(e,t,a,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.routes.push({method:e,path:t,handler:a,hooks:(0,r.mergeHook)({...this.event},i)});let h=this.meta[r.DEFS];if(i?.type)switch(i.type){case"text":i.type="text/plain";break;case"json":i.type="application/json";break;case"formdata":i.type="multipart/form-data";break;case"urlencoded":i.type="application/x-www-form-urlencoded"}(0,s.registerSchemaPath)({schema:this.meta[r.SCHEMA],contentType:i?.type,hook:i,method:e,path:t,models:this.meta[r.DEFS]});let u={body:(0,r.getSchemaValidator)(i?.body??this.$schema?.body,h),headers:(0,r.getSchemaValidator)(i?.headers??this.$schema?.headers,h,!0),params:(0,r.getSchemaValidator)(i?.params??this.$schema?.params,h),query:(0,r.getSchemaValidator)(i?.query??this.$schema?.query,h),response:(0,r.getResponseSchemaValidator)(i?.response??this.$schema?.response,h)},c=(0,r.mergeHook)(this.event,i),d=(0,o.composeHandler)({path:t,method:e,hooks:c,validator:u,handler:a,handleError:this.handleError,meta:n?this.meta:void 0,onRequest:this.event.request});if(-1===t.indexOf(":")&&-1===t.indexOf("*")){let r=this.staticRouter.handlers.length;this.staticRouter.handlers.push(d),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}]
|
|
1
|
+
function e(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,s=new WeakMap;return(e=function(e){return e?s:r})(t)}"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{default:function(){return h},Elysia:function(){return h},t:function(){return i.t},ws:function(){return a.ws},SCHEMA:function(){return r.SCHEMA},DEFS:function(){return r.DEFS},EXPOSED:function(){return r.EXPOSED},getSchemaValidator:function(){return r.getSchemaValidator},mergeDeep:function(){return r.mergeDeep},mergeHook:function(){return r.mergeHook},mergeObjectArray:function(){return r.mergeObjectArray},getResponseSchemaValidator:function(){return r.getResponseSchemaValidator},ParseError:function(){return n.ParseError},NotFoundError:function(){return n.NotFoundError},ValidationError:function(){return n.ValidationError},InternalServerError:function(){return n.InternalServerError}});const t=require("memoirist"),r=require("./utils"),s=require("./schema"),o=require("./compose"),a=require("./ws"),i=require("./custom-types"),n=require("./error");class h{config;store={};meta={[r.SCHEMA]:Object.create(null),[r.DEFS]:Object.create(null),[r.EXPOSED]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t.Memoirist;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",forceErrorEncapsulation:!1,...e}}add(e,t,a,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.routes.push({method:e,path:t,handler:a,hooks:(0,r.mergeHook)({...this.event},i)});let h=this.meta[r.DEFS];if(i?.type)switch(i.type){case"text":i.type="text/plain";break;case"json":i.type="application/json";break;case"formdata":i.type="multipart/form-data";break;case"urlencoded":i.type="application/x-www-form-urlencoded"}(0,s.registerSchemaPath)({schema:this.meta[r.SCHEMA],contentType:i?.type,hook:i,method:e,path:t,models:this.meta[r.DEFS]});let u={body:(0,r.getSchemaValidator)(i?.body??this.$schema?.body,h),headers:(0,r.getSchemaValidator)(i?.headers??this.$schema?.headers,h,!0),params:(0,r.getSchemaValidator)(i?.params??this.$schema?.params,h),query:(0,r.getSchemaValidator)(i?.query??this.$schema?.query,h),response:(0,r.getResponseSchemaValidator)(i?.response??this.$schema?.response,h)},c=(0,r.mergeHook)(this.event,i),d=(0,o.composeHandler)({path:t,method:e,hooks:c,validator:u,handler:a,handleError:this.handleError,meta:n?this.meta:void 0,onRequest:this.event.request,config:this.config});if(-1===t.indexOf(":")&&-1===t.indexOf("*")){let r=this.staticRouter.handlers.length;this.staticRouter.handlers.push(d),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}]
|
|
2
2
|
`,this.staticRouter.map[t]||(this.staticRouter.map[t]={code:""}),"ALL"===e?this.staticRouter.map[t].all=`default: return st${r}(ctx)
|
|
3
3
|
`:this.staticRouter.map[t].code+=`case '${e}': return st${r}(ctx)
|
|
4
|
-
`}else this.router.add(e,t,d)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,s){let o=new h;o.store=this.store,this.wsRouter&&o.use((0,a.ws)());let i="object"==typeof t,n=(i?s:t)(o);return this.decorators=(0,r.mergeDeep)(this.decorators,o.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(o.routes).forEach(({method:s,path:a,handler:h,hooks:u})=>{if(i){let i=`${e}${a}`,c=o.wsRouter?.find("subscribe",i);if(c){let e=o.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this.add(s,i,h,(0,r.mergeHook)(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${a}`,i=o.wsRouter?.find("subscribe",t);if(i){let e=o.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(t,e[2])}this.add(s,t,h,(0,r.mergeHook)(u,{error:n.event.error}))}}),o.wsRouter&&this.wsRouter&&o.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let s=new h;s.store=this.store,this.wsRouter&&s.use((0,a.ws)());let o=t(s);return this.decorators=(0,r.mergeDeep)(this.decorators,s.decorators),o.event.request.length&&(this.event.request=[...this.event.request,...o.event.request]),this.model(o.meta[r.DEFS]),Object.values(s.routes).forEach(({method:t,path:a,handler:i,hooks:n})=>{let h=s.wsRouter?.find("subscribe",a);if(h){let e=s.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(t,a,i,(0,r.mergeHook)(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...o.event.error]:[n.error,...o.event.error]:o.event.error}))}),s.wsRouter&&this.wsRouter&&s.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),headers:e.request.headers.toJSON(),message:(0,r.getSchemaValidator)(t?.body,this.meta[r.DEFS]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=(0,r.mergeDeep)(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=(0,r.mergeDeep)(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(t){return this.use(async r=>{let{fn:s}=await Promise.resolve().then(()=>(function(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var s=e(r);if(s&&s.has(t))return s.get(t);var o={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if("default"!==i&&Object.prototype.hasOwnProperty.call(t,i)){var n=a?Object.getOwnPropertyDescriptor(t,i):null;n&&(n.get||n.set)?Object.defineProperty(o,i,n):o[i]=t[i]}return o.default=t,s&&s.set(t,o),o})(require("@elysiajs/fn")));return s({app:r,value:t,path:r.config.fn})})}schema(e){let t=this.meta[r.DEFS];return this.$schema={body:(0,r.getSchemaValidator)(e.body,t),headers:(0,r.getSchemaValidator)(e?.headers,t,!0),params:(0,r.getSchemaValidator)(e?.params,t),query:(0,r.getSchemaValidator)(e?.query,t),response:(0,r.getSchemaValidator)(e?.response,t)},this}compile(){return this.fetch=(0,o.composeGeneralHandler)(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=(0,o.composeGeneralHandler)(this))(e);handleError=async(e,t,r)=>(this.handleError=(0,o.composeErrorHandler)(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[r.DEFS]||(this.meta[r.DEFS][e]=t)}):this.meta[r.DEFS][e]=t,this}}
|
|
4
|
+
`}else this.router.add(e,t,d)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,s){let o=new h;o.store=this.store,this.wsRouter&&o.use((0,a.ws)());let i="object"==typeof t,n=(i?s:t)(o);return this.decorators=(0,r.mergeDeep)(this.decorators,o.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(o.routes).forEach(({method:s,path:a,handler:h,hooks:u})=>{if(i){let i=`${e}${a}`,c=o.wsRouter?.find("subscribe",i);if(c){let e=o.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this.add(s,i,h,(0,r.mergeHook)(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${a}`,i=o.wsRouter?.find("subscribe",t);if(i){let e=o.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(t,e[2])}this.add(s,t,h,(0,r.mergeHook)(u,{error:n.event.error}))}}),o.wsRouter&&this.wsRouter&&o.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let s=new h;s.store=this.store,this.wsRouter&&s.use((0,a.ws)());let o=t(s);return this.decorators=(0,r.mergeDeep)(this.decorators,s.decorators),o.event.request.length&&(this.event.request=[...this.event.request,...o.event.request]),this.model(o.meta[r.DEFS]),Object.values(s.routes).forEach(({method:t,path:a,handler:i,hooks:n})=>{let h=s.wsRouter?.find("subscribe",a);if(h){let e=s.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(t,a,i,(0,r.mergeHook)(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...o.event.error]:[n.error,...o.event.error]:o.event.error}))}),s.wsRouter&&this.wsRouter&&s.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),headers:e.request.headers.toJSON(),message:(0,r.getSchemaValidator)(t?.body,this.meta[r.DEFS]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=(0,r.mergeDeep)(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=(0,r.mergeDeep)(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(t){return this.use(async r=>{let{fn:s}=await Promise.resolve().then(()=>(function(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var s=e(r);if(s&&s.has(t))return s.get(t);var o={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if("default"!==i&&Object.prototype.hasOwnProperty.call(t,i)){var n=a?Object.getOwnPropertyDescriptor(t,i):null;n&&(n.get||n.set)?Object.defineProperty(o,i,n):o[i]=t[i]}return o.default=t,s&&s.set(t,o),o})(require("@elysiajs/fn")));return s({app:r,value:t,path:r.config.fn})})}schema(e){let t=this.meta[r.DEFS];return this.$schema={body:(0,r.getSchemaValidator)(e.body,t),headers:(0,r.getSchemaValidator)(e?.headers,t,!0),params:(0,r.getSchemaValidator)(e?.params,t),query:(0,r.getSchemaValidator)(e?.query,t),response:(0,r.getSchemaValidator)(e?.response,t)},this}compile(){return this.fetch=(0,o.composeGeneralHandler)(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=(0,o.composeGeneralHandler)(this))(e);handleError=async(e,t,r)=>(this.handleError=(0,o.composeErrorHandler)(this))(e,t,r);outerErrorHandler=e=>new Response(e.message,{status:e?.status??500});listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r,error:this.outerErrorHandler}:{...this.config.serve,port:e,fetch:r,error:this.outerErrorHandler};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[r.DEFS]||(this.meta[r.DEFS][e]=t)}):this.meta[r.DEFS][e]=t,this}}
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -188,6 +188,7 @@ export type ComposedHandler = (context: Context) => MaybePromise<Response>;
|
|
|
188
188
|
export interface ElysiaConfig {
|
|
189
189
|
fn?: string;
|
|
190
190
|
serve?: Partial<Serve>;
|
|
191
|
+
forceErrorEncapsulation?: boolean;
|
|
191
192
|
}
|
|
192
193
|
export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : never;
|
|
193
194
|
export type ExtractPath<Path> = Path extends `${infer A}/${infer B}` ? IsPathParameter<A> | ExtractPath<B> : IsPathParameter<Path>;
|
package/dist/cjs/ws/index.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ export declare class ElysiaWS<WS extends ElysiaWSContext<any> = ElysiaWSContext,
|
|
|
20
20
|
export declare const ws: (config?: Omit<WebSocketHandler, 'open' | 'message' | 'close' | 'drain'>) => (app: Elysia) => Elysia<{
|
|
21
21
|
store: {};
|
|
22
22
|
request: {
|
|
23
|
-
publish: (topic: string, data: string | import("bun").ArrayBufferView
|
|
23
|
+
publish: (topic: string, data: string | ArrayBuffer | SharedArrayBuffer | import("bun").ArrayBufferView, compress?: boolean | undefined) => number;
|
|
24
24
|
};
|
|
25
25
|
schema: {};
|
|
26
26
|
meta: Record<typeof import("..").SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof import("..").EXPOSED, {}>;
|
package/dist/compose.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { Elysia } from '.';
|
|
2
2
|
import { SCHEMA, DEFS } from './utils';
|
|
3
|
-
import type { BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
|
|
4
|
-
import { TAnySchema } from '@sinclair/typebox';
|
|
3
|
+
import type { ElysiaConfig, BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types';
|
|
4
|
+
import type { TAnySchema } from '@sinclair/typebox';
|
|
5
5
|
export declare const hasReturn: (fnLiteral: string) => boolean;
|
|
6
6
|
export declare const isFnUse: (keyword: string, fnLiteral: string) => boolean;
|
|
7
7
|
export declare const findElysiaMeta: (type: string, schema: TAnySchema, found?: string[], parent?: string) => string[] | "root" | null;
|
|
8
|
-
export declare const composeHandler: ({
|
|
8
|
+
export declare const composeHandler: ({ method, hooks, validator, handler, handleError, meta, onRequest, config }: {
|
|
9
9
|
path: string;
|
|
10
10
|
method: HTTPMethod;
|
|
11
11
|
hooks: RegisteredHook<any>;
|
|
@@ -14,6 +14,7 @@ export declare const composeHandler: ({ path, method, hooks, validator, handler,
|
|
|
14
14
|
handleError: Elysia['handleError'];
|
|
15
15
|
meta?: (Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof import("./utils").EXPOSED, {}>) | undefined;
|
|
16
16
|
onRequest: BeforeRequestHandler<any, any>[];
|
|
17
|
+
config: ElysiaConfig;
|
|
17
18
|
}) => ComposedHandler;
|
|
18
19
|
export declare const composeGeneralHandler: (app: Elysia<any>) => any;
|
|
19
20
|
export declare const composeErrorHandler: (app: Elysia<any>) => any;
|
package/dist/compose.js
CHANGED
|
@@ -1,31 +1,42 @@
|
|
|
1
|
-
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t,mapCompactResponse as
|
|
1
|
+
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t,mapCompactResponse as s}from"./handler";import{SCHEMA as n,DEFS as o}from"./utils";import{ParseError as a,NotFoundError as c,ValidationError as l,InternalServerError as i}from"./error";let f="AsyncFunction",u=e=>e.constructor.name===f,d=new Headers,p=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 y=e=>({composeValidation:(r,t=`c.${r}`)=>e?`throw new ValidationError(
|
|
2
|
+
'${r}',
|
|
3
|
+
${r},
|
|
4
|
+
${t}
|
|
5
|
+
)`:`return new ValidationError(
|
|
6
|
+
'${r}',
|
|
7
|
+
${r},
|
|
8
|
+
${t}
|
|
9
|
+
).toResponse(c.set.headers)`,composeResponseValidation:(r="r")=>e?`throw new ValidationError(
|
|
10
|
+
'response',
|
|
11
|
+
response[c.set.status],
|
|
12
|
+
${r}
|
|
13
|
+
)`:`return new ValidationError(
|
|
14
|
+
'response',
|
|
15
|
+
response[c.set.status],
|
|
16
|
+
${r}
|
|
17
|
+
).toResponse(c.set.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.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let s=[t];for(let e of r.matchAll(p))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 o=n[r],a=s?s+"."+r:r;if("object"===o.type){findElysiaMeta(e,o,t,a);continue}if(o.anyOf){for(let r of o.anyOf)findElysiaMeta(e,r,t,a);continue}o.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(s&&t.push(s),"root"):null};export const composeHandler=({method:p,hooks:h,validator:$,handler:m,handleError:b,meta:q,onRequest:E,config:g})=>{let x=g.forceErrorEncapsulation||h.error.length>0||void 0===Bun,{composeValidation:w,composeResponseValidation:k}=y(x),H=x?"try {\n":"",R="string"==typeof h.type,v=$||"GET"!==p?[m,...h.transform,...h.beforeHandle,...h.afterHandle].map(e=>e.toString()):[],O="GET"!==p&&($.body||R||v.some(e=>isFnUse("body",e))),S=$.headers||v.some(e=>isFnUse("headers",e));S&&(H+=d.toJSON?`c.headers = c.request.headers.toJSON()
|
|
2
18
|
`:`c.headers = {}
|
|
3
19
|
for (const key of c.request.headers.keys())
|
|
4
20
|
h[key] = c.request.headers.get(key)
|
|
5
21
|
|
|
6
|
-
if (headers.Check(
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
headers,
|
|
10
|
-
h
|
|
11
|
-
)
|
|
12
|
-
}
|
|
13
|
-
`);let R=m.query||x.some(e=>isFnUse("query",e));R&&(q+=`const url = c.request.url
|
|
22
|
+
if (headers.Check(c.headers) === false)
|
|
23
|
+
${w("headers")}
|
|
24
|
+
`);let C=$.query||v.some(e=>isFnUse("query",e));C&&(H+=`const url = c.request.url
|
|
14
25
|
|
|
15
26
|
if(c.query !== -1) {
|
|
16
27
|
c.query = parseQuery(url.substring(c.query + 1))
|
|
17
28
|
} else {
|
|
18
29
|
c.query = {}
|
|
19
30
|
}
|
|
20
|
-
`);let v
|
|
31
|
+
`);let F=v.some(e=>isFnUse("set",e))||E.some(e=>isFnUse("set",e.toString())),N=O||m.constructor.name===f||h.parse.length||h.afterHandle.find(u)||h.beforeHandle.find(u)||h.transform.find(u);if(O){let e=$?.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(R||e){if(h.parse.length){H+=(S?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
|
|
21
32
|
if (contentType) {
|
|
22
33
|
const index = contentType.indexOf(';')
|
|
23
34
|
if (index !== -1) contentType = contentType.substring(0, index)
|
|
24
35
|
`+`let used = false
|
|
25
|
-
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(
|
|
26
|
-
`),
|
|
36
|
+
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(H+=`if(!used) {
|
|
37
|
+
`),H+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
|
|
27
38
|
if(${r} !== undefined) { c.body = ${r}; used = true }
|
|
28
|
-
`,0!==e&&(
|
|
39
|
+
`,0!==e&&(H+="}")}H+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?H+="c.body = parseQuery(await c.request.text())":$.body.Code().includes("custom('File")?H+=`c.body = {}
|
|
29
40
|
|
|
30
41
|
await c.request.formData().then((form) => {
|
|
31
42
|
for (const key of form.keys()) {
|
|
@@ -37,7 +48,7 @@ import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapRespons
|
|
|
37
48
|
c.body[key] = value[0]
|
|
38
49
|
else c.body[key] = value
|
|
39
50
|
}
|
|
40
|
-
})`:
|
|
51
|
+
})`:H+="c.body = JSON.parse(await c.request.text())":H+="c.body = await c.request.text()";else switch(h.type){case"application/json":H+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":H+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":H+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":H+=`c.body = {}
|
|
41
52
|
|
|
42
53
|
for (const key of (await c.request.formData()).keys()) {
|
|
43
54
|
if (c.body[key])
|
|
@@ -47,15 +58,15 @@ import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapRespons
|
|
|
47
58
|
if (value.length === 1)
|
|
48
59
|
c.body[key] = value[0]
|
|
49
60
|
else c.body[key] = value
|
|
50
|
-
}`}h.parse.length&&(
|
|
61
|
+
}`}h.parse.length&&(H+="}}")}else{if(H+="\n"+(S?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
|
|
51
62
|
if (contentType) {
|
|
52
63
|
const index = contentType.indexOf(';')
|
|
53
64
|
if (index !== -1) contentType = contentType.substring(0, index)
|
|
54
|
-
`,h.parse.length){
|
|
55
|
-
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(
|
|
56
|
-
`),
|
|
65
|
+
`,h.parse.length){H+=`let used = false
|
|
66
|
+
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(H+=`if(!used) {
|
|
67
|
+
`),H+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
|
|
57
68
|
if(${r} !== undefined) { c.body = ${r}; used = true }
|
|
58
|
-
`,0!==e&&(
|
|
69
|
+
`,0!==e&&(H+="}")}H+="if (!used)"}H+=`switch (contentType) {
|
|
59
70
|
case 'application/json':
|
|
60
71
|
c.body = JSON.parse(await c.request.text())
|
|
61
72
|
break
|
|
@@ -84,63 +95,59 @@ import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapRespons
|
|
|
84
95
|
break
|
|
85
96
|
}
|
|
86
97
|
}
|
|
87
|
-
`}
|
|
98
|
+
`}H+="\n"}if($.params){let e=findElysiaMeta("Numeric",$.params.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.params.${r} = +c.params.${r};`;H+="\n"}}if($.query){let e=findElysiaMeta("Numeric",$.query.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.query.${r} = +c.query.${r};`;H+="\n"}}if($.headers){let e=findElysiaMeta("Numeric",$.headers.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.headers.${r} = +c.headers.${r};`;H+="\n"}}if($.body){let e=findElysiaMeta("Numeric",$.body.schema);if(e){switch(typeof e){case"string":H+="c.body = +c.body;";break;case"object":for(let r of e)H+=`c.body.${r} = +c.body.${r};`}H+="\n"}}if(h?.transform)for(let e=0;e<h.transform.length;e++){let r=h.transform[e];"derive"===r.$elysia?H+=h.transform[e].constructor.name===f?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:H+=h.transform[e].constructor.name===f?`await transform[${e}](c);`:`transform[${e}](c);`}if($&&($.headers&&(H+=`
|
|
88
99
|
if (headers.Check(c.headers) === false) {
|
|
89
|
-
|
|
90
|
-
'header',
|
|
91
|
-
headers,
|
|
92
|
-
c.headers
|
|
93
|
-
)
|
|
100
|
+
${w("headers")}
|
|
94
101
|
}
|
|
95
|
-
`)
|
|
102
|
+
`),$.params&&(H+=`if(params.Check(c.params) === false) { ${w("params")} }`),$.query&&(H+=`if(query.Check(c.query) === false) { ${w("query")} }`),$.body&&(H+=`if(body.Check(c.body) === false) { ${w("body")} }`)),h?.beforeHandle)for(let e=0;e<h.beforeHandle.length;e++){let r=`be${e}`,t=hasReturn(h.beforeHandle[e].toString());if(t){if(H+=(h.beforeHandle[e].constructor.name===f?`let ${r} = await beforeHandle[${e}](c);
|
|
96
103
|
`:`let ${r} = beforeHandle[${e}](c);
|
|
97
104
|
`)+`if(${r} !== undefined) {
|
|
98
|
-
`,h?.afterHandle)for(let e=0;e<h.afterHandle.length;e++){let t=hasReturn(h.afterHandle[e].toString());if(t){let t=`af${e}`;
|
|
105
|
+
`,h?.afterHandle)for(let e=0;e<h.afterHandle.length;e++){let t=hasReturn(h.afterHandle[e].toString());if(t){let t=`af${e}`;H+=(h.afterHandle[e].constructor.name===f?`const ${t} = await afterHandle[${e}](c, ${r});
|
|
99
106
|
`:`const ${t} = afterHandle[${e}](c, ${r});
|
|
100
107
|
`)+`if(${t} !== undefined) { ${r} = ${t} }
|
|
101
|
-
`}else
|
|
108
|
+
`}else H+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, ${r});
|
|
102
109
|
`:`afterHandle[${e}](c, ${r});
|
|
103
|
-
`}
|
|
110
|
+
`}$.response&&(H+=`if(response[c.set.status]?.Check(${r}) === false) {
|
|
104
111
|
if(!(response instanceof Error))
|
|
105
|
-
|
|
112
|
+
${k(r)}
|
|
106
113
|
}
|
|
107
|
-
`),
|
|
108
|
-
`}else
|
|
114
|
+
`),H+=`return mapEarlyResponse(${r}, c.set)}
|
|
115
|
+
`}else H+=h.beforeHandle[e].constructor.name===f?`await beforeHandle[${e}](c);
|
|
109
116
|
`:`beforeHandle[${e}](c);
|
|
110
|
-
`}if(h?.afterHandle.length){
|
|
117
|
+
`}if(h?.afterHandle.length){H+=m.constructor.name===f?`let r = await handler(c);
|
|
111
118
|
`:`let r = handler(c);
|
|
112
|
-
`;for(let e=0;e<h.afterHandle.length;e++){let r=`af${e}`,t=hasReturn(h.afterHandle[e].toString());t?(
|
|
119
|
+
`;for(let e=0;e<h.afterHandle.length;e++){let r=`af${e}`,t=hasReturn(h.afterHandle[e].toString());t?(H+=h.afterHandle[e].constructor.name===f?`let ${r} = await afterHandle[${e}](c, r)
|
|
113
120
|
`:`let ${r} = afterHandle[${e}](c, r)
|
|
114
|
-
|
|
121
|
+
`,$.response?H+=`if(response[c.set.status]?.Check(${r}) === false) {
|
|
115
122
|
if(!(response instanceof Error))
|
|
116
|
-
|
|
123
|
+
${k(r)}
|
|
117
124
|
}
|
|
118
125
|
${r} = mapEarlyResponse(${r}, c.set)
|
|
119
126
|
if(${r}) return ${r};
|
|
120
|
-
`:
|
|
121
|
-
`):
|
|
127
|
+
`:H+=`if(${r}) return ${r};
|
|
128
|
+
`):H+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, r)
|
|
122
129
|
`:`afterHandle[${e}](c, r)
|
|
123
|
-
`}
|
|
130
|
+
`}$.response&&(H+=`if(response[c.set.status]?.Check(r) === false) {
|
|
124
131
|
if(!(response instanceof Error))
|
|
125
|
-
|
|
132
|
+
${k()}
|
|
126
133
|
}
|
|
127
|
-
`),
|
|
128
|
-
`:
|
|
129
|
-
`}else if(
|
|
134
|
+
`),F?H+=`return mapResponse(r, c.set)
|
|
135
|
+
`:H+=`return mapCompactResponse(r)
|
|
136
|
+
`}else if($.response)H+=(m.constructor.name===f?`const r = await handler(c);
|
|
130
137
|
`:`const r = handler(c);
|
|
131
138
|
`)+`if(response[c.set.status]?.Check(r) === false) {
|
|
132
139
|
if(!(response instanceof Error))
|
|
133
|
-
|
|
140
|
+
${k()}
|
|
134
141
|
}
|
|
135
|
-
`,
|
|
136
|
-
`:
|
|
137
|
-
`;else{let e
|
|
138
|
-
`:
|
|
139
|
-
`}
|
|
142
|
+
`,F?H+=`return mapResponse(r, c.set)
|
|
143
|
+
`:H+=`return mapCompactResponse(r)
|
|
144
|
+
`;else{let e=m.constructor.name===f?"await handler(c) ":"handler(c)";F?H+=`return mapResponse(${e}, c.set)
|
|
145
|
+
`:H+=`return mapCompactResponse(${e})
|
|
146
|
+
`}x&&(H+=`
|
|
140
147
|
} catch(error) {
|
|
141
148
|
|
|
142
149
|
|
|
143
|
-
${
|
|
150
|
+
${N?"":"return (async () => {"}
|
|
144
151
|
const set = c.set
|
|
145
152
|
|
|
146
153
|
if (!set.status || set.status < 300) set.status = 500
|
|
@@ -159,8 +166,8 @@ if(${r}) return ${r};
|
|
|
159
166
|
}`:""}
|
|
160
167
|
|
|
161
168
|
return handleError(c.request, error, set)
|
|
162
|
-
${
|
|
163
|
-
}
|
|
169
|
+
${N?"":"})()"}
|
|
170
|
+
}`),H=`const {
|
|
164
171
|
handler,
|
|
165
172
|
handleError,
|
|
166
173
|
hooks: {
|
|
@@ -181,7 +188,6 @@ if(${r}) return ${r};
|
|
|
181
188
|
mapResponse,
|
|
182
189
|
mapCompactResponse,
|
|
183
190
|
mapEarlyResponse,
|
|
184
|
-
mapErrorCode,
|
|
185
191
|
parseQuery
|
|
186
192
|
},
|
|
187
193
|
error: {
|
|
@@ -190,7 +196,7 @@ if(${r}) return ${r};
|
|
|
190
196
|
ValidationError,
|
|
191
197
|
InternalServerError
|
|
192
198
|
},
|
|
193
|
-
${
|
|
199
|
+
${q?`
|
|
194
200
|
meta,
|
|
195
201
|
SCHEMA,
|
|
196
202
|
DEFS,`:""}
|
|
@@ -198,10 +204,11 @@ if(${r}) return ${r};
|
|
|
198
204
|
|
|
199
205
|
const parseError = new ParseError()
|
|
200
206
|
|
|
201
|
-
return ${
|
|
202
|
-
${
|
|
203
|
-
${
|
|
204
|
-
}`;let
|
|
207
|
+
return ${N?"async":""} function(c) {
|
|
208
|
+
${q?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""}
|
|
209
|
+
${H}
|
|
210
|
+
}`;let T=Function("hooks",H);return T({handler:m,hooks:h,validator:$,handleError:b,utils:{mapResponse:t,mapCompactResponse:s,mapEarlyResponse:r,parseQuery:e},error:{ParseError:a,NotFoundError:c,ValidationError:l,InternalServerError:i},meta:q,SCHEMA:q?n:void 0,DEFS:q?o:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:s,staticRouter:n}=e,o=`
|
|
211
|
+
const route = find(request.method, path) ${s.root.ALL?'?? find("ALL", path)':""}
|
|
205
212
|
if (route === null)
|
|
206
213
|
return ${e.event.error.length?`handleError(
|
|
207
214
|
request,
|
|
@@ -213,12 +220,12 @@ if(${r}) return ${r};
|
|
|
213
220
|
|
|
214
221
|
ctx.params = route.params
|
|
215
222
|
|
|
216
|
-
return route.store(ctx)`,a="";for(let[e,{code:r,all:t}]of Object.entries(
|
|
217
|
-
switch(method) {
|
|
223
|
+
return route.store(ctx)`,a="";for(let[e,{code:r,all:t}]of Object.entries(n.map))a+=`case '${e}':
|
|
224
|
+
switch(request.method) {
|
|
218
225
|
${r}
|
|
219
|
-
${t
|
|
226
|
+
${t??`default: ${o}`}}
|
|
220
227
|
|
|
221
|
-
`;let
|
|
228
|
+
`;let l=`const {
|
|
222
229
|
app,
|
|
223
230
|
app: { store, router, staticRouter },
|
|
224
231
|
${e.event.request.length?"mapEarlyResponse,":""}
|
|
@@ -229,7 +236,7 @@ ${t??"default:\n"+o}}
|
|
|
229
236
|
|
|
230
237
|
${e.event.request.length?"const onRequest = app.event.request":""}
|
|
231
238
|
|
|
232
|
-
${
|
|
239
|
+
${n.variables}
|
|
233
240
|
|
|
234
241
|
const find = router.find.bind(router)
|
|
235
242
|
const handleError = app.handleError.bind(this)
|
|
@@ -237,43 +244,65 @@ ${t??"default:\n"+o}}
|
|
|
237
244
|
${e.event.error.length?"":"const error404 = notFound.message.toString()"}
|
|
238
245
|
|
|
239
246
|
return function(request) {
|
|
247
|
+
`;if(e.event.request.length){l+=`
|
|
248
|
+
const ctx = {
|
|
249
|
+
request,
|
|
250
|
+
store,
|
|
251
|
+
set: {
|
|
252
|
+
headers: {},
|
|
253
|
+
status: 200
|
|
254
|
+
}
|
|
255
|
+
${t}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
try {
|
|
259
|
+
`;for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());l+=t?`const response = mapEarlyResponse(
|
|
260
|
+
onRequest[${r}](ctx),
|
|
261
|
+
ctx.set
|
|
262
|
+
)
|
|
263
|
+
if (response) return response
|
|
264
|
+
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}l+=`} catch (error) {
|
|
265
|
+
return handleError(request, error, ctx.set)
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const url = request.url,
|
|
269
|
+
s = url.indexOf('/', 12),
|
|
270
|
+
i = ctx.query = url.indexOf('?', s + 1),
|
|
271
|
+
path = i === -1 ? url.substring(s) : url.substring(s, i);`}else l+=`
|
|
272
|
+
const url = request.url,
|
|
273
|
+
s = url.indexOf('/', 12)
|
|
274
|
+
|
|
240
275
|
const ctx = {
|
|
241
276
|
request,
|
|
242
277
|
store,
|
|
278
|
+
query: url.indexOf('?', s + 1),
|
|
243
279
|
set: {
|
|
244
280
|
headers: {},
|
|
245
281
|
status: 200
|
|
246
282
|
}
|
|
247
283
|
${t}
|
|
248
284
|
}
|
|
249
|
-
`;if(e.event.request.length){i+="try {";for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());i+=t?`const response = mapEarlyResponse(
|
|
250
|
-
onRequest[${r}](ctx),
|
|
251
|
-
ctx.set
|
|
252
|
-
)
|
|
253
|
-
if (response) return response
|
|
254
|
-
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}i+=`} catch (error) {
|
|
255
|
-
return handleError(request, error, ctx.set)
|
|
256
|
-
}`}return i+=`
|
|
257
|
-
const { url, method } = request,
|
|
258
|
-
s = url.indexOf('/', 12),
|
|
259
|
-
i = ctx.query = url.indexOf('?', s + 1),
|
|
260
|
-
path = i === -1 ? url.substring(s) : url.substring(s, i)
|
|
261
285
|
|
|
286
|
+
const path =
|
|
287
|
+
ctx.query === -1
|
|
288
|
+
? url.substring(s)
|
|
289
|
+
: url.substring(s, ctx.query);`;return l+=`
|
|
262
290
|
switch(path) {
|
|
263
291
|
${a}
|
|
264
292
|
|
|
265
|
-
default:
|
|
293
|
+
default:
|
|
294
|
+
${o}
|
|
266
295
|
}
|
|
267
|
-
}`,e.handleError=composeErrorHandler(e),Function("data",
|
|
296
|
+
}`,e.handleError=composeErrorHandler(e),Function("data",l)({app:e,mapEarlyResponse:r,NotFoundError:c})};export const composeErrorHandler=e=>{let r=`const {
|
|
268
297
|
app: { event: { error: onError } },
|
|
269
298
|
mapResponse
|
|
270
299
|
} = inject
|
|
271
300
|
|
|
272
|
-
return ${e.event.error.find(e=>e.constructor.name===f)?"async":""} function(request, error, set) {`;for(let t=0;t<e.event.error.length;t++){let
|
|
301
|
+
return ${e.event.error.find(e=>e.constructor.name===f)?"async":""} function(request, error, set) {`;for(let t=0;t<e.event.error.length;t++){let s=e.event.error[t],n=`${s.constructor.name===f?"await ":""}onError[${t}]({
|
|
273
302
|
request,
|
|
274
303
|
code: error.code ?? 'UNKNOWN',
|
|
275
304
|
error,
|
|
276
305
|
set
|
|
277
|
-
})`;hasReturn(
|
|
278
|
-
`:r+=
|
|
306
|
+
})`;hasReturn(s.toString())?r+=`const r${t} = ${n}; if(r${t} !== null) return mapResponse(r${t}, set)
|
|
307
|
+
`:r+=n+"\n"}return Function("inject",r+=`return new Response(error.message, { headers: set.headers, status: error.status ?? 500 })
|
|
279
308
|
}`)({app:e,mapResponse:t})};
|
package/dist/error.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bun-types" />
|
|
1
2
|
import type { TypeCheck } from '@sinclair/typebox/compiler';
|
|
2
3
|
export declare class InternalServerError extends Error {
|
|
3
4
|
code: string;
|
|
@@ -21,4 +22,5 @@ export declare class ValidationError extends Error {
|
|
|
21
22
|
status: number;
|
|
22
23
|
constructor(type: string, validator: TypeCheck<any>, value: unknown);
|
|
23
24
|
get all(): import("@sinclair/typebox/compiler").ValueError[];
|
|
25
|
+
toResponse(headers?: Record<string, any>): Response;
|
|
24
26
|
}
|
package/dist/error.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
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{validator;value;code;status;constructor(r,t
|
|
1
|
+
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{validator;value;code;status;constructor(r,s,t){let e=s.Errors(t).First();super(`Invalid ${r}: '${e?.path?.slice(1)||"root"}'. ${e?.message}`),this.validator=s,this.value=t,this.code="VALIDATION",this.status=400}get all(){return[...this.validator.Errors(this.value)]}toResponse(r){return new Response(this.message,{status:400,headers:r})}}
|
package/dist/index.d.ts
CHANGED
|
@@ -418,6 +418,7 @@ export default class Elysia<Instance extends ElysiaInstance = ElysiaInstance> {
|
|
|
418
418
|
handle: (request: Request) => Promise<Response>;
|
|
419
419
|
fetch: (request: Request) => MaybePromise<Response>;
|
|
420
420
|
handleError: (request: Request, error: Error | ValidationError | ParseError | NotFoundError | InternalServerError, set: Context['set']) => Promise<any>;
|
|
421
|
+
private outerErrorHandler;
|
|
421
422
|
listen: (options: string | number | Partial<Serve>, callback?: ListenCallback) => this;
|
|
422
423
|
stop: () => Promise<void>;
|
|
423
424
|
get modules(): Promise<Elysia<any>[]>;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as i,getResponseSchemaValidator as a,mergeDeep as h}from"./utils";import{registerSchemaPath as n}from"./schema";import{composeErrorHandler as u,composeGeneralHandler as d,composeHandler as l}from"./compose";import{ws as c}from"./ws";export default class p{config;store={};meta={[t]:Object.create(null),[s]:Object.create(null),[r]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}add(e,r,h,u,{allowMeta:d=!1}={allowMeta:!1}){r=""===r?r:47===r.charCodeAt(0)?r:`/${r}`,this.routes.push({method:e,path:r,handler:h,hooks:o({...this.event},u)});let c=this.meta[s];if(u?.type)switch(u.type){case"text":u.type="text/plain";break;case"json":u.type="application/json";break;case"formdata":u.type="multipart/form-data";break;case"urlencoded":u.type="application/x-www-form-urlencoded"}n({schema:this.meta[t],contentType:u?.type,hook:u,method:e,path:r,models:this.meta[s]});let p={body:i(u?.body??this.$schema?.body,c),headers:i(u?.headers??this.$schema?.headers,c,!0),params:i(u?.params??this.$schema?.params,c),query:i(u?.query??this.$schema?.query,c),response:a(u?.response??this.$schema?.response,c)},f=o(this.event,u),m=l({path:r,method:e,hooks:f,validator:p,handler:h,handleError:this.handleError,meta:d?this.meta:void 0,onRequest:this.event.request});if(-1===r.indexOf(":")&&-1===r.indexOf("*")){let t=this.staticRouter.handlers.length;this.staticRouter.handlers.push(m),this.staticRouter.variables+=`const st${t} = staticRouter.handlers[${t}]
|
|
1
|
+
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as i,getResponseSchemaValidator as a,mergeDeep as h}from"./utils";import{registerSchemaPath as n}from"./schema";import{composeErrorHandler as u,composeGeneralHandler as d,composeHandler as l}from"./compose";import{ws as c}from"./ws";export default class p{config;store={};meta={[t]:Object.create(null),[s]:Object.create(null),[r]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",forceErrorEncapsulation:!1,...e}}add(e,r,h,u,{allowMeta:d=!1}={allowMeta:!1}){r=""===r?r:47===r.charCodeAt(0)?r:`/${r}`,this.routes.push({method:e,path:r,handler:h,hooks:o({...this.event},u)});let c=this.meta[s];if(u?.type)switch(u.type){case"text":u.type="text/plain";break;case"json":u.type="application/json";break;case"formdata":u.type="multipart/form-data";break;case"urlencoded":u.type="application/x-www-form-urlencoded"}n({schema:this.meta[t],contentType:u?.type,hook:u,method:e,path:r,models:this.meta[s]});let p={body:i(u?.body??this.$schema?.body,c),headers:i(u?.headers??this.$schema?.headers,c,!0),params:i(u?.params??this.$schema?.params,c),query:i(u?.query??this.$schema?.query,c),response:a(u?.response??this.$schema?.response,c)},f=o(this.event,u),m=l({path:r,method:e,hooks:f,validator:p,handler:h,handleError:this.handleError,meta:d?this.meta:void 0,onRequest:this.event.request,config:this.config});if(-1===r.indexOf(":")&&-1===r.indexOf("*")){let t=this.staticRouter.handlers.length;this.staticRouter.handlers.push(m),this.staticRouter.variables+=`const st${t} = staticRouter.handlers[${t}]
|
|
2
2
|
`,this.staticRouter.map[r]||(this.staticRouter.map[r]={code:""}),"ALL"===e?this.staticRouter.map[r].all=`default: return st${t}(ctx)
|
|
3
3
|
`:this.staticRouter.map[r].code+=`case '${e}': return st${t}(ctx)
|
|
4
|
-
`}else this.router.add(e,r,m)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,r){let i=new p;i.store=this.store,this.wsRouter&&i.use(c());let a="object"==typeof t,n=(a?r:t)(i);return this.decorators=h(this.decorators,i.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(i.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(a){let a=`${e}${s}`,d=i.wsRouter?.find("subscribe",a);if(d){let e=i.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(r,a,h,o(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${s}`,a=i.wsRouter?.find("subscribe",t);if(a){let e=i.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this.add(r,t,h,o(u,{error:n.event.error}))}}),i.wsRouter&&this.wsRouter&&i.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let r=new p;r.store=this.store,this.wsRouter&&r.use(c());let i=t(r);return this.decorators=h(this.decorators,r.decorators),i.event.request.length&&(this.event.request=[...this.event.request,...i.event.request]),this.model(i.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:a,hooks:h})=>{let n=r.wsRouter?.find("subscribe",s);if(n){let e=r.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(s,e[2])}this.add(t,s,a,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...i.event.error]:[h.error,...i.event.error]:i.event.error}))}),r.wsRouter&&this.wsRouter&&r.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),headers:e.request.headers.toJSON(),message:i(t?.body,this.meta[s]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=h(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=h(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(e){return this.use(async t=>{let{fn:r}=await import("@elysiajs/fn");return r({app:t,value:e,path:t.config.fn})})}schema(e){let t=this.meta[s];return this.$schema={body:i(e.body,t),headers:i(e?.headers,t,!0),params:i(e?.params,t),query:i(e?.query,t),response:i(e?.response,t)},this}compile(){return this.fetch=d(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=d(this))(e);handleError=async(e,t,r)=>(this.handleError=u(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[s]||(this.meta[s][e]=t)}):this.meta[s][e]=t,this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{p as Elysia};
|
|
4
|
+
`}else this.router.add(e,r,m)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,r){let i=new p;i.store=this.store,this.wsRouter&&i.use(c());let a="object"==typeof t,n=(a?r:t)(i);return this.decorators=h(this.decorators,i.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(i.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(a){let a=`${e}${s}`,d=i.wsRouter?.find("subscribe",a);if(d){let e=i.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(r,a,h,o(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${s}`,a=i.wsRouter?.find("subscribe",t);if(a){let e=i.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this.add(r,t,h,o(u,{error:n.event.error}))}}),i.wsRouter&&this.wsRouter&&i.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let r=new p;r.store=this.store,this.wsRouter&&r.use(c());let i=t(r);return this.decorators=h(this.decorators,r.decorators),i.event.request.length&&(this.event.request=[...this.event.request,...i.event.request]),this.model(i.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:a,hooks:h})=>{let n=r.wsRouter?.find("subscribe",s);if(n){let e=r.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(s,e[2])}this.add(t,s,a,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...i.event.error]:[h.error,...i.event.error]:i.event.error}))}),r.wsRouter&&this.wsRouter&&r.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("CONNECT",e,t,r),this}ws(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),headers:e.request.headers.toJSON(),message:i(t?.body,this.meta[s]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.add(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=h(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=h(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(e){return this.use(async t=>{let{fn:r}=await import("@elysiajs/fn");return r({app:t,value:e,path:t.config.fn})})}schema(e){let t=this.meta[s];return this.$schema={body:i(e.body,t),headers:i(e?.headers,t,!0),params:i(e?.params,t),query:i(e?.query,t),response:i(e?.response,t)},this}compile(){return this.fetch=d(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=d(this))(e);handleError=async(e,t,r)=>(this.handleError=u(this))(e,t,r);outerErrorHandler=e=>new Response(e.message,{status:e?.status??500});listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r,error:this.outerErrorHandler}:{...this.config.serve,port:e,fetch:r,error:this.outerErrorHandler};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[s]||(this.meta[s][e]=t)}):this.meta[s][e]=t,this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{p as Elysia};
|
package/dist/types.d.ts
CHANGED
|
@@ -188,6 +188,7 @@ export type ComposedHandler = (context: Context) => MaybePromise<Response>;
|
|
|
188
188
|
export interface ElysiaConfig {
|
|
189
189
|
fn?: string;
|
|
190
190
|
serve?: Partial<Serve>;
|
|
191
|
+
forceErrorEncapsulation?: boolean;
|
|
191
192
|
}
|
|
192
193
|
export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : never;
|
|
193
194
|
export type ExtractPath<Path> = Path extends `${infer A}/${infer B}` ? IsPathParameter<A> | ExtractPath<B> : IsPathParameter<Path>;
|
package/dist/ws/index.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ export declare class ElysiaWS<WS extends ElysiaWSContext<any> = ElysiaWSContext,
|
|
|
20
20
|
export declare const ws: (config?: Omit<WebSocketHandler, 'open' | 'message' | 'close' | 'drain'>) => (app: Elysia) => Elysia<{
|
|
21
21
|
store: {};
|
|
22
22
|
request: {
|
|
23
|
-
publish: (topic: string, data: string | import("bun").ArrayBufferView
|
|
23
|
+
publish: (topic: string, data: string | ArrayBuffer | SharedArrayBuffer | import("bun").ArrayBufferView, compress?: boolean | undefined) => number;
|
|
24
24
|
};
|
|
25
25
|
schema: {};
|
|
26
26
|
meta: Record<typeof import("..").SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof import("..").EXPOSED, {}>;
|