logic-sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +47 -22
  2. package/dist/ai.d.ts +16 -29
  3. package/dist/ai.js +13 -24
  4. package/dist/cloudflare.d.ts +55 -0
  5. package/dist/cloudflare.js +85 -0
  6. package/dist/drizzle/pg.d.ts +237 -0
  7. package/dist/drizzle/pg.js +67 -0
  8. package/dist/drizzle/sqlite.d.ts +242 -0
  9. package/dist/drizzle/sqlite.js +194 -0
  10. package/dist/errors.d.ts +33 -0
  11. package/dist/errors.js +45 -0
  12. package/dist/fetch.d.ts +15 -18
  13. package/dist/fetch.js +18 -55
  14. package/dist/index.d.ts +80 -443
  15. package/dist/index.js +261 -229
  16. package/dist/jobs.d.ts +44 -0
  17. package/dist/jobs.js +252 -0
  18. package/dist/node.d.ts +26 -0
  19. package/dist/node.js +76 -0
  20. package/dist/orpc.d.ts +10 -20
  21. package/dist/orpc.js +19 -28
  22. package/dist/pg-boss.d.ts +55 -0
  23. package/dist/pg-boss.js +211 -0
  24. package/dist/postgres.d.ts +28 -0
  25. package/dist/postgres.js +82 -0
  26. package/dist/schedule.d.ts +23 -0
  27. package/dist/schedule.js +109 -0
  28. package/dist/sqlite.d.ts +9 -0
  29. package/dist/sqlite.js +65 -0
  30. package/dist/stored-jobs.d.ts +64 -0
  31. package/dist/stored-jobs.js +188 -0
  32. package/dist/testing.d.ts +51 -15
  33. package/dist/testing.js +198 -46
  34. package/dist/types.d.ts +653 -0
  35. package/dist/types.js +6 -0
  36. package/package.json +45 -7
  37. package/skills/logic-sdk/SKILL.md +114 -0
  38. package/src/ai.ts +29 -51
  39. package/src/cloudflare.ts +107 -0
  40. package/src/drizzle/pg.ts +111 -0
  41. package/src/drizzle/sqlite.ts +236 -0
  42. package/src/errors.ts +59 -0
  43. package/src/fetch.ts +17 -65
  44. package/src/index.ts +422 -572
  45. package/src/jobs.ts +296 -0
  46. package/src/node.ts +99 -0
  47. package/src/orpc.ts +24 -43
  48. package/src/pg-boss.ts +242 -0
  49. package/src/postgres.ts +90 -0
  50. package/src/schedule.ts +129 -0
  51. package/src/sqlite.ts +74 -0
  52. package/src/stored-jobs.ts +260 -0
  53. package/src/testing.ts +253 -56
  54. package/src/types.ts +683 -0
  55. package/dist/drizzle.d.ts +0 -18
  56. package/dist/drizzle.js +0 -23
  57. package/src/drizzle.ts +0 -39
package/src/jobs.ts ADDED
@@ -0,0 +1,296 @@
1
+ import { describeIssues, isDomainError, StalePayload } from "./errors.ts";
2
+ import { isDue, parseSchedule } from "./schedule.ts";
3
+ import type {
4
+ ActionCtx,
5
+ Call,
6
+ CallJob,
7
+ CronJob,
8
+ DatabaseAdapter,
9
+ Delivery,
10
+ Envelope,
11
+ FailureInfo,
12
+ Fn,
13
+ InProcess,
14
+ Job,
15
+ JobOutcome,
16
+ JobsAdapter,
17
+ JobScope,
18
+ Jobs,
19
+ ListenerEvent,
20
+ RegisteredCron,
21
+ RegisteredFn,
22
+ RegisteredListener,
23
+ RunJobOptions,
24
+ Runner,
25
+ } from "./types.ts";
26
+ import { RUNS_NOW } from "./types.ts";
27
+
28
+ const IN_PROCESS: InProcess = {
29
+ [RUNS_NOW]: true,
30
+ async deliver(jobs, { run }) {
31
+ // one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
32
+ for (const job of jobs) await run({ ...job, attempts: 1 });
33
+ },
34
+ };
35
+ /**
36
+ * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
37
+ * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
38
+ */
39
+ export const inProcess = (): InProcess => IN_PROCESS;
40
+ /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
41
+ export const runsNow = (adapter: JobsAdapter) => adapter === IN_PROCESS;
42
+
43
+ /**
44
+ * What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
45
+ * waits. Undefined for every other job. For adapters that replace (`replaces: true`).
46
+ */
47
+ export const replaceKeyOf = (job: Job): string | undefined => (job.kind === "call" && job.replace !== undefined ? `${job.fn}@${job.replace}` : undefined);
48
+
49
+ /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
50
+ export const deliveryOf = (l: RegisteredListener, e: Envelope): Delivery => ({
51
+ kind: "delivery",
52
+ id: `${l.id}@${e.id}`,
53
+ listener: l.id,
54
+ envelope: e,
55
+ attempts: l.listener.attempts ?? 1,
56
+ });
57
+
58
+ /** What running jobs needs from the registry: its definitions, and how it runs a function or a listener's handler. */
59
+ export interface JobsDeps {
60
+ listeners: readonly RegisteredListener[];
61
+ crons: readonly RegisteredCron[];
62
+ functions: readonly RegisteredFn[];
63
+ idOf(x: object): string;
64
+ jobsAdapter: JobsAdapter;
65
+ database: DatabaseAdapter<unknown, unknown> | undefined;
66
+ jobScope: JobScope | undefined;
67
+ maxEventDepth: number;
68
+ now(): Date;
69
+ wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
70
+ report(error: unknown, info: FailureInfo): void;
71
+ /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
72
+ 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>;
75
+ }
76
+
77
+ /**
78
+ * Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
79
+ * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
80
+ */
81
+ export function makeJobs(deps: JobsDeps) {
82
+ const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, listenerCtx } = deps;
83
+ const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
84
+ const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
85
+
86
+ // ── listeners ────────────────────────────────────────────────────────────
87
+ const byEvent = new Map<string, RegisteredListener[]>();
88
+ for (const l of listeners) {
89
+ const name = idOf(l.event);
90
+ byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
91
+ }
92
+
93
+ const listenerById = new Map(listeners.map((l) => [l.id, l]));
94
+
95
+ const scheduled = crons.map((c) => ({ ...c, schedule: parseSchedule(c.cron.schedule) }));
96
+ const cronById = new Map(crons.map((c) => [c.id, c]));
97
+ const fnById = new Map(functions.map((f) => [f.id, f]));
98
+
99
+ /**
100
+ * A job that waits (a listener's `delay`, `ctx.schedule`) needs an adapter that holds it: run early it'd be wrong,
101
+ * kept in memory it'd be lost on restart. Laravel's sync queue drops the delay; we refuse instead.
102
+ */
103
+ function checkHold(what: string, seconds: number) {
104
+ const { holds } = jobsAdapter;
105
+ if (!holds)
106
+ throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but your jobs adapter can't hold jobs (inProcess() can't). Use databaseQueue(database).`);
107
+ if (holds !== true && seconds > holds.max)
108
+ 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.`);
109
+ }
110
+ for (const l of listeners) if (l.listener.delay) checkHold(l.id, l.listener.delay);
111
+
112
+ /**
113
+ * What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
114
+ * scheduled. Events and calls due now past `maxEventDepth` (a listener loop, a function scheduling itself with no
115
+ * delay) are dropped, reported once.
116
+ */
117
+ function toJobs(envelopes: Envelope[], calls: CallJob[], parsed: Map<Envelope, unknown>): Job[] {
118
+ /** Its `when`, if any. A throw is a bug in the app: it fails the mutation, naming the listener. */
119
+ const wants = (l: RegisteredListener, e: Envelope, payload: unknown) => {
120
+ try {
121
+ return !l.listener.when || l.listener.when(payload);
122
+ } catch (error) {
123
+ throw new Error(`[logic-sdk] ${l.id}'s when threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
124
+ }
125
+ };
126
+ const fits = (job: { depth: number }) => job.depth <= maxEventDepth;
127
+ const deepEvent = envelopes.find((e) => !fits(e));
128
+ const deepCall = calls.find((c) => !fits(c));
129
+ const loop = (what: string) => new Error(`[logic-sdk] chain of events and calls deeper than ${maxEventDepth} (jobs.maxEventDepth): stopped queueing ${what} (a loop?)`);
130
+ if (deepEvent) report(loop(deepEvent.name), { source: deepEvent.name });
131
+ else if (deepCall) report(loop(deepCall.fn), infoOf(deepCall));
132
+ const deliveries = envelopes.filter(fits).flatMap((e) =>
133
+ (byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).map((l): Delivery => {
134
+ const job = deliveryOf(l, e);
135
+ const delay = l.listener.delay;
136
+ if (delay) job.runAt = new Date(Date.parse(e.occurredAt) + delay * 1000).toISOString();
137
+ return job;
138
+ }),
139
+ );
140
+ return [...deliveries, ...calls.filter(fits)];
141
+ }
142
+
143
+ /** An adapter that couldn't take a commit's jobs: each one may be lost, so each is reported. */
144
+ const reportEach = (error: unknown, jobs: Job[]) => {
145
+ for (const job of jobs) report(error, { source: "(jobs adapter)", job });
146
+ };
147
+
148
+ /** What `onError` hears about a job. */
149
+ const infoOf = (job: Job, attempt?: number): FailureInfo =>
150
+ job.kind === "delivery"
151
+ ? { source: job.listener, job, attempt }
152
+ : { source: job.kind === "cron" ? job.cron : job.fn, job, attempt };
153
+
154
+ /** Who a stored job runs as: `jobs.scope.load` rebuilds it; null means discard it (reported). */
155
+ async function scopeOf(job: Job, stored: object, attempt: number): Promise<object | null> {
156
+ if (!jobScope?.load) return stored;
157
+ const loaded = await jobScope.load(stored);
158
+ if (loaded === undefined) throw new Error(`[logic-sdk] jobs.scope.load returned undefined for ${job.id}. Return the scope, or null to discard the job.`);
159
+ if (loaded === null) report(new Error(`[logic-sdk] jobs.scope.load returned null for ${job.id}, so it was discarded.`), { ...infoOf(job, attempt), outcome: "discarded" });
160
+ return loaded;
161
+ }
162
+
163
+ /**
164
+ * Run one job: a listener's share of an event, a cron's run, or a scheduled call. Reports every failure; throws only when a retry might
165
+ * help and there are tries left. `fail` keeps a job that failed for good. The jobs it queues land in `queued`, for
166
+ * `deliver` to run once this one is settled; without it (`registry.jobs.run`, in a consumer) they're delivered at once.
167
+ */
168
+ async function runJob(job: Job, { attempt = 1, fail }: RunJobOptions = {}, queued?: Job[]): Promise<JobOutcome> {
169
+ const info = infoOf(job, attempt);
170
+ // read before narrowing: a job queued by another version can have a kind this one doesn't know
171
+ const { id, kind }: { id: string; kind: string } = job;
172
+ const failed = async (error: unknown) => {
173
+ report(error, { ...info, outcome: "failed" });
174
+ await fail?.(error);
175
+ return "failed" as const;
176
+ };
177
+ /** One try of the job's `attempts`. */
178
+ const attemptOnce = async (work: () => Promise<JobOutcome>): Promise<JobOutcome> => {
179
+ const { attempts } = job;
180
+ // its last try was claimed but never finished: a crash, or slower than the lease (Laravel checks this too)
181
+ if (attempt > attempts)
182
+ return failed(
183
+ new Error(`[logic-sdk] ${job.id} has used its ${attempts} attempt(s): the last one never finished (crashed or outlived the lease), or its result wasn't recorded.`),
184
+ );
185
+ try {
186
+ return await work();
187
+ } catch (error) {
188
+ const retrying = attempt < attempts && !(error instanceof StalePayload) && !(isDomainError(error) && error.kind !== "conflict");
189
+ if (!retrying) return failed(error);
190
+ report(error, { ...info, outcome: "retry" });
191
+ throw error;
192
+ }
193
+ };
194
+
195
+ // code this process doesn't have (renamed, removed, or not deployed here yet) is a try like any other, as Laravel
196
+ // treats a missing class: in a rolling deploy the new code gets a later one.
197
+ const cantRun = (why: string) =>
198
+ attemptOnce(async () => {
199
+ throw new Error(`[logic-sdk] ${why}`);
200
+ });
201
+ const missing = (what: string, id: string) =>
202
+ cantRun(`${id} isn't a registered ${what} (renamed, removed or not deployed here yet?), so job ${job.id} can't run.`);
203
+ if (job.kind === "cron") {
204
+ const c = cronById.get(job.cron);
205
+ if (!c) return missing("cron", job.cron);
206
+ return attemptOnce(async () => {
207
+ await runAs(c.cron.run, c.cron.input, c.cron.scope, 0, queued);
208
+ return "done";
209
+ });
210
+ }
211
+ if (job.kind === "call") {
212
+ const f = fnById.get(job.fn);
213
+ if (!f) return missing("function", job.fn);
214
+ return attemptOnce(async () => {
215
+ const scope = await scopeOf(job, job.scope, attempt);
216
+ if (!scope) return "discarded";
217
+ await runAs(f.fn, job.input, scope, job.depth, queued);
218
+ return "done";
219
+ });
220
+ }
221
+ if (job.kind !== "delivery") return cantRun(`job ${id} has kind ${JSON.stringify(kind)}, which this version can't run.`);
222
+ const l = listenerById.get(job.listener);
223
+ if (!l) return missing("listener", job.listener);
224
+ const { envelope } = job;
225
+ return attemptOnce(async () => {
226
+ const scope = await scopeOf(job, envelope.scope, attempt);
227
+ if (!scope) return "discarded";
228
+ await wrap({ id: l.id, kind: "listener", meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
229
+ // its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
230
+ if (idOf(l.event) !== envelope.name)
231
+ throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
232
+ const r = await l.event.payload["~standard"].validate(envelope.payload);
233
+ if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
234
+ const payload = r.value;
235
+ const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
236
+ 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
237
+ });
238
+ return "done";
239
+ });
240
+ }
241
+
242
+ /** A runner whose jobs' own jobs are collected in `queued`. */
243
+ const runnerInto = (queued: Job[]): Runner => ({
244
+ run: (job, options) => runJob(job, options, queued),
245
+ report: (e, job, attempt) => report(e, infoOf(job, attempt)),
246
+ });
247
+
248
+ /**
249
+ * Deliver jobs, then the jobs those queued, and so on. A job is settled before what it queued starts, as a Laravel
250
+ * worker deletes a job before it pops the ones it pushed: a crash in a follow-up can't run the job again.
251
+ */
252
+ async function deliver(jobs: Job[]) {
253
+ while (jobs.length) {
254
+ const batch = jobs;
255
+ jobs = [];
256
+ await jobsAdapter.deliver(batch, runnerInto(jobs)).catch((e) => reportEach(e, batch));
257
+ }
258
+ }
259
+
260
+ /** 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. */
261
+ function due(at: Date): CronJob[] {
262
+ if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
263
+ const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
264
+ const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
265
+ return scheduled
266
+ .filter((c) => isDue(c.schedule, minute, c.cron.timezone))
267
+ .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
268
+ }
269
+
270
+ const jobs: Jobs = {
271
+ // a consumer's own `fail` (pg-boss's work(), which records the reason itself) wins over the adapter's
272
+ run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (keepFailed && ((error) => keepFailed(job, error))) }),
273
+ async tick(at = now()) {
274
+ const jobs = due(at);
275
+ if (!jobs.length) return [];
276
+ if (enqueue) {
277
+ if (!database) throw new Error("[logic-sdk] Crons through a jobs adapter that stores them (like databaseQueue(database)) need `database`.");
278
+ await database.transaction((tx) => enqueue(tx, jobs));
279
+ }
280
+ await deliver(jobs);
281
+ return jobs.map((job) => job.cron);
282
+ },
283
+ async sweep(options) {
284
+ const queued: Job[] = [];
285
+ const result = (await jobsAdapter.sweep?.(runnerInto(queued), options)) ?? { done: 0, failed: 0, discarded: 0, retrying: 0 };
286
+ await deliver(queued);
287
+ return result;
288
+ },
289
+ async retry(id) {
290
+ 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.`);
291
+ return jobsAdapter.retry(id);
292
+ },
293
+ };
294
+
295
+ return { toJobs, deliver, jobs, due, checkHold };
296
+ }
package/src/node.ts ADDED
@@ -0,0 +1,99 @@
1
+ import type { Jobs } from "./index.ts";
2
+
3
+ export interface TickingOptions {
4
+ /** Seconds between sweeps: databaseQueue's retries, delayed jobs and what a crash left behind. Default 60; 0 turns it off. */
5
+ sweepEvery?: number;
6
+ /** Where a failed tick or sweep goes, and a skipped minute. Default `console.error`. */
7
+ onError?: (error: unknown) => void;
8
+ }
9
+
10
+ export interface StopOptions {
11
+ /** Seconds to wait for the running ticks and sweeps before giving up on them. Default 30, like pg-boss's `stop()`. */
12
+ timeout?: number;
13
+ }
14
+
15
+ const MINUTE = 60_000;
16
+ /**
17
+ * Ticks, and sweeps, still running before the next of its kind is skipped (reported). Overlap is normal, like Laravel and
18
+ * Oban: a slow cron doesn't hold back the next minute, and a hung job doesn't stop the sweeps, as it wouldn't stop the
19
+ * other workers of a queue. Ten still running means they're stuck (the database is unreachable), and letting them pile
20
+ * up would run a backlog of stale minutes when it comes back.
21
+ */
22
+ const MAX_RUNNING = 10;
23
+
24
+ /**
25
+ * A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
26
+ * every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
27
+ * minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
28
+ * which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
29
+ *
30
+ * ```ts
31
+ * import { startTicking } from "logic-sdk/node";
32
+ * const stop = startTicking(registry);
33
+ * process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
34
+ * ```
35
+ */
36
+ export function startTicking(
37
+ registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
38
+ options: TickingOptions = {},
39
+ ): (options?: StopOptions) => Promise<void> {
40
+ const sweepEvery = options.sweepEvery ?? 60;
41
+ const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
42
+ const onError = (error: unknown) => {
43
+ try {
44
+ reportTo(error);
45
+ } catch (inner) {
46
+ console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
47
+ }
48
+ };
49
+ let tickTimer: ReturnType<typeof setTimeout> | undefined;
50
+ let sweepTimer: ReturnType<typeof setTimeout> | undefined;
51
+ const ticks = new Set<Promise<void>>();
52
+ const sweeps = new Set<Promise<void>>();
53
+
54
+ const startOfMinute = (ms: number) => Math.floor(ms / MINUTE) * MINUTE;
55
+
56
+ const track = (running: Set<Promise<void>>, work: Promise<unknown>) => {
57
+ const run = work.then(() => {}, onError);
58
+ running.add(run);
59
+ void run.finally(() => running.delete(run));
60
+ };
61
+
62
+ const tick = (at: Date) => {
63
+ if (ticks.size >= MAX_RUNNING) {
64
+ onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
65
+ return;
66
+ }
67
+ track(ticks, registry.jobs.tick(at));
68
+ };
69
+
70
+ const armTick = (minute: number) => {
71
+ tickTimer = setTimeout(() => {
72
+ // early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
73
+ const due = Math.max(minute, startOfMinute(Date.now()));
74
+ armTick(due + MINUTE); // the next one first, so a slow tick can't delay it
75
+ tick(new Date(due));
76
+ }, minute - Date.now());
77
+ };
78
+
79
+ const sweep = () => {
80
+ sweepTimer = setTimeout(sweep, sweepEvery * 1000); // the next one first, so a hung job can't stop the sweeps
81
+ if (sweeps.size >= MAX_RUNNING) {
82
+ onError(new Error(`[logic-sdk] skipped a sweep: ${sweeps.size} earlier sweeps are still running. Is a job hung, or the database unreachable?`));
83
+ return;
84
+ }
85
+ track(sweeps, registry.jobs.sweep());
86
+ };
87
+
88
+ armTick(startOfMinute(Date.now()) + MINUTE);
89
+ if (sweepEvery > 0) sweepTimer = setTimeout(sweep, sweepEvery * 1000);
90
+
91
+ return async ({ timeout = 30 } = {}) => {
92
+ clearTimeout(tickTimer);
93
+ clearTimeout(sweepTimer);
94
+ let timer: ReturnType<typeof setTimeout> | undefined;
95
+ const gaveUp = new Promise<void>((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
96
+ await Promise.race([Promise.all([...ticks, ...sweeps]), gaveUp]);
97
+ clearTimeout(timer);
98
+ };
99
+ }
package/src/orpc.ts CHANGED
@@ -1,23 +1,16 @@
1
- import { ORPCError, os, type Procedure } from "@orpc/server";
1
+ import { ORPCError, os, type DecoratedProcedure } from "@orpc/server";
2
2
  import type { StandardSchemaV1 } from "@standard-schema/spec";
3
- import { isDomainError, type Caller, type ErrorKind, type Fn, type Registry } from "./index.ts";
3
+ import { isDomainError, type Caller, type ErrorKind, type Fn, type Kind, type PublishableFn, type ScopeOfFn } from "./index.ts";
4
4
 
5
- /** oRPC context the router expects: bind who is calling per request, in your handler or middleware. */
5
+ /** oRPC context a procedure expects: bind who is calling per request, in your handler or middleware. */
6
6
  export type ORPCContext<S extends object> = { caller: Caller<S> };
7
7
 
8
- type ProcedureOf<S extends object, F> =
9
- F extends Fn<any, infer I, infer O, true>
10
- ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}>
8
+ /** `toORPCProcedure(fn)`: an oRPC procedure, so `.use`, `.meta` and `.errors` work as on your own. */
9
+ export type ProcedureOf<F> =
10
+ F extends Fn<Kind, infer I, infer O>
11
+ ? DecoratedProcedure<ORPCContext<ScopeOfFn<F>>, object, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}>
11
12
  : never;
12
13
 
13
- /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose: true`. */
14
- export type ORPCRouterOf<S extends object, Mods> = {
15
- [M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
16
- [N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
17
- };
18
- };
19
- type ExposedOf<T> = { [N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N] };
20
-
21
14
  /** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
22
15
  export const orpcCodeOf: Record<ErrorKind, string> = {
23
16
  invalid: "BAD_REQUEST",
@@ -29,37 +22,25 @@ export const orpcCodeOf: Record<ErrorKind, string> = {
29
22
  };
30
23
 
31
24
  /**
32
- * Turn the registry into an oRPC router. Your modules stay the core; oRPC is the edge that gives you
33
- * a typed client, OpenAPI and MCP. Validation runs once, in the registry.
25
+ * One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
26
+ * own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
34
27
  *
35
28
  * ```ts
36
- * const router = toORPCRouter(registry);
37
- * const handler = new RPCHandler(router);
38
- * handler.handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
29
+ * export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
30
+ * new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
39
31
  * ```
40
32
  */
41
- export function toORPCRouter<S extends object, Mods extends Record<string, object>>(
42
- registry: Registry<S, Mods>,
43
- ): ORPCRouterOf<S, Mods> {
44
- const base = os.$context<ORPCContext<S>>().$config({ disableInputValidation: true, disableOutputValidation: true });
45
- const router: Record<string, Record<string, unknown>> = {};
46
-
47
- for (const f of registry.functions) {
48
- if (!f.exposed) continue;
49
- let b = base.input(f.fn.inputSchema as StandardSchemaV1);
50
- if (f.fn.outputSchema) b = b.output(f.fn.outputSchema as StandardSchemaV1) as any;
51
- (router[f.module] ??= {})[f.name] = b.handler(async ({ input, context, signal }) => {
52
- try {
53
- return await context.caller.run(f.fn, input, { signal });
54
- } catch (e) {
55
- if (isDomainError(e))
56
- throw new ORPCError(orpcCodeOf[e.kind], {
57
- message: e.code,
58
- data: { kind: e.kind, code: e.code, details: e.details },
59
- });
60
- throw e;
61
- }
62
- });
63
- }
64
- return router as ORPCRouterOf<S, Mods>;
33
+ export function toORPCProcedure<F extends PublishableFn>(fn: F): ProcedureOf<F> {
34
+ if (!fn.authorize) throw new Error("[logic-sdk] toORPCProcedure publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
35
+ const base = os.$context<ORPCContext<object>>().$config({ disableInputValidation: true, disableOutputValidation: true });
36
+ const withInput = fn.input ? base.input(fn.input) : base;
37
+ const b = fn.output ? withInput.output(fn.output) : withInput;
38
+ return b.handler(async ({ input, context, signal }) => {
39
+ try {
40
+ return await context.caller.run(fn, input, { signal });
41
+ } catch (e) {
42
+ if (isDomainError(e)) throw new ORPCError(orpcCodeOf[e.kind], { message: e.code, data: { kind: e.kind, code: e.code, details: e.details } });
43
+ throw e;
44
+ }
45
+ }) as ProcedureOf<F>; // SAFETY: the same procedure, typed from the function: its input, output and init's scope
65
46
  }