@supacloud/elysia 0.38.1 → 0.39.0

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/index.js CHANGED
@@ -2054,6 +2054,8 @@ var IDEMPOTENCY_KEY_HEADER = "idempotency-key";
2054
2054
  var idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,512}$/;
2055
2055
  function composeAspects(...aspects) {
2056
2056
  const active = aspects.filter((aspect) => typeof aspect === "function");
2057
+ if (active.length === 0)
2058
+ return (_context, next) => next();
2057
2059
  return (context, next) => {
2058
2060
  let index = -1;
2059
2061
  const dispatch = (current) => {
@@ -2231,6 +2233,9 @@ function safeHeaderValue(value, maxLength) {
2231
2233
  function isRecord2(value) {
2232
2234
  return value !== null && typeof value === "object" && !Array.isArray(value);
2233
2235
  }
2236
+ function isPromiseLike(value) {
2237
+ return value instanceof Promise;
2238
+ }
2234
2239
  function isTrustedIdentity(value) {
2235
2240
  return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2236
2241
  }
@@ -2461,14 +2466,18 @@ async function previewCompiledCommand(options) {
2461
2466
  }
2462
2467
  function once(next) {
2463
2468
  let called = false;
2464
- return async () => {
2469
+ return () => {
2465
2470
  if (called) {
2466
- throw new ApplicationError("Command continuation called multiple times", {
2471
+ return Promise.reject(new ApplicationError("Command continuation called multiple times", {
2467
2472
  code: "COMMAND_CONTINUATION_REUSED"
2468
- });
2473
+ }));
2469
2474
  }
2470
2475
  called = true;
2471
- return await next();
2476
+ try {
2477
+ return next();
2478
+ } catch (error) {
2479
+ return Promise.reject(error);
2480
+ }
2472
2481
  };
2473
2482
  }
2474
2483
  function requireTrustedIdentity(requestContext) {
@@ -2609,6 +2618,9 @@ function joinPaths(prefix, path) {
2609
2618
  function controllerInstance(value) {
2610
2619
  return isRecord2(value) ? value : undefined;
2611
2620
  }
2621
+ function canUseDirectRoute(compiled, controller, route) {
2622
+ return route.executionMode === "direct" && route.directInvoker !== undefined && controller.scope === "application" && compiled.createRequestScope === undefined && compiled.aspectPipeline === undefined && (compiled.aspects?.length ?? 0) === 0 && route.aspectPipeline === undefined && (route.aspects?.length ?? 0) === 0 && route.command === undefined && route.effect === undefined && route.responses === undefined;
2623
+ }
2612
2624
  function cookieValues(value) {
2613
2625
  if (!isRecord2(value))
2614
2626
  return;
@@ -2647,6 +2659,9 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2647
2659
  "nativeResponse",
2648
2660
  "invoker",
2649
2661
  "effect",
2662
+ "directInvoker",
2663
+ "directInvokerFast",
2664
+ "executionMode",
2650
2665
  "command",
2651
2666
  "aspects",
2652
2667
  "aspectPipeline",
@@ -2663,8 +2678,15 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2663
2678
  "parse",
2664
2679
  "allowDeleteBody"
2665
2680
  ]);
2681
+ const pendingRoutes = new Map;
2666
2682
  for (const controller of compiled.controllers) {
2667
2683
  for (const route of controller.routes) {
2684
+ if (pendingRoutes.has(route)) {
2685
+ throw new ApplicationError(`Duplicate route descriptor in module "${compiled.name}". Recompile the application.`, {
2686
+ code: "COMPILED_ROUTE_REGISTRATION_INVALID"
2687
+ });
2688
+ }
2689
+ pendingRoutes.set(route, { controller, path: joinPaths(controller.path, route.path) });
2668
2690
  const unsupported = Object.keys(route).filter((field) => !supportedFields.has(field));
2669
2691
  if (!supportedMethods.has(route.method) || unsupported.length > 0) {
2670
2692
  throw new ApplicationError(`Unsupported compiled route ${route.method} ${controller.path}${route.path}` + (unsupported.length > 0 ? `: ${unsupported.join(", ")}` : ""), { code: "ROUTE_DESCRIPTOR_UNSUPPORTED" });
@@ -2680,11 +2702,15 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2680
2702
  }
2681
2703
  }
2682
2704
  }
2705
+ if ((compiled.controllers.some((controller) => controller.routes.length > 0) || compiled.registerRoutes !== undefined) && typeof compiled.registerRoutes !== "function") {
2706
+ throw new ApplicationError(`Module "${compiled.name}" requires a compiler-emitted registerRoutes plan. Upgrade @supacloud/compiler with @supacloud/elysia and recompile the application.`, { code: "COMPILED_ROUTE_REGISTRATION_REQUIRED" });
2707
+ }
2683
2708
  const hasCommandRoutes = compiled.controllers.some((controller) => controller.routes.some((route) => route.command !== undefined));
2684
2709
  if (hasCommandRoutes && !options.commandGovernance && !options.commandExecutor) {
2685
2710
  throw new ApplicationError(`Module "${compiled.name}" has command routes but no commandGovernance`, { code: "COMMAND_GOVERNANCE_UNCONFIGURED" });
2686
2711
  }
2687
2712
  assertCommandGovernanceReady(compiled, options.commandGovernance, options.commandExecutor);
2713
+ const commandsByClassName = new Map((compiled.commands ?? []).map((command) => [command.className, command]));
2688
2714
  for (const controller of compiled.controllers) {
2689
2715
  for (const route of controller.routes) {
2690
2716
  const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
@@ -2707,7 +2733,12 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2707
2733
  const requestCompletions = new WeakMap;
2708
2734
  const governanceExecutor = options.commandGovernance ? createCommandExecutor(options.commandGovernance, options.onExecution) : undefined;
2709
2735
  const commandExecutor = options.commandExecutor && governanceExecutor ? composeCommandExecutors(options.commandExecutor, governanceExecutor) : options.commandExecutor ?? governanceExecutor;
2710
- const plugin = mountHttp(options.http, `supacloud:${compiled.name}`, options.normalize ?? true).derive(async (context) => {
2736
+ const modulePipeline = descriptorPipeline(compiled, `module:${compiled.name}`, options.onExecution);
2737
+ const needsRequestState = ctxFactory !== defaultRequestContext || pendingWork !== undefined || options.httpPolicies !== undefined || options.onExecution !== undefined || compiled.createRequestScope !== undefined || compiled.aspectPipeline !== undefined || (compiled.aspects?.length ?? 0) > 0 || options.errorMapper !== undefined || compiled.controllers.some((controller) => controller.routes.some((route) => !canUseDirectRoute(compiled, controller, route)));
2738
+ const basePlugin = mountHttp(options.http, `supacloud:${compiled.name}`, options.normalize ?? true);
2739
+ const servicesContext = { services };
2740
+ const servicesPlugin = basePlugin.derive(() => servicesContext);
2741
+ const plugin = needsRequestState ? servicesPlugin.derive((context) => {
2711
2742
  if (pendingWork?.closed)
2712
2743
  throw new ApplicationError("Application is stopping", { status: 503, code: "APPLICATION_STOPPING" });
2713
2744
  let complete;
@@ -2721,25 +2752,29 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2721
2752
  if (complete)
2722
2753
  requestCompletions.set(context.request, complete);
2723
2754
  const signal = pendingWork ? AbortSignal.any([context.request.signal, pendingWork.signal]) : context.request.signal;
2724
- const requestContext = await ctxFactory(context.request, context, signal);
2725
- requestContexts.set(context.request, requestContext);
2726
- return { services, requestContext };
2727
- });
2755
+ const finish = (requestContext) => {
2756
+ requestContexts.set(context.request, requestContext);
2757
+ return { requestContext };
2758
+ };
2759
+ const requestContext = ctxFactory(context.request, context, signal);
2760
+ return isPromiseLike(requestContext) ? requestContext.then(finish) : finish(requestContext);
2761
+ }) : servicesPlugin;
2728
2762
  const createRequestScope = compiled.createRequestScope;
2729
2763
  const requestScopes = new WeakMap;
2730
- plugin.onAfterResponse(async ({ request }) => {
2731
- const scope = requestScopes.get(request);
2732
- requestScopes.delete(request);
2733
- try {
2734
- if (scope)
2735
- await compiled.destroyRequestScope?.(scope);
2736
- } catch (error) {
2737
- console.error(`supacloud: request scope cleanup failed for "${compiled.name}"`, error);
2738
- } finally {
2739
- requestCompletions.get(request)?.();
2740
- requestCompletions.delete(request);
2741
- }
2742
- });
2764
+ if (needsRequestState)
2765
+ plugin.onAfterResponse(async ({ request }) => {
2766
+ const scope = requestScopes.get(request);
2767
+ requestScopes.delete(request);
2768
+ try {
2769
+ if (scope)
2770
+ await compiled.destroyRequestScope?.(scope);
2771
+ } catch (error) {
2772
+ console.error(`supacloud: request scope cleanup failed for "${compiled.name}"`, error);
2773
+ } finally {
2774
+ requestCompletions.get(request)?.();
2775
+ requestCompletions.delete(request);
2776
+ }
2777
+ });
2743
2778
  const mapError = async (error, frameworkCode, request) => {
2744
2779
  const context = {
2745
2780
  request,
@@ -2753,214 +2788,234 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2753
2788
  plugin.onError(SchemaContractError, ({ error, request }) => mapError(error, frameworkErrorCode(error), request));
2754
2789
  plugin.onError(({ error, request }) => mapError(error, frameworkErrorCode(error), request));
2755
2790
  const routeRegistrar = plugin;
2756
- for (const controller of compiled.controllers) {
2757
- for (const route of controller.routes) {
2758
- const path = joinPaths(controller.path, route.path);
2759
- const documentation = route.data?.openapi;
2760
- const hidden = documentation !== null && typeof documentation === "object" && "hide" in documentation && documentation.hide === true;
2761
- const tags = documentation !== null && typeof documentation === "object" && "tags" in documentation && Array.isArray(documentation.tags) ? documentation.tags.filter((tag) => typeof tag === "string") : undefined;
2762
- const schema = {
2763
- ...toElysiaRouteSchema(route),
2764
- ...route.parse === "none" ? { parse: "none" } : {},
2765
- ...route.title || hidden || tags ? { detail: {
2766
- ...route.title ? { summary: route.title } : {},
2767
- ...hidden ? { hide: true } : {},
2768
- ...tags ? { tags } : {}
2769
- } } : {}
2770
- };
2771
- const policies = compileHttpPolicies(route, path, options.httpPolicies);
2772
- if (policies.length > 0) {
2773
- Object.assign(schema, {
2774
- beforeHandle: async (context) => {
2775
- for (const policy of policies) {
2776
- const result = await policy({
2777
- http: context,
2778
- requestContext: requestContexts.get(context.request)
2779
- });
2780
- if (result instanceof Response)
2781
- return result;
2782
- if (result !== undefined) {
2783
- throw new Error("HTTP policies must return Response or undefined");
2784
- }
2785
- }
2786
- if (route.idempotency === "required") {
2787
- requireRouteIdempotencyKey(context.request);
2791
+ const registerRoute = (controller, route, path) => {
2792
+ if (pendingRoutes.get(route)?.controller !== controller || pendingRoutes.get(route)?.path !== path) {
2793
+ throw new ApplicationError(`Invalid static route registration in module "${compiled.name}". Recompile the application.`, {
2794
+ code: "COMPILED_ROUTE_REGISTRATION_INVALID"
2795
+ });
2796
+ }
2797
+ pendingRoutes.delete(route);
2798
+ const documentation = route.data?.openapi;
2799
+ const hidden = documentation !== null && typeof documentation === "object" && "hide" in documentation && documentation.hide === true;
2800
+ const tags = documentation !== null && typeof documentation === "object" && "tags" in documentation && Array.isArray(documentation.tags) ? documentation.tags.filter((tag) => typeof tag === "string") : undefined;
2801
+ const schema = {
2802
+ ...toElysiaRouteSchema(route),
2803
+ ...route.parse === "none" ? { parse: "none" } : {},
2804
+ ...route.title || hidden || tags ? { detail: {
2805
+ ...route.title ? { summary: route.title } : {},
2806
+ ...hidden ? { hide: true } : {},
2807
+ ...tags ? { tags } : {}
2808
+ } } : {}
2809
+ };
2810
+ const policies = compileHttpPolicies(route, path, options.httpPolicies);
2811
+ if (policies.length > 0) {
2812
+ Object.assign(schema, {
2813
+ beforeHandle: async (context) => {
2814
+ for (const policy of policies) {
2815
+ const result = await policy({
2816
+ http: context,
2817
+ requestContext: requestContexts.get(context.request)
2818
+ });
2819
+ if (result instanceof Response)
2820
+ return result;
2821
+ if (result !== undefined) {
2822
+ throw new Error("HTTP policies must return Response or undefined");
2788
2823
  }
2789
2824
  }
2790
- });
2791
- } else if (route.idempotency === "required") {
2792
- Object.assign(schema, {
2793
- beforeHandle: (context) => {
2825
+ if (route.idempotency === "required") {
2794
2826
  requireRouteIdempotencyKey(context.request);
2795
2827
  }
2796
- });
2797
- }
2798
- const responsePolicies = policies.filter((policy) => policy.afterResponse);
2799
- const mappingPolicies = policies.filter((policy) => policy.mapResponse);
2800
- if (mappingPolicies.length > 0) {
2801
- const responseValidators = Validator2.response(schema.response, { normalize: options.normalize ?? true });
2802
- Object.assign(schema, {
2803
- mapResponse: async (context) => {
2804
- let response = context.responseValue;
2805
- let mapped;
2806
- for (const policy of mappingPolicies) {
2807
- const result = await policy.mapResponse({
2808
- http: context,
2809
- requestContext: requestContexts.get(context.request),
2810
- response,
2811
- encodeResponse: async (value) => {
2812
- const validator = responseValidators?.get(responseStatusOf(value, context.set.status));
2813
- if (!validator)
2814
- return value;
2815
- if (!("EncodeFrom" in validator) || typeof validator.EncodeFrom !== "function") {
2816
- throw new ApplicationError("Response validation failed", { code: "RESPONSE_VALIDATION_FAILED" });
2817
- }
2818
- if ("mayReturnPromise" in validator && validator.mayReturnPromise && "From" in validator && typeof validator.From === "function") {
2819
- return await Reflect.apply(validator.From, validator, [value, "response", true]);
2820
- }
2821
- return await Reflect.apply(validator.EncodeFrom, validator, [value, "response"]);
2828
+ }
2829
+ });
2830
+ } else if (route.idempotency === "required") {
2831
+ Object.assign(schema, {
2832
+ beforeHandle: (context) => {
2833
+ requireRouteIdempotencyKey(context.request);
2834
+ }
2835
+ });
2836
+ }
2837
+ const responsePolicies = policies.filter((policy) => policy.afterResponse);
2838
+ const mappingPolicies = policies.filter((policy) => policy.mapResponse);
2839
+ const routePipeline = descriptorPipeline(route, "route", options.onExecution);
2840
+ const command = route.command ? commandsByClassName.get(route.command) : undefined;
2841
+ const commandPipeline = route.command ? descriptorPipeline(command ?? {}, "command", options.onExecution) : undefined;
2842
+ const routeInvoker = route.invoker;
2843
+ if (mappingPolicies.length > 0) {
2844
+ const responseValidators = Validator2.response(schema.response, { normalize: options.normalize ?? true });
2845
+ Object.assign(schema, {
2846
+ mapResponse: async (context) => {
2847
+ let response = context.responseValue;
2848
+ let mapped;
2849
+ for (const policy of mappingPolicies) {
2850
+ const result = await policy.mapResponse({
2851
+ http: context,
2852
+ requestContext: requestContexts.get(context.request),
2853
+ response,
2854
+ encodeResponse: (value) => {
2855
+ const validator = responseValidators?.get(responseStatusOf(value, context.set.status));
2856
+ if (!validator)
2857
+ return value;
2858
+ if (!("EncodeFrom" in validator) || typeof validator.EncodeFrom !== "function") {
2859
+ throw new ApplicationError("Response validation failed", { code: "RESPONSE_VALIDATION_FAILED" });
2860
+ }
2861
+ if ("mayReturnPromise" in validator && validator.mayReturnPromise && "From" in validator && typeof validator.From === "function") {
2862
+ return validator.From.call(validator, value, "response", true);
2822
2863
  }
2823
- });
2824
- if (result !== undefined) {
2825
- if (!(result instanceof Response))
2826
- throw new Error("HTTP response policies must return Response or undefined");
2827
- mapped = result;
2828
- response = result;
2864
+ return validator.EncodeFrom.call(validator, value, "response");
2829
2865
  }
2866
+ });
2867
+ if (result !== undefined) {
2868
+ if (!(result instanceof Response))
2869
+ throw new Error("HTTP response policies must return Response or undefined");
2870
+ mapped = result;
2871
+ response = result;
2830
2872
  }
2831
- return mapped;
2832
2873
  }
2833
- });
2834
- }
2835
- if (responsePolicies.length > 0) {
2836
- Object.assign(schema, {
2837
- afterResponse: async (context) => {
2838
- for (const policy of responsePolicies) {
2839
- await policy.afterResponse({
2840
- http: context,
2841
- requestContext: requestContexts.get(context.request),
2842
- response: context.responseValue
2843
- });
2844
- }
2874
+ return mapped;
2875
+ }
2876
+ });
2877
+ }
2878
+ if (responsePolicies.length > 0) {
2879
+ Object.assign(schema, {
2880
+ afterResponse: async (context) => {
2881
+ for (const policy of responsePolicies) {
2882
+ await policy.afterResponse({
2883
+ http: context,
2884
+ requestContext: requestContexts.get(context.request),
2885
+ response: context.responseValue
2886
+ });
2845
2887
  }
2846
- });
2847
- }
2848
- const handler = async (ctx) => {
2849
- const requestContext = requestContexts.get(ctx.request);
2850
- const execute = async () => {
2851
- const requestScope = createRequestScope ? await createRequestScope(services, requestContext, imported) : undefined;
2852
- if (requestScope && compiled.destroyRequestScope)
2853
- requestScopes.set(ctx.request, requestScope);
2854
- const source = controller.scope === "request" ? requestScope : services;
2855
- const instance = controllerInstance(source?.[controller.serviceKey]);
2856
- const method = instance?.[route.handler];
2857
- if (typeof method !== "function") {
2858
- throw new Error(`supacloud: controller "${controller.serviceKey}" has no handler "${route.handler}" in scope "${controller.scope}"`);
2888
+ }
2889
+ });
2890
+ }
2891
+ const directRoute = canUseDirectRoute(compiled, controller, route) && options.onExecution === undefined && policies.length === 0 && responsePolicies.length === 0 && mappingPolicies.length === 0;
2892
+ const directController = directRoute && route.directInvokerFast !== undefined ? controllerInstance(services[controller.serviceKey]) : undefined;
2893
+ const directMethod = directController?.[route.handler];
2894
+ const directInvokerFast = route.directInvokerFast;
2895
+ const directHandler = directController && typeof directMethod === "function" && directInvokerFast ? (ctx) => directInvokerFast(directController, directMethod, ctx) : (ctx) => route.directInvoker(services[controller.serviceKey], ctx);
2896
+ const handler = directRoute ? directHandler : async (ctx) => {
2897
+ const requestContext = requestContexts.get(ctx.request);
2898
+ const execute = async () => {
2899
+ const requestScope = createRequestScope ? await createRequestScope(services, requestContext, imported) : undefined;
2900
+ if (requestScope && compiled.destroyRequestScope)
2901
+ requestScopes.set(ctx.request, requestScope);
2902
+ const source = controller.scope === "request" ? requestScope : services;
2903
+ const instance = source?.[controller.serviceKey];
2904
+ const normalizedCookie = ctx.cookie === undefined ? undefined : cookieValues(ctx.cookie);
2905
+ const input = {
2906
+ body: ctx.body,
2907
+ params: ctx.params,
2908
+ query: ctx.query,
2909
+ headers: ctx.headers ?? Object.fromEntries(ctx.request.headers.entries()),
2910
+ ...normalizedCookie === undefined ? {} : { cookie: normalizedCookie },
2911
+ context: requestContext,
2912
+ request: ctx.request,
2913
+ ...requestScope ? { scope: requestScope } : {},
2914
+ requestContext
2915
+ };
2916
+ const handlerCall = () => {
2917
+ if (route.invoker)
2918
+ return route.invoker(instance, input);
2919
+ if (!isRecord2(instance))
2920
+ throw new TypeError("Route controller is not an object");
2921
+ const method = instance[route.handler];
2922
+ if (typeof method !== "function")
2923
+ throw new TypeError(`Route handler ${route.handler} is not callable`);
2924
+ return method.call(instance, input);
2925
+ };
2926
+ const invokeHandler = async () => runCompiledEffect(await handlerCall(), route.effect, options.effectRuntime);
2927
+ const invoke = once(() => route.command && options.commandGovernance ? invokeHandler() : options.onExecution ? observeExecution(options.onExecution, {
2928
+ kind: route.command ? "command" : "route",
2929
+ operation: route.command ?? `${route.method} ${path}`,
2930
+ stage: "handler",
2931
+ ...executionTrace(requestContext)
2932
+ }, invokeHandler) : invokeHandler());
2933
+ const routeContext = {
2934
+ kind: "route",
2935
+ name: `${route.method} ${path}`,
2936
+ input,
2937
+ request: ctx.request,
2938
+ requestContext,
2939
+ ...requestScope ? { scope: requestScope } : {},
2940
+ services,
2941
+ metadata: route
2942
+ };
2943
+ const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
2944
+ const commandContext = route.command === undefined ? routeContext : {
2945
+ kind: "command",
2946
+ name: command?.name ?? route.command,
2947
+ input,
2948
+ request: ctx.request,
2949
+ requestContext,
2950
+ ...requestScope ? { scope: requestScope } : {},
2951
+ services,
2952
+ metadata: command ?? route
2953
+ };
2954
+ const invokeRoute = () => modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
2955
+ const invokeCommand = () => {
2956
+ if (!route.command)
2957
+ return invokeRoute();
2958
+ if (!command) {
2959
+ throw new ApplicationError(`Command "${route.command}" is not registered`, {
2960
+ code: "COMMAND_NOT_REGISTERED"
2961
+ });
2859
2962
  }
2860
- const normalizedCookie = ctx.cookie === undefined ? undefined : cookieValues(ctx.cookie);
2861
- const input = {
2862
- body: ctx.body,
2863
- params: ctx.params,
2864
- query: ctx.query,
2865
- headers: ctx.headers ?? Object.fromEntries(ctx.request.headers.entries()),
2866
- ...normalizedCookie === undefined ? {} : { cookie: normalizedCookie },
2867
- context: requestContext,
2868
- request: ctx.request,
2869
- ...requestScope ? { scope: requestScope } : {},
2870
- requestContext
2871
- };
2872
- const handlerCall = () => route.invoker ? route.invoker(instance, input) : Reflect.apply(method, instance, [input]);
2873
- const invokeHandler = async () => runCompiledEffect(await handlerCall(), route.effect, options.effectRuntime);
2874
- const invoke = once(() => route.command && options.commandGovernance ? invokeHandler() : observeExecution(options.onExecution, {
2875
- kind: route.command ? "command" : "route",
2876
- operation: route.command ?? `${route.method} ${path}`,
2877
- stage: "handler",
2878
- ...executionTrace(requestContext)
2879
- }, invokeHandler));
2880
- const routeContext = {
2881
- kind: "route",
2882
- name: `${route.method} ${path}`,
2963
+ if (!commandExecutor) {
2964
+ throw new ApplicationError(`Command "${command.name}" has no executor`, {
2965
+ status: 501,
2966
+ code: "COMMAND_EXECUTOR_UNAVAILABLE"
2967
+ });
2968
+ }
2969
+ const invocation = {
2970
+ command,
2883
2971
  input,
2884
2972
  request: ctx.request,
2885
2973
  requestContext,
2886
2974
  ...requestScope ? { scope: requestScope } : {},
2887
- services,
2888
- metadata: route
2975
+ services
2889
2976
  };
2890
- const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
2891
- const commandContext = {
2977
+ return observeExecution(options.onExecution, {
2892
2978
  kind: "command",
2893
- name: command?.name ?? route.command ?? `${route.method} ${path}`,
2894
- input,
2895
- request: ctx.request,
2896
- requestContext,
2897
- ...requestScope ? { scope: requestScope } : {},
2898
- services,
2899
- metadata: command ?? route
2900
- };
2901
- const routePipeline = descriptorPipeline(route, "route", options.onExecution);
2902
- const commandPipeline = descriptorPipeline(command ?? {}, "command", options.onExecution);
2903
- const modulePipeline = descriptorPipeline(compiled, `module:${compiled.name}`, options.onExecution);
2904
- const invokeRoute = () => modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
2905
- const invokeCommand = () => {
2906
- if (!route.command)
2907
- return invokeRoute();
2908
- if (!command) {
2909
- throw new ApplicationError(`Command "${route.command}" is not registered`, {
2910
- code: "COMMAND_NOT_REGISTERED"
2911
- });
2912
- }
2913
- if (!commandExecutor) {
2914
- throw new ApplicationError(`Command "${command.name}" has no executor`, {
2915
- status: 501,
2916
- code: "COMMAND_EXECUTOR_UNAVAILABLE"
2917
- });
2918
- }
2919
- const invocation = {
2920
- command,
2921
- input,
2922
- request: ctx.request,
2923
- requestContext,
2924
- ...requestScope ? { scope: requestScope } : {},
2925
- services
2926
- };
2927
- return observeExecution(options.onExecution, {
2928
- kind: "command",
2929
- operation: command.name,
2930
- stage: "commandExecutor",
2931
- ...executionTrace(requestContext)
2932
- }, () => commandExecutor(invocation, once(invokeRoute)));
2933
- };
2934
- return invokeCommand();
2979
+ operation: command.name,
2980
+ stage: "commandExecutor",
2981
+ ...executionTrace(requestContext)
2982
+ }, () => commandExecutor(invocation, once(invokeRoute)));
2935
2983
  };
2936
- const result = await execute();
2937
- assertDeclaredResponseStatus(route, result, ctx.set.status);
2938
- return result;
2984
+ return invokeCommand();
2939
2985
  };
2940
- switch (route.method) {
2941
- case "GET":
2942
- routeRegistrar.get(path, schema, handler);
2943
- break;
2944
- case "POST":
2945
- routeRegistrar.post(path, schema, handler);
2946
- break;
2947
- case "PUT":
2948
- routeRegistrar.put(path, schema, handler);
2949
- break;
2950
- case "PATCH":
2951
- routeRegistrar.patch(path, schema, handler);
2952
- break;
2953
- case "DELETE":
2954
- routeRegistrar.delete(path, schema, handler);
2955
- break;
2956
- case "HEAD":
2957
- routeRegistrar.head(path, schema, handler);
2958
- break;
2959
- case "OPTIONS":
2960
- routeRegistrar.options(path, schema, handler);
2961
- break;
2962
- }
2986
+ const result = await execute();
2987
+ assertDeclaredResponseStatus(route, result, ctx.set.status);
2988
+ return result;
2989
+ };
2990
+ switch (route.method) {
2991
+ case "GET":
2992
+ routeRegistrar.get(path, schema, handler);
2993
+ break;
2994
+ case "POST":
2995
+ routeRegistrar.post(path, schema, handler);
2996
+ break;
2997
+ case "PUT":
2998
+ routeRegistrar.put(path, schema, handler);
2999
+ break;
3000
+ case "PATCH":
3001
+ routeRegistrar.patch(path, schema, handler);
3002
+ break;
3003
+ case "DELETE":
3004
+ routeRegistrar.delete(path, schema, handler);
3005
+ break;
3006
+ case "HEAD":
3007
+ routeRegistrar.head(path, schema, handler);
3008
+ break;
3009
+ case "OPTIONS":
3010
+ routeRegistrar.options(path, schema, handler);
3011
+ break;
2963
3012
  }
3013
+ };
3014
+ compiled.registerRoutes?.(registerRoute);
3015
+ if (pendingRoutes.size > 0) {
3016
+ throw new ApplicationError(`Incomplete static route registration in module "${compiled.name}". Recompile the application.`, {
3017
+ code: "COMPILED_ROUTE_REGISTRATION_INVALID"
3018
+ });
2964
3019
  }
2965
3020
  return plugin;
2966
3021
  }
@@ -3079,23 +3134,25 @@ function createApplication(options) {
3079
3134
  const app = new Elysia3({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3080
3135
  if (options.documentation)
3081
3136
  app.use(createDocumentationPlugin(options.documentation));
3082
- const configuredContextFactory = options.requestContext ?? defaultRequestContext;
3083
- const contextCache = new WeakMap;
3084
- const ctxFactory = (request, context, signal) => {
3085
- const cached = contextCache.get(request);
3086
- if (cached)
3137
+ const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
3138
+ const contextCache = new WeakMap;
3139
+ return (request, context, signal) => {
3140
+ if (contextCache.has(request))
3141
+ return contextCache.get(request);
3142
+ const value = options.requestContext(request, context, signal);
3143
+ const cached = isPromiseLike(value) ? Promise.resolve(value) : value;
3144
+ contextCache.set(request, cached);
3087
3145
  return cached;
3088
- const pending = Promise.resolve().then(() => configuredContextFactory(request, context, signal));
3089
- contextCache.set(request, pending);
3090
- return pending;
3091
- };
3146
+ };
3147
+ })();
3092
3148
  const imported = {};
3093
3149
  const moduleServices = [];
3094
3150
  for (const module of options.modules ?? []) {
3095
3151
  const services = module.createServices(options.deps ?? {}, imported);
3096
3152
  imported[module.name] = services;
3097
3153
  moduleServices.push({ module, services });
3098
- app.use(createModulePlugin(module, services, ctxFactory, { ...options, http: undefined }, imported, pendingWork));
3154
+ const moduleNeedsRequestState = options.pendingWork !== undefined || options.requestContext !== undefined || options.httpPolicies !== undefined || options.onExecution !== undefined || module.createRequestScope !== undefined || module.aspectPipeline !== undefined || module.controllers.some((controller) => controller.routes.some((route) => !canUseDirectRoute(module, controller, route)));
3155
+ app.use(createModulePlugin(module, services, ctxFactory, { ...options, http: undefined }, imported, moduleNeedsRequestState ? pendingWork : undefined));
3099
3156
  }
3100
3157
  let initialized = false;
3101
3158
  let destroyed = false;
package/dist/testing.d.ts CHANGED
@@ -2,3 +2,14 @@
2
2
  export declare function testRequest(app: {
3
3
  handle(request: Request): Response | Promise<Response>;
4
4
  }, path: string, init?: RequestInit): Promise<Response>;
5
+ type TestInvokerRequest = {
6
+ params?: Record<string, unknown>;
7
+ query?: Record<string, unknown>;
8
+ body?: unknown;
9
+ headers?: Record<string, unknown>;
10
+ cookie?: Record<string, unknown>;
11
+ context?: unknown;
12
+ };
13
+ /** Build generated-route-shaped invokers for hand-authored test modules. */
14
+ export declare function testInvoker(handlerName: string): (controller: unknown, request: TestInvokerRequest) => any;
15
+ export {};