logic-sdk 0.7.0 → 0.7.1

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.
package/README.md CHANGED
@@ -83,8 +83,8 @@ export const registry = createRegistry({
83
83
  // a listener, with tries
84
84
  export const sendConfirmation = listener({ event: () => confirmed, attempts: 3, handler });
85
85
 
86
- // a cron
87
- export const morningDigest = cron({ schedule: "0 8 * * MON-FRI", run: () => sendDigest, scope: asSystem("digest") });
86
+ // a cron: a listener for the clock
87
+ export const sendDigest = cron({ schedule: "0 8 * * MON-FRI", scope: { kind: "system", job: "digest" }, handler: (ctx) => ctx.run(mailDigest) });
88
88
 
89
89
  // later, from a mutation, committed with it
90
90
  ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Call, CallMetaOf, Config, ConfigOf, Constructor, Cron, DatabaseAdapter, DbOf, EventDef, Fn, FnIn, In, JobsOptions, Listener, ListenerCtx, ListenerMetaOf, Out, OwnModules, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, Schema, ScopeOf, ServicesOf } from "./types.ts";
2
- export type { ActionCtx, Call, CallJob, Caller, Config, Constructor, Cron, CronJob, DatabaseAdapter, DeepPartial, Delivery, Envelope, Errors, EventDef, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, SqlDatabase, SweepResult, } from "./types.ts";
1
+ import type { Call, CallMetaOf, Config, ConfigOf, Constructor, Cron, CronCtx, DatabaseAdapter, DbOf, EventDef, In, JobsOptions, Listener, ListenerCtx, ListenerMetaOf, Out, OwnModules, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, Schema, ScopeOf, ServicesOf } from "./types.ts";
2
+ export type { ActionCtx, Call, CallJob, Caller, Config, Constructor, Cron, CronCtx, CronRun, CronJob, DatabaseAdapter, DeepPartial, Delivery, Envelope, Errors, EventDef, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, SqlDatabase, SweepResult, } from "./types.ts";
3
3
  export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./errors.ts";
4
4
  export { inProcess, replaceKeyOf } from "./jobs.ts";
5
5
  type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
@@ -52,11 +52,12 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
52
52
  payload: S;
53
53
  }) => EventDef<In<S>, Out<S>>;
54
54
  /**
55
- * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
56
- * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
57
- * `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
55
+ * Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
56
+ * it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
57
+ * idempotent: a retry runs the whole handler again.
58
+ * `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
58
59
  */
59
- cron: <F extends Fn>(def: CronDef<ScopeOf<C>, F>) => Cron<C>;
60
+ cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>) => Cron<C>;
60
61
  /**
61
62
  * React to an event after commit, like an action. Must be idempotent.
62
63
  * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
@@ -87,28 +88,25 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
87
88
  handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
88
89
  }) => Listener<O, C>;
89
90
  };
90
- /** `cron({...})`: `input` is required exactly when the function needs one. */
91
- type CronDef<S, F extends Fn> = {
92
- /** Stable id, local to its module, like every definer's. Defaults to the export name. */
91
+ /** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
92
+ type CronDef<C extends Config, Sc> = {
93
+ /**
94
+ * Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
95
+ * so set it before you rename the export.
96
+ */
93
97
  id?: string;
94
- /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * 1"`. */
98
+ /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
95
99
  schedule: string;
96
100
  /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
97
101
  timezone?: string;
98
- /**
99
- * Any query, mutation or action, behind a function: `run: () => reports.sendWeekly`. It runs with its policy, validation
100
- * and tracing. Read when the registry is built, like a listener's `event`, so no definer reads an import while files load.
101
- */
102
- run: () => F;
103
- /** Who it runs as: a cron has no caller. */
104
- scope: S;
105
- /** Tries in total, like a listener's. Default 1. */
102
+ /** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
103
+ scope: Sc;
104
+ /** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
106
105
  attempts?: number;
107
- } & (undefined extends FnIn<F> ? {
108
- input?: FnIn<F>;
109
- } : {
110
- input: FnIn<F>;
111
- });
106
+ meta?: ListenerMetaOf<C>;
107
+ /** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
108
+ handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
109
+ };
112
110
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
113
111
  export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): Registry<S, Mods, unknown>;
114
112
  /**
package/dist/index.js CHANGED
@@ -26,17 +26,19 @@ export function init() {
26
26
  /** Something that happened. Emitted by mutations, delivered after commit. */
27
27
  event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
28
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 })`.
29
+ * Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
30
+ * it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
31
+ * idempotent: a retry runs the whole handler again.
32
+ * `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
32
33
  */
33
34
  cron: (def) => {
34
- const { id, schedule, timezone, run, input, scope, attempts } = def;
35
+ const { id, schedule, timezone, scope, attempts, meta, handler } = def;
35
36
  parseSchedule(schedule);
36
37
  if (timezone !== undefined)
37
38
  assertTimeZone(timezone);
38
39
  checkAttempts("cron", attempts);
39
- return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, run, input, scope, attempts });
40
+ // meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
41
+ return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, scope, attempts, meta: meta, handler });
40
42
  },
41
43
  /**
42
44
  * React to an event after commit, like an action. Must be idempotent.
@@ -162,7 +164,7 @@ export function describeModules(modules) {
162
164
  else if (value.kind === "listener")
163
165
  listeners.push({ id, module, name, listener: value, event: value.event() });
164
166
  else if (value.kind === "cron")
165
- crons.push({ id, module, name, cron: value, run: value.run() });
167
+ crons.push({ id, module, name, cron: value });
166
168
  else
167
169
  functions.push({ id, module, name, kind: value.kind, fn: value });
168
170
  }
@@ -206,7 +208,7 @@ function build(options, o) {
206
208
  for (const l of listeners)
207
209
  if (!ids.has(l.event))
208
210
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
209
- jobsAdapter.check?.({ listeners, database });
211
+ jobsAdapter.check?.({ listeners, crons, database });
210
212
  const idOf = (x) => {
211
213
  const id = ids.get(x);
212
214
  if (!id)
@@ -237,11 +239,6 @@ function build(options, o) {
237
239
  check.catch(() => { }); // surfaced at commit; never an unhandled rejection
238
240
  tx.pending.push(check);
239
241
  }
240
- for (const c of crons) {
241
- if (!ids.has(c.run))
242
- throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
243
- 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");
244
- }
245
242
  // ── ctx ──────────────────────────────────────────────────────────────────
246
243
  /** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
247
244
  const enter = (frame, options) => ({
@@ -350,7 +347,7 @@ function build(options, o) {
350
347
  wrap,
351
348
  report,
352
349
  runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
353
- listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
350
+ handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
354
351
  });
355
352
  // ── invoke ───────────────────────────────────────────────────────────────
356
353
  /** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
package/dist/jobs.d.ts CHANGED
@@ -28,8 +28,8 @@ export interface JobsDeps {
28
28
  report(error: unknown, info: FailureInfo): void;
29
29
  /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
30
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>;
31
+ /** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
32
+ handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
33
33
  }
34
34
  /**
35
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
@@ -39,6 +39,6 @@ export declare function makeJobs(deps: JobsDeps): {
39
39
  toJobs: (envelopes: Envelope[], calls: CallJob[], parsed: Map<Envelope, unknown>) => Job[];
40
40
  deliver: (jobs: Job[]) => Promise<void>;
41
41
  jobs: Jobs;
42
- due: (at: Date) => CronJob[];
42
+ due: (at: Date, only?: string) => CronJob[];
43
43
  checkHold: (what: string, seconds: number) => void;
44
44
  };
package/dist/jobs.js CHANGED
@@ -34,7 +34,7 @@ export const deliveryOf = (l, e) => ({
34
34
  * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
35
35
  */
36
36
  export function makeJobs(deps) {
37
- const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, listenerCtx } = deps;
37
+ const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
38
38
  const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
39
39
  const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
40
40
  // ── listeners ────────────────────────────────────────────────────────────
@@ -157,7 +157,10 @@ export function makeJobs(deps) {
157
157
  if (!c)
158
158
  return missing("cron", job.cron);
159
159
  return attemptOnce(async () => {
160
- await runAs(c.run, c.cron.input, c.cron.scope, 0, queued);
160
+ // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
161
+ const { scope, meta, handler } = c.cron;
162
+ const run = { id: c.id, scheduledAt: job.scheduledAt, attempt };
163
+ await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () => handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run }));
161
164
  return "done";
162
165
  });
163
166
  }
@@ -192,7 +195,7 @@ export function makeJobs(deps) {
192
195
  throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
193
196
  const payload = r.value;
194
197
  const ctxEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
195
- return l.listener.handler({ ...listenerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
198
+ return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
196
199
  });
197
200
  return "done";
198
201
  });
@@ -213,14 +216,17 @@ export function makeJobs(deps) {
213
216
  await jobsAdapter.deliver(batch, runnerInto(jobs)).catch((e) => reportEach(e, batch));
214
217
  }
215
218
  }
216
- /** The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once. */
217
- function due(at) {
219
+ /**
220
+ * The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once.
221
+ * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
222
+ */
223
+ function due(at, only) {
218
224
  if (Number.isNaN(at.getTime()))
219
225
  throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
220
226
  const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
221
227
  const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
222
228
  return scheduled
223
- .filter((c) => isDue(c.schedule, minute, c.cron.timezone))
229
+ .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
224
230
  .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
225
231
  }
226
232
  const jobs = {
package/dist/pg-boss.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type PgBoss, type Queue, type WorkOptions } from "pg-boss";
2
2
  import { type ForListeners, type Jobs, type JobsAdapter, type Registry } from "./index.ts";
3
- /** One queue's tuning: `meta.pgBoss`, and `work()`'s `calls` and `crons`. */
3
+ /** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
4
4
  export interface PgBossTuning {
5
5
  /** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
6
6
  queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
@@ -8,7 +8,7 @@ export interface PgBossTuning {
8
8
  worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
9
9
  }
10
10
  /**
11
- * What this adapter reads from a listener's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
11
+ * What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
12
12
  * `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
13
13
  * listener's `attempts`, and the other adapters ignore it.
14
14
  */
@@ -35,14 +35,12 @@ export declare function pgBoss(boss: PgBoss): JobsAdapter;
35
35
  export interface PgBossWorkOptions {
36
36
  /** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
37
37
  calls?: PgBossTuning;
38
- /** Every cron's queue, tuned the same way (crons have no `meta`): `{ queue: { expireInSeconds: 3600 } }` for a long one. */
39
- crons?: PgBossTuning;
40
38
  /** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
41
39
  onError?: (error: unknown) => void;
42
40
  }
43
41
  /**
44
42
  * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
45
- * every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
43
+ * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
46
44
  *
47
45
  * ```ts
48
46
  * await boss.start();
package/dist/pg-boss.js CHANGED
@@ -100,12 +100,14 @@ export function pgBoss(boss) {
100
100
  holds: true, // `startAfter`, however far ahead
101
101
  replaces: true,
102
102
  /** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
103
- check({ listeners, database: given }) {
103
+ check({ listeners, crons, database: given }) {
104
104
  if (!given)
105
105
  throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
106
106
  database = given;
107
107
  for (const l of listeners)
108
108
  queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
109
+ for (const c of crons)
110
+ queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
109
111
  },
110
112
  /** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
111
113
  async enqueue(tx, jobs) {
@@ -158,7 +160,7 @@ export function pgBoss(boss) {
158
160
  }
159
161
  /**
160
162
  * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
161
- * every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
163
+ * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
162
164
  *
163
165
  * ```ts
164
166
  * await boss.start();
@@ -171,7 +173,7 @@ export async function work(registry, boss, options = {}) {
171
173
  const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
172
174
  const queues = [
173
175
  ...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
174
- ...crons.map((c) => ({ name: queueName(c.id), tuning: options.crons })),
176
+ ...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
175
177
  { name: CALLS_QUEUE, tuning: options.calls },
176
178
  ];
177
179
  /** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Caller, type DeepPartial, type CallJob, type Delivery, type Envelope, type Fn, type FnIn, type FnOut, type JobOutcome, type Listener, type Registry } from "./index.ts";
1
+ import { type Caller, type DeepPartial, type CallJob, type Cron, type Delivery, type Envelope, type Fn, type FnIn, type FnOut, type JobOutcome, type Listener, type Registry } from "./index.ts";
2
2
  export interface TestOptions<Cf = unknown> {
3
3
  /** Replace services (e.g. `{ mailer: memoryMailer() }`). */
4
4
  services?: object;
@@ -32,6 +32,14 @@ export interface TestJobs<S> {
32
32
  scope: S;
33
33
  attempt?: number;
34
34
  }): Promise<JobOutcome>;
35
+ /**
36
+ * Run one cron by hand, as its own scope, for the minute `at` (default: the test's now), whatever its schedule. Throws
37
+ * its failure. `t.jobs.tick(at)` runs every cron due that minute instead.
38
+ */
39
+ perform(cron: Cron, options?: {
40
+ at?: Date | string;
41
+ attempt?: number;
42
+ }): Promise<JobOutcome>;
35
43
  /** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
36
44
  tick(at?: Date | string): Promise<string[]>;
37
45
  }
package/dist/testing.js CHANGED
@@ -194,8 +194,21 @@ export function createTestRegistry(registry, options = {}) {
194
194
  travelled = undefined;
195
195
  }
196
196
  },
197
- perform(listener, payload, { scope, attempt }) {
197
+ perform(target, ...rest) {
198
198
  const state = current();
199
+ if (target.kind === "cron") {
200
+ const { at, attempt } = (rest[0] ?? {});
201
+ const cron = state.registry.definitions.crons.find((c) => c.cron === target);
202
+ if (!cron)
203
+ throw new Error("[logic-sdk] t.jobs.perform got a cron that isn't registered: export it from its module.");
204
+ const when = at === undefined ? clock() : new Date(at);
205
+ if (Number.isNaN(when.getTime()))
206
+ throw new Error(`[logic-sdk] t.jobs.perform({ at }) needs a valid date (got ${String(at)}).`);
207
+ const [job] = state.registry[INTERNAL].due(when, cron.id);
208
+ return settle(state, () => state.registry.jobs.run(job, { attempt }));
209
+ }
210
+ const listener = target;
211
+ const [payload, { scope, attempt }] = rest;
199
212
  const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
200
213
  if (!registered)
201
214
  throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
package/dist/types.d.ts CHANGED
@@ -218,18 +218,26 @@ export interface CallJob {
218
218
  * run, or a call `ctx.schedule` asked for.
219
219
  */
220
220
  export type Job = Delivery | CronJob | CallJob;
221
- /** A function to run on a schedule, as `scope`. Export it from a module, like listeners. */
221
+ /** Work on a schedule, as `scope`: a handler, like a listener's, run when the clock says. Export it from a module. */
222
222
  export interface Cron<C extends Config = any> extends FromInit<C> {
223
223
  readonly [BRAND]: "cron";
224
224
  readonly kind: "cron";
225
225
  readonly id?: string;
226
226
  readonly schedule: string;
227
227
  readonly timezone?: string;
228
- /** The function it runs, read when the registry is built, like a listener's `event`. */
229
- readonly run: () => Fn;
230
- readonly input?: unknown;
231
228
  readonly scope: object;
232
229
  readonly attempts?: number;
230
+ readonly meta?: Readonly<Record<string, unknown>>;
231
+ readonly handler: (ctx: never) => Promise<unknown>;
232
+ }
233
+ /** The run a cron's handler is doing. No scope here: `ctx.scope` is the one it runs as. */
234
+ export interface CronRun {
235
+ /** The cron's id: `tasks.wakeDue`. */
236
+ id: string;
237
+ /** The minute this run is for (ISO), even when it runs late or again: which day a digest covers. */
238
+ scheduledAt: string;
239
+ /** 1 on the first try. */
240
+ attempt: number;
233
241
  }
234
242
  /**
235
243
  * What running a job resolved to. `failed`: out of attempts (code this process doesn't have uses them too), a rule said
@@ -267,7 +275,7 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
267
275
  export interface RunOptions<S = object> {
268
276
  /**
269
277
  * The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }`
270
- * to render in another language, `{ scope: asSystem("reports.weekly") }` to act as someone else on purpose. The
278
+ * to render in another language, `{ scope: { kind: "system", job: "reports.weekly" } }` to act as someone else on purpose. The
271
279
  * callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.
272
280
  */
273
281
  scope?: S;
@@ -349,6 +357,10 @@ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C,
349
357
  export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
350
358
  event: ListenerEvent<O>;
351
359
  }
360
+ /** A cron's handler's ctx: an action's, as the cron's own scope, plus the run. */
361
+ export interface CronCtx<C extends Config, S = ScopeOf<C>> extends ActionCtx<C, S> {
362
+ cron: CronRun;
363
+ }
352
364
  /**
353
365
  * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
354
366
  * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `handler`.
@@ -458,6 +470,7 @@ export interface JobsAdapter {
458
470
  /** At `createRegistry`: refuse a setup this adapter can't honour (a database it doesn't share). */
459
471
  check?(setup: {
460
472
  listeners: readonly RegisteredListener[];
473
+ crons: readonly RegisteredCron[];
461
474
  database: DatabaseAdapter<unknown, unknown> | undefined;
462
475
  }): void;
463
476
  /** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
@@ -530,8 +543,8 @@ export type JobsOptions<S = object, T = any> = {
530
543
  });
531
544
  export interface Call<M = unknown> {
532
545
  id: string;
533
- kind: Kind | "listener";
534
- /** The function's or listener's `meta` (undefined when it has none). */
546
+ kind: Kind | "listener" | "cron";
547
+ /** The function's, listener's or cron's `meta` (undefined when it has none). */
535
548
  meta: M | undefined;
536
549
  /** Raw input as received (before validation). */
537
550
  input: unknown;
@@ -598,7 +611,6 @@ export interface RegisteredListener extends Registered {
598
611
  }
599
612
  export interface RegisteredCron extends Registered {
600
613
  cron: Cron;
601
- run: Fn;
602
614
  }
603
615
  /** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
604
616
  export interface Jobs {
@@ -650,8 +662,8 @@ export interface Registry<S extends object = object, Mods extends Record<string,
650
662
  derive(more: Overrides): Registry<S, Mods, Cf>;
651
663
  /** An event as `emit` would make it, for `t.jobs.perform`. */
652
664
  envelope(event: EventDef, payload: unknown, scope: S): Envelope;
653
- /** The cron runs due in a minute, for `t.jobs.tick`. */
654
- due(at: Date): CronJob[];
665
+ /** The cron runs due in a minute, for `t.jobs.tick`; with `only`, that cron's run, due or not (`t.jobs.perform`). */
666
+ due(at: Date, only?: string): CronJob[];
655
667
  };
656
668
  }
657
669
  /** The registry's internals, for `logic-sdk/testing`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
5
5
  "keywords": [
6
6
  "actions",
@@ -113,7 +113,7 @@
113
113
  "drizzle-orm": ">=1.0.0-rc.6 <2",
114
114
  "pg-boss": ">=12.39.0 <13",
115
115
  "ai": ">=7 <8",
116
- "@logic-sdk/cli": ">=0.6.4 <0.7.0"
116
+ "@logic-sdk/cli": ">=0.6.5 <0.7.0"
117
117
  },
118
118
  "peerDependenciesMeta": {
119
119
  "@orpc/server": {
@@ -64,11 +64,11 @@ export const cancel = mutation({
64
64
  1. **Pick the kind by what it touches.** Only reads: `query`. Writes to our database: `mutation`. Talks to the network: `action`. Reacts to another module: `listener`.
65
65
  2. **Never put side effects in a mutation or query.** No email, HTTP or payments. They don't have `services` on purpose. Emit an event and react in a listener, or write an action that runs the mutation.
66
66
  3. **Call other modules only with `run(otherModule.fn, input)`.** Import them as `import * as availability from "../availability"`. Never import their `data.ts` or `schema.ts`, from a module or from routes and pages.
67
- 4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing. When an action must write, define the mutation in the action's own file without `export` and `ctx.run` it: nothing outside the file can reach it, so nothing can skip the action's checks. When two files need the same one, put it in `data.ts`, never in `mutations.ts`: exporting it from there for the other file makes `export * from "./mutations"` publish it. A private function can't be scheduled, run by a cron, published or run from a test: test it through the action.
67
+ 4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing. When an action must write, define the mutation in the action's own file without `export` and `ctx.run` it: nothing outside the file can reach it, so nothing can skip the action's checks. When two files need the same one, put it in `data.ts`, never in `mutations.ts`: exporting it from there for the other file makes `export * from "./mutations"` publish it. A private function can't be scheduled, published or run from a test: test it through the action (or the listener or cron whose handler runs it).
68
68
  5. **Always filter by `ctx.scope.accountId`** in `data.ts` helpers, writes included. Loading helpers throw `ctx.errors.notFound()`. Scope is who and where (actor, account, locale); input is what.
69
69
  6. **Authorize every function a user, client or AI tool may call.** `authorize: member` (a policy from `policies.ts`) says who may call it: sync, reads only scope, runs on every call including nested ones. Publish a function by listing it in `src/rpc.ts` (`toORPCProcedure(fn)`) or an agent's tools (`toAITool(caller, fn)`); both refuse one without `authorize`. A hand-written route or Server Action can `caller.run` anything, nothing stops it: only call functions that have `authorize` from them. Give published functions an `output` so nothing unintended leaves.
70
70
  7. **Record rules are `can*` predicates.** Load through a scoped helper, then `if (!canX(ctx.scope.actor, record)) throw ctx.errors.deny();`. `can*` is sync, its result is always used, and the same predicate feeds UI flags in list queries: `can: { cancel: canCancel(actor, b) }`. A rule that must hold at commit goes in the write's `WHERE` or a `FOR UPDATE` re-select.
71
- 8. **Errors:** `throw ctx.errors.reject("snake_reason", details?)` when a rule says no, `ctx.errors.conflict(...)` when someone got there first, `ctx.errors.notFound()`, `ctx.errors.deny()`. Codes are namespaced to your module for you. Never return error objects; never throw plain `Error` for expected cases. Catch only in actions; in a mutation, catch only to rethrow your own error: nested mutations share the caller's transaction, so a caught failure fails the commit with an error naming both. Work over many rows where each must commit or fail alone (a cron over every account) is an `action` that `ctx.run`s the mutation per row inside `try`/`catch`.
71
+ 8. **Errors:** `throw ctx.errors.reject("snake_reason", details?)` when a rule says no, `ctx.errors.conflict(...)` when someone got there first, `ctx.errors.notFound()`, `ctx.errors.deny()`. Codes are namespaced to your module for you. Never return error objects; never throw plain `Error` for expected cases. Catch only in actions; in a mutation, catch only to rethrow your own error: nested mutations share the caller's transaction, so a caught failure fails the commit with an error naming both. Work over many rows where each must commit or fail alone (a cron over every account) `ctx.run`s the mutation per row inside `try`/`catch`, from a cron's handler or an action: never from a mutation.
72
72
  9. **Need the result? `run` it. Just a consequence? `emit`** and let the owning module react in its `listeners.ts`.
73
73
  10. **A listener that wants only some events says so with `when: (payload) => boolean`** (sync, from the payload only), instead of returning early in its handler: the others get no job. The emitter never filters for its listeners.
74
74
  11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, pass the whole scope for that call: `ctx.run(fn, input, { scope: { ...ctx.scope, actor: system } })`. It's never merged, so it's always one of your scope's variants.
@@ -77,7 +77,7 @@ export const cancel = mutation({
77
77
  14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`. A form's schema comes from the function it submits to (`properties.update.input.pick({ name: true })`), not from a schema the module exports.
78
78
  15. **Settings come from `ctx.config`**, never from env inside a module. Declare its shape in `init<Config>()` (`config: { orders: { maxItems: number } }`), fill it from your env at the entry (`createRegistry({ config })`), and read it in any function: `ctx.config.orders.maxItems`. Plain data only. Clients built from secrets go in `services`. Outside modules (the entry, routes, scripts), read env however you like.
79
79
  16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database, jobs: { adapter: databaseQueue(database), scope: { store, load } } })` (your database is the queue, like Laravel's `database` driver; export `jobsTable` from the schema and sweep from a cron trigger or `startTicking`), `outbox(database, cloudflareQueue(env.JOBS))` when another queue runs them (the queue alone works too, and can lose a job on a crash), or `pgBoss(boss)` from `logic-sdk/pg-boss` when the app runs pg-boss (`await boss.start()` in every process, `await work(registry, boss)` in the worker, `boss.stop()` on SIGTERM; tune a listener's queue and workers with `meta: { pgBoss: { queue, worker } }`, never its retries). `store` saves ids, `load` rebuilds the scope when the job runs, with today's roles (`null` discards it: check membership there). `createRegistry` requires `load` with every adapter but `inProcess()`; keep the `system` field of a system scope in both. Never pass a jobs adapter per module, and never enqueue background work by hand from a mutation: `emit` an event. A listener tries once; give it `attempts: 5` when retrying is safe, and `delay: 60` (seconds) to run it later.
80
- 17. **Scheduled work is a `cron`,** exported from the module like a listener: `cron({ schedule: "0 9 * * MON", run: () => fn, scope: asSystem("reports.weekly") })`, where `asSystem` builds a `System` variant of the app's `Scope` (`actor: null`, `system: name`, never built from a request) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. `run` is an existing function (it keeps its policy); never put the work in the cron itself. On Node, `startTicking(registry)` from `logic-sdk/node` ticks and sweeps (`await stop()` on SIGTERM); with pg-boss, `work(registry, boss)` ticks them; on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)`.
80
+ 17. **Scheduled work is a `cron`,** a listener for the clock, exported from the module: `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(fn) } })`, where `scope` is a system variant of the app's own `Scope` (its own `kind` and the job's name, never built from a request; the library defines no scope fields) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. The handler gets an action's ctx plus `ctx.cron` (`scheduledAt`: the minute the run is for; `attempt`), and `ctx.scope` typed as the declared scope; every `ctx.run` checks that function's policy against it. Name a cron after its work, like a listener (`sendDigest`); one that runs shared work, after when it runs (`nightly`). A retry reruns the whole handler: make it idempotent, and put all-or-nothing work in one `ctx.run(mutation)`. `meta` like a listener's (`meta.pgBoss` tunes its queue). On Node, `startTicking(registry)` from `logic-sdk/node` ticks and sweeps (`await stop()` on SIGTERM); with pg-boss, `work(registry, boss)` ticks them; on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)` (every cron due that minute) or `t.jobs.perform(cron, { at })` (that one, due or not).
81
81
  18. **Work for later is `ctx.schedule(fn, input, { at } | { delay })`,** from a mutation only, so it commits with it (actions and listeners run a mutation that schedules). The function re-checks its reason when it runs ("still confirmed?"): there's no cancel. Like a cron's, it can run twice, mutations included, so make it idempotent (a unique key and `onConflictDoNothing()`). One try by default: add `attempts: 3` for an action that calls an API. When what it's for can change (a booking's dates), pass `replace: bookingId`: the newer call replaces the waiting one, so it doesn't run twice. It needs `jobs: { adapter: databaseQueue(database), scope: { store, load } }`, an `outbox` or `pgBoss(boss)` (rule 16); tests read `t.jobs.scheduled` and run it with `t.jobs.drain({ until })`.
82
82
 
83
83
  ## Tests
package/src/index.ts CHANGED
@@ -11,13 +11,13 @@ import type {
11
11
  ConfigOf,
12
12
  Constructor,
13
13
  Cron,
14
+ CronCtx,
14
15
  DatabaseAdapter,
15
16
  DbOf,
16
17
  Envelope,
17
18
  EventDef,
18
19
  FailureInfo,
19
20
  Fn,
20
- FnIn,
21
21
  Frozen,
22
22
  In,
23
23
  Job,
@@ -51,6 +51,8 @@ export type {
51
51
  Config,
52
52
  Constructor,
53
53
  Cron,
54
+ CronCtx,
55
+ CronRun,
54
56
  CronJob,
55
57
  DatabaseAdapter,
56
58
  DeepPartial,
@@ -157,16 +159,18 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
157
159
  }): EventDef<In<S>, Out<S>> =>
158
160
  Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
159
161
  /**
160
- * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
161
- * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
162
- * `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
162
+ * Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
163
+ * it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
164
+ * idempotent: a retry runs the whole handler again.
165
+ * `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
163
166
  */
164
- cron: <F extends Fn>(def: CronDef<ScopeOf<C>, F>): Cron<C> => {
165
- const { id, schedule, timezone, run, input, scope, attempts } = def;
167
+ cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>): Cron<C> => {
168
+ const { id, schedule, timezone, scope, attempts, meta, handler } = def;
166
169
  parseSchedule(schedule);
167
170
  if (timezone !== undefined) assertTimeZone(timezone);
168
171
  checkAttempts("cron", attempts);
169
- return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, run, input, scope, attempts });
172
+ // meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
173
+ return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, scope, attempts, meta: meta as Cron["meta"], handler });
170
174
  },
171
175
  /**
172
176
  * React to an event after commit, like an action. Must be idempotent.
@@ -207,24 +211,25 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
207
211
  };
208
212
  }
209
213
 
210
- /** `cron({...})`: `input` is required exactly when the function needs one. */
211
- type CronDef<S, F extends Fn> = {
212
- /** Stable id, local to its module, like every definer's. Defaults to the export name. */
214
+ /** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
215
+ type CronDef<C extends Config, Sc> = {
216
+ /**
217
+ * Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
218
+ * so set it before you rename the export.
219
+ */
213
220
  id?: string;
214
- /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * 1"`. */
221
+ /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
215
222
  schedule: string;
216
223
  /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
217
224
  timezone?: string;
218
- /**
219
- * Any query, mutation or action, behind a function: `run: () => reports.sendWeekly`. It runs with its policy, validation
220
- * and tracing. Read when the registry is built, like a listener's `event`, so no definer reads an import while files load.
221
- */
222
- run: () => F;
223
- /** Who it runs as: a cron has no caller. */
224
- scope: S;
225
- /** Tries in total, like a listener's. Default 1. */
225
+ /** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
226
+ scope: Sc;
227
+ /** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
226
228
  attempts?: number;
227
- } & (undefined extends FnIn<F> ? { input?: FnIn<F> } : { input: FnIn<F> });
229
+ meta?: ListenerMetaOf<C>;
230
+ /** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
231
+ handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
232
+ };
228
233
 
229
234
  /** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
230
235
  const MAX_RUN_DEPTH = 64;
@@ -371,7 +376,7 @@ export function describeModules(modules: Record<string, object>) {
371
376
  ids.set(value, id);
372
377
  if (value.kind === "event") events.push({ id, module, name, event: value });
373
378
  else if (value.kind === "listener") listeners.push({ id, module, name, listener: value, event: value.event() });
374
- else if (value.kind === "cron") crons.push({ id, module, name, cron: value, run: value.run() });
379
+ else if (value.kind === "cron") crons.push({ id, module, name, cron: value });
375
380
  else functions.push({ id, module, name, kind: value.kind, fn: value });
376
381
  }
377
382
  }
@@ -421,7 +426,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
421
426
  for (const l of listeners)
422
427
  if (!ids.has(l.event))
423
428
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
424
- jobsAdapter.check?.({ listeners, database });
429
+ jobsAdapter.check?.({ listeners, crons, database });
425
430
 
426
431
  const idOf = (x: object) => {
427
432
  const id = ids.get(x);
@@ -454,12 +459,6 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
454
459
  tx.pending.push(check);
455
460
  }
456
461
 
457
- for (const c of crons) {
458
- if (!ids.has(c.run))
459
- throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
460
- 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");
461
- }
462
-
463
462
  // ── ctx ──────────────────────────────────────────────────────────────────
464
463
  /** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
465
464
  const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
@@ -568,7 +567,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
568
567
  wrap,
569
568
  report,
570
569
  runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
571
- listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
570
+ handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
572
571
  });
573
572
 
574
573
  // ── invoke ───────────────────────────────────────────────────────────────
package/src/jobs.ts CHANGED
@@ -16,6 +16,7 @@ import type {
16
16
  JobsAdapter,
17
17
  JobScope,
18
18
  Jobs,
19
+ CronRun,
19
20
  ListenerEvent,
20
21
  RegisteredCron,
21
22
  RegisteredFn,
@@ -70,8 +71,8 @@ export interface JobsDeps {
70
71
  report(error: unknown, info: FailureInfo): void;
71
72
  /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
72
73
  runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
73
- /** The ctx a listener's handler gets, as `scope`, in an event chain `eventDepth` deep. */
74
- listenerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
74
+ /** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
75
+ handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
75
76
  }
76
77
 
77
78
  /**
@@ -79,7 +80,7 @@ export interface JobsDeps {
79
80
  * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
80
81
  */
81
82
  export function makeJobs(deps: JobsDeps) {
82
- const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, listenerCtx } = deps;
83
+ const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
83
84
  const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
84
85
  const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
85
86
 
@@ -206,7 +207,12 @@ export function makeJobs(deps: JobsDeps) {
206
207
  const c = cronById.get(job.cron);
207
208
  if (!c) return missing("cron", job.cron);
208
209
  return attemptOnce(async () => {
209
- await runAs(c.run, c.cron.input, c.cron.scope, 0, queued);
210
+ // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
211
+ const { scope, meta, handler } = c.cron;
212
+ const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
213
+ await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () =>
214
+ handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run } as never), // SAFETY: as for listeners: the ctx was built for a cron
215
+ );
210
216
  return "done";
211
217
  });
212
218
  }
@@ -235,7 +241,7 @@ export function makeJobs(deps: JobsDeps) {
235
241
  if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
236
242
  const payload = r.value;
237
243
  const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
238
- return l.listener.handler({ ...listenerCtx(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
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
239
245
  });
240
246
  return "done";
241
247
  });
@@ -259,13 +265,16 @@ export function makeJobs(deps: JobsDeps) {
259
265
  }
260
266
  }
261
267
 
262
- /** The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once. */
263
- function due(at: Date): CronJob[] {
268
+ /**
269
+ * The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once.
270
+ * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
271
+ */
272
+ function due(at: Date, only?: string): CronJob[] {
264
273
  if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
265
274
  const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
266
275
  const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
267
276
  return scheduled
268
- .filter((c) => isDue(c.schedule, minute, c.cron.timezone))
277
+ .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
269
278
  .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
270
279
  }
271
280
 
package/src/pg-boss.ts CHANGED
@@ -6,7 +6,7 @@ import { fromDrizzle, type Db, type DrizzleTransactionLike, type JobInsert, type
6
6
  import { replaceKeyOf, type DatabaseAdapter, type ForListeners, type Job, type Jobs, type JobsAdapter, type Registry } from "./index.ts";
7
7
  import { startTicking } from "./node.ts";
8
8
 
9
- /** One queue's tuning: `meta.pgBoss`, and `work()`'s `calls` and `crons`. */
9
+ /** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
10
10
  export interface PgBossTuning {
11
11
  /** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
12
12
  queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
@@ -15,7 +15,7 @@ export interface PgBossTuning {
15
15
  }
16
16
 
17
17
  /**
18
- * What this adapter reads from a listener's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
18
+ * What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
19
19
  * `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
20
20
  * listener's `attempts`, and the other adapters ignore it.
21
21
  */
@@ -123,10 +123,11 @@ export function pgBoss(boss: PgBoss): JobsAdapter {
123
123
  holds: true, // `startAfter`, however far ahead
124
124
  replaces: true,
125
125
  /** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
126
- check({ listeners, database: given }) {
126
+ check({ listeners, crons, database: given }) {
127
127
  if (!given) throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
128
128
  database = given;
129
129
  for (const l of listeners) queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
130
+ for (const c of crons) queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
130
131
  },
131
132
  /** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
132
133
  async enqueue(tx, jobs) {
@@ -176,15 +177,13 @@ export function pgBoss(boss: PgBoss): JobsAdapter {
176
177
  export interface PgBossWorkOptions {
177
178
  /** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
178
179
  calls?: PgBossTuning;
179
- /** Every cron's queue, tuned the same way (crons have no `meta`): `{ queue: { expireInSeconds: 3600 } }` for a long one. */
180
- crons?: PgBossTuning;
181
180
  /** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
182
181
  onError?: (error: unknown) => void;
183
182
  }
184
183
 
185
184
  /**
186
185
  * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
187
- * every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
186
+ * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
188
187
  *
189
188
  * ```ts
190
189
  * await boss.start();
@@ -201,7 +200,7 @@ export async function work(
201
200
  const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
202
201
  const queues: { name: string; tuning: PgBossTuning | undefined }[] = [
203
202
  ...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
204
- ...crons.map((c) => ({ name: queueName(c.id), tuning: options.crons })),
203
+ ...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
205
204
  { name: CALLS_QUEUE, tuning: options.calls },
206
205
  ];
207
206
 
package/src/testing.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  type DatabaseAdapter,
5
5
  type DeepPartial,
6
6
  type CallJob,
7
+ type Cron,
7
8
  type Delivery,
8
9
  type Envelope,
9
10
  type Fn,
@@ -47,6 +48,11 @@ export interface TestJobs<S> {
47
48
  drain(options?: { until?: Date | string }): Promise<void>;
48
49
  /** Run one listener by hand, as if its event had been emitted as `scope`. Throws its failure, like `drain()`. */
49
50
  perform<O>(listener: Listener<O>, payload: O, options: { scope: S; attempt?: number }): Promise<JobOutcome>;
51
+ /**
52
+ * Run one cron by hand, as its own scope, for the minute `at` (default: the test's now), whatever its schedule. Throws
53
+ * its failure. `t.jobs.tick(at)` runs every cron due that minute instead.
54
+ */
55
+ perform(cron: Cron, options?: { at?: Date | string; attempt?: number }): Promise<JobOutcome>;
50
56
  /** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
51
57
  tick(at?: Date | string): Promise<string[]>;
52
58
  }
@@ -270,8 +276,19 @@ export function createTestRegistry<S extends object, Mods extends Record<string,
270
276
  travelled = undefined;
271
277
  }
272
278
  },
273
- perform(listener, payload, { scope, attempt }) {
279
+ perform(target: Listener<any> | Cron, ...rest: any[]) {
274
280
  const state = current();
281
+ if (target.kind === "cron") {
282
+ const { at, attempt } = (rest[0] ?? {}) as { at?: Date | string; attempt?: number };
283
+ const cron = state.registry.definitions.crons.find((c) => c.cron === target);
284
+ if (!cron) throw new Error("[logic-sdk] t.jobs.perform got a cron that isn't registered: export it from its module.");
285
+ const when = at === undefined ? clock() : new Date(at);
286
+ if (Number.isNaN(when.getTime())) throw new Error(`[logic-sdk] t.jobs.perform({ at }) needs a valid date (got ${String(at)}).`);
287
+ const [job] = state.registry[INTERNAL].due(when, cron.id);
288
+ return settle(state, () => state.registry.jobs.run(job!, { attempt }));
289
+ }
290
+ const listener = target;
291
+ const [payload, { scope, attempt }] = rest as [unknown, { scope: S; attempt?: number }];
275
292
  const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
276
293
  if (!registered) throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
277
294
  const envelope = state.registry[INTERNAL].envelope(registered.event, payload, scope);
package/src/types.ts CHANGED
@@ -215,18 +215,27 @@ export interface CallJob {
215
215
  */
216
216
  export type Job = Delivery | CronJob | CallJob;
217
217
 
218
- /** A function to run on a schedule, as `scope`. Export it from a module, like listeners. */
218
+ /** Work on a schedule, as `scope`: a handler, like a listener's, run when the clock says. Export it from a module. */
219
219
  export interface Cron<C extends Config = any> extends FromInit<C> {
220
220
  readonly [BRAND]: "cron";
221
221
  readonly kind: "cron";
222
222
  readonly id?: string;
223
223
  readonly schedule: string;
224
224
  readonly timezone?: string;
225
- /** The function it runs, read when the registry is built, like a listener's `event`. */
226
- readonly run: () => Fn;
227
- readonly input?: unknown;
228
225
  readonly scope: object;
229
226
  readonly attempts?: number;
227
+ readonly meta?: Readonly<Record<string, unknown>>;
228
+ readonly handler: (ctx: never) => Promise<unknown>;
229
+ }
230
+
231
+ /** The run a cron's handler is doing. No scope here: `ctx.scope` is the one it runs as. */
232
+ export interface CronRun {
233
+ /** The cron's id: `tasks.wakeDue`. */
234
+ id: string;
235
+ /** The minute this run is for (ISO), even when it runs late or again: which day a digest covers. */
236
+ scheduledAt: string;
237
+ /** 1 on the first try. */
238
+ attempt: number;
230
239
  }
231
240
 
232
241
  /**
@@ -268,7 +277,7 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
268
277
  export interface RunOptions<S = object> {
269
278
  /**
270
279
  * The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }`
271
- * to render in another language, `{ scope: asSystem("reports.weekly") }` to act as someone else on purpose. The
280
+ * to render in another language, `{ scope: { kind: "system", job: "reports.weekly" } }` to act as someone else on purpose. The
272
281
  * callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.
273
282
  */
274
283
  scope?: S;
@@ -347,6 +356,10 @@ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C,
347
356
  export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
348
357
  event: ListenerEvent<O>;
349
358
  }
359
+ /** A cron's handler's ctx: an action's, as the cron's own scope, plus the run. */
360
+ export interface CronCtx<C extends Config, S = ScopeOf<C>> extends ActionCtx<C, S> {
361
+ cron: CronRun;
362
+ }
350
363
 
351
364
  /**
352
365
  * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
@@ -478,7 +491,11 @@ export interface JobsAdapter {
478
491
  */
479
492
  replaces?: true;
480
493
  /** At `createRegistry`: refuse a setup this adapter can't honour (a database it doesn't share). */
481
- check?(setup: { listeners: readonly RegisteredListener[]; database: DatabaseAdapter<unknown, unknown> | undefined }): void;
494
+ check?(setup: {
495
+ listeners: readonly RegisteredListener[];
496
+ crons: readonly RegisteredCron[];
497
+ database: DatabaseAdapter<unknown, unknown> | undefined;
498
+ }): void;
482
499
  /** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
483
500
  enqueue?(tx: unknown, jobs: Job[]): Promise<void>;
484
501
  /** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
@@ -555,8 +572,8 @@ export type JobsOptions<S = object, T = any> = {
555
572
 
556
573
  export interface Call<M = unknown> {
557
574
  id: string;
558
- kind: Kind | "listener";
559
- /** The function's or listener's `meta` (undefined when it has none). */
575
+ kind: Kind | "listener" | "cron";
576
+ /** The function's, listener's or cron's `meta` (undefined when it has none). */
560
577
  meta: M | undefined;
561
578
  /** Raw input as received (before validation). */
562
579
  input: unknown;
@@ -628,7 +645,6 @@ export interface RegisteredListener extends Registered {
628
645
  }
629
646
  export interface RegisteredCron extends Registered {
630
647
  cron: Cron;
631
- run: Fn;
632
648
  }
633
649
 
634
650
  /** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
@@ -680,8 +696,8 @@ export interface Registry<S extends object = object, Mods extends Record<string,
680
696
  derive(more: Overrides): Registry<S, Mods, Cf>;
681
697
  /** An event as `emit` would make it, for `t.jobs.perform`. */
682
698
  envelope(event: EventDef, payload: unknown, scope: S): Envelope;
683
- /** The cron runs due in a minute, for `t.jobs.tick`. */
684
- due(at: Date): CronJob[];
699
+ /** The cron runs due in a minute, for `t.jobs.tick`; with `only`, that cron's run, due or not (`t.jobs.perform`). */
700
+ due(at: Date, only?: string): CronJob[];
685
701
  };
686
702
  }
687
703