logic-sdk 0.0.0-stage → 0.2.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/src/index.ts ADDED
@@ -0,0 +1,736 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+
3
+ /* ────────────────────────────────────────────────────────────────────────────
4
+ * Types
5
+ * ──────────────────────────────────────────────────────────────────────────── */
6
+
7
+ type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
8
+ type In<S> = S extends Schema<infer I, any> ? I : never;
9
+ type Out<S> = S extends Schema<any, infer O> ? O : never;
10
+
11
+ /** What you declare once in `init<...>()`. */
12
+ export interface Config {
13
+ /** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
14
+ scope: object;
15
+ /** The transaction handle mutations receive (e.g. a Drizzle transaction). */
16
+ db?: unknown;
17
+ /** What queries receive. Defaults to `db`. Use a read-only type (e.g. `DrizzleReader<Tx>`). */
18
+ reader?: unknown;
19
+ /** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
20
+ services?: object;
21
+ /** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
22
+ meta?: object;
23
+ }
24
+ type ScopeOf<C extends Config> = C["scope"];
25
+ type DbOf<C extends Config> = C extends { db: infer D } ? D : never;
26
+ type ReaderOf<C extends Config> = C extends { reader: infer R } ? R : DbOf<C>;
27
+ type ServicesOf<C extends Config> = C extends { services: infer S } ? S : {};
28
+ type MetaOf<C extends Config> = C extends { meta: infer M } ? M : never;
29
+
30
+ export type Kind = "query" | "mutation" | "action";
31
+
32
+ declare const types: unique symbol;
33
+ const BRAND: unique symbol = Symbol.for("logic-sdk.brand") as any;
34
+
35
+ /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
36
+ export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean = boolean> {
37
+ readonly [BRAND]: K;
38
+ readonly kind: K;
39
+ readonly description: string;
40
+ readonly inputSchema: Schema;
41
+ readonly outputSchema?: Schema;
42
+ /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
43
+ readonly meta?: any;
44
+ /** Who may call it (from `authorize`). Runs on every call, before validation. */
45
+ readonly authorize?: Policy<any>;
46
+ /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
47
+ readonly expose?: true;
48
+ readonly execute: (input: any, ctx: any) => Promise<any>;
49
+ /** Phantom types, never set at runtime. */
50
+ readonly [types]?: { input: I; output: O; exposed: E };
51
+ }
52
+ /** A function with `expose: true`: adapters may publish it. */
53
+ export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
54
+ /** What callers pass to a function. */
55
+ export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
56
+ /** What a function returns. */
57
+ export type FnOut<F> = F extends Fn<any, any, infer O> ? O : never;
58
+
59
+ /** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
60
+ export interface EventDef<I = any, O = I> {
61
+ readonly [BRAND]: "event";
62
+ readonly kind: "event";
63
+ readonly schema: Schema;
64
+ readonly description?: string;
65
+ readonly [types]?: { input: I; payload: O };
66
+ }
67
+
68
+ /**
69
+ * What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
70
+ * and listeners get it parsed again by the event's schema at delivery.
71
+ */
72
+ export interface Envelope<P = unknown, S = object> {
73
+ id: string;
74
+ name: string;
75
+ payload: P;
76
+ scope: S;
77
+ occurredAt: string;
78
+ }
79
+
80
+ export interface Listener<O = any> {
81
+ readonly [BRAND]: "listener";
82
+ readonly kind: "listener";
83
+ /** Lazy, so listeners can import other modules' barrels without import cycles. */
84
+ readonly event: () => EventDef<any, O>;
85
+ readonly description?: string;
86
+ readonly execute: (payload: O, ctx: any) => Promise<unknown>;
87
+ }
88
+
89
+ type Run<Allowed extends Kind> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>) => Promise<FnOut<F>>;
90
+
91
+ /**
92
+ * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
93
+ * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
94
+ */
95
+ export interface Errors {
96
+ /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
97
+ reject(code: string, details?: unknown): DomainError;
98
+ /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
99
+ conflict(code: string, details?: unknown): DomainError;
100
+ /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
101
+ notFound(code?: string, details?: unknown): DomainError;
102
+ /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
103
+ deny(code?: string, details?: unknown): DomainError;
104
+ }
105
+ interface BaseCtx<S> {
106
+ scope: S;
107
+ /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
108
+ errors: Errors;
109
+ /** Current time. Fixed in tests. */
110
+ now: () => Date;
111
+ }
112
+ /** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
113
+ export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
114
+ db: ReaderOf<C>;
115
+ run: Run<"query">;
116
+ /** The caller's abort signal, if any. */
117
+ signal: AbortSignal | undefined;
118
+ with(patch: Partial<ScopeOf<C>>): QueryCtx<C>;
119
+ }
120
+ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
121
+ db: DbOf<C>;
122
+ run: Run<"query" | "mutation">;
123
+ /** Queue an event. Delivered to listeners only after the transaction commits. */
124
+ emit<I>(event: EventDef<I, any>, payload: I): void;
125
+ signal: AbortSignal | undefined;
126
+ with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
127
+ }
128
+ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
129
+ services: ServicesOf<C>;
130
+ /** Each mutation you run here gets its own transaction. */
131
+ run: Run<Kind>;
132
+ /** The caller's abort signal. Always undefined in listeners (they outlive the request). */
133
+ signal: AbortSignal | undefined;
134
+ with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
135
+ }
136
+ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
137
+ event: Envelope<unknown, ScopeOf<C>> & { payload: O };
138
+ }
139
+
140
+ /**
141
+ * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
142
+ * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
143
+ * Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
144
+ */
145
+ export type Policy<S> = (scope: S) => boolean;
146
+ type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
147
+ type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
148
+ ? QueryCtx<C, S>
149
+ : K extends "mutation"
150
+ ? MutationCtx<C, S>
151
+ : ActionCtx<C, S>;
152
+
153
+ type Def<IS extends Schema, Ctx, R> = {
154
+ /** One sentence, shown to humans, adapters and AI tools. */
155
+ description: string;
156
+ inputSchema: IS;
157
+ execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
158
+ };
159
+ type NotExposed = { expose?: undefined };
160
+ type NoPolicy = { authorize?: undefined };
161
+ type WithMeta<C extends Config> = { meta?: MetaOf<C> };
162
+ type WithOutput<OS extends Schema> = { outputSchema: OS };
163
+
164
+ /**
165
+ * `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
166
+ * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
167
+ */
168
+ interface Constructor<C extends Config, K extends Kind> {
169
+ <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
170
+ def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> &
171
+ WithOutput<OS> &
172
+ WithMeta<C> & { authorize: P; expose: true },
173
+ ): Fn<K, In<IS>, Out<OS>, true>;
174
+ <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
175
+ def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { authorize: P } & NotExposed,
176
+ ): Fn<K, In<IS>, Out<OS>, false>;
177
+ <IS extends Schema, R, P extends Policy<ScopeOf<C>>>(
178
+ def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & { authorize: P } & NotExposed,
179
+ ): Fn<K, In<IS>, R, false>;
180
+ <IS extends Schema, OS extends Schema>(
181
+ def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed,
182
+ ): Fn<K, In<IS>, Out<OS>, false>;
183
+ <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
184
+ }
185
+
186
+ /* ────────────────────────────────────────────────────────────────────────────
187
+ * Errors
188
+ * ──────────────────────────────────────────────────────────────────────────── */
189
+
190
+ export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
191
+
192
+ /**
193
+ * An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
194
+ * adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
195
+ * bugs) is unexpected: adapters answer 500 and report it.
196
+ */
197
+ export class DomainError extends Error {
198
+ readonly kind: ErrorKind;
199
+ readonly code: string;
200
+ readonly details: unknown;
201
+ constructor(kind: ErrorKind, code: string, details?: unknown) {
202
+ // the details are in the message too: logs and AI tool errors (which show only the message) stay useful
203
+ super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
204
+ this.name = "DomainError";
205
+ this.kind = kind;
206
+ this.code = code;
207
+ this.details = details;
208
+ }
209
+ }
210
+ /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
211
+ export const isDomainError = (e: unknown, code?: string): e is DomainError =>
212
+ e instanceof DomainError && (code === undefined || e.code === code);
213
+
214
+ /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
215
+ const errorsFor = (id: string): Errors => {
216
+ const module = id.slice(0, id.indexOf("."));
217
+ return {
218
+ reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
219
+ conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
220
+ notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
221
+ deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
222
+ };
223
+ };
224
+
225
+ /* ────────────────────────────────────────────────────────────────────────────
226
+ * Adapters and dispatcher seams
227
+ * ──────────────────────────────────────────────────────────────────────────── */
228
+
229
+ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
230
+ /** Root handle, used by top-level queries. */
231
+ readonly db: Db;
232
+ readonly transactions: "interactive";
233
+ transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
234
+ /** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
235
+ nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
236
+ /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
237
+ retryable?(error: unknown): boolean;
238
+ }
239
+
240
+ export interface Dispatcher {
241
+ /** Inside the transaction, before commit. In-process: nothing. Outbox: insert rows with `tx`. */
242
+ enqueue?(tx: unknown, envelopes: Envelope[]): Promise<void>;
243
+ /** After commit. `dispatch` runs the listeners for one envelope and never throws (failures go to `onError`). */
244
+ deliver(envelopes: Envelope[], dispatch: (envelope: Envelope) => Promise<void>): Promise<void>;
245
+ }
246
+
247
+ /** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
248
+ export const inProcess = (): Dispatcher => ({
249
+ async deliver(envelopes, dispatch) {
250
+ for (const e of envelopes) await dispatch(e);
251
+ },
252
+ });
253
+
254
+ export interface Call<M = unknown> {
255
+ id: string;
256
+ kind: Kind | "listener";
257
+ /** The function's `meta` (undefined for listeners and functions without it). */
258
+ meta: M | undefined;
259
+ /** Raw input as received (before validation). */
260
+ input: unknown;
261
+ scope: object;
262
+ depth: number;
263
+ }
264
+
265
+ export interface RegistryOptions<Mods extends Record<string, object>> {
266
+ /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
267
+ modules: Mods;
268
+ database?: DatabaseAdapter<any, any>;
269
+ services?: object;
270
+ events?: Dispatcher;
271
+ /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
272
+ wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
273
+ /**
274
+ * Serverless: let listeners finish after the response. Pass the platform's global:
275
+ * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
276
+ * Without it, `run` waits for listeners, which is what tests and long-lived servers want.
277
+ */
278
+ waitUntil?: (promise: Promise<unknown>) => void;
279
+ /** Failures after commit land here (listeners, dispatcher). They never fail the caller. */
280
+ onError?: (error: unknown, info: { listener: string; envelope: Envelope | undefined }) => void;
281
+ now?: () => Date;
282
+ /** Max chain of listener → mutation → event → listener… before delivery stops. Default 8 (real chains are 2 or 3). */
283
+ maxEventDepth?: number;
284
+ /**
285
+ * Re-run a top-level mutation in a fresh transaction when the database says it lost a race (deadlock,
286
+ * serialization failure). Safe because mutations have no side effects and events are rebuilt per attempt.
287
+ * Default 3 attempts in total; `{ attempts: 1 }` turns it off.
288
+ */
289
+ retry?: { attempts?: number };
290
+ }
291
+
292
+ export interface CallerOptions {
293
+ /** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
294
+ signal?: AbortSignal;
295
+ }
296
+
297
+ /** A registry bound to a scope: `const caller = registry.as(scope)`. */
298
+ export interface Caller<S extends object = object> {
299
+ readonly scope: S;
300
+ run<F extends Fn>(fn: F, input: FnIn<F>): Promise<FnOut<F>>;
301
+ with(patch: Partial<S>): Caller<S>;
302
+ }
303
+
304
+ export interface Registered {
305
+ id: string;
306
+ module: string;
307
+ name: string;
308
+ }
309
+ export interface RegisteredFn extends Registered {
310
+ fn: Fn;
311
+ kind: Kind;
312
+ /** Has `expose: true`: adapters may publish it. */
313
+ exposed: boolean;
314
+ }
315
+
316
+ /* ────────────────────────────────────────────────────────────────────────────
317
+ * init: typed constructors
318
+ * ──────────────────────────────────────────────────────────────────────────── */
319
+
320
+ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<RegistryOptions<Mods>, "wrap"> & {
321
+ /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
322
+ wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
323
+ } &
324
+ ({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
325
+ ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
326
+
327
+ /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
328
+ type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
329
+
330
+ /**
331
+ * Typed constructors for your app:
332
+ *
333
+ * ```ts
334
+ * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
335
+ * ```
336
+ */
337
+ export function init<C extends Config & OnlyKnownKeys<C>>() {
338
+ return constructors<C>();
339
+ }
340
+
341
+ function constructors<C extends Config>() {
342
+ const make =
343
+ <K extends Kind>(kind: K) =>
344
+ (def: any): any => {
345
+ const where = def?.description ? `"${def.description}"` : `a ${kind}`;
346
+ if (def.authorize !== undefined && typeof def.authorize !== "function")
347
+ throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
348
+ if (def.expose !== undefined && def.expose !== true)
349
+ throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
350
+ if (def.expose && !def.authorize)
351
+ throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
352
+ if (def.expose && !def.outputSchema)
353
+ throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
354
+ return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
355
+ };
356
+
357
+ return {
358
+ /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
359
+ createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
360
+ build<ScopeOf<C>, Mods>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
361
+ /** Reads data. Can run other queries. No writes, no events, no services. */
362
+ query: make("query") as Constructor<C, "query">,
363
+ /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
364
+ mutation: make("mutation") as Constructor<C, "mutation">,
365
+ /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
366
+ action: make("action") as Constructor<C, "action">,
367
+ /** Something that happened. Emitted by mutations, delivered after commit. */
368
+ event: <S extends Schema>(def: { schema: S; description?: string }): EventDef<In<S>, Out<S>> =>
369
+ Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
370
+ /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
371
+ on: <O>(
372
+ event: () => EventDef<any, O>,
373
+ execute: (payload: O, ctx: ListenerCtx<C, O>) => Promise<unknown>,
374
+ opts: { description?: string } = {},
375
+ ): Listener<O> =>
376
+ Object.freeze({
377
+ [BRAND]: "listener" as const,
378
+ kind: "listener" as const,
379
+ event,
380
+ description: opts.description,
381
+ execute: execute as Listener<O>["execute"],
382
+ }),
383
+ };
384
+ }
385
+
386
+ /* ────────────────────────────────────────────────────────────────────────────
387
+ * createRegistry
388
+ * ──────────────────────────────────────────────────────────────────────────── */
389
+
390
+ const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal") as any;
391
+
392
+ interface TxState {
393
+ db: unknown;
394
+ doomed: boolean;
395
+ reason: unknown;
396
+ outbox: Envelope[];
397
+ pending: Promise<void>[];
398
+ }
399
+ interface Frame {
400
+ scope: object;
401
+ depth: number;
402
+ opts: CallerOptions & { eventDepth?: number };
403
+ tx?: TxState;
404
+ }
405
+
406
+ export interface Overrides {
407
+ database?: DatabaseAdapter<any, any>;
408
+ services?: object;
409
+ events?: Dispatcher;
410
+ now?: () => Date;
411
+ stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
412
+ record?: (envelope: Envelope) => void;
413
+ }
414
+
415
+ export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>> = ReturnType<
416
+ typeof build<S, Mods>
417
+ >;
418
+
419
+ /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
420
+ export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
421
+ options: RegistryOptions<Mods>,
422
+ ) {
423
+ return build<S, Mods>(options, {});
424
+ }
425
+
426
+ const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
427
+ issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
428
+
429
+ /**
430
+ * What `createRegistry` finds in your modules, without a database or services: every function, event and
431
+ * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
432
+ */
433
+ export function describeModules(modules: Record<string, object>) {
434
+ const ids = new Map<object, string>();
435
+ const functions: RegisteredFn[] = [];
436
+ const events: (Registered & { event: EventDef })[] = [];
437
+ const listeners: (Registered & { listener: Listener; event: EventDef })[] = [];
438
+
439
+ for (const [module, ns] of Object.entries(modules)) {
440
+ for (const [name, value] of Object.entries(ns)) {
441
+ if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value)) continue;
442
+ const id = `${module}.${name}`;
443
+ ids.set(value, id);
444
+ const kind = (value as any)[BRAND];
445
+ if (kind === "event") events.push({ id, module, name, event: value as EventDef });
446
+ else if (kind === "listener") {
447
+ const listener = value as Listener;
448
+ listeners.push({ id, module, name, listener, event: listener.event() });
449
+ } else functions.push({ id, module, name, kind, fn: value as Fn, exposed: (value as Fn).expose === true });
450
+ }
451
+ }
452
+ return { ids, functions, events, listeners };
453
+ }
454
+
455
+ function build<S extends object, Mods extends Record<string, object>>(options: RegistryOptions<Mods>, o: Overrides) {
456
+ const { ids, functions, events, listeners } = describeModules(options.modules);
457
+
458
+ const database = o.database ?? options.database;
459
+ const services = o.services ?? options.services ?? {};
460
+ const dispatcher = o.events ?? options.events ?? inProcess();
461
+ const now = o.now ?? options.now ?? (() => new Date());
462
+ const wrap = options.wrap ?? ((_c, next) => next());
463
+ const maxEventDepth = options.maxEventDepth ?? 8;
464
+ const attempts = Math.max(1, options.retry?.attempts ?? 3);
465
+ const reportRaw =
466
+ options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.listener} failed`, e));
467
+ const report = (e: unknown, info: { listener: string; envelope: Envelope | undefined }) => {
468
+ try {
469
+ reportRaw(e, info);
470
+ } catch (inner) {
471
+ console.error("[logic-sdk] onError threw", inner, "while reporting", e);
472
+ }
473
+ };
474
+
475
+ if (functions.some((f) => f.kind === "mutation") && database?.transactions !== "interactive")
476
+ throw new Error(
477
+ "[logic-sdk] Mutations need a database adapter with interactive transactions (e.g. drizzleAdapter(db)). " +
478
+ "Drivers without them (Cloudflare D1, HTTP drivers) are not supported for mutations.",
479
+ );
480
+ for (const l of listeners)
481
+ if (!l.event || !ids.has(l.event))
482
+ throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
483
+
484
+ const idOf = (x: object) => {
485
+ const id = ids.get(x);
486
+ if (!id)
487
+ throw new Error(
488
+ "[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }).",
489
+ );
490
+ return id;
491
+ };
492
+
493
+ /** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
494
+ async function parseInput(schema: Schema, value: unknown, id: string, nested: boolean) {
495
+ const r = await schema["~standard"].validate(value);
496
+ if (!r.issues) return r.value;
497
+ const issues = describeIssues(r.issues);
498
+ if (nested) throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
499
+ throw new DomainError("invalid", `${id}.invalid_input`, { issues });
500
+ }
501
+ /** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
502
+ async function parseOwn(schema: Schema, value: unknown, what: string) {
503
+ const r = await schema["~standard"].validate(value);
504
+ if (r.issues) throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
505
+ return r.value;
506
+ }
507
+
508
+ // ── listeners ────────────────────────────────────────────────────────────
509
+ const byEvent = new Map<string, (Registered & { listener: Listener })[]>();
510
+ for (const l of listeners) {
511
+ const name = idOf(l.event);
512
+ byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
513
+ }
514
+ const eventByName = new Map(events.map((e) => [e.id, e.event]));
515
+
516
+ /** Run every listener for one envelope. Returns the failures instead of throwing. */
517
+ async function runListeners(envelope: Envelope, eventDepth: number) {
518
+ const failures: { listener: string; error: unknown }[] = [];
519
+ const event = eventByName.get(envelope.name);
520
+ for (const l of byEvent.get(envelope.name) ?? []) {
521
+ const frame: Frame = { scope: envelope.scope, depth: 0, opts: { eventDepth } };
522
+ try {
523
+ await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
524
+ const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
525
+ return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
526
+ });
527
+ } catch (error) {
528
+ failures.push({ listener: l.id, error });
529
+ }
530
+ }
531
+ return failures;
532
+ }
533
+
534
+ /** In-process delivery: failures go to onError. */
535
+ const deliverOne = (eventDepth: number) => async (envelope: Envelope) => {
536
+ for (const f of await runListeners(envelope, eventDepth)) report(f.error, { listener: f.listener, envelope });
537
+ };
538
+
539
+ /** Public: for durable dispatchers. Throws an AggregateError if any listener failed, so the consumer can retry. */
540
+ async function dispatch(envelope: Envelope) {
541
+ const failures = await runListeners(envelope, 1);
542
+ if (failures.length)
543
+ throw new AggregateError(
544
+ failures.map((f) => f.error),
545
+ `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`,
546
+ );
547
+ }
548
+
549
+ // ── ctx ──────────────────────────────────────────────────────────────────
550
+ const child = (frame: Frame): Frame => ({ ...frame, depth: frame.depth + 1 });
551
+ const rescope = (frame: Frame, patch: object): Frame => ({ ...frame, scope: { ...frame.scope, ...patch } });
552
+
553
+ function queryCtx(frame: Frame, id: string): QueryCtx<any> {
554
+ return {
555
+ errors: errorsFor(id),
556
+ scope: frame.scope,
557
+ now,
558
+ signal: frame.opts.signal,
559
+ db: frame.tx ? frame.tx.db : database?.db,
560
+ run: (fn, input) => invoke(fn, input, child(frame), ["query"]),
561
+ with: (patch) => queryCtx(rescope(frame, patch), id),
562
+ };
563
+ }
564
+ function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
565
+ const tx = frame.tx!;
566
+ return {
567
+ errors: errorsFor(id),
568
+ scope: frame.scope,
569
+ now,
570
+ signal: frame.opts.signal,
571
+ db: tx.db,
572
+ run: (fn, input) => invoke(fn, input, child(frame), ["query", "mutation"]),
573
+ emit: (event, payload) => {
574
+ const name = idOf(event);
575
+ payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
576
+ // reserve the slot now so events keep emit order, even with async schemas
577
+ const envelope: Envelope = {
578
+ id: crypto.randomUUID(),
579
+ name,
580
+ payload,
581
+ scope: structuredClone(frame.scope),
582
+ occurredAt: now().toISOString(),
583
+ };
584
+ tx.outbox.push(envelope);
585
+ const check = parseOwn(event.schema, payload, `${name} payload`).then(() => {});
586
+ check.catch(() => {}); // surfaced at commit; never an unhandled rejection
587
+ tx.pending.push(check);
588
+ },
589
+ with: (patch) => mutationCtx(rescope(frame, patch), id),
590
+ };
591
+ }
592
+ function actionCtx(frame: Frame, id: string): ActionCtx<any> {
593
+ return {
594
+ errors: errorsFor(id),
595
+ scope: frame.scope,
596
+ now,
597
+ signal: frame.opts.signal,
598
+ services,
599
+ run: (fn, input) => invoke(fn, input, child({ ...frame, tx: undefined }), ["query", "mutation", "action"]),
600
+ with: (patch) => actionCtx(rescope(frame, patch), id),
601
+ };
602
+ }
603
+
604
+ // ── invoke ───────────────────────────────────────────────────────────────
605
+ async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
606
+ const id = idOf(fn);
607
+ if (!allowed.includes(fn.kind))
608
+ throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
609
+
610
+ const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
611
+
612
+ /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
613
+ const prepare = async () => {
614
+ frame.opts.signal?.throwIfAborted();
615
+ if (fn.authorize) {
616
+ const allowed: unknown = fn.authorize(frame.scope);
617
+ if (allowed instanceof Promise || typeof (allowed as any)?.then === "function")
618
+ throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
619
+ if (allowed !== true) throw new DomainError("forbidden", `${id}.forbidden`);
620
+ }
621
+ return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
622
+ };
623
+ const execute = async (input: unknown, ctx: unknown) => {
624
+ const stub = o.stubs?.get(fn);
625
+ const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
626
+ return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
627
+ };
628
+
629
+ return wrap(call, async () => {
630
+ if (fn.kind === "query") return execute(await prepare(), queryCtx(frame, id));
631
+ if (fn.kind === "action") return execute(await prepare(), actionCtx(frame, id));
632
+
633
+ // mutation joining an open transaction: any failure dooms it, even if the caller catches
634
+ if (frame.tx) {
635
+ const tx = frame.tx;
636
+ try {
637
+ return await execute(await prepare(), mutationCtx(frame, id));
638
+ } catch (e) {
639
+ if (!tx.doomed) {
640
+ tx.doomed = true;
641
+ tx.reason = e;
642
+ }
643
+ throw e;
644
+ }
645
+ }
646
+
647
+ // top-level mutation: open the transaction, commit, then deliver events.
648
+ // A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
649
+ const input = await prepare();
650
+ let committed: { out: unknown; outbox: Envelope[] };
651
+ for (let attempt = 1; ; attempt++) {
652
+ let state: TxState | undefined;
653
+ try {
654
+ committed = await database!.transaction(async (txDb) => {
655
+ // fresh per attempt, so a retry never reuses events from a failed attempt
656
+ const tx: TxState = (state = { db: txDb, doomed: false, reason: undefined, outbox: [], pending: [] });
657
+ const out = await execute(input, mutationCtx({ ...frame, tx }, id));
658
+ await Promise.all(tx.pending);
659
+ if (tx.doomed) throw tx.reason;
660
+ await dispatcher.enqueue?.(txDb, tx.outbox);
661
+ return { out, outbox: tx.outbox };
662
+ });
663
+ break;
664
+ } catch (e) {
665
+ if (attempt < attempts && database!.retryable?.(e)) {
666
+ // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
667
+ await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
668
+ continue;
669
+ }
670
+ throw e;
671
+ } finally {
672
+ if (state) await Promise.allSettled(state.pending);
673
+ }
674
+ }
675
+
676
+ // committed. Nothing below may fail the caller.
677
+ if (committed.outbox.length) await afterCommit(committed.outbox, frame);
678
+ return committed.out;
679
+ });
680
+ }
681
+
682
+ async function afterCommit(outbox: Envelope[], frame: Frame) {
683
+ try {
684
+ for (const e of outbox) o.record?.(e);
685
+ const eventDepth = (frame.opts.eventDepth ?? 0) + 1;
686
+ if (eventDepth > maxEventDepth) {
687
+ report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
688
+ listener: "(dispatcher)",
689
+ envelope: outbox[0],
690
+ });
691
+ return;
692
+ }
693
+ const delivery = (async () => dispatcher.deliver(outbox, deliverOne(eventDepth)))().catch((e) =>
694
+ report(e, { listener: "(dispatcher)", envelope: outbox[0] }),
695
+ );
696
+ if (options.waitUntil) {
697
+ try {
698
+ options.waitUntil(delivery);
699
+ return;
700
+ } catch (e) {
701
+ report(e, { listener: "(waitUntil)", envelope: outbox[0] });
702
+ }
703
+ }
704
+ await delivery;
705
+ } catch (e) {
706
+ report(e, { listener: "(after commit)", envelope: outbox[0] });
707
+ }
708
+ }
709
+
710
+ function makeCaller(scope: S, opts: CallerOptions): Caller<S> {
711
+ return {
712
+ scope,
713
+ run: (fn, input) => invoke(fn, input, { scope, depth: 0, opts }, ["query", "mutation", "action"]),
714
+ with: (patch) => makeCaller({ ...scope, ...patch }, opts),
715
+ };
716
+ }
717
+
718
+ return {
719
+ /** The modules you registered (typed), for adapters that build typed routers. */
720
+ modules: options.modules,
721
+ /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
722
+ as: (scope: S, opts: CallerOptions = {}): Caller<S> => makeCaller(scope, opts),
723
+ /** Everything the registry can do. Adapters read this. */
724
+ functions: functions as readonly RegisteredFn[],
725
+ events: events as readonly (Registered & { event: EventDef })[],
726
+ listeners: listeners as readonly (Registered & { listener: Listener; event: EventDef })[],
727
+ idOf,
728
+ /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
729
+ dispatch,
730
+ /** @internal used by `logic-sdk/testing` */
731
+ [INTERNAL]: { options, overrides: o, derive: (more: Overrides) => build<S, Mods>(options, { ...o, ...more }) },
732
+ };
733
+ }
734
+
735
+ /** @internal */
736
+ export const internal = (registry: Registry<any, any>) => registry[INTERNAL];