@supacloud/elysia 0.38.0 → 0.38.2
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/bun-aot.d.ts +18 -0
- package/dist/bun-aot.js +3252 -0
- package/dist/fixtures/webhook-generated/application.d.ts +29 -1
- package/dist/http-policy-postgres.d.ts +1 -1
- package/dist/index.d.ts +16 -4
- package/dist/index.js +89 -51
- package/dist/testing.d.ts +11 -0
- package/package.json +10 -5
|
@@ -12,6 +12,19 @@ export interface CompiledRoute {
|
|
|
12
12
|
cookie?: unknown;
|
|
13
13
|
response?: unknown;
|
|
14
14
|
responses?: Record<string | number, unknown>;
|
|
15
|
+
effect?: {
|
|
16
|
+
required: true;
|
|
17
|
+
errors?: Array<{
|
|
18
|
+
tag: string;
|
|
19
|
+
status: number;
|
|
20
|
+
code: string;
|
|
21
|
+
message?: string;
|
|
22
|
+
}>;
|
|
23
|
+
dependencies?: string[];
|
|
24
|
+
retry?: "none" | "explicit";
|
|
25
|
+
maxAttempts?: number;
|
|
26
|
+
timeoutMs?: number;
|
|
27
|
+
};
|
|
15
28
|
/** Compile-time ownership and transport classification for the route boundary. */
|
|
16
29
|
contract?: {
|
|
17
30
|
body?: "framework" | "domain";
|
|
@@ -23,6 +36,8 @@ export interface CompiledRoute {
|
|
|
23
36
|
/** True when the handler returns a native Response rather than a framework value. */
|
|
24
37
|
nativeResponse?: boolean;
|
|
25
38
|
command?: string;
|
|
39
|
+
/** Transport-level idempotency contract, independent of route command binding. */
|
|
40
|
+
idempotency?: "required" | "none";
|
|
26
41
|
guards?: string[];
|
|
27
42
|
canMatch?: string[];
|
|
28
43
|
canDeactivate?: string[];
|
|
@@ -37,7 +52,7 @@ export interface CompiledRoute {
|
|
|
37
52
|
data?: Record<string, unknown>;
|
|
38
53
|
aspects?: CompiledAspect[];
|
|
39
54
|
aspectPipeline?: CompiledAspectPipeline;
|
|
40
|
-
invoker
|
|
55
|
+
invoker: (controller: unknown, request: {
|
|
41
56
|
params?: Record<string, unknown>;
|
|
42
57
|
query?: Record<string, unknown>;
|
|
43
58
|
body?: unknown;
|
|
@@ -45,19 +60,31 @@ export interface CompiledRoute {
|
|
|
45
60
|
cookie?: Record<string, unknown>;
|
|
46
61
|
context?: unknown;
|
|
47
62
|
}) => Promise<unknown> | unknown;
|
|
63
|
+
directInvoker?: (controller: unknown, context: unknown) => Promise<unknown> | unknown;
|
|
64
|
+
executionMode?: "direct" | "pipeline";
|
|
48
65
|
}
|
|
49
66
|
export interface CompiledCommand {
|
|
50
67
|
rpc?: string;
|
|
68
|
+
branches?: readonly CompiledCommandBranch[];
|
|
51
69
|
className: string;
|
|
52
70
|
name: string;
|
|
53
71
|
permission: string;
|
|
54
72
|
transaction: "required" | "none";
|
|
55
73
|
audit?: string;
|
|
56
74
|
idempotency: "required" | "none";
|
|
75
|
+
tenantScope?: "required" | "none";
|
|
57
76
|
standalone?: boolean;
|
|
58
77
|
aspects?: CompiledAspect[];
|
|
59
78
|
aspectPipeline?: CompiledAspectPipeline;
|
|
60
79
|
}
|
|
80
|
+
export interface CompiledCommandBranch {
|
|
81
|
+
when: string;
|
|
82
|
+
rpc: string;
|
|
83
|
+
transaction?: "required" | "none" | string;
|
|
84
|
+
audit?: string;
|
|
85
|
+
idempotency?: "required" | "none" | string;
|
|
86
|
+
boundary?: "database" | "external";
|
|
87
|
+
}
|
|
61
88
|
export interface CompiledJob {
|
|
62
89
|
className: string;
|
|
63
90
|
name: string;
|
|
@@ -69,6 +96,7 @@ export interface CompiledJob {
|
|
|
69
96
|
timeoutSec?: number;
|
|
70
97
|
maxAttempts?: number;
|
|
71
98
|
idempotency?: "required" | "none";
|
|
99
|
+
tenantScope?: "required" | "none";
|
|
72
100
|
aspects?: CompiledAspect[];
|
|
73
101
|
aspectPipeline?: CompiledAspectPipeline;
|
|
74
102
|
}
|
|
@@ -3,7 +3,7 @@ export interface HttpPolicyDatabase {
|
|
|
3
3
|
query(text: string, parameters: readonly unknown[]): Promise<readonly Record<string, unknown>[]>;
|
|
4
4
|
}
|
|
5
5
|
/** Apply through migrations, never from a request. Credentials must be server-only. */
|
|
6
|
-
export declare const HTTP_POLICY_STORE_SQL = "\nCREATE SCHEMA IF NOT EXISTS supacloud_http;\nREVOKE ALL ON SCHEMA supacloud_http FROM PUBLIC;\nCREATE TABLE IF NOT EXISTS supacloud_http.rate_limits (\n key text PRIMARY KEY CHECK (key ~ '^[a-f0-9]{64}$'),\n used bigint NOT NULL CHECK (used > 0),\n reset_at timestamptz NOT NULL\n);\nCREATE INDEX IF NOT EXISTS http_rate_limit_expiry ON supacloud_http.rate_limits(reset_at);\nCREATE TABLE IF NOT EXISTS supacloud_http.response_cache (\n key text PRIMARY KEY CHECK (key ~ '^[a-f0-9]{64}$'),\n body text NOT NULL CHECK (octet_length(body) <= 16777216),\n expires_at timestamptz NOT NULL,\n generation uuid NOT NULL\n);\nALTER TABLE supacloud_http.response_cache ADD COLUMN IF NOT EXISTS generation uuid\n NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';\nCREATE TABLE IF NOT EXISTS supacloud_http.cache_generation (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n generation uuid NOT NULL DEFAULT gen_random_uuid()\n);\nINSERT INTO supacloud_http.cache_generation(singleton) VALUES (true) ON CONFLICT DO NOTHING;\nCREATE INDEX IF NOT EXISTS http_response_cache_expiry ON supacloud_http.response_cache(expires_at);\nREVOKE ALL ON ALL TABLES IN SCHEMA supacloud_http FROM PUBLIC;\nCREATE OR REPLACE FUNCTION supacloud_http.consume_rate_limit(p_key text, p_limit bigint, p_window_ms integer)\nRETURNS TABLE(allowed boolean, remaining bigint, reset_at_ms numeric)\nLANGUAGE plpgsql SET search_path = pg_catalog, supacloud_http AS $rate$\nDECLARE\n entry supacloud_http.rate_limits%ROWTYPE;\n observed_at timestamptz;\nBEGIN\n IF p_limit < 1 OR p_limit > 1000000000 OR p_window_ms < 1 OR p_window_ms > 86400000 THEN\n RAISE EXCEPTION 'Invalid rate limit window';\n END IF;\n LOOP\n INSERT INTO supacloud_http.rate_limits(key, used, reset_at)\n VALUES (p_key, 1, '-infinity') ON CONFLICT DO NOTHING;\n SELECT
|
|
6
|
+
export declare const HTTP_POLICY_STORE_SQL = "\nCREATE SCHEMA IF NOT EXISTS supacloud_http;\nREVOKE ALL ON SCHEMA supacloud_http FROM PUBLIC;\nCREATE TABLE IF NOT EXISTS supacloud_http.rate_limits (\n key text PRIMARY KEY CHECK (key ~ '^[a-f0-9]{64}$'),\n used bigint NOT NULL CHECK (used > 0),\n reset_at timestamptz NOT NULL\n);\nCREATE INDEX IF NOT EXISTS http_rate_limit_expiry ON supacloud_http.rate_limits(reset_at);\nCREATE TABLE IF NOT EXISTS supacloud_http.response_cache (\n key text PRIMARY KEY CHECK (key ~ '^[a-f0-9]{64}$'),\n body text NOT NULL CHECK (octet_length(body) <= 16777216),\n expires_at timestamptz NOT NULL,\n generation uuid NOT NULL\n);\nALTER TABLE supacloud_http.response_cache ADD COLUMN IF NOT EXISTS generation uuid\n NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';\nCREATE TABLE IF NOT EXISTS supacloud_http.cache_generation (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n generation uuid NOT NULL DEFAULT gen_random_uuid()\n);\nINSERT INTO supacloud_http.cache_generation(singleton) VALUES (true) ON CONFLICT DO NOTHING;\nCREATE INDEX IF NOT EXISTS http_response_cache_expiry ON supacloud_http.response_cache(expires_at);\nREVOKE ALL ON ALL TABLES IN SCHEMA supacloud_http FROM PUBLIC;\nCREATE OR REPLACE FUNCTION supacloud_http.consume_rate_limit(p_key text, p_limit bigint, p_window_ms integer)\nRETURNS TABLE(allowed boolean, remaining bigint, reset_at_ms numeric)\nLANGUAGE plpgsql SET search_path = pg_catalog, supacloud_http AS $rate$\nDECLARE\n entry supacloud_http.rate_limits%ROWTYPE;\n observed_at timestamptz;\nBEGIN\n IF p_limit < 1 OR p_limit > 1000000000 OR p_window_ms < 1 OR p_window_ms > 86400000 THEN\n RAISE EXCEPTION 'Invalid rate limit window';\n END IF;\n LOOP\n INSERT INTO supacloud_http.rate_limits(key, used, reset_at)\n VALUES (p_key, 1, '-infinity') ON CONFLICT DO NOTHING;\n SELECT key, used, reset_at INTO entry FROM supacloud_http.rate_limits WHERE key=p_key FOR UPDATE;\n EXIT WHEN FOUND;\n -- Expiry pruning may remove a conflicting row before we acquire its lock.\n END LOOP;\n observed_at := clock_timestamp();\n IF entry.reset_at <= observed_at THEN\n entry.used := 1;\n entry.reset_at := observed_at + p_window_ms * interval '1 millisecond';\n ELSE\n entry.used := least(entry.used + 1, p_limit + 1);\n END IF;\n UPDATE supacloud_http.rate_limits SET used=entry.used, reset_at=entry.reset_at WHERE key=p_key;\n RETURN QUERY SELECT entry.used <= p_limit, greatest(p_limit-entry.used,0),\n extract(epoch FROM entry.reset_at)*1000;\nEND\n$rate$;\nREVOKE ALL ON FUNCTION supacloud_http.consume_rate_limit(text,bigint,integer) FROM PUBLIC;\n";
|
|
7
7
|
/** Independent instances sharing a database share atomic quotas and private cache entries. */
|
|
8
8
|
export declare function createPostgresHttpPolicyStores(database: HttpPolicyDatabase): {
|
|
9
9
|
rateLimitStore: HttpRateLimitStore;
|
package/dist/index.d.ts
CHANGED
|
@@ -62,8 +62,8 @@ export interface CompiledRoute {
|
|
|
62
62
|
schemaKinds?: Partial<Record<"body" | "params" | "query" | "headers" | "cookie" | "response", "opaque" | "declared">>;
|
|
63
63
|
/** True when the handler returns a native Response rather than a framework value. */
|
|
64
64
|
nativeResponse?: boolean;
|
|
65
|
-
/** Compiler-emitted positional invoker
|
|
66
|
-
invoker?: (controller:
|
|
65
|
+
/** Compiler-emitted positional invoker. */
|
|
66
|
+
invoker?: <Controller extends CompiledControllerInvokerTarget>(controller: Controller, request: {
|
|
67
67
|
params?: Record<string, unknown>;
|
|
68
68
|
query?: Record<string, unknown>;
|
|
69
69
|
body?: unknown;
|
|
@@ -71,6 +71,12 @@ export interface CompiledRoute {
|
|
|
71
71
|
cookie?: Record<string, unknown>;
|
|
72
72
|
context?: unknown;
|
|
73
73
|
}) => Promise<unknown> | unknown;
|
|
74
|
+
/** Compiler-emitted Elysia-context invoker for routes without SupaCloud stages. */
|
|
75
|
+
directInvoker?: <Controller extends CompiledControllerInvokerTarget>(controller: Controller, context: unknown) => Promise<unknown> | unknown;
|
|
76
|
+
/** Generated invoker accepting a controller and method validated at registration. */
|
|
77
|
+
directInvokerFast?: (controller: Record<string, unknown>, handler: (...args: unknown[]) => unknown, context: unknown) => unknown | Promise<unknown>;
|
|
78
|
+
/** Compiler-selected execution plan. Older artifacts default to the full pipeline. */
|
|
79
|
+
executionMode?: "direct" | "pipeline";
|
|
74
80
|
/** Class name of the @Command explicitly bound to this route. */
|
|
75
81
|
command?: string;
|
|
76
82
|
/** Transport-level idempotency contract, independent of route command binding. */
|
|
@@ -79,6 +85,13 @@ export interface CompiledRoute {
|
|
|
79
85
|
aspects?: ApplicationAspect[];
|
|
80
86
|
aspectPipeline?: ApplicationAspectPipeline;
|
|
81
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* The generated invoker validates the controller at runtime, while hand-written
|
|
90
|
+
* descriptors often call a known method directly. Keep the target callable so
|
|
91
|
+
* those descriptors retain useful contextual types without weakening the
|
|
92
|
+
* compiled module contract to `any`.
|
|
93
|
+
*/
|
|
94
|
+
export type CompiledControllerInvokerTarget = Record<string, (...args: unknown[]) => unknown> & object;
|
|
82
95
|
export interface CompiledCommand {
|
|
83
96
|
rpc?: string;
|
|
84
97
|
branches?: readonly CompiledCommandBranch[];
|
|
@@ -421,8 +434,7 @@ export declare function createModulePlugin<const Services extends Record<string,
|
|
|
421
434
|
response: Http["~Ephemeral"]["response"];
|
|
422
435
|
error: [...Http["~Ephemeral"]["error"]];
|
|
423
436
|
}, {}, {
|
|
424
|
-
|
|
425
|
-
readonly requestContext: unknown;
|
|
437
|
+
services: Services;
|
|
426
438
|
}>;
|
|
427
439
|
/**
|
|
428
440
|
* Execute one compiler-emitted Job descriptor.
|
package/dist/index.js
CHANGED
|
@@ -573,7 +573,7 @@ BEGIN
|
|
|
573
573
|
LOOP
|
|
574
574
|
INSERT INTO supacloud_http.rate_limits(key, used, reset_at)
|
|
575
575
|
VALUES (p_key, 1, '-infinity') ON CONFLICT DO NOTHING;
|
|
576
|
-
SELECT
|
|
576
|
+
SELECT key, used, reset_at INTO entry FROM supacloud_http.rate_limits WHERE key=p_key FOR UPDATE;
|
|
577
577
|
EXIT WHEN FOUND;
|
|
578
578
|
-- Expiry pruning may remove a conflicting row before we acquire its lock.
|
|
579
579
|
END LOOP;
|
|
@@ -602,7 +602,7 @@ function createPostgresHttpPolicyStores(database) {
|
|
|
602
602
|
if (!Number.isSafeInteger(limit) || limit <= 0 || limit > 1e9 || !Number.isSafeInteger(windowMs) || windowMs <= 0 || windowMs > 86400000) {
|
|
603
603
|
throw new TypeError("Invalid rate limit window");
|
|
604
604
|
}
|
|
605
|
-
const [row] = await database.query("SELECT
|
|
605
|
+
const [row] = await database.query("SELECT allowed, remaining, reset_at_ms FROM supacloud_http.consume_rate_limit($1,$2,$3)", [key, limit, windowMs]);
|
|
606
606
|
if (!row || typeof row.allowed !== "boolean")
|
|
607
607
|
throw new Error("Invalid rate limit storage result");
|
|
608
608
|
return { allowed: row.allowed, remaining: Number(row.remaining), resetAt: Number(row.reset_at_ms) };
|
|
@@ -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
|
|
2469
|
+
return () => {
|
|
2465
2470
|
if (called) {
|
|
2466
|
-
|
|
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
|
-
|
|
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",
|
|
@@ -2685,6 +2700,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2685
2700
|
throw new ApplicationError(`Module "${compiled.name}" has command routes but no commandGovernance`, { code: "COMMAND_GOVERNANCE_UNCONFIGURED" });
|
|
2686
2701
|
}
|
|
2687
2702
|
assertCommandGovernanceReady(compiled, options.commandGovernance, options.commandExecutor);
|
|
2703
|
+
const commandsByClassName = new Map((compiled.commands ?? []).map((command) => [command.className, command]));
|
|
2688
2704
|
for (const controller of compiled.controllers) {
|
|
2689
2705
|
for (const route of controller.routes) {
|
|
2690
2706
|
const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
|
|
@@ -2707,7 +2723,12 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2707
2723
|
const requestCompletions = new WeakMap;
|
|
2708
2724
|
const governanceExecutor = options.commandGovernance ? createCommandExecutor(options.commandGovernance, options.onExecution) : undefined;
|
|
2709
2725
|
const commandExecutor = options.commandExecutor && governanceExecutor ? composeCommandExecutors(options.commandExecutor, governanceExecutor) : options.commandExecutor ?? governanceExecutor;
|
|
2710
|
-
const
|
|
2726
|
+
const modulePipeline = descriptorPipeline(compiled, `module:${compiled.name}`, options.onExecution);
|
|
2727
|
+
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)));
|
|
2728
|
+
const basePlugin = mountHttp(options.http, `supacloud:${compiled.name}`, options.normalize ?? true);
|
|
2729
|
+
const servicesContext = { services };
|
|
2730
|
+
const servicesPlugin = basePlugin.derive(() => servicesContext);
|
|
2731
|
+
const plugin = needsRequestState ? servicesPlugin.derive((context) => {
|
|
2711
2732
|
if (pendingWork?.closed)
|
|
2712
2733
|
throw new ApplicationError("Application is stopping", { status: 503, code: "APPLICATION_STOPPING" });
|
|
2713
2734
|
let complete;
|
|
@@ -2721,25 +2742,29 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2721
2742
|
if (complete)
|
|
2722
2743
|
requestCompletions.set(context.request, complete);
|
|
2723
2744
|
const signal = pendingWork ? AbortSignal.any([context.request.signal, pendingWork.signal]) : context.request.signal;
|
|
2724
|
-
const
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2745
|
+
const finish = (requestContext) => {
|
|
2746
|
+
requestContexts.set(context.request, requestContext);
|
|
2747
|
+
return { requestContext };
|
|
2748
|
+
};
|
|
2749
|
+
const requestContext = ctxFactory(context.request, context, signal);
|
|
2750
|
+
return isPromiseLike(requestContext) ? requestContext.then(finish) : finish(requestContext);
|
|
2751
|
+
}) : servicesPlugin;
|
|
2728
2752
|
const createRequestScope = compiled.createRequestScope;
|
|
2729
2753
|
const requestScopes = new WeakMap;
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2754
|
+
if (needsRequestState)
|
|
2755
|
+
plugin.onAfterResponse(async ({ request }) => {
|
|
2756
|
+
const scope = requestScopes.get(request);
|
|
2757
|
+
requestScopes.delete(request);
|
|
2758
|
+
try {
|
|
2759
|
+
if (scope)
|
|
2760
|
+
await compiled.destroyRequestScope?.(scope);
|
|
2761
|
+
} catch (error) {
|
|
2762
|
+
console.error(`supacloud: request scope cleanup failed for "${compiled.name}"`, error);
|
|
2763
|
+
} finally {
|
|
2764
|
+
requestCompletions.get(request)?.();
|
|
2765
|
+
requestCompletions.delete(request);
|
|
2766
|
+
}
|
|
2767
|
+
});
|
|
2743
2768
|
const mapError = async (error, frameworkCode, request) => {
|
|
2744
2769
|
const context = {
|
|
2745
2770
|
request,
|
|
@@ -2797,6 +2822,10 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2797
2822
|
}
|
|
2798
2823
|
const responsePolicies = policies.filter((policy) => policy.afterResponse);
|
|
2799
2824
|
const mappingPolicies = policies.filter((policy) => policy.mapResponse);
|
|
2825
|
+
const routePipeline = descriptorPipeline(route, "route", options.onExecution);
|
|
2826
|
+
const command = route.command ? commandsByClassName.get(route.command) : undefined;
|
|
2827
|
+
const commandPipeline = route.command ? descriptorPipeline(command ?? {}, "command", options.onExecution) : undefined;
|
|
2828
|
+
const routeInvoker = route.invoker;
|
|
2800
2829
|
if (mappingPolicies.length > 0) {
|
|
2801
2830
|
const responseValidators = Validator2.response(schema.response, { normalize: options.normalize ?? true });
|
|
2802
2831
|
Object.assign(schema, {
|
|
@@ -2808,7 +2837,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2808
2837
|
http: context,
|
|
2809
2838
|
requestContext: requestContexts.get(context.request),
|
|
2810
2839
|
response,
|
|
2811
|
-
encodeResponse:
|
|
2840
|
+
encodeResponse: (value) => {
|
|
2812
2841
|
const validator = responseValidators?.get(responseStatusOf(value, context.set.status));
|
|
2813
2842
|
if (!validator)
|
|
2814
2843
|
return value;
|
|
@@ -2816,9 +2845,9 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2816
2845
|
throw new ApplicationError("Response validation failed", { code: "RESPONSE_VALIDATION_FAILED" });
|
|
2817
2846
|
}
|
|
2818
2847
|
if ("mayReturnPromise" in validator && validator.mayReturnPromise && "From" in validator && typeof validator.From === "function") {
|
|
2819
|
-
return
|
|
2848
|
+
return validator.From.call(validator, value, "response", true);
|
|
2820
2849
|
}
|
|
2821
|
-
return
|
|
2850
|
+
return validator.EncodeFrom.call(validator, value, "response");
|
|
2822
2851
|
}
|
|
2823
2852
|
});
|
|
2824
2853
|
if (result !== undefined) {
|
|
@@ -2845,18 +2874,19 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2845
2874
|
}
|
|
2846
2875
|
});
|
|
2847
2876
|
}
|
|
2848
|
-
const
|
|
2877
|
+
const directRoute = canUseDirectRoute(compiled, controller, route) && options.onExecution === undefined && policies.length === 0 && responsePolicies.length === 0 && mappingPolicies.length === 0;
|
|
2878
|
+
const directController = directRoute && route.directInvokerFast !== undefined ? controllerInstance(services[controller.serviceKey]) : undefined;
|
|
2879
|
+
const directMethod = directController?.[route.handler];
|
|
2880
|
+
const directInvokerFast = route.directInvokerFast;
|
|
2881
|
+
const directHandler = directController && typeof directMethod === "function" && directInvokerFast ? (ctx) => directInvokerFast(directController, directMethod, ctx) : (ctx) => route.directInvoker(services[controller.serviceKey], ctx);
|
|
2882
|
+
const handler = directRoute ? directHandler : async (ctx) => {
|
|
2849
2883
|
const requestContext = requestContexts.get(ctx.request);
|
|
2850
2884
|
const execute = async () => {
|
|
2851
2885
|
const requestScope = createRequestScope ? await createRequestScope(services, requestContext, imported) : undefined;
|
|
2852
2886
|
if (requestScope && compiled.destroyRequestScope)
|
|
2853
2887
|
requestScopes.set(ctx.request, requestScope);
|
|
2854
2888
|
const source = controller.scope === "request" ? requestScope : services;
|
|
2855
|
-
const instance =
|
|
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}"`);
|
|
2859
|
-
}
|
|
2889
|
+
const instance = source?.[controller.serviceKey];
|
|
2860
2890
|
const normalizedCookie = ctx.cookie === undefined ? undefined : cookieValues(ctx.cookie);
|
|
2861
2891
|
const input = {
|
|
2862
2892
|
body: ctx.body,
|
|
@@ -2869,14 +2899,23 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2869
2899
|
...requestScope ? { scope: requestScope } : {},
|
|
2870
2900
|
requestContext
|
|
2871
2901
|
};
|
|
2872
|
-
const handlerCall = () =>
|
|
2902
|
+
const handlerCall = () => {
|
|
2903
|
+
if (route.invoker)
|
|
2904
|
+
return route.invoker(instance, input);
|
|
2905
|
+
if (!isRecord2(instance))
|
|
2906
|
+
throw new TypeError("Route controller is not an object");
|
|
2907
|
+
const method = instance[route.handler];
|
|
2908
|
+
if (typeof method !== "function")
|
|
2909
|
+
throw new TypeError(`Route handler ${route.handler} is not callable`);
|
|
2910
|
+
return method.call(instance, input);
|
|
2911
|
+
};
|
|
2873
2912
|
const invokeHandler = async () => runCompiledEffect(await handlerCall(), route.effect, options.effectRuntime);
|
|
2874
|
-
const invoke = once(() => route.command && options.commandGovernance ? invokeHandler() : observeExecution(options.onExecution, {
|
|
2913
|
+
const invoke = once(() => route.command && options.commandGovernance ? invokeHandler() : options.onExecution ? observeExecution(options.onExecution, {
|
|
2875
2914
|
kind: route.command ? "command" : "route",
|
|
2876
2915
|
operation: route.command ?? `${route.method} ${path}`,
|
|
2877
2916
|
stage: "handler",
|
|
2878
2917
|
...executionTrace(requestContext)
|
|
2879
|
-
}, invokeHandler));
|
|
2918
|
+
}, invokeHandler) : invokeHandler());
|
|
2880
2919
|
const routeContext = {
|
|
2881
2920
|
kind: "route",
|
|
2882
2921
|
name: `${route.method} ${path}`,
|
|
@@ -2888,9 +2927,9 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2888
2927
|
metadata: route
|
|
2889
2928
|
};
|
|
2890
2929
|
const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
|
|
2891
|
-
const commandContext = {
|
|
2930
|
+
const commandContext = route.command === undefined ? routeContext : {
|
|
2892
2931
|
kind: "command",
|
|
2893
|
-
name: command?.name ?? route.command
|
|
2932
|
+
name: command?.name ?? route.command,
|
|
2894
2933
|
input,
|
|
2895
2934
|
request: ctx.request,
|
|
2896
2935
|
requestContext,
|
|
@@ -2898,9 +2937,6 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
|
|
|
2898
2937
|
services,
|
|
2899
2938
|
metadata: command ?? route
|
|
2900
2939
|
};
|
|
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
2940
|
const invokeRoute = () => modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
|
|
2905
2941
|
const invokeCommand = () => {
|
|
2906
2942
|
if (!route.command)
|
|
@@ -3079,23 +3115,25 @@ function createApplication(options) {
|
|
|
3079
3115
|
const app = new Elysia3({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
|
|
3080
3116
|
if (options.documentation)
|
|
3081
3117
|
app.use(createDocumentationPlugin(options.documentation));
|
|
3082
|
-
const
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3118
|
+
const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
|
|
3119
|
+
const contextCache = new WeakMap;
|
|
3120
|
+
return (request, context, signal) => {
|
|
3121
|
+
if (contextCache.has(request))
|
|
3122
|
+
return contextCache.get(request);
|
|
3123
|
+
const value = options.requestContext(request, context, signal);
|
|
3124
|
+
const cached = isPromiseLike(value) ? Promise.resolve(value) : value;
|
|
3125
|
+
contextCache.set(request, cached);
|
|
3087
3126
|
return cached;
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
return pending;
|
|
3091
|
-
};
|
|
3127
|
+
};
|
|
3128
|
+
})();
|
|
3092
3129
|
const imported = {};
|
|
3093
3130
|
const moduleServices = [];
|
|
3094
3131
|
for (const module of options.modules ?? []) {
|
|
3095
3132
|
const services = module.createServices(options.deps ?? {}, imported);
|
|
3096
3133
|
imported[module.name] = services;
|
|
3097
3134
|
moduleServices.push({ module, services });
|
|
3098
|
-
|
|
3135
|
+
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)));
|
|
3136
|
+
app.use(createModulePlugin(module, services, ctxFactory, { ...options, http: undefined }, imported, moduleNeedsRequestState ? pendingWork : undefined));
|
|
3099
3137
|
}
|
|
3100
3138
|
let initialized = false;
|
|
3101
3139
|
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 {};
|
package/package.json
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/elysia",
|
|
3
|
-
"version": "0.38.
|
|
3
|
+
"version": "0.38.2",
|
|
4
4
|
"description": "Elysia runtime adapter for SupaCloud compiled modules: application/request scopes, route registration and validation",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"module": "./dist/index.js",
|
|
8
8
|
"types": "./dist/index.d.ts",
|
|
9
9
|
"exports": {
|
|
10
|
+
"./bun-aot": {
|
|
11
|
+
"types": "./dist/bun-aot.d.ts",
|
|
12
|
+
"import": "./dist/bun-aot.js",
|
|
13
|
+
"default": "./dist/bun-aot.js"
|
|
14
|
+
},
|
|
10
15
|
".": {
|
|
11
16
|
"types": "./dist/index.d.ts",
|
|
12
17
|
"import": "./dist/index.js",
|
|
@@ -23,7 +28,7 @@
|
|
|
23
28
|
"scripts": {
|
|
24
29
|
"generate:example": "bun src/generate-webhook-example.ts",
|
|
25
30
|
"build": "bun run clean && bun run build:js && bun run build:types",
|
|
26
|
-
"build:js": "bun build src/index.ts --outdir dist --target node --external elysia --external effect --external jose --external @supacloud/app --external @supacloud/db --external @supacloud/contracts --external @supacloud/commands",
|
|
31
|
+
"build:js": "bun build src/index.ts src/bun-aot.ts --outdir dist --target node --external elysia --external effect --external jose --external @supacloud/app --external @supacloud/db --external @supacloud/contracts --external @supacloud/commands",
|
|
27
32
|
"build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
|
|
28
33
|
"clean": "rm -rf dist",
|
|
29
34
|
"prepublishOnly": "bun run build",
|
|
@@ -49,7 +54,7 @@
|
|
|
49
54
|
"directory": "packages/elysia"
|
|
50
55
|
},
|
|
51
56
|
"dependencies": {
|
|
52
|
-
"@supacloud/app": "0.36.
|
|
57
|
+
"@supacloud/app": "0.36.1",
|
|
53
58
|
"@supacloud/commands": "0.11.2",
|
|
54
59
|
"@supacloud/contracts": "0.15.2",
|
|
55
60
|
"effect": "4.0.5",
|
|
@@ -67,9 +72,9 @@
|
|
|
67
72
|
"elysia": "2.0.0-rc.1"
|
|
68
73
|
},
|
|
69
74
|
"devDependencies": {
|
|
70
|
-
"@supacloud/compiler": "0.
|
|
75
|
+
"@supacloud/compiler": "0.55.1",
|
|
71
76
|
"@supacloud/delivery": "0.24.0",
|
|
72
|
-
"@supacloud/db": "0.20.
|
|
77
|
+
"@supacloud/db": "0.20.5",
|
|
73
78
|
"@types/bun": "^1.4.4",
|
|
74
79
|
"elysia": "2.0.0-rc.1",
|
|
75
80
|
"typescript": "^7.0.2"
|