logic-sdk 0.3.0 → 0.5.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.
Files changed (57) hide show
  1. package/README.md +47 -22
  2. package/dist/ai.d.ts +16 -29
  3. package/dist/ai.js +13 -24
  4. package/dist/cloudflare.d.ts +55 -0
  5. package/dist/cloudflare.js +85 -0
  6. package/dist/drizzle/pg.d.ts +237 -0
  7. package/dist/drizzle/pg.js +67 -0
  8. package/dist/drizzle/sqlite.d.ts +242 -0
  9. package/dist/drizzle/sqlite.js +194 -0
  10. package/dist/errors.d.ts +33 -0
  11. package/dist/errors.js +45 -0
  12. package/dist/fetch.d.ts +15 -18
  13. package/dist/fetch.js +18 -55
  14. package/dist/index.d.ts +80 -443
  15. package/dist/index.js +261 -229
  16. package/dist/jobs.d.ts +44 -0
  17. package/dist/jobs.js +252 -0
  18. package/dist/node.d.ts +26 -0
  19. package/dist/node.js +76 -0
  20. package/dist/orpc.d.ts +10 -20
  21. package/dist/orpc.js +19 -28
  22. package/dist/pg-boss.d.ts +55 -0
  23. package/dist/pg-boss.js +211 -0
  24. package/dist/postgres.d.ts +28 -0
  25. package/dist/postgres.js +82 -0
  26. package/dist/schedule.d.ts +23 -0
  27. package/dist/schedule.js +109 -0
  28. package/dist/sqlite.d.ts +9 -0
  29. package/dist/sqlite.js +65 -0
  30. package/dist/stored-jobs.d.ts +64 -0
  31. package/dist/stored-jobs.js +188 -0
  32. package/dist/testing.d.ts +51 -15
  33. package/dist/testing.js +198 -46
  34. package/dist/types.d.ts +653 -0
  35. package/dist/types.js +6 -0
  36. package/package.json +45 -7
  37. package/skills/logic-sdk/SKILL.md +114 -0
  38. package/src/ai.ts +29 -51
  39. package/src/cloudflare.ts +107 -0
  40. package/src/drizzle/pg.ts +111 -0
  41. package/src/drizzle/sqlite.ts +236 -0
  42. package/src/errors.ts +59 -0
  43. package/src/fetch.ts +17 -65
  44. package/src/index.ts +422 -572
  45. package/src/jobs.ts +296 -0
  46. package/src/node.ts +99 -0
  47. package/src/orpc.ts +24 -43
  48. package/src/pg-boss.ts +242 -0
  49. package/src/postgres.ts +90 -0
  50. package/src/schedule.ts +129 -0
  51. package/src/sqlite.ts +74 -0
  52. package/src/stored-jobs.ts +260 -0
  53. package/src/testing.ts +253 -56
  54. package/src/types.ts +683 -0
  55. package/dist/drizzle.d.ts +0 -18
  56. package/dist/drizzle.js +0 -23
  57. package/src/drizzle.ts +0 -39
package/src/index.ts CHANGED
@@ -1,357 +1,123 @@
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
- /**
22
- * Your app's settings, read as `ctx.config` in every function: base URL, limits, switches. Plain data, read-only.
23
- * Build it once from your env at the entry; clients built from secrets go in `services` instead.
24
- */
25
- config?: object;
26
- /** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
27
- meta?: object;
28
- }
29
- type ScopeOf<C extends Config> = C["scope"];
30
- type DbOf<C extends Config> = C extends { db: infer D } ? D : never;
31
- type ReaderOf<C extends Config> = C extends { reader: infer R } ? R : DbOf<C>;
32
- type ServicesOf<C extends Config> = C extends { services: infer S } ? S : {};
33
- type MetaOf<C extends Config> = C extends { meta: infer M } ? M : never;
34
- /** Without a declared `config`, nothing may be passed or read: no silently ignored settings. */
35
- type ConfigOf<C extends Config> = C extends { config: infer F } ? F : Record<string, never>;
36
-
37
- type Primitive = string | number | boolean | bigint | symbol | null | undefined;
38
- /** Read-only all the way down: what `ctx.config` gives you. Primitives (branded ones too) stay as they are. */
39
- export type Frozen<T> = T extends Primitive
40
- ? T
41
- : T extends readonly (infer U)[]
42
- ? readonly Frozen<U>[]
43
- : { readonly [K in keyof T]: Frozen<T[K]> };
44
- /** Any part of `T`, at any depth: what a test may override in `config`. Arrays are replaced whole, like at runtime. */
45
- export type DeepPartial<T> = T extends Primitive | readonly unknown[] ? T : { [K in keyof T]?: DeepPartial<T[K]> };
46
-
47
- export type Kind = "query" | "mutation" | "action";
48
-
49
- declare const types: unique symbol;
50
- const BRAND: unique symbol = Symbol.for("logic-sdk.brand") as any;
51
-
52
- /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
53
- export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean = boolean> {
54
- readonly [BRAND]: K;
55
- readonly kind: K;
56
- readonly description: string;
57
- readonly inputSchema: Schema;
58
- readonly outputSchema?: Schema;
59
- /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
60
- readonly meta?: any;
61
- /** Who may call it (from `authorize`). Runs on every call, before validation. */
62
- readonly authorize?: Policy<any>;
63
- /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
64
- readonly expose?: true;
65
- readonly execute: (input: any, ctx: any) => Promise<any>;
66
- /** Phantom types, never set at runtime. */
67
- readonly [types]?: { input: I; output: O; exposed: E };
68
- }
69
- /** A function with `expose: true`: adapters may publish it. */
70
- export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
71
- /** What callers pass to a function. */
72
- export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
73
- /** What a function returns. */
74
- export type FnOut<F> = F extends Fn<any, any, infer O> ? O : never;
75
-
76
- /** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
77
- export interface EventDef<I = any, O = I> {
78
- readonly [BRAND]: "event";
79
- readonly kind: "event";
80
- readonly schema: Schema;
81
- readonly description?: string;
82
- readonly [types]?: { input: I; payload: O };
83
- }
84
-
85
- /**
86
- * What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
87
- * and listeners get it parsed again by the event's schema at delivery.
88
- */
89
- export interface Envelope<P = unknown, S = object> {
90
- id: string;
91
- name: string;
92
- payload: P;
93
- scope: S;
94
- occurredAt: string;
95
- }
96
-
97
- export interface Listener<O = any> {
98
- readonly [BRAND]: "listener";
99
- readonly kind: "listener";
100
- /** Lazy, so listeners can import other modules' barrels without import cycles. */
101
- readonly event: () => EventDef<any, O>;
102
- readonly description?: string;
103
- readonly execute: (payload: O, ctx: any) => Promise<unknown>;
104
- }
105
-
106
- /** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
107
- export interface RunOptions<S = object> {
108
- /**
109
- * Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
110
- * someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
111
- */
112
- scope?: Partial<S>;
113
- /**
114
- * Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
115
- * Never checked between your steps, so a caller who gives up can't leave a workflow half done.
116
- */
117
- signal?: AbortSignal;
118
- }
119
- type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>, options?: RunOptions<S>) => Promise<FnOut<F>>;
120
-
121
- /**
122
- * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
123
- * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
124
- */
125
- export interface Errors {
126
- /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
127
- reject(code: string, details?: unknown): DomainError;
128
- /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
129
- conflict(code: string, details?: unknown): DomainError;
130
- /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
131
- notFound(code?: string, details?: unknown): DomainError;
132
- /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
133
- deny(code?: string, details?: unknown): DomainError;
134
- }
135
- interface BaseCtx<C extends Config, S> {
136
- scope: S;
137
- /** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
138
- config: Frozen<ConfigOf<C>>;
139
- /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
140
- errors: Errors;
141
- /** Current time. Fixed in tests. */
142
- now: () => Date;
143
- }
144
- /** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
145
- export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
146
- db: ReaderOf<C>;
147
- /** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
148
- run: Run<"query", ScopeOf<C>>;
149
- }
150
- export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
151
- db: DbOf<C>;
152
- /**
153
- * Call a query or mutation inside this same transaction, with its policy and validation:
154
- * `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
155
- */
156
- run: Run<"query" | "mutation", ScopeOf<C>>;
157
- /** Queue an event. Delivered to listeners only after the transaction commits. */
158
- emit<I>(event: EventDef<I, any>, payload: I): void;
159
- }
160
- export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
161
- services: ServicesOf<C>;
162
- /** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
163
- run: Run<Kind, ScopeOf<C>>;
164
- /** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
165
- signal: AbortSignal | undefined;
166
- }
167
- export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
168
- event: Envelope<unknown, ScopeOf<C>> & { payload: O };
169
- }
170
-
171
- /**
172
- * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
173
- * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
174
- * Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
175
- */
176
- export type Policy<S> = (scope: S) => boolean;
177
- type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
178
- type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
179
- ? QueryCtx<C, S>
180
- : K extends "mutation"
181
- ? MutationCtx<C, S>
182
- : ActionCtx<C, S>;
183
-
184
- type Def<IS extends Schema, Ctx, R> = {
185
- /** One sentence, shown to humans, adapters and AI tools. */
186
- description: string;
187
- inputSchema: IS;
188
- execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
189
- };
190
- type NotExposed = { expose?: undefined };
191
- type NoPolicy = { authorize?: undefined };
192
- type WithMeta<C extends Config> = { meta?: MetaOf<C> };
193
- type WithOutput<OS extends Schema> = { outputSchema: OS };
194
-
195
- /**
196
- * `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
197
- * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
198
- */
199
- interface Constructor<C extends Config, K extends Kind> {
200
- <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
201
- def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> &
202
- WithOutput<OS> &
203
- WithMeta<C> & { authorize: P; expose: true },
204
- ): Fn<K, In<IS>, Out<OS>, true>;
205
- <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
206
- def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { authorize: P } & NotExposed,
207
- ): Fn<K, In<IS>, Out<OS>, false>;
208
- <IS extends Schema, R, P extends Policy<ScopeOf<C>>>(
209
- def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & { authorize: P } & NotExposed,
210
- ): Fn<K, In<IS>, R, false>;
211
- <IS extends Schema, OS extends Schema>(
212
- def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed,
213
- ): Fn<K, In<IS>, Out<OS>, false>;
214
- <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
215
- }
216
-
217
- /* ────────────────────────────────────────────────────────────────────────────
218
- * Errors
219
- * ──────────────────────────────────────────────────────────────────────────── */
220
-
221
- export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
222
-
223
- /**
224
- * An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
225
- * adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
226
- * bugs) is unexpected: adapters answer 500 and report it.
227
- */
228
- export class DomainError extends Error {
229
- readonly kind: ErrorKind;
230
- readonly code: string;
231
- readonly details: unknown;
232
- constructor(kind: ErrorKind, code: string, details?: unknown) {
233
- // the details are in the message too: logs and AI tool errors (which show only the message) stay useful
234
- super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
235
- this.name = "DomainError";
236
- this.kind = kind;
237
- this.code = code;
238
- this.details = details;
239
- }
240
- }
241
- /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
242
- export const isDomainError = (e: unknown, code?: string): e is DomainError =>
243
- e instanceof DomainError && (code === undefined || e.code === code);
244
-
245
- /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
246
- const errorsFor = (id: string): Errors => {
247
- const module = id.slice(0, id.indexOf("."));
248
- return {
249
- reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
250
- conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
251
- notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
252
- deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
253
- };
254
- };
255
-
256
- /* ────────────────────────────────────────────────────────────────────────────
257
- * Adapters and dispatcher seams
258
- * ──────────────────────────────────────────────────────────────────────────── */
259
-
260
- export interface DatabaseAdapter<Db = unknown, Tx = Db> {
261
- /** Root handle, used by top-level queries. */
262
- readonly db: Db;
263
- readonly transactions: "interactive";
264
- transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
265
- /** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
266
- nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
267
- /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
268
- retryable?(error: unknown): boolean;
269
- }
270
-
271
- export interface Dispatcher {
272
- /** Inside the transaction, before commit. In-process: nothing. Outbox: insert rows with `tx`. */
273
- enqueue?(tx: unknown, envelopes: Envelope[]): Promise<void>;
274
- /** After commit. `dispatch` runs the listeners for one envelope and never throws (failures go to `onError`). */
275
- deliver(envelopes: Envelope[], dispatch: (envelope: Envelope) => Promise<void>): Promise<void>;
276
- }
277
-
278
- /** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
279
- export const inProcess = (): Dispatcher => ({
280
- async deliver(envelopes, dispatch) {
281
- for (const e of envelopes) await dispatch(e);
282
- },
283
- });
284
-
285
- export interface Call<M = unknown> {
286
- id: string;
287
- kind: Kind | "listener";
288
- /** The function's `meta` (undefined for listeners and functions without it). */
289
- meta: M | undefined;
290
- /** Raw input as received (before validation). */
291
- input: unknown;
292
- scope: object;
293
- depth: number;
294
- }
295
-
296
- export interface RegistryOptions<Mods extends Record<string, object>> {
297
- /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
298
- modules: Mods;
299
- database?: DatabaseAdapter<any, any>;
300
- services?: object;
301
- /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
302
- config?: object;
303
- events?: Dispatcher;
304
- /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
305
- wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
306
- /**
307
- * Serverless: let listeners finish after the response. Pass the platform's global:
308
- * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
309
- * Without it, `run` waits for listeners, which is what tests and long-lived servers want.
310
- */
311
- waitUntil?: (promise: Promise<unknown>) => void;
312
- /** Failures after commit land here (listeners, dispatcher). They never fail the caller. */
313
- onError?: (error: unknown, info: { listener: string; envelope: Envelope | undefined }) => void;
314
- now?: () => Date;
315
- /** Max chain of listener → mutation → event → listener… before delivery stops. Default 8 (real chains are 2 or 3). */
316
- maxEventDepth?: number;
317
- /**
318
- * Re-run a top-level mutation in a fresh transaction when the database says it lost a race (deadlock,
319
- * serialization failure). Safe because mutations have no side effects and events are rebuilt per attempt.
320
- * Default 3 attempts in total; `{ attempts: 1 }` turns it off.
321
- */
322
- retry?: { attempts?: number };
323
- }
324
-
325
- /** A registry bound to who is calling: `const caller = registry.as(scope)`. */
326
- export interface Caller<S extends object = object> {
327
- readonly scope: S;
328
- /** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
329
- run<F extends Fn>(fn: F, input: FnIn<F>, options?: RunOptions<S>): Promise<FnOut<F>>;
330
- }
331
-
332
- export interface Registered {
333
- id: string;
334
- module: string;
335
- name: string;
336
- }
337
- export interface RegisteredFn extends Registered {
338
- fn: Fn;
339
- kind: Kind;
340
- /** Has `expose: true`: adapters may publish it. */
341
- exposed: boolean;
342
- }
1
+ import { describeIssues, DomainError, errorsFor } from "./errors.ts";
2
+ import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.ts";
3
+ import { assertTimeZone, parseSchedule } from "./schedule.ts";
4
+ import { BRAND, INTERNAL } from "./types.ts";
5
+ import type {
6
+ ActionCtx,
7
+ Call,
8
+ CallJob,
9
+ CallMetaOf,
10
+ Config,
11
+ ConfigOf,
12
+ Constructor,
13
+ Cron,
14
+ DatabaseAdapter,
15
+ DbOf,
16
+ Envelope,
17
+ EventDef,
18
+ FailureInfo,
19
+ Fn,
20
+ FnIn,
21
+ Frozen,
22
+ In,
23
+ Job,
24
+ JobsOptions,
25
+ Kind,
26
+ Listener,
27
+ ListenerCtx,
28
+ ListenerMetaOf,
29
+ MutationCtx,
30
+ Out,
31
+ Overrides,
32
+ OwnModules,
33
+ QueryCtx,
34
+ RegisteredCron,
35
+ RegisteredEvent,
36
+ RegisteredFn,
37
+ RegisteredListener,
38
+ Registry,
39
+ RegistryOptions,
40
+ RunOptions,
41
+ Schema,
42
+ ScopeOf,
43
+ ServicesOf,
44
+ } from "./types.ts";
45
+
46
+ export type {
47
+ ActionCtx,
48
+ Call,
49
+ CallJob,
50
+ Caller,
51
+ Config,
52
+ Constructor,
53
+ Cron,
54
+ CronJob,
55
+ DatabaseAdapter,
56
+ DeepPartial,
57
+ Delivery,
58
+ Envelope,
59
+ Errors,
60
+ EventDef,
61
+ FailureInfo,
62
+ Fn,
63
+ FnIn,
64
+ FnOut,
65
+ ForFunctions,
66
+ ForListeners,
67
+ Frozen,
68
+ In,
69
+ InProcess,
70
+ Job,
71
+ JobOutcome,
72
+ JobsAdapter,
73
+ JobScope,
74
+ Jobs,
75
+ JobsOptions,
76
+ Kind,
77
+ Listener,
78
+ ListenerCtx,
79
+ ListenerEvent,
80
+ MutationCtx,
81
+ Out,
82
+ Policy,
83
+ PublishableFn,
84
+ ScopeOfFn,
85
+ QueryCtx,
86
+ ReadWrite,
87
+ Registered,
88
+ RegisteredCron,
89
+ RegisteredEvent,
90
+ RegisteredFn,
91
+ RegisteredListener,
92
+ Registry,
93
+ RegistryOptions,
94
+ RunArgs,
95
+ RunJob,
96
+ RunJobOptions,
97
+ RunOptions,
98
+ Runner,
99
+ ScheduleOptions,
100
+ Schema,
101
+ SqlDatabase,
102
+ SweepResult,
103
+ } from "./types.ts";
104
+ export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./errors.ts";
105
+ export { inProcess, replaceKeyOf } from "./jobs.ts";
343
106
 
344
107
  /* ────────────────────────────────────────────────────────────────────────────
345
108
  * init: typed constructors
346
109
  * ──────────────────────────────────────────────────────────────────────────── */
347
110
 
348
- type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<RegistryOptions<Mods>, "wrap"> & {
111
+ type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
112
+ /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
113
+ jobs?: JobsOptions<ScopeOf<C>, T>;
349
114
  /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
350
- wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
115
+ wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
351
116
  } &
352
117
  ({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
353
118
  ({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
354
- ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
119
+ ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<unknown, DbOf<C>> }) &
120
+ { modules: OwnModules<C, Mods> };
355
121
 
356
122
  /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
357
123
  type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
@@ -360,33 +126,20 @@ type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
360
126
  * Typed constructors for your app:
361
127
  *
362
128
  * ```ts
363
- * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
129
+ * export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
364
130
  * ```
365
131
  */
366
132
  export function init<C extends Config & OnlyKnownKeys<C>>() {
367
- return constructors<C>();
368
- }
369
-
370
- function constructors<C extends Config>() {
133
+ // One implementation behind the typed signature of `Constructor`: the types are the contract, the adapters check `authorize`.
371
134
  const make =
372
135
  <K extends Kind>(kind: K) =>
373
- (def: any): any => {
374
- const where = def?.description ? `"${def.description}"` : `a ${kind}`;
375
- if (def.authorize !== undefined && typeof def.authorize !== "function")
376
- throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
377
- if (def.expose !== undefined && def.expose !== true)
378
- throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
379
- if (def.expose && !def.authorize)
380
- throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
381
- if (def.expose && !def.outputSchema)
382
- throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
383
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
384
- };
136
+ (def: object) =>
137
+ Object.freeze({ [BRAND]: kind, kind, ...def });
385
138
 
386
139
  return {
387
140
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
388
- createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
389
- build<ScopeOf<C>, Mods, ConfigOf<C>>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
141
+ createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) =>
142
+ build<ScopeOf<C>, Mods, ConfigOf<C>>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by CallMetaOf<C>; the values come from typed defs
390
143
  /** Reads data. Can run other queries. No writes, no events, no services. */
391
144
  query: make("query") as Constructor<C, "query">,
392
145
  /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
@@ -394,35 +147,100 @@ function constructors<C extends Config>() {
394
147
  /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
395
148
  action: make("action") as Constructor<C, "action">,
396
149
  /** Something that happened. Emitted by mutations, delivered after commit. */
397
- event: <S extends Schema>(def: { schema: S; description?: string }): EventDef<In<S>, Out<S>> =>
150
+ event: <S extends Schema>(def: {
151
+ /**
152
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
153
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
154
+ */
155
+ id?: string;
156
+ payload: S;
157
+ }): EventDef<In<S>, Out<S>> =>
398
158
  Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
399
- /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
400
- on: <O>(
401
- event: () => EventDef<any, O>,
402
- execute: (payload: O, ctx: ListenerCtx<C, O>) => Promise<unknown>,
403
- opts: { description?: string } = {},
404
- ): Listener<O> =>
405
- Object.freeze({
406
- [BRAND]: "listener" as const,
407
- kind: "listener" as const,
408
- event,
409
- description: opts.description,
410
- execute: execute as Listener<O>["execute"],
411
- }),
159
+ /**
160
+ * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
161
+ * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
162
+ * `cron({ schedule: "0 9 * * 1", run: reports.sendWeekly, scope: system })`.
163
+ */
164
+ cron: <F extends Fn>(def: CronDef<ScopeOf<C>, F>): Cron<C> => {
165
+ const { id, schedule, timezone, run, input, scope, attempts } = def;
166
+ parseSchedule(schedule);
167
+ if (timezone !== undefined) assertTimeZone(timezone);
168
+ checkAttempts("cron", attempts);
169
+ return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, run, input, scope, attempts });
170
+ },
171
+ /**
172
+ * React to an event after commit, like an action. Must be idempotent.
173
+ * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
174
+ */
175
+ listener: <O>(def: {
176
+ /**
177
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
178
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
179
+ */
180
+ id?: string;
181
+ /** The event it reacts to, as a thunk so modules can import each other's barrels without cycles. */
182
+ event: () => EventDef<unknown, O>;
183
+ /**
184
+ * Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
185
+ * Once they're used, the job is `failed` (kept by `databaseQueue`, `outbox` and pg-boss, retried with `registry.jobs.retry(id)`).
186
+ */
187
+ attempts?: number;
188
+ /** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
189
+ delay?: number;
190
+ /**
191
+ * Whether this event gets a job for this listener, like Laravel's `shouldQueue($event)`: false, and nothing is
192
+ * stored, run or counted. From the payload the handler gets (parsed), at commit, so sync and from the event only:
193
+ * a condition on the database belongs in the handler, since it can change before the job runs. A throw fails the
194
+ * mutation, as a bad payload does.
195
+ */
196
+ when?: (payload: O) => boolean;
197
+ meta?: ListenerMetaOf<C>;
198
+ handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
199
+ }): Listener<O, C> => {
200
+ const { id, event, attempts, delay, when, meta, handler } = def;
201
+ checkAttempts("listener", attempts);
202
+ if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
203
+ throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
204
+ // meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
205
+ return Object.freeze({ [BRAND]: "listener" as const, kind: "listener" as const, id, event, attempts, delay, when, meta: meta as Listener["meta"], handler });
206
+ },
412
207
  };
413
208
  }
414
209
 
210
+ /** `cron({...})`: `input` is required exactly when the function needs one. */
211
+ type CronDef<S, F extends Fn> = {
212
+ /** Stable id, local to its module, like every definer's. Defaults to the export name. */
213
+ id?: string;
214
+ /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * 1"`. */
215
+ schedule: string;
216
+ /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
217
+ timezone?: string;
218
+ /** Any query, mutation or action: it runs with its policy, validation and tracing. */
219
+ run: F;
220
+ /** Who it runs as: a cron has no caller. */
221
+ scope: S;
222
+ /** Tries in total, like a listener's. Default 1. */
223
+ attempts?: number;
224
+ } & (undefined extends FnIn<F> ? { input?: FnIn<F> } : { input: FnIn<F> });
225
+
226
+ function checkAttempts(what: string, attempts: number | undefined) {
227
+ if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
228
+ throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
229
+ }
230
+
415
231
  /* ────────────────────────────────────────────────────────────────────────────
416
232
  * createRegistry
417
233
  * ──────────────────────────────────────────────────────────────────────────── */
418
234
 
419
- const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal") as any;
420
-
421
235
  interface TxState {
422
236
  db: unknown;
423
237
  doomed: boolean;
424
238
  reason: unknown;
425
- outbox: Envelope[];
239
+ events: Envelope[];
240
+ /** Each event's payload as its schema parsed it, for listeners' `when`: the value their handler gets. */
241
+ parsed: Map<Envelope, unknown>;
242
+ /** What `ctx.schedule` asked for, enqueued with the events at commit. */
243
+ calls: CallJob[];
426
244
  pending: Promise<void>[];
427
245
  }
428
246
  interface Frame {
@@ -432,25 +250,13 @@ interface Frame {
432
250
  signal?: AbortSignal;
433
251
  /** Passed to this very call: checked before it starts. */
434
252
  abortOn?: AbortSignal;
435
- eventDepth?: number;
253
+ /** Hops in the chain of events and calls due now that led here: 0 for a call from outside. */
254
+ eventDepth: number;
255
+ /** Inside a job: where the jobs it queues wait until it's settled. */
256
+ queued?: Job[];
436
257
  tx?: TxState;
437
258
  }
438
259
 
439
- export interface Overrides {
440
- database?: DatabaseAdapter<any, any>;
441
- services?: object;
442
- /** Merged over the registry's config, section by section. */
443
- config?: object;
444
- events?: Dispatcher;
445
- now?: () => Date;
446
- stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
447
- record?: (envelope: Envelope) => void;
448
- }
449
-
450
- export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> = ReturnType<
451
- typeof build<S, Mods, Cf>
452
- >;
453
-
454
260
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
455
261
  export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
456
262
  options: RegistryOptions<Mods>,
@@ -469,65 +275,111 @@ function mergeConfig(base: unknown, patch: unknown): unknown {
469
275
  return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
470
276
  }
471
277
 
278
+ /** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
279
+ function freezeConfig(value: unknown): unknown {
280
+ assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
281
+ const freeze = (v: unknown): unknown => {
282
+ if (v && typeof v === "object") {
283
+ for (const item of Object.values(v)) freeze(item);
284
+ Object.freeze(v);
285
+ }
286
+ return v;
287
+ };
288
+ return freeze(structuredClone(value));
289
+ }
290
+
472
291
  /**
473
- * A frozen copy of plain data: strings, numbers, booleans, null, plain objects and arrays. Anything else (a Date, a Map,
474
- * a client, a class) is rejected with its path, so settings can't change under everyone else or hide behavior.
292
+ * Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
293
+ * Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
475
294
  */
476
- function freezeConfig(value: unknown, path = "config"): unknown {
477
- if (value === null || ["string", "number", "boolean", "undefined"].includes(typeof value)) return value;
478
- if (Array.isArray(value)) return Object.freeze(value.map((v, i) => freezeConfig(v, `${path}[${i}]`)));
479
- if (isPlain(value))
480
- return Object.freeze(Object.fromEntries(Object.entries(value).map(([k, v]) => [k, freezeConfig(v, `${path}.${k}`)])));
481
- const what = typeof value === "function" ? "a function" : (value as object).constructor?.name ?? typeof value;
482
- throw new Error(
483
- `[logic-sdk] ${path} is ${what}. config holds plain data (strings, numbers, booleans, null, objects, arrays): ` +
484
- "pass a Date as an ISO string, and put clients in services.",
485
- );
295
+ function assertPlain(value: unknown, what: string, hint: string): void {
296
+ const seen = new Set<object>();
297
+ const check = (v: unknown, path: string): void => {
298
+ const fail = (found: string): never => {
299
+ throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
300
+ };
301
+ if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean") return;
302
+ if (typeof v === "number") {
303
+ if (!Number.isFinite(v)) fail(String(v));
304
+ return;
305
+ }
306
+ if (typeof v !== "object") return fail(`a ${typeof v}`);
307
+ if (seen.has(v)) fail("a circular reference");
308
+ seen.add(v);
309
+ if (Array.isArray(v)) v.forEach((item, i) => check(item, `${path}[${i}]`));
310
+ else {
311
+ if (!isPlain(v)) fail(`a ${v.constructor?.name ?? "class instance"}`);
312
+ for (const [k, item] of Object.entries(v)) check(item, path ? `${path}.${k}` : k);
313
+ }
314
+ seen.delete(v);
315
+ };
316
+ check(value, "");
486
317
  }
487
318
 
488
- const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
489
- issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
319
+ const isBranded = (v: unknown): v is Fn | EventDef | Listener | Cron => !!v && typeof v === "object" && BRAND in v;
490
320
 
491
321
  /**
492
- * What `createRegistry` finds in your modules, without a database or services: every function, event and
493
- * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
322
+ * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
323
+ * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
494
324
  */
495
325
  export function describeModules(modules: Record<string, object>) {
496
326
  const ids = new Map<object, string>();
497
327
  const functions: RegisteredFn[] = [];
498
- const events: (Registered & { event: EventDef })[] = [];
499
- const listeners: (Registered & { listener: Listener; event: EventDef })[] = [];
328
+ const events: RegisteredEvent[] = [];
329
+ const listeners: RegisteredListener[] = [];
330
+ const crons: RegisteredCron[] = [];
331
+
332
+ const taken = new Map<string, string>();
500
333
 
501
334
  for (const [module, ns] of Object.entries(modules)) {
502
335
  for (const [name, value] of Object.entries(ns)) {
503
- if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value)) continue;
504
- const id = `${module}.${name}`;
336
+ if (!isBranded(value) || ids.has(value)) continue;
337
+ const local = value.id ?? name;
338
+ if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
339
+ throw new Error(`[logic-sdk] ${module}.${name} has id ${JSON.stringify(value.id)}. Give the local name ("send"): the module key is added, so it's ${module}.<id>.`);
340
+ const id = `${module}.${local}`;
341
+ const other = taken.get(id);
342
+ if (other) throw new Error(`[logic-sdk] ${module}.${other} and ${module}.${name} both have the id ${id}. Ids must be unique: jobs find their code by it.`);
343
+ taken.set(id, name);
505
344
  ids.set(value, id);
506
- const kind = (value as any)[BRAND];
507
- if (kind === "event") events.push({ id, module, name, event: value as EventDef });
508
- else if (kind === "listener") {
509
- const listener = value as Listener;
510
- listeners.push({ id, module, name, listener, event: listener.event() });
511
- } else functions.push({ id, module, name, kind, fn: value as Fn, exposed: (value as Fn).expose === true });
345
+ if (value.kind === "event") events.push({ id, module, name, event: value });
346
+ else if (value.kind === "listener") listeners.push({ id, module, name, listener: value, event: value.event() });
347
+ else if (value.kind === "cron") crons.push({ id, module, name, cron: value });
348
+ else functions.push({ id, module, name, kind: value.kind, fn: value });
512
349
  }
513
350
  }
514
- return { ids, functions, events, listeners };
351
+ return { ids, functions, events, listeners, crons };
515
352
  }
516
353
 
517
- function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(options: RegistryOptions<Mods>, o: Overrides) {
518
- const { ids, functions, events, listeners } = describeModules(options.modules);
354
+ function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(
355
+ options: RegistryOptions<Mods>,
356
+ o: Overrides,
357
+ ): Registry<S, Mods, Cf> {
358
+ const { ids, functions, events, listeners, crons } = describeModules(options.modules);
519
359
 
520
360
  const database = o.database ?? options.database;
521
361
  const services = o.services ?? options.services ?? {};
522
362
  const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
523
- const dispatcher = o.events ?? options.events ?? inProcess();
363
+ const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
364
+ const jobScope = options.jobs?.scope;
365
+ if (jobScope?.store && !jobScope.load) throw new Error("[logic-sdk] jobs.scope has store but no load. Jobs run as a scope, so rebuild it from what store saved.");
366
+ // a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
367
+ // back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
368
+ const appAdapter = options.jobs?.adapter;
369
+ if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
370
+ throw new Error(
371
+ "[logic-sdk] Your jobs adapter keeps jobs to run later, so set jobs.scope.load: it rebuilds the scope when a job runs, with today's " +
372
+ "roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.",
373
+ );
524
374
  const now = o.now ?? options.now ?? (() => new Date());
525
375
  const wrap = options.wrap ?? ((_c, next) => next());
526
- const maxEventDepth = options.maxEventDepth ?? 8;
527
- const attempts = Math.max(1, options.retry?.attempts ?? 3);
376
+ const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
377
+ checkAttempts("database transaction", options.database?.transactionAttempts);
378
+ const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
379
+ const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
528
380
  const reportRaw =
529
- options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.listener} failed`, e));
530
- const report = (e: unknown, info: { listener: string; envelope: Envelope | undefined }) => {
381
+ o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
382
+ const report = (e: unknown, info: FailureInfo) => {
531
383
  try {
532
384
  reportRaw(e, info);
533
385
  } catch (inner) {
@@ -535,14 +387,15 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
535
387
  }
536
388
  };
537
389
 
538
- if (functions.some((f) => f.kind === "mutation") && database?.transactions !== "interactive")
390
+ if (!database && functions.some((f) => f.kind === "mutation"))
539
391
  throw new Error(
540
- "[logic-sdk] Mutations need a database adapter with interactive transactions (e.g. drizzleAdapter(db)). " +
541
- "Drivers without them (Cloudflare D1, HTTP drivers) are not supported for mutations.",
392
+ "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
393
+ "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.",
542
394
  );
543
395
  for (const l of listeners)
544
- if (!l.event || !ids.has(l.event))
396
+ if (!ids.has(l.event))
545
397
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
398
+ jobsAdapter.check?.({ listeners, database });
546
399
 
547
400
  const idOf = (x: object) => {
548
401
  const id = ids.get(x);
@@ -567,46 +420,17 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
567
420
  if (r.issues) throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
568
421
  return r.value;
569
422
  }
570
-
571
- // ── listeners ────────────────────────────────────────────────────────────
572
- const byEvent = new Map<string, (Registered & { listener: Listener })[]>();
573
- for (const l of listeners) {
574
- const name = idOf(l.event);
575
- byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
576
- }
577
- const eventByName = new Map(events.map((e) => [e.id, e.event]));
578
-
579
- /** Run every listener for one envelope. Returns the failures instead of throwing. */
580
- async function runListeners(envelope: Envelope, eventDepth: number) {
581
- const failures: { listener: string; error: unknown }[] = [];
582
- const event = eventByName.get(envelope.name);
583
- for (const l of byEvent.get(envelope.name) ?? []) {
584
- const frame: Frame = { scope: envelope.scope, depth: 0, eventDepth };
585
- try {
586
- await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
587
- const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
588
- return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
589
- });
590
- } catch (error) {
591
- failures.push({ listener: l.id, error });
592
- }
593
- }
594
- return failures;
423
+ /** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
424
+ function checkAtCommit(tx: TxState, schema: Schema, value: unknown, what: string, keep?: (parsed: unknown) => void) {
425
+ const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
426
+ check.catch(() => {}); // surfaced at commit; never an unhandled rejection
427
+ tx.pending.push(check);
595
428
  }
596
429
 
597
- /** In-process delivery: failures go to onError. */
598
- const deliverOne = (eventDepth: number) => async (envelope: Envelope) => {
599
- for (const f of await runListeners(envelope, eventDepth)) report(f.error, { listener: f.listener, envelope });
600
- };
601
-
602
- /** Public: for durable dispatchers. Throws an AggregateError if any listener failed, so the consumer can retry. */
603
- async function dispatch(envelope: Envelope) {
604
- const failures = await runListeners(envelope, 1);
605
- if (failures.length)
606
- throw new AggregateError(
607
- failures.map((f) => f.error),
608
- `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`,
609
- );
430
+ for (const c of crons) {
431
+ if (!ids.has(c.cron.run))
432
+ throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
433
+ assertPlain(c.cron.input, `${c.id} input`, "Cron runs travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
610
434
  }
611
435
 
612
436
  // ── ctx ──────────────────────────────────────────────────────────────────
@@ -619,54 +443,102 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
619
443
  abortOn: options?.signal,
620
444
  });
621
445
 
622
- function queryCtx(frame: Frame, id: string): QueryCtx<any> {
623
- return {
624
- errors: errorsFor(id),
625
- scope: frame.scope,
626
- config: config as any,
627
- now,
628
- db: frame.tx ? frame.tx.db : database?.db,
629
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
630
- };
631
- }
632
- function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
633
- const tx = frame.tx!;
446
+ /** What every ctx has. `allowed`: the kinds its `run` may call. */
447
+ const baseCtx = (frame: Frame, id: string, allowed: Kind[]) => ({
448
+ errors: errorsFor(id),
449
+ scope: frame.scope,
450
+ config: config as any, // Frozen<Cf> here; each app's ctx types it from its own Config
451
+ now,
452
+ run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed),
453
+ });
454
+ const queryCtx = (frame: Frame, id: string): QueryCtx<any> => ({
455
+ ...baseCtx(frame, id, ["query"]),
456
+ db: frame.tx ? frame.tx.db : database?.db,
457
+ });
458
+ function mutationCtx(frame: Frame, tx: TxState, id: string): MutationCtx<any> {
634
459
  return {
635
- errors: errorsFor(id),
636
- scope: frame.scope,
637
- config: config as any,
638
- now,
460
+ ...baseCtx(frame, id, ["query", "mutation"]),
639
461
  db: tx.db,
640
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
641
462
  emit: (event, payload) => {
642
- const name = idOf(event);
643
- payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
644
463
  // reserve the slot now so events keep emit order, even with async schemas
645
- const envelope: Envelope = {
646
- id: crypto.randomUUID(),
647
- name,
648
- payload,
649
- scope: structuredClone(frame.scope),
650
- occurredAt: now().toISOString(),
464
+ const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
465
+ tx.events.push(envelope);
466
+ checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
467
+ },
468
+ schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
469
+ const fnId = idOf(fn);
470
+ const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
471
+ if (!Number.isFinite(seconds) || (!at && seconds < 0))
472
+ throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
473
+ checkAttempts(`ctx.schedule(${fnId})`, attempts);
474
+ if (replace !== undefined) {
475
+ if (!replace) throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replace must be a non-empty key.`);
476
+ if (!jobsAdapter.replaces)
477
+ throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replaces a waiting call, but your jobs adapter can't replace one it already has. Use databaseQueue(database), or outbox(database, queue) in front of your queue.`);
478
+ }
479
+ // due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
480
+ const waits = seconds > 0;
481
+ if (waits) checkHold(`ctx.schedule(${fnId})`, seconds);
482
+ assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
483
+ const job: CallJob = {
484
+ kind: "call",
485
+ id: `${fnId}@${crypto.randomUUID()}`,
486
+ fn: fnId,
487
+ input: structuredClone(input),
488
+ scope: storedScope(frame.scope, `the scope scheduling ${fnId}`),
489
+ attempts,
490
+ depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
651
491
  };
652
- tx.outbox.push(envelope);
653
- const check = parseOwn(event.schema, payload, `${name} payload`).then(() => {});
654
- check.catch(() => {}); // surfaced at commit; never an unhandled rejection
655
- tx.pending.push(check);
492
+ if (waits) job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
493
+ if (replace !== undefined) {
494
+ job.replace = replace;
495
+ // scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
496
+ // a bad input is a bug wherever it is)
497
+ const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
498
+ if (earlier >= 0) tx.calls.splice(earlier, 1);
499
+ }
500
+ tx.calls.push(job);
501
+ // our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
502
+ if (fn.input) checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
503
+ return job.id;
656
504
  },
657
505
  };
658
506
  }
659
- function actionCtx(frame: Frame, id: string): ActionCtx<any> {
660
- return {
661
- errors: errorsFor(id),
662
- scope: frame.scope,
663
- config: config as any,
664
- now,
665
- signal: frame.signal,
666
- services,
667
- run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
668
- };
507
+ /** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
508
+ function envelopeOf(event: EventDef, payload: unknown, scope: object, depth: number): Envelope {
509
+ const name = idOf(event);
510
+ // a queue carries JSON: a Date or a class instance would work in-process and break only in production
511
+ assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
512
+ return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
669
513
  }
514
+ /** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
515
+ function storedScope(scope: object, what: string): object {
516
+ const stored = jobScope?.store ? jobScope.store(scope) : scope;
517
+ assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
518
+ return structuredClone(stored);
519
+ }
520
+
521
+ const actionCtx = (frame: Frame, id: string): ActionCtx<any> => ({
522
+ ...baseCtx(frame, id, ["query", "mutation", "action"]),
523
+ signal: frame.signal,
524
+ services,
525
+ });
526
+
527
+ const { toJobs, deliver, jobs, due, checkHold } = makeJobs({
528
+ listeners,
529
+ crons,
530
+ functions,
531
+ idOf,
532
+ jobsAdapter,
533
+ database,
534
+ jobScope,
535
+ maxEventDepth,
536
+ now,
537
+ wrap,
538
+ report,
539
+ runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, depth: -1, eventDepth, queued }, undefined), ["query", "mutation", "action"]),
540
+ listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, depth: 0, eventDepth, queued }, id),
541
+ });
670
542
 
671
543
  // ── invoke ───────────────────────────────────────────────────────────────
672
544
  async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
@@ -680,17 +552,18 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
680
552
  const prepare = async () => {
681
553
  frame.abortOn?.throwIfAborted();
682
554
  if (fn.authorize) {
683
- const allowed: unknown = fn.authorize(frame.scope);
684
- if (allowed instanceof Promise || typeof (allowed as any)?.then === "function")
685
- throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
686
- if (allowed !== true) throw new DomainError("forbidden", `${id}.forbidden`);
555
+ // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
556
+ if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", `${id}.forbidden`);
687
557
  }
688
- return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
558
+ // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
559
+ return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
689
560
  };
690
561
  const execute = async (input: unknown, ctx: unknown) => {
691
- const stub = o.stubs?.get(fn);
692
- const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
693
- return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
562
+ // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
563
+ // and `input` just passed its own schema (or it takes none).
564
+ const handler = o.stubs?.get(fn) ?? fn.handler;
565
+ const out = await handler(ctx as never, input as never);
566
+ return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
694
567
  };
695
568
 
696
569
  return wrap(call, async () => {
@@ -701,7 +574,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
701
574
  if (frame.tx) {
702
575
  const tx = frame.tx;
703
576
  try {
704
- return await execute(await prepare(), mutationCtx(frame, id));
577
+ return await execute(await prepare(), mutationCtx(frame, tx, id));
705
578
  } catch (e) {
706
579
  if (!tx.doomed) {
707
580
  tx.doomed = true;
@@ -714,95 +587,72 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
714
587
  // top-level mutation: open the transaction, commit, then deliver events.
715
588
  // A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
716
589
  const input = await prepare();
717
- let committed: { out: unknown; outbox: Envelope[] };
590
+ let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
718
591
  for (let attempt = 1; ; attempt++) {
719
- let state: TxState | undefined;
720
592
  try {
593
+ // SAFETY: createRegistry refuses mutations without a database that has interactive transactions
721
594
  committed = await database!.transaction(async (txDb) => {
722
595
  // fresh per attempt, so a retry never reuses events from a failed attempt
723
- const tx: TxState = (state = { db: txDb, doomed: false, reason: undefined, outbox: [], pending: [] });
724
- const out = await execute(input, mutationCtx({ ...frame, tx }, id));
596
+ const tx: TxState = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
597
+ const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
725
598
  await Promise.all(tx.pending);
726
599
  if (tx.doomed) throw tx.reason;
727
- await dispatcher.enqueue?.(txDb, tx.outbox);
728
- return { out, outbox: tx.outbox };
600
+ const jobs = toJobs(tx.events, tx.calls, tx.parsed);
601
+ if (jobs.length) await jobsAdapter.enqueue?.(txDb, jobs);
602
+ return { out, events: tx.events, jobs };
729
603
  });
730
604
  break;
731
605
  } catch (e) {
732
- if (attempt < attempts && database!.retryable?.(e)) {
606
+ if (attempt < transactionAttempts && database!.retryable?.(e)) { // SAFETY: as above
733
607
  // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
734
608
  await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
735
609
  continue;
736
610
  }
737
611
  throw e;
738
- } finally {
739
- if (state) await Promise.allSettled(state.pending);
740
612
  }
741
613
  }
742
614
 
743
615
  // committed. Nothing below may fail the caller.
744
- if (committed.outbox.length) await afterCommit(committed.outbox, frame);
616
+ await afterCommit(committed.events, committed.jobs, frame.queued);
745
617
  return committed.out;
746
618
  });
747
619
  }
748
620
 
749
- async function afterCommit(outbox: Envelope[], frame: Frame) {
621
+ async function afterCommit(emitted: Envelope[], jobs: Job[], queued: Job[] | undefined) {
750
622
  try {
751
- for (const e of outbox) o.record?.(e);
752
- const eventDepth = (frame.eventDepth ?? 0) + 1;
753
- if (eventDepth > maxEventDepth) {
754
- report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
755
- listener: "(dispatcher)",
756
- envelope: outbox[0],
757
- });
758
- return;
759
- }
760
- const delivery = (async () => dispatcher.deliver(outbox, deliverOne(eventDepth)))().catch((e) =>
761
- report(e, { listener: "(dispatcher)", envelope: outbox[0] }),
762
- );
763
- if (options.waitUntil) {
623
+ for (const e of emitted) o.record?.(e);
624
+ if (!jobs.length) return;
625
+ if (queued) return void queued.push(...jobs); // queued by a job: delivered once that job is settled
626
+ const delivery = deliver(jobs);
627
+ if (waitUntil) {
764
628
  try {
765
- options.waitUntil(delivery);
629
+ waitUntil(delivery);
766
630
  return;
767
631
  } catch (e) {
768
- report(e, { listener: "(waitUntil)", envelope: outbox[0] });
632
+ report(e, { source: "(waitUntil)" });
769
633
  }
770
634
  }
771
635
  await delivery;
772
636
  } catch (e) {
773
- report(e, { listener: "(after commit)", envelope: outbox[0] });
637
+ report(e, { source: "(after commit)" });
774
638
  }
775
639
  }
776
640
 
777
- function makeCaller(scope: S): Caller<S> {
778
- return {
779
- scope,
780
- run: (fn, input, options) =>
781
- invoke(fn, input, enter({ scope, depth: -1 }, options as RunOptions | undefined), ["query", "mutation", "action"]), // depth 0
782
- };
783
- }
784
-
785
641
  return {
786
- /** The modules you registered (typed), for adapters that build typed routers. */
787
- modules: options.modules,
788
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
789
- as: (scope: S): Caller<S> => makeCaller(scope),
790
- /** Everything the registry can do. Adapters read this. */
791
- functions: functions as readonly RegisteredFn[],
792
- events: events as readonly (Registered & { event: EventDef })[],
793
- listeners: listeners as readonly (Registered & { listener: Listener; event: EventDef })[],
642
+ as: (scope) => ({
643
+ scope,
644
+ run: (fn: Fn, input?: unknown, options?: RunOptions) =>
645
+ invoke(fn, input, enter({ scope, depth: -1, eventDepth: 0 }, options), ["query", "mutation", "action"]), // depth 0
646
+ }),
647
+ definitions: { functions, events, listeners, crons },
794
648
  idOf,
795
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
796
- dispatch,
797
- /** @internal used by `logic-sdk/testing` */
649
+ jobs,
798
650
  [INTERNAL]: {
799
651
  options,
800
- overrides: o,
801
652
  config,
802
- derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) as object | undefined }),
653
+ derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
654
+ envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
655
+ due,
803
656
  },
804
657
  };
805
658
  }
806
-
807
- /** @internal */
808
- export const internal = (registry: Registry<any, any, any>) => registry[INTERNAL];