logic-sdk 0.4.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.
- package/README.md +39 -13
- package/dist/ai.d.ts +16 -26
- package/dist/ai.js +8 -21
- package/dist/cloudflare.d.ts +55 -0
- package/dist/cloudflare.js +85 -0
- package/dist/drizzle/pg.d.ts +237 -0
- package/dist/drizzle/pg.js +67 -0
- package/dist/drizzle/sqlite.d.ts +242 -0
- package/dist/drizzle/sqlite.js +194 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +45 -0
- package/dist/fetch.d.ts +15 -18
- package/dist/fetch.js +18 -55
- package/dist/index.d.ts +75 -379
- package/dist/index.js +228 -181
- package/dist/jobs.d.ts +44 -0
- package/dist/jobs.js +252 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +76 -0
- package/dist/orpc.d.ts +10 -17
- package/dist/orpc.js +19 -28
- package/dist/pg-boss.d.ts +55 -0
- package/dist/pg-boss.js +211 -0
- package/dist/postgres.d.ts +28 -0
- package/dist/postgres.js +82 -0
- package/dist/schedule.d.ts +23 -0
- package/dist/schedule.js +109 -0
- package/dist/sqlite.d.ts +9 -0
- package/dist/sqlite.js +65 -0
- package/dist/stored-jobs.d.ts +64 -0
- package/dist/stored-jobs.js +188 -0
- package/dist/testing.d.ts +50 -14
- package/dist/testing.js +198 -46
- package/dist/types.d.ts +653 -0
- package/dist/types.js +6 -0
- package/package.json +45 -7
- package/skills/logic-sdk/SKILL.md +114 -0
- package/src/ai.ts +23 -46
- package/src/cloudflare.ts +107 -0
- package/src/drizzle/pg.ts +111 -0
- package/src/drizzle/sqlite.ts +236 -0
- package/src/errors.ts +59 -0
- package/src/fetch.ts +17 -65
- package/src/index.ts +384 -558
- package/src/jobs.ts +296 -0
- package/src/node.ts +99 -0
- package/src/orpc.ts +24 -42
- package/src/pg-boss.ts +242 -0
- package/src/postgres.ts +90 -0
- package/src/schedule.ts +129 -0
- package/src/sqlite.ts +74 -0
- package/src/stored-jobs.ts +260 -0
- package/src/testing.ts +252 -55
- package/src/types.ts +683 -0
- package/dist/drizzle.d.ts +0 -18
- package/dist/drizzle.js +0 -23
- package/src/drizzle.ts +0 -39
package/dist/fetch.js
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
import {
|
|
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
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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,327 +1,12 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
type
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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 = unknown, O = unknown, E extends boolean = boolean> {
|
|
54
|
-
readonly [BRAND]: K;
|
|
55
|
-
readonly kind: K;
|
|
56
|
-
readonly description: string;
|
|
57
|
-
/** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
|
|
58
|
-
readonly input?: Schema;
|
|
59
|
-
/** What callers get back, checked before it leaves. */
|
|
60
|
-
readonly output?: Schema;
|
|
61
|
-
/** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
|
|
62
|
-
readonly meta?: Readonly<Record<string, unknown>>;
|
|
63
|
-
/** Who may call it (from `authorize`). Runs on every call, before validation. */
|
|
64
|
-
readonly authorize?: Policy<never>;
|
|
65
|
-
/** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `output`. */
|
|
66
|
-
readonly expose?: true;
|
|
67
|
-
readonly handler: (ctx: never, input: never) => Promise<unknown>;
|
|
68
|
-
/** Phantom types, never set at runtime. */
|
|
69
|
-
readonly [types]?: {
|
|
70
|
-
input: I;
|
|
71
|
-
output: O;
|
|
72
|
-
exposed: E;
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
/** The exposed functions of one module: what adapters publish. */
|
|
76
|
-
export type ExposedOf<T> = {
|
|
77
|
-
[N in keyof T as T[N] extends Fn<Kind, unknown, unknown, true> ? N : never]: T[N];
|
|
78
|
-
};
|
|
79
|
-
/** A function with `expose: true`: adapters may publish it. */
|
|
80
|
-
export type ExposedFn<K extends Kind = Kind, I = unknown, O = unknown> = Fn<K, I, O, true>;
|
|
81
|
-
/** What callers pass to a function. */
|
|
82
|
-
export type FnIn<F> = F extends Fn<Kind, infer I, unknown> ? I : never;
|
|
83
|
-
/** What a function returns. */
|
|
84
|
-
export type FnOut<F> = F extends Fn<Kind, unknown, infer O> ? O : never;
|
|
85
|
-
/** `I`: what `emit` takes. `O`: what listeners receive (after the payload schema's transforms and defaults). */
|
|
86
|
-
export interface EventDef<I = unknown, O = I> {
|
|
87
|
-
readonly [BRAND]: "event";
|
|
88
|
-
readonly kind: "event";
|
|
89
|
-
/** The payload's schema, checked when emitted and again at delivery. */
|
|
90
|
-
readonly payload: Schema;
|
|
91
|
-
readonly description?: string;
|
|
92
|
-
readonly [types]?: {
|
|
93
|
-
input: I;
|
|
94
|
-
payload: O;
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
|
|
99
|
-
* and listeners get it parsed again by the event's payload schema at delivery.
|
|
100
|
-
*/
|
|
101
|
-
export interface Envelope<P = unknown, S = object> {
|
|
102
|
-
id: string;
|
|
103
|
-
name: string;
|
|
104
|
-
payload: P;
|
|
105
|
-
scope: S;
|
|
106
|
-
occurredAt: string;
|
|
107
|
-
}
|
|
108
|
-
export interface Listener<O = unknown> {
|
|
109
|
-
readonly [BRAND]: "listener";
|
|
110
|
-
readonly kind: "listener";
|
|
111
|
-
/** Lazy, so listeners can import other modules' barrels without import cycles. */
|
|
112
|
-
readonly event: () => EventDef<unknown, O>;
|
|
113
|
-
readonly description?: string;
|
|
114
|
-
readonly handler: (ctx: never, payload: O) => Promise<unknown>;
|
|
115
|
-
}
|
|
116
|
-
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
117
|
-
export interface RunOptions<S = object> {
|
|
118
|
-
/**
|
|
119
|
-
* Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
|
|
120
|
-
* someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
|
|
121
|
-
*/
|
|
122
|
-
scope?: Partial<S>;
|
|
123
|
-
/**
|
|
124
|
-
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
125
|
-
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|
|
126
|
-
*/
|
|
127
|
-
signal?: AbortSignal;
|
|
128
|
-
}
|
|
129
|
-
/** `run(fn, input, options?)`, or `run(fn)` for a function that takes no input. */
|
|
130
|
-
export type RunArgs<F, S> = undefined extends FnIn<F> ? [input?: FnIn<F>, options?: RunOptions<S>] : [input: FnIn<F>, options?: RunOptions<S>];
|
|
131
|
-
type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, ...args: RunArgs<F, S>) => Promise<FnOut<F>>;
|
|
132
|
-
/**
|
|
133
|
-
* Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
|
|
134
|
-
* code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
|
|
135
|
-
*/
|
|
136
|
-
export interface Errors {
|
|
137
|
-
/** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
|
|
138
|
-
reject(code: string, details?: unknown): DomainError;
|
|
139
|
-
/** Someone else got there first, or it already exists. Refreshing and retrying may work. */
|
|
140
|
-
conflict(code: string, details?: unknown): DomainError;
|
|
141
|
-
/** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
|
|
142
|
-
notFound(code?: string, details?: unknown): DomainError;
|
|
143
|
-
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
|
|
144
|
-
deny(code?: string, details?: unknown): DomainError;
|
|
145
|
-
}
|
|
146
|
-
interface BaseCtx<C extends Config, S> {
|
|
147
|
-
scope: S;
|
|
148
|
-
/** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
|
|
149
|
-
config: Frozen<ConfigOf<C>>;
|
|
150
|
-
/** Expected failures: `throw ctx.errors.reject("not_pending")`. */
|
|
151
|
-
errors: Errors;
|
|
152
|
-
/** Current time. Fixed in tests. */
|
|
153
|
-
now: () => Date;
|
|
154
|
-
}
|
|
155
|
-
/** `S` is the scope, narrowed by the function's policy. Alias it next to `init`: `type QueryCtx = QueryCtx<Config>`. */
|
|
156
|
-
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
157
|
-
db: ReaderOf<C>;
|
|
158
|
-
/** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
|
|
159
|
-
run: Run<"query", ScopeOf<C>>;
|
|
160
|
-
}
|
|
161
|
-
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
162
|
-
db: DbOf<C>;
|
|
163
|
-
/**
|
|
164
|
-
* Call a query or mutation inside this same transaction, with its policy and validation:
|
|
165
|
-
* `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
|
|
166
|
-
*/
|
|
167
|
-
run: Run<"query" | "mutation", ScopeOf<C>>;
|
|
168
|
-
/** Queue an event. Delivered to listeners only after the transaction commits. */
|
|
169
|
-
emit<I>(event: EventDef<I, unknown>, payload: I): void;
|
|
170
|
-
}
|
|
171
|
-
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
172
|
-
services: ServicesOf<C>;
|
|
173
|
-
/** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
|
|
174
|
-
run: Run<Kind, ScopeOf<C>>;
|
|
175
|
-
/** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
|
|
176
|
-
signal: AbortSignal | undefined;
|
|
177
|
-
}
|
|
178
|
-
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
179
|
-
event: Envelope<unknown, ScopeOf<C>> & {
|
|
180
|
-
payload: O;
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
|
|
185
|
-
* Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `handler`.
|
|
186
|
-
* Rules about one record ("only the owner may cancel") go in `handler`, after loading it.
|
|
187
|
-
*/
|
|
188
|
-
export type Policy<S> = (scope: S) => boolean;
|
|
189
|
-
type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
|
|
190
|
-
type CtxOf<C extends Config, K extends Kind, S> = K extends "query" ? QueryCtx<C, S> : K extends "mutation" ? MutationCtx<C, S> : ActionCtx<C, S>;
|
|
191
|
-
/** What a function without `input` gets: nothing. */
|
|
192
|
-
type NoInput = StandardSchemaV1<undefined, undefined>;
|
|
193
|
-
type Def<IS extends Schema, Ctx, R> = {
|
|
194
|
-
/** One sentence, shown to humans, adapters and AI tools. */
|
|
195
|
-
description: string;
|
|
196
|
-
/** What callers pass, validated on every call. Leave it out when the function takes nothing. */
|
|
197
|
-
input?: IS;
|
|
198
|
-
handler: (ctx: Ctx, input: Out<IS>) => Promise<R>;
|
|
199
|
-
};
|
|
200
|
-
type NotExposed = {
|
|
201
|
-
expose?: undefined;
|
|
202
|
-
};
|
|
203
|
-
type NoPolicy = {
|
|
204
|
-
authorize?: undefined;
|
|
205
|
-
};
|
|
206
|
-
type WithMeta<C extends Config> = {
|
|
207
|
-
meta?: MetaOf<C>;
|
|
208
|
-
};
|
|
209
|
-
type WithOutput<OS extends Schema> = {
|
|
210
|
-
output: OS;
|
|
211
|
-
};
|
|
212
|
-
/**
|
|
213
|
-
* `expose: true` needs `authorize` and `output`: you can't publish something without saying who may call it,
|
|
214
|
-
* and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
|
|
215
|
-
*/
|
|
216
|
-
interface Constructor<C extends Config, K extends Kind> {
|
|
217
|
-
<IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
|
|
218
|
-
authorize: P;
|
|
219
|
-
expose: true;
|
|
220
|
-
}): Fn<K, In<IS>, Out<OS>, true>;
|
|
221
|
-
<IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
|
|
222
|
-
authorize: P;
|
|
223
|
-
} & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
|
|
224
|
-
<IS extends Schema = NoInput, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & {
|
|
225
|
-
authorize: P;
|
|
226
|
-
} & NotExposed): Fn<K, In<IS>, R, false>;
|
|
227
|
-
<IS extends Schema = NoInput, OS extends Schema = Schema>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
|
|
228
|
-
<IS extends Schema = NoInput, R = unknown>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
|
|
229
|
-
}
|
|
230
|
-
export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
|
|
231
|
-
/**
|
|
232
|
-
* An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
|
|
233
|
-
* adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
|
|
234
|
-
* bugs) is unexpected: adapters answer 500 and report it.
|
|
235
|
-
*/
|
|
236
|
-
export declare class DomainError extends Error {
|
|
237
|
-
readonly kind: ErrorKind;
|
|
238
|
-
readonly code: string;
|
|
239
|
-
readonly details: unknown;
|
|
240
|
-
constructor(kind: ErrorKind, code: string, details?: unknown);
|
|
241
|
-
}
|
|
242
|
-
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
243
|
-
export declare const isDomainError: (e: unknown, code?: string) => e is DomainError;
|
|
244
|
-
export interface DatabaseAdapter<Db = unknown, Tx = Db> {
|
|
245
|
-
/** Root handle, used by top-level queries. */
|
|
246
|
-
readonly db: Db;
|
|
247
|
-
readonly transactions: "interactive";
|
|
248
|
-
transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
|
|
249
|
-
/** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
|
|
250
|
-
nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
|
|
251
|
-
/** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
|
|
252
|
-
retryable?(error: unknown): boolean;
|
|
253
|
-
}
|
|
254
|
-
export interface Dispatcher {
|
|
255
|
-
/** Inside the transaction, before commit. In-process: nothing. Outbox: insert rows with `tx`. */
|
|
256
|
-
enqueue?(tx: unknown, envelopes: Envelope[]): Promise<void>;
|
|
257
|
-
/** After commit. `dispatch` runs the listeners for one envelope and never throws (failures go to `onError`). */
|
|
258
|
-
deliver(envelopes: Envelope[], dispatch: (envelope: Envelope) => Promise<void>): Promise<void>;
|
|
259
|
-
}
|
|
260
|
-
/** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
|
|
261
|
-
export declare const inProcess: () => Dispatcher;
|
|
262
|
-
export interface Call<M = unknown> {
|
|
263
|
-
id: string;
|
|
264
|
-
kind: Kind | "listener";
|
|
265
|
-
/** The function's `meta` (undefined for listeners and functions without it). */
|
|
266
|
-
meta: M | undefined;
|
|
267
|
-
/** Raw input as received (before validation). */
|
|
268
|
-
input: unknown;
|
|
269
|
-
scope: object;
|
|
270
|
-
depth: number;
|
|
271
|
-
}
|
|
272
|
-
export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
273
|
-
/** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
|
|
274
|
-
modules: Mods;
|
|
275
|
-
database?: DatabaseAdapter<unknown, unknown>;
|
|
276
|
-
services?: object;
|
|
277
|
-
/** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
|
|
278
|
-
config?: object;
|
|
279
|
-
events?: Dispatcher;
|
|
280
|
-
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
281
|
-
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
282
|
-
/**
|
|
283
|
-
* Serverless: let listeners finish after the response. Pass the platform's global:
|
|
284
|
-
* `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
|
|
285
|
-
* Without it, `run` waits for listeners, which is what tests and long-lived servers want.
|
|
286
|
-
*/
|
|
287
|
-
waitUntil?: (promise: Promise<unknown>) => void;
|
|
288
|
-
/** Failures after commit land here (listeners, dispatcher). They never fail the caller. */
|
|
289
|
-
onError?: (error: unknown, info: {
|
|
290
|
-
listener: string;
|
|
291
|
-
envelope: Envelope | undefined;
|
|
292
|
-
}) => void;
|
|
293
|
-
now?: () => Date;
|
|
294
|
-
/** Max chain of listener → mutation → event → listener… before delivery stops. Default 8 (real chains are 2 or 3). */
|
|
295
|
-
maxEventDepth?: number;
|
|
296
|
-
/**
|
|
297
|
-
* Re-run a top-level mutation in a fresh transaction when the database says it lost a race (deadlock,
|
|
298
|
-
* serialization failure). Safe because mutations have no side effects and events are rebuilt per attempt.
|
|
299
|
-
* Default 3 attempts in total; `{ attempts: 1 }` turns it off.
|
|
300
|
-
*/
|
|
301
|
-
retry?: {
|
|
302
|
-
attempts?: number;
|
|
303
|
-
};
|
|
304
|
-
}
|
|
305
|
-
/** A registry bound to who is calling: `const caller = registry.as(scope)`. */
|
|
306
|
-
export interface Caller<S extends object = object> {
|
|
307
|
-
readonly scope: S;
|
|
308
|
-
/** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
|
|
309
|
-
run<F extends Fn>(fn: F, ...args: RunArgs<F, S>): Promise<FnOut<F>>;
|
|
310
|
-
}
|
|
311
|
-
export interface Registered {
|
|
312
|
-
id: string;
|
|
313
|
-
module: string;
|
|
314
|
-
name: string;
|
|
315
|
-
}
|
|
316
|
-
export interface RegisteredFn extends Registered {
|
|
317
|
-
fn: Fn;
|
|
318
|
-
kind: Kind;
|
|
319
|
-
/** Has `expose: true`: adapters may publish it. */
|
|
320
|
-
exposed: boolean;
|
|
321
|
-
}
|
|
322
|
-
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>;
|
|
323
8
|
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
324
|
-
wrap?: (call: Call<
|
|
9
|
+
wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
|
|
325
10
|
} & ({} extends ServicesOf<C> ? {
|
|
326
11
|
services?: ServicesOf<C>;
|
|
327
12
|
} : {
|
|
@@ -334,7 +19,9 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
|
|
|
334
19
|
database?: undefined;
|
|
335
20
|
} : {
|
|
336
21
|
database: DatabaseAdapter<unknown, DbOf<C>>;
|
|
337
|
-
})
|
|
22
|
+
}) & {
|
|
23
|
+
modules: OwnModules<C, Mods>;
|
|
24
|
+
};
|
|
338
25
|
/** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
|
|
339
26
|
type OnlyKnownKeys<C> = {
|
|
340
27
|
[K in Exclude<keyof C, keyof Config>]: never;
|
|
@@ -343,12 +30,12 @@ type OnlyKnownKeys<C> = {
|
|
|
343
30
|
* Typed constructors for your app:
|
|
344
31
|
*
|
|
345
32
|
* ```ts
|
|
346
|
-
* export const { query, mutation, action, event,
|
|
33
|
+
* export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
|
|
347
34
|
* ```
|
|
348
35
|
*/
|
|
349
36
|
export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
350
37
|
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
351
|
-
createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) => Registry<ScopeOf<C>, Mods, ConfigOf<C>>;
|
|
38
|
+
createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) => Registry<ScopeOf<C>, Mods, ConfigOf<C>>;
|
|
352
39
|
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
353
40
|
query: Constructor<C, "query">;
|
|
354
41
|
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
@@ -357,69 +44,78 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
357
44
|
action: Constructor<C, "action">;
|
|
358
45
|
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
359
46
|
event: <S extends Schema>(def: {
|
|
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;
|
|
360
52
|
payload: S;
|
|
361
|
-
description?: string;
|
|
362
53
|
}) => EventDef<In<S>, Out<S>>;
|
|
363
|
-
/**
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
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>;
|
|
367
89
|
};
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
export interface Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
|
|
388
|
-
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
389
|
-
readonly modules: Mods;
|
|
390
|
-
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
391
|
-
as(scope: S): Caller<S>;
|
|
392
|
-
/** Everything the registry can do. Adapters read this. */
|
|
393
|
-
readonly functions: readonly RegisteredFn[];
|
|
394
|
-
readonly events: readonly RegisteredEvent[];
|
|
395
|
-
readonly listeners: readonly RegisteredListener[];
|
|
396
|
-
/** `"bookings.confirm"` for a registered function or event. Throws for anything unregistered. */
|
|
397
|
-
idOf(fnOrEvent: object): string;
|
|
398
|
-
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
399
|
-
dispatch(envelope: Envelope): Promise<void>;
|
|
400
|
-
/** @internal used by `logic-sdk/testing` */
|
|
401
|
-
readonly [INTERNAL]: {
|
|
402
|
-
options: RegistryOptions<Mods>;
|
|
403
|
-
config: Frozen<Cf>;
|
|
404
|
-
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
405
|
-
};
|
|
406
|
-
}
|
|
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
|
+
});
|
|
407
109
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
408
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>;
|
|
409
111
|
/**
|
|
410
|
-
* What `createRegistry` finds in your modules, without a database or services: every function, event and
|
|
411
|
-
*
|
|
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.
|
|
412
114
|
*/
|
|
413
115
|
export declare function describeModules(modules: Record<string, object>): {
|
|
414
116
|
ids: Map<object, string>;
|
|
415
117
|
functions: RegisteredFn[];
|
|
416
118
|
events: RegisteredEvent[];
|
|
417
119
|
listeners: RegisteredListener[];
|
|
120
|
+
crons: RegisteredCron[];
|
|
418
121
|
};
|
|
419
|
-
/** @internal */
|
|
420
|
-
export declare const internal: <S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>) => {
|
|
421
|
-
options: RegistryOptions<Mods>;
|
|
422
|
-
config: Frozen<Cf>;
|
|
423
|
-
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
424
|
-
};
|
|
425
|
-
export {};
|