elysia 2.0.0-exp.2 → 2.0.0-exp.21

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.
Files changed (135) hide show
  1. package/dist/_virtual/_rolldown/runtime.js +2 -0
  2. package/dist/adapter/bun/index.d.ts +2 -25
  3. package/dist/adapter/bun/index.js +18 -12
  4. package/dist/adapter/bun/index.mjs +19 -13
  5. package/dist/adapter/bun/router.js +1 -1
  6. package/dist/adapter/bun/router.mjs +1 -1
  7. package/dist/adapter/constants.d.ts +3 -26
  8. package/dist/adapter/index.d.ts +1 -26
  9. package/dist/adapter/index.js +1 -17
  10. package/dist/adapter/index.mjs +1 -17
  11. package/dist/adapter/types.d.ts +1 -0
  12. package/dist/adapter/utils.d.ts +3 -4
  13. package/dist/adapter/utils.js +83 -81
  14. package/dist/adapter/utils.mjs +82 -80
  15. package/dist/adapter/web-standard/handler.js +6 -3
  16. package/dist/adapter/web-standard/handler.mjs +6 -3
  17. package/dist/adapter/web-standard/index.d.ts +2 -26
  18. package/dist/adapter/web-standard/index.js +12 -1
  19. package/dist/adapter/web-standard/index.mjs +12 -1
  20. package/dist/base.d.ts +38 -68
  21. package/dist/base.js +133 -97
  22. package/dist/base.mjs +133 -97
  23. package/dist/compile/aot.d.ts +22 -1
  24. package/dist/compile/aot.js +22 -0
  25. package/dist/compile/aot.mjs +22 -0
  26. package/dist/compile/handler/index.d.ts +2 -2
  27. package/dist/compile/handler/index.js +85 -456
  28. package/dist/compile/handler/index.mjs +86 -457
  29. package/dist/compile/handler/jit.d.ts +35 -0
  30. package/dist/compile/handler/jit.js +445 -0
  31. package/dist/compile/handler/jit.mjs +443 -0
  32. package/dist/compile/handler/params.js +3 -2
  33. package/dist/compile/handler/params.mjs +4 -3
  34. package/dist/compile/handler/reconstruct.d.ts +13 -0
  35. package/dist/compile/handler/reconstruct.js +29 -0
  36. package/dist/compile/handler/reconstruct.mjs +28 -0
  37. package/dist/compile/handler/utils.d.ts +2 -1
  38. package/dist/compile/handler/utils.js +9 -3
  39. package/dist/compile/handler/utils.mjs +9 -4
  40. package/dist/compile/jit-probe.d.ts +19 -0
  41. package/dist/compile/jit-probe.js +38 -0
  42. package/dist/compile/jit-probe.mjs +36 -0
  43. package/dist/cookie/index.d.ts +4 -3
  44. package/dist/cookie/index.js +2 -1
  45. package/dist/cookie/index.mjs +2 -1
  46. package/dist/cookie/serialize.d.ts +6 -0
  47. package/dist/cookie/serialize.js +28 -0
  48. package/dist/cookie/serialize.mjs +27 -0
  49. package/dist/cookie/utils.d.ts +1 -2
  50. package/dist/cookie/utils.js +2 -23
  51. package/dist/cookie/utils.mjs +5 -25
  52. package/dist/handler/error.js +2 -2
  53. package/dist/handler/error.mjs +3 -3
  54. package/dist/handler/fetch.js +49 -42
  55. package/dist/handler/fetch.mjs +50 -43
  56. package/dist/index.d.ts +13 -8
  57. package/dist/index.js +11 -4
  58. package/dist/index.mjs +7 -6
  59. package/dist/parse-query.js +1 -1
  60. package/dist/parse-query.mjs +1 -1
  61. package/dist/plugin/bun.d.ts +10 -0
  62. package/dist/plugin/bun.js +18 -1
  63. package/dist/plugin/bun.mjs +19 -2
  64. package/dist/plugin/core.d.ts +61 -1
  65. package/dist/plugin/core.js +90 -10
  66. package/dist/plugin/core.mjs +90 -12
  67. package/dist/plugin/esbuild.d.ts +10 -0
  68. package/dist/plugin/esbuild.js +18 -1
  69. package/dist/plugin/esbuild.mjs +19 -2
  70. package/dist/plugin/source.d.ts +38 -1
  71. package/dist/plugin/source.js +104 -13
  72. package/dist/plugin/source.mjs +102 -14
  73. package/dist/plugin/vite.d.ts +7 -0
  74. package/dist/plugin/vite.js +22 -1
  75. package/dist/plugin/vite.mjs +23 -2
  76. package/dist/sucrose.js +23 -10
  77. package/dist/sucrose.mjs +23 -10
  78. package/dist/trace.d.ts +1 -1
  79. package/dist/trace.js +4 -6
  80. package/dist/trace.mjs +4 -6
  81. package/dist/type/bridge.d.ts +9 -8
  82. package/dist/type/coerce.d.ts +20 -2
  83. package/dist/type/coerce.js +110 -0
  84. package/dist/type/coerce.mjs +109 -2
  85. package/dist/type/compat.js +4 -3
  86. package/dist/type/compat.mjs +2 -1
  87. package/dist/type/constants.d.ts +1 -1
  88. package/dist/type/elysia/boolean-string.js +1 -1
  89. package/dist/type/elysia/boolean-string.mjs +1 -1
  90. package/dist/type/elysia/file-type.js +1 -1
  91. package/dist/type/elysia/file-type.mjs +1 -1
  92. package/dist/type/elysia/integer-string.js +1 -1
  93. package/dist/type/elysia/integer-string.mjs +1 -1
  94. package/dist/type/exports.js +29 -2059
  95. package/dist/type/exports.mjs +7 -295
  96. package/dist/type/index.d.ts +6 -2
  97. package/dist/type/index.js +4 -0
  98. package/dist/type/index.mjs +3 -1
  99. package/dist/type/types.d.ts +1 -1
  100. package/dist/type/utils.js +4 -4
  101. package/dist/type/utils.mjs +4 -4
  102. package/dist/type/validator/custom-error.d.ts +10 -0
  103. package/dist/type/validator/custom-error.js +113 -0
  104. package/dist/type/validator/custom-error.mjs +110 -0
  105. package/dist/type/validator/default-precompute.d.ts +22 -0
  106. package/dist/type/validator/default-precompute.js +476 -0
  107. package/dist/type/validator/default-precompute.mjs +465 -0
  108. package/dist/type/validator/frozen-check.d.ts +11 -0
  109. package/dist/type/validator/frozen-check.js +19 -0
  110. package/dist/type/validator/frozen-check.mjs +18 -0
  111. package/dist/type/{validator.d.ts → validator/index.d.ts} +7 -20
  112. package/dist/type/validator/index.js +572 -0
  113. package/dist/type/validator/index.mjs +567 -0
  114. package/dist/type/validator/string-codec-aot.d.ts +9 -0
  115. package/dist/type/validator/string-codec-aot.js +106 -0
  116. package/dist/type/validator/string-codec-aot.mjs +102 -0
  117. package/dist/type/validator/validator-cache.d.ts +21 -0
  118. package/dist/type/validator/validator-cache.js +163 -0
  119. package/dist/type/validator/validator-cache.mjs +161 -0
  120. package/dist/types.d.ts +22 -14
  121. package/dist/universal/file.d.ts +1 -1
  122. package/dist/universal/file.js +35 -29
  123. package/dist/universal/file.mjs +35 -29
  124. package/dist/utils.d.ts +12 -1
  125. package/dist/utils.js +89 -45
  126. package/dist/utils.mjs +88 -46
  127. package/dist/validator/index.d.ts +1 -1
  128. package/dist/validator/index.js +15 -2
  129. package/dist/validator/index.mjs +15 -2
  130. package/dist/validator/route.d.ts +0 -1
  131. package/dist/ws/route.js +47 -24
  132. package/dist/ws/route.mjs +48 -25
  133. package/package.json +10 -4
  134. package/dist/type/validator.js +0 -1033
  135. package/dist/type/validator.mjs +0 -1029
@@ -1,112 +1,20 @@
1
- import { hasHeaderShorthand } from "../../universal/constants.mjs";
2
- import { isDynamicRegex } from "../../constants.mjs";
3
- import { cloneHook, eventProperties, flattenChain, flattenChainMemo, fnOrigin, isLocalScope, mapMethodBack, mergeHook, nullObject, requestId } from "../../utils.mjs";
4
- import { ElysiaStatus, ParseError, ValidationError } from "../../error.mjs";
5
- import { compileCookieConfig } from "../../cookie/config.mjs";
6
- import { buildCookieJar, parseCookieRaw, parseCookieRawSync, signCookieValues } from "../../cookie/utils.mjs";
7
- import { tee } from "../../adapter/utils.mjs";
8
- import { parseQueryFromURL } from "../../parse-query.mjs";
9
- import { sucrose } from "../../sucrose.mjs";
10
- import { Capture, Compiled } from "../aot.mjs";
11
- import { RouteValidator } from "../../validator/route.mjs";
12
- import { isAsyncFunction, isAsyncLifecycle, mayReturnPromise } from "../utils.mjs";
13
- import { cloneResponse, getQueryParseArgs, mapAfterHandle, mapAfterResponse, mapBeforeHandle, mapError, mapMapResponse, mapTransform } from "./utils.mjs";
14
- import { defaultAdapter } from "../../adapter/constants.mjs";
15
- import { forwardError } from "../../handler/utils.mjs";
16
- import { createTracer } from "../../trace.mjs";
1
+ import { cloneHook, eventProperties, flattenChain, flattenChainMemo, fnOrigin, isLocalScope, mapMethodBack, mergeHook, nullObject } from "../../utils.mjs";
2
+ import { createContext } from "../../context.mjs";
3
+ import { Compiled } from "../aot.mjs";
17
4
  import { resolveHandlerParams } from "./params.mjs";
5
+ import { compileHandlerJit, setCaptureHeaderShorthand } from "./jit.mjs";
6
+ import { Reconstrct } from "./reconstruct.mjs";
7
+ import { defaultAdapter } from "../../adapter/constants.mjs";
18
8
 
19
9
  //#region src/compile/handler/index.ts
20
- const parseFormData = "c.body=await pf(c)\n";
21
- const matchReturnIdentifier = /(?:=>|\breturn)\s+(?!(?:true|false|null|undefined|void|new|typeof|async|await|function|class)\b)[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*\s*(?![\w$([])/;
22
- const mayReturnIdentifier = (fn) => matchReturnIdentifier.test(fn.toString());
23
- let captureHeaderShorthand;
24
- const setCaptureHeaderShorthand = (value) => {
25
- captureHeaderShorthand = value;
26
- };
27
- function builtinParser(adapter, parse, link) {
28
- switch (parse) {
29
- case "formdata":
30
- case "multipart/form-data":
31
- link(adapter.formData, "pf");
32
- return parseFormData;
33
- case "json":
34
- case "application/json":
35
- link(adapter.json, "pj");
36
- return "c.body=await pj(c)\n";
37
- case "urlencoded":
38
- case "application/x-www-form-urlencoded":
39
- link(adapter.urlencoded, "pu");
40
- return "c.body=await pu(c)\n";
41
- case "arrayBuffer":
42
- case "application/octet-stream":
43
- link(adapter.arrayBuffer, "pa");
44
- return "c.body=await pa(c)\n";
45
- case "text":
46
- case "text/plain":
47
- link(adapter.text, "pt");
48
- return "c.body=await pt(c)\n";
49
- case "none": return "";
50
- default: throw new Error(`Unsupported content type: ${parse}`);
51
- }
52
- }
53
- function parse(adapter, parsers, bodyVali, hasHeaders, link, report) {
54
- if (parsers && typeof parsers === "function") parsers = [parsers];
55
- if (typeof parsers === "string" || parsers?.length === 1 && typeof parsers[0] === "string") {
56
- if (parsers.length === 1) parsers = parsers[0];
57
- const builtinName = parsers;
58
- const child = report?.resolveChild(builtinName);
59
- const begin = child ? child.begin : "";
60
- const end = child ? child.end() : "";
61
- return begin + builtinParser(adapter, parsers, link) + end;
62
- }
63
- let code = `let ct=((${hasHeaders ? "c.headers['content-type']" : "c.request.headers.get('content-type')"})||'')\nlet cti=ct.indexOf(";")
64
- if(cti!==-1)ct=ct.slice(0,cti)
65
- c.contentType=ct
66
- `;
67
- let hasFn = false;
68
- let hasType = false;
69
- if (parsers) for (let i = 0; i < parsers.length; i++) {
70
- const parser = parsers[i];
71
- if (typeof parser === "function") {
72
- hasFn = true;
73
- link(0, "");
74
- const child = report?.resolveChild(parser.name || "anonymous");
75
- if (i) code += "if(!hasBody){";
76
- if (child) code += child.begin;
77
- code += isAsyncFunction(parser) ? `c.body=await ho.parse[${i}](c,ct)\n` : `_bp=ho.parse[${i}](c,ct)\nif(_bp instanceof Promise)_bp=await _bp\nc.body=_bp\n`;
78
- code += "hasBody=c.body!==undefined\n";
79
- if (child) code += child.end();
80
- if (i) code += "}\n";
81
- } else {
82
- hasType = true;
83
- const child = report?.resolveChild(parser);
84
- if (i) code += "if(!hasBody){\n";
85
- if (child) code += child.begin;
86
- code += builtinParser(adapter, parser, link);
87
- if (child) code += child.end();
88
- if (i) code += "}\n";
89
- break;
90
- }
91
- }
92
- if (!hasType) {
93
- const child = report?.resolveChild("default");
94
- const begin = child ? child.begin : "";
95
- const end = child ? child.end() : "";
96
- const guard = bodyVali ? "ct" : "ct&&c.request.body";
97
- code += hasFn ? `if(!hasBody&&${guard}){${begin}c.body=await pd(c,ct)\n${end}}\n` : `if(${guard}){${begin}c.body=await pd(c,ct)\n${end}}\n`;
98
- link(adapter.default, "pd");
99
- }
100
- return hasFn ? "let hasBody=false,_bp\n" + code : code;
101
- }
102
- const isAsyncValidator = (vali) => vali?.isAsync ?? true;
103
- function applyHook(localHook, appHook, rootHook) {
10
+ function applyHook(localHook, appHook, rootHook, appHookFresh = false) {
104
11
  let hook;
105
12
  if (localHook && appHook) hook = mergeHook(cloneHook(localHook), appHook, true);
106
13
  else {
107
14
  const base = localHook ?? appHook;
108
- if (!rootHook) return base ? cloneHook(base) : base;
109
- hook = base ? cloneHook(base) : nullObject();
15
+ const ownsBase = appHookFresh && !localHook && base !== void 0;
16
+ if (!rootHook) return ownsBase ? base : base ? cloneHook(base) : base;
17
+ hook = ownsBase ? base : base ? cloneHook(base) : nullObject();
110
18
  }
111
19
  if (rootHook) mergeHook(hook, rootHook, true, true);
112
20
  return hook;
@@ -134,11 +42,16 @@ function dropHooksByOrigin(hook, skip) {
134
42
  const v = hook[key];
135
43
  if (!v) continue;
136
44
  if (Array.isArray(v)) {
137
- const kept = v.filter((fn) => {
45
+ let kept;
46
+ for (let i = 0; i < v.length; i++) {
47
+ const fn = v[i];
138
48
  const origin = fnOrigin.get(fn);
139
- return origin === void 0 || !skip.has(origin);
140
- });
141
- if (kept.length !== v.length) {
49
+ const keep = origin === void 0 || !skip.has(origin);
50
+ if (kept) {
51
+ if (keep) kept.push(fn);
52
+ } else if (!keep) kept = v.slice(0, i);
53
+ }
54
+ if (kept) {
142
55
  if (out === hook) out = { ...hook };
143
56
  out[key] = kept;
144
57
  }
@@ -152,18 +65,21 @@ function dropHooksByOrigin(hook, skip) {
152
65
  }
153
66
  return out;
154
67
  }
155
- const createInlineHandler = (map, h) => ((c) => {
156
- const r = h(c);
157
- if (r instanceof Error) throw r;
158
- if (r instanceof Promise) return r.then((v) => map(forwardError(v), c.request));
159
- return map(r, c.request);
160
- });
161
- const createInlineHandlerWithSet = (map, h) => ((c) => {
162
- const r = h(c);
163
- if (r instanceof Error) throw r;
164
- if (r instanceof Promise) return r.then((v) => map(forwardError(v), c.set, c.request));
165
- return map(r, c.set, c.request);
166
- });
68
+ function reconstructNeedsHookState(names) {
69
+ for (let i = 0; i < names.length; i++) switch (names[i]) {
70
+ case "ho":
71
+ case "tf":
72
+ case "bf":
73
+ case "af":
74
+ case "mr":
75
+ case "er":
76
+ case "ar":
77
+ case "va":
78
+ case "cc":
79
+ case "tr": return true;
80
+ }
81
+ return false;
82
+ }
167
83
  function promoteDerive(hook) {
168
84
  const derive = hook.derive;
169
85
  if (derive === void 0) return;
@@ -195,17 +111,25 @@ function composeRootHook(root, inheritedChain) {
195
111
  if (!locals) return inherited;
196
112
  return mergeHook(inherited, locals);
197
113
  }
198
- function buildNativeStaticResponse([, , handler, instance, localHook, appHook, inheritedChain], root) {
199
- if (typeof handler === "function") return;
200
- if (handler instanceof Error) return;
114
+ function buildNativeStaticResponse([, , handler, instance, localHook, appHook, inheritedChain], root, hasMapResponse) {
115
+ if (typeof handler === "function" || handler instanceof Error) return;
201
116
  const adapter = root["~config"]?.adapter ?? defaultAdapter;
202
- if (localHook) root["~applyMacro"](localHook);
203
- resolveChainMacros(root, appHook);
204
- if (inheritedChain) resolveChainMacros(root, inheritedChain);
205
- const hook = applyHook(localHook, flattenChainMemo(root, appHook), instance !== root ? composeRootHook(root, inheritedChain) : void 0);
206
- const has = (v) => Array.isArray(v) ? v.length > 0 : !!v;
207
- if (has(hook?.parse) || has(hook?.transform) || has(hook?.beforeHandle) || has(hook?.afterHandle) || has(hook?.mapResponse) || has(hook?.afterResponse) || has(hook?.trace)) return;
208
- if (hook?.body || hook?.query || hook?.params || hook?.headers || hook?.cookie || (hook?.schemas)?.length) return;
117
+ if (hasMapResponse) {
118
+ if (localHook) root["~applyMacro"](localHook);
119
+ resolveChainMacros(root, appHook);
120
+ if (inheritedChain) resolveChainMacros(root, inheritedChain);
121
+ const hook = applyHook(localHook, flattenChainMemo(root, appHook), instance !== root ? composeRootHook(root, inheritedChain) : void 0, true);
122
+ if (hook?.mapResponse) {
123
+ const context = new (createContext(root))(new Request("http://e.ly"));
124
+ context.responseValue = handler;
125
+ for (let i = 0; i < hook.mapResponse.length; i++) {
126
+ const fn = hook.mapResponse[i];
127
+ if (typeof fn !== "function") continue;
128
+ const mapped = fn(context);
129
+ if (mapped instanceof Response || mapped instanceof Promise) return mapped;
130
+ }
131
+ }
132
+ }
209
133
  const rootHeaders = root["~ext"]?.headers;
210
134
  const buildSet = () => ({ headers: rootHeaders ? Object.assign(nullObject(), rootHeaders) : nullObject() });
211
135
  if (handler instanceof Promise) return handler.then((resolved) => {
@@ -215,22 +139,26 @@ function buildNativeStaticResponse([, , handler, instance, localHook, appHook, i
215
139
  });
216
140
  if (handler instanceof Response && !rootHeaders) return handler;
217
141
  const mapped = adapter.response.map(handler, buildSet());
218
- if (mapped instanceof Response) return mapped;
219
- if (mapped instanceof Promise) return mapped;
142
+ if (mapped instanceof Response || mapped instanceof Promise) return mapped;
220
143
  }
221
144
  function toArray(name, hook) {
222
145
  if (typeof hook[name] === "function") hook[name] = [hook[name]];
223
146
  }
224
147
  function composeRouteHook(instance, localHook, appHook, inheritedChain, root) {
225
148
  const flatAppHook = appHook ? flattenChainMemo(root, appHook) : void 0;
226
- let rootHook = instance !== root ? composeRootHook(root, inheritedChain) : void 0;
227
- if (rootHook && (flatAppHook || localHook)) {
149
+ let inherited = instance !== root ? flattenChainMemo(root, inheritedChain) : void 0;
150
+ let locals = instance !== root ? flattenChain(root["~hookChain"], isLocalScope, inheritedChain) : void 0;
151
+ if ((inherited || locals) && (flatAppHook || localHook)) {
228
152
  const present = /* @__PURE__ */ new Set();
229
153
  collectHookOrigins(localHook, present);
230
154
  collectHookOrigins(flatAppHook, present);
231
- if (present.size) rootHook = dropHooksByOrigin(rootHook, present);
155
+ if (present.size) {
156
+ if (inherited) inherited = dropHooksByOrigin(inherited, present);
157
+ if (locals) locals = dropHooksByOrigin(locals, present);
158
+ }
232
159
  }
233
- let hook = applyHook(localHook, flatAppHook, rootHook);
160
+ let hook = applyHook(localHook, flatAppHook, inherited, true);
161
+ if (locals) hook = hook ? mergeHook(hook, locals, false, true) : locals;
234
162
  if (instance !== root) {
235
163
  const errors = flattenChain(instance["~hookChain"], isLocalScope)?.error;
236
164
  if (errors) {
@@ -248,6 +176,16 @@ function composeRouteHook(instance, localHook, appHook, inheritedChain, root) {
248
176
  }
249
177
  function compileHandler([_method, path, handler, instance, localHook, appHook, inheritedChain], root, precomputedStatic) {
250
178
  const adapter = root["~config"]?.adapter ?? defaultAdapter;
179
+ const method = mapMethodBack(_method);
180
+ const reconstructed = Compiled.handlers?.[method]?.[path];
181
+ if (reconstructed && !precomputedStatic && typeof handler === "function" && !root["~ext"]?.macro && !reconstructNeedsHookState(reconstructed.a)) return reconstructed.f(handler, ...resolveHandlerParams(reconstructed.a, {
182
+ parse: adapter.parse,
183
+ res: adapter.response,
184
+ hook: nullObject(),
185
+ vali: void 0,
186
+ cookieConfig: void 0,
187
+ tracers: void 0
188
+ }));
251
189
  if (root["~ext"]?.macro) {
252
190
  if (localHook) root["~applyMacro"](localHook);
253
191
  if (appHook) resolveChainMacros(root, appHook);
@@ -264,17 +202,7 @@ function compileHandler([_method, path, handler, instance, localHook, appHook, i
264
202
  toArray("afterResponse", hook);
265
203
  toArray("error", hook);
266
204
  }
267
- const method = mapMethodBack(_method);
268
- const vali = hook ? new RouteValidator(hook, {
269
- models: root["~ext"]?.models,
270
- normalize: root["~config"]?.normalize,
271
- sanitize: root["~config"]?.sanitize,
272
- schemas: hook?.schemas,
273
- aot: {
274
- method,
275
- path
276
- }
277
- }) : void 0;
205
+ const buildValidator = () => hook ? Reconstrct.validator(hook, root, method, path) : void 0;
278
206
  if (handler instanceof Error) {
279
207
  const error = handler;
280
208
  handler = () => {
@@ -296,326 +224,27 @@ function compileHandler([_method, path, handler, instance, localHook, appHook, i
296
224
  const resolve = (p) => typeof p === "string" && p in namedParsers ? namedParsers[p] : p;
297
225
  hook.parse = Array.isArray(hook.parse) ? hook.parse.map(resolve) : resolve(hook.parse);
298
226
  }
299
- const reconstructed = Compiled.handlers?.[method]?.[path];
300
227
  if (reconstructed) return reconstructed.f(handler, ...resolveHandlerParams(reconstructed.a, {
301
228
  parse: adapter.parse,
302
229
  res: adapter.response,
303
230
  hook: hook ?? nullObject(),
304
- vali,
305
- cookieConfig: reconstructed.a.includes("cc") ? compileCookieConfig(hook?.cookie, root["~config"]?.cookie) : void 0,
306
- tracers: reconstructed.a.includes("tr") ? (hook?.trace)?.map((fn) => createTracer(fn)) : void 0
231
+ vali: reconstructed.a.includes("va") ? buildValidator() : void 0,
232
+ cookieConfig: reconstructed.a.includes("cc") ? Reconstrct.cookie(hook, root) : void 0,
233
+ tracers: reconstructed.a.includes("tr") ? Reconstrct.trace(hook) : void 0
307
234
  }));
308
- const inference = sucrose(handler, hook);
309
- const params = /* @__PURE__ */ new Set();
310
- let alias = "";
311
- function link(v, key) {
312
- if (v === 0) {
313
- if (!params.has(hook)) {
314
- params.add(hook);
315
- alias += `${alias ? "," : ""}ho`;
316
- }
317
- return;
318
- }
319
- if (!params.has(v)) {
320
- params.add(v);
321
- alias += `${alias ? "," : ""}${key}`;
322
- }
323
- }
324
- if (hook && typeof hook.parse === "function") hook.parse = [hook.parse];
325
- const parseLength = Array.isArray(hook?.parse) ? hook.parse.length : 0;
326
- const parseFirst = Array.isArray(hook?.parse) ? hook.parse[0] : hook?.parse;
327
- const hasStandaloneBody = !!hook?.schemas?.some((s) => s?.body);
328
- const bodylessMethod = method === "GET" || method === "HEAD";
329
- const hasBody = !!hook?.body || hasStandaloneBody || !bodylessMethod && (parseLength > 0 || inference.body) && parseFirst !== "none";
330
- const bodyValiIsAsync = hasBody && isAsyncValidator(vali?.body);
331
- const headersValiIsAsync = vali?.headers && isAsyncValidator(vali?.headers);
332
- const paramsValiIsAsync = vali?.params && isAsyncValidator(vali?.params);
333
- const queryValiIsAsync = vali?.query && isAsyncValidator(vali?.query);
334
- const cookieValidIsAsync = vali?.cookie && isAsyncValidator(vali?.cookie);
335
- const appCookieConfig = root["~config"]?.cookie;
336
- const needsCookie = !!vali?.cookie || !!inference.cookie;
337
- const cookieConfig = needsCookie ? compileCookieConfig(hook?.cookie, appCookieConfig) : void 0;
338
- const hasCookieSign = !!cookieConfig?.hasSign;
339
- const hasErrorHook = !!hook?.error?.length;
340
- const hasAfterResponse = !!hook?.afterResponse?.length;
341
- const hasBeforeHandle = !!hook?.beforeHandle?.length;
342
- const hasAfterHandle = !!hook?.afterHandle?.length;
343
- const hasMapResponse = !!hook?.mapResponse?.length;
344
- const hasResponseValidator = !!vali?.response;
345
- const traceHandlers = hook?.trace ?? void 0;
346
- const hasTrace = !!traceHandlers?.length;
347
- const traceCount = hasTrace ? traceHandlers.length : 0;
348
- const beginTrace = (phase, total) => {
349
- if (!hasTrace) return "";
350
- let s = "";
351
- for (let i = 0; i < traceCount; i++) s += `rp${i}=tr${i}.${phase}({id:c.rid,event:'${phase}',name:'${phase}',begin:performance.now(),total:${total}})\n`;
352
- return s;
353
- };
354
- const endTrace = (errBinding) => {
355
- if (!hasTrace) return "";
356
- let s = "";
357
- for (let i = 0; i < traceCount; i++) s += `rp${i}.resolve(${errBinding ?? ""})\n`;
358
- return s;
359
- };
360
- const buildReport = (phase) => {
361
- if (!hasTrace) return;
362
- return { resolveChild(name) {
363
- let begin = "";
364
- for (let i = 0; i < traceCount; i++) begin += `rpc${i}=rp${i}.resolveChild?.shift?.()?.({id:c.rid,event:'${phase}',name:${JSON.stringify(name)},begin:performance.now()})\n`;
365
- return {
366
- begin,
367
- end(errBinding) {
368
- let close = "";
369
- for (let i = 0; i < traceCount; i++) if (errBinding) close += `if(${errBinding} instanceof Error){rpc${i}?.(${errBinding})}else{rpc${i}?.()}\n`;
370
- else close += `rpc${i}?.()\n`;
371
- return close;
372
- }
373
- };
374
- } };
375
- };
376
- const responseValiAsync = !!(vali?.response && Object.values(vali.response).find(isAsyncValidator));
377
- const handlerIsAsync = isHandleFunction && isAsyncFunction(handler);
378
- const errorHookForcesAsync = hasErrorHook && (hasAfterHandle || hasMapResponse || hasResponseValidator);
379
- const responseValiForcesAsync = hasResponseValidator && isHandleFunction && !handlerIsAsync && (mayReturnPromise(handler) || mayReturnIdentifier(handler));
380
- const afterResponseForcesAsync = hasAfterResponse && (isAsyncLifecycle(hook?.afterResponse) || hasAfterHandle || hasMapResponse || hasResponseValidator || hasErrorHook);
381
- const isAsync = hasBody || handlerIsAsync || errorHookForcesAsync || responseValiForcesAsync || afterResponseForcesAsync || hasTrace || hasCookieSign || responseValiAsync || hook && (!!isAsyncLifecycle(hook?.afterHandle) || !!isAsyncLifecycle(hook?.beforeHandle) || !!isAsyncLifecycle(hook?.transform) || !!isAsyncLifecycle(hook?.mapResponse) || !!isAsyncLifecycle(hook?.error) || bodyValiIsAsync || headersValiIsAsync || paramsValiIsAsync || queryValiIsAsync || cookieValidIsAsync);
382
- const callHandlerSyncOnAsync = isAsync && isHandleFunction && !handlerIsAsync;
383
- const syncErrorHook = hasErrorHook && !isAsync && !hasTrace;
384
- const syncAfterResponse = hasAfterResponse && !isAsync && !hasTrace && !hasErrorHook;
385
- const callHandler = isHandleFunction ? callHandlerSyncOnAsync ? `_r=h(c)\nif(_r instanceof Promise)_r=await _r\n` : `_r=${isAsync ? "await " : ""}h(c)\n` : isStaticResponse ? `_r=h.clone()\n` : isPromiseHandler ? `_r=h.then(cr)\n` : `_r=h\n`;
386
- let code = `${isAsync ? "async " : ""}function route(c){\n`;
387
- if ((hasAfterResponse || hasTrace) && !syncAfterResponse) code += "let _stl\n";
388
- if (hasCookieSign) code += "let _sg\n";
389
- if (hasTrace) {
390
- link(traceHandlers.map((fn) => createTracer(fn)), "tr");
391
- link(requestId, "rid");
392
- code += `c.rid??=rid()\n`;
393
- for (let i = 0; i < traceCount; i++) code += `let rp${i},rpc${i},_hr${i};\n`;
394
- code += `c.trace??=[`;
395
- for (let i = 0; i < traceCount; i++) code += (i ? "," : "") + `tr[${i}](c)`;
396
- code += `]\n`;
397
- for (let i = 0; i < traceCount; i++) code += `const tr${i}=c.trace[${i}]\n`;
398
- code += `let _trs\n`;
399
- }
400
- let inlineUnsafe = false;
401
- if ((hasTrace || inference.route) && isDynamicRegex.test(path)) {
402
- code += `c.route=${JSON.stringify(path)}\n`;
403
- inlineUnsafe = true;
404
- }
405
- const head = code;
406
- code = "";
407
- if (hasErrorHook || hasTrace) code += "try{\n";
408
- const hasHeaders = inference.headers || !!vali?.headers;
409
- if (inference.query || vali?.query) {
410
- const parseArgs = getQueryParseArgs((vali?.query)?.schema);
411
- code += `c.query=pq(c.request.url,c.qi${parseArgs})\n`;
412
- link(parseQueryFromURL, "pq");
413
- }
414
- if (hasHeaders) {
415
- if (captureHeaderShorthand === void 0 && Capture.isCapturing()) code += `c.headers=c.request.headers.toJSON?.()??Object.fromEntries(c.request.headers)\n`;
416
- else code += `c.headers=${captureHeaderShorthand ?? hasHeaderShorthand ? "c.request.headers.toJSON()" : "Object.fromEntries(c.request.headers)"}\n`;
417
- inlineUnsafe = true;
418
- }
419
- if (hasBody) {
420
- const parseLen = Array.isArray(hook?.parse) ? hook.parse.length : 0;
421
- if (hasTrace) code += beginTrace("parse", parseLen);
422
- const parseCode = parse(adapter.parse, hook?.parse, vali?.body, hasHeaders, link, buildReport("parse"));
423
- link(ParseError, "pe");
424
- code += "try{\n" + parseCode + "}catch(e){throw new pe(e)}\n";
425
- if (hasTrace) code += endTrace();
426
- } else if (hasTrace) code += beginTrace("parse", 0) + endTrace();
427
- if (hook?.transform?.length || hasTrace) {
428
- const transformLen = hook?.transform?.length ?? 0;
429
- code += beginTrace("transform", transformLen);
430
- if (transformLen) {
431
- link(hook.transform, "tf");
432
- code += mapTransform(hook.transform, [buildReport("transform")]);
433
- }
434
- code += endTrace();
435
- }
436
- if (vali?.body) {
437
- link(vali, "va");
438
- code += `c.body=${bodyValiIsAsync ? "await " : ""}va.body.From(c.body,'body')\n`;
439
- }
440
- if (vali?.headers) {
441
- link(vali, "va");
442
- code += `c.headers=${headersValiIsAsync ? "await " : ""}va.headers.From(c.headers,'headers')\n`;
443
- }
444
- if (vali?.params) {
445
- link(vali, "va");
446
- code += `c.params=${paramsValiIsAsync ? "await " : ""}va.params.From(c.params,'params')\n`;
447
- }
448
- if (vali?.query) {
449
- link(vali, "va");
450
- code += `c.query=${queryValiIsAsync ? "await " : ""}va.query.From(c.query,'query')\n`;
451
- }
452
- if (cookieConfig) {
453
- link(buildCookieJar, "bcj");
454
- link(cookieConfig, "cc");
455
- if (!hasCookieSign && !cookieValidIsAsync) {
456
- link(parseCookieRawSync, "pcrs");
457
- code += `let _ck=pcrs(c.request.headers.get('cookie'),cc)\n`;
458
- } else {
459
- link(parseCookieRaw, "pcr");
460
- code += `let _ck=await pcr(c.request.headers.get('cookie'),cc)\n`;
461
- }
462
- if (vali?.cookie) {
463
- link(vali, "va");
464
- const cookieIsOptional = !!(hook?.cookie)?.["~optional"];
465
- const validateExpr = `_ck=${cookieValidIsAsync ? "await " : ""}va.cookie.From(_ck,'cookie')\n`;
466
- if (cookieIsOptional) code += `if(Object.keys(_ck).length){${validateExpr}}\n`;
467
- else code += validateExpr;
468
- }
469
- code += `c.cookie=bcj(c.set,_ck,cc)\n`;
470
- }
471
- const hasSet = inference.cookie || inference.set || !!root["~ext"]?.["headers"] || needsCookie || hasAfterResponse || hasErrorHook || hasResponseValidator || hasTrace;
472
- const res = adapter.response;
473
- const map = hasSet ? link(res.map, "rm") ?? "rm" : link(res.compact ?? res.map, "rc") ?? "rc";
474
- if (isPromiseHandler) link(cloneResponse, "cr");
475
- const handleInstruction = isHandleFunction ? "h(c)" : isStaticResponse ? "h.clone()" : isPromiseHandler ? "h.then(cr)" : "h";
476
- const mapReturn = hasSet ? `rm(${handleInstruction},c.set,c.request)\n` : `rc(${handleInstruction},c.request)\n`;
477
- if (hasAfterResponse) link(hook.afterResponse, "ar");
478
- const drainTraceStream = hasTrace ? `let _ser\nif(_trs){try{for await(const v of _trs){}}catch(_te){_ser=_te}}\n` : "";
479
- const resolveHandlePostDrain = hasTrace ? (() => {
480
- let s = "";
481
- for (let i = 0; i < traceCount; i++) s += `_hr${i}?.resolve(_ser)\n`;
482
- return s;
483
- })() : "";
484
- const setImmediateFn = Capture.isCapturing() ? ";(typeof setImmediate==='function'?setImmediate:(f)=>Promise.resolve().then(f))" : typeof setImmediate === "function" ? "setImmediate" : "Promise.resolve().then";
485
- const scheduleAfterResponse = hasAfterResponse || hasTrace ? `c._arf=true\n${setImmediateFn}(async()=>{if(_stl)for await(const v of _stl){}\n` + drainTraceStream + resolveHandlePostDrain + beginTrace("afterResponse", hook?.afterResponse?.length ?? 0) + (hasAfterResponse ? mapAfterResponse(hook.afterResponse, [buildReport("afterResponse")]) : "") + endTrace() + `})\n` : "";
486
- const dedupSchedule = !!scheduleAfterResponse && (hasErrorHook || hasTrace) && !syncAfterResponse && !syncErrorHook;
487
- const scheduleDecl = dedupSchedule ? `function _sc(){\n${scheduleAfterResponse}}\n` : "";
488
- const schedule = dedupSchedule ? `_sc()\n` : scheduleAfterResponse;
489
- const signPrefix = hasCookieSign ? `_sg=scv(c.set.cookie,cc)\nif(_sg)await _sg\n` : "";
490
- if (hasCookieSign) link(signCookieValues, "scv");
491
- let factoryHelpers = "";
492
- if (hasBeforeHandle || hasAfterHandle || hasMapResponse || hasAfterResponse || hasResponseValidator || hasCookieSign || hasTrace) {
493
- code += `let _r,tmp\n`;
494
- if (hasBeforeHandle || hasTrace) {
495
- const bfLen = hook?.beforeHandle?.length ?? 0;
496
- code += beginTrace("beforeHandle", bfLen);
497
- if (hasBeforeHandle) {
498
- link(hook.beforeHandle, "bf");
499
- const rootDerive = root["~derive"];
500
- const instanceDerive = instance?.["~derive"];
501
- const deriveSet = rootDerive && instanceDerive ? { has: (fn) => rootDerive.has(fn) || instanceDerive.has(fn) } : rootDerive ?? instanceDerive;
502
- code += mapBeforeHandle(hook.beforeHandle, deriveSet, link, buildReport("beforeHandle"));
503
- }
504
- code += endTrace();
505
- }
506
- if (hasAfterResponse || hasTrace) link(tee, "tee");
507
- const teeConsumers = (hasAfterResponse ? 1 : 0) + (hasTrace ? 1 : 0);
508
- const teeCount = teeConsumers + 1;
509
- const teeBlock = teeConsumers > 0 && !syncAfterResponse ? `if(_r&&(_r[Symbol.iterator]||_r[Symbol.asyncIterator])&&typeof _r.next==='function'){\nconst _s=await tee(_r,${teeCount})\n_r=_s[0]\n` + (hasAfterResponse ? `_stl=_s[1]\n` : "") + (hasTrace ? `_trs=_s[${1 + (hasAfterResponse ? 1 : 0)}]\n` : "") + `}\n` : "";
510
- if (hasTrace) {
511
- const handleName = handler?.name && typeof handler.name === "string" ? handler.name : "anonymous";
512
- code += beginTrace("handle", 1);
513
- const handleChild = buildReport("handle").resolveChild(handleName);
514
- code += handleChild.begin;
515
- if (hasBeforeHandle) code += `if(_r===undefined){\n${callHandler}${teeBlock}}\n`;
516
- else code += callHandler + teeBlock;
517
- code += handleChild.end("_r");
518
- code += `if(_trs){\n`;
519
- for (let i = 0; i < traceCount; i++) code += `_hr${i}=rp${i};\n`;
520
- code += `}else{\n`;
521
- code += endTrace();
522
- code += `}\n`;
523
- } else if (hasBeforeHandle) code += `if(_r===undefined){\n${callHandler}${teeBlock}}\n`;
524
- else code += callHandler + teeBlock;
525
- if (syncAfterResponse) {
526
- link(forwardError, "fe");
527
- factoryHelpers += `function _fin(c,_r){
528
- if(_r instanceof Error)throw _r
529
- if(_r&&(_r[Symbol.iterator]||_r[Symbol.asyncIterator])&&typeof _r.next==='function'){
530
- return tee(_r,${teeCount}).then((_s)=>_fin2(c,_s[0],_s[1]))\n}\nreturn _fin2(c,_r,undefined)\n}\nfunction _fin2(c,_r,_stl){\nc.responseValue=_r\n` + scheduleAfterResponse + `return ${hasSet ? `${map}(_r,c.set,c.request)` : `${map}(_r,c.request)`}\n}\n`;
531
- code += "if(_r instanceof Promise)return _r.then(fe).then((_v)=>_fin(c,_v))\nreturn _fin(c,_r)\n";
532
- } else {
533
- code += `if(_r instanceof Error)throw _r\n`;
534
- if (!isAsync) {
535
- link(forwardError, "fe");
536
- code += `else if(_r instanceof Promise)_r=_r.then(fe)\n`;
537
- }
538
- if (hasAfterHandle || hasMapResponse || hasAfterResponse || hasTrace) code += `c.responseValue=_r\n`;
539
- if (hasAfterHandle || hasTrace) {
540
- const afLen = hook?.afterHandle?.length ?? 0;
541
- code += beginTrace("afterHandle", afLen);
542
- if (hasAfterHandle) {
543
- link(hook.afterHandle, "af");
544
- code += mapAfterHandle(hook.afterHandle, buildReport("afterHandle"));
545
- }
546
- code += endTrace();
547
- }
548
- if (hasMapResponse || hasTrace) {
549
- const mrLen = hook?.mapResponse?.length ?? 0;
550
- code += beginTrace("mapResponse", mrLen);
551
- if (hasMapResponse) {
552
- link(hook.mapResponse, "mr");
553
- code += mapMapResponse(hook.mapResponse, buildReport("mapResponse"));
554
- }
555
- code += endTrace();
556
- }
557
- if (hasResponseValidator) {
558
- link(vali, "va");
559
- link(ElysiaStatus, "es");
560
- const awaitStr = responseValiAsync ? "await " : "";
561
- code += `if(_r instanceof es){
562
- const _vr=va.response[_r.code]
563
- if(_vr)_r.response=${awaitStr}_vr.EncodeFrom(_r.response,'response')\n}else if(!(_r instanceof Response)&&!(_r instanceof ReadableStream)&&typeof _r?.next!=='function'){\nconst _vr=va.response[c.set.status??200]\nif(_vr)_r=${awaitStr}_vr.EncodeFrom(_r,'response')\n}\n`;
564
- }
565
- code += schedule;
566
- code += signPrefix;
567
- const finalMap = hasSet ? `${map}(_r,c.set,c.request)` : `${map}(_r,c.request)`;
568
- if (syncErrorHook) code += `if(_r instanceof Promise)return ${finalMap}.catch((_e)=>_ce(_e,c))\n`;
569
- code += `return ${finalMap}\n`;
570
- }
571
- } else if (isHandleFunction) {
572
- if (!isAsync) link(forwardError, "fe");
573
- const mapArgs = hasSet ? "c.set,c.request" : "c.request";
574
- code += (callHandlerSyncOnAsync ? `let _r=h(c)\nif(_r instanceof Promise)_r=await _r\n` : `let _r=${isAsync ? "await " : ""}h(c)\n`) + `if(_r instanceof Error)throw _r\n` + (isAsync ? `return ${map}(_r,${mapArgs})\n` : syncErrorHook ? `if(_r instanceof Promise)return ${map}(_r.then(fe),${mapArgs}).catch((_e)=>_ce(_e,c))\nreturn ${map}(_r,${mapArgs})\n` : `if(_r instanceof Promise)_r=_r.then(fe)\nreturn ${map}(_r,${mapArgs})\n`);
575
- } else code += `return ${mapReturn}`;
576
- if (hasErrorHook || hasTrace) {
577
- let body = "";
578
- if (hasTrace) {
579
- for (let i = 0; i < traceCount; i++) body += `rp${i}?.resolve(e);rpc${i}?.(e)\n`;
580
- body += beginTrace("error", hook?.error?.length ?? 0);
581
- }
582
- if (hasErrorHook) {
583
- link(hook.error, "er");
584
- link(ElysiaStatus, "es");
585
- const allowUnsafeDetail = !!root["~config"]?.allowUnsafeValidationDetails;
586
- if (allowUnsafeDetail) link(ValidationError, "verr");
587
- body += `c.error=e\n` + (allowUnsafeDetail ? `if(e instanceof verr)e.allowUnsafeValidationDetails=true\n` : ``) + `if(e?.status)c.set.status=e.status
588
- else if(c.set.status===undefined||c.set.status===200)c.set.status=500
589
- let _r${hasMapResponse ? ",tmp" : ""}\n` + mapError(hook.error, [
590
- map,
591
- link,
592
- res.map,
593
- (hasMapResponse ? `c.responseValue=_r\n` + mapMapResponse(hook.mapResponse, void 0) : "") + endTrace() + schedule,
594
- signPrefix
595
- ]) + endTrace() + schedule + `if(typeof e?.toResponse==='function'){const _er=e.toResponse();if(_er instanceof Response){${signPrefix}return ${map}(_er,c.set,c.request)}}\nif(e instanceof es){${signPrefix}return ${map}(e,c.set,c.request)}\nif(e?.status){${signPrefix}return ${map}(e?.response??e?.message??'',c.set,c.request)}\nc.set.status=500\n` + signPrefix + `return ${map}(e?.message!=null?e.message:'Internal Server Error',c.set,c.request)\n`;
596
- } else {
597
- body += endTrace() + schedule;
598
- body += `throw e\n`;
599
- }
600
- if (syncErrorHook) {
601
- factoryHelpers += `function _ce(e,c){\n${body}}\n`;
602
- code += `}catch(e){return _ce(e,c)}\n`;
603
- } else code += `}catch(e){\n${body}}\n`;
604
- }
605
- code += "}";
606
- code = head + scheduleDecl + code;
607
- if (factoryHelpers) code = `(function(){\n${factoryHelpers}return ${code}})()`;
608
- if (!hasTrace && isHandleFunction && !inlineUnsafe) {
609
- if (alias === "rc" || !isAsync && !syncErrorHook && alias === "rc,fe") return createInlineHandler(res.compact ?? res.map, handler);
610
- else if (alias === "rm" || !isAsync && !syncErrorHook && alias === "rm,fe") return createInlineHandlerWithSet(res.map, handler);
611
- }
612
- if (!precomputedStatic) Capture.handler({
235
+ return compileHandlerJit({
613
236
  method,
614
237
  path,
615
- alias,
616
- code
238
+ handler,
239
+ instance,
240
+ root,
241
+ hook,
242
+ adapter,
243
+ buildValidator,
244
+ isHandleFunction,
245
+ isStaticResponse,
246
+ isPromiseHandler
617
247
  });
618
- return new Function("h", alias, `return ${code}`)(handler, ...params);
619
248
  }
620
249
 
621
250
  //#endregion
@@ -0,0 +1,35 @@
1
+ import { AnyLocalHook, CompiledHandler } from "../../types.js";
2
+ import { AnyElysia } from "../../base.js";
3
+ import { ElysiaAdapter } from "../../adapter/index.js";
4
+ import { RouteValidator } from "../../validator/route.js";
5
+
6
+ //#region src/compile/handler/jit.d.ts
7
+ declare const setCaptureHeaderShorthand: (value: boolean | undefined) => void;
8
+ interface CompileHandlerJitOptions {
9
+ method: string;
10
+ path: string;
11
+ handler: unknown;
12
+ instance: AnyElysia;
13
+ root: AnyElysia;
14
+ hook: AnyLocalHook | undefined;
15
+ adapter: ElysiaAdapter;
16
+ buildValidator: () => RouteValidator<any> | undefined;
17
+ isHandleFunction: boolean;
18
+ isStaticResponse: boolean;
19
+ isPromiseHandler: boolean;
20
+ }
21
+ declare function compileHandlerJit({
22
+ method,
23
+ path,
24
+ handler,
25
+ instance,
26
+ root,
27
+ hook,
28
+ adapter,
29
+ buildValidator,
30
+ isHandleFunction,
31
+ isStaticResponse,
32
+ isPromiseHandler
33
+ }: CompileHandlerJitOptions): CompiledHandler;
34
+ //#endregion
35
+ export { CompileHandlerJitOptions, compileHandlerJit, setCaptureHeaderShorthand };