@supacloud/elysia 0.27.1 → 0.29.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/README.md CHANGED
@@ -9,9 +9,12 @@ is a separately authorized business command, never an assumed rollback.
9
9
  ## Compatibility and Acceptance Boundary
10
10
 
11
11
  The Elysia peer and development dependency are pinned to `2.0.0-beta.21`.
12
+ The runtime adapter pins Effect `4.0.2` and consumes its `Exit`-based
13
+ execution boundary.
12
14
  `compatibility.json` records the acceptance target: Bun 1.4.2, Elysia
13
- 2.0.0-beta.21, `typebox` 1.3.34, `exact-mirror` 1.2.6, TypeScript CLI 7.0.2
14
- and the compiler's separate TypeScript 6 semantic API 6.0.2. The matrix is a
15
+ 2.0.0-beta.21, Effect 4.0.2, `typebox` 1.3.34, `exact-mirror` 1.2.6,
16
+ TypeScript CLI 7.0.2 and the compiler's separate TypeScript 6 semantic API 6.0.2.
17
+ The matrix is a
15
18
  required target, not proof of an execution. See the dated, commit-specific
16
19
  [framework acceptance record](../../docs/framework-acceptance.md) for actual
17
20
  results. The contract-upgrade gate checks both TypeScript engines. These tests
@@ -2,6 +2,7 @@
2
2
  "bun": "1.4.2",
3
3
  "packages": {
4
4
  "elysia": "2.0.0-beta.21",
5
+ "effect": "4.0.2",
5
6
  "typescript": "7.0.2",
6
7
  "typebox": "1.3.34",
7
8
  "exact-mirror": "1.2.6",
@@ -0,0 +1,28 @@
1
+ import { Effect, Exit } from "effect";
2
+ import type * as Layer from "effect/Layer";
3
+ export interface CompiledEffectError {
4
+ readonly tag: string;
5
+ readonly status: number;
6
+ readonly code: string;
7
+ readonly message?: string;
8
+ }
9
+ export interface CompiledEffectDescriptor {
10
+ readonly required: true;
11
+ readonly errors?: readonly CompiledEffectError[];
12
+ readonly dependencies?: readonly string[];
13
+ readonly retry?: "none" | "explicit";
14
+ readonly maxAttempts?: number;
15
+ readonly timeoutMs?: number;
16
+ }
17
+ export interface SupaCloudEffectRuntime {
18
+ run(program: Effect.Effect<unknown, unknown, unknown>): Promise<Exit.Exit<unknown, unknown>>;
19
+ }
20
+ export declare class EffectApplicationError extends Error {
21
+ readonly status: number;
22
+ readonly code: string;
23
+ readonly expose: true;
24
+ constructor(message: string, status: number, code: string);
25
+ }
26
+ export declare function createDefaultEffectRuntime(): SupaCloudEffectRuntime;
27
+ export declare function createEffectRuntimeFromLayer<Services>(layer: Layer.Layer<Services, never, never>): SupaCloudEffectRuntime;
28
+ export declare function runCompiledEffect(value: unknown, descriptor?: CompiledEffectDescriptor, runtime?: SupaCloudEffectRuntime): Promise<unknown>;
package/dist/index.d.ts CHANGED
@@ -16,10 +16,13 @@ export type { HttpTelemetryEvent, HttpTelemetryObserver } from "./http-telemetry
16
16
  import { type ExecutionObserver } from "./execution";
17
17
  import { SchemaContractError } from "./schema_contract";
18
18
  import { type ApplicationDocumentationOptions } from "./documentation";
19
+ import { type CompiledEffectDescriptor, type SupaCloudEffectRuntime } from "./effect";
19
20
  export type { ExecutionEvent, ExecutionObserver } from "./execution";
20
21
  export { bindCompiledCommand } from "./command-binding";
21
22
  export type { CompiledCommandBinding, CompiledCommandBindingOptions, CompiledCommandCallContext, } from "./command-binding";
22
23
  export { createSchemaDecoder, assertResponseStatusDeclared, defineElysiaRoute, defineJsonContract, defineRouteContract, registerElysiaRoute, responseSchemaForStatus, responseStatusDeclared, responseStatusOf, SchemaContractError, toElysiaRouteSchema, } from "./schema_contract";
24
+ export { createDefaultEffectRuntime, createEffectRuntimeFromLayer, EffectApplicationError, runCompiledEffect, } from "./effect";
25
+ export type { CompiledEffectDescriptor, SupaCloudEffectRuntime } from "./effect";
23
26
  export type { ElysiaRouteContext, ElysiaRouteDefinition, ElysiaRouteHandler, ElysiaRouteSchema, ResponseMapSelector, RouteContractSchemas, SchemaDecoderOptions, SchemaNormalizeMode, } from "./schema_contract";
24
27
  export { createPersistentCommandAdapter, type PersistentCommandHandler } from "./persistent-command";
25
28
  export { createDocumentationPlugin } from "./documentation";
@@ -46,6 +49,7 @@ export interface CompiledRoute {
46
49
  /** @deprecated Use `responses` with an explicit HTTP status map. */
47
50
  response?: unknown;
48
51
  responses?: Record<string | number, unknown>;
52
+ effect?: CompiledEffectDescriptor;
49
53
  /** Compile-time ownership and transport classification for the route boundary. */
50
54
  contract?: {
51
55
  body?: "framework" | "domain";
@@ -292,6 +296,8 @@ export interface ApplicationOptions<Http extends AnyElysia = Elysia, RequestCont
292
296
  commandExecutor?: CommandExecutor;
293
297
  /** Maps framework or application failures to the public HTTP contract. */
294
298
  errorMapper?: ErrorMapper;
299
+ /** Runs Effect route programs and provides their environment at the HTTP boundary. */
300
+ effectRuntime?: SupaCloudEffectRuntime;
295
301
  /** Best-effort execution metadata only; durable audit belongs to governance. */
296
302
  onExecution?: ExecutionObserver;
297
303
  /** Optional read-only OpenAPI and GraphQL documentation endpoints. */
@@ -383,7 +389,7 @@ interface HttpContext {
383
389
  * and passed to the controller input as `scope`. Request-scoped controllers
384
390
  * are looked up on that scope, everything else on `services`.
385
391
  */
386
- export declare function createModulePlugin<const Services extends Record<string, unknown>, const Http extends AnyElysia = Elysia>(compiled: CompiledModule, services: Services, ctxFactory?: HttpRequestContextFactory<Http>, options?: Pick<ApplicationOptions<Http>, "http" | "httpPolicies" | "commandGovernance" | "commandExecutor" | "errorMapper" | "onExecution" | "normalize">, imported?: Record<string, Record<string, unknown>>, pendingWork?: PendingWorkRegistry): import("elysia/types").LocalHookReturn<"", "local", {
392
+ export declare function createModulePlugin<const Services extends Record<string, unknown>, const Http extends AnyElysia = Elysia>(compiled: CompiledModule, services: Services, ctxFactory?: HttpRequestContextFactory<Http>, options?: Pick<ApplicationOptions<Http>, "http" | "httpPolicies" | "commandGovernance" | "commandExecutor" | "errorMapper" | "effectRuntime" | "onExecution" | "normalize">, imported?: Record<string, Record<string, unknown>>, pendingWork?: PendingWorkRegistry): import("elysia/types").LocalHookReturn<"", "local", {
387
393
  decorator: {} & Http["~Singleton"]["decorator"];
388
394
  store: ({} & Http["~Singleton"]["store"] extends infer T_1 ? { [K_1 in keyof T_1]: T_1[K_1]; } : never) extends infer T ? { [K in keyof T]: T[K]; } : never;
389
395
  derive: {} & Http["~Singleton"]["derive"];
package/dist/index.js CHANGED
@@ -1014,6 +1014,81 @@ function createDocumentationPlugin(options = {}) {
1014
1014
  return app;
1015
1015
  }
1016
1016
 
1017
+ // src/effect.ts
1018
+ import { Cause, Duration, Effect, Exit, Schedule } from "effect";
1019
+
1020
+ class EffectApplicationError extends Error {
1021
+ status;
1022
+ code;
1023
+ expose = true;
1024
+ constructor(message, status, code) {
1025
+ super(message);
1026
+ this.status = status;
1027
+ this.code = code;
1028
+ this.name = "EffectApplicationError";
1029
+ }
1030
+ }
1031
+ function createDefaultEffectRuntime() {
1032
+ return {
1033
+ run(program) {
1034
+ return Effect.runPromiseExit(program);
1035
+ }
1036
+ };
1037
+ }
1038
+ function createEffectRuntimeFromLayer(layer) {
1039
+ return {
1040
+ run(program) {
1041
+ const provided = Effect.provide(layer)(program);
1042
+ return Effect.runPromiseExit(provided);
1043
+ }
1044
+ };
1045
+ }
1046
+ function isRecord(value) {
1047
+ return value !== null && typeof value === "object";
1048
+ }
1049
+ function effectErrorTag(error) {
1050
+ if (isRecord(error)) {
1051
+ for (const key of ["_tag", "tag", "code", "name"]) {
1052
+ const value = error[key];
1053
+ if (typeof value === "string" && value.length > 0)
1054
+ return value;
1055
+ }
1056
+ }
1057
+ if (error instanceof Error && error.constructor.name)
1058
+ return error.constructor.name;
1059
+ return;
1060
+ }
1061
+ function mapEffectFailure(error, descriptor) {
1062
+ const tag = effectErrorTag(error);
1063
+ const mapping = tag && descriptor?.errors?.find((entry) => entry.tag === tag);
1064
+ if (mapping) {
1065
+ return new EffectApplicationError(mapping.message ?? mapping.code, mapping.status, mapping.code);
1066
+ }
1067
+ if (tag === "TimeoutException" || tag === "TimeoutError") {
1068
+ return new EffectApplicationError("Effect execution timed out", 504, "EFFECT_TIMEOUT");
1069
+ }
1070
+ return new EffectApplicationError("Effect execution failed", 500, descriptor?.required ? "EFFECT_UNMAPPED_ERROR" : "EFFECT_RUNTIME_ERROR");
1071
+ }
1072
+ async function runCompiledEffect(value, descriptor, runtime = createDefaultEffectRuntime()) {
1073
+ if (!Effect.isEffect(value)) {
1074
+ if (descriptor?.required) {
1075
+ throw new EffectApplicationError("Route declared an Effect contract but returned a non-Effect value", 500, "EFFECT_PROGRAM_REQUIRED");
1076
+ }
1077
+ return value;
1078
+ }
1079
+ let program = value;
1080
+ if (descriptor?.timeoutMs !== undefined) {
1081
+ program = Effect.timeout(program, Duration.millis(descriptor.timeoutMs));
1082
+ }
1083
+ if (descriptor?.retry === "explicit" && descriptor.maxAttempts !== undefined && descriptor.maxAttempts > 1) {
1084
+ program = Effect.retry(program, Schedule.recurs(descriptor.maxAttempts - 1));
1085
+ }
1086
+ const exit = await runtime.run(program);
1087
+ if (Exit.isSuccess(exit))
1088
+ return exit.value;
1089
+ throw mapEffectFailure(Cause.squash(exit.cause), descriptor);
1090
+ }
1091
+
1017
1092
  // src/command-binding.ts
1018
1093
  function bindCompiledCommand(options) {
1019
1094
  const { module, command, governance, observer, handler, decode, preview } = options;
@@ -1893,7 +1968,7 @@ function createCommandAuthorizationAdapter(options) {
1893
1968
  });
1894
1969
  }
1895
1970
  const context = invocation.requestContext;
1896
- const identity = isRecord(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
1971
+ const identity = isRecord2(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
1897
1972
  if (!isAuthenticatedTrustedIdentity(identity)) {
1898
1973
  throw new ApplicationError("Authentication required", { status: 401, code: "AUTHENTICATION_REQUIRED" });
1899
1974
  }
@@ -1908,7 +1983,7 @@ function createCommandAuthorizationAdapter(options) {
1908
1983
  } catch {
1909
1984
  throw new ApplicationError("Authorization is unavailable", { status: 503, code: "AUTHORIZATION_UNAVAILABLE" });
1910
1985
  }
1911
- if (!isRecord(resolved) || !Array.isArray(resolved.permissions) || !resolved.permissions.every((value) => typeof value === "string") || resolved.permissionCatalogVersion !== undefined && typeof resolved.permissionCatalogVersion !== "string" || resolved.permissionCatalogDigest !== undefined && typeof resolved.permissionCatalogDigest !== "string" || resolved.applicationId !== options.applicationId || options.catalog !== undefined && (resolved.permissionCatalogVersion !== options.catalog.version || options.catalog.digest !== undefined && resolved.permissionCatalogDigest !== options.catalog.digest)) {
1986
+ if (!isRecord2(resolved) || !Array.isArray(resolved.permissions) || !resolved.permissions.every((value) => typeof value === "string") || resolved.permissionCatalogVersion !== undefined && typeof resolved.permissionCatalogVersion !== "string" || resolved.permissionCatalogDigest !== undefined && typeof resolved.permissionCatalogDigest !== "string" || resolved.applicationId !== options.applicationId || options.catalog !== undefined && (resolved.permissionCatalogVersion !== options.catalog.version || options.catalog.digest !== undefined && resolved.permissionCatalogDigest !== options.catalog.digest)) {
1912
1987
  throw new ApplicationError("Authorization context is not bound to this application", {
1913
1988
  status: 503,
1914
1989
  code: "AUTHORIZATION_CONTEXT_INVALID"
@@ -2017,11 +2092,11 @@ function safeHeaderValue(value, maxLength) {
2017
2092
  }
2018
2093
  return value;
2019
2094
  }
2020
- function isRecord(value) {
2095
+ function isRecord2(value) {
2021
2096
  return value !== null && typeof value === "object" && !Array.isArray(value);
2022
2097
  }
2023
2098
  function isTrustedIdentity(value) {
2024
- return isRecord(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2099
+ return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2025
2100
  }
2026
2101
  function isAuthenticatedTrustedIdentity(value) {
2027
2102
  return value?.authenticated === true && typeof value.subject === "string" && value.subject.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
@@ -2212,7 +2287,7 @@ function once(next) {
2212
2287
  };
2213
2288
  }
2214
2289
  function requireTrustedIdentity(requestContext) {
2215
- const context = isRecord(requestContext) ? requestContext : {};
2290
+ const context = isRecord2(requestContext) ? requestContext : {};
2216
2291
  const identity = isTrustedIdentity(context.identity) ? context.identity : undefined;
2217
2292
  if (!isAuthenticatedTrustedIdentity(identity)) {
2218
2293
  throw new ApplicationError("Authenticated user context is required", {
@@ -2223,7 +2298,7 @@ function requireTrustedIdentity(requestContext) {
2223
2298
  return identity;
2224
2299
  }
2225
2300
  function requireIdempotencyKey(invocation) {
2226
- const context = isRecord(invocation.requestContext) ? invocation.requestContext : {};
2301
+ const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2227
2302
  const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2228
2303
  if (!key) {
2229
2304
  throw new ApplicationError("Idempotency-Key header is required", {
@@ -2271,7 +2346,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2271
2346
  }
2272
2347
  if (command.rpc !== undefined) {
2273
2348
  const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2274
- if (!adapter || typeof adapter.execute !== "function" || !isRecord(adapter.capabilities)) {
2349
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2275
2350
  throw new ApplicationError(`Command "${command.name}" has no RPC governance adapter`, {
2276
2351
  code: "COMMAND_RPC_UNCONFIGURED"
2277
2352
  });
@@ -2299,14 +2374,14 @@ function joinPaths(prefix, path) {
2299
2374
  return joined.length > 1 ? joined.replace(/\/+$/, "") : joined;
2300
2375
  }
2301
2376
  function controllerInstance(value) {
2302
- return isRecord(value) ? value : undefined;
2377
+ return isRecord2(value) ? value : undefined;
2303
2378
  }
2304
2379
  function cookieValues(value) {
2305
- if (!isRecord(value))
2380
+ if (!isRecord2(value))
2306
2381
  return;
2307
2382
  const result = {};
2308
2383
  for (const [name, entry] of Object.entries(value)) {
2309
- result[name] = isRecord(entry) && "value" in entry ? entry.value : entry;
2384
+ result[name] = isRecord2(entry) && "value" in entry ? entry.value : entry;
2310
2385
  }
2311
2386
  return result;
2312
2387
  }
@@ -2338,6 +2413,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2338
2413
  "schemaKinds",
2339
2414
  "nativeResponse",
2340
2415
  "invoker",
2416
+ "effect",
2341
2417
  "command",
2342
2418
  "aspects",
2343
2419
  "aspectPipeline",
@@ -2377,6 +2453,15 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2377
2453
  code: "COMMAND_NOT_REGISTERED"
2378
2454
  });
2379
2455
  }
2456
+ if (route.effect?.retry === "explicit" && route.command) {
2457
+ const command = commandsByClassName.get(route.command);
2458
+ if (command && command.idempotency !== "required") {
2459
+ throw new ApplicationError(`Effect retry is not allowed for non-idempotent command "${command.name}"`, { code: "EFFECT_RETRY_IDEMPOTENCY_REQUIRED" });
2460
+ }
2461
+ }
2462
+ if (route.effect?.dependencies && route.effect.dependencies.length > 0 && !options.effectRuntime) {
2463
+ throw new ApplicationError(`Route ${route.method} ${controller.path}${route.path} declares Effect dependencies without an effectRuntime`, { code: "EFFECT_RUNTIME_UNCONFIGURED" });
2464
+ }
2380
2465
  }
2381
2466
  }
2382
2467
  const requestContexts = new WeakMap;
@@ -2537,12 +2622,13 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2537
2622
  requestContext
2538
2623
  };
2539
2624
  const handlerCall = () => route.invoker ? route.invoker(instance, input) : Reflect.apply(method, instance, [input]);
2540
- const invoke = once(() => route.command && options.commandGovernance ? handlerCall() : observeExecution(options.onExecution, {
2625
+ const invokeHandler = async () => runCompiledEffect(await handlerCall(), route.effect, options.effectRuntime);
2626
+ const invoke = once(() => route.command && options.commandGovernance ? invokeHandler() : observeExecution(options.onExecution, {
2541
2627
  kind: route.command ? "command" : "route",
2542
2628
  operation: route.command ?? `${route.method} ${path}`,
2543
2629
  stage: "handler",
2544
2630
  ...executionTrace(requestContext)
2545
- }, handlerCall));
2631
+ }, invokeHandler));
2546
2632
  const routeContext = {
2547
2633
  kind: "route",
2548
2634
  name: `${route.method} ${path}`,
@@ -2700,7 +2786,7 @@ function defaultErrorResponse(error, frameworkCode) {
2700
2786
  }, { status: 400 });
2701
2787
  }
2702
2788
  if (frameworkCode === "VALIDATION") {
2703
- if (isRecord(error) && error.type === "response") {
2789
+ if (isRecord2(error) && error.type === "response") {
2704
2790
  return Response.json({
2705
2791
  ok: false,
2706
2792
  code: "RESPONSE_VALIDATION_ERROR",
@@ -2720,7 +2806,7 @@ function defaultErrorResponse(error, frameworkCode) {
2720
2806
  }, { status: 500 });
2721
2807
  }
2722
2808
  function isPublicApplicationError(error) {
2723
- if (!(error instanceof Error) || !isRecord(error))
2809
+ if (!(error instanceof Error) || !isRecord2(error))
2724
2810
  return false;
2725
2811
  return error.expose === true && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 400 && error.status <= 599 && typeof error.code === "string" && error.code.length > 0;
2726
2812
  }
@@ -2829,6 +2915,7 @@ function createTestApp(options) {
2829
2915
  export {
2830
2916
  ApplicationError,
2831
2917
  EXECUTION_ID_HEADER,
2918
+ EffectApplicationError,
2832
2919
  HTTP_POLICY_STORE_SQL,
2833
2920
  HttpPolicyConfigurationError,
2834
2921
  IDEMPOTENCY_KEY_HEADER,
@@ -2846,7 +2933,9 @@ export {
2846
2933
  createApplication,
2847
2934
  createCommandAuthorizationAdapter,
2848
2935
  createCommandExecutor,
2936
+ createDefaultEffectRuntime,
2849
2937
  createDocumentationPlugin,
2938
+ createEffectRuntimeFromLayer,
2850
2939
  createHttpPolicySuite,
2851
2940
  createHttpTelemetry,
2852
2941
  createMemoryHttpCacheStore,
@@ -2877,6 +2966,7 @@ export {
2877
2966
  responseSchemaForStatus,
2878
2967
  responseStatusDeclared,
2879
2968
  responseStatusOf,
2969
+ runCompiledEffect,
2880
2970
  toElysiaRouteSchema,
2881
2971
  validatedJsonResponse
2882
2972
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/elysia",
3
- "version": "0.27.1",
3
+ "version": "0.29.0",
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",
@@ -23,7 +23,7 @@
23
23
  "scripts": {
24
24
  "generate:example": "bun src/generate-webhook-example.ts",
25
25
  "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 jose --external @supacloud/app --external @supacloud/db --external @supacloud/contracts",
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",
27
27
  "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
28
28
  "clean": "rm -rf dist",
29
29
  "prepublishOnly": "bun run build",
@@ -49,8 +49,9 @@
49
49
  "directory": "packages/elysia"
50
50
  },
51
51
  "dependencies": {
52
- "@supacloud/app": "0.23.0",
52
+ "@supacloud/app": "0.24.0",
53
53
  "@supacloud/contracts": "0.8.0",
54
+ "effect": "4.0.2",
54
55
  "exact-mirror": "1.2.6",
55
56
  "jose": "^6.2.11",
56
57
  "typebox": "1.3.34"
@@ -65,10 +66,10 @@
65
66
  "elysia": "2.0.0-beta.21"
66
67
  },
67
68
  "devDependencies": {
68
- "@supacloud/compiler": "0.40.1",
69
+ "@supacloud/compiler": "0.42.0",
69
70
  "@supacloud/delivery": "0.8.0",
70
71
  "@supacloud/commands": "0.9.1",
71
- "@supacloud/db": "0.13.2",
72
+ "@supacloud/db": "0.14.0",
72
73
  "@types/bun": "^1.4.2",
73
74
  "elysia": "2.0.0-beta.21",
74
75
  "typescript": "^7.0.2"