logic-sdk 0.7.0 → 0.7.2
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 +9 -9
- package/dist/adapters/cloudflare-queue.d.ts +14 -0
- package/dist/adapters/cloudflare-queue.js +48 -0
- package/dist/adapters/drizzle-pg.d.ts +250 -0
- package/dist/adapters/drizzle-pg.js +69 -0
- package/dist/adapters/drizzle-sqlite.d.ts +257 -0
- package/dist/adapters/drizzle-sqlite.js +196 -0
- package/dist/adapters/pg-boss.d.ts +45 -0
- package/dist/adapters/pg-boss.js +180 -0
- package/dist/adapters/postgres.d.ts +32 -0
- package/dist/adapters/postgres.js +105 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +88 -0
- package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
- package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
- package/dist/ai.d.ts +1 -32
- package/dist/ai.js +1 -40
- package/dist/cloudflare.d.ts +2 -55
- package/dist/cloudflare.js +2 -85
- package/dist/core/in-process.d.ts +9 -0
- package/dist/core/in-process.js +17 -0
- package/dist/core/jobs.d.ts +57 -0
- package/dist/{jobs.js → core/jobs.js} +161 -42
- package/dist/core/registry.d.ts +120 -0
- package/dist/core/registry.js +503 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +230 -0
- package/dist/{types.d.ts → core/types.d.ts} +224 -49
- package/dist/drizzle/pg.d.ts +3 -236
- package/dist/drizzle/pg.js +2 -67
- package/dist/drizzle/sqlite.d.ts +3 -242
- package/dist/drizzle/sqlite.js +2 -194
- package/dist/fetch.d.ts +1 -19
- package/dist/fetch.js +1 -30
- package/dist/hosts/cloudflare.d.ts +42 -0
- package/dist/hosts/cloudflare.js +39 -0
- package/dist/hosts/node.d.ts +26 -0
- package/dist/hosts/node.js +76 -0
- package/dist/hosts/pg-boss.d.ts +22 -0
- package/dist/hosts/pg-boss.js +55 -0
- package/dist/index.d.ts +5 -124
- package/dist/index.js +4 -495
- package/dist/integrations/ai.d.ts +32 -0
- package/dist/integrations/ai.js +40 -0
- package/dist/integrations/fetch.d.ts +19 -0
- package/dist/integrations/fetch.js +30 -0
- package/dist/integrations/orpc.d.ts +22 -0
- package/dist/integrations/orpc.js +37 -0
- package/dist/node.d.ts +1 -26
- package/dist/node.js +1 -76
- package/dist/orpc.d.ts +1 -21
- package/dist/orpc.js +1 -37
- package/dist/pg-boss.d.ts +2 -55
- package/dist/pg-boss.js +2 -211
- package/dist/postgres.d.ts +2 -28
- package/dist/postgres.js +1 -82
- package/dist/sqlite.d.ts +2 -9
- package/dist/sqlite.js +1 -65
- package/dist/testing.d.ts +1 -67
- package/dist/testing.js +1 -214
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +7 -6
- package/src/adapters/cloudflare-queue.ts +56 -0
- package/src/adapters/drizzle-pg.ts +108 -0
- package/src/adapters/drizzle-sqlite.ts +234 -0
- package/src/adapters/pg-boss.ts +195 -0
- package/src/adapters/postgres.ts +112 -0
- package/src/adapters/sqlite.ts +96 -0
- package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +18 -0
- package/src/{jobs.ts → core/jobs.ts} +166 -43
- package/src/core/registry.ts +671 -0
- package/src/core/testing.ts +307 -0
- package/src/{types.ts → core/types.ts} +219 -46
- package/src/drizzle/pg.ts +3 -110
- package/src/drizzle/sqlite.ts +3 -236
- package/src/fetch.ts +1 -31
- package/src/hosts/cloudflare.ts +54 -0
- package/src/hosts/node.ts +99 -0
- package/src/hosts/pg-boss.ts +71 -0
- package/src/index.ts +17 -655
- package/src/integrations/ai.ts +63 -0
- package/src/integrations/fetch.ts +31 -0
- package/src/integrations/orpc.ts +47 -0
- package/src/node.ts +1 -99
- package/src/orpc.ts +1 -46
- package/src/pg-boss.ts +2 -242
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -288
- package/dist/jobs.d.ts +0 -44
- /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
- /package/dist/{errors.js → core/errors.js} +0 -0
- /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
- /package/dist/{schedule.js → core/schedule.js} +0 -0
- /package/dist/{types.js → core/types.js} +0 -0
- /package/src/{errors.ts → core/errors.ts} +0 -0
- /package/src/{schedule.ts → core/schedule.ts} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,495 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
export { DomainError, isDomainError, unauthenticated } from "./errors.js";
|
|
6
|
-
export { inProcess, replaceKeyOf } from "./jobs.js";
|
|
7
|
-
/**
|
|
8
|
-
* Typed constructors for your app:
|
|
9
|
-
*
|
|
10
|
-
* ```ts
|
|
11
|
-
* export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
|
|
12
|
-
* ```
|
|
13
|
-
*/
|
|
14
|
-
export function init() {
|
|
15
|
-
// One implementation behind the typed signature of `Constructor`: the types are the contract, the adapters check `authorize`.
|
|
16
|
-
const make = (kind) => (def) => Object.freeze({ [BRAND]: kind, kind, ...def });
|
|
17
|
-
return {
|
|
18
|
-
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
19
|
-
createRegistry: (options) => build(options, {}), // meta in wrap is typed by CallMetaOf<C>; the values come from typed defs
|
|
20
|
-
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
21
|
-
query: make("query"),
|
|
22
|
-
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
23
|
-
mutation: make("mutation"),
|
|
24
|
-
/** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
|
|
25
|
-
action: make("action"),
|
|
26
|
-
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
27
|
-
event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
|
|
28
|
-
/**
|
|
29
|
-
* Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
|
|
30
|
-
* `registry.jobs.tick()` every minute (or from your platform's cron trigger):
|
|
31
|
-
* `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
|
|
32
|
-
*/
|
|
33
|
-
cron: (def) => {
|
|
34
|
-
const { id, schedule, timezone, run, input, scope, attempts } = def;
|
|
35
|
-
parseSchedule(schedule);
|
|
36
|
-
if (timezone !== undefined)
|
|
37
|
-
assertTimeZone(timezone);
|
|
38
|
-
checkAttempts("cron", attempts);
|
|
39
|
-
return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, run, input, scope, attempts });
|
|
40
|
-
},
|
|
41
|
-
/**
|
|
42
|
-
* React to an event after commit, like an action. Must be idempotent.
|
|
43
|
-
* `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
|
|
44
|
-
*/
|
|
45
|
-
listener: (def) => {
|
|
46
|
-
const { id, event, attempts, delay, when, meta, handler } = def;
|
|
47
|
-
checkAttempts("listener", attempts);
|
|
48
|
-
if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
|
|
49
|
-
throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
|
|
50
|
-
// meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
|
|
51
|
-
return Object.freeze({ [BRAND]: "listener", kind: "listener", id, event, attempts, delay, when, meta: meta, handler });
|
|
52
|
-
},
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
/** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
|
|
56
|
-
const MAX_RUN_DEPTH = 64;
|
|
57
|
-
function checkAttempts(what, attempts) {
|
|
58
|
-
if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
|
|
59
|
-
throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
|
|
60
|
-
}
|
|
61
|
-
/** What a mutation throws at commit when a nested mutation failed and was caught: the transaction they share is doomed. */
|
|
62
|
-
function caughtNestedFailure(id, tx) {
|
|
63
|
-
let why;
|
|
64
|
-
try {
|
|
65
|
-
why = tx.reason instanceof Error ? tx.reason.message : String(tx.reason);
|
|
66
|
-
}
|
|
67
|
-
catch {
|
|
68
|
-
why = Object.prototype.toString.call(tx.reason); // an object String() can't print
|
|
69
|
-
}
|
|
70
|
-
return new CaughtNestedFailure(`[logic-sdk] ${tx.doomedBy?.at(-1)} failed inside ${id}'s transaction (${tx.doomedBy?.join(" → ")}) and was ` +
|
|
71
|
-
`caught, so ${id} can't commit: a mutation shares its transaction with the mutations it runs. To let each one ` +
|
|
72
|
-
`commit or fail on its own, run them from an action. The failure (this error's cause): ${why}`, { cause: tx.reason });
|
|
73
|
-
}
|
|
74
|
-
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
75
|
-
export function createRegistry(options) {
|
|
76
|
-
return build(options, {});
|
|
77
|
-
}
|
|
78
|
-
const isPlain = (v) => !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
79
|
-
/** Plain objects merge key by key; anything else (values, arrays, null) replaces. `undefined` keeps the base. */
|
|
80
|
-
function mergeConfig(base, patch) {
|
|
81
|
-
if (patch === undefined)
|
|
82
|
-
return base;
|
|
83
|
-
if (!isPlain(base) || !isPlain(patch))
|
|
84
|
-
return patch;
|
|
85
|
-
const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
|
|
86
|
-
return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
|
|
87
|
-
}
|
|
88
|
-
/** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
|
|
89
|
-
function freezeConfig(value) {
|
|
90
|
-
assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
|
|
91
|
-
const freeze = (v) => {
|
|
92
|
-
if (v && typeof v === "object") {
|
|
93
|
-
for (const item of Object.values(v))
|
|
94
|
-
freeze(item);
|
|
95
|
-
Object.freeze(v);
|
|
96
|
-
}
|
|
97
|
-
return v;
|
|
98
|
-
};
|
|
99
|
-
return freeze(structuredClone(value));
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
|
|
103
|
-
* Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
|
|
104
|
-
*/
|
|
105
|
-
function assertPlain(value, what, hint) {
|
|
106
|
-
const seen = new Set();
|
|
107
|
-
const check = (v, path) => {
|
|
108
|
-
const fail = (found) => {
|
|
109
|
-
throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
|
|
110
|
-
};
|
|
111
|
-
if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean")
|
|
112
|
-
return;
|
|
113
|
-
if (typeof v === "number") {
|
|
114
|
-
if (!Number.isFinite(v))
|
|
115
|
-
fail(String(v));
|
|
116
|
-
return;
|
|
117
|
-
}
|
|
118
|
-
if (typeof v !== "object")
|
|
119
|
-
return fail(`a ${typeof v}`);
|
|
120
|
-
if (seen.has(v))
|
|
121
|
-
fail("a circular reference");
|
|
122
|
-
seen.add(v);
|
|
123
|
-
if (Array.isArray(v))
|
|
124
|
-
v.forEach((item, i) => check(item, `${path}[${i}]`));
|
|
125
|
-
else {
|
|
126
|
-
if (!isPlain(v))
|
|
127
|
-
fail(`a ${v.constructor?.name ?? "class instance"}`);
|
|
128
|
-
for (const [k, item] of Object.entries(v))
|
|
129
|
-
check(item, path ? `${path}.${k}` : k);
|
|
130
|
-
}
|
|
131
|
-
seen.delete(v);
|
|
132
|
-
};
|
|
133
|
-
check(value, "");
|
|
134
|
-
}
|
|
135
|
-
const isBranded = (v) => !!v && typeof v === "object" && BRAND in v;
|
|
136
|
-
/**
|
|
137
|
-
* What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
|
|
138
|
-
* cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
|
|
139
|
-
*/
|
|
140
|
-
export function describeModules(modules) {
|
|
141
|
-
const ids = new Map();
|
|
142
|
-
const functions = [];
|
|
143
|
-
const events = [];
|
|
144
|
-
const listeners = [];
|
|
145
|
-
const crons = [];
|
|
146
|
-
const taken = new Map();
|
|
147
|
-
for (const [module, ns] of Object.entries(modules)) {
|
|
148
|
-
for (const [name, value] of Object.entries(ns)) {
|
|
149
|
-
if (!isBranded(value) || ids.has(value))
|
|
150
|
-
continue;
|
|
151
|
-
const local = value.id ?? name;
|
|
152
|
-
if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
|
|
153
|
-
throw new Error(`[logic-sdk] ${module}.${name} has id ${JSON.stringify(value.id)}. Give the local name ("send"): the module key is added, so it's ${module}.<id>.`);
|
|
154
|
-
const id = `${module}.${local}`;
|
|
155
|
-
const other = taken.get(id);
|
|
156
|
-
if (other)
|
|
157
|
-
throw new Error(`[logic-sdk] ${module}.${other} and ${module}.${name} both have the id ${id}. Ids must be unique: jobs find their code by it.`);
|
|
158
|
-
taken.set(id, name);
|
|
159
|
-
ids.set(value, id);
|
|
160
|
-
if (value.kind === "event")
|
|
161
|
-
events.push({ id, module, name, event: value });
|
|
162
|
-
else if (value.kind === "listener")
|
|
163
|
-
listeners.push({ id, module, name, listener: value, event: value.event() });
|
|
164
|
-
else if (value.kind === "cron")
|
|
165
|
-
crons.push({ id, module, name, cron: value, run: value.run() });
|
|
166
|
-
else
|
|
167
|
-
functions.push({ id, module, name, kind: value.kind, fn: value });
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
return { ids, functions, events, listeners, crons };
|
|
171
|
-
}
|
|
172
|
-
function build(options, o) {
|
|
173
|
-
const { ids, functions, events, listeners, crons } = describeModules(options.modules);
|
|
174
|
-
const database = o.database ?? options.database;
|
|
175
|
-
const services = o.services ?? options.services ?? {};
|
|
176
|
-
const config = freezeConfig(mergeConfig(options.config ?? {}, o.config));
|
|
177
|
-
const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
|
|
178
|
-
const jobScope = options.jobs?.scope;
|
|
179
|
-
if (jobScope?.store && !jobScope.load)
|
|
180
|
-
throw new Error("[logic-sdk] jobs.scope has store but no load. Jobs run as a scope, so rebuild it from what store saved.");
|
|
181
|
-
// a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
|
|
182
|
-
// back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
|
|
183
|
-
const appAdapter = options.jobs?.adapter;
|
|
184
|
-
if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
|
|
185
|
-
throw new Error("[logic-sdk] Your jobs adapter keeps jobs to run later, so set jobs.scope.load: it rebuilds the scope when a job runs, with today's " +
|
|
186
|
-
"roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.");
|
|
187
|
-
const now = o.now ?? options.now ?? (() => new Date());
|
|
188
|
-
const wrap = options.wrap ?? ((_c, next) => next());
|
|
189
|
-
const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
|
|
190
|
-
checkAttempts("database transaction", options.database?.transactionAttempts);
|
|
191
|
-
const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
|
|
192
|
-
const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
|
|
193
|
-
const reportRaw = o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
|
|
194
|
-
const report = (e, info) => {
|
|
195
|
-
try {
|
|
196
|
-
reportRaw(e, info);
|
|
197
|
-
}
|
|
198
|
-
catch (inner) {
|
|
199
|
-
console.error("[logic-sdk] onError threw", inner, "while reporting", e);
|
|
200
|
-
}
|
|
201
|
-
};
|
|
202
|
-
const noDatabase = "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
|
|
203
|
-
"transactions, so Cloudflare D1 and HTTP drivers can't run mutations.";
|
|
204
|
-
if (!database && functions.some((f) => f.kind === "mutation"))
|
|
205
|
-
throw new Error(noDatabase);
|
|
206
|
-
for (const l of listeners)
|
|
207
|
-
if (!ids.has(l.event))
|
|
208
|
-
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
209
|
-
jobsAdapter.check?.({ listeners, database });
|
|
210
|
-
const idOf = (x) => {
|
|
211
|
-
const id = ids.get(x);
|
|
212
|
-
if (!id)
|
|
213
|
-
throw new Error("[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }). " +
|
|
214
|
-
"A private function (one the index doesn't export) runs only through ctx.run, from its own module.");
|
|
215
|
-
return id;
|
|
216
|
-
};
|
|
217
|
-
/** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
|
|
218
|
-
async function parseInput(schema, value, id, nested) {
|
|
219
|
-
const r = await schema["~standard"].validate(value);
|
|
220
|
-
if (!r.issues)
|
|
221
|
-
return r.value;
|
|
222
|
-
const issues = describeIssues(r.issues);
|
|
223
|
-
if (nested)
|
|
224
|
-
throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
|
|
225
|
-
throw new DomainError("invalid", `${id}.invalid_input`, { issues });
|
|
226
|
-
}
|
|
227
|
-
/** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
|
|
228
|
-
async function parseOwn(schema, value, what) {
|
|
229
|
-
const r = await schema["~standard"].validate(value);
|
|
230
|
-
if (r.issues)
|
|
231
|
-
throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
232
|
-
return r.value;
|
|
233
|
-
}
|
|
234
|
-
/** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
|
|
235
|
-
function checkAtCommit(tx, schema, value, what, keep) {
|
|
236
|
-
const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
|
|
237
|
-
check.catch(() => { }); // surfaced at commit; never an unhandled rejection
|
|
238
|
-
tx.pending.push(check);
|
|
239
|
-
}
|
|
240
|
-
for (const c of crons) {
|
|
241
|
-
if (!ids.has(c.run))
|
|
242
|
-
throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
|
|
243
|
-
assertPlain(c.cron.input, `${c.id} input`, "Cron runs travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
|
|
244
|
-
}
|
|
245
|
-
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
246
|
-
/** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
|
|
247
|
-
const enter = (frame, options) => ({
|
|
248
|
-
...frame,
|
|
249
|
-
scope: options?.scope ?? frame.scope,
|
|
250
|
-
signal: options?.signal ?? frame.signal,
|
|
251
|
-
abortOn: options?.signal,
|
|
252
|
-
});
|
|
253
|
-
/** What every ctx has. `allowed`: the kinds its `run` may call. */
|
|
254
|
-
const baseCtx = (frame, id, allowed) => ({
|
|
255
|
-
errors: errorsFor(id),
|
|
256
|
-
scope: frame.scope,
|
|
257
|
-
config: config, // Frozen<Cf> here; each app's ctx types it from its own Config
|
|
258
|
-
now,
|
|
259
|
-
run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed, moduleOf(id)),
|
|
260
|
-
});
|
|
261
|
-
const queryCtx = (frame, id) => ({
|
|
262
|
-
...baseCtx(frame, id, ["query"]),
|
|
263
|
-
db: frame.tx ? frame.tx.db : database?.db,
|
|
264
|
-
});
|
|
265
|
-
function mutationCtx(frame, tx, id) {
|
|
266
|
-
return {
|
|
267
|
-
...baseCtx(frame, id, ["query", "mutation"]),
|
|
268
|
-
db: tx.db,
|
|
269
|
-
emit: (event, payload) => {
|
|
270
|
-
// reserve the slot now so events keep emit order, even with async schemas
|
|
271
|
-
const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
|
|
272
|
-
tx.events.push(envelope);
|
|
273
|
-
checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
|
|
274
|
-
},
|
|
275
|
-
schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
|
|
276
|
-
const fnId = ids.get(fn);
|
|
277
|
-
if (!fnId)
|
|
278
|
-
throw new Error("[logic-sdk] ctx.schedule needs a function its module's index.ts exports: a scheduled call waits as a name, and a worker finds the code by it. " +
|
|
279
|
-
"A private function runs only through ctx.run.");
|
|
280
|
-
const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
|
|
281
|
-
if (!Number.isFinite(seconds) || (!at && seconds < 0))
|
|
282
|
-
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
|
|
283
|
-
checkAttempts(`ctx.schedule(${fnId})`, attempts);
|
|
284
|
-
if (replace !== undefined) {
|
|
285
|
-
if (!replace)
|
|
286
|
-
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replace must be a non-empty key.`);
|
|
287
|
-
if (!jobsAdapter.replaces)
|
|
288
|
-
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replaces a waiting call, but your jobs adapter can't replace one it already has. Use databaseQueue(database), or outbox(database, queue) in front of your queue.`);
|
|
289
|
-
}
|
|
290
|
-
// due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
|
|
291
|
-
const waits = seconds > 0;
|
|
292
|
-
if (waits)
|
|
293
|
-
checkHold(`ctx.schedule(${fnId})`, seconds);
|
|
294
|
-
assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
|
|
295
|
-
const job = {
|
|
296
|
-
kind: "call",
|
|
297
|
-
id: `${fnId}@${crypto.randomUUID()}`,
|
|
298
|
-
fn: fnId,
|
|
299
|
-
input: structuredClone(input),
|
|
300
|
-
scope: storedScope(frame.scope, `the scope scheduling ${fnId}`),
|
|
301
|
-
attempts,
|
|
302
|
-
depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
|
|
303
|
-
};
|
|
304
|
-
if (waits)
|
|
305
|
-
job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
|
|
306
|
-
if (replace !== undefined) {
|
|
307
|
-
job.replace = replace;
|
|
308
|
-
// scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
|
|
309
|
-
// a bad input is a bug wherever it is)
|
|
310
|
-
const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
|
|
311
|
-
if (earlier >= 0)
|
|
312
|
-
tx.calls.splice(earlier, 1);
|
|
313
|
-
}
|
|
314
|
-
tx.calls.push(job);
|
|
315
|
-
// our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
|
|
316
|
-
if (fn.input)
|
|
317
|
-
checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
|
|
318
|
-
return job.id;
|
|
319
|
-
},
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
/** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
|
|
323
|
-
function envelopeOf(event, payload, scope, depth) {
|
|
324
|
-
const name = idOf(event);
|
|
325
|
-
// a queue carries JSON: a Date or a class instance would work in-process and break only in production
|
|
326
|
-
assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
|
|
327
|
-
return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
|
|
328
|
-
}
|
|
329
|
-
/** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
|
|
330
|
-
function storedScope(scope, what) {
|
|
331
|
-
const stored = jobScope?.store ? jobScope.store(scope) : scope;
|
|
332
|
-
assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
|
|
333
|
-
return structuredClone(stored);
|
|
334
|
-
}
|
|
335
|
-
const actionCtx = (frame, id) => ({
|
|
336
|
-
...baseCtx(frame, id, ["query", "mutation", "action"]),
|
|
337
|
-
signal: frame.signal,
|
|
338
|
-
services,
|
|
339
|
-
});
|
|
340
|
-
const { toJobs, deliver, jobs, due, checkHold } = makeJobs({
|
|
341
|
-
listeners,
|
|
342
|
-
crons,
|
|
343
|
-
functions,
|
|
344
|
-
idOf,
|
|
345
|
-
jobsAdapter,
|
|
346
|
-
database,
|
|
347
|
-
jobScope,
|
|
348
|
-
maxEventDepth,
|
|
349
|
-
now,
|
|
350
|
-
wrap,
|
|
351
|
-
report,
|
|
352
|
-
runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
|
|
353
|
-
listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
354
|
-
});
|
|
355
|
-
// ── invoke ───────────────────────────────────────────────────────────────
|
|
356
|
-
/** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
|
|
357
|
-
async function invoke(fn, rawInput, outer, allowed, callerModule) {
|
|
358
|
-
// anything else that runs one finds it by name, and it has none: idOf throws, saying so
|
|
359
|
-
const id = ids.get(fn) ?? (callerModule ? `${callerModule}.${fn.id ?? PRIVATE}` : idOf(fn));
|
|
360
|
-
if (!allowed.includes(fn.kind))
|
|
361
|
-
throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
|
|
362
|
-
const depth = outer.trail.length;
|
|
363
|
-
// a function that runs itself, through other modules or not, never returns: stop it with the path, not run out of memory
|
|
364
|
-
if (depth > MAX_RUN_DEPTH)
|
|
365
|
-
throw new Error(`[logic-sdk] ctx.run nested past ${MAX_RUN_DEPTH} calls: … → ${[...outer.trail.slice(-6), id].join(" → ")}. ` +
|
|
366
|
-
"Recurse in a plain helper that takes ctx, or make each step separate work (an event, or ctx.schedule).");
|
|
367
|
-
const frame = { ...outer, trail: [...outer.trail, id] };
|
|
368
|
-
const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth };
|
|
369
|
-
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
370
|
-
const prepare = async () => {
|
|
371
|
-
frame.abortOn?.throwIfAborted();
|
|
372
|
-
if (fn.authorize) {
|
|
373
|
-
// SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
|
|
374
|
-
if (fn.authorize(frame.scope) !== true)
|
|
375
|
-
throw new DomainError("forbidden", forbiddenOf(id));
|
|
376
|
-
}
|
|
377
|
-
// no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
|
|
378
|
-
return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
|
|
379
|
-
};
|
|
380
|
-
const execute = async (input, ctx) => {
|
|
381
|
-
// SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
|
|
382
|
-
// and `input` just passed its own schema (or it takes none).
|
|
383
|
-
const handler = o.stubs?.get(fn) ?? fn.handler;
|
|
384
|
-
const out = await handler(ctx, input);
|
|
385
|
-
return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
|
|
386
|
-
};
|
|
387
|
-
return wrap(call, async () => {
|
|
388
|
-
if (fn.kind === "query")
|
|
389
|
-
return execute(await prepare(), queryCtx(frame, id));
|
|
390
|
-
if (fn.kind === "action")
|
|
391
|
-
return execute(await prepare(), actionCtx(frame, id));
|
|
392
|
-
// mutation joining an open transaction: any failure dooms it, even if the caller catches
|
|
393
|
-
if (frame.tx) {
|
|
394
|
-
const tx = frame.tx;
|
|
395
|
-
try {
|
|
396
|
-
return await execute(await prepare(), mutationCtx(frame, tx, id));
|
|
397
|
-
}
|
|
398
|
-
catch (e) {
|
|
399
|
-
if (!tx.doomed) {
|
|
400
|
-
tx.doomed = true;
|
|
401
|
-
tx.reason = e;
|
|
402
|
-
tx.doomedBy = frame.trail.slice(tx.from);
|
|
403
|
-
}
|
|
404
|
-
throw e;
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
// top-level mutation: open the transaction, commit, then deliver events.
|
|
408
|
-
// A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
|
|
409
|
-
// createRegistry checks for one, but a private mutation isn't registered, so it can only be checked here
|
|
410
|
-
if (!database)
|
|
411
|
-
throw new Error(noDatabase);
|
|
412
|
-
const input = await prepare();
|
|
413
|
-
let committed;
|
|
414
|
-
for (let attempt = 1;; attempt++) {
|
|
415
|
-
const attemptTx = {};
|
|
416
|
-
try {
|
|
417
|
-
committed = await database.transaction(async (txDb) => {
|
|
418
|
-
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
419
|
-
const tx = {
|
|
420
|
-
db: txDb, doomed: false, reason: undefined, from: frame.trail.length - 1, doomedBy: undefined,
|
|
421
|
-
events: [], parsed: new Map(), calls: [], pending: [],
|
|
422
|
-
};
|
|
423
|
-
attemptTx.current = tx;
|
|
424
|
-
const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
|
|
425
|
-
await Promise.all(tx.pending);
|
|
426
|
-
// a nested failure was caught: a bug, so its own error, with the failure as its cause (Ecto's aborted
|
|
427
|
-
// transaction). Retries still see a deadlock: `retryable` walks causes
|
|
428
|
-
if (tx.doomed)
|
|
429
|
-
throw caughtNestedFailure(id, tx);
|
|
430
|
-
const jobs = toJobs(tx.events, tx.calls, tx.parsed);
|
|
431
|
-
if (jobs.length)
|
|
432
|
-
await jobsAdapter.enqueue?.(txDb, jobs);
|
|
433
|
-
return { out, events: tx.events, jobs };
|
|
434
|
-
});
|
|
435
|
-
break;
|
|
436
|
-
}
|
|
437
|
-
catch (e) {
|
|
438
|
-
// a lost race dooms the transaction even when a caller caught it and went on: Postgres then fails the next
|
|
439
|
-
// statement with 25P02, or the caller throws its own error, and the race is still what to retry
|
|
440
|
-
const doomed = attemptTx.current?.doomed ? attemptTx.current.reason : undefined;
|
|
441
|
-
const lostRace = database.retryable?.(e) || (doomed !== undefined && database.retryable?.(doomed));
|
|
442
|
-
if (attempt < transactionAttempts && lostRace) {
|
|
443
|
-
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
444
|
-
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
445
|
-
continue;
|
|
446
|
-
}
|
|
447
|
-
throw e;
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
// committed. Nothing below may fail the caller.
|
|
451
|
-
await afterCommit(committed.events, committed.jobs, frame.queued);
|
|
452
|
-
return committed.out;
|
|
453
|
-
});
|
|
454
|
-
}
|
|
455
|
-
async function afterCommit(emitted, jobs, queued) {
|
|
456
|
-
try {
|
|
457
|
-
for (const e of emitted)
|
|
458
|
-
o.record?.(e);
|
|
459
|
-
if (!jobs.length)
|
|
460
|
-
return;
|
|
461
|
-
if (queued)
|
|
462
|
-
return void queued.push(...jobs); // queued by a job: delivered once that job is settled
|
|
463
|
-
const delivery = deliver(jobs);
|
|
464
|
-
if (waitUntil) {
|
|
465
|
-
try {
|
|
466
|
-
waitUntil(delivery);
|
|
467
|
-
return;
|
|
468
|
-
}
|
|
469
|
-
catch (e) {
|
|
470
|
-
report(e, { source: "(waitUntil)" });
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
await delivery;
|
|
474
|
-
}
|
|
475
|
-
catch (e) {
|
|
476
|
-
report(e, { source: "(after commit)" });
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
return {
|
|
480
|
-
as: (scope) => ({
|
|
481
|
-
scope,
|
|
482
|
-
run: (fn, input, options) => invoke(fn, input, enter({ scope, trail: [], eventDepth: 0 }, options), ["query", "mutation", "action"]),
|
|
483
|
-
}),
|
|
484
|
-
definitions: { functions, events, listeners, crons },
|
|
485
|
-
idOf,
|
|
486
|
-
jobs,
|
|
487
|
-
[INTERNAL]: {
|
|
488
|
-
options,
|
|
489
|
-
config,
|
|
490
|
-
derive: (more) => build(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
|
|
491
|
-
envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
|
|
492
|
-
due,
|
|
493
|
-
},
|
|
494
|
-
};
|
|
495
|
-
}
|
|
1
|
+
export { DomainError, isDomainError, unauthenticated } from "./core/errors.js";
|
|
2
|
+
export { inProcess } from "./core/in-process.js";
|
|
3
|
+
export { defaultBackoff, storedReplaceKey } from "./core/jobs.js";
|
|
4
|
+
export { createRegistry, describeModules, init } from "./core/registry.js";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Tool } from "ai";
|
|
2
|
+
import type { Caller, FnIn, FnOut, ForFunctions, PublishableFn, ScopeOfFn } from "../core/types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* What this adapter reads from a function's `meta` (not a listener's). Add it to your meta shape:
|
|
5
|
+
* `init<{ meta: AIMeta & AppMeta }>()`, then `meta: { ai: { description: "Use when the customer asks to cancel an order" } }`.
|
|
6
|
+
*/
|
|
7
|
+
export type AIMeta = ForFunctions<{
|
|
8
|
+
ai?: {
|
|
9
|
+
/** What the model reads to decide when to call it. Optional, but models pick tools better with one. */
|
|
10
|
+
description?: string;
|
|
11
|
+
};
|
|
12
|
+
}>;
|
|
13
|
+
export interface AIToolOptions {
|
|
14
|
+
/** Overrides `meta.ai.description` for this tool. */
|
|
15
|
+
description?: string;
|
|
16
|
+
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
17
|
+
onError?: (error: unknown) => void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
|
|
21
|
+
* and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
|
|
22
|
+
* `authorize`: the model acts for someone else.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
26
|
+
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
30
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
31
|
+
*/
|
|
32
|
+
export declare function toAITool<F extends PublishableFn>(caller: Caller<ScopeOfFn<F>>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { jsonSchema, tool } from "ai";
|
|
2
|
+
import { isDomainError } from "../core/errors.js";
|
|
3
|
+
/** `meta.ai` as `AIMeta` types it where you write it (meta is stored loose). */
|
|
4
|
+
const aiMeta = (fn) => fn.meta?.ai;
|
|
5
|
+
/** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
|
|
6
|
+
const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
|
7
|
+
/**
|
|
8
|
+
* One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
|
|
9
|
+
* and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
|
|
10
|
+
* `authorize`: the model acts for someone else.
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
14
|
+
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
18
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
19
|
+
*/
|
|
20
|
+
export function toAITool(caller, fn, options = {}) {
|
|
21
|
+
if (!fn.authorize)
|
|
22
|
+
throw new Error("[logic-sdk] toAITool publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
|
|
23
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
24
|
+
return tool({
|
|
25
|
+
description: options.description ?? aiMeta(fn)?.description,
|
|
26
|
+
inputSchema: fn.input ?? noInput,
|
|
27
|
+
outputSchema: fn.output,
|
|
28
|
+
async execute(input, { abortSignal }) {
|
|
29
|
+
try {
|
|
30
|
+
return await caller.run(fn, input, { signal: abortSignal });
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
if (isDomainError(e))
|
|
34
|
+
throw e;
|
|
35
|
+
onError(e);
|
|
36
|
+
throw new Error("internal_error");
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type ErrorKind } from "../core/errors.ts";
|
|
2
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
3
|
+
export declare const statusOf: Record<ErrorKind, number>;
|
|
4
|
+
/**
|
|
5
|
+
* A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
|
|
6
|
+
* (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
|
|
7
|
+
* and logs it, and its message never reaches the client.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* app.post("/orders", async (c) => {
|
|
11
|
+
* try {
|
|
12
|
+
* return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
|
|
13
|
+
* } catch (e) {
|
|
14
|
+
* return toResponse(e);
|
|
15
|
+
* }
|
|
16
|
+
* });
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare function toResponse(error: unknown): Response;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { isDomainError } from "../core/errors.js";
|
|
2
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
3
|
+
export const statusOf = {
|
|
4
|
+
invalid: 400,
|
|
5
|
+
unauthenticated: 401,
|
|
6
|
+
forbidden: 403,
|
|
7
|
+
not_found: 404,
|
|
8
|
+
conflict: 409,
|
|
9
|
+
rejected: 422,
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
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
|
+
* ```
|
|
25
|
+
*/
|
|
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] });
|
|
30
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type DecoratedProcedure } from "@orpc/server";
|
|
2
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
import { type ErrorKind } from "../core/errors.ts";
|
|
4
|
+
import type { Caller, Fn, Kind, PublishableFn, ScopeOfFn } from "../core/types.ts";
|
|
5
|
+
/** oRPC context a procedure expects: bind who is calling per request, in your handler or middleware. */
|
|
6
|
+
export type ORPCContext<S extends object> = {
|
|
7
|
+
caller: Caller<S>;
|
|
8
|
+
};
|
|
9
|
+
/** `toORPCProcedure(fn)`: an oRPC procedure, so `.use`, `.meta` and `.errors` work as on your own. */
|
|
10
|
+
export type ProcedureOf<F> = F extends Fn<Kind, infer I, infer O> ? DecoratedProcedure<ORPCContext<ScopeOfFn<F>>, object, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
|
|
11
|
+
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
12
|
+
export declare const orpcCodeOf: Record<ErrorKind, string>;
|
|
13
|
+
/**
|
|
14
|
+
* One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
|
|
15
|
+
* own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
19
|
+
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function toORPCProcedure<F extends PublishableFn>(fn: F): ProcedureOf<F>;
|