logic-sdk 0.7.1 → 0.7.2

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 (99) hide show
  1. package/README.md +7 -7
  2. package/dist/adapters/cloudflare-queue.d.ts +14 -0
  3. package/dist/adapters/cloudflare-queue.js +48 -0
  4. package/dist/adapters/drizzle-pg.d.ts +250 -0
  5. package/dist/adapters/drizzle-pg.js +69 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +257 -0
  7. package/dist/adapters/drizzle-sqlite.js +196 -0
  8. package/dist/adapters/pg-boss.d.ts +45 -0
  9. package/dist/adapters/pg-boss.js +180 -0
  10. package/dist/adapters/postgres.d.ts +32 -0
  11. package/dist/adapters/postgres.js +105 -0
  12. package/dist/adapters/sqlite.d.ts +13 -0
  13. package/dist/adapters/sqlite.js +88 -0
  14. package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
  15. package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
  16. package/dist/ai.d.ts +1 -32
  17. package/dist/ai.js +1 -40
  18. package/dist/cloudflare.d.ts +2 -55
  19. package/dist/cloudflare.js +2 -85
  20. package/dist/core/in-process.d.ts +9 -0
  21. package/dist/core/in-process.js +17 -0
  22. package/dist/{jobs.d.ts → core/jobs.d.ts} +23 -10
  23. package/dist/{jobs.js → core/jobs.js} +152 -39
  24. package/dist/core/registry.d.ts +120 -0
  25. package/dist/core/registry.js +503 -0
  26. package/dist/core/testing.d.ts +75 -0
  27. package/dist/core/testing.js +230 -0
  28. package/dist/{types.d.ts → core/types.d.ts} +203 -40
  29. package/dist/drizzle/pg.d.ts +3 -236
  30. package/dist/drizzle/pg.js +2 -67
  31. package/dist/drizzle/sqlite.d.ts +3 -242
  32. package/dist/drizzle/sqlite.js +2 -194
  33. package/dist/fetch.d.ts +1 -19
  34. package/dist/fetch.js +1 -30
  35. package/dist/hosts/cloudflare.d.ts +42 -0
  36. package/dist/hosts/cloudflare.js +39 -0
  37. package/dist/hosts/node.d.ts +26 -0
  38. package/dist/hosts/node.js +76 -0
  39. package/dist/hosts/pg-boss.d.ts +22 -0
  40. package/dist/hosts/pg-boss.js +55 -0
  41. package/dist/index.d.ts +5 -122
  42. package/dist/index.js +4 -492
  43. package/dist/integrations/ai.d.ts +32 -0
  44. package/dist/integrations/ai.js +40 -0
  45. package/dist/integrations/fetch.d.ts +19 -0
  46. package/dist/integrations/fetch.js +30 -0
  47. package/dist/integrations/orpc.d.ts +22 -0
  48. package/dist/integrations/orpc.js +37 -0
  49. package/dist/node.d.ts +1 -26
  50. package/dist/node.js +1 -76
  51. package/dist/orpc.d.ts +1 -21
  52. package/dist/orpc.js +1 -37
  53. package/dist/pg-boss.d.ts +2 -53
  54. package/dist/pg-boss.js +2 -213
  55. package/dist/postgres.d.ts +2 -28
  56. package/dist/postgres.js +1 -82
  57. package/dist/sqlite.d.ts +2 -9
  58. package/dist/sqlite.js +1 -65
  59. package/dist/testing.d.ts +1 -75
  60. package/dist/testing.js +1 -227
  61. package/package.json +2 -2
  62. package/skills/logic-sdk/SKILL.md +4 -3
  63. package/src/adapters/cloudflare-queue.ts +56 -0
  64. package/src/adapters/drizzle-pg.ts +108 -0
  65. package/src/adapters/drizzle-sqlite.ts +234 -0
  66. package/src/adapters/pg-boss.ts +195 -0
  67. package/src/adapters/postgres.ts +112 -0
  68. package/src/adapters/sqlite.ts +96 -0
  69. package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
  70. package/src/ai.ts +1 -62
  71. package/src/cloudflare.ts +2 -107
  72. package/src/core/in-process.ts +18 -0
  73. package/src/{jobs.ts → core/jobs.ts} +152 -38
  74. package/src/core/registry.ts +671 -0
  75. package/src/core/testing.ts +307 -0
  76. package/src/{types.ts → core/types.ts} +197 -40
  77. package/src/drizzle/pg.ts +3 -110
  78. package/src/drizzle/sqlite.ts +3 -236
  79. package/src/fetch.ts +1 -31
  80. package/src/hosts/cloudflare.ts +54 -0
  81. package/src/hosts/node.ts +99 -0
  82. package/src/hosts/pg-boss.ts +71 -0
  83. package/src/index.ts +15 -652
  84. package/src/integrations/ai.ts +63 -0
  85. package/src/integrations/fetch.ts +31 -0
  86. package/src/integrations/orpc.ts +47 -0
  87. package/src/node.ts +1 -99
  88. package/src/orpc.ts +1 -46
  89. package/src/pg-boss.ts +2 -241
  90. package/src/postgres.ts +2 -90
  91. package/src/sqlite.ts +2 -74
  92. package/src/testing.ts +1 -305
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -7,10 +7,10 @@ import type {
7
7
  CronJob,
8
8
  DatabaseAdapter,
9
9
  Delivery,
10
+ FailedJobs,
10
11
  Envelope,
11
12
  FailureInfo,
12
13
  Fn,
13
- InProcess,
14
14
  Job,
15
15
  JobOutcome,
16
16
  JobsAdapter,
@@ -23,29 +23,73 @@ import type {
23
23
  RegisteredListener,
24
24
  RunJobOptions,
25
25
  Runner,
26
+ ScopeMatch,
26
27
  } from "./types.ts";
27
- import { RUNS_NOW } from "./types.ts";
28
28
 
29
- const IN_PROCESS: InProcess = {
30
- [RUNS_NOW]: true,
31
- async deliver(jobs, { run }) {
32
- // one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
33
- for (const job of jobs) await run({ ...job, attempts: 1 });
34
- },
35
- };
29
+ export const isPlainObject = (v: unknown): v is Record<string, unknown> =>
30
+ !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
31
+
32
+ /**
33
+ * JSON with object keys sorted, so `{ a, b }` and `{ b, a }` are one input, like TanStack Query's `hashKey`. Undefined
34
+ * properties drop out, as in JSON; array order counts. The input as passed, before its schema runs (defaults aren't
35
+ * applied), so a schema change doesn't move what's waiting.
36
+ */
37
+ const canonical = (value: unknown): string =>
38
+ JSON.stringify(value, (_, v) => (isPlainObject(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v)) ?? "";
39
+
40
+ /**
41
+ * What makes a scheduled call with `replace: true` replaceable: its function and its input, `<function id>@<input>`. A
42
+ * newer call with the same one replaces it while it waits. Undefined for every other job.
43
+ */
44
+ export const replaceKeyOf = (job: Job): string | undefined => (job.kind === "call" && job.replace ? `${job.fn}@${canonical(job.input)}` : undefined);
45
+
46
+ /**
47
+ * `replaceKeyOf`, as adapters that replace (`replaces: true`) store it: `<function id>@<sha-256 of the input>`, so a
48
+ * large input still fits an index and the function stays readable.
49
+ */
50
+ export async function storedReplaceKey(job: Job): Promise<string | undefined> {
51
+ if (job.kind !== "call" || !job.replace) return undefined;
52
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(job.input)));
53
+ return `${job.fn}@${Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("")}`;
54
+ }
55
+
36
56
  /**
37
- * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
38
- * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
57
+ * A `failed({ scope })` filter as the fields it matches: `{ organization: { id: "o1" } }` is `organization.id = "o1"`.
58
+ * Strings, numbers, booleans and null; never an array or an empty object, which two databases would read differently.
39
59
  */
40
- export const inProcess = (): InProcess => IN_PROCESS;
41
- /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
42
- export const runsNow = (adapter: JobsAdapter) => adapter === IN_PROCESS;
60
+ function scopeMatches(filter: unknown): ScopeMatch[] {
61
+ const out: ScopeMatch[] = [];
62
+ const walk = (value: unknown, path: string[]) => {
63
+ if (value === null || typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) {
64
+ out.push({ path, value });
65
+ return;
66
+ }
67
+ const where = path.length ? path.join(".") : "scope";
68
+ if (!isPlainObject(value))
69
+ throw new Error(`[logic-sdk] jobs.failed({ scope }) matches strings, numbers, booleans and null: ${where} is ${Array.isArray(value) ? "an array" : typeof value}.`);
70
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined);
71
+ if (!keys.length) throw new Error(`[logic-sdk] jobs.failed({ scope }) matches fields: ${where} is an empty object.`);
72
+ for (const k of keys) walk(value[k], [...path, k]);
73
+ };
74
+ walk(filter, []);
75
+ return out;
76
+ }
43
77
 
44
78
  /**
45
- * What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
46
- * waits. Undefined for every other job. For adapters that replace (`replaces: true`).
79
+ * Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. The
80
+ * core's, so every adapter that backs off (the jobs table, Cloudflare's redelivery) waits the same.
47
81
  */
48
- export const replaceKeyOf = (job: Job): string | undefined => (job.kind === "call" && job.replace !== undefined ? `${job.fn}@${job.replace}` : undefined);
82
+ export const defaultBackoff = (attempt: number) => Math.exp(Math.min(attempt, 10));
83
+
84
+ /** Where the docs list each adapter and what it can do. */
85
+ export const ADAPTERS = "see Jobs, Adapters in the docs";
86
+
87
+ /** The minute `at` falls in, and its stamp for a job id: `20261123T0900Z` (no `:`, which BullMQ rejects). */
88
+ function minuteOf(at: Date, what: string) {
89
+ if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] ${what} needs a valid date (got ${String(at)}).`);
90
+ const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
91
+ return { minute, stamp: minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z" };
92
+ }
49
93
 
50
94
  /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
51
95
  export const deliveryOf = (l: RegisteredListener, e: Envelope): Delivery => ({
@@ -65,12 +109,14 @@ export interface JobsDeps {
65
109
  jobsAdapter: JobsAdapter;
66
110
  database: DatabaseAdapter<unknown, unknown> | undefined;
67
111
  jobScope: JobScope | undefined;
112
+ /** `jobs.failed`: where failed jobs are kept when the adapter keeps none. */
113
+ failedStore: FailedJobs | undefined;
68
114
  maxEventDepth: number;
69
115
  now(): Date;
70
116
  wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
71
117
  report(error: unknown, info: FailureInfo): void;
72
118
  /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
73
- runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
119
+ runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined, job: { id: string; attempt: number }): Promise<unknown>;
74
120
  /** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
75
121
  handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
76
122
  }
@@ -80,9 +126,19 @@ export interface JobsDeps {
80
126
  * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
81
127
  */
82
128
  export function makeJobs(deps: JobsDeps) {
83
- const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
84
- const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
129
+ const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, failedStore, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
130
+ // the adapter's own, or the store's: a job that failed for good is kept by whichever there is
131
+ const keepFailed = jobsAdapter.fail?.bind(jobsAdapter) ?? failedStore?.fail.bind(failedStore);
132
+ /** Your adapter, as messages name it: by what it can't do, and by its own name. */
133
+ const yours = jobsAdapter.name ? `your jobs adapter, ${jobsAdapter.name},` : "your jobs adapter";
134
+ if (failedStore && jobsAdapter.fail) throw new Error(`[logic-sdk] ${yours} keeps failed jobs itself, so jobs.failed has nothing to keep: drop it.`);
85
135
  const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
136
+ if (enqueue && crons.length && !database)
137
+ throw new Error(`[logic-sdk] Crons need \`database\` with ${yours}: their runs are written in a transaction of their own.`);
138
+ /** Cron runs, queued in a transaction of their own (a stored adapter runs each minute once there). */
139
+ const enqueueAlone = async (jobs: Job[]) => {
140
+ if (enqueue && database) await database.transaction((tx) => enqueue(tx, jobs));
141
+ };
86
142
 
87
143
  // ── listeners ────────────────────────────────────────────────────────────
88
144
  const byEvent = new Map<string, RegisteredListener[]>();
@@ -103,12 +159,18 @@ export function makeJobs(deps: JobsDeps) {
103
159
  */
104
160
  function checkHold(what: string, seconds: number) {
105
161
  const { holds } = jobsAdapter;
106
- if (!holds)
107
- throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but your jobs adapter can't hold jobs (inProcess() can't). Use databaseQueue(database).`);
162
+ if (!holds) throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but ${yours} can't hold jobs. Use one that holds them (${ADAPTERS}).`);
108
163
  if (holds !== true && seconds > holds.max)
109
- throw new Error(`[logic-sdk] ${what} waits ${seconds}s; your jobs adapter holds jobs for at most ${holds.max}s. Put an outbox in front, outbox(database, queue): it holds them as long as needed.`);
164
+ throw new Error(`[logic-sdk] ${what} waits ${seconds}s; ${yours} holds jobs for at most ${holds.max}s. Use one that holds them longer, or a jobs table in front of it (${ADAPTERS}).`);
165
+ }
166
+ /** `attempts` above 1 need an adapter that runs a job again: ignored, a failure would just be lost. Rails' inline adapter refuses too. */
167
+ function checkRetries(what: string, attempts: number) {
168
+ if (attempts > 1 && !jobsAdapter.retries)
169
+ throw new Error(`[logic-sdk] ${what} has attempts: ${attempts}, but ${yours} runs each job once. Use one that retries (${ADAPTERS}), or attempts: 1.`);
110
170
  }
111
171
  for (const l of listeners) if (l.listener.delay) checkHold(l.id, l.listener.delay);
172
+ for (const l of listeners) checkRetries(l.id, l.listener.attempts ?? 1);
173
+ for (const c of crons) checkRetries(c.id, c.cron.attempts ?? 1);
112
174
 
113
175
  /**
114
176
  * What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
@@ -210,7 +272,7 @@ export function makeJobs(deps: JobsDeps) {
210
272
  // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
211
273
  const { scope, meta, handler } = c.cron;
212
274
  const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
213
- await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () =>
275
+ await wrap({ id: c.id, kind: "cron", job: { id: job.id, attempt }, meta, input: undefined, scope, depth: 0 }, () =>
214
276
  handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run } as never), // SAFETY: as for listeners: the ctx was built for a cron
215
277
  );
216
278
  return "done";
@@ -222,7 +284,7 @@ export function makeJobs(deps: JobsDeps) {
222
284
  return attemptOnce(async () => {
223
285
  const scope = await scopeOf(job, job.scope, attempt);
224
286
  if (!scope) return "discarded";
225
- await runAs(f.fn, job.input, scope, job.depth, queued);
287
+ await runAs(f.fn, job.input, scope, job.depth, queued, { id: job.id, attempt });
226
288
  return "done";
227
289
  });
228
290
  }
@@ -233,7 +295,7 @@ export function makeJobs(deps: JobsDeps) {
233
295
  return attemptOnce(async () => {
234
296
  const scope = await scopeOf(job, envelope.scope, attempt);
235
297
  if (!scope) return "discarded";
236
- await wrap({ id: l.id, kind: "listener", meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
298
+ await wrap({ id: l.id, kind: "listener", job: { id: job.id, attempt }, meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
237
299
  // its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
238
300
  if (idOf(l.event) !== envelope.name)
239
301
  throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
@@ -241,7 +303,7 @@ export function makeJobs(deps: JobsDeps) {
241
303
  if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
242
304
  const payload = r.value;
243
305
  const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
244
- return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
306
+ return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, payload); // SAFETY: as in registry.ts's invoke: the ctx was built for a listener
245
307
  });
246
308
  return "done";
247
309
  });
@@ -249,7 +311,8 @@ export function makeJobs(deps: JobsDeps) {
249
311
 
250
312
  /** A runner whose jobs' own jobs are collected in `queued`. */
251
313
  const runnerInto = (queued: Job[]): Runner => ({
252
- run: (job, options) => runJob(job, options, queued),
314
+ // a job the adapter runs here and doesn't record itself (inProcess) is kept by the store, if there's one
315
+ run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (failedStore && ((error) => failedStore.fail(job, error))) }, queued),
253
316
  report: (e, job, attempt) => report(e, infoOf(job, attempt)),
254
317
  });
255
318
 
@@ -270,9 +333,7 @@ export function makeJobs(deps: JobsDeps) {
270
333
  * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
271
334
  */
272
335
  function due(at: Date, only?: string): CronJob[] {
273
- if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
274
- const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
275
- const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
336
+ const { minute, stamp } = minuteOf(at, "tick");
276
337
  return scheduled
277
338
  .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
278
339
  .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
@@ -284,10 +345,7 @@ export function makeJobs(deps: JobsDeps) {
284
345
  async tick(at = now()) {
285
346
  const jobs = due(at);
286
347
  if (!jobs.length) return [];
287
- if (enqueue) {
288
- if (!database) throw new Error("[logic-sdk] Crons through a jobs adapter that stores them (like databaseQueue(database)) need `database`.");
289
- await database.transaction((tx) => enqueue(tx, jobs));
290
- }
348
+ await enqueueAlone(jobs);
291
349
  await deliver(jobs);
292
350
  return jobs.map((job) => job.cron);
293
351
  },
@@ -298,10 +356,66 @@ export function makeJobs(deps: JobsDeps) {
298
356
  return result;
299
357
  },
300
358
  async retry(id) {
301
- if (!jobsAdapter.retry) throw new Error(`[logic-sdk] your jobs adapter keeps no jobs, so there's nothing to retry (${id}). databaseQueue(database), outbox(database, queue) and pgBoss(boss) do.`);
302
- return jobsAdapter.retry(id);
359
+ if (jobsAdapter.retry) return jobsAdapter.retry(id);
360
+ if (!failedStore) throw new Error(`[logic-sdk] ${yours} keeps no failed jobs, so there's nothing to retry (${id}). Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
361
+ // out of the store, back to the queue with a fresh set of tries; a hand-off that fails puts it back and throws
362
+ const job = await failedStore.take(id);
363
+ if (!job) return false;
364
+ const queued: Job[] = [];
365
+ try {
366
+ await jobsAdapter.deliver([job], runnerInto(queued));
367
+ } catch (error) {
368
+ await failedStore.fail(job, error);
369
+ throw error;
370
+ }
371
+ await deliver(queued);
372
+ return true;
373
+ },
374
+ async failed(options = {}) {
375
+ const store = jobsAdapter.failed ? jobsAdapter : failedStore;
376
+ if (!store?.failed) throw new Error(`[logic-sdk] ${yours} can't list failed jobs. Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
377
+ const { source, scope, limit = 100, cursor } = options;
378
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw new Error(`[logic-sdk] jobs.failed({ limit }) takes 1 to 1000 (got ${String(limit)}).`);
379
+ const page = await store.failed({ source, scope: scope === undefined ? undefined : scopeMatches(scope), limit, cursor });
380
+ return {
381
+ jobs: page.rows.map(({ id, job, error, failedAt }) => ({
382
+ id,
383
+ kind: job.kind,
384
+ source: infoOf(job).source,
385
+ scope: (job.kind === "call" ? job.scope : job.kind === "delivery" ? job.envelope.scope : undefined) as never, // what `store` saved, typed by the caller
386
+ error,
387
+ failedAt,
388
+ job,
389
+ })),
390
+ cursor: page.cursor,
391
+ };
392
+ },
393
+ async forget(id) {
394
+ const store = jobsAdapter.forget ? jobsAdapter : failedStore;
395
+ if (!store?.forget) throw new Error(`[logic-sdk] ${yours} keeps no failed jobs, so there's nothing to forget (${id}). Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
396
+ return store.forget(id);
397
+ },
398
+ /**
399
+ * One run of a cron, due or not, through the adapter as a tick's would go. Its id is the minute's plus a uuid, so a
400
+ * tick for that minute still runs (stored adapters run each id once), and so does a second invoke.
401
+ */
402
+ async invoke(target, options = {}) {
403
+ const c = typeof target === "string" ? cronById.get(target) : crons.find((r) => r.cron === target);
404
+ if (!c)
405
+ throw new Error(
406
+ typeof target === "string"
407
+ ? `[logic-sdk] jobs.invoke(${JSON.stringify(target)}): no cron has that id (${[...cronById.keys()].join(", ") || "none registered"}).`
408
+ : "[logic-sdk] jobs.invoke got a cron that isn't registered: export it from its module.",
409
+ );
410
+ const { minute, stamp } = minuteOf(options.at ?? now(), "jobs.invoke({ at })");
411
+ const job: CronJob = { kind: "cron", id: `${c.id}@${stamp}-${crypto.randomUUID()}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 };
412
+ await enqueueAlone([job]);
413
+ const queued: Job[] = [];
414
+ await jobsAdapter.deliver([job], runnerInto(queued)); // unlike a tick, a hand-off that fails throws: whoever invoked it needs to know
415
+ await deliver(queued);
416
+ return job.id;
303
417
  },
304
418
  };
305
419
 
306
- return { toJobs, deliver, jobs, due, checkHold };
420
+ return { toJobs, deliver, jobs, due, checkHold, checkRetries, yours };
307
421
  }