@supacloud/elysia 0.39.0 → 0.41.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
@@ -65,6 +65,41 @@ evidence. A server using this adapter still installs Elysia; application metadat
65
65
  and business modules need not import native Elysia types. See the
66
66
  [dependency boundary and upgrade policy](../../docs/elysia-compatibility.md).
67
67
 
68
+ ## Identity-bound ZenStack read adapter
69
+
70
+ `createZenStackReadPlugin` mounts explicit GET/HEAD resources on native Elysia 2.
71
+ Each request calls `bindIdentity`, receives the read-only `models` facade from
72
+ `createZenStackDatabase(...).forIdentity(...)`, and invokes one allow-listed
73
+ ZenStack read operation. TypeBox contracts and argument builders are supplied
74
+ per resource:
75
+
76
+ ```ts
77
+ const read = createZenStackReadPlugin({
78
+ resources: [{
79
+ path: "/model/orders/:id",
80
+ model: "order",
81
+ operation: "findUnique",
82
+ contract: { params: Type.Object({ id: Type.String() }) },
83
+ args: ({ params, identity }) => ({
84
+ where: { tenantId: identity, id: params["id"] },
85
+ }),
86
+ }],
87
+ bindIdentity: async request => ({
88
+ identity: await verifyTenant(request),
89
+ models: database.forIdentity(await verifyPrincipal(request)).models,
90
+ }),
91
+ });
92
+
93
+ const app = new Elysia().use(read);
94
+ ```
95
+
96
+ The adapter does not expose writes, raw clients, arbitrary model names, or
97
+ automatic CRUD routes. Durable writes remain Commands and use
98
+ `transaction.db`; business routes continue through the compiled module adapter.
99
+ The official `@zenstackhq/server` Elysia handler is not used here because its
100
+ current peer baseline targets Elysia 1.x and its generic CRUD surface would add
101
+ another application boundary.
102
+
68
103
  Run `bun run test:conformance` in this package after building the local
69
104
  `@supacloud/contracts` and `@supacloud/app` dependencies and installing this
70
105
  package's dependencies. The suite runs through `app.handle(Request)` without a
@@ -3,9 +3,8 @@
3
3
  "packages": {
4
4
  "elysia": "2.0.0-rc.1",
5
5
  "effect": "4.0.5",
6
- "typescript": "7.0.2",
6
+ "typescript": "7.1.0-beta",
7
7
  "typebox": "1.4.3",
8
- "exact-mirror": "1.2.6",
9
- "@typescript/typescript6": "6.0.2"
8
+ "exact-mirror": "1.2.6"
10
9
  }
11
10
  }
package/dist/bun-aot.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // src/index.ts
2
- import { Elysia as Elysia3, setupTypebox, Validator as Validator2 } from "elysia";
2
+ import { Elysia as Elysia4, setupTypebox, Validator as Validator2 } from "elysia";
3
3
  import { requireFeatureRequestContext } from "@supacloud/app";
4
+ import { composeAspects as composeApplicationAspects, invokeAspect, freezeAspectData } from "@supacloud/app/execution";
4
5
  import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/runtime";
5
6
  import { commandFailureMetadata as commandFailureMetadata3, decodeCommandPreview } from "@supacloud/contracts";
6
7
 
@@ -1154,6 +1155,64 @@ function bindCompiledCommand(options) {
1154
1155
  } : {}
1155
1156
  };
1156
1157
  }
1158
+ // src/zenstack-read.ts
1159
+ import { Elysia as Elysia3 } from "elysia";
1160
+ var READ_OPERATIONS = new Set([
1161
+ "findUnique",
1162
+ "findUniqueOrThrow",
1163
+ "findFirst",
1164
+ "findFirstOrThrow",
1165
+ "findMany",
1166
+ "count",
1167
+ "aggregate",
1168
+ "groupBy"
1169
+ ]);
1170
+ function isRecord2(value) {
1171
+ return value !== null && typeof value === "object";
1172
+ }
1173
+ function invokeRead(models, modelName, operation, args) {
1174
+ const model = Reflect.get(models, modelName);
1175
+ if (!model || typeof model !== "object")
1176
+ throw new Error(`ZenStack read model is unavailable: ${modelName}`);
1177
+ const method = Reflect.get(model, operation);
1178
+ if (typeof method !== "function")
1179
+ throw new Error(`ZenStack read operation is unavailable: ${modelName}.${operation}`);
1180
+ return Promise.resolve(args === undefined ? Reflect.apply(method, model, []) : Reflect.apply(method, model, [args]));
1181
+ }
1182
+ function createZenStackReadPlugin(options) {
1183
+ if (options.resources.length === 0)
1184
+ throw new TypeError("ZenStack read adapter requires at least one resource");
1185
+ const app = new Elysia3({ name: options.name ?? "supacloud:zenstack-read" });
1186
+ const paths = new Set;
1187
+ for (const resource of options.resources) {
1188
+ if (!resource.path.startsWith("/") || paths.has(resource.path)) {
1189
+ throw new TypeError(`Duplicate or invalid ZenStack read path: ${resource.path}`);
1190
+ }
1191
+ paths.add(resource.path);
1192
+ if (!READ_OPERATIONS.has(resource.operation)) {
1193
+ throw new TypeError(`Unsupported ZenStack read operation: ${resource.operation}`);
1194
+ }
1195
+ const contract = resource.contract ?? {};
1196
+ const schema = toElysiaRouteSchema(contract);
1197
+ const handler = async (context) => {
1198
+ const binding = await options.bindIdentity(context.request);
1199
+ if (!binding || !isRecord2(binding) || !isRecord2(binding.models) || binding.identity === null || binding.identity === undefined) {
1200
+ throw new Error("ZenStack identity binding must provide a read-only models facade");
1201
+ }
1202
+ const input = {
1203
+ request: context.request,
1204
+ params: isRecord2(context.params) ? context.params : {},
1205
+ query: isRecord2(context.query) ? context.query : {},
1206
+ headers: isRecord2(context.headers) ? context.headers : {},
1207
+ identity: binding.identity
1208
+ };
1209
+ return invokeRead(binding.models, resource.model, resource.operation, resource.args?.(input));
1210
+ };
1211
+ app.get(resource.path, schema, handler);
1212
+ app.head(resource.path, schema, handler);
1213
+ }
1214
+ return app;
1215
+ }
1157
1216
  // src/persistent-command.ts
1158
1217
  import {
1159
1218
  CommandError,
@@ -2054,22 +2113,7 @@ var IDEMPOTENCY_KEY_HEADER = "idempotency-key";
2054
2113
  var idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,512}$/;
2055
2114
  function composeAspects(...aspects) {
2056
2115
  const active = aspects.filter((aspect) => typeof aspect === "function");
2057
- if (active.length === 0)
2058
- return (_context, next) => next();
2059
- return (context, next) => {
2060
- let index = -1;
2061
- const dispatch = (current) => {
2062
- if (current <= index) {
2063
- return Promise.reject(new Error("next() called multiple times"));
2064
- }
2065
- index = current;
2066
- const aspect = active[current];
2067
- if (!aspect)
2068
- return Promise.resolve(next());
2069
- return Promise.resolve(aspect(context, () => dispatch(current + 1)));
2070
- };
2071
- return dispatch(0);
2072
- };
2116
+ return composeApplicationAspects(...active);
2073
2117
  }
2074
2118
  function observedAspects(aspects, boundary, observer) {
2075
2119
  return composeAspects(...aspects.map((aspect, index) => (context, next) => observeExecution(observer, {
@@ -2100,7 +2144,7 @@ function createCommandAuthorizationAdapter(options) {
2100
2144
  });
2101
2145
  }
2102
2146
  const context = invocation.requestContext;
2103
- const identity = isRecord2(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2147
+ const identity = isRecord3(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2104
2148
  if (!isAuthenticatedTrustedIdentity(identity)) {
2105
2149
  throw new ApplicationError("Authentication required", { status: 401, code: "AUTHENTICATION_REQUIRED" });
2106
2150
  }
@@ -2115,7 +2159,7 @@ function createCommandAuthorizationAdapter(options) {
2115
2159
  } catch {
2116
2160
  throw new ApplicationError("Authorization is unavailable", { status: 503, code: "AUTHORIZATION_UNAVAILABLE" });
2117
2161
  }
2118
- 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)) {
2162
+ if (!isRecord3(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)) {
2119
2163
  throw new ApplicationError("Authorization context is not bound to this application", {
2120
2164
  status: 503,
2121
2165
  code: "AUTHORIZATION_CONTEXT_INVALID"
@@ -2202,10 +2246,10 @@ function contextPlugin(http) {
2202
2246
  seed = ++nextHttpPluginId;
2203
2247
  httpPluginIds.set(http, seed);
2204
2248
  }
2205
- return new Elysia3({ name: "supacloud:http-context", seed }).use(http ?? new Elysia3).as("plugin");
2249
+ return new Elysia4({ name: "supacloud:http-context", seed }).use(http ?? new Elysia4).as("plugin");
2206
2250
  }
2207
2251
  function mountHttp(http, name, normalize = true) {
2208
- return new Elysia3({ name, normalize }).use(contextPlugin(http));
2252
+ return new Elysia4({ name, normalize }).use(contextPlugin(http));
2209
2253
  }
2210
2254
  function resolveCompiledCommand(module, reference) {
2211
2255
  const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
@@ -2230,14 +2274,14 @@ function safeHeaderValue(value, maxLength) {
2230
2274
  }
2231
2275
  return value;
2232
2276
  }
2233
- function isRecord2(value) {
2277
+ function isRecord3(value) {
2234
2278
  return value !== null && typeof value === "object" && !Array.isArray(value);
2235
2279
  }
2236
2280
  function isPromiseLike(value) {
2237
2281
  return value instanceof Promise;
2238
2282
  }
2239
2283
  function isTrustedIdentity(value) {
2240
- return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2284
+ return isRecord3(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2241
2285
  }
2242
2286
  function isAuthenticatedTrustedIdentity(value) {
2243
2287
  return value?.authenticated === true && typeof value.subject === "string" && value.subject.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
@@ -2302,7 +2346,7 @@ function selectCommandBranch(command, input) {
2302
2346
  const root = parts[0];
2303
2347
  let value = root === "body" || root === "params" || root === "query" ? input[root] : input.body;
2304
2348
  for (const part of root === "body" || root === "params" || root === "query" ? parts.slice(1) : parts) {
2305
- if (!isRecord2(value)) {
2349
+ if (!isRecord3(value)) {
2306
2350
  value = undefined;
2307
2351
  break;
2308
2352
  }
@@ -2481,7 +2525,7 @@ function once(next) {
2481
2525
  };
2482
2526
  }
2483
2527
  function requireTrustedIdentity(requestContext) {
2484
- const context = isRecord2(requestContext) ? requestContext : {};
2528
+ const context = isRecord3(requestContext) ? requestContext : {};
2485
2529
  const identity = isTrustedIdentity(context.identity) ? context.identity : undefined;
2486
2530
  if (!isAuthenticatedTrustedIdentity(identity)) {
2487
2531
  throw new ApplicationError("Authenticated user context is required", {
@@ -2492,7 +2536,7 @@ function requireTrustedIdentity(requestContext) {
2492
2536
  return identity;
2493
2537
  }
2494
2538
  function requireIdempotencyKey(invocation) {
2495
- const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2539
+ const context = isRecord3(invocation.requestContext) ? invocation.requestContext : {};
2496
2540
  const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2497
2541
  if (!key || !idempotencyKeyPattern.test(key)) {
2498
2542
  throw new ApplicationError("A valid Idempotency-Key header is required", {
@@ -2545,7 +2589,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2545
2589
  });
2546
2590
  }
2547
2591
  const adapter = Object.hasOwn(governance.rpc ?? {}, branch.rpc) ? governance.rpc?.[branch.rpc] : undefined;
2548
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2592
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2549
2593
  throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no RPC governance adapter`, {
2550
2594
  code: "COMMAND_RPC_UNCONFIGURED"
2551
2595
  });
@@ -2588,7 +2632,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2588
2632
  }
2589
2633
  if (command.rpc !== undefined) {
2590
2634
  const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2591
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2635
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2592
2636
  throw new ApplicationError(`Command "${command.name}" has no RPC governance adapter`, {
2593
2637
  code: "COMMAND_RPC_UNCONFIGURED"
2594
2638
  });
@@ -2616,17 +2660,17 @@ function joinPaths(prefix, path) {
2616
2660
  return joined.length > 1 ? joined.replace(/\/+$/, "") : joined;
2617
2661
  }
2618
2662
  function controllerInstance(value) {
2619
- return isRecord2(value) ? value : undefined;
2663
+ return isRecord3(value) ? value : undefined;
2620
2664
  }
2621
2665
  function canUseDirectRoute(compiled, controller, route) {
2622
2666
  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
2667
  }
2624
2668
  function cookieValues(value) {
2625
- if (!isRecord2(value))
2669
+ if (!isRecord3(value))
2626
2670
  return;
2627
2671
  const result = {};
2628
2672
  for (const [name, entry] of Object.entries(value)) {
2629
- result[name] = isRecord2(entry) && "value" in entry ? entry.value : entry;
2673
+ result[name] = isRecord3(entry) && "value" in entry ? entry.value : entry;
2630
2674
  }
2631
2675
  return result;
2632
2676
  }
@@ -2839,6 +2883,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2839
2883
  const routePipeline = descriptorPipeline(route, "route", options.onExecution);
2840
2884
  const command = route.command ? commandsByClassName.get(route.command) : undefined;
2841
2885
  const commandPipeline = route.command ? descriptorPipeline(command ?? {}, "command", options.onExecution) : undefined;
2886
+ const routeHasAspects = compiled.aspectPipeline !== undefined || (compiled.aspects?.length ?? 0) > 0 || route.aspectPipeline !== undefined || (route.aspects?.length ?? 0) > 0 || command?.aspectPipeline !== undefined || (command?.aspects?.length ?? 0) > 0;
2842
2887
  const routeInvoker = route.invoker;
2843
2888
  if (mappingPolicies.length > 0) {
2844
2889
  const responseValidators = Validator2.response(schema.response, { normalize: options.normalize ?? true });
@@ -2916,7 +2961,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2916
2961
  const handlerCall = () => {
2917
2962
  if (route.invoker)
2918
2963
  return route.invoker(instance, input);
2919
- if (!isRecord2(instance))
2964
+ if (!isRecord3(instance))
2920
2965
  throw new TypeError("Route controller is not an object");
2921
2966
  const method = instance[route.handler];
2922
2967
  if (typeof method !== "function")
@@ -2951,7 +2996,10 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2951
2996
  services,
2952
2997
  metadata: command ?? route
2953
2998
  };
2954
- const invokeRoute = () => modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
2999
+ const invokeRoute = () => route.command && routeHasAspects ? invokeAspect(commandContext, (_context, next) => modulePipeline(commandContext, () => routePipeline(routeContext, () => commandPipeline(commandContext, next))), invoke, (result) => {
3000
+ if (!(result instanceof Response))
3001
+ freezeAspectData(result);
3002
+ }) : modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
2955
3003
  const invokeCommand = () => {
2956
3004
  if (!route.command)
2957
3005
  return invokeRoute();
@@ -3105,7 +3153,7 @@ function defaultErrorResponse(error, frameworkCode) {
3105
3153
  }, { status: 400 });
3106
3154
  }
3107
3155
  if (frameworkCode === "VALIDATION") {
3108
- if (isRecord2(error) && error.type === "response") {
3156
+ if (isRecord3(error) && error.type === "response") {
3109
3157
  return Response.json({
3110
3158
  ok: false,
3111
3159
  code: "RESPONSE_VALIDATION_ERROR",
@@ -3125,13 +3173,13 @@ function defaultErrorResponse(error, frameworkCode) {
3125
3173
  }, { status: 500 });
3126
3174
  }
3127
3175
  function isPublicApplicationError(error) {
3128
- if (!(error instanceof Error) || !isRecord2(error))
3176
+ if (!(error instanceof Error) || !isRecord3(error))
3129
3177
  return false;
3130
3178
  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;
3131
3179
  }
3132
3180
  function createApplication(options) {
3133
3181
  const pendingWork = new PendingWorkRegistry2(options.pendingWork ? { capacity: options.pendingWork.capacity } : {});
3134
- const app = new Elysia3({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3182
+ const app = new Elysia4({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3135
3183
  if (options.documentation)
3136
3184
  app.use(createDocumentationPlugin(options.documentation));
3137
3185
  const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
package/dist/index.d.ts CHANGED
@@ -23,6 +23,8 @@ export type { CompiledCommandBinding, CompiledCommandBindingOptions, CompiledCom
23
23
  export { createSchemaDecoder, assertResponseStatusDeclared, defineElysiaRoute, defineJsonContract, defineRouteContract, registerElysiaRoute, responseSchemaForStatus, responseStatusDeclared, responseStatusOf, SchemaContractError, toElysiaRouteSchema, } from "./schema_contract";
24
24
  export { createDefaultEffectRuntime, createEffectRuntimeFromLayer, EffectApplicationError, runCompiledEffect, } from "./effect";
25
25
  export type { CompiledEffectDescriptor, SupaCloudEffectRuntime } from "./effect";
26
+ export { createZenStackReadPlugin } from "./zenstack-read";
27
+ export type { ZenStackReadAdapterOptions, ZenStackReadIdentityBinding, ZenStackReadInput, ZenStackReadModels, ZenStackReadOperation, ZenStackReadResource, } from "./zenstack-read";
26
28
  export type { ElysiaRouteContext, ElysiaRouteDefinition, ElysiaRouteHandler, ElysiaRouteSchema, ResponseMapSelector, RouteContractSchemas, SchemaDecoderOptions, SchemaNormalizeMode, } from "./schema_contract";
27
29
  export { createPersistentCommandAdapter, type PersistentCommandHandler } from "./persistent-command";
28
30
  export { createTransactionalCommandGovernance } from "./transactional-command";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // src/index.ts
2
- import { Elysia as Elysia3, setupTypebox, Validator as Validator2 } from "elysia";
2
+ import { Elysia as Elysia4, setupTypebox, Validator as Validator2 } from "elysia";
3
3
  import { requireFeatureRequestContext } from "@supacloud/app";
4
+ import { composeAspects as composeApplicationAspects, invokeAspect, freezeAspectData } from "@supacloud/app/execution";
4
5
  import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/runtime";
5
6
  import { commandFailureMetadata as commandFailureMetadata3, decodeCommandPreview } from "@supacloud/contracts";
6
7
 
@@ -1154,6 +1155,64 @@ function bindCompiledCommand(options) {
1154
1155
  } : {}
1155
1156
  };
1156
1157
  }
1158
+ // src/zenstack-read.ts
1159
+ import { Elysia as Elysia3 } from "elysia";
1160
+ var READ_OPERATIONS = new Set([
1161
+ "findUnique",
1162
+ "findUniqueOrThrow",
1163
+ "findFirst",
1164
+ "findFirstOrThrow",
1165
+ "findMany",
1166
+ "count",
1167
+ "aggregate",
1168
+ "groupBy"
1169
+ ]);
1170
+ function isRecord2(value) {
1171
+ return value !== null && typeof value === "object";
1172
+ }
1173
+ function invokeRead(models, modelName, operation, args) {
1174
+ const model = Reflect.get(models, modelName);
1175
+ if (!model || typeof model !== "object")
1176
+ throw new Error(`ZenStack read model is unavailable: ${modelName}`);
1177
+ const method = Reflect.get(model, operation);
1178
+ if (typeof method !== "function")
1179
+ throw new Error(`ZenStack read operation is unavailable: ${modelName}.${operation}`);
1180
+ return Promise.resolve(args === undefined ? Reflect.apply(method, model, []) : Reflect.apply(method, model, [args]));
1181
+ }
1182
+ function createZenStackReadPlugin(options) {
1183
+ if (options.resources.length === 0)
1184
+ throw new TypeError("ZenStack read adapter requires at least one resource");
1185
+ const app = new Elysia3({ name: options.name ?? "supacloud:zenstack-read" });
1186
+ const paths = new Set;
1187
+ for (const resource of options.resources) {
1188
+ if (!resource.path.startsWith("/") || paths.has(resource.path)) {
1189
+ throw new TypeError(`Duplicate or invalid ZenStack read path: ${resource.path}`);
1190
+ }
1191
+ paths.add(resource.path);
1192
+ if (!READ_OPERATIONS.has(resource.operation)) {
1193
+ throw new TypeError(`Unsupported ZenStack read operation: ${resource.operation}`);
1194
+ }
1195
+ const contract = resource.contract ?? {};
1196
+ const schema = toElysiaRouteSchema(contract);
1197
+ const handler = async (context) => {
1198
+ const binding = await options.bindIdentity(context.request);
1199
+ if (!binding || !isRecord2(binding) || !isRecord2(binding.models) || binding.identity === null || binding.identity === undefined) {
1200
+ throw new Error("ZenStack identity binding must provide a read-only models facade");
1201
+ }
1202
+ const input = {
1203
+ request: context.request,
1204
+ params: isRecord2(context.params) ? context.params : {},
1205
+ query: isRecord2(context.query) ? context.query : {},
1206
+ headers: isRecord2(context.headers) ? context.headers : {},
1207
+ identity: binding.identity
1208
+ };
1209
+ return invokeRead(binding.models, resource.model, resource.operation, resource.args?.(input));
1210
+ };
1211
+ app.get(resource.path, schema, handler);
1212
+ app.head(resource.path, schema, handler);
1213
+ }
1214
+ return app;
1215
+ }
1157
1216
  // src/persistent-command.ts
1158
1217
  import {
1159
1218
  CommandError,
@@ -2054,22 +2113,7 @@ var IDEMPOTENCY_KEY_HEADER = "idempotency-key";
2054
2113
  var idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,512}$/;
2055
2114
  function composeAspects(...aspects) {
2056
2115
  const active = aspects.filter((aspect) => typeof aspect === "function");
2057
- if (active.length === 0)
2058
- return (_context, next) => next();
2059
- return (context, next) => {
2060
- let index = -1;
2061
- const dispatch = (current) => {
2062
- if (current <= index) {
2063
- return Promise.reject(new Error("next() called multiple times"));
2064
- }
2065
- index = current;
2066
- const aspect = active[current];
2067
- if (!aspect)
2068
- return Promise.resolve(next());
2069
- return Promise.resolve(aspect(context, () => dispatch(current + 1)));
2070
- };
2071
- return dispatch(0);
2072
- };
2116
+ return composeApplicationAspects(...active);
2073
2117
  }
2074
2118
  function observedAspects(aspects, boundary, observer) {
2075
2119
  return composeAspects(...aspects.map((aspect, index) => (context, next) => observeExecution(observer, {
@@ -2100,7 +2144,7 @@ function createCommandAuthorizationAdapter(options) {
2100
2144
  });
2101
2145
  }
2102
2146
  const context = invocation.requestContext;
2103
- const identity = isRecord2(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2147
+ const identity = isRecord3(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2104
2148
  if (!isAuthenticatedTrustedIdentity(identity)) {
2105
2149
  throw new ApplicationError("Authentication required", { status: 401, code: "AUTHENTICATION_REQUIRED" });
2106
2150
  }
@@ -2115,7 +2159,7 @@ function createCommandAuthorizationAdapter(options) {
2115
2159
  } catch {
2116
2160
  throw new ApplicationError("Authorization is unavailable", { status: 503, code: "AUTHORIZATION_UNAVAILABLE" });
2117
2161
  }
2118
- 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)) {
2162
+ if (!isRecord3(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)) {
2119
2163
  throw new ApplicationError("Authorization context is not bound to this application", {
2120
2164
  status: 503,
2121
2165
  code: "AUTHORIZATION_CONTEXT_INVALID"
@@ -2202,10 +2246,10 @@ function contextPlugin(http) {
2202
2246
  seed = ++nextHttpPluginId;
2203
2247
  httpPluginIds.set(http, seed);
2204
2248
  }
2205
- return new Elysia3({ name: "supacloud:http-context", seed }).use(http ?? new Elysia3).as("plugin");
2249
+ return new Elysia4({ name: "supacloud:http-context", seed }).use(http ?? new Elysia4).as("plugin");
2206
2250
  }
2207
2251
  function mountHttp(http, name, normalize = true) {
2208
- return new Elysia3({ name, normalize }).use(contextPlugin(http));
2252
+ return new Elysia4({ name, normalize }).use(contextPlugin(http));
2209
2253
  }
2210
2254
  function resolveCompiledCommand(module, reference) {
2211
2255
  const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
@@ -2230,14 +2274,14 @@ function safeHeaderValue(value, maxLength) {
2230
2274
  }
2231
2275
  return value;
2232
2276
  }
2233
- function isRecord2(value) {
2277
+ function isRecord3(value) {
2234
2278
  return value !== null && typeof value === "object" && !Array.isArray(value);
2235
2279
  }
2236
2280
  function isPromiseLike(value) {
2237
2281
  return value instanceof Promise;
2238
2282
  }
2239
2283
  function isTrustedIdentity(value) {
2240
- return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2284
+ return isRecord3(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2241
2285
  }
2242
2286
  function isAuthenticatedTrustedIdentity(value) {
2243
2287
  return value?.authenticated === true && typeof value.subject === "string" && value.subject.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
@@ -2302,7 +2346,7 @@ function selectCommandBranch(command, input) {
2302
2346
  const root = parts[0];
2303
2347
  let value = root === "body" || root === "params" || root === "query" ? input[root] : input.body;
2304
2348
  for (const part of root === "body" || root === "params" || root === "query" ? parts.slice(1) : parts) {
2305
- if (!isRecord2(value)) {
2349
+ if (!isRecord3(value)) {
2306
2350
  value = undefined;
2307
2351
  break;
2308
2352
  }
@@ -2481,7 +2525,7 @@ function once(next) {
2481
2525
  };
2482
2526
  }
2483
2527
  function requireTrustedIdentity(requestContext) {
2484
- const context = isRecord2(requestContext) ? requestContext : {};
2528
+ const context = isRecord3(requestContext) ? requestContext : {};
2485
2529
  const identity = isTrustedIdentity(context.identity) ? context.identity : undefined;
2486
2530
  if (!isAuthenticatedTrustedIdentity(identity)) {
2487
2531
  throw new ApplicationError("Authenticated user context is required", {
@@ -2492,7 +2536,7 @@ function requireTrustedIdentity(requestContext) {
2492
2536
  return identity;
2493
2537
  }
2494
2538
  function requireIdempotencyKey(invocation) {
2495
- const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2539
+ const context = isRecord3(invocation.requestContext) ? invocation.requestContext : {};
2496
2540
  const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2497
2541
  if (!key || !idempotencyKeyPattern.test(key)) {
2498
2542
  throw new ApplicationError("A valid Idempotency-Key header is required", {
@@ -2545,7 +2589,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2545
2589
  });
2546
2590
  }
2547
2591
  const adapter = Object.hasOwn(governance.rpc ?? {}, branch.rpc) ? governance.rpc?.[branch.rpc] : undefined;
2548
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2592
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2549
2593
  throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no RPC governance adapter`, {
2550
2594
  code: "COMMAND_RPC_UNCONFIGURED"
2551
2595
  });
@@ -2588,7 +2632,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2588
2632
  }
2589
2633
  if (command.rpc !== undefined) {
2590
2634
  const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2591
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2635
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2592
2636
  throw new ApplicationError(`Command "${command.name}" has no RPC governance adapter`, {
2593
2637
  code: "COMMAND_RPC_UNCONFIGURED"
2594
2638
  });
@@ -2616,17 +2660,17 @@ function joinPaths(prefix, path) {
2616
2660
  return joined.length > 1 ? joined.replace(/\/+$/, "") : joined;
2617
2661
  }
2618
2662
  function controllerInstance(value) {
2619
- return isRecord2(value) ? value : undefined;
2663
+ return isRecord3(value) ? value : undefined;
2620
2664
  }
2621
2665
  function canUseDirectRoute(compiled, controller, route) {
2622
2666
  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
2667
  }
2624
2668
  function cookieValues(value) {
2625
- if (!isRecord2(value))
2669
+ if (!isRecord3(value))
2626
2670
  return;
2627
2671
  const result = {};
2628
2672
  for (const [name, entry] of Object.entries(value)) {
2629
- result[name] = isRecord2(entry) && "value" in entry ? entry.value : entry;
2673
+ result[name] = isRecord3(entry) && "value" in entry ? entry.value : entry;
2630
2674
  }
2631
2675
  return result;
2632
2676
  }
@@ -2839,6 +2883,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2839
2883
  const routePipeline = descriptorPipeline(route, "route", options.onExecution);
2840
2884
  const command = route.command ? commandsByClassName.get(route.command) : undefined;
2841
2885
  const commandPipeline = route.command ? descriptorPipeline(command ?? {}, "command", options.onExecution) : undefined;
2886
+ const routeHasAspects = compiled.aspectPipeline !== undefined || (compiled.aspects?.length ?? 0) > 0 || route.aspectPipeline !== undefined || (route.aspects?.length ?? 0) > 0 || command?.aspectPipeline !== undefined || (command?.aspects?.length ?? 0) > 0;
2842
2887
  const routeInvoker = route.invoker;
2843
2888
  if (mappingPolicies.length > 0) {
2844
2889
  const responseValidators = Validator2.response(schema.response, { normalize: options.normalize ?? true });
@@ -2916,7 +2961,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2916
2961
  const handlerCall = () => {
2917
2962
  if (route.invoker)
2918
2963
  return route.invoker(instance, input);
2919
- if (!isRecord2(instance))
2964
+ if (!isRecord3(instance))
2920
2965
  throw new TypeError("Route controller is not an object");
2921
2966
  const method = instance[route.handler];
2922
2967
  if (typeof method !== "function")
@@ -2951,7 +2996,10 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2951
2996
  services,
2952
2997
  metadata: command ?? route
2953
2998
  };
2954
- const invokeRoute = () => modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
2999
+ const invokeRoute = () => route.command && routeHasAspects ? invokeAspect(commandContext, (_context, next) => modulePipeline(commandContext, () => routePipeline(routeContext, () => commandPipeline(commandContext, next))), invoke, (result) => {
3000
+ if (!(result instanceof Response))
3001
+ freezeAspectData(result);
3002
+ }) : modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
2955
3003
  const invokeCommand = () => {
2956
3004
  if (!route.command)
2957
3005
  return invokeRoute();
@@ -3105,7 +3153,7 @@ function defaultErrorResponse(error, frameworkCode) {
3105
3153
  }, { status: 400 });
3106
3154
  }
3107
3155
  if (frameworkCode === "VALIDATION") {
3108
- if (isRecord2(error) && error.type === "response") {
3156
+ if (isRecord3(error) && error.type === "response") {
3109
3157
  return Response.json({
3110
3158
  ok: false,
3111
3159
  code: "RESPONSE_VALIDATION_ERROR",
@@ -3125,13 +3173,13 @@ function defaultErrorResponse(error, frameworkCode) {
3125
3173
  }, { status: 500 });
3126
3174
  }
3127
3175
  function isPublicApplicationError(error) {
3128
- if (!(error instanceof Error) || !isRecord2(error))
3176
+ if (!(error instanceof Error) || !isRecord3(error))
3129
3177
  return false;
3130
3178
  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;
3131
3179
  }
3132
3180
  function createApplication(options) {
3133
3181
  const pendingWork = new PendingWorkRegistry2(options.pendingWork ? { capacity: options.pendingWork.capacity } : {});
3134
- const app = new Elysia3({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3182
+ const app = new Elysia4({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3135
3183
  if (options.documentation)
3136
3184
  app.use(createDocumentationPlugin(options.documentation));
3137
3185
  const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
@@ -3279,6 +3327,7 @@ export {
3279
3327
  createTestApp,
3280
3328
  createTransactionalCommandGovernance,
3281
3329
  createWorker,
3330
+ createZenStackReadPlugin,
3282
3331
  defaultErrorResponse,
3283
3332
  defineElysiaRoute,
3284
3333
  defineJsonContract,
@@ -0,0 +1,48 @@
1
+ import { Elysia } from "elysia";
2
+ import type { TSchema } from "typebox";
3
+ import { type RouteContractSchemas } from "./schema_contract";
4
+ /** Read operations exposed by the identity-bound ZenStack facade. */
5
+ export type ZenStackReadOperation = "findUnique" | "findUniqueOrThrow" | "findFirst" | "findFirstOrThrow" | "findMany" | "count" | "aggregate" | "groupBy";
6
+ /** Structural facade so @supacloud/elysia does not depend on the DB package at runtime. */
7
+ export type ZenStackReadModels = object;
8
+ export interface ZenStackReadIdentityBinding {
9
+ /** Read-only model facade returned after trusted identity verification. */
10
+ readonly models: ZenStackReadModels;
11
+ /** Identity used to create the facade; available to the argument builder only. */
12
+ readonly identity: unknown;
13
+ }
14
+ export interface ZenStackReadInput {
15
+ readonly request: Request;
16
+ readonly params: Record<string, unknown>;
17
+ readonly query: Record<string, unknown>;
18
+ readonly headers: Record<string, unknown>;
19
+ readonly identity: unknown;
20
+ }
21
+ export interface ZenStackReadResource {
22
+ /** URL path. The path is registered as GET and HEAD only. */
23
+ readonly path: string;
24
+ /** Model key as exposed by ModelReadClient, for example `order`. */
25
+ readonly model: string;
26
+ readonly operation: ZenStackReadOperation;
27
+ /** Optional TypeBox request/response schemas. */
28
+ readonly contract?: RouteContractSchemas & {
29
+ readonly response?: TSchema;
30
+ };
31
+ /** Builds exact ZenStack query args from the decoded request and verified identity. */
32
+ readonly args?: (input: ZenStackReadInput) => unknown;
33
+ }
34
+ export interface ZenStackReadAdapterOptions {
35
+ readonly name?: string;
36
+ readonly resources: readonly ZenStackReadResource[];
37
+ /** Resolve and bind identity for every request. Never accept identity from query/body. */
38
+ readonly bindIdentity: (request: Request) => Promise<ZenStackReadIdentityBinding> | ZenStackReadIdentityBinding;
39
+ }
40
+ /**
41
+ * Mounts explicit, read-only ZenStack resources on native Elysia 2.
42
+ *
43
+ * This adapter intentionally does not use @zenstackhq/server automatic CRUD:
44
+ * the current server package targets Elysia 1.x and its generic CRUD surface
45
+ * would create a second application boundary. Each request binds identity,
46
+ * selects a read-only facade, and calls one allow-listed operation.
47
+ */
48
+ export declare function createZenStackReadPlugin(options: ZenStackReadAdapterOptions): Elysia;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/elysia",
3
- "version": "0.39.0",
3
+ "version": "0.41.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",
@@ -54,29 +54,31 @@
54
54
  "directory": "packages/elysia"
55
55
  },
56
56
  "dependencies": {
57
- "@supacloud/app": "0.37.0",
58
- "@supacloud/commands": "0.11.2",
59
- "@supacloud/contracts": "0.15.2",
57
+ "@supacloud/app": "0.39.0",
58
+ "@supacloud/commands": "0.12.0",
59
+ "@supacloud/contracts": "0.16.0",
60
60
  "effect": "4.0.5",
61
61
  "exact-mirror": "1.2.6",
62
62
  "jose": "^6.2.13",
63
63
  "typebox": "1.4.3"
64
64
  },
65
65
  "overrides": {
66
- "@supacloud/delivery": "0.24.0",
67
- "@supacloud/contracts": "0.15.2",
68
- "@supacloud/commands": "0.11.2",
69
- "@graphql-tools/utils": "^12.0.4"
66
+ "@supacloud/delivery": "0.25.0",
67
+ "@supacloud/contracts": "0.16.0",
68
+ "@supacloud/commands": "0.12.0",
69
+ "@graphql-tools/utils": "^12.0.4",
70
+ "deepmerge-ts": "8.0.2",
71
+ "prisma": "6.19.3"
70
72
  },
71
73
  "peerDependencies": {
72
74
  "elysia": "2.0.0-rc.1"
73
75
  },
74
76
  "devDependencies": {
75
- "@supacloud/compiler": "0.56.0",
76
- "@supacloud/delivery": "0.24.0",
77
- "@supacloud/db": "0.20.5",
77
+ "@supacloud/compiler": "0.58.0",
78
+ "@supacloud/delivery": "0.25.0",
79
+ "@supacloud/db": "0.22.0",
78
80
  "@types/bun": "^1.4.4",
79
81
  "elysia": "2.0.0-rc.1",
80
- "typescript": "^7.0.2"
82
+ "typescript": "7.1.0-beta"
81
83
  }
82
84
  }