elysia 2.0.0-exp.26 → 2.0.0-exp.27

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/base.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { ElysiaStatus } from "./error.js";
2
2
  import { TraceHandler } from "./trace.js";
3
- import { AnySchema } from "./type/types.js";
4
3
  import { ListenCallback, Serve, Server } from "./universal/server.js";
5
- import { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, BodyHandler, CompiledHandler, CreateEden, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, DocumentDecoration, ElysiaConfig, ElysiaHandlerToResponseSchemaAmbiguous, EphemeralType, ErrorDefinitionEntry, ErrorHandler, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, GlobalHookReturn, GracefulHandler, GuardLocalHook, HTTPMethod, HookContextSchema, HookContextSingleton, InlineHandler, InlineHandlerNonMacro, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObjectSchema, JoinPath, LocalHook, LocalHookReturn, Macro, MacroSchemaChannel, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, NonResolvableMacroKey, ObjectMacroDefs, OptionalHandler, PluginHookReturn, PreHandler, Prettify, PublicRoute, ResolveRouteErrors, RouteBase, SingletonBase, TransformHandler, UnionResponseStatus, UnwrapRoute, WrapFn } from "./types.js";
4
+ import { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, BodyHandler, CompiledHandler, CreateEden, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, DocumentDecoration, ElysiaConfig, ElysiaHandlerToResponseSchemaAmbiguous, EphemeralType, ErrorDefinitionEntry, ErrorHandler, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, GlobalHookReturn, GracefulHandler, GuardHookSingleton, GuardLocalHook, HTTPMethod, HookContextSchema, HookContextSingleton, InlineHandler, InlineHandlerNonMacro, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObjectSchema, JoinPath, LocalHook, LocalHookReturn, Macro, MacroSchemaChannel, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, NonResolvableMacroKey, ObjectMacroDefs, OptionalHandler, PluginHookReturn, PreHandler, Prettify, PublicRoute, ResolveRouteErrors, RouteBase, SingletonBase, TransformHandler, UnionResponseStatus, UnwrapRoute, WrapFn } from "./types.js";
5
+ import { AnySchema } from "./type/types.js";
6
6
  import { ChainNode } from "./utils.js";
7
7
  import { Context, ErrorContext, LifecycleContext } from "./context.js";
8
8
  import { WSHandlerResponse, WSLocalHook, WSMessageHandler } from "./ws/types.js";
@@ -16,9 +16,6 @@ interface StaticMapAliases {
16
16
  paths: string[];
17
17
  head: boolean;
18
18
  }
19
- type GuardHookSingleton<Singleton extends SingletonBase, Ephemeral extends EphemeralType, Volatile extends EphemeralType, MacroContext> = Singleton & {
20
- derive: Ephemeral['derive'] & Volatile['derive'] & MacroContext['resolve'];
21
- };
22
19
  declare class Elysia<const in out BasePath extends string = '', const in out Scope extends EventScope = 'local', const in out Singleton extends SingletonBase = DefaultSingleton, const in out Definitions extends DefinitionBase = {
23
20
  typebox: {};
24
21
  error: [];
@@ -801,13 +798,6 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
801
798
  /**
802
799
  * Force all route handlers to compile immediately (sets `precompile: true`
803
800
  * on the config and triggers a fresh build of the fetch handler).
804
- *
805
- * @remarks
806
- * **Memory trade-off (bench-memory-1):** each compiled route retains ~4.8 KB
807
- * (no schema) to ~6.6 KB (validated body) of memory (JSC compiled-function
808
- * representation + closure scope); 1 000 validated routes ≈ 6.6 MB. Without
809
- * this call, routes compile lazily on first request, spreading that cost over
810
- * time. Use the AOT build plugin for the lowest cold-start footprint.
811
801
  */
812
802
  compile(): this;
813
803
  handler(index: number, immediate?: boolean | undefined, route?: InternalRoute, precomputedStatic?: Response, aliases?: StaticMapAliases): CompiledHandler;
@@ -838,28 +828,6 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
838
828
  * draining gracefully.
839
829
  */
840
830
  stop(closeActiveConnections?: boolean): Promise<void> | void;
841
- /** @deprecated renamed to `.error()` in Elysia 2 */
842
- onError: 'onError was renamed to .error() in Elysia 2';
843
- /** @deprecated renamed to `.request()` in Elysia 2 */
844
- onRequest: 'onRequest was renamed to .request() in Elysia 2';
845
- /** @deprecated renamed to `.parse()` in Elysia 2 */
846
- onParse: 'onParse was renamed to .parse() in Elysia 2';
847
- /** @deprecated renamed to `.transform()` in Elysia 2 */
848
- onTransform: 'onTransform was renamed to .transform() in Elysia 2';
849
- /** @deprecated renamed to `.beforeHandle()` in Elysia 2 */
850
- onBeforeHandle: 'onBeforeHandle was renamed to .beforeHandle() in Elysia 2';
851
- /** @deprecated renamed to `.afterHandle()` in Elysia 2 */
852
- onAfterHandle: 'onAfterHandle was renamed to .afterHandle() in Elysia 2';
853
- /** @deprecated renamed to `.afterResponse()` in Elysia 2 */
854
- onAfterResponse: 'onAfterResponse was renamed to .afterResponse() in Elysia 2';
855
- /** @deprecated renamed to `.mapResponse()` in Elysia 2 */
856
- onResponse: 'onResponse was renamed to .mapResponse() in Elysia 2';
857
- /** @deprecated removed in Elysia 2 — use the `listen(port, callback)` callback */
858
- onStart: 'onStart was removed in Elysia 2 — use the listen(port, callback) callback';
859
- /** @deprecated removed in Elysia 2 — use `.cleanup()` */
860
- onStop: 'onStop was removed in Elysia 2 — use .cleanup()';
861
- /** @deprecated removed in Elysia 2 — use `.derive()` */
862
- resolve: 'resolve was removed in Elysia 2 — use .derive() instead';
863
831
  }
864
832
  //#endregion
865
833
  export { AnyElysia, Elysia };
package/dist/base.js CHANGED
@@ -15,22 +15,6 @@ memoirist = require_runtime.__toESM(memoirist);
15
15
 
16
16
  //#region src/base.ts
17
17
  const useNodesBuffer = [];
18
- const macroSeedRefIds = /* @__PURE__ */ new WeakMap();
19
- let macroSeedRefCounter = 0;
20
- function macroSeedRefId(ref) {
21
- let id = macroSeedRefIds.get(ref);
22
- if (id === void 0) macroSeedRefIds.set(ref, id = ++macroSeedRefCounter);
23
- return id;
24
- }
25
- function macroSeedReplacer(_key, value) {
26
- switch (typeof value) {
27
- case "function": return "\0fn:" + macroSeedRefId(value);
28
- case "bigint": return "\0bigint:" + value.toString();
29
- case "symbol": return "\0sym:" + String(value);
30
- case "undefined": return "\0undefined";
31
- default: return value;
32
- }
33
- }
34
18
  var Elysia = class Elysia {
35
19
  #hasPlugin;
36
20
  #hasGlobal;
@@ -415,7 +399,7 @@ var Elysia = class Elysia {
415
399
  for (const key in macro) {
416
400
  if (typeof macro[key] === "object") macro[key] = require_utils.hookToGuard(macro[key]);
417
401
  if (this.#hash !== void 0 && !require_utils.macroOrigin.has(macro[key])) require_utils.macroOrigin.set(macro[key], this.#hash);
418
- if (baseline?.has(key) && key in m && m[key] !== macro[key]) throw new Error(`Macro "${key}" is defined by more than one plugin. Rename one of them (macro names must be unique across composed plugins), or give the plugin a \`name\` so repeated instances deduplicate.`);
402
+ if (baseline?.has(key) && key in m && m[key] !== macro[key]) throw new Error(`[Elysia] Macro "${key}" can be only define once`);
419
403
  }
420
404
  Object.assign(m, macro);
421
405
  this.#cachedRoutes = void 0;
@@ -440,7 +424,7 @@ var Elysia = class Elysia {
440
424
  let seedKey;
441
425
  if (seedSource === null || seedSource === void 0 || seedType !== "object") seedKey = key + "\0" + seedType + "\0" + String(seedSource);
442
426
  else try {
443
- seedKey = key + "\0object\0" + JSON.stringify(seedSource, macroSeedReplacer);
427
+ seedKey = key + "\0object\0" + JSON.stringify(seedSource, require_utils.serializeMacroSeed);
444
428
  } catch {
445
429
  throw new Error(`[Elysia] macro "${key}" received a circular seed value; pass a primitive \`seed\` to dedup it.`);
446
430
  }
@@ -530,7 +514,7 @@ var Elysia = class Elysia {
530
514
  return this.#useAsync(result.then((value) => {
531
515
  const after = this["~ext"]?.macro;
532
516
  if (after) {
533
- for (const [k, def] of Object.entries(after)) if (beforeMacro.get(k) !== def) throw new Error(`Macro ${k} was added by an async plugin which Elysia can't ensure the soundness. Please register macro in the plugin synchronously instead of async.`);
517
+ for (const [k, def] of Object.entries(after)) if (beforeMacro.get(k) !== def) throw new Error(`Macro ${k} can only run in sync plugin`);
534
518
  }
535
519
  return value;
536
520
  }));
@@ -577,7 +561,7 @@ var Elysia = class Elysia {
577
561
  const origin = require_utils.macroOrigin.get(existing);
578
562
  if (origin !== void 0 && origin === require_utils.macroOrigin.get(incoming)) continue;
579
563
  if (addedByThisCall) for (const h of addedByThisCall) this.#childrenHash.delete(h);
580
- throw new Error(`Macro "${macroName}" is defined by more than one plugin.Rename one of them (macro names must be unique across composed plugins), or give the plugin a \`name\` so repeated instances deduplicate.`);
564
+ throw new Error(`[Elysia] Macro "${macroName}" can be only define once`);
581
565
  }
582
566
  if (app.#history) {
583
567
  if (app["~hasWS"]) this["~hasWS"] = true;
@@ -783,7 +767,6 @@ var Elysia = class Elysia {
783
767
  this.#buildRouter();
784
768
  }
785
769
  #add(method, path, fn, hook) {
786
- if (hook !== void 0 && (typeof hook !== "object" || hook === null)) throw new Error(`Elysia 2 route signature is (path, hook, handler) — received ${typeof hook} in the hook position for "${method} ${path}". Did you use the Elysia 1 order (path, handler, hook)?`);
787
770
  if (this["~Prefix"]) path = require_utils.joinPath(this["~Prefix"], path);
788
771
  else if (path && path.charCodeAt(0) !== 47) path = "/" + path;
789
772
  const appHook = this["~hookChain"];
@@ -946,13 +929,6 @@ var Elysia = class Elysia {
946
929
  /**
947
930
  * Force all route handlers to compile immediately (sets `precompile: true`
948
931
  * on the config and triggers a fresh build of the fetch handler).
949
- *
950
- * @remarks
951
- * **Memory trade-off (bench-memory-1):** each compiled route retains ~4.8 KB
952
- * (no schema) to ~6.6 KB (validated body) of memory (JSC compiled-function
953
- * representation + closure scope); 1 000 validated routes ≈ 6.6 MB. Without
954
- * this call, routes compile lazily on first request, spreading that cost over
955
- * time. Use the AOT build plugin for the lowest cold-start footprint.
956
932
  */
957
933
  compile() {
958
934
  this["~config"] ??= require_utils.nullObject();
@@ -1032,13 +1008,13 @@ var Elysia = class Elysia {
1032
1008
  if (!require_utils.schemaProperties.has(key)) continue;
1033
1009
  const v = hook[key];
1034
1010
  if (typeof v === "string") {
1035
- if (!models || !(v in models)) throw new Error(`[Elysia] Unknown model reference "${v}" for ${key} on route ${method} ${path}. Register it with .model('${v}', ...) before listen()/compile().`);
1011
+ if (!models || !(v in models)) throw new Error(`[Elysia] Unknown model reference "${v}" for ${key} on route ${method} ${path}.`);
1036
1012
  } else if (key === "response" && v && typeof v === "object") {
1037
1013
  const record = v;
1038
1014
  if ("~kind" in record || "~elyAcl" in record || "~standard" in record) continue;
1039
1015
  for (const status in record) {
1040
1016
  const r = record[status];
1041
- if (typeof r === "string" && (!models || !(r in models))) throw new Error(`[Elysia] Unknown model reference "${r}" for response ${status} on route ${method} ${path}. Register it with .model('${r}', ...) before listen()/compile().`);
1017
+ if (typeof r === "string" && (!models || !(r in models))) throw new Error(`[Elysia] Unknown model reference "${r}" for response ${status} on route ${method} ${path}.`);
1042
1018
  }
1043
1019
  }
1044
1020
  }
@@ -1123,7 +1099,7 @@ var Elysia = class Elysia {
1123
1099
  const existing = this["~config"].websocket;
1124
1100
  if (existing && require_universal_constants.isBun) {
1125
1101
  for (const key in options) if (key in existing && existing[key] !== options[key]) {
1126
- console.warn(`[Elysia] Conflicting per-route WebSocket option '${key}'\nBun uses one global WebSocket config per server, so per-route values are not enforced (the last-registered route wins).`);
1102
+ console.warn(`[Elysia] Conflicting per-route WebSocket option '${key}'\nBun uses one global WebSocket config per server, per-route values are not enforced (the last-registered route wins).`);
1127
1103
  console.warn((/* @__PURE__ */ new Error()).stack);
1128
1104
  }
1129
1105
  Object.assign(existing, options);
@@ -1250,26 +1226,6 @@ var Elysia = class Elysia {
1250
1226
  return r;
1251
1227
  }
1252
1228
  };
1253
- for (const [old, hint] of [
1254
- ["onError", "use .error() instead"],
1255
- ["onRequest", "use .request() instead"],
1256
- ["onParse", "use .parse() instead"],
1257
- ["onTransform", "use .transform() instead"],
1258
- ["onBeforeHandle", "use .beforeHandle() instead"],
1259
- ["onAfterHandle", "use .afterHandle() instead"],
1260
- ["onAfterResponse", "use .afterResponse() instead"],
1261
- ["onResponse", "use .mapResponse() instead"],
1262
- ["onStart", "use the listen(port, callback) callback instead"],
1263
- ["onStop", "use .cleanup() instead"],
1264
- ["resolve", "use .derive() instead"]
1265
- ]) Object.defineProperty(Elysia.prototype, old, {
1266
- value: function removed() {
1267
- throw new Error(`.${old}() was removed in Elysia 2 — ${hint}`);
1268
- },
1269
- writable: true,
1270
- enumerable: false,
1271
- configurable: true
1272
- });
1273
1229
 
1274
1230
  //#endregion
1275
1231
  exports.Elysia = Elysia;
package/dist/base.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { isBun } from "./universal/constants.mjs";
2
2
  import { MethodMap, isDynamicRegex, needEncodeRegex } from "./constants.mjs";
3
- import { clonePlainDecorators, clonePlainDeep, coalesceStandaloneSchemas, createErrorEventHandler, eventProperties, fnOrigin, fnv1a, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isEmpty, isNotEmpty, isRecordNumber, joinPath, macroOrigin, mapMethodBack, mergeDeep, mergeResponse, nullObject, pushField, schemaProperties } from "./utils.mjs";
3
+ import { clonePlainDecorators, clonePlainDeep, coalesceStandaloneSchemas, createErrorEventHandler, eventProperties, fnOrigin, fnv1a, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isEmpty, isNotEmpty, isRecordNumber, joinPath, macroOrigin, mapMethodBack, mergeDeep, mergeResponse, nullObject, pushField, schemaProperties, serializeMacroSeed } from "./utils.mjs";
4
4
  import { Ref } from "./type/bridge.mjs";
5
5
  import { isProduction } from "./error.mjs";
6
6
  import { Capture } from "./compile/aot.mjs";
@@ -12,22 +12,6 @@ import Memoirist from "memoirist";
12
12
 
13
13
  //#region src/base.ts
14
14
  const useNodesBuffer = [];
15
- const macroSeedRefIds = /* @__PURE__ */ new WeakMap();
16
- let macroSeedRefCounter = 0;
17
- function macroSeedRefId(ref) {
18
- let id = macroSeedRefIds.get(ref);
19
- if (id === void 0) macroSeedRefIds.set(ref, id = ++macroSeedRefCounter);
20
- return id;
21
- }
22
- function macroSeedReplacer(_key, value) {
23
- switch (typeof value) {
24
- case "function": return "\0fn:" + macroSeedRefId(value);
25
- case "bigint": return "\0bigint:" + value.toString();
26
- case "symbol": return "\0sym:" + String(value);
27
- case "undefined": return "\0undefined";
28
- default: return value;
29
- }
30
- }
31
15
  var Elysia = class Elysia {
32
16
  #hasPlugin;
33
17
  #hasGlobal;
@@ -412,7 +396,7 @@ var Elysia = class Elysia {
412
396
  for (const key in macro) {
413
397
  if (typeof macro[key] === "object") macro[key] = hookToGuard(macro[key]);
414
398
  if (this.#hash !== void 0 && !macroOrigin.has(macro[key])) macroOrigin.set(macro[key], this.#hash);
415
- if (baseline?.has(key) && key in m && m[key] !== macro[key]) throw new Error(`Macro "${key}" is defined by more than one plugin. Rename one of them (macro names must be unique across composed plugins), or give the plugin a \`name\` so repeated instances deduplicate.`);
399
+ if (baseline?.has(key) && key in m && m[key] !== macro[key]) throw new Error(`[Elysia] Macro "${key}" can be only define once`);
416
400
  }
417
401
  Object.assign(m, macro);
418
402
  this.#cachedRoutes = void 0;
@@ -437,7 +421,7 @@ var Elysia = class Elysia {
437
421
  let seedKey;
438
422
  if (seedSource === null || seedSource === void 0 || seedType !== "object") seedKey = key + "\0" + seedType + "\0" + String(seedSource);
439
423
  else try {
440
- seedKey = key + "\0object\0" + JSON.stringify(seedSource, macroSeedReplacer);
424
+ seedKey = key + "\0object\0" + JSON.stringify(seedSource, serializeMacroSeed);
441
425
  } catch {
442
426
  throw new Error(`[Elysia] macro "${key}" received a circular seed value; pass a primitive \`seed\` to dedup it.`);
443
427
  }
@@ -527,7 +511,7 @@ var Elysia = class Elysia {
527
511
  return this.#useAsync(result.then((value) => {
528
512
  const after = this["~ext"]?.macro;
529
513
  if (after) {
530
- for (const [k, def] of Object.entries(after)) if (beforeMacro.get(k) !== def) throw new Error(`Macro ${k} was added by an async plugin which Elysia can't ensure the soundness. Please register macro in the plugin synchronously instead of async.`);
514
+ for (const [k, def] of Object.entries(after)) if (beforeMacro.get(k) !== def) throw new Error(`Macro ${k} can only run in sync plugin`);
531
515
  }
532
516
  return value;
533
517
  }));
@@ -574,7 +558,7 @@ var Elysia = class Elysia {
574
558
  const origin = macroOrigin.get(existing);
575
559
  if (origin !== void 0 && origin === macroOrigin.get(incoming)) continue;
576
560
  if (addedByThisCall) for (const h of addedByThisCall) this.#childrenHash.delete(h);
577
- throw new Error(`Macro "${macroName}" is defined by more than one plugin.Rename one of them (macro names must be unique across composed plugins), or give the plugin a \`name\` so repeated instances deduplicate.`);
561
+ throw new Error(`[Elysia] Macro "${macroName}" can be only define once`);
578
562
  }
579
563
  if (app.#history) {
580
564
  if (app["~hasWS"]) this["~hasWS"] = true;
@@ -780,7 +764,6 @@ var Elysia = class Elysia {
780
764
  this.#buildRouter();
781
765
  }
782
766
  #add(method, path, fn, hook) {
783
- if (hook !== void 0 && (typeof hook !== "object" || hook === null)) throw new Error(`Elysia 2 route signature is (path, hook, handler) — received ${typeof hook} in the hook position for "${method} ${path}". Did you use the Elysia 1 order (path, handler, hook)?`);
784
767
  if (this["~Prefix"]) path = joinPath(this["~Prefix"], path);
785
768
  else if (path && path.charCodeAt(0) !== 47) path = "/" + path;
786
769
  const appHook = this["~hookChain"];
@@ -943,13 +926,6 @@ var Elysia = class Elysia {
943
926
  /**
944
927
  * Force all route handlers to compile immediately (sets `precompile: true`
945
928
  * on the config and triggers a fresh build of the fetch handler).
946
- *
947
- * @remarks
948
- * **Memory trade-off (bench-memory-1):** each compiled route retains ~4.8 KB
949
- * (no schema) to ~6.6 KB (validated body) of memory (JSC compiled-function
950
- * representation + closure scope); 1 000 validated routes ≈ 6.6 MB. Without
951
- * this call, routes compile lazily on first request, spreading that cost over
952
- * time. Use the AOT build plugin for the lowest cold-start footprint.
953
929
  */
954
930
  compile() {
955
931
  this["~config"] ??= nullObject();
@@ -1029,13 +1005,13 @@ var Elysia = class Elysia {
1029
1005
  if (!schemaProperties.has(key)) continue;
1030
1006
  const v = hook[key];
1031
1007
  if (typeof v === "string") {
1032
- if (!models || !(v in models)) throw new Error(`[Elysia] Unknown model reference "${v}" for ${key} on route ${method} ${path}. Register it with .model('${v}', ...) before listen()/compile().`);
1008
+ if (!models || !(v in models)) throw new Error(`[Elysia] Unknown model reference "${v}" for ${key} on route ${method} ${path}.`);
1033
1009
  } else if (key === "response" && v && typeof v === "object") {
1034
1010
  const record = v;
1035
1011
  if ("~kind" in record || "~elyAcl" in record || "~standard" in record) continue;
1036
1012
  for (const status in record) {
1037
1013
  const r = record[status];
1038
- if (typeof r === "string" && (!models || !(r in models))) throw new Error(`[Elysia] Unknown model reference "${r}" for response ${status} on route ${method} ${path}. Register it with .model('${r}', ...) before listen()/compile().`);
1014
+ if (typeof r === "string" && (!models || !(r in models))) throw new Error(`[Elysia] Unknown model reference "${r}" for response ${status} on route ${method} ${path}.`);
1039
1015
  }
1040
1016
  }
1041
1017
  }
@@ -1120,7 +1096,7 @@ var Elysia = class Elysia {
1120
1096
  const existing = this["~config"].websocket;
1121
1097
  if (existing && isBun) {
1122
1098
  for (const key in options) if (key in existing && existing[key] !== options[key]) {
1123
- console.warn(`[Elysia] Conflicting per-route WebSocket option '${key}'\nBun uses one global WebSocket config per server, so per-route values are not enforced (the last-registered route wins).`);
1099
+ console.warn(`[Elysia] Conflicting per-route WebSocket option '${key}'\nBun uses one global WebSocket config per server, per-route values are not enforced (the last-registered route wins).`);
1124
1100
  console.warn((/* @__PURE__ */ new Error()).stack);
1125
1101
  }
1126
1102
  Object.assign(existing, options);
@@ -1247,26 +1223,6 @@ var Elysia = class Elysia {
1247
1223
  return r;
1248
1224
  }
1249
1225
  };
1250
- for (const [old, hint] of [
1251
- ["onError", "use .error() instead"],
1252
- ["onRequest", "use .request() instead"],
1253
- ["onParse", "use .parse() instead"],
1254
- ["onTransform", "use .transform() instead"],
1255
- ["onBeforeHandle", "use .beforeHandle() instead"],
1256
- ["onAfterHandle", "use .afterHandle() instead"],
1257
- ["onAfterResponse", "use .afterResponse() instead"],
1258
- ["onResponse", "use .mapResponse() instead"],
1259
- ["onStart", "use the listen(port, callback) callback instead"],
1260
- ["onStop", "use .cleanup() instead"],
1261
- ["resolve", "use .derive() instead"]
1262
- ]) Object.defineProperty(Elysia.prototype, old, {
1263
- value: function removed() {
1264
- throw new Error(`.${old}() was removed in Elysia 2 — ${hint}`);
1265
- },
1266
- writable: true,
1267
- enumerable: false,
1268
- configurable: true
1269
- });
1270
1226
 
1271
1227
  //#endregion
1272
1228
  export { Elysia };
@@ -273,15 +273,9 @@ function captureGet(loc) {
273
273
  return capture?.get(`${loc.method}_${loc.path}_${loc.slot}`);
274
274
  }
275
275
  const isAotBuildEnv = () => !!require_universal_env.env.ELYSIA_AOT_BUILD;
276
- let captureLogEmitted = false;
277
276
  const isValidatorCapturing = () => {
278
277
  if (capture !== void 0) return true;
279
- if (!isAotBuildEnv()) return false;
280
- if (!captureLogEmitted) {
281
- captureLogEmitted = true;
282
- console.log("[elysia-aot] build capture mode enabled");
283
- }
284
- return true;
278
+ return isAotBuildEnv();
285
279
  };
286
280
  const Capture = {
287
281
  set: captureSet,
@@ -296,9 +290,7 @@ const Capture = {
296
290
  * Reset module-level capture lifecycle state.
297
291
  * FOR TESTS ONLY — not exported from the package index.
298
292
  */
299
- const resetCaptureLifecycleForTests = () => {
300
- captureLogEmitted = false;
301
- };
293
+ const resetCaptureLifecycleForTests = () => void 0;
302
294
 
303
295
  //#endregion
304
296
  exports.Capture = Capture;
@@ -272,15 +272,9 @@ function captureGet(loc) {
272
272
  return capture?.get(`${loc.method}_${loc.path}_${loc.slot}`);
273
273
  }
274
274
  const isAotBuildEnv = () => !!env.ELYSIA_AOT_BUILD;
275
- let captureLogEmitted = false;
276
275
  const isValidatorCapturing = () => {
277
276
  if (capture !== void 0) return true;
278
- if (!isAotBuildEnv()) return false;
279
- if (!captureLogEmitted) {
280
- captureLogEmitted = true;
281
- console.log("[elysia-aot] build capture mode enabled");
282
- }
283
- return true;
277
+ return isAotBuildEnv();
284
278
  };
285
279
  const Capture = {
286
280
  set: captureSet,
@@ -295,9 +289,7 @@ const Capture = {
295
289
  * Reset module-level capture lifecycle state.
296
290
  * FOR TESTS ONLY — not exported from the package index.
297
291
  */
298
- const resetCaptureLifecycleForTests = () => {
299
- captureLogEmitted = false;
300
- };
292
+ const resetCaptureLifecycleForTests = () => void 0;
301
293
 
302
294
  //#endregion
303
295
  export { Capture, Compiled, EMPTY_EXTERNALS, Source, beginValidatorCapture, collectExternals, endHandlerCapture, endValidatorCapture, externalsMatch, instantiateFrozenBoth, instantiateFrozenDecodeMirror, instantiateFrozenEncodeMirror, instantiateFrozenMirror, reconstructCheck, resetCaptureLifecycleForTests };
@@ -1,5 +1,5 @@
1
- import { CapturedValidator, FrozenValidator } from "../aot.js";
2
1
  import { AnyLocalHook, HTTPMethod } from "../../types.js";
2
+ import { CapturedValidator, FrozenValidator } from "../aot.js";
3
3
  import { AnyElysia } from "../../base.js";
4
4
 
5
5
  //#region src/compile/handler/frozen-validator.d.ts
@@ -6,27 +6,6 @@ const require_compile_aot = require('../aot.js');
6
6
 
7
7
  //#region src/compile/handler/frozen-validator.ts
8
8
  const isBridgeNotInitialized = (error) => error instanceof Error && error.message.startsWith("Typebox module isn't initialized");
9
- /**
10
- * A codec (`k`) slot is bridge-free ONLY when it is a slot-level SCALAR coercion
11
- * schema whose coerced form equals the raw hook schema — i.e. the user wrote the
12
- * coercion type explicitly (`t.Numeric()`/`t.IntegerString()`/`t.BooleanString()`
13
- * /`t.Date()`, optionally `t.Optional(...)`), so no coerce PLAN (`cp`) was baked.
14
- *
15
- * The reconstruction consumes only TypeBox-free `aot.ts` helpers off the raw
16
- * schema: `instantiateFrozenBoth` (check + Clean, wiring `e`/`u` from the schema),
17
- * `instantiateFrozenDecodeMirror` (the string→typed decode + Clean, `dm`). The
18
- * decode leaves and Refine predicates are pure closures already frozen into the
19
- * schema, so nothing here touches TypeBox.
20
- *
21
- * Refuses the cases the frozen `From` cannot serve bridge-free:
22
- * - `cp`: needs `buildCoercedFromPlan` (drags TypeBox) to rebuild the schema.
23
- * - `ic`: `t.ObjectString`/`t.ArrayString` inner codecs (JSON-in-string).
24
- * - `em`: response-side encode mirror (request codec slots don't set it, but
25
- * refuse defensively — the frozen `From` only wires the decode direction).
26
- * - `ce`/`a`: custom errors / async refinement — the non-codec path refuses
27
- * these too.
28
- * - defaults not preallocated (`d` && !`ps`): would call the severed `Default`.
29
- */
30
9
  function codecCoercionBridgeFree(f) {
31
10
  return f.k === 1 && !!f.dm && !f.cp && !f.ic && !f.em && !f.ce && f.a !== 1 && !(f.d === 1 && f.ps !== 1);
32
11
  }
@@ -5,27 +5,6 @@ import { Compiled, EMPTY_EXTERNALS, instantiateFrozenBoth, instantiateFrozenDeco
5
5
 
6
6
  //#region src/compile/handler/frozen-validator.ts
7
7
  const isBridgeNotInitialized = (error) => error instanceof Error && error.message.startsWith("Typebox module isn't initialized");
8
- /**
9
- * A codec (`k`) slot is bridge-free ONLY when it is a slot-level SCALAR coercion
10
- * schema whose coerced form equals the raw hook schema — i.e. the user wrote the
11
- * coercion type explicitly (`t.Numeric()`/`t.IntegerString()`/`t.BooleanString()`
12
- * /`t.Date()`, optionally `t.Optional(...)`), so no coerce PLAN (`cp`) was baked.
13
- *
14
- * The reconstruction consumes only TypeBox-free `aot.ts` helpers off the raw
15
- * schema: `instantiateFrozenBoth` (check + Clean, wiring `e`/`u` from the schema),
16
- * `instantiateFrozenDecodeMirror` (the string→typed decode + Clean, `dm`). The
17
- * decode leaves and Refine predicates are pure closures already frozen into the
18
- * schema, so nothing here touches TypeBox.
19
- *
20
- * Refuses the cases the frozen `From` cannot serve bridge-free:
21
- * - `cp`: needs `buildCoercedFromPlan` (drags TypeBox) to rebuild the schema.
22
- * - `ic`: `t.ObjectString`/`t.ArrayString` inner codecs (JSON-in-string).
23
- * - `em`: response-side encode mirror (request codec slots don't set it, but
24
- * refuse defensively — the frozen `From` only wires the decode direction).
25
- * - `ce`/`a`: custom errors / async refinement — the non-codec path refuses
26
- * these too.
27
- * - defaults not preallocated (`d` && !`ps`): would call the severed `Default`.
28
- */
29
8
  function codecCoercionBridgeFree(f) {
30
9
  return f.k === 1 && !!f.dm && !f.cp && !f.ic && !f.em && !f.ce && f.a !== 1 && !(f.d === 1 && f.ps !== 1);
31
10
  }
package/dist/constants.js CHANGED
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  //#region src/constants.ts
4
4
  const mapBack = (map) => Object.fromEntries(Object.entries(map).map(([key, value]) => [value, key]));
5
- const MethodMap = {
5
+ const MethodMap = (/*#__PURE__*/ {
6
6
  GET: 0,
7
7
  HEAD: 1,
8
8
  POST: 2,
@@ -12,9 +12,9 @@ const MethodMap = {
12
12
  OPTIONS: 6,
13
13
  CONNECT: 7,
14
14
  TRACE: 8
15
- };
15
+ });
16
16
  const MethodMapBack = mapBack(MethodMap);
17
- const StatusMap = {
17
+ const StatusMap = (/*#__PURE__*/ {
18
18
  Continue: 100,
19
19
  "Switching Protocols": 101,
20
20
  Processing: 102,
@@ -76,7 +76,7 @@ const StatusMap = {
76
76
  "Loop Detected": 508,
77
77
  "Not Extended": 510,
78
78
  "Network Authentication Required": 511
79
- };
79
+ });
80
80
  const traceEvents = [
81
81
  "request",
82
82
  "parse",
@@ -1,6 +1,6 @@
1
1
  //#region src/constants.ts
2
2
  const mapBack = (map) => Object.fromEntries(Object.entries(map).map(([key, value]) => [value, key]));
3
- const MethodMap = {
3
+ const MethodMap = (/*#__PURE__*/ {
4
4
  GET: 0,
5
5
  HEAD: 1,
6
6
  POST: 2,
@@ -10,9 +10,9 @@ const MethodMap = {
10
10
  OPTIONS: 6,
11
11
  CONNECT: 7,
12
12
  TRACE: 8
13
- };
13
+ });
14
14
  const MethodMapBack = mapBack(MethodMap);
15
- const StatusMap = {
15
+ const StatusMap = (/*#__PURE__*/ {
16
16
  Continue: 100,
17
17
  "Switching Protocols": 101,
18
18
  Processing: 102,
@@ -74,7 +74,7 @@ const StatusMap = {
74
74
  "Loop Detected": 508,
75
75
  "Not Extended": 510,
76
76
  "Network Authentication Required": 511
77
- };
77
+ });
78
78
  const traceEvents = [
79
79
  "request",
80
80
  "parse",
package/dist/index.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import { StatusMap, StatusMapBack } from "./constants.js";
2
2
  import { ElysiaError, ElysiaStatus, InternalServerError, NotFound, ParseError, Problem, SelectiveStatus, ValidationError, problem, status, validationDetail } from "./error.js";
3
- import { ElysiaFile, file } from "./universal/file.js";
4
3
  import { BaseCookie, CookieOptions } from "./cookie/types.js";
5
4
  import { Cookie } from "./cookie/cookie.js";
6
5
  import { InvalidCookie } from "./cookie/error.js";
6
+ import { ElysiaFile, file } from "./universal/file.js";
7
+ import { env } from "./universal/env.js";
8
+ import { Server } from "./universal/server.js";
9
+ import { HTTPHeaders, InputSchema, Macro, MacroToContext, MacroToProperty, RouteSchema, SSEPayload, UnwrapRoute, UnwrapSchema } from "./types.js";
7
10
  import { AnySchema, BaseSchema, StandardJSONSchemaV1Like, StandardSchemaV1Like } from "./type/types.js";
8
11
  import { TCookieField, TCookieObject } from "./type/elysia/cookie.js";
9
12
  import { FileTypeDetector, fileType, setFileTypeDetector } from "./type/elysia/file-type.js";
@@ -13,9 +16,6 @@ import { Capture, Compiled } from "./compile/aot.js";
13
16
  import { MultiValidator, StandardValidator, Validator } from "./validator/index.js";
14
17
  import { TypeBoxValidator } from "./type/validator/index.js";
15
18
  import { TypeSystem, t } from "./type/index.js";
16
- import { env } from "./universal/env.js";
17
- import { Server } from "./universal/server.js";
18
- import { HTTPHeaders, InputSchema, Macro, MacroToContext, MacroToProperty, RouteSchema, SSEPayload, UnwrapRoute, UnwrapSchema } from "./types.js";
19
19
  import { form, prefix, redirect, sse } from "./utils.js";
20
20
  import { Context, ErrorContext, createBaseContext, createContext } from "./context.js";
21
21
  import { AnyElysia, Elysia } from "./base.js";
@@ -359,8 +359,6 @@ async function generateCompiledArtifacts(file, options) {
359
359
  if (typedApp["~config"]?.normalize === "typebox") routesForbidSeal = true;
360
360
  const frozenSlots = artifacts.validators.length;
361
361
  const { plan: stub, mode } = planFromReport(strip, report, hasWS, aliases, artifacts.handlers.length > 0 && !routesForbidSeal && frozenSlots >= expectedSlots && artifacts.validators.every((v) => v.bridgeFree === true));
362
- const stubbed = Object.keys(stub).filter((key) => stub[key]);
363
- console.log(`[elysia-aot] routes=${routes.length} handlers=${artifacts.handlers.length} validators=${frozenSlots}/${expectedSlots} mode=${mode} stub=${stubbed.join(",") || "none"}` + (report.jit ? "" : ` jit-reachable (${report.reasons.join(", ") || "unknown"})`));
364
362
  if (options?.target === "workerd") {
365
363
  if (!report.jit) throw new Error(`[elysia-aot] target 'workerd' but handler JIT is still reachable (${report.reasons.join(", ") || "unknown"}). Every route must be captured into the AOT manifest.`);
366
364
  if (frozenSlots < expectedSlots) console.warn(`[elysia-aot] target 'workerd': only ${frozenSlots}/${expectedSlots} validator slots were frozen unfrozen slots compile at runtime and will fail on workerd.`);
@@ -357,8 +357,6 @@ async function generateCompiledArtifacts(file, options) {
357
357
  if (typedApp["~config"]?.normalize === "typebox") routesForbidSeal = true;
358
358
  const frozenSlots = artifacts.validators.length;
359
359
  const { plan: stub, mode } = planFromReport(strip, report, hasWS, aliases, artifacts.handlers.length > 0 && !routesForbidSeal && frozenSlots >= expectedSlots && artifacts.validators.every((v) => v.bridgeFree === true));
360
- const stubbed = Object.keys(stub).filter((key) => stub[key]);
361
- console.log(`[elysia-aot] routes=${routes.length} handlers=${artifacts.handlers.length} validators=${frozenSlots}/${expectedSlots} mode=${mode} stub=${stubbed.join(",") || "none"}` + (report.jit ? "" : ` jit-reachable (${report.reasons.join(", ") || "unknown"})`));
362
360
  if (options?.target === "workerd") {
363
361
  if (!report.jit) throw new Error(`[elysia-aot] target 'workerd' but handler JIT is still reachable (${report.reasons.join(", ") || "unknown"}). Every route must be captured into the AOT manifest.`);
364
362
  if (frozenSlots < expectedSlots) console.warn(`[elysia-aot] target 'workerd': only ${frozenSlots}/${expectedSlots} validator slots were frozen unfrozen slots compile at runtime and will fail on workerd.`);
@@ -64,7 +64,7 @@ const aot = (entry, options) => {
64
64
  virtualType = generated.virtualType;
65
65
  },
66
66
  buildEnd() {
67
- if (!entryMatched) throw new Error(`[elysia-aot] entry "${entry}" never appeared in the Vite module graph the compiled manifest was not injected. Check that the plugin entry matches a build input.`);
67
+ if (!entryMatched) throw new Error(`[elysia-aot] entry "${entry}" never appeared in the Vite module graph. Compiled manifest was not injected. Check that the plugin entry matches a build input.`);
68
68
  },
69
69
  resolveId(id) {
70
70
  if (id === "elysia/compiled") return VIRTUAL;
@@ -62,7 +62,7 @@ const aot = (entry, options) => {
62
62
  virtualType = generated.virtualType;
63
63
  },
64
64
  buildEnd() {
65
- if (!entryMatched) throw new Error(`[elysia-aot] entry "${entry}" never appeared in the Vite module graph the compiled manifest was not injected. Check that the plugin entry matches a build input.`);
65
+ if (!entryMatched) throw new Error(`[elysia-aot] entry "${entry}" never appeared in the Vite module graph. Compiled manifest was not injected. Check that the plugin entry matches a build input.`);
66
66
  },
67
67
  resolveId(id) {
68
68
  if (id === "elysia/compiled") return VIRTUAL;
@@ -1,16 +1,16 @@
1
- import { Intersect as Intersect$1 } from "./elysia/intersect.js";
1
+ import { Intersect as Intersect$2 } from "./elysia/intersect.js";
2
2
  import { applyCoercions as applyCoercions$1, coerceBody as coerceBody$1, coerceFormData as coerceFormData$1, coerceQuery as coerceQuery$1, coerceRoot as coerceRoot$1, coerceStringToStructure as coerceStringToStructure$1 } from "./coerce.js";
3
3
  import { hasTypes as hasTypes$1 } from "./utils.js";
4
4
  import { TypeBoxValidatorCache as TypeBoxValidatorCache$1 } from "./validator/validator-cache.js";
5
5
  import { TypeBoxValidator as TypeBoxValidator$1 } from "./validator/index.js";
6
6
  import { Ref as Ref$1, TAny, TSchema } from "typebox/type";
7
7
  import { Compile as Compile$1 } from "typebox/compile";
8
- import { Clone as Clone$1, Decode as Decode$1, Default as Default$1, HasCodec as HasCodec$1 } from "typebox/value";
8
+ import { Clone as Clone$1, Decode as Decode$2, Default as Default$1, HasCodec as HasCodec$1 } from "typebox/value";
9
9
 
10
10
  //#region src/type/bridge.d.ts
11
11
  interface TypeboxModule {
12
12
  Compile: typeof Compile$1;
13
- Decode: typeof Decode$1;
13
+ Decode: typeof Decode$2;
14
14
  applyCoercions: typeof applyCoercions$1;
15
15
  TypeBoxValidator: TypeBoxValidator$1;
16
16
  TypeBoxValidatorCache: TypeBoxValidatorCache$1;
@@ -21,13 +21,13 @@ interface TypeboxModule {
21
21
  coerceBody: typeof coerceBody$1;
22
22
  hasTypes: typeof hasTypes$1;
23
23
  HasCodec: typeof HasCodec$1;
24
- Intersect: typeof Intersect$1;
24
+ Intersect: typeof Intersect$2;
25
25
  Default: typeof Default$1;
26
26
  Ref: typeof Ref$1;
27
27
  Clone: typeof Clone$1;
28
28
  }
29
29
  declare let Compile: typeof Compile$1;
30
- declare let Decode: typeof Decode$1;
30
+ declare let Decode: typeof Decode$2;
31
31
  declare let applyCoercions: typeof applyCoercions$1;
32
32
  declare let TypeBoxValidator: TypeBoxValidator$1;
33
33
  type TypeBoxValidator<T extends TSchema = TAny> = TypeBoxValidator$1<T>;
@@ -40,7 +40,7 @@ declare let coerceStringToStructure: typeof coerceStringToStructure$1;
40
40
  declare let coerceBody: typeof coerceBody$1;
41
41
  declare let hasTypes: typeof hasTypes$1;
42
42
  declare let HasCodec: typeof HasCodec$1;
43
- declare let Intersect: typeof Intersect$1;
43
+ declare let Intersect: typeof Intersect$2;
44
44
  declare let Default: typeof Default$1;
45
45
  declare let Ref: typeof Ref$1;
46
46
  declare let Clone: typeof Clone$1;
@@ -36,7 +36,7 @@ declare const coerceQuery: () => CoerceOption[];
36
36
  declare const coerceBody: () => CoerceOption[];
37
37
  declare const coerceFormData: () => CoerceOption[];
38
38
  declare const coerceStringToStructure: () => CoerceOption[];
39
- declare function applyCoercions(schema: BaseSchema | TSchema, coerces: CoerceOption[] | undefined): TSchema | BaseSchema;
39
+ declare function applyCoercions(schema: BaseSchema | TSchema, coerces: CoerceOption[] | undefined): BaseSchema | TSchema;
40
40
  interface CoerceLeaf {
41
41
  e: number;
42
42
  c?: Record<string, unknown>;
@@ -17,7 +17,7 @@ declare const ELYSIA_TYPES: {
17
17
  readonly NoValidate: 15;
18
18
  };
19
19
  type ELYSIA_TYPES = typeof ELYSIA_TYPES;
20
- declare const primitiveElysiaTypes: Set<3 | 1 | 2 | 6 | 14 | 13 | 11 | 10>;
20
+ declare const primitiveElysiaTypes: Set<1 | 2 | 3 | 6 | 10 | 11 | 13 | 14>;
21
21
  declare const noEnumerable: {
22
22
  readonly enumerable: false;
23
23
  };
@@ -1,5 +1,5 @@
1
- import { FileType, FileUnit } from "../types.js";
2
1
  import { MaybeArray, MaybePromise } from "../../types.js";
2
+ import { FileType, FileUnit } from "../types.js";
3
3
 
4
4
  //#region src/type/elysia/file-type.d.ts
5
5
  type FileTypeDetector = (file: File) => MaybePromise<string | {
@@ -1,6 +1,6 @@
1
+ import { MaybePromise } from "../../types.js";
1
2
  import { Validator as Validator$1, ValidatorOptions } from "../../validator/index.js";
2
3
  import { TypeBoxValidatorCache } from "./validator-cache.js";
3
- import { MaybePromise } from "../../types.js";
4
4
  import { Static, StaticDecode, StaticEncode, TAny, TSchema } from "typebox/type";
5
5
  import { Validator } from "typebox/schema";
6
6
  import { TLocalizedValidationError } from "typebox/error";
package/dist/types.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { MethodMap, StatusMapBack } from "./constants.js";
2
2
  import { ElysiaError, ElysiaStatus } from "./error.js";
3
+ import { CookieOptions } from "./cookie/types.js";
3
4
  import { ElysiaFile } from "./universal/file.js";
4
5
  import { TraceEvent, TraceListener } from "./trace.js";
5
- import { CookieOptions } from "./cookie/types.js";
6
- import { AnySchema, StandardSchemaV1Like, TypeBoxSchema } from "./type/types.js";
7
6
  import { Serve } from "./universal/server.js";
7
+ import { AnySchema, StandardSchemaV1Like, TypeBoxSchema } from "./type/types.js";
8
8
  import { ChainNode } from "./utils.js";
9
9
  import { Context, ErrorContext, LifecycleContext, PreContext } from "./context.js";
10
10
  import { WebSocketHandler } from "./ws/types.js";
@@ -914,5 +914,8 @@ type GlobalHookReturn<BasePath extends string, Scope extends EventScope, Singlet
914
914
  type AddWSRoute<BasePath extends string, Scope extends EventScope, Singleton extends SingletonBase, Definitions extends DefinitionBase, Metadata extends MetadataBase, Routes extends RouteBase, Ephemeral extends EphemeralType, Volatile extends EphemeralType, Path extends string, Schema extends RouteSchema, MacroContext extends RouteSchema, Response> = Elysia<BasePath, Scope, Singleton, Definitions, Metadata, Routes & CreateEden<JoinPath<BasePath, Path>, {
915
915
  subscribe: CreateWSEdenResponse<Path, Schema, MacroContext, ComposeElysiaResponse<Schema & MacroContext & Metadata['schemas'] & Ephemeral['schemas'] & Volatile['schemas'], Response, UnionResponseStatus<Metadata['response'], UnionResponseStatus<Ephemeral['response'], UnionResponseStatus<Volatile['response'], MacroContext['return'] & {}>>>, [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']], Path>>;
916
916
  }>, Ephemeral, Volatile>;
917
+ type GuardHookSingleton<Singleton extends SingletonBase, Ephemeral extends EphemeralType, Volatile extends EphemeralType, MacroContext> = Singleton & {
918
+ derive: Ephemeral['derive'] & Volatile['derive'] & MacroContext['resolve'];
919
+ };
917
920
  //#endregion
918
- export { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, type AnySchema, AnyWSLocalHook, AppEvent, AppHook, BaseMacro, BodyHandler, BunHTMLBundlelike, CompiledHandler, ComposeElysiaResponse, ContentType, ContextAppendType, CreateEden, CreateEdenResponse, CreateWSEdenResponse, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, DocumentDecoration, ElysiaConfig, ElysiaFormData, ElysiaHandlerToResponseSchema, ElysiaHandlerToResponseSchemaAmbiguous, ElysiaHandlerToResponseSchemas, EmptyInputSchema, EphemeralType, Equal, ErrorDefinition, ErrorDefinitionEntry, ErrorHandler, ErrorHandlerResponseSchema, EventFn, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, ExtractReturnedError, GetPathParameter, GlobalHookReturn, GracefulHandler, GuardLocalHook, GuardSchemaType, HTTPHeaders, HTTPMethod, Handler, HookContextSchema, HookContextSingleton, InlineHandler, InlineHandlerNonMacro, InlineHandlerResponse, InlineResponse, InlineSchemaResponse, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObject, IntersectIfObjectSchema, IsAny, IsNever, IsTuple, IsUnknown, JoinPath, LocalHook, LocalHookReturn, Macro, MacroProperty, MacroPropertyKey, MacroSchemaChannel, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MaybeValueOrVoidFunction, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, NonResolvableMacroKey, ObjectMacroDefs, OptionalHandler, PluginHookReturn, PossibleResponse, PreHandler, Prettify, PublicRoute, Replace, ResolveHandler, ResolvePath, ResolveRouteErrors, RouteBase, RouteSchema, SSEPayload, SingletonBase, type StandardSchemaV1Like, TraceHandler, TransformHandler, type TypeBoxSchema, UnhandledReturnedError, UnhandledReturnedErrorOf, UnionResponseStatus, UnionToIntersect, UnwrapArray, UnwrapBodySchema, UnwrapMacroSchema, UnwrapRoute, UnwrapSchema, ValueOrFunctionToResponseSchema, ValueToResponseSchema, VoidHandler, WrapFn };
921
+ export { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, type AnySchema, AnyWSLocalHook, AppEvent, AppHook, BaseMacro, BodyHandler, BunHTMLBundlelike, CompiledHandler, ComposeElysiaResponse, ContentType, ContextAppendType, CreateEden, CreateEdenResponse, CreateWSEdenResponse, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, DocumentDecoration, ElysiaConfig, ElysiaFormData, ElysiaHandlerToResponseSchema, ElysiaHandlerToResponseSchemaAmbiguous, ElysiaHandlerToResponseSchemas, EmptyInputSchema, EphemeralType, Equal, ErrorDefinition, ErrorDefinitionEntry, ErrorHandler, ErrorHandlerResponseSchema, EventFn, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, ExtractReturnedError, GetPathParameter, GlobalHookReturn, GracefulHandler, GuardHookSingleton, GuardLocalHook, GuardSchemaType, HTTPHeaders, HTTPMethod, Handler, HookContextSchema, HookContextSingleton, InlineHandler, InlineHandlerNonMacro, InlineHandlerResponse, InlineResponse, InlineSchemaResponse, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObject, IntersectIfObjectSchema, IsAny, IsNever, IsTuple, IsUnknown, JoinPath, LocalHook, LocalHookReturn, Macro, MacroProperty, MacroPropertyKey, MacroSchemaChannel, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MaybeValueOrVoidFunction, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, NonResolvableMacroKey, ObjectMacroDefs, OptionalHandler, PluginHookReturn, PossibleResponse, PreHandler, Prettify, PublicRoute, Replace, ResolveHandler, ResolvePath, ResolveRouteErrors, RouteBase, RouteSchema, SSEPayload, SingletonBase, type StandardSchemaV1Like, TraceHandler, TransformHandler, type TypeBoxSchema, UnhandledReturnedError, UnhandledReturnedErrorOf, UnionResponseStatus, UnionToIntersect, UnwrapArray, UnwrapBodySchema, UnwrapMacroSchema, UnwrapRoute, UnwrapSchema, ValueOrFunctionToResponseSchema, ValueToResponseSchema, VoidHandler, WrapFn };
package/dist/utils.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MethodMap } from "./constants.js";
2
- import { AnySchema, StandardSchemaV1Like } from "./type/types.js";
3
2
  import { AnyLocalHook, AppHook, ElysiaFormData, EventFn, EventScope, GuardSchemaType, InputSchema, Macro, MaybeArray, Prettify, SSEPayload } from "./types.js";
3
+ import { AnySchema, StandardSchemaV1Like } from "./type/types.js";
4
4
  import { Context } from "./context.js";
5
5
 
6
6
  //#region src/utils.d.ts
@@ -147,5 +147,6 @@ declare function prefix<T extends string, Models extends Record<string, AnySchem
147
147
  declare namespace prefix {
148
148
  var capitalize: <T extends string, Models extends Record<string, AnySchema>>(prefix: T, models: Models) => { [k in keyof Models as `${T}.${Capitalize<k & string>}`]: Models[k] };
149
149
  }
150
+ declare function serializeMacroSeed(_key: string, value: unknown): unknown;
150
151
  //#endregion
151
- export { ChainNode, cloneHook, clonePlainDecorators, clonePlainDeep, coalesceStandaloneSchemas, constantTimeEqual, createErrorEventHandler, dedupedMergeArray, eventProperties, flattenChain, flattenChainMemo, fnOrigin, fnv1a, form, formToFormData, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isBlob, isDownwardScope, isEmpty, isLocalScope, isNotEmpty, isRecordNumber, joinPath, macroEpoch, macroOrigin, mapMethodBack, mergeArray, mergeDeep, mergeHook, mergeResponse, nullObject, prefix, pushField, redirect, replaceUrlPath, requestId, schemaProperties, sse };
152
+ export { ChainNode, cloneHook, clonePlainDecorators, clonePlainDeep, coalesceStandaloneSchemas, constantTimeEqual, createErrorEventHandler, dedupedMergeArray, eventProperties, flattenChain, flattenChainMemo, fnOrigin, fnv1a, form, formToFormData, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isBlob, isDownwardScope, isEmpty, isLocalScope, isNotEmpty, isRecordNumber, joinPath, macroEpoch, macroOrigin, mapMethodBack, mergeArray, mergeDeep, mergeHook, mergeResponse, nullObject, prefix, pushField, redirect, replaceUrlPath, requestId, schemaProperties, serializeMacroSeed, sse };
package/dist/utils.js CHANGED
@@ -509,6 +509,22 @@ prefix.capitalize = function prefixModelsCapitalize(prefix, models) {
509
509
  for (const key in models) prefixed[`${prefix}.${capitalize(key)}`] = models[key];
510
510
  return prefixed;
511
511
  };
512
+ const macroSeedRefIds = /* @__PURE__ */ new WeakMap();
513
+ let macroSeedRefCounter = 0;
514
+ function macroSeedRefId(ref) {
515
+ let id = macroSeedRefIds.get(ref);
516
+ if (id === void 0) macroSeedRefIds.set(ref, id = ++macroSeedRefCounter);
517
+ return id;
518
+ }
519
+ function serializeMacroSeed(_key, value) {
520
+ switch (typeof value) {
521
+ case "function": return "\0fn:" + macroSeedRefId(value);
522
+ case "bigint": return "\0bigint:" + value.toString();
523
+ case "symbol": return "\0sym:" + String(value);
524
+ case "undefined": return "\0undefined";
525
+ default: return value;
526
+ }
527
+ }
512
528
 
513
529
  //#endregion
514
530
  exports.cloneHook = cloneHook;
@@ -550,4 +566,5 @@ exports.redirect = redirect;
550
566
  exports.replaceUrlPath = replaceUrlPath;
551
567
  exports.requestId = requestId;
552
568
  exports.schemaProperties = schemaProperties;
569
+ exports.serializeMacroSeed = serializeMacroSeed;
553
570
  exports.sse = sse;
package/dist/utils.mjs CHANGED
@@ -508,6 +508,22 @@ prefix.capitalize = function prefixModelsCapitalize(prefix, models) {
508
508
  for (const key in models) prefixed[`${prefix}.${capitalize(key)}`] = models[key];
509
509
  return prefixed;
510
510
  };
511
+ const macroSeedRefIds = /* @__PURE__ */ new WeakMap();
512
+ let macroSeedRefCounter = 0;
513
+ function macroSeedRefId(ref) {
514
+ let id = macroSeedRefIds.get(ref);
515
+ if (id === void 0) macroSeedRefIds.set(ref, id = ++macroSeedRefCounter);
516
+ return id;
517
+ }
518
+ function serializeMacroSeed(_key, value) {
519
+ switch (typeof value) {
520
+ case "function": return "\0fn:" + macroSeedRefId(value);
521
+ case "bigint": return "\0bigint:" + value.toString();
522
+ case "symbol": return "\0sym:" + String(value);
523
+ case "undefined": return "\0undefined";
524
+ default: return value;
525
+ }
526
+ }
511
527
 
512
528
  //#endregion
513
- export { cloneHook, clonePlainDecorators, clonePlainDeep, coalesceStandaloneSchemas, constantTimeEqual, createErrorEventHandler, dedupedMergeArray, eventProperties, flattenChain, flattenChainMemo, fnOrigin, fnv1a, form, formToFormData, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isBlob, isDownwardScope, isEmpty, isLocalScope, isNotEmpty, isRecordNumber, joinPath, macroEpoch, macroOrigin, mapMethodBack, mergeArray, mergeDeep, mergeHook, mergeResponse, nullObject, prefix, pushField, redirect, replaceUrlPath, requestId, schemaProperties, sse };
529
+ export { cloneHook, clonePlainDecorators, clonePlainDeep, coalesceStandaloneSchemas, constantTimeEqual, createErrorEventHandler, dedupedMergeArray, eventProperties, flattenChain, flattenChainMemo, fnOrigin, fnv1a, form, formToFormData, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isBlob, isDownwardScope, isEmpty, isLocalScope, isNotEmpty, isRecordNumber, joinPath, macroEpoch, macroOrigin, mapMethodBack, mergeArray, mergeDeep, mergeHook, mergeResponse, nullObject, prefix, pushField, redirect, replaceUrlPath, requestId, schemaProperties, serializeMacroSeed, sse };
@@ -1,8 +1,8 @@
1
+ import { ElysiaConfig, MaybePromise } from "../types.js";
1
2
  import { AnySchema, StandardSchemaV1Like } from "../type/types.js";
2
3
  import { CoerceOption } from "../type/coerce.js";
3
4
  import { ValidatorSlot } from "../compile/aot.js";
4
5
  import { TypeBoxValidator } from "../type/bridge.js";
5
- import { ElysiaConfig, MaybePromise } from "../types.js";
6
6
  import { TSchema } from "typebox/type";
7
7
  import { TLocalizedValidationError } from "typebox/error";
8
8
 
@@ -94,7 +94,7 @@ const isCompiledSchema = (schema) => schema != null && typeof schema.Check === "
94
94
  const isSingleSchema = (schema) => "~kind" in schema || "~elyAcl" in schema || "~standard" in schema;
95
95
  const toStatusBased = (schema) => isSingleSchema(schema) ? { 200: schema } : schema;
96
96
  const isAsyncStandardSchema = (schema) => require_compile_utils.isAsyncFunction(schema["~standard"].validate);
97
- const asyncStandardSchemaError = () => /* @__PURE__ */ new Error("[Elysia] An asynchronous Standard Schema was used where only synchronous validation is supported. Declare the schema validate function as async so Elysia can emit an async route.");
97
+ const asyncStandardSchemaError = () => /* @__PURE__ */ new Error("[Elysia] An asynchronous Standard Schema was used where only synchronous validation is supported.");
98
98
  var StandardValidator = class extends Validator {
99
99
  #validate;
100
100
  constructor(schema) {
@@ -93,7 +93,7 @@ const isCompiledSchema = (schema) => schema != null && typeof schema.Check === "
93
93
  const isSingleSchema = (schema) => "~kind" in schema || "~elyAcl" in schema || "~standard" in schema;
94
94
  const toStatusBased = (schema) => isSingleSchema(schema) ? { 200: schema } : schema;
95
95
  const isAsyncStandardSchema = (schema) => isAsyncFunction(schema["~standard"].validate);
96
- const asyncStandardSchemaError = () => /* @__PURE__ */ new Error("[Elysia] An asynchronous Standard Schema was used where only synchronous validation is supported. Declare the schema validate function as async so Elysia can emit an async route.");
96
+ const asyncStandardSchemaError = () => /* @__PURE__ */ new Error("[Elysia] An asynchronous Standard Schema was used where only synchronous validation is supported.");
97
97
  var StandardValidator = class extends Validator {
98
98
  #validate;
99
99
  constructor(schema) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "elysia",
3
3
  "description": "Ergonomic Framework for Human",
4
- "version": "2.0.0-exp.26",
4
+ "version": "2.0.0-exp.27",
5
5
  "author": {
6
6
  "name": "saltyAom",
7
7
  "url": "https://github.com/SaltyAom",