logic-sdk 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +129 -2
- package/bin/logic-sdk.js +14 -0
- package/dist/ai.d.ts +45 -0
- package/dist/ai.js +51 -0
- package/dist/drizzle.d.ts +18 -0
- package/dist/drizzle.js +23 -0
- package/dist/fetch.d.ts +24 -0
- package/dist/fetch.js +68 -0
- package/dist/index.d.ts +444 -0
- package/dist/index.js +388 -0
- package/dist/orpc.d.ts +31 -0
- package/dist/orpc.js +46 -0
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +61 -0
- package/package.json +106 -4
- package/src/ai.ts +84 -0
- package/src/drizzle.ts +39 -0
- package/src/fetch.ts +82 -0
- package/src/index.ts +736 -0
- package/src/orpc.ts +65 -0
- package/src/testing.ts +88 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
const BRAND = Symbol.for("logic-sdk.brand");
|
|
2
|
+
/**
|
|
3
|
+
* An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
|
|
4
|
+
* adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
|
|
5
|
+
* bugs) is unexpected: adapters answer 500 and report it.
|
|
6
|
+
*/
|
|
7
|
+
export class DomainError extends Error {
|
|
8
|
+
kind;
|
|
9
|
+
code;
|
|
10
|
+
details;
|
|
11
|
+
constructor(kind, code, details) {
|
|
12
|
+
// the details are in the message too: logs and AI tool errors (which show only the message) stay useful
|
|
13
|
+
super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
|
|
14
|
+
this.name = "DomainError";
|
|
15
|
+
this.kind = kind;
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.details = details;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
21
|
+
export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
|
|
22
|
+
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
23
|
+
const errorsFor = (id) => {
|
|
24
|
+
const module = id.slice(0, id.indexOf("."));
|
|
25
|
+
return {
|
|
26
|
+
reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
|
|
27
|
+
conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
|
|
28
|
+
notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
|
|
29
|
+
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
|
|
33
|
+
export const inProcess = () => ({
|
|
34
|
+
async deliver(envelopes, dispatch) {
|
|
35
|
+
for (const e of envelopes)
|
|
36
|
+
await dispatch(e);
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
/**
|
|
40
|
+
* Typed constructors for your app:
|
|
41
|
+
*
|
|
42
|
+
* ```ts
|
|
43
|
+
* export const { query, mutation, action, event, on, createRegistry } = init<Config>();
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export function init() {
|
|
47
|
+
return constructors();
|
|
48
|
+
}
|
|
49
|
+
function constructors() {
|
|
50
|
+
const make = (kind) => (def) => {
|
|
51
|
+
const where = def?.description ? `"${def.description}"` : `a ${kind}`;
|
|
52
|
+
if (def.authorize !== undefined && typeof def.authorize !== "function")
|
|
53
|
+
throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
|
|
54
|
+
if (def.expose !== undefined && def.expose !== true)
|
|
55
|
+
throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
|
|
56
|
+
if (def.expose && !def.authorize)
|
|
57
|
+
throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
|
|
58
|
+
if (def.expose && !def.outputSchema)
|
|
59
|
+
throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
|
|
60
|
+
return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
|
|
61
|
+
};
|
|
62
|
+
return {
|
|
63
|
+
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
64
|
+
createRegistry: (options) => build(options, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
|
|
65
|
+
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
66
|
+
query: make("query"),
|
|
67
|
+
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
68
|
+
mutation: make("mutation"),
|
|
69
|
+
/** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
|
|
70
|
+
action: make("action"),
|
|
71
|
+
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
72
|
+
event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
|
|
73
|
+
/** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
|
|
74
|
+
on: (event, execute, opts = {}) => Object.freeze({
|
|
75
|
+
[BRAND]: "listener",
|
|
76
|
+
kind: "listener",
|
|
77
|
+
event,
|
|
78
|
+
description: opts.description,
|
|
79
|
+
execute: execute,
|
|
80
|
+
}),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
84
|
+
* createRegistry
|
|
85
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
86
|
+
const INTERNAL = Symbol.for("logic-sdk.internal");
|
|
87
|
+
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
88
|
+
export function createRegistry(options) {
|
|
89
|
+
return build(options, {});
|
|
90
|
+
}
|
|
91
|
+
const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
|
|
92
|
+
/**
|
|
93
|
+
* What `createRegistry` finds in your modules, without a database or services: every function, event and
|
|
94
|
+
* listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
|
|
95
|
+
*/
|
|
96
|
+
export function describeModules(modules) {
|
|
97
|
+
const ids = new Map();
|
|
98
|
+
const functions = [];
|
|
99
|
+
const events = [];
|
|
100
|
+
const listeners = [];
|
|
101
|
+
for (const [module, ns] of Object.entries(modules)) {
|
|
102
|
+
for (const [name, value] of Object.entries(ns)) {
|
|
103
|
+
if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value))
|
|
104
|
+
continue;
|
|
105
|
+
const id = `${module}.${name}`;
|
|
106
|
+
ids.set(value, id);
|
|
107
|
+
const kind = value[BRAND];
|
|
108
|
+
if (kind === "event")
|
|
109
|
+
events.push({ id, module, name, event: value });
|
|
110
|
+
else if (kind === "listener") {
|
|
111
|
+
const listener = value;
|
|
112
|
+
listeners.push({ id, module, name, listener, event: listener.event() });
|
|
113
|
+
}
|
|
114
|
+
else
|
|
115
|
+
functions.push({ id, module, name, kind, fn: value, exposed: value.expose === true });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return { ids, functions, events, listeners };
|
|
119
|
+
}
|
|
120
|
+
function build(options, o) {
|
|
121
|
+
const { ids, functions, events, listeners } = describeModules(options.modules);
|
|
122
|
+
const database = o.database ?? options.database;
|
|
123
|
+
const services = o.services ?? options.services ?? {};
|
|
124
|
+
const dispatcher = o.events ?? options.events ?? inProcess();
|
|
125
|
+
const now = o.now ?? options.now ?? (() => new Date());
|
|
126
|
+
const wrap = options.wrap ?? ((_c, next) => next());
|
|
127
|
+
const maxEventDepth = options.maxEventDepth ?? 8;
|
|
128
|
+
const attempts = Math.max(1, options.retry?.attempts ?? 3);
|
|
129
|
+
const reportRaw = options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.listener} failed`, e));
|
|
130
|
+
const report = (e, info) => {
|
|
131
|
+
try {
|
|
132
|
+
reportRaw(e, info);
|
|
133
|
+
}
|
|
134
|
+
catch (inner) {
|
|
135
|
+
console.error("[logic-sdk] onError threw", inner, "while reporting", e);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
if (functions.some((f) => f.kind === "mutation") && database?.transactions !== "interactive")
|
|
139
|
+
throw new Error("[logic-sdk] Mutations need a database adapter with interactive transactions (e.g. drizzleAdapter(db)). " +
|
|
140
|
+
"Drivers without them (Cloudflare D1, HTTP drivers) are not supported for mutations.");
|
|
141
|
+
for (const l of listeners)
|
|
142
|
+
if (!l.event || !ids.has(l.event))
|
|
143
|
+
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
144
|
+
const idOf = (x) => {
|
|
145
|
+
const id = ids.get(x);
|
|
146
|
+
if (!id)
|
|
147
|
+
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 }).");
|
|
148
|
+
return id;
|
|
149
|
+
};
|
|
150
|
+
/** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
|
|
151
|
+
async function parseInput(schema, value, id, nested) {
|
|
152
|
+
const r = await schema["~standard"].validate(value);
|
|
153
|
+
if (!r.issues)
|
|
154
|
+
return r.value;
|
|
155
|
+
const issues = describeIssues(r.issues);
|
|
156
|
+
if (nested)
|
|
157
|
+
throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
|
|
158
|
+
throw new DomainError("invalid", `${id}.invalid_input`, { issues });
|
|
159
|
+
}
|
|
160
|
+
/** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
|
|
161
|
+
async function parseOwn(schema, value, what) {
|
|
162
|
+
const r = await schema["~standard"].validate(value);
|
|
163
|
+
if (r.issues)
|
|
164
|
+
throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
165
|
+
return r.value;
|
|
166
|
+
}
|
|
167
|
+
// ── listeners ────────────────────────────────────────────────────────────
|
|
168
|
+
const byEvent = new Map();
|
|
169
|
+
for (const l of listeners) {
|
|
170
|
+
const name = idOf(l.event);
|
|
171
|
+
byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
|
|
172
|
+
}
|
|
173
|
+
const eventByName = new Map(events.map((e) => [e.id, e.event]));
|
|
174
|
+
/** Run every listener for one envelope. Returns the failures instead of throwing. */
|
|
175
|
+
async function runListeners(envelope, eventDepth) {
|
|
176
|
+
const failures = [];
|
|
177
|
+
const event = eventByName.get(envelope.name);
|
|
178
|
+
for (const l of byEvent.get(envelope.name) ?? []) {
|
|
179
|
+
const frame = { scope: envelope.scope, depth: 0, opts: { eventDepth } };
|
|
180
|
+
try {
|
|
181
|
+
await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
|
|
182
|
+
const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
|
|
183
|
+
return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
failures.push({ listener: l.id, error });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return failures;
|
|
191
|
+
}
|
|
192
|
+
/** In-process delivery: failures go to onError. */
|
|
193
|
+
const deliverOne = (eventDepth) => async (envelope) => {
|
|
194
|
+
for (const f of await runListeners(envelope, eventDepth))
|
|
195
|
+
report(f.error, { listener: f.listener, envelope });
|
|
196
|
+
};
|
|
197
|
+
/** Public: for durable dispatchers. Throws an AggregateError if any listener failed, so the consumer can retry. */
|
|
198
|
+
async function dispatch(envelope) {
|
|
199
|
+
const failures = await runListeners(envelope, 1);
|
|
200
|
+
if (failures.length)
|
|
201
|
+
throw new AggregateError(failures.map((f) => f.error), `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`);
|
|
202
|
+
}
|
|
203
|
+
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
204
|
+
const child = (frame) => ({ ...frame, depth: frame.depth + 1 });
|
|
205
|
+
const rescope = (frame, patch) => ({ ...frame, scope: { ...frame.scope, ...patch } });
|
|
206
|
+
function queryCtx(frame, id) {
|
|
207
|
+
return {
|
|
208
|
+
errors: errorsFor(id),
|
|
209
|
+
scope: frame.scope,
|
|
210
|
+
now,
|
|
211
|
+
signal: frame.opts.signal,
|
|
212
|
+
db: frame.tx ? frame.tx.db : database?.db,
|
|
213
|
+
run: (fn, input) => invoke(fn, input, child(frame), ["query"]),
|
|
214
|
+
with: (patch) => queryCtx(rescope(frame, patch), id),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
function mutationCtx(frame, id) {
|
|
218
|
+
const tx = frame.tx;
|
|
219
|
+
return {
|
|
220
|
+
errors: errorsFor(id),
|
|
221
|
+
scope: frame.scope,
|
|
222
|
+
now,
|
|
223
|
+
signal: frame.opts.signal,
|
|
224
|
+
db: tx.db,
|
|
225
|
+
run: (fn, input) => invoke(fn, input, child(frame), ["query", "mutation"]),
|
|
226
|
+
emit: (event, payload) => {
|
|
227
|
+
const name = idOf(event);
|
|
228
|
+
payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
|
|
229
|
+
// reserve the slot now so events keep emit order, even with async schemas
|
|
230
|
+
const envelope = {
|
|
231
|
+
id: crypto.randomUUID(),
|
|
232
|
+
name,
|
|
233
|
+
payload,
|
|
234
|
+
scope: structuredClone(frame.scope),
|
|
235
|
+
occurredAt: now().toISOString(),
|
|
236
|
+
};
|
|
237
|
+
tx.outbox.push(envelope);
|
|
238
|
+
const check = parseOwn(event.schema, payload, `${name} payload`).then(() => { });
|
|
239
|
+
check.catch(() => { }); // surfaced at commit; never an unhandled rejection
|
|
240
|
+
tx.pending.push(check);
|
|
241
|
+
},
|
|
242
|
+
with: (patch) => mutationCtx(rescope(frame, patch), id),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function actionCtx(frame, id) {
|
|
246
|
+
return {
|
|
247
|
+
errors: errorsFor(id),
|
|
248
|
+
scope: frame.scope,
|
|
249
|
+
now,
|
|
250
|
+
signal: frame.opts.signal,
|
|
251
|
+
services,
|
|
252
|
+
run: (fn, input) => invoke(fn, input, child({ ...frame, tx: undefined }), ["query", "mutation", "action"]),
|
|
253
|
+
with: (patch) => actionCtx(rescope(frame, patch), id),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
// ── invoke ───────────────────────────────────────────────────────────────
|
|
257
|
+
async function invoke(fn, rawInput, frame, allowed) {
|
|
258
|
+
const id = idOf(fn);
|
|
259
|
+
if (!allowed.includes(fn.kind))
|
|
260
|
+
throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
|
|
261
|
+
const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
|
|
262
|
+
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
263
|
+
const prepare = async () => {
|
|
264
|
+
frame.opts.signal?.throwIfAborted();
|
|
265
|
+
if (fn.authorize) {
|
|
266
|
+
const allowed = fn.authorize(frame.scope);
|
|
267
|
+
if (allowed instanceof Promise || typeof allowed?.then === "function")
|
|
268
|
+
throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
|
|
269
|
+
if (allowed !== true)
|
|
270
|
+
throw new DomainError("forbidden", `${id}.forbidden`);
|
|
271
|
+
}
|
|
272
|
+
return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
|
|
273
|
+
};
|
|
274
|
+
const execute = async (input, ctx) => {
|
|
275
|
+
const stub = o.stubs?.get(fn);
|
|
276
|
+
const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
|
|
277
|
+
return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
|
|
278
|
+
};
|
|
279
|
+
return wrap(call, async () => {
|
|
280
|
+
if (fn.kind === "query")
|
|
281
|
+
return execute(await prepare(), queryCtx(frame, id));
|
|
282
|
+
if (fn.kind === "action")
|
|
283
|
+
return execute(await prepare(), actionCtx(frame, id));
|
|
284
|
+
// mutation joining an open transaction: any failure dooms it, even if the caller catches
|
|
285
|
+
if (frame.tx) {
|
|
286
|
+
const tx = frame.tx;
|
|
287
|
+
try {
|
|
288
|
+
return await execute(await prepare(), mutationCtx(frame, id));
|
|
289
|
+
}
|
|
290
|
+
catch (e) {
|
|
291
|
+
if (!tx.doomed) {
|
|
292
|
+
tx.doomed = true;
|
|
293
|
+
tx.reason = e;
|
|
294
|
+
}
|
|
295
|
+
throw e;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// top-level mutation: open the transaction, commit, then deliver events.
|
|
299
|
+
// A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
|
|
300
|
+
const input = await prepare();
|
|
301
|
+
let committed;
|
|
302
|
+
for (let attempt = 1;; attempt++) {
|
|
303
|
+
let state;
|
|
304
|
+
try {
|
|
305
|
+
committed = await database.transaction(async (txDb) => {
|
|
306
|
+
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
307
|
+
const tx = (state = { db: txDb, doomed: false, reason: undefined, outbox: [], pending: [] });
|
|
308
|
+
const out = await execute(input, mutationCtx({ ...frame, tx }, id));
|
|
309
|
+
await Promise.all(tx.pending);
|
|
310
|
+
if (tx.doomed)
|
|
311
|
+
throw tx.reason;
|
|
312
|
+
await dispatcher.enqueue?.(txDb, tx.outbox);
|
|
313
|
+
return { out, outbox: tx.outbox };
|
|
314
|
+
});
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
catch (e) {
|
|
318
|
+
if (attempt < attempts && database.retryable?.(e)) {
|
|
319
|
+
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
320
|
+
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
throw e;
|
|
324
|
+
}
|
|
325
|
+
finally {
|
|
326
|
+
if (state)
|
|
327
|
+
await Promise.allSettled(state.pending);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
// committed. Nothing below may fail the caller.
|
|
331
|
+
if (committed.outbox.length)
|
|
332
|
+
await afterCommit(committed.outbox, frame);
|
|
333
|
+
return committed.out;
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
async function afterCommit(outbox, frame) {
|
|
337
|
+
try {
|
|
338
|
+
for (const e of outbox)
|
|
339
|
+
o.record?.(e);
|
|
340
|
+
const eventDepth = (frame.opts.eventDepth ?? 0) + 1;
|
|
341
|
+
if (eventDepth > maxEventDepth) {
|
|
342
|
+
report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
|
|
343
|
+
listener: "(dispatcher)",
|
|
344
|
+
envelope: outbox[0],
|
|
345
|
+
});
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
const delivery = (async () => dispatcher.deliver(outbox, deliverOne(eventDepth)))().catch((e) => report(e, { listener: "(dispatcher)", envelope: outbox[0] }));
|
|
349
|
+
if (options.waitUntil) {
|
|
350
|
+
try {
|
|
351
|
+
options.waitUntil(delivery);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
catch (e) {
|
|
355
|
+
report(e, { listener: "(waitUntil)", envelope: outbox[0] });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
await delivery;
|
|
359
|
+
}
|
|
360
|
+
catch (e) {
|
|
361
|
+
report(e, { listener: "(after commit)", envelope: outbox[0] });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function makeCaller(scope, opts) {
|
|
365
|
+
return {
|
|
366
|
+
scope,
|
|
367
|
+
run: (fn, input) => invoke(fn, input, { scope, depth: 0, opts }, ["query", "mutation", "action"]),
|
|
368
|
+
with: (patch) => makeCaller({ ...scope, ...patch }, opts),
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
return {
|
|
372
|
+
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
373
|
+
modules: options.modules,
|
|
374
|
+
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
375
|
+
as: (scope, opts = {}) => makeCaller(scope, opts),
|
|
376
|
+
/** Everything the registry can do. Adapters read this. */
|
|
377
|
+
functions: functions,
|
|
378
|
+
events: events,
|
|
379
|
+
listeners: listeners,
|
|
380
|
+
idOf,
|
|
381
|
+
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
382
|
+
dispatch,
|
|
383
|
+
/** @internal used by `logic-sdk/testing` */
|
|
384
|
+
[INTERNAL]: { options, overrides: o, derive: (more) => build(options, { ...o, ...more }) },
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
/** @internal */
|
|
388
|
+
export const internal = (registry) => registry[INTERNAL];
|
package/dist/orpc.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type Procedure } from "@orpc/server";
|
|
2
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
import { type Caller, type ErrorKind, type Fn, type Registry } from "./index.ts";
|
|
4
|
+
/** oRPC context the router expects: bind who is calling per request, in your handler or middleware. */
|
|
5
|
+
export type ORPCContext<S extends object> = {
|
|
6
|
+
caller: Caller<S>;
|
|
7
|
+
};
|
|
8
|
+
type ProcedureOf<S extends object, F> = F extends Fn<any, infer I, infer O, true> ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
|
|
9
|
+
/** `{ bookings: { confirm, cancel, … } }`: only functions with `expose: true`. */
|
|
10
|
+
export type ORPCRouterOf<S extends object, Mods> = {
|
|
11
|
+
[M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
|
|
12
|
+
[N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
type ExposedOf<T> = {
|
|
16
|
+
[N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N];
|
|
17
|
+
};
|
|
18
|
+
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
19
|
+
export declare const orpcCodeOf: Record<ErrorKind, string>;
|
|
20
|
+
/**
|
|
21
|
+
* Turn the registry into an oRPC router. Your modules stay the core; oRPC is the edge that gives you
|
|
22
|
+
* a typed client, OpenAPI and MCP. Validation runs once, in the registry.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* const router = toORPCRouter(registry);
|
|
26
|
+
* const handler = new RPCHandler(router);
|
|
27
|
+
* handler.handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export declare function toORPCRouter<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>): ORPCRouterOf<S, Mods>;
|
|
31
|
+
export {};
|
package/dist/orpc.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { ORPCError, os } from "@orpc/server";
|
|
2
|
+
import { isDomainError } from "./index.js";
|
|
3
|
+
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
4
|
+
export const orpcCodeOf = {
|
|
5
|
+
invalid: "BAD_REQUEST",
|
|
6
|
+
unauthenticated: "UNAUTHORIZED",
|
|
7
|
+
forbidden: "FORBIDDEN",
|
|
8
|
+
not_found: "NOT_FOUND",
|
|
9
|
+
conflict: "CONFLICT",
|
|
10
|
+
rejected: "UNPROCESSABLE_CONTENT",
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Turn the registry into an oRPC router. Your modules stay the core; oRPC is the edge that gives you
|
|
14
|
+
* a typed client, OpenAPI and MCP. Validation runs once, in the registry.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* const router = toORPCRouter(registry);
|
|
18
|
+
* const handler = new RPCHandler(router);
|
|
19
|
+
* handler.handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export function toORPCRouter(registry) {
|
|
23
|
+
const base = os.$context().$config({ disableInputValidation: true, disableOutputValidation: true });
|
|
24
|
+
const router = {};
|
|
25
|
+
for (const f of registry.functions) {
|
|
26
|
+
if (!f.exposed)
|
|
27
|
+
continue;
|
|
28
|
+
let b = base.input(f.fn.inputSchema);
|
|
29
|
+
if (f.fn.outputSchema)
|
|
30
|
+
b = b.output(f.fn.outputSchema);
|
|
31
|
+
(router[f.module] ??= {})[f.name] = b.handler(async ({ input, context }) => {
|
|
32
|
+
try {
|
|
33
|
+
return await context.caller.run(f.fn, input);
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
if (isDomainError(e))
|
|
37
|
+
throw new ORPCError(orpcCodeOf[e.kind], {
|
|
38
|
+
message: e.code,
|
|
39
|
+
data: { kind: e.kind, code: e.code, details: e.details },
|
|
40
|
+
});
|
|
41
|
+
throw e;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
return router;
|
|
46
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type Caller, type CallerOptions, type Envelope, type Fn, type FnIn, type FnOut, type Registry } from "./index.ts";
|
|
2
|
+
export interface TestOptions {
|
|
3
|
+
/** Replace services (e.g. `{ mailer: memoryMailer() }`). */
|
|
4
|
+
services?: object;
|
|
5
|
+
/** Freeze time. */
|
|
6
|
+
now?: Date | string | (() => Date);
|
|
7
|
+
/** Run listeners inline after each mutation (default), or not at all to test one module in isolation. */
|
|
8
|
+
listeners?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object>> {
|
|
11
|
+
/** Bind who is calling, exactly like `registry.as(...)`. */
|
|
12
|
+
as(scope: S, opts?: CallerOptions): Caller<S>;
|
|
13
|
+
/** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
|
|
14
|
+
stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
|
|
15
|
+
/** Every event emitted (and committed) so far, in order. */
|
|
16
|
+
readonly events: Envelope[];
|
|
17
|
+
/** The test transaction itself: read rows to assert on them. */
|
|
18
|
+
readonly db: any;
|
|
19
|
+
/** The registry bound to this test transaction, for adapters: `toFetchHandler(tx.registry, …)`. */
|
|
20
|
+
readonly registry: Registry<S, Mods>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Run each test inside a transaction that is always rolled back.
|
|
24
|
+
* Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes,
|
|
25
|
+
* like it would in production. Run top-level mutations one at a time inside a test (one connection, nested savepoints).
|
|
26
|
+
*/
|
|
27
|
+
export declare function createTestRegistry<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, options?: TestOptions): {
|
|
28
|
+
transaction<T>(fn: (t: TestTransaction<S, Mods>) => Promise<T>): Promise<T>;
|
|
29
|
+
};
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { internal } from "./index.js";
|
|
2
|
+
class Rollback extends Error {
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Run each test inside a transaction that is always rolled back.
|
|
6
|
+
* Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes,
|
|
7
|
+
* like it would in production. Run top-level mutations one at a time inside a test (one connection, nested savepoints).
|
|
8
|
+
*/
|
|
9
|
+
export function createTestRegistry(registry, options = {}) {
|
|
10
|
+
const { options: registryOptions } = internal(registry);
|
|
11
|
+
const now = options.now === undefined
|
|
12
|
+
? undefined
|
|
13
|
+
: typeof options.now === "function"
|
|
14
|
+
? options.now
|
|
15
|
+
: (() => {
|
|
16
|
+
const fixed = new Date(options.now);
|
|
17
|
+
return () => new Date(fixed);
|
|
18
|
+
})();
|
|
19
|
+
return {
|
|
20
|
+
async transaction(fn) {
|
|
21
|
+
const database = registryOptions.database;
|
|
22
|
+
let result;
|
|
23
|
+
const body = async (outer) => {
|
|
24
|
+
const stubs = new Map();
|
|
25
|
+
const events = [];
|
|
26
|
+
const derived = internal(registry).derive({
|
|
27
|
+
database: outer !== undefined && database?.nest ? database.nest(outer) : database,
|
|
28
|
+
services: options.services,
|
|
29
|
+
now,
|
|
30
|
+
stubs,
|
|
31
|
+
record: (e) => events.push(e),
|
|
32
|
+
events: options.listeners === false ? { deliver: async () => { } } : undefined,
|
|
33
|
+
});
|
|
34
|
+
result = await fn({
|
|
35
|
+
as: (scope, opts) => derived.as(scope, opts),
|
|
36
|
+
stub: (f, impl) => void stubs.set(f, impl),
|
|
37
|
+
events,
|
|
38
|
+
db: outer,
|
|
39
|
+
registry: derived,
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
if (!database) {
|
|
43
|
+
await body(undefined);
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
if (!database.nest)
|
|
47
|
+
throw new Error("[logic-sdk] This database adapter can't nest transactions, so tests can't roll back.");
|
|
48
|
+
try {
|
|
49
|
+
await database.transaction(async (outer) => {
|
|
50
|
+
await body(outer);
|
|
51
|
+
throw new Rollback();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
if (!(e instanceof Rollback))
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,108 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "logic-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"actions",
|
|
7
|
+
"agents",
|
|
8
|
+
"ai-agents",
|
|
9
|
+
"ai-sdk",
|
|
10
|
+
"business-logic",
|
|
11
|
+
"cloudflare-workers",
|
|
12
|
+
"drizzle",
|
|
13
|
+
"events",
|
|
14
|
+
"mutations",
|
|
15
|
+
"queries",
|
|
16
|
+
"tools",
|
|
17
|
+
"transactions",
|
|
18
|
+
"typescript"
|
|
19
|
+
],
|
|
20
|
+
"author": {
|
|
21
|
+
"name": "Franco Romano Losada",
|
|
22
|
+
"url": "https://github.com/fprl"
|
|
23
|
+
},
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/logic-sdk/logic-sdk.git",
|
|
28
|
+
"directory": "packages/logic-sdk"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://github.com/logic-sdk/logic-sdk#readme",
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/logic-sdk/logic-sdk/issues"
|
|
33
|
+
},
|
|
34
|
+
"type": "module",
|
|
35
|
+
"sideEffects": false,
|
|
36
|
+
"bin": {
|
|
37
|
+
"logic-sdk": "bin/logic-sdk.js"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -p tsconfig.build.json",
|
|
41
|
+
"typecheck": "tsc -p .",
|
|
42
|
+
"test": "bun test"
|
|
43
|
+
},
|
|
44
|
+
"exports": {
|
|
45
|
+
".": {
|
|
46
|
+
"types": "./dist/index.d.ts",
|
|
47
|
+
"default": "./dist/index.js"
|
|
48
|
+
},
|
|
49
|
+
"./drizzle": {
|
|
50
|
+
"types": "./dist/drizzle.d.ts",
|
|
51
|
+
"default": "./dist/drizzle.js"
|
|
52
|
+
},
|
|
53
|
+
"./testing": {
|
|
54
|
+
"types": "./dist/testing.d.ts",
|
|
55
|
+
"default": "./dist/testing.js"
|
|
56
|
+
},
|
|
57
|
+
"./fetch": {
|
|
58
|
+
"types": "./dist/fetch.d.ts",
|
|
59
|
+
"default": "./dist/fetch.js"
|
|
60
|
+
},
|
|
61
|
+
"./orpc": {
|
|
62
|
+
"types": "./dist/orpc.d.ts",
|
|
63
|
+
"default": "./dist/orpc.js"
|
|
64
|
+
},
|
|
65
|
+
"./ai": {
|
|
66
|
+
"types": "./dist/ai.d.ts",
|
|
67
|
+
"default": "./dist/ai.js"
|
|
68
|
+
},
|
|
69
|
+
"./package.json": "./package.json"
|
|
70
|
+
},
|
|
71
|
+
"files": [
|
|
72
|
+
"dist",
|
|
73
|
+
"src",
|
|
74
|
+
"bin"
|
|
75
|
+
],
|
|
76
|
+
"publishConfig": {
|
|
77
|
+
"access": "public"
|
|
78
|
+
},
|
|
79
|
+
"engines": {
|
|
80
|
+
"node": ">=24"
|
|
81
|
+
},
|
|
82
|
+
"dependencies": {
|
|
83
|
+
"@standard-schema/spec": "^1.1.0"
|
|
84
|
+
},
|
|
85
|
+
"peerDependencies": {
|
|
86
|
+
"@orpc/server": ">=2.0.0-beta.51 <3",
|
|
87
|
+
"ai": ">=7 <8",
|
|
88
|
+
"@logic-sdk/cli": ">=0.2.0 <0.3.0"
|
|
89
|
+
},
|
|
90
|
+
"peerDependenciesMeta": {
|
|
91
|
+
"@orpc/server": {
|
|
92
|
+
"optional": true
|
|
93
|
+
},
|
|
94
|
+
"ai": {
|
|
95
|
+
"optional": true
|
|
96
|
+
},
|
|
97
|
+
"@logic-sdk/cli": {
|
|
98
|
+
"optional": true
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
"devDependencies": {
|
|
102
|
+
"@orpc/server": "2.0.0-beta.51",
|
|
103
|
+
"@types/bun": "^1.4.4",
|
|
104
|
+
"ai": "^7.0.177",
|
|
105
|
+
"drizzle-orm": "1.0.0-rc.5",
|
|
106
|
+
"zod": "^4.6.7"
|
|
107
|
+
}
|
|
108
|
+
}
|