elysia 2.0.0-beta.30 → 2.0.0-beta.32

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.
@@ -1,7 +1,8 @@
1
1
  import { isResponseParam } from "../../compile/handler/params.mjs";
2
2
  import { REQUEST_SLOTS, isResponseMap, isStandardSchema, mergeSchemasAllStandard, resolveModelRef } from "../../compile/handler/frozen-validator.mjs";
3
3
  import { composeRouteHook, runIntrospect } from "../../compile/handler/index.mjs";
4
- import { captureArtifacts, compileToSource, replayStubbability } from "./source.mjs";
4
+ import { abortCapture } from "../../compile/aot-capture.mjs";
5
+ import { captureArtifacts, emitModule, manifestKey, replayStubbability } from "./source.mjs";
5
6
  import { createRequire } from "node:module";
6
7
  import { existsSync, readFileSync, realpathSync } from "node:fs";
7
8
  import { dirname, extname, join, resolve } from "node:path";
@@ -55,9 +56,9 @@ const NO_STUB = {
55
56
  adapter: false,
56
57
  isProduction: false
57
58
  };
58
- function planFromReport(strip, report, hasWS, mayTrace, aliases, allBridgeFree, zeroCapture, adapterStub = false, productionStub = true, wsCookie = false, exactMirror = false) {
59
+ function planFromReport(strip, report, hasWS, mayTrace, aliases, allBridgeFree, zeroCapture, adapterStub = false, productionStub = true, wsCookie = false, exactMirror = false, key = "") {
59
60
  const jit = report.jit;
60
- if (strip === true && !jit) throw new Error(`[elysia-aot] strip: true requires every route to be covered by the AOT handler manifest, but handler JIT is still reachable (${report.reasons.join(", ") || "unknown"}). Use strip: 'auto' to skip stubbing when the app is not fully precompiled.`);
61
+ if (strip === true && !jit) throw new Error(`[elysia-aot] strip: true requires every route${key && ` of app "${key}"`} to be covered by the AOT handler manifest, but handler JIT is still reachable (${report.reasons.join(", ") || "unknown"}). Use strip: 'auto' to skip stubbing when the app is not fully precompiled.`);
61
62
  const mode = !jit ? "off" : allBridgeFree ? "sealed" : hasWS && zeroCapture ? "off" : "wired";
62
63
  return {
63
64
  plan: {
@@ -68,16 +69,51 @@ function planFromReport(strip, report, hasWS, mayTrace, aliases, allBridgeFree,
68
69
  cookie: jit && !aliases.has("cc") && !wsCookie,
69
70
  trace: !aliases.has("tr") && (jit || !mayTrace),
70
71
  sucrose: jit,
71
- compat: mode !== "off",
72
- bridge: mode === "wired",
73
- typeboxValue: mode !== "sealed",
74
- exactMirror: exactMirror && mode !== "sealed",
72
+ ...bridgePlan(mode, exactMirror),
75
73
  adapter: adapterStub,
76
74
  isProduction: productionStub
77
75
  },
78
76
  mode
79
77
  };
80
78
  }
79
+ const bridgePlan = (mode, exactMirror) => ({
80
+ compat: mode !== "off",
81
+ bridge: mode === "wired",
82
+ typeboxValue: mode !== "sealed",
83
+ exactMirror: exactMirror && mode !== "sealed"
84
+ });
85
+ const MODE_RANK = {
86
+ off: 0,
87
+ wired: 1,
88
+ sealed: 2
89
+ };
90
+ const REMOVAL_FLAGS = {
91
+ jit: 0,
92
+ staticClone: 0,
93
+ ws: 0,
94
+ reconstruct: 0,
95
+ cookie: 0,
96
+ trace: 0,
97
+ sucrose: 0
98
+ };
99
+ function mergePlans(plans, exactMirror) {
100
+ const plan = { ...plans[0].plan };
101
+ let mode = plans[0].mode;
102
+ for (const each of plans) {
103
+ if (MODE_RANK[each.mode] < MODE_RANK[mode]) mode = each.mode;
104
+ for (const key in REMOVAL_FLAGS) {
105
+ const flag = key;
106
+ plan[flag] &&= each.plan[flag];
107
+ }
108
+ }
109
+ return {
110
+ plan: {
111
+ ...plan,
112
+ ...bridgePlan(mode, exactMirror)
113
+ },
114
+ mode
115
+ };
116
+ }
81
117
  function adapterConstantsSource(target) {
82
118
  if (target === "bun") return "import { BunAdapter } from './bun/index'\nexport const defaultAdapter = BunAdapter\n";
83
119
  return "import { WebStandardAdapter } from './web-standard/index'\nexport const defaultAdapter = WebStandardAdapter\n";
@@ -409,13 +445,6 @@ function validatorSlotSetsMatch(expected, captured) {
409
445
  for (const key of expectedKeys) if (!capturedKeys.has(key)) return false;
410
446
  return true;
411
447
  }
412
- const assertNoMount = (app, entry) => {
413
- const routes = app["~routes"];
414
- const mounted = [];
415
- for (const route of routes) if (route[2]?.["~mount"] && !mounted.includes(route[1])) mounted.push(route[1]);
416
- if (!mounted.length) return;
417
- throw new Error(`[elysia-aot] "${entry}" mounts a sub-app (${mounted.join(", ")}). AOT cannot compile a mounted sub-app. Compose with .use() instead of .mount(), or disable AOT plugin`);
418
- };
419
448
  async function generateCompiledArtifacts(file, options, moduleCondition = resolveEntryModuleKind(file)) {
420
449
  if (moduleCondition !== loadedModuleCondition) throw new Error(`[elysia-aot] entry uses the ${moduleCondition === "cjs" ? "CommonJS \"require\"" : "ESM \"import\""} package condition, but the AOT build plugin was loaded through ${loadedModuleCondition === "cjs" ? "CommonJS \"require\"" : "ESM \"import\""}; entry: ${JSON.stringify(resolveEntry(file))}. Load the plugin through ${moduleCondition === "cjs" ? "require()" : "import"} so capture and generated registration share one Elysia module instance.`);
421
450
  const previousAotBuild = process.env.ELYSIA_AOT_BUILD;
@@ -430,6 +459,8 @@ async function generateCompiledArtifacts(file, options, moduleCondition = resolv
430
459
  _importedEntries.add(entryReal);
431
460
  const mod = await import(entry);
432
461
  const isApp = (value) => typeof value?.compile === "function";
462
+ await Promise.allSettled(Object.values(mod).filter(isApp).map((app) => app.modules));
463
+ abortCapture();
433
464
  let app = isApp(mod.app) ? mod.app : mod.default;
434
465
  if (!isApp(app)) {
435
466
  const names = Object.keys(mod).filter((name) => isApp(mod[name]));
@@ -437,8 +468,22 @@ async function generateCompiledArtifacts(file, options, moduleCondition = resolv
437
468
  app = names[0] ? mod[names[0]] : void 0;
438
469
  }
439
470
  if (!isApp(app)) throw new Error(`[elysia-aot] "${entry}" must export an Elysia app`);
440
- const typedApp = app;
441
- assertNoMount(typedApp, entry);
471
+ const primary = app;
472
+ const apps = [primary];
473
+ const exportOf = new Map([[manifestKey(primary), Object.keys(mod).find((name) => mod[name] === app)]]);
474
+ for (const name of Object.keys(mod)) {
475
+ const other = mod[name];
476
+ const key = isApp(other) && !apps.includes(other) && manifestKey(other);
477
+ if (!key || !other["~routes"].length) continue;
478
+ if (exportOf.has(key)) throw new Error(`[elysia-aot] "${entry}" exports two Elysia apps named "${key}" (${exportOf.get(key)}, ${name}). Each AOT manifest is keyed by app name, rename one`);
479
+ exportOf.set(key, name);
480
+ apps.push(other);
481
+ }
482
+ if (apps.length > 1 && !manifestKey(primary)) {
483
+ const unnamed = exportOf.get("");
484
+ const named = [...exportOf.values()].slice(1).map((name) => `\`${name}\``).join(", ");
485
+ throw new Error(`[elysia-aot] "${entry}" exports \`${unnamed}\` with no name next to named Elysia apps (${named}): name it (new Elysia({ name: '${unnamed}' })), or stop exporting ${named}`);
486
+ }
442
487
  const sourceOptions = {
443
488
  moduleCondition,
444
489
  registerFrom: options?.registerFrom,
@@ -450,8 +495,90 @@ async function generateCompiledArtifacts(file, options, moduleCondition = resolv
450
495
  const adapterStub = options?.target === "bun" ? "bun" : options?.target === "node" || options?.target === "workerd" ? "web-standard" : false;
451
496
  const productionStub = options?.production !== false;
452
497
  const exactMirror = resolveExactMirror(entry);
498
+ const analyze = (typedApp, artifacts) => {
499
+ const report = replayStubbability(typedApp, artifacts.handlers, options?.target);
500
+ const aliases = /* @__PURE__ */ new Set();
501
+ for (const handler of artifacts.handlers) if (handler.alias) for (const name of handler.alias.split(",")) aliases.add(isResponseParam(name) ? "va" : name);
502
+ const history = typedApp["~routes"];
503
+ const hasWS = !!typedApp["~hasWS"] || history.some((route) => route[0] === "WS");
504
+ const mayTrace = !!typedApp["~hasTrace"] || history.some((route) => (route?.[4])?.trace?.length || route?.[2]?.["~mount"]);
505
+ const expectedSlots = [];
506
+ const declaredTypeBoxSlots = /* @__PURE__ */ new Set();
507
+ let routesForbidSeal = false;
508
+ let wsCookie = false;
509
+ for (const route of history) {
510
+ const method = route[0];
511
+ const path = route[1];
512
+ const expectTypeBoxSlot = (slot) => {
513
+ const identity = {
514
+ method,
515
+ path,
516
+ slot
517
+ };
518
+ const key = validatorSlotKey(identity);
519
+ if (declaredTypeBoxSlots.has(key)) routesForbidSeal = true;
520
+ else {
521
+ declaredTypeBoxSlots.add(key);
522
+ expectedSlots.push(identity);
523
+ }
524
+ };
525
+ const [, , , instance, hook, appHook, inheritedChain, macroScope] = route;
526
+ const hooks = composeRouteHook(instance, hook, appHook, inheritedChain, typedApp, macroScope);
527
+ runIntrospect(hooks);
528
+ if (method === "WS" && (hook?.cookie !== void 0 || hooks?.cookie !== void 0)) wsCookie = true;
529
+ if (!hooks) continue;
530
+ let routeHasTypeBoxDirectSlot = false;
531
+ const classify = (schema, slot) => {
532
+ if (schema === void 0) {
533
+ routesForbidSeal = true;
534
+ return;
535
+ }
536
+ if (isStandardSchema(schema)) return;
537
+ routeHasTypeBoxDirectSlot = true;
538
+ expectTypeBoxSlot(slot);
539
+ };
540
+ for (const slot of REQUEST_SLOTS) {
541
+ const value = hooks[slot];
542
+ if (value !== void 0) classify(resolveModelRef(value, typedApp), slot);
543
+ }
544
+ if (hooks.response !== void 0) {
545
+ const response = resolveModelRef(hooks.response, typedApp);
546
+ if (isResponseMap(response)) for (const status in response) classify(resolveModelRef(response[status], typedApp), `response:${status}`);
547
+ else classify(response, "response:200");
548
+ }
549
+ const mergeSchemas = hooks.schemas;
550
+ if (Array.isArray(mergeSchemas) && mergeSchemas.length > 0) {
551
+ if (routeHasTypeBoxDirectSlot || !mergeSchemasAllStandard(mergeSchemas)) routesForbidSeal = true;
552
+ }
553
+ }
554
+ if (typedApp["~config"]?.normalize === "typebox") routesForbidSeal = true;
555
+ const validatorSlotsMatch = validatorSlotSetsMatch(expectedSlots, artifacts.validators);
556
+ const hasReplayableCapture = artifacts.handlers.some((h) => h.code) || artifacts.validators.length > 0;
557
+ const plan = planFromReport(strip, report, hasWS, mayTrace, aliases, hasReplayableCapture && !routesForbidSeal && validatorSlotsMatch && artifacts.validators.every((v) => v.bridgeFree === true), !hasReplayableCapture, adapterStub, productionStub, wsCookie, exactMirror, artifacts.key);
558
+ if (options?.target === "workerd") {
559
+ if (!report.jit) throw new Error(`[elysia-aot] target 'workerd' but handler JIT is still reachable${artifacts.key && ` in app "${artifacts.key}"`} (${report.reasons.join(", ") || "unknown"}). Every route must be captured into the AOT manifest.`);
560
+ if (!validatorSlotsMatch) console.warn("[elysia-aot] target 'workerd': captured validator slots do not exactly match declared slots; unfrozen slots compile at runtime and will fail on workerd.");
561
+ }
562
+ return plan;
563
+ };
564
+ const captured = [];
565
+ const plans = [];
566
+ for (const each of apps) {
567
+ let artifacts;
568
+ try {
569
+ artifacts = await captureArtifacts(each, sourceOptions);
570
+ } catch (error) {
571
+ if (each === primary) throw error;
572
+ const key = manifestKey(each);
573
+ console.warn(`[elysia-aot] export \`${exportOf.get(key)}\` (app "${key}") gets no AOT manifest, its capture failed: ${error.message}`);
574
+ continue;
575
+ }
576
+ captured.push(artifacts);
577
+ if (strip !== false) plans.push(analyze(each, artifacts));
578
+ }
579
+ const source = captured.length > 1 ? emitModule(captured, captured[0].fingerprint, sourceOptions) : captured[0].source;
453
580
  if (strip === false) return {
454
- source: await compileToSource(typedApp, sourceOptions),
581
+ source,
455
582
  stub: {
456
583
  ...NO_STUB,
457
584
  typeboxValue: true,
@@ -461,76 +588,12 @@ async function generateCompiledArtifacts(file, options, moduleCondition = resolv
461
588
  },
462
589
  mode: "off"
463
590
  };
464
- const artifacts = await captureArtifacts(typedApp, sourceOptions);
465
- const report = replayStubbability(typedApp, artifacts.handlers, options?.target);
466
- const aliases = /* @__PURE__ */ new Set();
467
- for (const handler of artifacts.handlers) if (handler.alias) for (const name of handler.alias.split(",")) aliases.add(isResponseParam(name) ? "va" : name);
468
- const history = typedApp["~routes"];
469
- const hasWS = !!typedApp["~hasWS"] || history.some((route) => route[0] === "WS");
470
- const mayTrace = !!typedApp["~hasTrace"] || history.some((route) => (route?.[4])?.trace?.length || route?.[2]?.["~mount"]);
471
- const expectedSlots = [];
472
- const declaredTypeBoxSlots = /* @__PURE__ */ new Set();
473
- let routesForbidSeal = false;
474
- let wsCookie = false;
475
- for (const route of history) {
476
- const method = route[0];
477
- const path = route[1];
478
- const expectTypeBoxSlot = (slot) => {
479
- const identity = {
480
- method,
481
- path,
482
- slot
483
- };
484
- const key = validatorSlotKey(identity);
485
- if (declaredTypeBoxSlots.has(key)) routesForbidSeal = true;
486
- else {
487
- declaredTypeBoxSlots.add(key);
488
- expectedSlots.push(identity);
489
- }
490
- };
491
- const [, , , instance, hook, appHook, inheritedChain, macroScope] = route;
492
- const hooks = composeRouteHook(instance, hook, appHook, inheritedChain, typedApp, macroScope);
493
- runIntrospect(hooks);
494
- if (method === "WS" && (hook?.cookie !== void 0 || hooks?.cookie !== void 0)) wsCookie = true;
495
- if (!hooks) continue;
496
- let routeHasTypeBoxDirectSlot = false;
497
- const classify = (schema, slot) => {
498
- if (schema === void 0) {
499
- routesForbidSeal = true;
500
- return;
501
- }
502
- if (isStandardSchema(schema)) return;
503
- routeHasTypeBoxDirectSlot = true;
504
- expectTypeBoxSlot(slot);
505
- };
506
- for (const slot of REQUEST_SLOTS) {
507
- const value = hooks[slot];
508
- if (value !== void 0) classify(resolveModelRef(value, typedApp), slot);
509
- }
510
- if (hooks.response !== void 0) {
511
- const response = resolveModelRef(hooks.response, typedApp);
512
- if (isResponseMap(response)) for (const status in response) classify(resolveModelRef(response[status], typedApp), `response:${status}`);
513
- else classify(response, "response:200");
514
- }
515
- const mergeSchemas = hooks.schemas;
516
- if (Array.isArray(mergeSchemas) && mergeSchemas.length > 0) {
517
- if (routeHasTypeBoxDirectSlot || !mergeSchemasAllStandard(mergeSchemas)) routesForbidSeal = true;
518
- }
519
- }
520
- if (typedApp["~config"]?.normalize === "typebox") routesForbidSeal = true;
521
- const validatorSlotsMatch = validatorSlotSetsMatch(expectedSlots, artifacts.validators);
522
- const hasReplayableCapture = artifacts.handlers.some((h) => h.code) || artifacts.validators.length > 0;
523
- const { plan: stub, mode } = planFromReport(strip, report, hasWS, mayTrace, aliases, hasReplayableCapture && !routesForbidSeal && validatorSlotsMatch && artifacts.validators.every((v) => v.bridgeFree === true), !hasReplayableCapture, adapterStub, productionStub, wsCookie, exactMirror);
524
- if (options?.target === "workerd") {
525
- 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.`);
526
- if (!validatorSlotsMatch) console.warn("[elysia-aot] target 'workerd': captured validator slots do not exactly match declared slots; unfrozen slots compile at runtime and will fail on workerd.");
527
- }
528
- const virtualType = mode === "off" ? void 0 : await generateVirtualType(moduleCondition);
591
+ const { plan: stub, mode } = mergePlans(plans, exactMirror);
529
592
  return {
530
- source: artifacts.source,
593
+ source,
531
594
  stub,
532
595
  mode,
533
- virtualType
596
+ virtualType: mode === "off" ? void 0 : await generateVirtualType(moduleCondition)
534
597
  };
535
598
  } finally {
536
599
  if (previousAotBuild === void 0) delete process.env.ELYSIA_AOT_BUILD;
@@ -549,4 +612,4 @@ const realPath = (path) => {
549
612
  };
550
613
 
551
614
  //#endregion
552
- export { ADAPTER_BUN_FILTER, ADAPTER_CONSTANTS_FILTER, ELYSIA_MODULE_FILTER, EXACT_MIRROR_REQUIRE_FILTER, IS_PRODUCTION_FILTER, NO_STUB, OVERRIDE_MAP, SOURCE_REGEX, STUB_SOURCES, TYPEBOX_REQUIRE_FILTER, TYPEBOX_SYSTEM_LITE_FILTER, TYPEBOX_TYPE_FILTER, adapterConstantsSource, alignStubExtensions, bunAdapterStubSource, generateCompiledArtifacts, generateCompiledArtifactsIsolated, generateVirtualType, makeIsElysiaModule, planFromReport, realPath, resolveElysiaRoot, resolveEntry, resolveEntryModuleKind, resolveExactMirror, rewriteIsProductionCalls, siblingModuleExt, validatorSlotSetsMatch };
615
+ export { ADAPTER_BUN_FILTER, ADAPTER_CONSTANTS_FILTER, ELYSIA_MODULE_FILTER, EXACT_MIRROR_REQUIRE_FILTER, IS_PRODUCTION_FILTER, NO_STUB, OVERRIDE_MAP, SOURCE_REGEX, STUB_SOURCES, TYPEBOX_REQUIRE_FILTER, TYPEBOX_SYSTEM_LITE_FILTER, TYPEBOX_TYPE_FILTER, adapterConstantsSource, alignStubExtensions, bunAdapterStubSource, generateCompiledArtifacts, generateCompiledArtifactsIsolated, generateVirtualType, makeIsElysiaModule, mergePlans, planFromReport, realPath, resolveElysiaRoot, resolveEntry, resolveEntryModuleKind, resolveExactMirror, rewriteIsProductionCalls, siblingModuleExt, validatorSlotSetsMatch };
@@ -12,13 +12,18 @@ interface CompileToSourceOptions extends Pick<ElysiaAotOptions, 'registerFrom' |
12
12
  }
13
13
  declare const autoGroupSize: (routes: number) => number;
14
14
  declare function compileToSource(app: AnyElysia, options?: CompileToSourceOptions): Promise<string>;
15
+ /** An app claims the manifest registered under its `name`, see `base.ts` */
16
+ declare const manifestKey: (app: AnyElysia) => string;
15
17
  interface CapturedArtifacts {
16
18
  source: string;
19
+ key: string;
17
20
  validators: CapturedValidator[];
18
21
  handlers: CapturedHandler[];
19
22
  fingerprint: AotFingerprint;
20
23
  }
21
24
  declare function captureArtifacts(app: AnyElysia, options?: CompileToSourceOptions): Promise<CapturedArtifacts>;
22
25
  declare function replayStubbability(app: AnyElysia, handlers: CapturedHandler[], target?: AotTarget): JITProbeResult;
26
+ /** The manifest module: shared imports, then one registration per app key */
27
+ declare function emitModule(apps: Pick<CapturedArtifacts, 'key' | 'validators' | 'handlers'>[], fingerprint: AotFingerprint, options: CompileToSourceOptions | undefined): string;
23
28
  //#endregion
24
- export { AotModuleCondition, AotTarget, CapturedArtifacts, CompileToSourceOptions, autoGroupSize, captureArtifacts, compileToSource, replayStubbability };
29
+ export { AotModuleCondition, AotTarget, CapturedArtifacts, CompileToSourceOptions, autoGroupSize, captureArtifacts, compileToSource, emitModule, manifestKey, replayStubbability };
@@ -14,19 +14,29 @@ const autoGroupSize = (routes) => routes < 64 ? 1 : routes < 256 ? 2 : routes <
14
14
  async function compileToSource(app, options) {
15
15
  return (await captureArtifacts(app, options)).source;
16
16
  }
17
+ const manifestKey = (app) => app["~config"]?.name || "";
17
18
  async function captureArtifacts(app, options) {
18
19
  const previousAotBuild = require_universal_env.env.ELYSIA_AOT_BUILD;
19
20
  require_universal_env.env.ELYSIA_AOT_BUILD = "1";
20
21
  try {
21
22
  require_compile_aot_capture.beginValidatorCapture();
22
23
  await app.modules;
24
+ const session = require_compile_aot.CompilerState.session;
25
+ session?.capture?.clear();
26
+ session?.handlerCapture?.clear();
23
27
  if (options?.target !== void 0) require_compile_handler_jit.setCaptureHeaderShorthand(options.target === "bun");
24
28
  app.compile();
25
29
  const captured = require_compile_aot_capture.endValidatorCapture();
26
30
  const handlers = require_compile_aot_capture.endHandlerCapture();
27
31
  const fingerprint = app["~aotFingerprint"] ?? require_compile_aot.createAotFingerprint();
32
+ const key = manifestKey(app);
28
33
  return {
29
- source: emitModule(captured, handlers, fingerprint, options),
34
+ source: emitModule([{
35
+ key,
36
+ validators: captured,
37
+ handlers
38
+ }], fingerprint, options),
39
+ key,
30
40
  validators: captured,
31
41
  handlers,
32
42
  fingerprint
@@ -193,7 +203,7 @@ function entryParts(c, enc) {
193
203
  }
194
204
  return parts;
195
205
  }
196
- function emitModule(captured, handlers, fingerprint, options) {
206
+ function emitRegistration(captured, handlers, options) {
197
207
  const enc = createEntryEncoder();
198
208
  const treeToSource = (tree) => {
199
209
  const slotRef = /* @__PURE__ */ new Map();
@@ -395,23 +405,33 @@ function emitModule(captured, handlers, fingerprint, options) {
395
405
  handlerExport += " },\n";
396
406
  }
397
407
  handlerExport += "}\n";
408
+ return {
409
+ hasCoercePlan: enc.hasCoercePlan,
410
+ generated: enc.branchDecls + enc.unionDecls + validatorDecls + handlerDecls,
411
+ iife: "(() => {\n" + enc.branchDecls + (enc.branchDecls && "\n") + enc.unionDecls + (enc.unionDecls && "\n") + validatorDecls + handlerDecls + "\n" + validatorExport + "\n" + handlerExport + "\nreturn { fingerprint, " + (lazy ? "lazyGroups: _groups, lazyGroupOf: _groupOf, " : "validators, ") + `handlers${enc.hasCoercePlan ? ", planRebuilder: buildCoercedFromPlan" : ""} }\n})()`
412
+ };
413
+ }
414
+ function emitModule(apps, fingerprint, options) {
415
+ const parts = apps.map((app) => emitRegistration(app.validators, app.handlers, options));
416
+ const hasCaptured = apps.some((app) => app.validators.length);
398
417
  let body = "// Generated by Elysia build plugin. Do not edit.\n";
399
418
  const moduleCondition = options?.moduleCondition ?? "esm";
400
419
  const importNamed = (name, specifier) => moduleCondition === "cjs" ? `const { ${name} } = require(${JSON.stringify(specifier)})\n` : `import { ${name} } from ${JSON.stringify(specifier)}\n`;
401
420
  body += importNamed("Compiled", options?.registerFrom ?? "elysia");
402
- if (enc.hasCoercePlan) body += importNamed("buildCoercedFromPlan", "elysia/coerce-plan");
403
- if (captured.length) body += importNamed("Reconstruct", options?.reconstructFrom ?? "elysia/reconstruct");
404
- const generated = enc.branchDecls + enc.unionDecls + validatorDecls + handlerDecls;
405
- const needs = (symbol) => new RegExp(`\\b${symbol}\\b`).test(generated);
421
+ if (parts.some((part) => part.hasCoercePlan)) body += importNamed("buildCoercedFromPlan", "elysia/coerce-plan");
422
+ if (hasCaptured) body += importNamed("Reconstruct", options?.reconstructFrom ?? "elysia/reconstruct");
423
+ const needs = (symbol) => {
424
+ const pattern = new RegExp(`\\b${symbol}\\b`);
425
+ return parts.some((part) => pattern.test(part.generated));
426
+ };
406
427
  if (needs("CheckContext")) body += importNamed("CheckContext", "typebox/schema");
407
428
  if (needs("Guard")) body += importNamed("Guard", "typebox/guard");
408
429
  if (needs("Format")) body += importNamed("Format", "typebox/format");
409
430
  if (needs("Hashing")) body += importNamed("Hashing", "typebox/system");
410
431
  body += "\n";
411
- if (captured.length) body += "Compiled.reconstruct = Reconstruct\n";
412
- body += `export const fingerprint = ${JSON.stringify(fingerprint)}\nCompiled.register((() => {
413
- ` + enc.branchDecls + (enc.branchDecls && "\n") + enc.unionDecls + (enc.unionDecls && "\n") + validatorDecls + handlerDecls + "\n" + validatorExport + "\n" + handlerExport + "\nreturn { fingerprint, " + (lazy ? "lazyGroups: _groups, lazyGroupOf: _groupOf, " : "validators, ") + `handlers${enc.hasCoercePlan ? ", planRebuilder: buildCoercedFromPlan" : ""} }\n})())
414
- `;
432
+ if (hasCaptured) body += "Compiled.reconstruct = Reconstruct\n";
433
+ body += `export const fingerprint = ${JSON.stringify(fingerprint)}\n`;
434
+ for (let i = 0; i < parts.length; i++) body += `Compiled.register(${parts[i].iife}${apps[i].key ? ", " + JSON.stringify(apps[i].key) : ""})\n`;
415
435
  return body;
416
436
  }
417
437
 
@@ -419,4 +439,6 @@ function emitModule(captured, handlers, fingerprint, options) {
419
439
  exports.autoGroupSize = autoGroupSize;
420
440
  exports.captureArtifacts = captureArtifacts;
421
441
  exports.compileToSource = compileToSource;
442
+ exports.emitModule = emitModule;
443
+ exports.manifestKey = manifestKey;
422
444
  exports.replayStubbability = replayStubbability;
@@ -1,6 +1,6 @@
1
1
  import { nullObject } from "../../utils.mjs";
2
2
  import { env } from "../../universal/env.mjs";
3
- import { Compiled, createAotFingerprint } from "../../compile/aot.mjs";
3
+ import { Compiled, CompilerState, createAotFingerprint } from "../../compile/aot.mjs";
4
4
  import { Validator } from "../../validator/index.mjs";
5
5
  import { JITProbe } from "../../compile/jit-probe.mjs";
6
6
  import { setCaptureHeaderShorthand } from "../../compile/handler/jit.mjs";
@@ -13,19 +13,29 @@ const autoGroupSize = (routes) => routes < 64 ? 1 : routes < 256 ? 2 : routes <
13
13
  async function compileToSource(app, options) {
14
14
  return (await captureArtifacts(app, options)).source;
15
15
  }
16
+ const manifestKey = (app) => app["~config"]?.name || "";
16
17
  async function captureArtifacts(app, options) {
17
18
  const previousAotBuild = env.ELYSIA_AOT_BUILD;
18
19
  env.ELYSIA_AOT_BUILD = "1";
19
20
  try {
20
21
  beginValidatorCapture();
21
22
  await app.modules;
23
+ const session = CompilerState.session;
24
+ session?.capture?.clear();
25
+ session?.handlerCapture?.clear();
22
26
  if (options?.target !== void 0) setCaptureHeaderShorthand(options.target === "bun");
23
27
  app.compile();
24
28
  const captured = endValidatorCapture();
25
29
  const handlers = endHandlerCapture();
26
30
  const fingerprint = app["~aotFingerprint"] ?? createAotFingerprint();
31
+ const key = manifestKey(app);
27
32
  return {
28
- source: emitModule(captured, handlers, fingerprint, options),
33
+ source: emitModule([{
34
+ key,
35
+ validators: captured,
36
+ handlers
37
+ }], fingerprint, options),
38
+ key,
29
39
  validators: captured,
30
40
  handlers,
31
41
  fingerprint
@@ -192,7 +202,7 @@ function entryParts(c, enc) {
192
202
  }
193
203
  return parts;
194
204
  }
195
- function emitModule(captured, handlers, fingerprint, options) {
205
+ function emitRegistration(captured, handlers, options) {
196
206
  const enc = createEntryEncoder();
197
207
  const treeToSource = (tree) => {
198
208
  const slotRef = /* @__PURE__ */ new Map();
@@ -394,25 +404,35 @@ function emitModule(captured, handlers, fingerprint, options) {
394
404
  handlerExport += " },\n";
395
405
  }
396
406
  handlerExport += "}\n";
407
+ return {
408
+ hasCoercePlan: enc.hasCoercePlan,
409
+ generated: enc.branchDecls + enc.unionDecls + validatorDecls + handlerDecls,
410
+ iife: "(() => {\n" + enc.branchDecls + (enc.branchDecls && "\n") + enc.unionDecls + (enc.unionDecls && "\n") + validatorDecls + handlerDecls + "\n" + validatorExport + "\n" + handlerExport + "\nreturn { fingerprint, " + (lazy ? "lazyGroups: _groups, lazyGroupOf: _groupOf, " : "validators, ") + `handlers${enc.hasCoercePlan ? ", planRebuilder: buildCoercedFromPlan" : ""} }\n})()`
411
+ };
412
+ }
413
+ function emitModule(apps, fingerprint, options) {
414
+ const parts = apps.map((app) => emitRegistration(app.validators, app.handlers, options));
415
+ const hasCaptured = apps.some((app) => app.validators.length);
397
416
  let body = "// Generated by Elysia build plugin. Do not edit.\n";
398
417
  const moduleCondition = options?.moduleCondition ?? "esm";
399
418
  const importNamed = (name, specifier) => moduleCondition === "cjs" ? `const { ${name} } = require(${JSON.stringify(specifier)})\n` : `import { ${name} } from ${JSON.stringify(specifier)}\n`;
400
419
  body += importNamed("Compiled", options?.registerFrom ?? "elysia");
401
- if (enc.hasCoercePlan) body += importNamed("buildCoercedFromPlan", "elysia/coerce-plan");
402
- if (captured.length) body += importNamed("Reconstruct", options?.reconstructFrom ?? "elysia/reconstruct");
403
- const generated = enc.branchDecls + enc.unionDecls + validatorDecls + handlerDecls;
404
- const needs = (symbol) => new RegExp(`\\b${symbol}\\b`).test(generated);
420
+ if (parts.some((part) => part.hasCoercePlan)) body += importNamed("buildCoercedFromPlan", "elysia/coerce-plan");
421
+ if (hasCaptured) body += importNamed("Reconstruct", options?.reconstructFrom ?? "elysia/reconstruct");
422
+ const needs = (symbol) => {
423
+ const pattern = new RegExp(`\\b${symbol}\\b`);
424
+ return parts.some((part) => pattern.test(part.generated));
425
+ };
405
426
  if (needs("CheckContext")) body += importNamed("CheckContext", "typebox/schema");
406
427
  if (needs("Guard")) body += importNamed("Guard", "typebox/guard");
407
428
  if (needs("Format")) body += importNamed("Format", "typebox/format");
408
429
  if (needs("Hashing")) body += importNamed("Hashing", "typebox/system");
409
430
  body += "\n";
410
- if (captured.length) body += "Compiled.reconstruct = Reconstruct\n";
411
- body += `export const fingerprint = ${JSON.stringify(fingerprint)}\nCompiled.register((() => {
412
- ` + enc.branchDecls + (enc.branchDecls && "\n") + enc.unionDecls + (enc.unionDecls && "\n") + validatorDecls + handlerDecls + "\n" + validatorExport + "\n" + handlerExport + "\nreturn { fingerprint, " + (lazy ? "lazyGroups: _groups, lazyGroupOf: _groupOf, " : "validators, ") + `handlers${enc.hasCoercePlan ? ", planRebuilder: buildCoercedFromPlan" : ""} }\n})())
413
- `;
431
+ if (hasCaptured) body += "Compiled.reconstruct = Reconstruct\n";
432
+ body += `export const fingerprint = ${JSON.stringify(fingerprint)}\n`;
433
+ for (let i = 0; i < parts.length; i++) body += `Compiled.register(${parts[i].iife}${apps[i].key ? ", " + JSON.stringify(apps[i].key) : ""})\n`;
414
434
  return body;
415
435
  }
416
436
 
417
437
  //#endregion
418
- export { autoGroupSize, captureArtifacts, compileToSource, replayStubbability };
438
+ export { autoGroupSize, captureArtifacts, compileToSource, emitModule, manifestKey, replayStubbability };
@@ -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<2 | 1 | 6 | 3 | 10 | 11 | 13 | 14>;
20
+ declare const primitiveElysiaTypes: Set<6 | 1 | 2 | 3 | 10 | 11 | 13 | 14>;
21
21
  declare const noEnumerable: {
22
22
  readonly enumerable: false;
23
23
  };