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/dist/fetch.js CHANGED
@@ -1,9 +1,4 @@
1
- import { DomainError, isDomainError } from "./index.js";
2
- /**
3
- * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
4
- * For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
5
- */
6
- export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
1
+ import { isDomainError } from "./index.js";
7
2
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
8
3
  export const statusOf = {
9
4
  invalid: 400,
@@ -13,55 +8,23 @@ export const statusOf = {
13
8
  conflict: 409,
14
9
  rejected: 422,
15
10
  };
16
- const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
17
11
  /**
18
- * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
19
- * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
20
- * queries also accept GET `?input=<json>`.
12
+ * A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
13
+ * (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
14
+ * and logs it, and its message never reaches the client.
15
+ *
16
+ * ```ts
17
+ * app.post("/orders", async (c) => {
18
+ * try {
19
+ * return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
20
+ * } catch (e) {
21
+ * return toResponse(e);
22
+ * }
23
+ * });
24
+ * ```
21
25
  */
22
- export function toFetchHandler(registry, options) {
23
- const base = (options.basePath ?? "/").replace(/\/?$/, "/");
24
- const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
25
- const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));
26
- return async (request, ...rest) => {
27
- const path = new URL(request.url).pathname;
28
- if (!path.startsWith(base))
29
- return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
30
- const id = path.slice(base.length);
31
- const entry = exposed.get(id);
32
- if (!entry)
33
- return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
34
- let input;
35
- try {
36
- if (request.method === "POST") {
37
- // JSON only: blocks cross-site "simple" form posts (CSRF) because they can't send this content type without a preflight
38
- if (!(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json"))
39
- return json({ error: { kind: "invalid", code: "unsupported_media_type" } }, 415);
40
- const text = await request.text();
41
- input = text ? JSON.parse(text) : undefined;
42
- }
43
- else if (request.method === "GET" && entry.kind === "query") {
44
- const raw = new URL(request.url).searchParams.get("input");
45
- input = raw ? JSON.parse(raw) : undefined;
46
- }
47
- else {
48
- const res = json({ error: { kind: "invalid", code: "method_not_allowed" } }, 405);
49
- res.headers.set("allow", entry.kind === "query" ? "GET, POST" : "POST");
50
- return res;
51
- }
52
- }
53
- catch {
54
- return json({ error: { kind: "invalid", code: "malformed_json" } }, 400);
55
- }
56
- try {
57
- const scope = await options.resolveScope(request, ...rest);
58
- return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
59
- }
60
- catch (e) {
61
- if (isDomainError(e))
62
- return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
63
- onError(e);
64
- return json({ error: { kind: "internal", code: "internal_error" } }, 500);
65
- }
66
- };
26
+ export function toResponse(error) {
27
+ if (!isDomainError(error))
28
+ throw error;
29
+ return Response.json({ error: { kind: error.kind, code: error.code, details: error.details } }, { status: statusOf[error.kind] });
67
30
  }
package/dist/index.d.ts CHANGED
@@ -1,315 +1,12 @@
1
- import type { StandardSchemaV1 } from "@standard-schema/spec";
2
- type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
3
- type In<S> = S extends Schema<infer I, any> ? I : never;
4
- type Out<S> = S extends Schema<any, infer O> ? O : never;
5
- /** What you declare once in `init<...>()`. */
6
- export interface Config {
7
- /** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
8
- scope: object;
9
- /** The transaction handle mutations receive (e.g. a Drizzle transaction). */
10
- db?: unknown;
11
- /** What queries receive. Defaults to `db`. Use a read-only type (e.g. `DrizzleReader<Tx>`). */
12
- reader?: unknown;
13
- /** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
14
- services?: object;
15
- /**
16
- * Your app's settings, read as `ctx.config` in every function: base URL, limits, switches. Plain data, read-only.
17
- * Build it once from your env at the entry; clients built from secrets go in `services` instead.
18
- */
19
- config?: object;
20
- /** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
21
- meta?: object;
22
- }
23
- type ScopeOf<C extends Config> = C["scope"];
24
- type DbOf<C extends Config> = C extends {
25
- db: infer D;
26
- } ? D : never;
27
- type ReaderOf<C extends Config> = C extends {
28
- reader: infer R;
29
- } ? R : DbOf<C>;
30
- type ServicesOf<C extends Config> = C extends {
31
- services: infer S;
32
- } ? S : {};
33
- type MetaOf<C extends Config> = C extends {
34
- meta: infer M;
35
- } ? M : never;
36
- /** Without a declared `config`, nothing may be passed or read: no silently ignored settings. */
37
- type ConfigOf<C extends Config> = C extends {
38
- config: infer F;
39
- } ? F : Record<string, never>;
40
- type Primitive = string | number | boolean | bigint | symbol | null | undefined;
41
- /** Read-only all the way down: what `ctx.config` gives you. Primitives (branded ones too) stay as they are. */
42
- export type Frozen<T> = T extends Primitive ? T : T extends readonly (infer U)[] ? readonly Frozen<U>[] : {
43
- readonly [K in keyof T]: Frozen<T[K]>;
44
- };
45
- /** Any part of `T`, at any depth: what a test may override in `config`. Arrays are replaced whole, like at runtime. */
46
- export type DeepPartial<T> = T extends Primitive | readonly unknown[] ? T : {
47
- [K in keyof T]?: DeepPartial<T[K]>;
48
- };
49
- export type Kind = "query" | "mutation" | "action";
50
- declare const types: unique symbol;
51
- declare const BRAND: unique symbol;
52
- /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
53
- export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean = boolean> {
54
- readonly [BRAND]: K;
55
- readonly kind: K;
56
- readonly description: string;
57
- readonly inputSchema: Schema;
58
- readonly outputSchema?: Schema;
59
- /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
60
- readonly meta?: any;
61
- /** Who may call it (from `authorize`). Runs on every call, before validation. */
62
- readonly authorize?: Policy<any>;
63
- /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
64
- readonly expose?: true;
65
- readonly execute: (input: any, ctx: any) => Promise<any>;
66
- /** Phantom types, never set at runtime. */
67
- readonly [types]?: {
68
- input: I;
69
- output: O;
70
- exposed: E;
71
- };
72
- }
73
- /** A function with `expose: true`: adapters may publish it. */
74
- export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
75
- /** What callers pass to a function. */
76
- export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
77
- /** What a function returns. */
78
- export type FnOut<F> = F extends Fn<any, any, infer O> ? O : never;
79
- /** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
80
- export interface EventDef<I = any, O = I> {
81
- readonly [BRAND]: "event";
82
- readonly kind: "event";
83
- readonly schema: Schema;
84
- readonly description?: string;
85
- readonly [types]?: {
86
- input: I;
87
- payload: O;
88
- };
89
- }
90
- /**
91
- * What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
92
- * and listeners get it parsed again by the event's schema at delivery.
93
- */
94
- export interface Envelope<P = unknown, S = object> {
95
- id: string;
96
- name: string;
97
- payload: P;
98
- scope: S;
99
- occurredAt: string;
100
- }
101
- export interface Listener<O = any> {
102
- readonly [BRAND]: "listener";
103
- readonly kind: "listener";
104
- /** Lazy, so listeners can import other modules' barrels without import cycles. */
105
- readonly event: () => EventDef<any, O>;
106
- readonly description?: string;
107
- readonly execute: (payload: O, ctx: any) => Promise<unknown>;
108
- }
109
- /** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
110
- export interface RunOptions<S = object> {
111
- /**
112
- * Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
113
- * someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
114
- */
115
- scope?: Partial<S>;
116
- /**
117
- * Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
118
- * Never checked between your steps, so a caller who gives up can't leave a workflow half done.
119
- */
120
- signal?: AbortSignal;
121
- }
122
- type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>, options?: RunOptions<S>) => Promise<FnOut<F>>;
123
- /**
124
- * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
125
- * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
126
- */
127
- export interface Errors {
128
- /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
129
- reject(code: string, details?: unknown): DomainError;
130
- /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
131
- conflict(code: string, details?: unknown): DomainError;
132
- /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
133
- notFound(code?: string, details?: unknown): DomainError;
134
- /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
135
- deny(code?: string, details?: unknown): DomainError;
136
- }
137
- interface BaseCtx<C extends Config, S> {
138
- scope: S;
139
- /** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
140
- config: Frozen<ConfigOf<C>>;
141
- /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
142
- errors: Errors;
143
- /** Current time. Fixed in tests. */
144
- now: () => Date;
145
- }
146
- /** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
147
- export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
148
- db: ReaderOf<C>;
149
- /** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
150
- run: Run<"query", ScopeOf<C>>;
151
- }
152
- export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
153
- db: DbOf<C>;
154
- /**
155
- * Call a query or mutation inside this same transaction, with its policy and validation:
156
- * `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
157
- */
158
- run: Run<"query" | "mutation", ScopeOf<C>>;
159
- /** Queue an event. Delivered to listeners only after the transaction commits. */
160
- emit<I>(event: EventDef<I, any>, payload: I): void;
161
- }
162
- export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
163
- services: ServicesOf<C>;
164
- /** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
165
- run: Run<Kind, ScopeOf<C>>;
166
- /** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
167
- signal: AbortSignal | undefined;
168
- }
169
- export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
170
- event: Envelope<unknown, ScopeOf<C>> & {
171
- payload: O;
172
- };
173
- }
174
- /**
175
- * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
176
- * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
177
- * Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
178
- */
179
- export type Policy<S> = (scope: S) => boolean;
180
- type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
181
- type CtxOf<C extends Config, K extends Kind, S> = K extends "query" ? QueryCtx<C, S> : K extends "mutation" ? MutationCtx<C, S> : ActionCtx<C, S>;
182
- type Def<IS extends Schema, Ctx, R> = {
183
- /** One sentence, shown to humans, adapters and AI tools. */
184
- description: string;
185
- inputSchema: IS;
186
- execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
187
- };
188
- type NotExposed = {
189
- expose?: undefined;
190
- };
191
- type NoPolicy = {
192
- authorize?: undefined;
193
- };
194
- type WithMeta<C extends Config> = {
195
- meta?: MetaOf<C>;
196
- };
197
- type WithOutput<OS extends Schema> = {
198
- outputSchema: OS;
199
- };
200
- /**
201
- * `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
202
- * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
203
- */
204
- interface Constructor<C extends Config, K extends Kind> {
205
- <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
206
- authorize: P;
207
- expose: true;
208
- }): Fn<K, In<IS>, Out<OS>, true>;
209
- <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
210
- authorize: P;
211
- } & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
212
- <IS extends Schema, R, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & {
213
- authorize: P;
214
- } & NotExposed): Fn<K, In<IS>, R, false>;
215
- <IS extends Schema, OS extends Schema>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
216
- <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
217
- }
218
- export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
219
- /**
220
- * An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
221
- * adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
222
- * bugs) is unexpected: adapters answer 500 and report it.
223
- */
224
- export declare class DomainError extends Error {
225
- readonly kind: ErrorKind;
226
- readonly code: string;
227
- readonly details: unknown;
228
- constructor(kind: ErrorKind, code: string, details?: unknown);
229
- }
230
- /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
231
- export declare const isDomainError: (e: unknown, code?: string) => e is DomainError;
232
- export interface DatabaseAdapter<Db = unknown, Tx = Db> {
233
- /** Root handle, used by top-level queries. */
234
- readonly db: Db;
235
- readonly transactions: "interactive";
236
- transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
237
- /** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
238
- nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
239
- /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
240
- retryable?(error: unknown): boolean;
241
- }
242
- export interface Dispatcher {
243
- /** Inside the transaction, before commit. In-process: nothing. Outbox: insert rows with `tx`. */
244
- enqueue?(tx: unknown, envelopes: Envelope[]): Promise<void>;
245
- /** After commit. `dispatch` runs the listeners for one envelope and never throws (failures go to `onError`). */
246
- deliver(envelopes: Envelope[], dispatch: (envelope: Envelope) => Promise<void>): Promise<void>;
247
- }
248
- /** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
249
- export declare const inProcess: () => Dispatcher;
250
- export interface Call<M = unknown> {
251
- id: string;
252
- kind: Kind | "listener";
253
- /** The function's `meta` (undefined for listeners and functions without it). */
254
- meta: M | undefined;
255
- /** Raw input as received (before validation). */
256
- input: unknown;
257
- scope: object;
258
- depth: number;
259
- }
260
- export interface RegistryOptions<Mods extends Record<string, object>> {
261
- /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
262
- modules: Mods;
263
- database?: DatabaseAdapter<any, any>;
264
- services?: object;
265
- /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
266
- config?: object;
267
- events?: Dispatcher;
268
- /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
269
- wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
270
- /**
271
- * Serverless: let listeners finish after the response. Pass the platform's global:
272
- * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
273
- * Without it, `run` waits for listeners, which is what tests and long-lived servers want.
274
- */
275
- waitUntil?: (promise: Promise<unknown>) => void;
276
- /** Failures after commit land here (listeners, dispatcher). They never fail the caller. */
277
- onError?: (error: unknown, info: {
278
- listener: string;
279
- envelope: Envelope | undefined;
280
- }) => void;
281
- now?: () => Date;
282
- /** Max chain of listener → mutation → event → listener… before delivery stops. Default 8 (real chains are 2 or 3). */
283
- maxEventDepth?: number;
284
- /**
285
- * Re-run a top-level mutation in a fresh transaction when the database says it lost a race (deadlock,
286
- * serialization failure). Safe because mutations have no side effects and events are rebuilt per attempt.
287
- * Default 3 attempts in total; `{ attempts: 1 }` turns it off.
288
- */
289
- retry?: {
290
- attempts?: number;
291
- };
292
- }
293
- /** A registry bound to who is calling: `const caller = registry.as(scope)`. */
294
- export interface Caller<S extends object = object> {
295
- readonly scope: S;
296
- /** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
297
- run<F extends Fn>(fn: F, input: FnIn<F>, options?: RunOptions<S>): Promise<FnOut<F>>;
298
- }
299
- export interface Registered {
300
- id: string;
301
- module: string;
302
- name: string;
303
- }
304
- export interface RegisteredFn extends Registered {
305
- fn: Fn;
306
- kind: Kind;
307
- /** Has `expose: true`: adapters may publish it. */
308
- exposed: boolean;
309
- }
310
- type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<RegistryOptions<Mods>, "wrap"> & {
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";
3
+ export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./errors.ts";
4
+ export { inProcess, replaceKeyOf } from "./jobs.ts";
5
+ type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
6
+ /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
7
+ jobs?: JobsOptions<ScopeOf<C>, T>;
311
8
  /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
312
- wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
9
+ wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
313
10
  } & ({} extends ServicesOf<C> ? {
314
11
  services?: ServicesOf<C>;
315
12
  } : {
@@ -321,8 +18,10 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
321
18
  }) & ([DbOf<C>] extends [never] ? {
322
19
  database?: undefined;
323
20
  } : {
324
- database: DatabaseAdapter<any, DbOf<C>>;
325
- });
21
+ database: DatabaseAdapter<unknown, DbOf<C>>;
22
+ }) & {
23
+ modules: OwnModules<C, Mods>;
24
+ };
326
25
  /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
327
26
  type OnlyKnownKeys<C> = {
328
27
  [K in Exclude<keyof C, keyof Config>]: never;
@@ -331,36 +30,12 @@ type OnlyKnownKeys<C> = {
331
30
  * Typed constructors for your app:
332
31
  *
333
32
  * ```ts
334
- * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
33
+ * export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
335
34
  * ```
336
35
  */
337
36
  export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
338
37
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
339
- createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) => {
340
- /** The modules you registered (typed), for adapters that build typed routers. */
341
- modules: Mods;
342
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
343
- as: (scope: ScopeOf<C>) => Caller<ScopeOf<C>>;
344
- /** Everything the registry can do. Adapters read this. */
345
- functions: readonly RegisteredFn[];
346
- events: readonly (Registered & {
347
- event: EventDef;
348
- })[];
349
- listeners: readonly (Registered & {
350
- listener: Listener;
351
- event: EventDef;
352
- })[];
353
- idOf: (x: object) => string;
354
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
355
- dispatch: (envelope: Envelope) => Promise<void>;
356
- /** @internal used by `logic-sdk/testing` */
357
- [INTERNAL]: {
358
- options: RegistryOptions<Mods>;
359
- overrides: Overrides;
360
- config: Frozen<ConfigOf<C>>;
361
- derive: (more: Overrides) => /*elided*/ any;
362
- };
363
- };
38
+ createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) => Registry<ScopeOf<C>, Mods, ConfigOf<C>>;
364
39
  /** Reads data. Can run other queries. No writes, no events, no services. */
365
40
  query: Constructor<C, "query">;
366
41
  /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
@@ -369,116 +44,78 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
369
44
  action: Constructor<C, "action">;
370
45
  /** Something that happened. Emitted by mutations, delivered after commit. */
371
46
  event: <S extends Schema>(def: {
372
- schema: S;
373
- description?: string;
47
+ /**
48
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
49
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
50
+ */
51
+ id?: string;
52
+ payload: S;
374
53
  }) => EventDef<In<S>, Out<S>>;
375
- /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
376
- on: <O>(event: () => EventDef<any, O>, execute: (payload: O, ctx: ListenerCtx<C, O>) => Promise<unknown>, opts?: {
377
- description?: string;
378
- }) => Listener<O>;
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 })`.
58
+ */
59
+ cron: <F extends Fn>(def: CronDef<ScopeOf<C>, F>) => Cron<C>;
60
+ /**
61
+ * React to an event after commit, like an action. Must be idempotent.
62
+ * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
63
+ */
64
+ listener: <O>(def: {
65
+ /**
66
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
67
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
68
+ */
69
+ id?: string;
70
+ /** The event it reacts to, as a thunk so modules can import each other's barrels without cycles. */
71
+ event: () => EventDef<unknown, O>;
72
+ /**
73
+ * Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
74
+ * Once they're used, the job is `failed` (kept by `databaseQueue`, `outbox` and pg-boss, retried with `registry.jobs.retry(id)`).
75
+ */
76
+ attempts?: number;
77
+ /** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
78
+ delay?: number;
79
+ /**
80
+ * Whether this event gets a job for this listener, like Laravel's `shouldQueue($event)`: false, and nothing is
81
+ * stored, run or counted. From the payload the handler gets (parsed), at commit, so sync and from the event only:
82
+ * a condition on the database belongs in the handler, since it can change before the job runs. A throw fails the
83
+ * mutation, as a bad payload does.
84
+ */
85
+ when?: (payload: O) => boolean;
86
+ meta?: ListenerMetaOf<C>;
87
+ handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
88
+ }) => Listener<O, C>;
379
89
  };
380
- declare const INTERNAL: unique symbol;
381
- export interface Overrides {
382
- database?: DatabaseAdapter<any, any>;
383
- services?: object;
384
- /** Merged over the registry's config, section by section. */
385
- config?: object;
386
- events?: Dispatcher;
387
- now?: () => Date;
388
- stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
389
- record?: (envelope: Envelope) => void;
390
- }
391
- export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> = ReturnType<typeof build<S, Mods, Cf>>;
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. */
93
+ id?: string;
94
+ /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * 1"`. */
95
+ schedule: string;
96
+ /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
97
+ timezone?: string;
98
+ /** Any query, mutation or action: it runs with its policy, validation and tracing. */
99
+ run: F;
100
+ /** Who it runs as: a cron has no caller. */
101
+ scope: S;
102
+ /** Tries in total, like a listener's. Default 1. */
103
+ attempts?: number;
104
+ } & (undefined extends FnIn<F> ? {
105
+ input?: FnIn<F>;
106
+ } : {
107
+ input: FnIn<F>;
108
+ });
392
109
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
393
- export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): {
394
- /** The modules you registered (typed), for adapters that build typed routers. */
395
- modules: Mods;
396
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
397
- as: (scope: S) => Caller<S>;
398
- /** Everything the registry can do. Adapters read this. */
399
- functions: readonly RegisteredFn[];
400
- events: readonly (Registered & {
401
- event: EventDef;
402
- })[];
403
- listeners: readonly (Registered & {
404
- listener: Listener;
405
- event: EventDef;
406
- })[];
407
- idOf: (x: object) => string;
408
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
409
- dispatch: (envelope: Envelope) => Promise<void>;
410
- /** @internal used by `logic-sdk/testing` */
411
- [INTERNAL]: {
412
- options: RegistryOptions<Mods>;
413
- overrides: Overrides;
414
- config: {};
415
- derive: (more: Overrides) => /*elided*/ any;
416
- };
417
- };
110
+ export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): Registry<S, Mods, unknown>;
418
111
  /**
419
- * What `createRegistry` finds in your modules, without a database or services: every function, event and
420
- * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
112
+ * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
113
+ * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
421
114
  */
422
115
  export declare function describeModules(modules: Record<string, object>): {
423
116
  ids: Map<object, string>;
424
117
  functions: RegisteredFn[];
425
- events: (Registered & {
426
- event: EventDef;
427
- })[];
428
- listeners: (Registered & {
429
- listener: Listener;
430
- event: EventDef;
431
- })[];
432
- };
433
- declare function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(options: RegistryOptions<Mods>, o: Overrides): {
434
- /** The modules you registered (typed), for adapters that build typed routers. */
435
- modules: Mods;
436
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
437
- as: (scope: S) => Caller<S>;
438
- /** Everything the registry can do. Adapters read this. */
439
- functions: readonly RegisteredFn[];
440
- events: readonly (Registered & {
441
- event: EventDef;
442
- })[];
443
- listeners: readonly (Registered & {
444
- listener: Listener;
445
- event: EventDef;
446
- })[];
447
- idOf: (x: object) => string;
448
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
449
- dispatch: (envelope: Envelope) => Promise<void>;
450
- /** @internal used by `logic-sdk/testing` */
451
- [INTERNAL]: {
452
- options: RegistryOptions<Mods>;
453
- overrides: Overrides;
454
- config: Frozen<Cf>;
455
- derive: (more: Overrides) => /*elided*/ any;
456
- };
457
- };
458
- /** @internal */
459
- export declare const internal: (registry: Registry<any, any, any>) => {
460
- options: RegistryOptions<any>;
461
- overrides: Overrides;
462
- config: any;
463
- derive: (more: Overrides) => {
464
- /** The modules you registered (typed), for adapters that build typed routers. */
465
- modules: any;
466
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
467
- as: (scope: any) => Caller<any>;
468
- /** Everything the registry can do. Adapters read this. */
469
- functions: readonly RegisteredFn[];
470
- events: readonly (Registered & {
471
- event: EventDef;
472
- })[];
473
- listeners: readonly (Registered & {
474
- listener: Listener;
475
- event: EventDef;
476
- })[];
477
- idOf: (x: object) => string;
478
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
479
- dispatch: (envelope: Envelope) => Promise<void>;
480
- /** @internal used by `logic-sdk/testing` */
481
- [INTERNAL]: /*elided*/ any;
482
- };
118
+ events: RegisteredEvent[];
119
+ listeners: RegisteredListener[];
120
+ crons: RegisteredCron[];
483
121
  };
484
- export {};