logic-sdk 0.4.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 +39 -13
  2. package/dist/ai.d.ts +16 -26
  3. package/dist/ai.js +8 -21
  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 +75 -379
  15. package/dist/index.js +228 -181
  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 -17
  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 +50 -14
  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 +23 -46
  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 +384 -558
  45. package/src/jobs.ts +296 -0
  46. package/src/node.ts +99 -0
  47. package/src/orpc.ts +24 -42
  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 +252 -55
  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
- // 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,37 @@ 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
+ 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,59 +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)) }));
117
120
  const isBranded = (v) => !!v && typeof v === "object" && BRAND in v;
118
121
  /**
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.
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.
121
124
  */
122
125
  export function describeModules(modules) {
123
126
  const ids = new Map();
124
127
  const functions = [];
125
128
  const events = [];
126
129
  const listeners = [];
130
+ const crons = [];
131
+ const taken = new Map();
127
132
  for (const [module, ns] of Object.entries(modules)) {
128
133
  for (const [name, value] of Object.entries(ns)) {
129
134
  if (!isBranded(value) || ids.has(value))
130
135
  continue;
131
- 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);
132
144
  ids.set(value, id);
133
145
  if (value.kind === "event")
134
146
  events.push({ id, module, name, event: value });
135
147
  else if (value.kind === "listener")
136
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 });
137
151
  else
138
- functions.push({ id, module, name, kind: value.kind, fn: value, exposed: value.expose === true });
152
+ functions.push({ id, module, name, kind: value.kind, fn: value });
139
153
  }
140
154
  }
141
- return { ids, functions, events, listeners };
155
+ return { ids, functions, events, listeners, crons };
142
156
  }
143
157
  function build(options, o) {
144
- const { ids, functions, events, listeners } = describeModules(options.modules);
158
+ const { ids, functions, events, listeners, crons } = describeModules(options.modules);
145
159
  const database = o.database ?? options.database;
146
160
  const services = o.services ?? options.services ?? {};
147
161
  const config = freezeConfig(mergeConfig(options.config ?? {}, o.config));
148
- 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`.");
149
172
  const now = o.now ?? options.now ?? (() => new Date());
150
173
  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));
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));
154
179
  const report = (e, info) => {
155
180
  try {
156
181
  reportRaw(e, info);
@@ -159,12 +184,13 @@ function build(options, o) {
159
184
  console.error("[logic-sdk] onError threw", inner, "while reporting", e);
160
185
  }
161
186
  };
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.");
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.");
165
190
  for (const l of listeners)
166
- if (!l.event || !ids.has(l.event))
191
+ if (!ids.has(l.event))
167
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 });
168
194
  const idOf = (x) => {
169
195
  const id = ids.get(x);
170
196
  if (!id)
@@ -188,41 +214,16 @@ function build(options, o) {
188
214
  throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
189
215
  return r.value;
190
216
  }
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]);
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);
196
222
  }
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(", ")}`);
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");
226
227
  }
227
228
  // ── ctx ──────────────────────────────────────────────────────────────────
228
229
  /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
@@ -245,34 +246,93 @@ function build(options, o) {
245
246
  ...baseCtx(frame, id, ["query"]),
246
247
  db: frame.tx ? frame.tx.db : database?.db,
247
248
  });
248
- function mutationCtx(frame, id) {
249
- const tx = frame.tx;
249
+ function mutationCtx(frame, tx, id) {
250
250
  return {
251
251
  ...baseCtx(frame, id, ["query", "mutation"]),
252
252
  db: tx.db,
253
253
  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
254
  // 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(),
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
263
284
  };
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);
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;
268
300
  },
269
301
  };
270
302
  }
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);
315
+ }
271
316
  const actionCtx = (frame, id) => ({
272
317
  ...baseCtx(frame, id, ["query", "mutation", "action"]),
273
318
  signal: frame.signal,
274
319
  services,
275
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
+ });
276
336
  // ── invoke ───────────────────────────────────────────────────────────────
277
337
  async function invoke(fn, rawInput, frame, allowed) {
278
338
  const id = idOf(fn);
@@ -284,10 +344,7 @@ function build(options, o) {
284
344
  frame.abortOn?.throwIfAborted();
285
345
  if (fn.authorize) {
286
346
  // 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)
347
+ if (fn.authorize(frame.scope) !== true)
291
348
  throw new DomainError("forbidden", `${id}.forbidden`);
292
349
  }
293
350
  // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
@@ -309,7 +366,7 @@ function build(options, o) {
309
366
  if (frame.tx) {
310
367
  const tx = frame.tx;
311
368
  try {
312
- return await execute(await prepare(), mutationCtx(frame, id));
369
+ return await execute(await prepare(), mutationCtx(frame, tx, id));
313
370
  }
314
371
  catch (e) {
315
372
  if (!tx.doomed) {
@@ -324,84 +381,74 @@ function build(options, o) {
324
381
  const input = await prepare();
325
382
  let committed;
326
383
  for (let attempt = 1;; attempt++) {
327
- let state;
328
384
  try {
385
+ // SAFETY: createRegistry refuses mutations without a database that has interactive transactions
329
386
  committed = await database.transaction(async (txDb) => {
330
387
  // 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));
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));
333
390
  await Promise.all(tx.pending);
334
391
  if (tx.doomed)
335
392
  throw tx.reason;
336
- await dispatcher.enqueue?.(txDb, tx.outbox);
337
- 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 };
338
397
  });
339
398
  break;
340
399
  }
341
400
  catch (e) {
342
- if (attempt < attempts && database.retryable?.(e)) {
401
+ if (attempt < transactionAttempts && database.retryable?.(e)) { // SAFETY: as above
343
402
  // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
344
403
  await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
345
404
  continue;
346
405
  }
347
406
  throw e;
348
407
  }
349
- finally {
350
- if (state)
351
- await Promise.allSettled(state.pending);
352
- }
353
408
  }
354
409
  // committed. Nothing below may fail the caller.
355
- if (committed.outbox.length)
356
- await afterCommit(committed.outbox, frame);
410
+ await afterCommit(committed.events, committed.jobs, frame.queued);
357
411
  return committed.out;
358
412
  });
359
413
  }
360
- async function afterCommit(outbox, frame) {
414
+ async function afterCommit(emitted, jobs, queued) {
361
415
  try {
362
- for (const e of outbox)
416
+ for (const e of emitted)
363
417
  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
- });
418
+ if (!jobs.length)
370
419
  return;
371
- }
372
- const delivery = (async () => dispatcher.deliver(outbox, deliverOne(eventDepth)))().catch((e) => report(e, { listener: "(dispatcher)", envelope: outbox[0] }));
373
- 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) {
374
424
  try {
375
- options.waitUntil(delivery);
425
+ waitUntil(delivery);
376
426
  return;
377
427
  }
378
428
  catch (e) {
379
- report(e, { listener: "(waitUntil)", envelope: outbox[0] });
429
+ report(e, { source: "(waitUntil)" });
380
430
  }
381
431
  }
382
432
  await delivery;
383
433
  }
384
434
  catch (e) {
385
- report(e, { listener: "(after commit)", envelope: outbox[0] });
435
+ report(e, { source: "(after commit)" });
386
436
  }
387
437
  }
388
438
  return {
389
- modules: options.modules,
390
439
  as: (scope) => ({
391
440
  scope,
392
- run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
441
+ run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1, eventDepth: 0 }, options), ["query", "mutation", "action"]), // depth 0
393
442
  }),
394
- functions,
395
- events,
396
- listeners,
443
+ definitions: { functions, events, listeners, crons },
397
444
  idOf,
398
- dispatch,
445
+ jobs,
399
446
  [INTERNAL]: {
400
447
  options,
401
448
  config,
402
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,
403
452
  },
404
453
  };
405
454
  }
406
- /** @internal */
407
- export const internal = (registry) => registry[INTERNAL];
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ import type { ActionCtx, Call, CallJob, CronJob, DatabaseAdapter, Delivery, Envelope, FailureInfo, Fn, InProcess, Job, JobsAdapter, JobScope, Jobs, RegisteredCron, RegisteredFn, RegisteredListener } from "./types.ts";
2
+ /**
3
+ * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
4
+ * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
5
+ */
6
+ export declare const inProcess: () => InProcess;
7
+ /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
8
+ export declare const runsNow: (adapter: JobsAdapter) => boolean;
9
+ /**
10
+ * What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
11
+ * waits. Undefined for every other job. For adapters that replace (`replaces: true`).
12
+ */
13
+ export declare const replaceKeyOf: (job: Job) => string | undefined;
14
+ /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
15
+ export declare const deliveryOf: (l: RegisteredListener, e: Envelope) => Delivery;
16
+ /** What running jobs needs from the registry: its definitions, and how it runs a function or a listener's handler. */
17
+ export interface JobsDeps {
18
+ listeners: readonly RegisteredListener[];
19
+ crons: readonly RegisteredCron[];
20
+ functions: readonly RegisteredFn[];
21
+ idOf(x: object): string;
22
+ jobsAdapter: JobsAdapter;
23
+ database: DatabaseAdapter<unknown, unknown> | undefined;
24
+ jobScope: JobScope | undefined;
25
+ maxEventDepth: number;
26
+ now(): Date;
27
+ wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
28
+ report(error: unknown, info: FailureInfo): void;
29
+ /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
30
+ runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
31
+ /** The ctx a listener's handler gets, as `scope`, in an event chain `eventDepth` deep. */
32
+ listenerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
33
+ }
34
+ /**
35
+ * Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
36
+ * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
37
+ */
38
+ export declare function makeJobs(deps: JobsDeps): {
39
+ toJobs: (envelopes: Envelope[], calls: CallJob[], parsed: Map<Envelope, unknown>) => Job[];
40
+ deliver: (jobs: Job[]) => Promise<void>;
41
+ jobs: Jobs;
42
+ due: (at: Date) => CronJob[];
43
+ checkHold: (what: string, seconds: number) => void;
44
+ };