logic-sdk 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +40 -15
  2. package/bin/logic-sdk.js +1 -1
  3. package/dist/ai.d.ts +16 -26
  4. package/dist/ai.js +8 -21
  5. package/dist/cloudflare.d.ts +55 -0
  6. package/dist/cloudflare.js +85 -0
  7. package/dist/drizzle/pg.d.ts +236 -0
  8. package/dist/drizzle/pg.js +67 -0
  9. package/dist/drizzle/sqlite.d.ts +242 -0
  10. package/dist/drizzle/sqlite.js +194 -0
  11. package/dist/errors.d.ts +33 -0
  12. package/dist/errors.js +45 -0
  13. package/dist/fetch.d.ts +15 -18
  14. package/dist/fetch.js +18 -55
  15. package/dist/index.d.ts +78 -379
  16. package/dist/index.js +240 -186
  17. package/dist/jobs.d.ts +44 -0
  18. package/dist/jobs.js +252 -0
  19. package/dist/node.d.ts +26 -0
  20. package/dist/node.js +76 -0
  21. package/dist/orpc.d.ts +10 -17
  22. package/dist/orpc.js +19 -28
  23. package/dist/pg-boss.d.ts +55 -0
  24. package/dist/pg-boss.js +211 -0
  25. package/dist/postgres.d.ts +28 -0
  26. package/dist/postgres.js +82 -0
  27. package/dist/schedule.d.ts +23 -0
  28. package/dist/schedule.js +109 -0
  29. package/dist/sqlite.d.ts +9 -0
  30. package/dist/sqlite.js +65 -0
  31. package/dist/stored-jobs.d.ts +64 -0
  32. package/dist/stored-jobs.js +188 -0
  33. package/dist/testing.d.ts +50 -14
  34. package/dist/testing.js +198 -46
  35. package/dist/types.d.ts +655 -0
  36. package/dist/types.js +6 -0
  37. package/package.json +45 -7
  38. package/skills/logic-sdk/SKILL.md +114 -0
  39. package/src/ai.ts +23 -46
  40. package/src/cloudflare.ts +107 -0
  41. package/src/drizzle/pg.ts +110 -0
  42. package/src/drizzle/sqlite.ts +236 -0
  43. package/src/errors.ts +59 -0
  44. package/src/fetch.ts +17 -65
  45. package/src/index.ts +404 -564
  46. package/src/jobs.ts +296 -0
  47. package/src/node.ts +99 -0
  48. package/src/orpc.ts +24 -42
  49. package/src/pg-boss.ts +242 -0
  50. package/src/postgres.ts +90 -0
  51. package/src/schedule.ts +129 -0
  52. package/src/sqlite.ts +74 -0
  53. package/src/stored-jobs.ts +260 -0
  54. package/src/testing.ts +252 -55
  55. package/src/types.ts +685 -0
  56. package/dist/drizzle.d.ts +0 -18
  57. package/dist/drizzle.js +0 -23
  58. package/src/drizzle.ts +0 -39
@@ -0,0 +1,655 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { DomainError } from "./errors.ts";
3
+ export type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
4
+ export type In<S> = S extends StandardSchemaV1<infer I, unknown> ? I : never;
5
+ export type Out<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
6
+ /** What you declare once in `init<...>()`. */
7
+ export interface Config {
8
+ /** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
9
+ scope: object;
10
+ /**
11
+ * Your database's type: `DrizzleDb<Db>`, or your own `ReadWrite<Reader, Tx>`. Queries get the reader, mutations the
12
+ * transaction. A plain type is what both get.
13
+ */
14
+ db?: unknown;
15
+ /** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
16
+ services?: object;
17
+ /**
18
+ * Your app's settings, read as `ctx.config` in every function: base URL, limits, switches. Plain data, read-only.
19
+ * Build it once from your env at the entry; clients built from secrets go in `services` instead.
20
+ */
21
+ config?: object;
22
+ /**
23
+ * The shape of `meta`: yours, plus what your adapters read (`AppMeta & AIMeta & PgBossMeta`). Yours goes on functions
24
+ * and listeners, each adapter's only where it reads it.
25
+ */
26
+ meta?: object;
27
+ }
28
+ export type ScopeOf<C extends Config> = C["scope"];
29
+ declare const READ_WRITE: unique symbol;
30
+ /** A database type with two sides: what queries get and what mutations get. `DrizzleDb<Db>` is one. Type only. */
31
+ export interface ReadWrite<Reader, Tx> {
32
+ readonly [READ_WRITE]: {
33
+ reader: Reader;
34
+ tx: Tx;
35
+ };
36
+ }
37
+ /** Says what's missing from the setup, where `never` would say nothing. */
38
+ interface SetupError<Message extends string> {
39
+ readonly setupError: Message;
40
+ }
41
+ type NoDb = SetupError<"Add db to the Config you pass to init">;
42
+ /** What mutations get, and `database`'s transaction type. `never`: the app declared no database. */
43
+ export type DbOf<C extends Config> = C extends {
44
+ db: infer D;
45
+ } ? (D extends ReadWrite<any, infer Tx> ? Tx : D) : never;
46
+ type ReaderOf<C extends Config> = C extends {
47
+ db: infer D;
48
+ } ? (D extends ReadWrite<infer Reader, any> ? Reader : D) : NoDb;
49
+ type TxOf<C extends Config> = C extends {
50
+ db: unknown;
51
+ } ? DbOf<C> : NoDb;
52
+ export type ServicesOf<C extends Config> = C extends {
53
+ services: infer S;
54
+ } ? S : {};
55
+ type MetaOf<C extends Config> = C extends {
56
+ meta: infer M;
57
+ } ? M : never;
58
+ declare const FOR_FUNCTIONS: unique symbol;
59
+ declare const FOR_LISTENERS: unique symbol;
60
+ /** An adapter's part of `meta`, read on queries, mutations and actions: `type AIMeta = ForFunctions<{ ai?: ... }>`. */
61
+ export interface ForFunctions<M> {
62
+ readonly [FOR_FUNCTIONS]?: M;
63
+ }
64
+ /** An adapter's part of `meta`, read on listeners: `type PgBossMeta = ForListeners<{ pgBoss?: ... }>`. */
65
+ export interface ForListeners<M> {
66
+ readonly [FOR_LISTENERS]?: M;
67
+ }
68
+ type AppPart<M> = {
69
+ [P in keyof M as P extends symbol ? never : P]: M[P];
70
+ };
71
+ type AdapterPart<M, S extends symbol> = S extends keyof M ? NonNullable<M[S]> : {};
72
+ /** `never` when nothing is left, or `{}` would take any object. */
73
+ type NeverIfEmpty<M> = keyof M extends never ? never : M;
74
+ /** A query, mutation or action's `meta`. */
75
+ export type FunctionMetaOf<C extends Config, M = MetaOf<C>> = M extends unknown ? NeverIfEmpty<AppPart<M> & AdapterPart<M, typeof FOR_FUNCTIONS>> : never;
76
+ /** A listener's `meta`. */
77
+ export type ListenerMetaOf<C extends Config, M = MetaOf<C>> = M extends unknown ? NeverIfEmpty<AppPart<M> & AdapterPart<M, typeof FOR_LISTENERS>> : never;
78
+ /** What `wrap` sees: it runs for both. */
79
+ export type CallMetaOf<C extends Config, M = MetaOf<C>> = M extends unknown ? NeverIfEmpty<AppPart<M> & AdapterPart<M, typeof FOR_FUNCTIONS> & AdapterPart<M, typeof FOR_LISTENERS>> : never;
80
+ /** Without a declared `config`, nothing may be passed or read: no silently ignored settings. */
81
+ export type ConfigOf<C extends Config> = C extends {
82
+ config: infer F;
83
+ } ? F : Record<string, never>;
84
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined;
85
+ /** Read-only all the way down: what `ctx.config` gives you. Primitives (branded ones too) stay as they are. */
86
+ export type Frozen<T> = T extends Primitive ? T : T extends readonly (infer U)[] ? readonly Frozen<U>[] : {
87
+ readonly [K in keyof T]: Frozen<T[K]>;
88
+ };
89
+ /** Any part of `T`, at any depth: what a test may override in `config`. Arrays are replaced whole, like at runtime. */
90
+ export type DeepPartial<T> = T extends Primitive | readonly unknown[] ? T : {
91
+ [K in keyof T]?: DeepPartial<T[K]>;
92
+ };
93
+ export type Kind = "query" | "mutation" | "action";
94
+ declare const types: unique symbol;
95
+ /** Brands every definer's result, so `createRegistry` finds them among a module's exports. */
96
+ export declare const BRAND: unique symbol;
97
+ /** Which `init` defined it, as a phantom type: `createRegistry` refuses another init's (`any` when the type was erased, as in a bare `Fn`). */
98
+ type FromInit<C extends Config> = {
99
+ readonly [types]?: {
100
+ init: (config: C) => void;
101
+ };
102
+ };
103
+ /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
104
+ export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any> {
105
+ readonly [BRAND]: K;
106
+ readonly kind: K;
107
+ /** Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name. */
108
+ readonly id?: string;
109
+ /** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
110
+ readonly input?: Schema;
111
+ /** What callers get back, checked before it leaves. */
112
+ readonly output?: Schema;
113
+ /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
114
+ readonly meta?: Readonly<Record<string, unknown>>;
115
+ /** Who may call it (from `authorize`). Runs on every call, before validation. */
116
+ readonly authorize?: Policy<never>;
117
+ readonly handler: (ctx: never, input: never) => Promise<unknown>;
118
+ /** Phantom types, never set at runtime. `authorized`: it has an `authorize`, so adapters may publish it. */
119
+ readonly [types]?: {
120
+ input: I;
121
+ output: O;
122
+ authorized: A;
123
+ init: (config: C) => void;
124
+ };
125
+ }
126
+ /**
127
+ * A function that says who may call it (`authorize`), so an adapter may publish it: `toORPCProcedure(fn)`,
128
+ * `toAITool(caller, fn)`. Everyone is a decision too: `authorize: anyone`, with `const anyone = () => true`.
129
+ */
130
+ export type PublishableFn<K extends Kind = Kind, I = unknown, O = unknown, C extends Config = any> = Fn<K, I, O, true, C>;
131
+ /** The scope of the `init` that defined `F`: what a caller running it must be bound to. */
132
+ export type ScopeOfFn<F> = F extends Fn<Kind, unknown, unknown, true, infer C> ? ScopeOf<C> : object;
133
+ /** What callers pass to a function. */
134
+ export type FnIn<F> = F extends Fn<Kind, infer I, unknown> ? I : never;
135
+ /** What a function returns. */
136
+ export type FnOut<F> = F extends Fn<Kind, unknown, infer O> ? O : never;
137
+ /** `I`: what `emit` takes. `O`: what listeners receive (after the payload schema's transforms and defaults). */
138
+ export interface EventDef<I = unknown, O = I> {
139
+ readonly [BRAND]: "event";
140
+ readonly kind: "event";
141
+ /** Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name. */
142
+ readonly id?: string;
143
+ /** The payload's schema, checked when emitted and again at delivery. */
144
+ readonly payload: Schema;
145
+ readonly [types]?: {
146
+ input: I;
147
+ payload: O;
148
+ };
149
+ }
150
+ /**
151
+ * What a jobs adapter stores and delivers. Fully JSON: `payload` is what was emitted (validated),
152
+ * and listeners get it parsed again by the event's payload schema at delivery.
153
+ */
154
+ export interface Envelope {
155
+ id: string;
156
+ name: string;
157
+ payload: unknown;
158
+ scope: object;
159
+ occurredAt: string;
160
+ /** Hops in the chain: 1 for an event a caller's mutation emitted, +1 each time a listener's mutation emits (or a call it schedules to run now). */
161
+ depth: number;
162
+ }
163
+ /**
164
+ * One listener's share of one event: what a queue carries, one message each, so a failing listener retries alone.
165
+ * `id` (`<listener id>@<event id>`) is the key to dedupe on.
166
+ */
167
+ export interface Delivery {
168
+ /** What kind of job this is. Stored with it, so jobs queued today still run when other kinds exist. */
169
+ kind: "delivery";
170
+ id: string;
171
+ /** The listener's id, `"<module>.<id or export>"`. */
172
+ listener: string;
173
+ envelope: Envelope;
174
+ /** Tries in total, stamped when it's queued, like Laravel's `maxTries` and Oban's `max_attempts`: a deploy that changes them applies to jobs queued after it. */
175
+ attempts: number;
176
+ /** When it may run (ISO), for a listener with a `delay`. Absent: right away. */
177
+ runAt?: string;
178
+ }
179
+ /** One run of a cron: `id` is `<cron id>@<minute>` (`reports.weekly@20261123T0900Z`), so a tick runs once. */
180
+ export interface CronJob {
181
+ kind: "cron";
182
+ id: string;
183
+ /** The cron's id, `"<module>.<id or export>"`. */
184
+ cron: string;
185
+ /** The minute it was due (ISO). */
186
+ scheduledAt: string;
187
+ /** Tries in total, stamped when it's queued, like Laravel's `maxTries` and Oban's `max_attempts`: a deploy that changes them applies to jobs queued after it. */
188
+ attempts: number;
189
+ /** When it may run (ISO), like a delivery's. Absent for crons: they run when ticked. */
190
+ runAt?: string;
191
+ }
192
+ /** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`, returned by `ctx.schedule`. */
193
+ export interface CallJob {
194
+ kind: "call";
195
+ id: string;
196
+ /** The function's id, `"<module>.<id or export>"`. */
197
+ fn: string;
198
+ input: unknown;
199
+ /** Who it runs as, as `jobs.scope.store` saved it (`load` rebuilds it when it runs). */
200
+ scope: object;
201
+ /** Tries in total, stamped when it's queued, like Laravel's `maxTries` and Oban's `max_attempts`: a deploy that changes them applies to jobs queued after it. */
202
+ attempts: number;
203
+ /**
204
+ * Hops in the chain, counted with events' (`maxEventDepth`): a call due now continues the chain that scheduled it, so a
205
+ * function that schedules itself with no delay stops like a listener loop. A delayed one starts a new chain (0).
206
+ */
207
+ depth: number;
208
+ /** Its `replace` key: a newer call to `fn` with the same key replaces this one while it waits. */
209
+ replace?: string;
210
+ /** When it may run (ISO). */
211
+ runAt?: string;
212
+ }
213
+ /**
214
+ * One unit of background work, what `registry.jobs` runs, sweeps and retries: a listener's share of an event, a cron's
215
+ * run, or a call `ctx.schedule` asked for.
216
+ */
217
+ export type Job = Delivery | CronJob | CallJob;
218
+ /** A function to run on a schedule, as `scope`. Export it from a module, like listeners. */
219
+ export interface Cron<C extends Config = any> extends FromInit<C> {
220
+ readonly [BRAND]: "cron";
221
+ readonly kind: "cron";
222
+ readonly id?: string;
223
+ readonly schedule: string;
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
+ readonly scope: object;
229
+ readonly attempts?: number;
230
+ }
231
+ /**
232
+ * What running a job resolved to. `failed`: out of attempts (code this process doesn't have uses them too), a rule said
233
+ * no (`invalid`, `unauthenticated`, `forbidden`, `not_found`, `rejected`), or the payload no longer matches its schema.
234
+ * It's over, so acknowledge it; it's been reported.
235
+ * `discarded`: `jobs.scope.load` returned null (who it ran as is gone). Acknowledge it too; it's been reported.
236
+ */
237
+ export type JobOutcome = "done" | "failed" | "discarded";
238
+ /** The event a listener is handling. No scope here: `ctx.scope` is the one it runs as. */
239
+ export interface ListenerEvent<O = unknown> {
240
+ id: string;
241
+ name: string;
242
+ payload: O;
243
+ occurredAt: string;
244
+ /** 1 on the first try. Queues count their redeliveries. */
245
+ attempt: number;
246
+ }
247
+ export interface Listener<O = unknown, C extends Config = any> extends FromInit<C> {
248
+ readonly [BRAND]: "listener";
249
+ readonly kind: "listener";
250
+ /** Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name. */
251
+ readonly id?: string;
252
+ /** Lazy, so listeners can import other modules' barrels without import cycles. */
253
+ readonly event: () => EventDef<unknown, O>;
254
+ /** Tries in total, the first included. Default 1. */
255
+ readonly attempts?: number;
256
+ /** Seconds after the event before the first try. Default 0. */
257
+ readonly delay?: number;
258
+ /** Whether this event gets a job for this listener, from the parsed payload, at commit. Default: every event. */
259
+ readonly when?: (payload: O) => boolean;
260
+ readonly meta?: Readonly<Record<string, unknown>>;
261
+ readonly handler: (ctx: never, payload: O) => Promise<unknown>;
262
+ }
263
+ /** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
264
+ export interface RunOptions<S = object> {
265
+ /**
266
+ * Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
267
+ * someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
268
+ */
269
+ scope?: Partial<S>;
270
+ /**
271
+ * Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
272
+ * Never checked between your steps, so a caller who gives up can't leave a workflow half done.
273
+ */
274
+ signal?: AbortSignal;
275
+ }
276
+ /** `run(fn, input, options?)`, or `run(fn)` for a function that takes no input. */
277
+ export type RunArgs<F, S> = undefined extends FnIn<F> ? [input?: FnIn<F>, options?: RunOptions<S>] : [input: FnIn<F>, options?: RunOptions<S>];
278
+ type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, ...args: RunArgs<F, S>) => Promise<FnOut<F>>;
279
+ /**
280
+ * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
281
+ * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
282
+ */
283
+ export interface Errors {
284
+ /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
285
+ reject(code: string, details?: unknown): DomainError;
286
+ /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
287
+ conflict(code: string, details?: unknown): DomainError;
288
+ /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
289
+ notFound(code?: string, details?: unknown): DomainError;
290
+ /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
291
+ deny(code?: string, details?: unknown): DomainError;
292
+ }
293
+ interface BaseCtx<C extends Config, S> {
294
+ scope: S;
295
+ /** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
296
+ config: Frozen<ConfigOf<C>>;
297
+ /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
298
+ errors: Errors;
299
+ /** Current time. Fixed in tests. */
300
+ now: () => Date;
301
+ }
302
+ /** `S` is the scope, narrowed by the function's policy. Alias it next to `init`: `type QueryCtx = QueryCtx<Config>`. */
303
+ export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
304
+ db: ReaderOf<C>;
305
+ /** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
306
+ run: Run<"query", ScopeOf<C>>;
307
+ }
308
+ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
309
+ db: TxOf<C>;
310
+ /**
311
+ * Call a query or mutation inside this same transaction, with its policy and validation:
312
+ * `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
313
+ */
314
+ run: Run<"query" | "mutation", ScopeOf<C>>;
315
+ /** Queue an event. Delivered to listeners only after the transaction commits. */
316
+ emit<I>(event: EventDef<I, unknown>, payload: I): void;
317
+ /**
318
+ * Run a mutation or action once, later, as this scope: `ctx.schedule(guests.remind, { bookingId }, { at })` or
319
+ * `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind. Returns its job
320
+ * id. It runs whatever happens meanwhile, so it should check that its reason still holds ("still confirmed?").
321
+ * `attempts`: tries in total, default 1; give an action that calls an API a few. `replace`: a key, so a newer call
322
+ * with it replaces the one still waiting (`replace: booking.id` when the dates change), like Oban's `replace`.
323
+ */
324
+ schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions): string;
325
+ }
326
+ /** When a scheduled call runs (`at` or `delay` in seconds), and how many tries it gets. */
327
+ export type ScheduleOptions = ({
328
+ at: Date;
329
+ delay?: never;
330
+ } | {
331
+ delay: number;
332
+ at?: never;
333
+ }) & {
334
+ attempts?: number;
335
+ /** A key: the call to this function waiting with the same key (not started yet) is replaced by this one. */
336
+ replace?: string;
337
+ };
338
+ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
339
+ services: ServicesOf<C>;
340
+ /** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
341
+ run: Run<Kind, ScopeOf<C>>;
342
+ /** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
343
+ signal: AbortSignal | undefined;
344
+ }
345
+ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
346
+ event: ListenerEvent<O>;
347
+ }
348
+ /**
349
+ * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
350
+ * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `handler`.
351
+ * Rules about one record ("only the owner may cancel") go in `handler`, after loading it.
352
+ */
353
+ export type Policy<S> = (scope: S) => boolean;
354
+ type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
355
+ type CtxOf<C extends Config, K extends Kind, S> = K extends "query" ? QueryCtx<C, S> : K extends "mutation" ? MutationCtx<C, S> : ActionCtx<C, S>;
356
+ /** What a function without `input` gets: nothing. */
357
+ type NoInput = StandardSchemaV1<undefined, undefined>;
358
+ type Def<C extends Config, K extends Kind, IS, OS, R, P, A> = {
359
+ /**
360
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
361
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
362
+ */
363
+ id?: string;
364
+ /** What callers pass, validated on every call. Leave it out when the function takes nothing. */
365
+ input?: IS;
366
+ /**
367
+ * Who may call it, on every call. A type guard narrows `ctx.scope` in `handler`. Required to publish it through an
368
+ * adapter: callers outside your server are untrusted. Leave it out when only your own code runs it.
369
+ */
370
+ authorize?: P & ((scope: ScopeOf<C>) => A);
371
+ /**
372
+ * What callers get back, checked before it leaves: unknown fields are stripped, and a published function's client
373
+ * types come from it. Without it, the handler's return type, all of it.
374
+ */
375
+ output?: OS;
376
+ meta?: FunctionMetaOf<C>;
377
+ handler: (ctx: CtxOf<C, K, Guarded<P, ScopeOf<C>>>, input: Out<IS>) => Promise<[OS] extends [Schema] ? In<OS> : R>;
378
+ };
379
+ /**
380
+ * One signature, not overloads, so a mistake gets one error naming the missing field ("Property 'handler' is missing")
381
+ * instead of "No overload matches this call". Keep `output: OS` plain: `OS & Schema` makes TypeScript compare the whole
382
+ * schema type structurally on every definition (about 10x slower to check).
383
+ */
384
+ export type Constructor<C extends Config, K extends Kind> = <IS extends Schema = NoInput, OS extends Schema | undefined = undefined, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>, A extends boolean = never>(def: Def<C, K, IS, OS, R, P, A>) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C>;
385
+ type OtherInit = SetupError<"Defined with another init(), so it would run with this registry's scope, not its own. Define it with the init() this createRegistry came from">;
386
+ /** `createRegistry`'s modules: a function, listener or cron defined with another `init` is an error, since it would run with this one's scope. Events have no `init`. */
387
+ export type OwnModules<C extends Config, Mods> = {
388
+ [M in keyof Mods]: {
389
+ [N in keyof Mods[M]]: Mods[M][N] extends FromInit<never> ? (Mods[M][N] extends FromInit<C> ? Mods[M][N] : OtherInit) : Mods[M][N];
390
+ };
391
+ };
392
+ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
393
+ /** Root handle, used by top-level queries. */
394
+ readonly db: Db;
395
+ transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
396
+ /** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
397
+ nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
398
+ /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
399
+ retryable?(error: unknown): boolean;
400
+ /**
401
+ * Tries in total for a top-level mutation whose transaction is `retryable`, each in a fresh one, like Laravel's
402
+ * `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
403
+ */
404
+ transactionAttempts?: number;
405
+ /**
406
+ * One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves the rows it
407
+ * returns. `databaseQueue` and `outbox` run their table through it, so any ORM that can run SQL has them.
408
+ */
409
+ query?(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
410
+ }
411
+ /** A database adapter with `query`: what `databaseQueue(database)` and `outbox(database, queue)` take. */
412
+ export interface SqlDatabase<Db = any, Tx = any> extends DatabaseAdapter<Db, Tx> {
413
+ query(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
414
+ }
415
+ /** Runs one job: resolves when it's done or failed for good (acknowledge it), throws when a retry might help. */
416
+ export type RunJob = (job: Job, options?: RunJobOptions) => Promise<JobOutcome>;
417
+ export interface RunJobOptions {
418
+ /** 1 on the first try; the adapter counts. */
419
+ attempt?: number;
420
+ /**
421
+ * Called with the error when the job fails for good, before `run` resolves `"failed"`: keep it. Default: the adapter's
422
+ * `fail` (`databaseQueue` and `outbox` write a failed row).
423
+ */
424
+ fail?: (error: unknown) => Promise<void>;
425
+ }
426
+ /** What a sweep did: done, failed for good, discarded (`jobs.scope.load` returned null), or put back with a backoff. */
427
+ export interface SweepResult {
428
+ done: number;
429
+ failed: number;
430
+ discarded: number;
431
+ retrying: number;
432
+ }
433
+ /** What the registry hands an adapter: run a job here, or report a failure of the adapter's own (a send that failed). */
434
+ export interface Runner {
435
+ /** Every failure it meets is already reported to `onError`; a throw means "retry it". */
436
+ run: RunJob;
437
+ report(error: unknown, job: Job, attempt?: number): void;
438
+ }
439
+ export interface JobsAdapter {
440
+ /**
441
+ * It can hold a job until its `runAt` (a listener's `delay`, `ctx.schedule`): `true`, or for at most `max` seconds.
442
+ * Without it (`inProcess()`), `createRegistry` refuses delayed listeners and `ctx.schedule` throws, rather than run
443
+ * them early or lose them.
444
+ */
445
+ holds?: true | {
446
+ max: number;
447
+ };
448
+ /**
449
+ * Can replace a call waiting to run: `enqueue` gets a call with `replace`, and a pending call to the same `fn` with
450
+ * the same key that hasn't started is replaced by it. `databaseQueue` and `outbox` can; a queue that already has the message can't.
451
+ * Without it, `ctx.schedule` with `replace` is refused.
452
+ */
453
+ replaces?: true;
454
+ /** At `createRegistry`: refuse a setup this adapter can't honour (a database it doesn't share). */
455
+ check?(setup: {
456
+ listeners: readonly RegisteredListener[];
457
+ database: DatabaseAdapter<unknown, unknown> | undefined;
458
+ }): void;
459
+ /** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
460
+ enqueue?(tx: unknown, jobs: Job[]): Promise<void>;
461
+ /** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
462
+ deliver(jobs: Job[], runner: Runner): Promise<void>;
463
+ /** Run what's due (retries, deliveries whose runner crashed). Only adapters that store deliveries have it. */
464
+ sweep?(runner: Runner, options?: {
465
+ limit?: number;
466
+ }): Promise<SweepResult>;
467
+ /** Put a failed job back in line. `false` when there's no failed job with that id. Only adapters that store them. */
468
+ retry?(id: string): Promise<boolean>;
469
+ /**
470
+ * Keep a job that failed for good after it left the adapter: `registry.jobs.run` calls it from a queue consumer, so
471
+ * `outbox` stores the failure Cloudflare would otherwise drop. Not called for jobs the adapter ran itself.
472
+ */
473
+ fail?(job: Job, error: unknown): Promise<void>;
474
+ }
475
+ /**
476
+ * What `onError` gets with a failure after commit. `job`, `attempt` and `outcome` are set when a job failed: the job
477
+ * itself, like Laravel's `JobFailed` and Oban's exception telemetry.
478
+ */
479
+ export interface FailureInfo {
480
+ /** The listener, cron or scheduled function that failed, or the part of the registry (`"(jobs adapter)"`). */
481
+ source: string;
482
+ /** The job that failed, or that the adapter couldn't take (`"(jobs adapter)"`). */
483
+ job?: Job;
484
+ attempt?: number;
485
+ /** `retry`: tries are left and the adapter may run it again. `failed` and `discarded`: it's over. */
486
+ outcome?: "retry" | "failed" | "discarded";
487
+ }
488
+ /**
489
+ * Who a job runs as, at rest. `store` picks what's saved with the job (ids, not whole objects); `load` rebuilds the
490
+ * scope when it runs, so policies see today's roles. `load` returning null discards the job (reported to `onError`),
491
+ * a throw retries it. By default the scope is stored as it was at emit. `store` needs `load`: listeners run as a scope,
492
+ * not as what was saved. Every adapter but `inProcess()` keeps jobs to run later, so it needs `load`: `createRegistry` checks.
493
+ */
494
+ export interface JobScope<S = object, T = any> {
495
+ store?: (scope: S) => T;
496
+ /** What `store` saved. Write `store` first so TypeScript infers it (or annotate this parameter). */
497
+ load?: (stored: T) => S | null | Promise<S | null>;
498
+ }
499
+ /** Marks `inProcess()` for TypeScript: the one adapter that keeps no jobs, so needs no `jobs.scope`. */
500
+ export declare const RUNS_NOW: unique symbol;
501
+ /** What `inProcess()` returns. */
502
+ export interface InProcess extends JobsAdapter {
503
+ readonly [RUNS_NOW]: true;
504
+ }
505
+ /**
506
+ * `createRegistry({ jobs })`: where background work goes, and what every adapter applies. `load` inside `scope` is
507
+ * checked at startup: requiring it here would report a missing one as a wrong `store`.
508
+ */
509
+ export type JobsOptions<S = object, T = any> = {
510
+ /**
511
+ * Max chain of listener → mutation → event → listener… before queueing stops, reported. Calls `ctx.schedule` runs
512
+ * right away count too, so a function that schedules itself with no delay stops the same way. Default 8 (real chains
513
+ * are 2 or 3).
514
+ */
515
+ maxEventDepth?: number;
516
+ } & ({
517
+ /** `inProcess()` (default), or a durable one like `databaseQueue(database)`. Its own options go in its factory. */
518
+ adapter?: InProcess;
519
+ /** Applied by the registry in every adapter, `inProcess()` and tests included. */
520
+ scope?: JobScope<S, T>;
521
+ } | {
522
+ /** An adapter that keeps jobs to run later, like `databaseQueue(database)`. */
523
+ adapter?: JobsAdapter;
524
+ /** Required: such a job runs as the scope `load` rebuilds, with today's roles. */
525
+ scope: JobScope<S, T>;
526
+ });
527
+ export interface Call<M = unknown> {
528
+ id: string;
529
+ kind: Kind | "listener";
530
+ /** The function's or listener's `meta` (undefined when it has none). */
531
+ meta: M | undefined;
532
+ /** Raw input as received (before validation). */
533
+ input: unknown;
534
+ scope: object;
535
+ depth: number;
536
+ }
537
+ export interface RegistryOptions<Mods extends Record<string, object>> {
538
+ /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
539
+ modules: Mods;
540
+ database?: DatabaseAdapter<unknown, unknown>;
541
+ services?: object;
542
+ /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
543
+ config?: object;
544
+ /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
545
+ jobs?: JobsOptions;
546
+ /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
547
+ wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
548
+ /**
549
+ * Serverless: let listeners finish after the response. Pass the platform's global:
550
+ * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
551
+ * Without it, `run` waits for listeners. On a long-lived server with `databaseQueue`, `() => {}` answers first (a restart
552
+ * is swept up after its lease: retried, or failed when it was out of attempts); with `inProcess()`, don't: work
553
+ * still running at a restart is lost.
554
+ */
555
+ waitUntil?: (promise: Promise<unknown>) => void;
556
+ /** Failures no caller waits for: jobs, and the work after commit that runs them. They never fail the caller. */
557
+ onError?: (error: unknown, info: FailureInfo) => void;
558
+ now?: () => Date;
559
+ }
560
+ /** A registry bound to who is calling: `const caller = registry.as(scope)`. */
561
+ export interface Caller<S extends object = object> {
562
+ readonly scope: S;
563
+ /** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
564
+ run<F extends Fn>(fn: F, ...args: RunArgs<F, S>): Promise<FnOut<F>>;
565
+ }
566
+ export interface Registered {
567
+ id: string;
568
+ module: string;
569
+ name: string;
570
+ }
571
+ export interface RegisteredFn extends Registered {
572
+ fn: Fn;
573
+ kind: Kind;
574
+ }
575
+ export interface Overrides {
576
+ database?: DatabaseAdapter<unknown, unknown>;
577
+ services?: object;
578
+ /** Merged over the registry's config, section by section. */
579
+ config?: unknown;
580
+ adapter?: JobsAdapter;
581
+ now?: () => Date;
582
+ stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
583
+ record?: (envelope: Envelope) => void;
584
+ onError?: (error: unknown, info: FailureInfo) => void;
585
+ /** Present and undefined turns the registry's off. */
586
+ waitUntil?: (promise: Promise<unknown>) => void;
587
+ }
588
+ export interface RegisteredEvent extends Registered {
589
+ event: EventDef;
590
+ }
591
+ export interface RegisteredListener extends Registered {
592
+ listener: Listener;
593
+ event: EventDef;
594
+ }
595
+ export interface RegisteredCron extends Registered {
596
+ cron: Cron;
597
+ run: Fn;
598
+ }
599
+ /** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
600
+ export interface Jobs {
601
+ /**
602
+ * Run one stored job (queue consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
603
+ * Resolves `"done"`, `"failed"` or `"discarded"` (acknowledge all three); throws when a retry might help and the
604
+ * job has tries left. A `failed` job goes to `fail`: yours, or your adapter's (`databaseQueue` and `outbox` keep it).
605
+ */
606
+ run(job: Job, options?: RunJobOptions): Promise<JobOutcome>;
607
+ /**
608
+ * Run the crons due in `at`'s minute (default now), from a timer or your platform's cron trigger:
609
+ * `await registry.jobs.tick(new Date(controller.scheduledTime))`. Resolves the ids of the crons that were due. Each run
610
+ * goes through your jobs adapter, and with `databaseQueue` or `outbox` a minute that's ticked twice still runs each cron once.
611
+ */
612
+ tick(at?: Date): Promise<string[]>;
613
+ /**
614
+ * Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue(database)`, that's
615
+ * retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing, or maintain themselves
616
+ * (pg-boss), resolve zeros.
617
+ */
618
+ sweep(options?: {
619
+ limit?: number;
620
+ }): Promise<SweepResult>;
621
+ /**
622
+ * Put a failed job back in line with a fresh set of attempts. `false` when no failed job has that id (it's pending,
623
+ * running, done, or never existed). Throws when your adapter keeps no jobs, like `inProcess()`.
624
+ */
625
+ retry(id: string): Promise<boolean>;
626
+ }
627
+ /** What `createRegistry` returns. `Cf` is your config's type, so tests can override parts of it. */
628
+ export interface Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
629
+ /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
630
+ as(scope: S): Caller<S>;
631
+ /** Everything you registered, with ids. Adapters and plugins read this. */
632
+ readonly definitions: {
633
+ readonly functions: readonly RegisteredFn[];
634
+ readonly events: readonly RegisteredEvent[];
635
+ readonly listeners: readonly RegisteredListener[];
636
+ readonly crons: readonly RegisteredCron[];
637
+ };
638
+ /** `"bookings.confirm"` for a registered function or event. Throws for anything unregistered. */
639
+ idOf(fnOrEvent: object): string;
640
+ /** The background work your `jobs` adapter holds. */
641
+ readonly jobs: Jobs;
642
+ /** @internal used by `logic-sdk/testing` */
643
+ readonly [INTERNAL]: {
644
+ options: RegistryOptions<Mods>;
645
+ config: Frozen<Cf>;
646
+ derive(more: Overrides): Registry<S, Mods, Cf>;
647
+ /** An event as `emit` would make it, for `t.jobs.perform`. */
648
+ envelope(event: EventDef, payload: unknown, scope: S): Envelope;
649
+ /** The cron runs due in a minute, for `t.jobs.tick`. */
650
+ due(at: Date): CronJob[];
651
+ };
652
+ }
653
+ /** The registry's internals, for `logic-sdk/testing`. */
654
+ export declare const INTERNAL: unique symbol;
655
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /** Brands every definer's result, so `createRegistry` finds them among a module's exports. */
2
+ export const BRAND = Symbol.for("logic-sdk.brand");
3
+ /** Marks `inProcess()` for TypeScript: the one adapter that keeps no jobs, so needs no `jobs.scope`. */
4
+ export const RUNS_NOW = Symbol.for("logic-sdk.runsNow");
5
+ /** The registry's internals, for `logic-sdk/testing`. */
6
+ export const INTERNAL = Symbol.for("logic-sdk.internal");