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