@supacloud/elysia 0.40.0 → 0.42.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
package/dist/bun-aot.js CHANGED
@@ -1,5 +1,5 @@
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
4
  import { composeAspects as composeApplicationAspects, invokeAspect, freezeAspectData } from "@supacloud/app/execution";
5
5
  import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/runtime";
@@ -1155,6 +1155,64 @@ function bindCompiledCommand(options) {
1155
1155
  } : {}
1156
1156
  };
1157
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
+ }
1158
1216
  // src/persistent-command.ts
1159
1217
  import {
1160
1218
  CommandError,
@@ -1633,6 +1691,95 @@ function cloneValue(value) {
1633
1691
  }
1634
1692
  // src/worker.ts
1635
1693
  import { PendingWorkRegistry } from "@supacloud/app/runtime";
1694
+ function createRabbitMqQueuePort(options) {
1695
+ if (!options.channel || typeof options.channel.consume !== "function" || typeof options.channel.ack !== "function" || typeof options.channel.nack !== "function" || !/^[A-Za-z0-9_.:-]{1,255}$/.test(options.queue)) {
1696
+ throw new TypeError("RabbitMQ queue port options are invalid");
1697
+ }
1698
+ const prefetch = options.prefetch ?? 1;
1699
+ const timeoutMs = options.receiveTimeoutMs ?? 1000;
1700
+ if (!Number.isSafeInteger(prefetch) || prefetch < 1 || prefetch > 4096 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000) {
1701
+ throw new TypeError("RabbitMQ queue port limits are invalid");
1702
+ }
1703
+ const buffered = [];
1704
+ const pending = [];
1705
+ const deliveries = new Map;
1706
+ let consumer;
1707
+ let starting;
1708
+ let closed = false;
1709
+ const deliver = (message) => {
1710
+ if (message === null)
1711
+ return;
1712
+ const id = String(message.fields.deliveryTag);
1713
+ let payload;
1714
+ try {
1715
+ payload = JSON.parse(new TextDecoder().decode(message.content));
1716
+ } catch {
1717
+ options.channel.nack(message, false, false);
1718
+ return;
1719
+ }
1720
+ const value = { id, payload };
1721
+ deliveries.set(id, message);
1722
+ const waiter = pending.shift();
1723
+ if (waiter)
1724
+ waiter(value);
1725
+ else
1726
+ buffered.push({ message, value });
1727
+ };
1728
+ const start = async () => {
1729
+ if (closed)
1730
+ throw new Error("RABBITMQ_QUEUE_CLOSED");
1731
+ if (!starting) {
1732
+ starting = Promise.resolve(options.channel.prefetch(prefetch)).then(() => options.channel.consume(options.queue, deliver, { noAck: false })).then((value) => {
1733
+ consumer = value;
1734
+ });
1735
+ }
1736
+ await starting;
1737
+ };
1738
+ const receive = async () => {
1739
+ await start();
1740
+ const item = buffered.shift();
1741
+ if (item)
1742
+ return item.value;
1743
+ return new Promise((resolve) => {
1744
+ const timer = setTimeout(() => {
1745
+ const index = pending.indexOf(resolve);
1746
+ if (index >= 0)
1747
+ pending.splice(index, 1);
1748
+ resolve(null);
1749
+ }, timeoutMs);
1750
+ pending.push((value) => {
1751
+ clearTimeout(timer);
1752
+ resolve(value);
1753
+ });
1754
+ });
1755
+ };
1756
+ return {
1757
+ receive,
1758
+ ack(messageId) {
1759
+ const message = deliveries.get(String(messageId));
1760
+ if (!message)
1761
+ throw new Error("RABBITMQ_DELIVERY_UNKNOWN");
1762
+ deliveries.delete(String(messageId));
1763
+ options.channel.ack(message);
1764
+ },
1765
+ fail(messageId, failure) {
1766
+ const message = deliveries.get(String(messageId));
1767
+ if (!message)
1768
+ throw new Error("RABBITMQ_DELIVERY_UNKNOWN");
1769
+ deliveries.delete(String(messageId));
1770
+ options.channel.nack(message, false, failure?.deadLetter !== true);
1771
+ },
1772
+ async close() {
1773
+ closed = true;
1774
+ for (const resolve of pending.splice(0))
1775
+ resolve(null);
1776
+ if (consumer)
1777
+ await options.channel.cancel(consumer.consumerTag);
1778
+ consumer = undefined;
1779
+ starting = undefined;
1780
+ }
1781
+ };
1782
+ }
1636
1783
  function workerFailureMessage(error) {
1637
1784
  const message = error instanceof Error ? error.message : typeof error === "string" ? error : "Worker job failed";
1638
1785
  const normalized = message.replace(/[\u0000-\u001f\u007f]/g, " ").trim();
@@ -2086,7 +2233,7 @@ function createCommandAuthorizationAdapter(options) {
2086
2233
  });
2087
2234
  }
2088
2235
  const context = invocation.requestContext;
2089
- const identity = isRecord2(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2236
+ const identity = isRecord3(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2090
2237
  if (!isAuthenticatedTrustedIdentity(identity)) {
2091
2238
  throw new ApplicationError("Authentication required", { status: 401, code: "AUTHENTICATION_REQUIRED" });
2092
2239
  }
@@ -2101,7 +2248,7 @@ function createCommandAuthorizationAdapter(options) {
2101
2248
  } catch {
2102
2249
  throw new ApplicationError("Authorization is unavailable", { status: 503, code: "AUTHORIZATION_UNAVAILABLE" });
2103
2250
  }
2104
- 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)) {
2251
+ 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)) {
2105
2252
  throw new ApplicationError("Authorization context is not bound to this application", {
2106
2253
  status: 503,
2107
2254
  code: "AUTHORIZATION_CONTEXT_INVALID"
@@ -2188,10 +2335,10 @@ function contextPlugin(http) {
2188
2335
  seed = ++nextHttpPluginId;
2189
2336
  httpPluginIds.set(http, seed);
2190
2337
  }
2191
- return new Elysia3({ name: "supacloud:http-context", seed }).use(http ?? new Elysia3).as("plugin");
2338
+ return new Elysia4({ name: "supacloud:http-context", seed }).use(http ?? new Elysia4).as("plugin");
2192
2339
  }
2193
2340
  function mountHttp(http, name, normalize = true) {
2194
- return new Elysia3({ name, normalize }).use(contextPlugin(http));
2341
+ return new Elysia4({ name, normalize }).use(contextPlugin(http));
2195
2342
  }
2196
2343
  function resolveCompiledCommand(module, reference) {
2197
2344
  const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
@@ -2216,14 +2363,14 @@ function safeHeaderValue(value, maxLength) {
2216
2363
  }
2217
2364
  return value;
2218
2365
  }
2219
- function isRecord2(value) {
2366
+ function isRecord3(value) {
2220
2367
  return value !== null && typeof value === "object" && !Array.isArray(value);
2221
2368
  }
2222
2369
  function isPromiseLike(value) {
2223
2370
  return value instanceof Promise;
2224
2371
  }
2225
2372
  function isTrustedIdentity(value) {
2226
- return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2373
+ return isRecord3(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2227
2374
  }
2228
2375
  function isAuthenticatedTrustedIdentity(value) {
2229
2376
  return value?.authenticated === true && typeof value.subject === "string" && value.subject.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
@@ -2288,7 +2435,7 @@ function selectCommandBranch(command, input) {
2288
2435
  const root = parts[0];
2289
2436
  let value = root === "body" || root === "params" || root === "query" ? input[root] : input.body;
2290
2437
  for (const part of root === "body" || root === "params" || root === "query" ? parts.slice(1) : parts) {
2291
- if (!isRecord2(value)) {
2438
+ if (!isRecord3(value)) {
2292
2439
  value = undefined;
2293
2440
  break;
2294
2441
  }
@@ -2304,6 +2451,8 @@ function selectCommandBranch(command, input) {
2304
2451
  };
2305
2452
  }
2306
2453
  }
2454
+ if (command.branchesFallback === "command")
2455
+ return command;
2307
2456
  throw new ApplicationError(`Command "${command.name}" has no matching RPC branch`, {
2308
2457
  status: 422,
2309
2458
  code: "COMMAND_BRANCH_UNMATCHED"
@@ -2467,7 +2616,7 @@ function once(next) {
2467
2616
  };
2468
2617
  }
2469
2618
  function requireTrustedIdentity(requestContext) {
2470
- const context = isRecord2(requestContext) ? requestContext : {};
2619
+ const context = isRecord3(requestContext) ? requestContext : {};
2471
2620
  const identity = isTrustedIdentity(context.identity) ? context.identity : undefined;
2472
2621
  if (!isAuthenticatedTrustedIdentity(identity)) {
2473
2622
  throw new ApplicationError("Authenticated user context is required", {
@@ -2478,7 +2627,7 @@ function requireTrustedIdentity(requestContext) {
2478
2627
  return identity;
2479
2628
  }
2480
2629
  function requireIdempotencyKey(invocation) {
2481
- const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2630
+ const context = isRecord3(invocation.requestContext) ? invocation.requestContext : {};
2482
2631
  const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2483
2632
  if (!key || !idempotencyKeyPattern.test(key)) {
2484
2633
  throw new ApplicationError("A valid Idempotency-Key header is required", {
@@ -2519,6 +2668,11 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2519
2668
  });
2520
2669
  }
2521
2670
  for (const command of compiled.commands ?? []) {
2671
+ if (command.branchesFallback !== undefined && command.branchesFallback !== "reject" && command.branchesFallback !== "command") {
2672
+ throw new ApplicationError(`Command "${command.name}" has an invalid branches fallback`, {
2673
+ code: "COMMAND_BRANCH_FALLBACK_INVALID"
2674
+ });
2675
+ }
2522
2676
  if (command.rpc !== undefined && command.branches !== undefined) {
2523
2677
  throw new ApplicationError(`Command "${command.name}" declares both rpc and branches`, {
2524
2678
  code: "COMMAND_BRANCHES_CONFLICT"
@@ -2531,7 +2685,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2531
2685
  });
2532
2686
  }
2533
2687
  const adapter = Object.hasOwn(governance.rpc ?? {}, branch.rpc) ? governance.rpc?.[branch.rpc] : undefined;
2534
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2688
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2535
2689
  throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no RPC governance adapter`, {
2536
2690
  code: "COMMAND_RPC_UNCONFIGURED"
2537
2691
  });
@@ -2574,7 +2728,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2574
2728
  }
2575
2729
  if (command.rpc !== undefined) {
2576
2730
  const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2577
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2731
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2578
2732
  throw new ApplicationError(`Command "${command.name}" has no RPC governance adapter`, {
2579
2733
  code: "COMMAND_RPC_UNCONFIGURED"
2580
2734
  });
@@ -2602,17 +2756,17 @@ function joinPaths(prefix, path) {
2602
2756
  return joined.length > 1 ? joined.replace(/\/+$/, "") : joined;
2603
2757
  }
2604
2758
  function controllerInstance(value) {
2605
- return isRecord2(value) ? value : undefined;
2759
+ return isRecord3(value) ? value : undefined;
2606
2760
  }
2607
2761
  function canUseDirectRoute(compiled, controller, route) {
2608
2762
  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;
2609
2763
  }
2610
2764
  function cookieValues(value) {
2611
- if (!isRecord2(value))
2765
+ if (!isRecord3(value))
2612
2766
  return;
2613
2767
  const result = {};
2614
2768
  for (const [name, entry] of Object.entries(value)) {
2615
- result[name] = isRecord2(entry) && "value" in entry ? entry.value : entry;
2769
+ result[name] = isRecord3(entry) && "value" in entry ? entry.value : entry;
2616
2770
  }
2617
2771
  return result;
2618
2772
  }
@@ -2903,7 +3057,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2903
3057
  const handlerCall = () => {
2904
3058
  if (route.invoker)
2905
3059
  return route.invoker(instance, input);
2906
- if (!isRecord2(instance))
3060
+ if (!isRecord3(instance))
2907
3061
  throw new TypeError("Route controller is not an object");
2908
3062
  const method = instance[route.handler];
2909
3063
  if (typeof method !== "function")
@@ -3095,7 +3249,7 @@ function defaultErrorResponse(error, frameworkCode) {
3095
3249
  }, { status: 400 });
3096
3250
  }
3097
3251
  if (frameworkCode === "VALIDATION") {
3098
- if (isRecord2(error) && error.type === "response") {
3252
+ if (isRecord3(error) && error.type === "response") {
3099
3253
  return Response.json({
3100
3254
  ok: false,
3101
3255
  code: "RESPONSE_VALIDATION_ERROR",
@@ -3115,13 +3269,13 @@ function defaultErrorResponse(error, frameworkCode) {
3115
3269
  }, { status: 500 });
3116
3270
  }
3117
3271
  function isPublicApplicationError(error) {
3118
- if (!(error instanceof Error) || !isRecord2(error))
3272
+ if (!(error instanceof Error) || !isRecord3(error))
3119
3273
  return false;
3120
3274
  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;
3121
3275
  }
3122
3276
  function createApplication(options) {
3123
3277
  const pendingWork = new PendingWorkRegistry2(options.pendingWork ? { capacity: options.pendingWork.capacity } : {});
3124
- const app = new Elysia3({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3278
+ const app = new Elysia4({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3125
3279
  if (options.documentation)
3126
3280
  app.use(createDocumentationPlugin(options.documentation));
3127
3281
  const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
@@ -67,6 +67,7 @@ export interface CompiledRoute {
67
67
  export interface CompiledCommand {
68
68
  rpc?: string;
69
69
  branches?: readonly CompiledCommandBranch[];
70
+ branchesFallback?: "reject" | "command";
70
71
  className: string;
71
72
  name: string;
72
73
  permission: string;
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";
@@ -95,6 +97,7 @@ export type CompiledControllerInvokerTarget = Record<string, (...args: unknown[]
95
97
  export interface CompiledCommand {
96
98
  rpc?: string;
97
99
  branches?: readonly CompiledCommandBranch[];
100
+ branchesFallback?: "reject" | "command";
98
101
  className: string;
99
102
  name: string;
100
103
  permission?: string;
@@ -502,5 +505,5 @@ export { createMemorySandbox, } from "./memory";
502
505
  export type { HandleLike as MemoryHandleLike, MemoryDatabase, MemorySandbox, MemorySandboxOptions, MemoryStorage, MemoryStorageObject, } from "./memory";
503
506
  export { createMemoryPolicy } from "./memory_policy";
504
507
  export type { MemoryPolicy } from "./memory_policy";
505
- export { createQueueWorkerTransport, createWorker, SupaCloudWorker, WorkerRegistrationError, WorkerReceiptUnconfirmedError, } from "./worker";
506
- export type { WorkerAcknowledge, WorkerClaim, WorkerFail, WorkerOptions, QueueWorkerTransportOptions, WorkerQueueFailureOptions, WorkerQueueMessage, WorkerQueuePort, WorkerQueueReceiveOptions, WorkerReceiptContext, WorkerReceiptOperation, WorkerRunResult, WorkerState, WorkerTransport, } from "./worker";
508
+ export { createQueueWorkerTransport, createRabbitMqQueuePort, createWorker, SupaCloudWorker, WorkerRegistrationError, WorkerReceiptUnconfirmedError, } from "./worker";
509
+ export type { WorkerAcknowledge, WorkerClaim, WorkerFail, WorkerOptions, QueueWorkerTransportOptions, WorkerQueueFailureOptions, WorkerQueueMessage, WorkerQueuePort, WorkerQueueReceiveOptions, RabbitMqChannel, RabbitMqMessage, RabbitMqQueuePortOptions, WorkerReceiptContext, WorkerReceiptOperation, WorkerRunResult, WorkerState, WorkerTransport, } from "./worker";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
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
4
  import { composeAspects as composeApplicationAspects, invokeAspect, freezeAspectData } from "@supacloud/app/execution";
5
5
  import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/runtime";
@@ -1155,6 +1155,64 @@ function bindCompiledCommand(options) {
1155
1155
  } : {}
1156
1156
  };
1157
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
+ }
1158
1216
  // src/persistent-command.ts
1159
1217
  import {
1160
1218
  CommandError,
@@ -1633,6 +1691,95 @@ function cloneValue(value) {
1633
1691
  }
1634
1692
  // src/worker.ts
1635
1693
  import { PendingWorkRegistry } from "@supacloud/app/runtime";
1694
+ function createRabbitMqQueuePort(options) {
1695
+ if (!options.channel || typeof options.channel.consume !== "function" || typeof options.channel.ack !== "function" || typeof options.channel.nack !== "function" || !/^[A-Za-z0-9_.:-]{1,255}$/.test(options.queue)) {
1696
+ throw new TypeError("RabbitMQ queue port options are invalid");
1697
+ }
1698
+ const prefetch = options.prefetch ?? 1;
1699
+ const timeoutMs = options.receiveTimeoutMs ?? 1000;
1700
+ if (!Number.isSafeInteger(prefetch) || prefetch < 1 || prefetch > 4096 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000) {
1701
+ throw new TypeError("RabbitMQ queue port limits are invalid");
1702
+ }
1703
+ const buffered = [];
1704
+ const pending = [];
1705
+ const deliveries = new Map;
1706
+ let consumer;
1707
+ let starting;
1708
+ let closed = false;
1709
+ const deliver = (message) => {
1710
+ if (message === null)
1711
+ return;
1712
+ const id = String(message.fields.deliveryTag);
1713
+ let payload;
1714
+ try {
1715
+ payload = JSON.parse(new TextDecoder().decode(message.content));
1716
+ } catch {
1717
+ options.channel.nack(message, false, false);
1718
+ return;
1719
+ }
1720
+ const value = { id, payload };
1721
+ deliveries.set(id, message);
1722
+ const waiter = pending.shift();
1723
+ if (waiter)
1724
+ waiter(value);
1725
+ else
1726
+ buffered.push({ message, value });
1727
+ };
1728
+ const start = async () => {
1729
+ if (closed)
1730
+ throw new Error("RABBITMQ_QUEUE_CLOSED");
1731
+ if (!starting) {
1732
+ starting = Promise.resolve(options.channel.prefetch(prefetch)).then(() => options.channel.consume(options.queue, deliver, { noAck: false })).then((value) => {
1733
+ consumer = value;
1734
+ });
1735
+ }
1736
+ await starting;
1737
+ };
1738
+ const receive = async () => {
1739
+ await start();
1740
+ const item = buffered.shift();
1741
+ if (item)
1742
+ return item.value;
1743
+ return new Promise((resolve) => {
1744
+ const timer = setTimeout(() => {
1745
+ const index = pending.indexOf(resolve);
1746
+ if (index >= 0)
1747
+ pending.splice(index, 1);
1748
+ resolve(null);
1749
+ }, timeoutMs);
1750
+ pending.push((value) => {
1751
+ clearTimeout(timer);
1752
+ resolve(value);
1753
+ });
1754
+ });
1755
+ };
1756
+ return {
1757
+ receive,
1758
+ ack(messageId) {
1759
+ const message = deliveries.get(String(messageId));
1760
+ if (!message)
1761
+ throw new Error("RABBITMQ_DELIVERY_UNKNOWN");
1762
+ deliveries.delete(String(messageId));
1763
+ options.channel.ack(message);
1764
+ },
1765
+ fail(messageId, failure) {
1766
+ const message = deliveries.get(String(messageId));
1767
+ if (!message)
1768
+ throw new Error("RABBITMQ_DELIVERY_UNKNOWN");
1769
+ deliveries.delete(String(messageId));
1770
+ options.channel.nack(message, false, failure?.deadLetter !== true);
1771
+ },
1772
+ async close() {
1773
+ closed = true;
1774
+ for (const resolve of pending.splice(0))
1775
+ resolve(null);
1776
+ if (consumer)
1777
+ await options.channel.cancel(consumer.consumerTag);
1778
+ consumer = undefined;
1779
+ starting = undefined;
1780
+ }
1781
+ };
1782
+ }
1636
1783
  function workerFailureMessage(error) {
1637
1784
  const message = error instanceof Error ? error.message : typeof error === "string" ? error : "Worker job failed";
1638
1785
  const normalized = message.replace(/[\u0000-\u001f\u007f]/g, " ").trim();
@@ -2086,7 +2233,7 @@ function createCommandAuthorizationAdapter(options) {
2086
2233
  });
2087
2234
  }
2088
2235
  const context = invocation.requestContext;
2089
- const identity = isRecord2(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2236
+ const identity = isRecord3(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2090
2237
  if (!isAuthenticatedTrustedIdentity(identity)) {
2091
2238
  throw new ApplicationError("Authentication required", { status: 401, code: "AUTHENTICATION_REQUIRED" });
2092
2239
  }
@@ -2101,7 +2248,7 @@ function createCommandAuthorizationAdapter(options) {
2101
2248
  } catch {
2102
2249
  throw new ApplicationError("Authorization is unavailable", { status: 503, code: "AUTHORIZATION_UNAVAILABLE" });
2103
2250
  }
2104
- 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)) {
2251
+ 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)) {
2105
2252
  throw new ApplicationError("Authorization context is not bound to this application", {
2106
2253
  status: 503,
2107
2254
  code: "AUTHORIZATION_CONTEXT_INVALID"
@@ -2188,10 +2335,10 @@ function contextPlugin(http) {
2188
2335
  seed = ++nextHttpPluginId;
2189
2336
  httpPluginIds.set(http, seed);
2190
2337
  }
2191
- return new Elysia3({ name: "supacloud:http-context", seed }).use(http ?? new Elysia3).as("plugin");
2338
+ return new Elysia4({ name: "supacloud:http-context", seed }).use(http ?? new Elysia4).as("plugin");
2192
2339
  }
2193
2340
  function mountHttp(http, name, normalize = true) {
2194
- return new Elysia3({ name, normalize }).use(contextPlugin(http));
2341
+ return new Elysia4({ name, normalize }).use(contextPlugin(http));
2195
2342
  }
2196
2343
  function resolveCompiledCommand(module, reference) {
2197
2344
  const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
@@ -2216,14 +2363,14 @@ function safeHeaderValue(value, maxLength) {
2216
2363
  }
2217
2364
  return value;
2218
2365
  }
2219
- function isRecord2(value) {
2366
+ function isRecord3(value) {
2220
2367
  return value !== null && typeof value === "object" && !Array.isArray(value);
2221
2368
  }
2222
2369
  function isPromiseLike(value) {
2223
2370
  return value instanceof Promise;
2224
2371
  }
2225
2372
  function isTrustedIdentity(value) {
2226
- return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2373
+ return isRecord3(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2227
2374
  }
2228
2375
  function isAuthenticatedTrustedIdentity(value) {
2229
2376
  return value?.authenticated === true && typeof value.subject === "string" && value.subject.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
@@ -2288,7 +2435,7 @@ function selectCommandBranch(command, input) {
2288
2435
  const root = parts[0];
2289
2436
  let value = root === "body" || root === "params" || root === "query" ? input[root] : input.body;
2290
2437
  for (const part of root === "body" || root === "params" || root === "query" ? parts.slice(1) : parts) {
2291
- if (!isRecord2(value)) {
2438
+ if (!isRecord3(value)) {
2292
2439
  value = undefined;
2293
2440
  break;
2294
2441
  }
@@ -2304,6 +2451,8 @@ function selectCommandBranch(command, input) {
2304
2451
  };
2305
2452
  }
2306
2453
  }
2454
+ if (command.branchesFallback === "command")
2455
+ return command;
2307
2456
  throw new ApplicationError(`Command "${command.name}" has no matching RPC branch`, {
2308
2457
  status: 422,
2309
2458
  code: "COMMAND_BRANCH_UNMATCHED"
@@ -2467,7 +2616,7 @@ function once(next) {
2467
2616
  };
2468
2617
  }
2469
2618
  function requireTrustedIdentity(requestContext) {
2470
- const context = isRecord2(requestContext) ? requestContext : {};
2619
+ const context = isRecord3(requestContext) ? requestContext : {};
2471
2620
  const identity = isTrustedIdentity(context.identity) ? context.identity : undefined;
2472
2621
  if (!isAuthenticatedTrustedIdentity(identity)) {
2473
2622
  throw new ApplicationError("Authenticated user context is required", {
@@ -2478,7 +2627,7 @@ function requireTrustedIdentity(requestContext) {
2478
2627
  return identity;
2479
2628
  }
2480
2629
  function requireIdempotencyKey(invocation) {
2481
- const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2630
+ const context = isRecord3(invocation.requestContext) ? invocation.requestContext : {};
2482
2631
  const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2483
2632
  if (!key || !idempotencyKeyPattern.test(key)) {
2484
2633
  throw new ApplicationError("A valid Idempotency-Key header is required", {
@@ -2519,6 +2668,11 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2519
2668
  });
2520
2669
  }
2521
2670
  for (const command of compiled.commands ?? []) {
2671
+ if (command.branchesFallback !== undefined && command.branchesFallback !== "reject" && command.branchesFallback !== "command") {
2672
+ throw new ApplicationError(`Command "${command.name}" has an invalid branches fallback`, {
2673
+ code: "COMMAND_BRANCH_FALLBACK_INVALID"
2674
+ });
2675
+ }
2522
2676
  if (command.rpc !== undefined && command.branches !== undefined) {
2523
2677
  throw new ApplicationError(`Command "${command.name}" declares both rpc and branches`, {
2524
2678
  code: "COMMAND_BRANCHES_CONFLICT"
@@ -2531,7 +2685,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2531
2685
  });
2532
2686
  }
2533
2687
  const adapter = Object.hasOwn(governance.rpc ?? {}, branch.rpc) ? governance.rpc?.[branch.rpc] : undefined;
2534
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2688
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2535
2689
  throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no RPC governance adapter`, {
2536
2690
  code: "COMMAND_RPC_UNCONFIGURED"
2537
2691
  });
@@ -2574,7 +2728,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2574
2728
  }
2575
2729
  if (command.rpc !== undefined) {
2576
2730
  const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2577
- if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2731
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord3(adapter.capabilities)) {
2578
2732
  throw new ApplicationError(`Command "${command.name}" has no RPC governance adapter`, {
2579
2733
  code: "COMMAND_RPC_UNCONFIGURED"
2580
2734
  });
@@ -2602,17 +2756,17 @@ function joinPaths(prefix, path) {
2602
2756
  return joined.length > 1 ? joined.replace(/\/+$/, "") : joined;
2603
2757
  }
2604
2758
  function controllerInstance(value) {
2605
- return isRecord2(value) ? value : undefined;
2759
+ return isRecord3(value) ? value : undefined;
2606
2760
  }
2607
2761
  function canUseDirectRoute(compiled, controller, route) {
2608
2762
  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;
2609
2763
  }
2610
2764
  function cookieValues(value) {
2611
- if (!isRecord2(value))
2765
+ if (!isRecord3(value))
2612
2766
  return;
2613
2767
  const result = {};
2614
2768
  for (const [name, entry] of Object.entries(value)) {
2615
- result[name] = isRecord2(entry) && "value" in entry ? entry.value : entry;
2769
+ result[name] = isRecord3(entry) && "value" in entry ? entry.value : entry;
2616
2770
  }
2617
2771
  return result;
2618
2772
  }
@@ -2903,7 +3057,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2903
3057
  const handlerCall = () => {
2904
3058
  if (route.invoker)
2905
3059
  return route.invoker(instance, input);
2906
- if (!isRecord2(instance))
3060
+ if (!isRecord3(instance))
2907
3061
  throw new TypeError("Route controller is not an object");
2908
3062
  const method = instance[route.handler];
2909
3063
  if (typeof method !== "function")
@@ -3095,7 +3249,7 @@ function defaultErrorResponse(error, frameworkCode) {
3095
3249
  }, { status: 400 });
3096
3250
  }
3097
3251
  if (frameworkCode === "VALIDATION") {
3098
- if (isRecord2(error) && error.type === "response") {
3252
+ if (isRecord3(error) && error.type === "response") {
3099
3253
  return Response.json({
3100
3254
  ok: false,
3101
3255
  code: "RESPONSE_VALIDATION_ERROR",
@@ -3115,13 +3269,13 @@ function defaultErrorResponse(error, frameworkCode) {
3115
3269
  }, { status: 500 });
3116
3270
  }
3117
3271
  function isPublicApplicationError(error) {
3118
- if (!(error instanceof Error) || !isRecord2(error))
3272
+ if (!(error instanceof Error) || !isRecord3(error))
3119
3273
  return false;
3120
3274
  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;
3121
3275
  }
3122
3276
  function createApplication(options) {
3123
3277
  const pendingWork = new PendingWorkRegistry2(options.pendingWork ? { capacity: options.pendingWork.capacity } : {});
3124
- const app = new Elysia3({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3278
+ const app = new Elysia4({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3125
3279
  if (options.documentation)
3126
3280
  app.use(createDocumentationPlugin(options.documentation));
3127
3281
  const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
@@ -3262,6 +3416,7 @@ export {
3262
3416
  createPersistentCommandAdapter,
3263
3417
  createPostgresHttpPolicyStores,
3264
3418
  createQueueWorkerTransport,
3419
+ createRabbitMqQueuePort,
3265
3420
  createSchemaDecoder,
3266
3421
  createSupAuthRequestContext,
3267
3422
  createSupaCloudFramework,
@@ -3269,6 +3424,7 @@ export {
3269
3424
  createTestApp,
3270
3425
  createTransactionalCommandGovernance,
3271
3426
  createWorker,
3427
+ createZenStackReadPlugin,
3272
3428
  defaultErrorResponse,
3273
3429
  defineElysiaRoute,
3274
3430
  defineJsonContract,
package/dist/worker.d.ts CHANGED
@@ -31,6 +31,39 @@ export interface WorkerQueueFailureOptions {
31
31
  error?: string;
32
32
  deadLetter?: boolean;
33
33
  }
34
+ /** Minimal AMQP 0-9-1 channel shape; keeps RabbitMQ optional at package level. */
35
+ export interface RabbitMqChannel {
36
+ prefetch(count: number): Promise<void> | void;
37
+ consume(queue: string, onMessage: (message: RabbitMqMessage | null) => void, options?: {
38
+ noAck?: boolean;
39
+ }): Promise<{
40
+ consumerTag: string;
41
+ }>;
42
+ ack(message: RabbitMqMessage): void;
43
+ nack(message: RabbitMqMessage, allUpTo?: boolean, requeue?: boolean): void;
44
+ cancel(consumerTag: string): Promise<void> | void;
45
+ }
46
+ export interface RabbitMqMessage {
47
+ content: Uint8Array;
48
+ fields: {
49
+ deliveryTag: number;
50
+ };
51
+ properties?: Readonly<Record<string, unknown>>;
52
+ }
53
+ export interface RabbitMqQueuePortOptions {
54
+ queue: string;
55
+ channel: RabbitMqChannel;
56
+ prefetch?: number;
57
+ receiveTimeoutMs?: number;
58
+ }
59
+ /**
60
+ * Adapts an AMQP consumer to the same pull/ack/fail port used by the native
61
+ * SupaCloud queue client. The channel owns redelivery; the worker owns JSON
62
+ * decoding and business idempotency.
63
+ */
64
+ export declare function createRabbitMqQueuePort(options: RabbitMqQueuePortOptions): WorkerQueuePort & {
65
+ close(): Promise<void>;
66
+ };
34
67
  /** Structural port implemented by `client.queue(name)` without a package dependency. */
35
68
  export interface WorkerQueuePort<TMessage extends WorkerQueueMessage = WorkerQueueMessage, TReceipt = unknown> {
36
69
  receive(options?: WorkerQueueReceiveOptions): Promise<TMessage | null>;
@@ -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.40.0",
3
+ "version": "0.42.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,7 +54,7 @@
54
54
  "directory": "packages/elysia"
55
55
  },
56
56
  "dependencies": {
57
- "@supacloud/app": "0.38.0",
57
+ "@supacloud/app": "0.39.1",
58
58
  "@supacloud/commands": "0.12.0",
59
59
  "@supacloud/contracts": "0.16.0",
60
60
  "effect": "4.0.5",
@@ -63,7 +63,7 @@
63
63
  "typebox": "1.4.3"
64
64
  },
65
65
  "overrides": {
66
- "@supacloud/delivery": "0.25.0",
66
+ "@supacloud/delivery": "0.26.0",
67
67
  "@supacloud/contracts": "0.16.0",
68
68
  "@supacloud/commands": "0.12.0",
69
69
  "@graphql-tools/utils": "^12.0.4",
@@ -74,9 +74,9 @@
74
74
  "elysia": "2.0.0-rc.1"
75
75
  },
76
76
  "devDependencies": {
77
- "@supacloud/compiler": "0.57.0",
78
- "@supacloud/delivery": "0.25.0",
79
- "@supacloud/db": "0.21.0",
77
+ "@supacloud/compiler": "0.59.0",
78
+ "@supacloud/delivery": "0.26.0",
79
+ "@supacloud/db": "0.23.1",
80
80
  "@types/bun": "^1.4.4",
81
81
  "elysia": "2.0.0-rc.1",
82
82
  "typescript": "7.1.0-beta"