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/dist/index.js CHANGED
@@ -1,67 +1,22 @@
1
- const BRAND = Symbol.for("logic-sdk.brand");
2
- /**
3
- * An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
4
- * adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
5
- * bugs) is unexpected: adapters answer 500 and report it.
6
- */
7
- export class DomainError extends Error {
8
- kind;
9
- code;
10
- details;
11
- constructor(kind, code, details) {
12
- // the details are in the message too: logs and AI tool errors (which show only the message) stay useful
13
- super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
14
- this.name = "DomainError";
15
- this.kind = kind;
16
- this.code = code;
17
- this.details = details;
18
- }
19
- }
20
- /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
21
- export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
22
- /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
23
- const errorsFor = (id) => {
24
- const module = id.slice(0, id.indexOf("."));
25
- return {
26
- reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
27
- conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
28
- notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
29
- deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
30
- };
31
- };
32
- /** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
33
- export const inProcess = () => ({
34
- async deliver(envelopes, dispatch) {
35
- for (const e of envelopes)
36
- await dispatch(e);
37
- },
38
- });
1
+ import { describeIssues, DomainError, errorsFor } from "./errors.js";
2
+ import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.js";
3
+ import { assertTimeZone, parseSchedule } from "./schedule.js";
4
+ import { BRAND, INTERNAL } from "./types.js";
5
+ export { DomainError, isDomainError, unauthenticated } from "./errors.js";
6
+ export { inProcess, replaceKeyOf } from "./jobs.js";
39
7
  /**
40
8
  * Typed constructors for your app:
41
9
  *
42
10
  * ```ts
43
- * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
11
+ * export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
44
12
  * ```
45
13
  */
46
14
  export function init() {
47
- return constructors();
48
- }
49
- function constructors() {
50
- const make = (kind) => (def) => {
51
- const where = def?.description ? `"${def.description}"` : `a ${kind}`;
52
- if (def.authorize !== undefined && typeof def.authorize !== "function")
53
- throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
54
- if (def.expose !== undefined && def.expose !== true)
55
- throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
56
- if (def.expose && !def.authorize)
57
- throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
58
- if (def.expose && !def.outputSchema)
59
- throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
60
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
61
- };
15
+ // One implementation behind the typed signature of `Constructor`: the types are the contract, the adapters check `authorize`.
16
+ const make = (kind) => (def) => Object.freeze({ [BRAND]: kind, kind, ...def });
62
17
  return {
63
18
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
64
- createRegistry: (options) => build(options, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
19
+ createRegistry: (options) => build(options, {}), // meta in wrap is typed by CallMetaOf<C>; the values come from typed defs
65
20
  /** Reads data. Can run other queries. No writes, no events, no services. */
66
21
  query: make("query"),
67
22
  /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
@@ -70,20 +25,37 @@ function constructors() {
70
25
  action: make("action"),
71
26
  /** Something that happened. Emitted by mutations, delivered after commit. */
72
27
  event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
73
- /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
74
- on: (event, execute, opts = {}) => Object.freeze({
75
- [BRAND]: "listener",
76
- kind: "listener",
77
- event,
78
- description: opts.description,
79
- execute: execute,
80
- }),
28
+ /**
29
+ * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
30
+ * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
31
+ * `cron({ schedule: "0 9 * * 1", run: reports.sendWeekly, scope: system })`.
32
+ */
33
+ cron: (def) => {
34
+ const { id, schedule, timezone, run, input, scope, attempts } = def;
35
+ parseSchedule(schedule);
36
+ if (timezone !== undefined)
37
+ assertTimeZone(timezone);
38
+ checkAttempts("cron", attempts);
39
+ return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, run, input, scope, attempts });
40
+ },
41
+ /**
42
+ * React to an event after commit, like an action. Must be idempotent.
43
+ * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
44
+ */
45
+ listener: (def) => {
46
+ const { id, event, attempts, delay, when, meta, handler } = def;
47
+ checkAttempts("listener", attempts);
48
+ if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
49
+ throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
50
+ // meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
51
+ return Object.freeze({ [BRAND]: "listener", kind: "listener", id, event, attempts, delay, when, meta: meta, handler });
52
+ },
81
53
  };
82
54
  }
83
- /* ────────────────────────────────────────────────────────────────────────────
84
- * createRegistry
85
- * ──────────────────────────────────────────────────────────────────────────── */
86
- const INTERNAL = Symbol.for("logic-sdk.internal");
55
+ function checkAttempts(what, attempts) {
56
+ if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
57
+ throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
58
+ }
87
59
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
88
60
  export function createRegistry(options) {
89
61
  return build(options, {});
@@ -98,61 +70,112 @@ function mergeConfig(base, patch) {
98
70
  const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
99
71
  return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
100
72
  }
73
+ /** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
74
+ function freezeConfig(value) {
75
+ assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
76
+ const freeze = (v) => {
77
+ if (v && typeof v === "object") {
78
+ for (const item of Object.values(v))
79
+ freeze(item);
80
+ Object.freeze(v);
81
+ }
82
+ return v;
83
+ };
84
+ return freeze(structuredClone(value));
85
+ }
101
86
  /**
102
- * A frozen copy of plain data: strings, numbers, booleans, null, plain objects and arrays. Anything else (a Date, a Map,
103
- * a client, a class) is rejected with its path, so settings can't change under everyone else or hide behavior.
87
+ * Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
88
+ * Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
104
89
  */
105
- function freezeConfig(value, path = "config") {
106
- if (value === null || ["string", "number", "boolean", "undefined"].includes(typeof value))
107
- return value;
108
- if (Array.isArray(value))
109
- return Object.freeze(value.map((v, i) => freezeConfig(v, `${path}[${i}]`)));
110
- if (isPlain(value))
111
- return Object.freeze(Object.fromEntries(Object.entries(value).map(([k, v]) => [k, freezeConfig(v, `${path}.${k}`)])));
112
- const what = typeof value === "function" ? "a function" : value.constructor?.name ?? typeof value;
113
- throw new Error(`[logic-sdk] ${path} is ${what}. config holds plain data (strings, numbers, booleans, null, objects, arrays): ` +
114
- "pass a Date as an ISO string, and put clients in services.");
90
+ function assertPlain(value, what, hint) {
91
+ const seen = new Set();
92
+ const check = (v, path) => {
93
+ const fail = (found) => {
94
+ throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
95
+ };
96
+ if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean")
97
+ return;
98
+ if (typeof v === "number") {
99
+ if (!Number.isFinite(v))
100
+ fail(String(v));
101
+ return;
102
+ }
103
+ if (typeof v !== "object")
104
+ return fail(`a ${typeof v}`);
105
+ if (seen.has(v))
106
+ fail("a circular reference");
107
+ seen.add(v);
108
+ if (Array.isArray(v))
109
+ v.forEach((item, i) => check(item, `${path}[${i}]`));
110
+ else {
111
+ if (!isPlain(v))
112
+ fail(`a ${v.constructor?.name ?? "class instance"}`);
113
+ for (const [k, item] of Object.entries(v))
114
+ check(item, path ? `${path}.${k}` : k);
115
+ }
116
+ seen.delete(v);
117
+ };
118
+ check(value, "");
115
119
  }
116
- const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
120
+ const isBranded = (v) => !!v && typeof v === "object" && BRAND in v;
117
121
  /**
118
- * What `createRegistry` finds in your modules, without a database or services: every function, event and
119
- * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
122
+ * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
123
+ * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
120
124
  */
121
125
  export function describeModules(modules) {
122
126
  const ids = new Map();
123
127
  const functions = [];
124
128
  const events = [];
125
129
  const listeners = [];
130
+ const crons = [];
131
+ const taken = new Map();
126
132
  for (const [module, ns] of Object.entries(modules)) {
127
133
  for (const [name, value] of Object.entries(ns)) {
128
- if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value))
134
+ if (!isBranded(value) || ids.has(value))
129
135
  continue;
130
- const id = `${module}.${name}`;
136
+ const local = value.id ?? name;
137
+ if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
138
+ 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>.`);
139
+ const id = `${module}.${local}`;
140
+ const other = taken.get(id);
141
+ if (other)
142
+ 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.`);
143
+ taken.set(id, name);
131
144
  ids.set(value, id);
132
- const kind = value[BRAND];
133
- if (kind === "event")
145
+ if (value.kind === "event")
134
146
  events.push({ id, module, name, event: value });
135
- else if (kind === "listener") {
136
- const listener = value;
137
- listeners.push({ id, module, name, listener, event: listener.event() });
138
- }
147
+ else if (value.kind === "listener")
148
+ listeners.push({ id, module, name, listener: value, event: value.event() });
149
+ else if (value.kind === "cron")
150
+ crons.push({ id, module, name, cron: value });
139
151
  else
140
- functions.push({ id, module, name, kind, fn: value, exposed: value.expose === true });
152
+ functions.push({ id, module, name, kind: value.kind, fn: value });
141
153
  }
142
154
  }
143
- return { ids, functions, events, listeners };
155
+ return { ids, functions, events, listeners, crons };
144
156
  }
145
157
  function build(options, o) {
146
- const { ids, functions, events, listeners } = describeModules(options.modules);
158
+ const { ids, functions, events, listeners, crons } = describeModules(options.modules);
147
159
  const database = o.database ?? options.database;
148
160
  const services = o.services ?? options.services ?? {};
149
161
  const config = freezeConfig(mergeConfig(options.config ?? {}, o.config));
150
- const dispatcher = o.events ?? options.events ?? inProcess();
162
+ const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
163
+ const jobScope = options.jobs?.scope;
164
+ if (jobScope?.store && !jobScope.load)
165
+ throw new Error("[logic-sdk] jobs.scope has store but no load. Jobs run as a scope, so rebuild it from what store saved.");
166
+ // a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
167
+ // back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
168
+ const appAdapter = options.jobs?.adapter;
169
+ if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
170
+ throw new Error("[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 " +
171
+ "roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.");
151
172
  const now = o.now ?? options.now ?? (() => new Date());
152
173
  const wrap = options.wrap ?? ((_c, next) => next());
153
- const maxEventDepth = options.maxEventDepth ?? 8;
154
- const attempts = Math.max(1, options.retry?.attempts ?? 3);
155
- const reportRaw = options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.listener} failed`, e));
174
+ const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
175
+ checkAttempts("database transaction", options.database?.transactionAttempts);
176
+ const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
177
+ const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
178
+ const reportRaw = o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
156
179
  const report = (e, info) => {
157
180
  try {
158
181
  reportRaw(e, info);
@@ -161,12 +184,13 @@ function build(options, o) {
161
184
  console.error("[logic-sdk] onError threw", inner, "while reporting", e);
162
185
  }
163
186
  };
164
- if (functions.some((f) => f.kind === "mutation") && database?.transactions !== "interactive")
165
- throw new Error("[logic-sdk] Mutations need a database adapter with interactive transactions (e.g. drizzleAdapter(db)). " +
166
- "Drivers without them (Cloudflare D1, HTTP drivers) are not supported for mutations.");
187
+ if (!database && functions.some((f) => f.kind === "mutation"))
188
+ throw new Error("[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
189
+ "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.");
167
190
  for (const l of listeners)
168
- if (!l.event || !ids.has(l.event))
191
+ if (!ids.has(l.event))
169
192
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
193
+ jobsAdapter.check?.({ listeners, database });
170
194
  const idOf = (x) => {
171
195
  const id = ids.get(x);
172
196
  if (!id)
@@ -190,41 +214,16 @@ function build(options, o) {
190
214
  throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
191
215
  return r.value;
192
216
  }
193
- // ── listeners ────────────────────────────────────────────────────────────
194
- const byEvent = new Map();
195
- for (const l of listeners) {
196
- const name = idOf(l.event);
197
- byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
217
+ /** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
218
+ function checkAtCommit(tx, schema, value, what, keep) {
219
+ const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
220
+ check.catch(() => { }); // surfaced at commit; never an unhandled rejection
221
+ tx.pending.push(check);
198
222
  }
199
- const eventByName = new Map(events.map((e) => [e.id, e.event]));
200
- /** Run every listener for one envelope. Returns the failures instead of throwing. */
201
- async function runListeners(envelope, eventDepth) {
202
- const failures = [];
203
- const event = eventByName.get(envelope.name);
204
- for (const l of byEvent.get(envelope.name) ?? []) {
205
- const frame = { scope: envelope.scope, depth: 0, eventDepth };
206
- try {
207
- await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
208
- const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
209
- return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
210
- });
211
- }
212
- catch (error) {
213
- failures.push({ listener: l.id, error });
214
- }
215
- }
216
- return failures;
217
- }
218
- /** In-process delivery: failures go to onError. */
219
- const deliverOne = (eventDepth) => async (envelope) => {
220
- for (const f of await runListeners(envelope, eventDepth))
221
- report(f.error, { listener: f.listener, envelope });
222
- };
223
- /** Public: for durable dispatchers. Throws an AggregateError if any listener failed, so the consumer can retry. */
224
- async function dispatch(envelope) {
225
- const failures = await runListeners(envelope, 1);
226
- if (failures.length)
227
- throw new AggregateError(failures.map((f) => f.error), `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`);
223
+ for (const c of crons) {
224
+ if (!ids.has(c.cron.run))
225
+ throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
226
+ 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");
228
227
  }
229
228
  // ── ctx ──────────────────────────────────────────────────────────────────
230
229
  /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
@@ -235,54 +234,105 @@ function build(options, o) {
235
234
  signal: options?.signal ?? frame.signal,
236
235
  abortOn: options?.signal,
237
236
  });
238
- function queryCtx(frame, id) {
239
- return {
240
- errors: errorsFor(id),
241
- scope: frame.scope,
242
- config: config,
243
- now,
244
- db: frame.tx ? frame.tx.db : database?.db,
245
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
246
- };
247
- }
248
- function mutationCtx(frame, id) {
249
- const tx = frame.tx;
237
+ /** What every ctx has. `allowed`: the kinds its `run` may call. */
238
+ const baseCtx = (frame, id, allowed) => ({
239
+ errors: errorsFor(id),
240
+ scope: frame.scope,
241
+ config: config, // Frozen<Cf> here; each app's ctx types it from its own Config
242
+ now,
243
+ run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed),
244
+ });
245
+ const queryCtx = (frame, id) => ({
246
+ ...baseCtx(frame, id, ["query"]),
247
+ db: frame.tx ? frame.tx.db : database?.db,
248
+ });
249
+ function mutationCtx(frame, tx, id) {
250
250
  return {
251
- errors: errorsFor(id),
252
- scope: frame.scope,
253
- config: config,
254
- now,
251
+ ...baseCtx(frame, id, ["query", "mutation"]),
255
252
  db: tx.db,
256
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
257
253
  emit: (event, payload) => {
258
- const name = idOf(event);
259
- payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
260
254
  // reserve the slot now so events keep emit order, even with async schemas
261
- const envelope = {
262
- id: crypto.randomUUID(),
263
- name,
264
- payload,
265
- scope: structuredClone(frame.scope),
266
- occurredAt: now().toISOString(),
255
+ const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
256
+ tx.events.push(envelope);
257
+ checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
258
+ },
259
+ schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
260
+ const fnId = idOf(fn);
261
+ const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
262
+ if (!Number.isFinite(seconds) || (!at && seconds < 0))
263
+ throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
264
+ checkAttempts(`ctx.schedule(${fnId})`, attempts);
265
+ if (replace !== undefined) {
266
+ if (!replace)
267
+ throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replace must be a non-empty key.`);
268
+ if (!jobsAdapter.replaces)
269
+ 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.`);
270
+ }
271
+ // due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
272
+ const waits = seconds > 0;
273
+ if (waits)
274
+ checkHold(`ctx.schedule(${fnId})`, seconds);
275
+ assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
276
+ const job = {
277
+ kind: "call",
278
+ id: `${fnId}@${crypto.randomUUID()}`,
279
+ fn: fnId,
280
+ input: structuredClone(input),
281
+ scope: storedScope(frame.scope, `the scope scheduling ${fnId}`),
282
+ attempts,
283
+ depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
267
284
  };
268
- tx.outbox.push(envelope);
269
- const check = parseOwn(event.schema, payload, `${name} payload`).then(() => { });
270
- check.catch(() => { }); // surfaced at commit; never an unhandled rejection
271
- tx.pending.push(check);
285
+ if (waits)
286
+ job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
287
+ if (replace !== undefined) {
288
+ job.replace = replace;
289
+ // scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
290
+ // a bad input is a bug wherever it is)
291
+ const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
292
+ if (earlier >= 0)
293
+ tx.calls.splice(earlier, 1);
294
+ }
295
+ tx.calls.push(job);
296
+ // our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
297
+ if (fn.input)
298
+ checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
299
+ return job.id;
272
300
  },
273
301
  };
274
302
  }
275
- function actionCtx(frame, id) {
276
- return {
277
- errors: errorsFor(id),
278
- scope: frame.scope,
279
- config: config,
280
- now,
281
- signal: frame.signal,
282
- services,
283
- run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
284
- };
303
+ /** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
304
+ function envelopeOf(event, payload, scope, depth) {
305
+ const name = idOf(event);
306
+ // a queue carries JSON: a Date or a class instance would work in-process and break only in production
307
+ assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
308
+ return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
309
+ }
310
+ /** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
311
+ function storedScope(scope, what) {
312
+ const stored = jobScope?.store ? jobScope.store(scope) : scope;
313
+ assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
314
+ return structuredClone(stored);
285
315
  }
316
+ const actionCtx = (frame, id) => ({
317
+ ...baseCtx(frame, id, ["query", "mutation", "action"]),
318
+ signal: frame.signal,
319
+ services,
320
+ });
321
+ const { toJobs, deliver, jobs, due, checkHold } = makeJobs({
322
+ listeners,
323
+ crons,
324
+ functions,
325
+ idOf,
326
+ jobsAdapter,
327
+ database,
328
+ jobScope,
329
+ maxEventDepth,
330
+ now,
331
+ wrap,
332
+ report,
333
+ runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, depth: -1, eventDepth, queued }, undefined), ["query", "mutation", "action"]),
334
+ listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, depth: 0, eventDepth, queued }, id),
335
+ });
286
336
  // ── invoke ───────────────────────────────────────────────────────────────
287
337
  async function invoke(fn, rawInput, frame, allowed) {
288
338
  const id = idOf(fn);
@@ -293,18 +343,19 @@ function build(options, o) {
293
343
  const prepare = async () => {
294
344
  frame.abortOn?.throwIfAborted();
295
345
  if (fn.authorize) {
296
- const allowed = fn.authorize(frame.scope);
297
- if (allowed instanceof Promise || typeof allowed?.then === "function")
298
- throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
299
- if (allowed !== true)
346
+ // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
347
+ if (fn.authorize(frame.scope) !== true)
300
348
  throw new DomainError("forbidden", `${id}.forbidden`);
301
349
  }
302
- return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
350
+ // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
351
+ return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
303
352
  };
304
353
  const execute = async (input, ctx) => {
305
- const stub = o.stubs?.get(fn);
306
- const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
307
- return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
354
+ // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
355
+ // and `input` just passed its own schema (or it takes none).
356
+ const handler = o.stubs?.get(fn) ?? fn.handler;
357
+ const out = await handler(ctx, input);
358
+ return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
308
359
  };
309
360
  return wrap(call, async () => {
310
361
  if (fn.kind === "query")
@@ -315,7 +366,7 @@ function build(options, o) {
315
366
  if (frame.tx) {
316
367
  const tx = frame.tx;
317
368
  try {
318
- return await execute(await prepare(), mutationCtx(frame, id));
369
+ return await execute(await prepare(), mutationCtx(frame, tx, id));
319
370
  }
320
371
  catch (e) {
321
372
  if (!tx.doomed) {
@@ -330,93 +381,74 @@ function build(options, o) {
330
381
  const input = await prepare();
331
382
  let committed;
332
383
  for (let attempt = 1;; attempt++) {
333
- let state;
334
384
  try {
385
+ // SAFETY: createRegistry refuses mutations without a database that has interactive transactions
335
386
  committed = await database.transaction(async (txDb) => {
336
387
  // fresh per attempt, so a retry never reuses events from a failed attempt
337
- const tx = (state = { db: txDb, doomed: false, reason: undefined, outbox: [], pending: [] });
338
- const out = await execute(input, mutationCtx({ ...frame, tx }, id));
388
+ const tx = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
389
+ const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
339
390
  await Promise.all(tx.pending);
340
391
  if (tx.doomed)
341
392
  throw tx.reason;
342
- await dispatcher.enqueue?.(txDb, tx.outbox);
343
- return { out, outbox: tx.outbox };
393
+ const jobs = toJobs(tx.events, tx.calls, tx.parsed);
394
+ if (jobs.length)
395
+ await jobsAdapter.enqueue?.(txDb, jobs);
396
+ return { out, events: tx.events, jobs };
344
397
  });
345
398
  break;
346
399
  }
347
400
  catch (e) {
348
- if (attempt < attempts && database.retryable?.(e)) {
401
+ if (attempt < transactionAttempts && database.retryable?.(e)) { // SAFETY: as above
349
402
  // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
350
403
  await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
351
404
  continue;
352
405
  }
353
406
  throw e;
354
407
  }
355
- finally {
356
- if (state)
357
- await Promise.allSettled(state.pending);
358
- }
359
408
  }
360
409
  // committed. Nothing below may fail the caller.
361
- if (committed.outbox.length)
362
- await afterCommit(committed.outbox, frame);
410
+ await afterCommit(committed.events, committed.jobs, frame.queued);
363
411
  return committed.out;
364
412
  });
365
413
  }
366
- async function afterCommit(outbox, frame) {
414
+ async function afterCommit(emitted, jobs, queued) {
367
415
  try {
368
- for (const e of outbox)
416
+ for (const e of emitted)
369
417
  o.record?.(e);
370
- const eventDepth = (frame.eventDepth ?? 0) + 1;
371
- if (eventDepth > maxEventDepth) {
372
- report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
373
- listener: "(dispatcher)",
374
- envelope: outbox[0],
375
- });
418
+ if (!jobs.length)
376
419
  return;
377
- }
378
- const delivery = (async () => dispatcher.deliver(outbox, deliverOne(eventDepth)))().catch((e) => report(e, { listener: "(dispatcher)", envelope: outbox[0] }));
379
- if (options.waitUntil) {
420
+ if (queued)
421
+ return void queued.push(...jobs); // queued by a job: delivered once that job is settled
422
+ const delivery = deliver(jobs);
423
+ if (waitUntil) {
380
424
  try {
381
- options.waitUntil(delivery);
425
+ waitUntil(delivery);
382
426
  return;
383
427
  }
384
428
  catch (e) {
385
- report(e, { listener: "(waitUntil)", envelope: outbox[0] });
429
+ report(e, { source: "(waitUntil)" });
386
430
  }
387
431
  }
388
432
  await delivery;
389
433
  }
390
434
  catch (e) {
391
- report(e, { listener: "(after commit)", envelope: outbox[0] });
435
+ report(e, { source: "(after commit)" });
392
436
  }
393
437
  }
394
- function makeCaller(scope) {
395
- return {
396
- scope,
397
- run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
398
- };
399
- }
400
438
  return {
401
- /** The modules you registered (typed), for adapters that build typed routers. */
402
- modules: options.modules,
403
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
404
- as: (scope) => makeCaller(scope),
405
- /** Everything the registry can do. Adapters read this. */
406
- functions: functions,
407
- events: events,
408
- listeners: listeners,
439
+ as: (scope) => ({
440
+ scope,
441
+ run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1, eventDepth: 0 }, options), ["query", "mutation", "action"]), // depth 0
442
+ }),
443
+ definitions: { functions, events, listeners, crons },
409
444
  idOf,
410
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
411
- dispatch,
412
- /** @internal used by `logic-sdk/testing` */
445
+ jobs,
413
446
  [INTERNAL]: {
414
447
  options,
415
- overrides: o,
416
448
  config,
417
449
  derive: (more) => build(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
450
+ envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
451
+ due,
418
452
  },
419
453
  };
420
454
  }
421
- /** @internal */
422
- export const internal = (registry) => registry[INTERNAL];