logic-sdk 0.2.0 → 0.3.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 +1 -0
- package/dist/ai.js +2 -2
- package/dist/fetch.d.ts +1 -3
- package/dist/fetch.js +1 -2
- package/dist/index.d.ts +70 -30
- package/dist/index.js +53 -19
- package/dist/orpc.js +2 -2
- package/dist/testing.d.ts +9 -7
- package/dist/testing.js +2 -1
- package/package.json +5 -5
- package/src/ai.ts +2 -2
- package/src/fetch.ts +2 -5
- package/src/index.ts +121 -49
- package/src/orpc.ts +2 -2
- package/src/testing.ts +14 -11
package/README.md
CHANGED
|
@@ -80,6 +80,7 @@ await caller.run(bookings.confirm, { bookingId });
|
|
|
80
80
|
- **Authorization on every call.** `authorize` runs whoever calls: HTTP, an agent, a job or another function. Record rules are sync `can*` predicates the CLI checks.
|
|
81
81
|
- **Internal by default.** Only `expose: true` functions reach HTTP, RPC or AI tools, with a required policy and output contract.
|
|
82
82
|
- **Agents included.** `toAITool` gives an agent your functions, under the same policies and transactions as your API. Opt-in, one function at a time or by `filter`.
|
|
83
|
+
- **Settings in one place.** Declare `config` once, fill it from env at the entry, read `ctx.config` anywhere. The CLI fails the build if a module reads env.
|
|
83
84
|
- **Errors without HTTP.** `ctx.errors.reject`, `conflict`, `notFound`, `deny`; adapters map them to statuses.
|
|
84
85
|
- **Tests without mocks.** Each test is a real transaction on a real database, always rolled back.
|
|
85
86
|
- **No magic.** No decorators, classes, codegen, build step or `AsyncLocalStorage`.
|
package/dist/ai.js
CHANGED
|
@@ -20,9 +20,9 @@ export function toAITool(caller, fn, options = {}) {
|
|
|
20
20
|
description: fn.description,
|
|
21
21
|
inputSchema: fn.inputSchema,
|
|
22
22
|
outputSchema: fn.outputSchema,
|
|
23
|
-
async execute(input) {
|
|
23
|
+
async execute(input, { abortSignal }) {
|
|
24
24
|
try {
|
|
25
|
-
return await caller.run(fn, input);
|
|
25
|
+
return await caller.run(fn, input, { signal: abortSignal });
|
|
26
26
|
}
|
|
27
27
|
catch (e) {
|
|
28
28
|
if (isDomainError(e))
|
package/dist/fetch.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DomainError, type
|
|
1
|
+
import { DomainError, type ErrorKind, type Registry } from "./index.ts";
|
|
2
2
|
/**
|
|
3
3
|
* Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
|
|
4
4
|
* For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
|
|
@@ -9,8 +9,6 @@ export declare const statusOf: Record<ErrorKind, number>;
|
|
|
9
9
|
export interface FetchOptions<S extends object> {
|
|
10
10
|
/** Build the scope for this request (session → actor, account, locale...). */
|
|
11
11
|
resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
|
|
12
|
-
/** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
|
|
13
|
-
callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
|
|
14
12
|
/** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
|
|
15
13
|
basePath?: string;
|
|
16
14
|
/** Unexpected (non-domain) errors. Default: console.error. */
|
package/dist/fetch.js
CHANGED
|
@@ -55,8 +55,7 @@ export function toFetchHandler(registry, options) {
|
|
|
55
55
|
}
|
|
56
56
|
try {
|
|
57
57
|
const scope = await options.resolveScope(request, ...rest);
|
|
58
|
-
|
|
59
|
-
return json({ data: await caller.run(entry.fn, input) });
|
|
58
|
+
return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
|
|
60
59
|
}
|
|
61
60
|
catch (e) {
|
|
62
61
|
if (isDomainError(e))
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,11 @@ export interface Config {
|
|
|
12
12
|
reader?: unknown;
|
|
13
13
|
/** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
|
|
14
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;
|
|
15
20
|
/** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
|
|
16
21
|
meta?: object;
|
|
17
22
|
}
|
|
@@ -28,6 +33,19 @@ type ServicesOf<C extends Config> = C extends {
|
|
|
28
33
|
type MetaOf<C extends Config> = C extends {
|
|
29
34
|
meta: infer M;
|
|
30
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
|
+
};
|
|
31
49
|
export type Kind = "query" | "mutation" | "action";
|
|
32
50
|
declare const types: unique symbol;
|
|
33
51
|
declare const BRAND: unique symbol;
|
|
@@ -88,7 +106,20 @@ export interface Listener<O = any> {
|
|
|
88
106
|
readonly description?: string;
|
|
89
107
|
readonly execute: (payload: O, ctx: any) => Promise<unknown>;
|
|
90
108
|
}
|
|
91
|
-
|
|
109
|
+
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
110
|
+
export interface RunOptions<S = object> {
|
|
111
|
+
/**
|
|
112
|
+
* Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
|
|
113
|
+
* someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
|
|
114
|
+
*/
|
|
115
|
+
scope?: Partial<S>;
|
|
116
|
+
/**
|
|
117
|
+
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
118
|
+
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|
|
119
|
+
*/
|
|
120
|
+
signal?: AbortSignal;
|
|
121
|
+
}
|
|
122
|
+
type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>, options?: RunOptions<S>) => Promise<FnOut<F>>;
|
|
92
123
|
/**
|
|
93
124
|
* Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
|
|
94
125
|
* code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
|
|
@@ -103,36 +134,37 @@ export interface Errors {
|
|
|
103
134
|
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
|
|
104
135
|
deny(code?: string, details?: unknown): DomainError;
|
|
105
136
|
}
|
|
106
|
-
interface BaseCtx<S> {
|
|
137
|
+
interface BaseCtx<C extends Config, S> {
|
|
107
138
|
scope: S;
|
|
139
|
+
/** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
|
|
140
|
+
config: Frozen<ConfigOf<C>>;
|
|
108
141
|
/** Expected failures: `throw ctx.errors.reject("not_pending")`. */
|
|
109
142
|
errors: Errors;
|
|
110
143
|
/** Current time. Fixed in tests. */
|
|
111
144
|
now: () => Date;
|
|
112
145
|
}
|
|
113
146
|
/** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
|
|
114
|
-
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
147
|
+
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
115
148
|
db: ReaderOf<C>;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
signal: AbortSignal | undefined;
|
|
119
|
-
with(patch: Partial<ScopeOf<C>>): QueryCtx<C>;
|
|
149
|
+
/** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
|
|
150
|
+
run: Run<"query", ScopeOf<C>>;
|
|
120
151
|
}
|
|
121
|
-
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
152
|
+
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
122
153
|
db: DbOf<C>;
|
|
123
|
-
|
|
154
|
+
/**
|
|
155
|
+
* Call a query or mutation inside this same transaction, with its policy and validation:
|
|
156
|
+
* `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
|
|
157
|
+
*/
|
|
158
|
+
run: Run<"query" | "mutation", ScopeOf<C>>;
|
|
124
159
|
/** Queue an event. Delivered to listeners only after the transaction commits. */
|
|
125
160
|
emit<I>(event: EventDef<I, any>, payload: I): void;
|
|
126
|
-
signal: AbortSignal | undefined;
|
|
127
|
-
with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
|
|
128
161
|
}
|
|
129
|
-
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
162
|
+
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
130
163
|
services: ServicesOf<C>;
|
|
131
|
-
/** Each mutation you run
|
|
132
|
-
run: Run<Kind
|
|
133
|
-
/** The caller's abort signal. Always undefined in listeners (they outlive the request). */
|
|
164
|
+
/** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
|
|
165
|
+
run: Run<Kind, ScopeOf<C>>;
|
|
166
|
+
/** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
|
|
134
167
|
signal: AbortSignal | undefined;
|
|
135
|
-
with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
|
|
136
168
|
}
|
|
137
169
|
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
138
170
|
event: Envelope<unknown, ScopeOf<C>> & {
|
|
@@ -230,6 +262,8 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
230
262
|
modules: Mods;
|
|
231
263
|
database?: DatabaseAdapter<any, any>;
|
|
232
264
|
services?: object;
|
|
265
|
+
/** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
|
|
266
|
+
config?: object;
|
|
233
267
|
events?: Dispatcher;
|
|
234
268
|
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
235
269
|
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
@@ -256,15 +290,11 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
256
290
|
attempts?: number;
|
|
257
291
|
};
|
|
258
292
|
}
|
|
259
|
-
|
|
260
|
-
/** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
|
|
261
|
-
signal?: AbortSignal;
|
|
262
|
-
}
|
|
263
|
-
/** A registry bound to a scope: `const caller = registry.as(scope)`. */
|
|
293
|
+
/** A registry bound to who is calling: `const caller = registry.as(scope)`. */
|
|
264
294
|
export interface Caller<S extends object = object> {
|
|
265
295
|
readonly scope: S;
|
|
266
|
-
|
|
267
|
-
|
|
296
|
+
/** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
|
|
297
|
+
run<F extends Fn>(fn: F, input: FnIn<F>, options?: RunOptions<S>): Promise<FnOut<F>>;
|
|
268
298
|
}
|
|
269
299
|
export interface Registered {
|
|
270
300
|
id: string;
|
|
@@ -284,6 +314,10 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
|
|
|
284
314
|
services?: ServicesOf<C>;
|
|
285
315
|
} : {
|
|
286
316
|
services: ServicesOf<C>;
|
|
317
|
+
}) & ({} extends ConfigOf<C> ? {
|
|
318
|
+
config?: ConfigOf<C>;
|
|
319
|
+
} : {
|
|
320
|
+
config: ConfigOf<C>;
|
|
287
321
|
}) & ([DbOf<C>] extends [never] ? {
|
|
288
322
|
database?: undefined;
|
|
289
323
|
} : {
|
|
@@ -306,7 +340,7 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
306
340
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
307
341
|
modules: Mods;
|
|
308
342
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
309
|
-
as: (scope: ScopeOf<C
|
|
343
|
+
as: (scope: ScopeOf<C>) => Caller<ScopeOf<C>>;
|
|
310
344
|
/** Everything the registry can do. Adapters read this. */
|
|
311
345
|
functions: readonly RegisteredFn[];
|
|
312
346
|
events: readonly (Registered & {
|
|
@@ -323,6 +357,7 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
323
357
|
[INTERNAL]: {
|
|
324
358
|
options: RegistryOptions<Mods>;
|
|
325
359
|
overrides: Overrides;
|
|
360
|
+
config: Frozen<ConfigOf<C>>;
|
|
326
361
|
derive: (more: Overrides) => /*elided*/ any;
|
|
327
362
|
};
|
|
328
363
|
};
|
|
@@ -346,18 +381,20 @@ declare const INTERNAL: unique symbol;
|
|
|
346
381
|
export interface Overrides {
|
|
347
382
|
database?: DatabaseAdapter<any, any>;
|
|
348
383
|
services?: object;
|
|
384
|
+
/** Merged over the registry's config, section by section. */
|
|
385
|
+
config?: object;
|
|
349
386
|
events?: Dispatcher;
|
|
350
387
|
now?: () => Date;
|
|
351
388
|
stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
|
|
352
389
|
record?: (envelope: Envelope) => void;
|
|
353
390
|
}
|
|
354
|
-
export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object
|
|
391
|
+
export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> = ReturnType<typeof build<S, Mods, Cf>>;
|
|
355
392
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
356
393
|
export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): {
|
|
357
394
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
358
395
|
modules: Mods;
|
|
359
396
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
360
|
-
as: (scope: S
|
|
397
|
+
as: (scope: S) => Caller<S>;
|
|
361
398
|
/** Everything the registry can do. Adapters read this. */
|
|
362
399
|
functions: readonly RegisteredFn[];
|
|
363
400
|
events: readonly (Registered & {
|
|
@@ -374,6 +411,7 @@ export declare function createRegistry<S extends object = object, const Mods ext
|
|
|
374
411
|
[INTERNAL]: {
|
|
375
412
|
options: RegistryOptions<Mods>;
|
|
376
413
|
overrides: Overrides;
|
|
414
|
+
config: {};
|
|
377
415
|
derive: (more: Overrides) => /*elided*/ any;
|
|
378
416
|
};
|
|
379
417
|
};
|
|
@@ -392,11 +430,11 @@ export declare function describeModules(modules: Record<string, object>): {
|
|
|
392
430
|
event: EventDef;
|
|
393
431
|
})[];
|
|
394
432
|
};
|
|
395
|
-
declare function build<S extends object, Mods extends Record<string, object
|
|
433
|
+
declare function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(options: RegistryOptions<Mods>, o: Overrides): {
|
|
396
434
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
397
435
|
modules: Mods;
|
|
398
436
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
399
|
-
as: (scope: S
|
|
437
|
+
as: (scope: S) => Caller<S>;
|
|
400
438
|
/** Everything the registry can do. Adapters read this. */
|
|
401
439
|
functions: readonly RegisteredFn[];
|
|
402
440
|
events: readonly (Registered & {
|
|
@@ -413,18 +451,20 @@ declare function build<S extends object, Mods extends Record<string, object>>(op
|
|
|
413
451
|
[INTERNAL]: {
|
|
414
452
|
options: RegistryOptions<Mods>;
|
|
415
453
|
overrides: Overrides;
|
|
454
|
+
config: Frozen<Cf>;
|
|
416
455
|
derive: (more: Overrides) => /*elided*/ any;
|
|
417
456
|
};
|
|
418
457
|
};
|
|
419
458
|
/** @internal */
|
|
420
|
-
export declare const internal: (registry: Registry<any, any>) => {
|
|
459
|
+
export declare const internal: (registry: Registry<any, any, any>) => {
|
|
421
460
|
options: RegistryOptions<any>;
|
|
422
461
|
overrides: Overrides;
|
|
462
|
+
config: any;
|
|
423
463
|
derive: (more: Overrides) => {
|
|
424
464
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
425
465
|
modules: any;
|
|
426
466
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
427
|
-
as: (scope: any
|
|
467
|
+
as: (scope: any) => Caller<any>;
|
|
428
468
|
/** Everything the registry can do. Adapters read this. */
|
|
429
469
|
functions: readonly RegisteredFn[];
|
|
430
470
|
events: readonly (Registered & {
|
package/dist/index.js
CHANGED
|
@@ -88,6 +88,31 @@ const INTERNAL = Symbol.for("logic-sdk.internal");
|
|
|
88
88
|
export function createRegistry(options) {
|
|
89
89
|
return build(options, {});
|
|
90
90
|
}
|
|
91
|
+
const isPlain = (v) => !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
92
|
+
/** Plain objects merge key by key; anything else (values, arrays, null) replaces. `undefined` keeps the base. */
|
|
93
|
+
function mergeConfig(base, patch) {
|
|
94
|
+
if (patch === undefined)
|
|
95
|
+
return base;
|
|
96
|
+
if (!isPlain(base) || !isPlain(patch))
|
|
97
|
+
return patch;
|
|
98
|
+
const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
|
|
99
|
+
return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* A frozen copy of plain data: strings, numbers, booleans, null, plain objects and arrays. Anything else (a Date, a Map,
|
|
103
|
+
* a client, a class) is rejected with its path, so settings can't change under everyone else or hide behavior.
|
|
104
|
+
*/
|
|
105
|
+
function freezeConfig(value, path = "config") {
|
|
106
|
+
if (value === null || ["string", "number", "boolean", "undefined"].includes(typeof value))
|
|
107
|
+
return value;
|
|
108
|
+
if (Array.isArray(value))
|
|
109
|
+
return Object.freeze(value.map((v, i) => freezeConfig(v, `${path}[${i}]`)));
|
|
110
|
+
if (isPlain(value))
|
|
111
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).map(([k, v]) => [k, freezeConfig(v, `${path}.${k}`)])));
|
|
112
|
+
const what = typeof value === "function" ? "a function" : value.constructor?.name ?? typeof value;
|
|
113
|
+
throw new Error(`[logic-sdk] ${path} is ${what}. config holds plain data (strings, numbers, booleans, null, objects, arrays): ` +
|
|
114
|
+
"pass a Date as an ISO string, and put clients in services.");
|
|
115
|
+
}
|
|
91
116
|
const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
|
|
92
117
|
/**
|
|
93
118
|
* What `createRegistry` finds in your modules, without a database or services: every function, event and
|
|
@@ -121,6 +146,7 @@ function build(options, o) {
|
|
|
121
146
|
const { ids, functions, events, listeners } = describeModules(options.modules);
|
|
122
147
|
const database = o.database ?? options.database;
|
|
123
148
|
const services = o.services ?? options.services ?? {};
|
|
149
|
+
const config = freezeConfig(mergeConfig(options.config ?? {}, o.config));
|
|
124
150
|
const dispatcher = o.events ?? options.events ?? inProcess();
|
|
125
151
|
const now = o.now ?? options.now ?? (() => new Date());
|
|
126
152
|
const wrap = options.wrap ?? ((_c, next) => next());
|
|
@@ -176,7 +202,7 @@ function build(options, o) {
|
|
|
176
202
|
const failures = [];
|
|
177
203
|
const event = eventByName.get(envelope.name);
|
|
178
204
|
for (const l of byEvent.get(envelope.name) ?? []) {
|
|
179
|
-
const frame = { scope: envelope.scope, depth: 0,
|
|
205
|
+
const frame = { scope: envelope.scope, depth: 0, eventDepth };
|
|
180
206
|
try {
|
|
181
207
|
await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
|
|
182
208
|
const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
|
|
@@ -201,17 +227,22 @@ function build(options, o) {
|
|
|
201
227
|
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
228
|
}
|
|
203
229
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
204
|
-
|
|
205
|
-
const
|
|
230
|
+
/** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
|
|
231
|
+
const enter = (frame, options) => ({
|
|
232
|
+
...frame,
|
|
233
|
+
depth: frame.depth + 1,
|
|
234
|
+
scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
|
|
235
|
+
signal: options?.signal ?? frame.signal,
|
|
236
|
+
abortOn: options?.signal,
|
|
237
|
+
});
|
|
206
238
|
function queryCtx(frame, id) {
|
|
207
239
|
return {
|
|
208
240
|
errors: errorsFor(id),
|
|
209
241
|
scope: frame.scope,
|
|
242
|
+
config: config,
|
|
210
243
|
now,
|
|
211
|
-
signal: frame.opts.signal,
|
|
212
244
|
db: frame.tx ? frame.tx.db : database?.db,
|
|
213
|
-
run: (fn, input) => invoke(fn, input,
|
|
214
|
-
with: (patch) => queryCtx(rescope(frame, patch), id),
|
|
245
|
+
run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
|
|
215
246
|
};
|
|
216
247
|
}
|
|
217
248
|
function mutationCtx(frame, id) {
|
|
@@ -219,10 +250,10 @@ function build(options, o) {
|
|
|
219
250
|
return {
|
|
220
251
|
errors: errorsFor(id),
|
|
221
252
|
scope: frame.scope,
|
|
253
|
+
config: config,
|
|
222
254
|
now,
|
|
223
|
-
signal: frame.opts.signal,
|
|
224
255
|
db: tx.db,
|
|
225
|
-
run: (fn, input) => invoke(fn, input,
|
|
256
|
+
run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
|
|
226
257
|
emit: (event, payload) => {
|
|
227
258
|
const name = idOf(event);
|
|
228
259
|
payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
|
|
@@ -239,18 +270,17 @@ function build(options, o) {
|
|
|
239
270
|
check.catch(() => { }); // surfaced at commit; never an unhandled rejection
|
|
240
271
|
tx.pending.push(check);
|
|
241
272
|
},
|
|
242
|
-
with: (patch) => mutationCtx(rescope(frame, patch), id),
|
|
243
273
|
};
|
|
244
274
|
}
|
|
245
275
|
function actionCtx(frame, id) {
|
|
246
276
|
return {
|
|
247
277
|
errors: errorsFor(id),
|
|
248
278
|
scope: frame.scope,
|
|
279
|
+
config: config,
|
|
249
280
|
now,
|
|
250
|
-
signal: frame.
|
|
281
|
+
signal: frame.signal,
|
|
251
282
|
services,
|
|
252
|
-
run: (fn, input) => invoke(fn, input,
|
|
253
|
-
with: (patch) => actionCtx(rescope(frame, patch), id),
|
|
283
|
+
run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
|
|
254
284
|
};
|
|
255
285
|
}
|
|
256
286
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
@@ -261,7 +291,7 @@ function build(options, o) {
|
|
|
261
291
|
const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
|
|
262
292
|
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
263
293
|
const prepare = async () => {
|
|
264
|
-
frame.
|
|
294
|
+
frame.abortOn?.throwIfAborted();
|
|
265
295
|
if (fn.authorize) {
|
|
266
296
|
const allowed = fn.authorize(frame.scope);
|
|
267
297
|
if (allowed instanceof Promise || typeof allowed?.then === "function")
|
|
@@ -337,7 +367,7 @@ function build(options, o) {
|
|
|
337
367
|
try {
|
|
338
368
|
for (const e of outbox)
|
|
339
369
|
o.record?.(e);
|
|
340
|
-
const eventDepth = (frame.
|
|
370
|
+
const eventDepth = (frame.eventDepth ?? 0) + 1;
|
|
341
371
|
if (eventDepth > maxEventDepth) {
|
|
342
372
|
report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
|
|
343
373
|
listener: "(dispatcher)",
|
|
@@ -361,18 +391,17 @@ function build(options, o) {
|
|
|
361
391
|
report(e, { listener: "(after commit)", envelope: outbox[0] });
|
|
362
392
|
}
|
|
363
393
|
}
|
|
364
|
-
function makeCaller(scope
|
|
394
|
+
function makeCaller(scope) {
|
|
365
395
|
return {
|
|
366
396
|
scope,
|
|
367
|
-
run: (fn, input) => invoke(fn, input, { scope, depth:
|
|
368
|
-
with: (patch) => makeCaller({ ...scope, ...patch }, opts),
|
|
397
|
+
run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
|
|
369
398
|
};
|
|
370
399
|
}
|
|
371
400
|
return {
|
|
372
401
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
373
402
|
modules: options.modules,
|
|
374
403
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
375
|
-
as: (scope
|
|
404
|
+
as: (scope) => makeCaller(scope),
|
|
376
405
|
/** Everything the registry can do. Adapters read this. */
|
|
377
406
|
functions: functions,
|
|
378
407
|
events: events,
|
|
@@ -381,7 +410,12 @@ function build(options, o) {
|
|
|
381
410
|
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
382
411
|
dispatch,
|
|
383
412
|
/** @internal used by `logic-sdk/testing` */
|
|
384
|
-
[INTERNAL]: {
|
|
413
|
+
[INTERNAL]: {
|
|
414
|
+
options,
|
|
415
|
+
overrides: o,
|
|
416
|
+
config,
|
|
417
|
+
derive: (more) => build(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
|
|
418
|
+
},
|
|
385
419
|
};
|
|
386
420
|
}
|
|
387
421
|
/** @internal */
|
package/dist/orpc.js
CHANGED
|
@@ -28,9 +28,9 @@ export function toORPCRouter(registry) {
|
|
|
28
28
|
let b = base.input(f.fn.inputSchema);
|
|
29
29
|
if (f.fn.outputSchema)
|
|
30
30
|
b = b.output(f.fn.outputSchema);
|
|
31
|
-
(router[f.module] ??= {})[f.name] = b.handler(async ({ input, context }) => {
|
|
31
|
+
(router[f.module] ??= {})[f.name] = b.handler(async ({ input, context, signal }) => {
|
|
32
32
|
try {
|
|
33
|
-
return await context.caller.run(f.fn, input);
|
|
33
|
+
return await context.caller.run(f.fn, input, { signal });
|
|
34
34
|
}
|
|
35
35
|
catch (e) {
|
|
36
36
|
if (isDomainError(e))
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
import { type Caller, type
|
|
2
|
-
export interface TestOptions {
|
|
1
|
+
import { type Caller, type DeepPartial, type Envelope, type Fn, type FnIn, type FnOut, type Registry } from "./index.ts";
|
|
2
|
+
export interface TestOptions<Cf = unknown> {
|
|
3
3
|
/** Replace services (e.g. `{ mailer: memoryMailer() }`). */
|
|
4
4
|
services?: object;
|
|
5
|
+
/** Override parts of `config` (e.g. `{ orders: { maxItems: 1 } }`). Merged over the registry's, section by section. */
|
|
6
|
+
config?: DeepPartial<Cf>;
|
|
5
7
|
/** Freeze time. */
|
|
6
8
|
now?: Date | string | (() => Date);
|
|
7
9
|
/** Run listeners inline after each mutation (default), or not at all to test one module in isolation. */
|
|
8
10
|
listeners?: boolean;
|
|
9
11
|
}
|
|
10
|
-
export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object
|
|
12
|
+
export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
|
|
11
13
|
/** Bind who is calling, exactly like `registry.as(...)`. */
|
|
12
|
-
as(scope: S
|
|
14
|
+
as(scope: S): Caller<S>;
|
|
13
15
|
/** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
|
|
14
16
|
stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
|
|
15
17
|
/** Every event emitted (and committed) so far, in order. */
|
|
@@ -17,13 +19,13 @@ export interface TestTransaction<S extends object, Mods extends Record<string, o
|
|
|
17
19
|
/** The test transaction itself: read rows to assert on them. */
|
|
18
20
|
readonly db: any;
|
|
19
21
|
/** The registry bound to this test transaction, for adapters: `toFetchHandler(tx.registry, …)`. */
|
|
20
|
-
readonly registry: Registry<S, Mods>;
|
|
22
|
+
readonly registry: Registry<S, Mods, Cf>;
|
|
21
23
|
}
|
|
22
24
|
/**
|
|
23
25
|
* Run each test inside a transaction that is always rolled back.
|
|
24
26
|
* Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes,
|
|
25
27
|
* like it would in production. Run top-level mutations one at a time inside a test (one connection, nested savepoints).
|
|
26
28
|
*/
|
|
27
|
-
export declare function createTestRegistry<S extends object, Mods extends Record<string, object
|
|
28
|
-
transaction<T>(fn: (t: TestTransaction<S, Mods>) => Promise<T>): Promise<T>;
|
|
29
|
+
export declare function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>, options?: TestOptions<Cf>): {
|
|
30
|
+
transaction<T>(fn: (t: TestTransaction<S, Mods, Cf>) => Promise<T>): Promise<T>;
|
|
29
31
|
};
|
package/dist/testing.js
CHANGED
|
@@ -26,13 +26,14 @@ export function createTestRegistry(registry, options = {}) {
|
|
|
26
26
|
const derived = internal(registry).derive({
|
|
27
27
|
database: outer !== undefined && database?.nest ? database.nest(outer) : database,
|
|
28
28
|
services: options.services,
|
|
29
|
+
config: options.config,
|
|
29
30
|
now,
|
|
30
31
|
stubs,
|
|
31
32
|
record: (e) => events.push(e),
|
|
32
33
|
events: options.listeners === false ? { deliver: async () => { } } : undefined,
|
|
33
34
|
});
|
|
34
35
|
result = await fn({
|
|
35
|
-
as: (scope
|
|
36
|
+
as: (scope) => derived.as(scope),
|
|
36
37
|
stub: (f, impl) => void stubs.set(f, impl),
|
|
37
38
|
events,
|
|
38
39
|
db: outer,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "logic-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"actions",
|
|
@@ -24,12 +24,12 @@
|
|
|
24
24
|
"license": "MIT",
|
|
25
25
|
"repository": {
|
|
26
26
|
"type": "git",
|
|
27
|
-
"url": "git+https://github.com/
|
|
27
|
+
"url": "git+https://github.com/fprl/logic-sdk.git",
|
|
28
28
|
"directory": "packages/logic-sdk"
|
|
29
29
|
},
|
|
30
|
-
"homepage": "https://github.com/
|
|
30
|
+
"homepage": "https://github.com/fprl/logic-sdk#readme",
|
|
31
31
|
"bugs": {
|
|
32
|
-
"url": "https://github.com/
|
|
32
|
+
"url": "https://github.com/fprl/logic-sdk/issues"
|
|
33
33
|
},
|
|
34
34
|
"type": "module",
|
|
35
35
|
"sideEffects": false,
|
|
@@ -85,7 +85,7 @@
|
|
|
85
85
|
"peerDependencies": {
|
|
86
86
|
"@orpc/server": ">=2.0.0-beta.51 <3",
|
|
87
87
|
"ai": ">=7 <8",
|
|
88
|
-
"@logic-sdk/cli": ">=0.
|
|
88
|
+
"@logic-sdk/cli": ">=0.3.0 <0.4.0"
|
|
89
89
|
},
|
|
90
90
|
"peerDependenciesMeta": {
|
|
91
91
|
"@orpc/server": {
|
package/src/ai.ts
CHANGED
|
@@ -51,9 +51,9 @@ export function toAITool<F extends Fn<any, any, any, true>>(
|
|
|
51
51
|
description: fn.description,
|
|
52
52
|
inputSchema: fn.inputSchema as FlexibleSchema,
|
|
53
53
|
outputSchema: fn.outputSchema as FlexibleSchema,
|
|
54
|
-
async execute(input) {
|
|
54
|
+
async execute(input, { abortSignal }) {
|
|
55
55
|
try {
|
|
56
|
-
return await caller.run(fn, input);
|
|
56
|
+
return await caller.run(fn, input, { signal: abortSignal });
|
|
57
57
|
} catch (e) {
|
|
58
58
|
if (isDomainError(e)) throw e;
|
|
59
59
|
onError(e);
|
package/src/fetch.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DomainError, isDomainError, type
|
|
1
|
+
import { DomainError, isDomainError, type ErrorKind, type Registry } from "./index.ts";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
|
|
@@ -20,8 +20,6 @@ export const statusOf: Record<ErrorKind, number> = {
|
|
|
20
20
|
export interface FetchOptions<S extends object> {
|
|
21
21
|
/** Build the scope for this request (session → actor, account, locale...). */
|
|
22
22
|
resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
|
|
23
|
-
/** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
|
|
24
|
-
callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
|
|
25
23
|
/** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
|
|
26
24
|
basePath?: string;
|
|
27
25
|
/** Unexpected (non-domain) errors. Default: console.error. */
|
|
@@ -71,8 +69,7 @@ export function toFetchHandler<S extends object>(registry: Registry<S, any>, opt
|
|
|
71
69
|
|
|
72
70
|
try {
|
|
73
71
|
const scope = await options.resolveScope(request, ...rest);
|
|
74
|
-
|
|
75
|
-
return json({ data: await caller.run(entry.fn, input) });
|
|
72
|
+
return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
|
|
76
73
|
} catch (e) {
|
|
77
74
|
if (isDomainError(e)) return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
|
|
78
75
|
onError(e);
|
package/src/index.ts
CHANGED
|
@@ -18,6 +18,11 @@ export interface Config {
|
|
|
18
18
|
reader?: unknown;
|
|
19
19
|
/** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
|
|
20
20
|
services?: object;
|
|
21
|
+
/**
|
|
22
|
+
* Your app's settings, read as `ctx.config` in every function: base URL, limits, switches. Plain data, read-only.
|
|
23
|
+
* Build it once from your env at the entry; clients built from secrets go in `services` instead.
|
|
24
|
+
*/
|
|
25
|
+
config?: object;
|
|
21
26
|
/** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
|
|
22
27
|
meta?: object;
|
|
23
28
|
}
|
|
@@ -26,6 +31,18 @@ type DbOf<C extends Config> = C extends { db: infer D } ? D : never;
|
|
|
26
31
|
type ReaderOf<C extends Config> = C extends { reader: infer R } ? R : DbOf<C>;
|
|
27
32
|
type ServicesOf<C extends Config> = C extends { services: infer S } ? S : {};
|
|
28
33
|
type MetaOf<C extends Config> = C extends { meta: infer M } ? M : never;
|
|
34
|
+
/** Without a declared `config`, nothing may be passed or read: no silently ignored settings. */
|
|
35
|
+
type ConfigOf<C extends Config> = C extends { config: infer F } ? F : Record<string, never>;
|
|
36
|
+
|
|
37
|
+
type Primitive = string | number | boolean | bigint | symbol | null | undefined;
|
|
38
|
+
/** Read-only all the way down: what `ctx.config` gives you. Primitives (branded ones too) stay as they are. */
|
|
39
|
+
export type Frozen<T> = T extends Primitive
|
|
40
|
+
? T
|
|
41
|
+
: T extends readonly (infer U)[]
|
|
42
|
+
? readonly Frozen<U>[]
|
|
43
|
+
: { readonly [K in keyof T]: Frozen<T[K]> };
|
|
44
|
+
/** Any part of `T`, at any depth: what a test may override in `config`. Arrays are replaced whole, like at runtime. */
|
|
45
|
+
export type DeepPartial<T> = T extends Primitive | readonly unknown[] ? T : { [K in keyof T]?: DeepPartial<T[K]> };
|
|
29
46
|
|
|
30
47
|
export type Kind = "query" | "mutation" | "action";
|
|
31
48
|
|
|
@@ -86,7 +103,20 @@ export interface Listener<O = any> {
|
|
|
86
103
|
readonly execute: (payload: O, ctx: any) => Promise<unknown>;
|
|
87
104
|
}
|
|
88
105
|
|
|
89
|
-
|
|
106
|
+
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
107
|
+
export interface RunOptions<S = object> {
|
|
108
|
+
/**
|
|
109
|
+
* Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
|
|
110
|
+
* someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
|
|
111
|
+
*/
|
|
112
|
+
scope?: Partial<S>;
|
|
113
|
+
/**
|
|
114
|
+
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
115
|
+
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|
|
116
|
+
*/
|
|
117
|
+
signal?: AbortSignal;
|
|
118
|
+
}
|
|
119
|
+
type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>, options?: RunOptions<S>) => Promise<FnOut<F>>;
|
|
90
120
|
|
|
91
121
|
/**
|
|
92
122
|
* Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
|
|
@@ -102,36 +132,37 @@ export interface Errors {
|
|
|
102
132
|
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
|
|
103
133
|
deny(code?: string, details?: unknown): DomainError;
|
|
104
134
|
}
|
|
105
|
-
interface BaseCtx<S> {
|
|
135
|
+
interface BaseCtx<C extends Config, S> {
|
|
106
136
|
scope: S;
|
|
137
|
+
/** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
|
|
138
|
+
config: Frozen<ConfigOf<C>>;
|
|
107
139
|
/** Expected failures: `throw ctx.errors.reject("not_pending")`. */
|
|
108
140
|
errors: Errors;
|
|
109
141
|
/** Current time. Fixed in tests. */
|
|
110
142
|
now: () => Date;
|
|
111
143
|
}
|
|
112
144
|
/** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
|
|
113
|
-
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
145
|
+
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
114
146
|
db: ReaderOf<C>;
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
signal: AbortSignal | undefined;
|
|
118
|
-
with(patch: Partial<ScopeOf<C>>): QueryCtx<C>;
|
|
147
|
+
/** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
|
|
148
|
+
run: Run<"query", ScopeOf<C>>;
|
|
119
149
|
}
|
|
120
|
-
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
150
|
+
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
121
151
|
db: DbOf<C>;
|
|
122
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Call a query or mutation inside this same transaction, with its policy and validation:
|
|
154
|
+
* `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
|
|
155
|
+
*/
|
|
156
|
+
run: Run<"query" | "mutation", ScopeOf<C>>;
|
|
123
157
|
/** Queue an event. Delivered to listeners only after the transaction commits. */
|
|
124
158
|
emit<I>(event: EventDef<I, any>, payload: I): void;
|
|
125
|
-
signal: AbortSignal | undefined;
|
|
126
|
-
with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
|
|
127
159
|
}
|
|
128
|
-
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
160
|
+
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
129
161
|
services: ServicesOf<C>;
|
|
130
|
-
/** Each mutation you run
|
|
131
|
-
run: Run<Kind
|
|
132
|
-
/** The caller's abort signal. Always undefined in listeners (they outlive the request). */
|
|
162
|
+
/** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
|
|
163
|
+
run: Run<Kind, ScopeOf<C>>;
|
|
164
|
+
/** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
|
|
133
165
|
signal: AbortSignal | undefined;
|
|
134
|
-
with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
|
|
135
166
|
}
|
|
136
167
|
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
137
168
|
event: Envelope<unknown, ScopeOf<C>> & { payload: O };
|
|
@@ -267,6 +298,8 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
267
298
|
modules: Mods;
|
|
268
299
|
database?: DatabaseAdapter<any, any>;
|
|
269
300
|
services?: object;
|
|
301
|
+
/** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
|
|
302
|
+
config?: object;
|
|
270
303
|
events?: Dispatcher;
|
|
271
304
|
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
272
305
|
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
@@ -289,16 +322,11 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
289
322
|
retry?: { attempts?: number };
|
|
290
323
|
}
|
|
291
324
|
|
|
292
|
-
|
|
293
|
-
/** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
|
|
294
|
-
signal?: AbortSignal;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
/** A registry bound to a scope: `const caller = registry.as(scope)`. */
|
|
325
|
+
/** A registry bound to who is calling: `const caller = registry.as(scope)`. */
|
|
298
326
|
export interface Caller<S extends object = object> {
|
|
299
327
|
readonly scope: S;
|
|
300
|
-
|
|
301
|
-
|
|
328
|
+
/** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
|
|
329
|
+
run<F extends Fn>(fn: F, input: FnIn<F>, options?: RunOptions<S>): Promise<FnOut<F>>;
|
|
302
330
|
}
|
|
303
331
|
|
|
304
332
|
export interface Registered {
|
|
@@ -322,6 +350,7 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
|
|
|
322
350
|
wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
|
|
323
351
|
} &
|
|
324
352
|
({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
|
|
353
|
+
({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
|
|
325
354
|
([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
|
|
326
355
|
|
|
327
356
|
/** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
|
|
@@ -357,7 +386,7 @@ function constructors<C extends Config>() {
|
|
|
357
386
|
return {
|
|
358
387
|
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
359
388
|
createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
|
|
360
|
-
build<ScopeOf<C>, Mods
|
|
389
|
+
build<ScopeOf<C>, Mods, ConfigOf<C>>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
|
|
361
390
|
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
362
391
|
query: make("query") as Constructor<C, "query">,
|
|
363
392
|
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
@@ -399,21 +428,27 @@ interface TxState {
|
|
|
399
428
|
interface Frame {
|
|
400
429
|
scope: object;
|
|
401
430
|
depth: number;
|
|
402
|
-
|
|
431
|
+
/** Inherited, for actions to pass on as ctx.signal. */
|
|
432
|
+
signal?: AbortSignal;
|
|
433
|
+
/** Passed to this very call: checked before it starts. */
|
|
434
|
+
abortOn?: AbortSignal;
|
|
435
|
+
eventDepth?: number;
|
|
403
436
|
tx?: TxState;
|
|
404
437
|
}
|
|
405
438
|
|
|
406
439
|
export interface Overrides {
|
|
407
440
|
database?: DatabaseAdapter<any, any>;
|
|
408
441
|
services?: object;
|
|
442
|
+
/** Merged over the registry's config, section by section. */
|
|
443
|
+
config?: object;
|
|
409
444
|
events?: Dispatcher;
|
|
410
445
|
now?: () => Date;
|
|
411
446
|
stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
|
|
412
447
|
record?: (envelope: Envelope) => void;
|
|
413
448
|
}
|
|
414
449
|
|
|
415
|
-
export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object
|
|
416
|
-
typeof build<S, Mods>
|
|
450
|
+
export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> = ReturnType<
|
|
451
|
+
typeof build<S, Mods, Cf>
|
|
417
452
|
>;
|
|
418
453
|
|
|
419
454
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
@@ -423,6 +458,33 @@ export function createRegistry<S extends object = object, const Mods extends Rec
|
|
|
423
458
|
return build<S, Mods>(options, {});
|
|
424
459
|
}
|
|
425
460
|
|
|
461
|
+
const isPlain = (v: unknown): v is Record<string, unknown> =>
|
|
462
|
+
!!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
463
|
+
|
|
464
|
+
/** Plain objects merge key by key; anything else (values, arrays, null) replaces. `undefined` keeps the base. */
|
|
465
|
+
function mergeConfig(base: unknown, patch: unknown): unknown {
|
|
466
|
+
if (patch === undefined) return base;
|
|
467
|
+
if (!isPlain(base) || !isPlain(patch)) return patch;
|
|
468
|
+
const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
|
|
469
|
+
return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* A frozen copy of plain data: strings, numbers, booleans, null, plain objects and arrays. Anything else (a Date, a Map,
|
|
474
|
+
* a client, a class) is rejected with its path, so settings can't change under everyone else or hide behavior.
|
|
475
|
+
*/
|
|
476
|
+
function freezeConfig(value: unknown, path = "config"): unknown {
|
|
477
|
+
if (value === null || ["string", "number", "boolean", "undefined"].includes(typeof value)) return value;
|
|
478
|
+
if (Array.isArray(value)) return Object.freeze(value.map((v, i) => freezeConfig(v, `${path}[${i}]`)));
|
|
479
|
+
if (isPlain(value))
|
|
480
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).map(([k, v]) => [k, freezeConfig(v, `${path}.${k}`)])));
|
|
481
|
+
const what = typeof value === "function" ? "a function" : (value as object).constructor?.name ?? typeof value;
|
|
482
|
+
throw new Error(
|
|
483
|
+
`[logic-sdk] ${path} is ${what}. config holds plain data (strings, numbers, booleans, null, objects, arrays): ` +
|
|
484
|
+
"pass a Date as an ISO string, and put clients in services.",
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
|
|
426
488
|
const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
|
|
427
489
|
issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
|
|
428
490
|
|
|
@@ -452,11 +514,12 @@ export function describeModules(modules: Record<string, object>) {
|
|
|
452
514
|
return { ids, functions, events, listeners };
|
|
453
515
|
}
|
|
454
516
|
|
|
455
|
-
function build<S extends object, Mods extends Record<string, object
|
|
517
|
+
function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(options: RegistryOptions<Mods>, o: Overrides) {
|
|
456
518
|
const { ids, functions, events, listeners } = describeModules(options.modules);
|
|
457
519
|
|
|
458
520
|
const database = o.database ?? options.database;
|
|
459
521
|
const services = o.services ?? options.services ?? {};
|
|
522
|
+
const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
|
|
460
523
|
const dispatcher = o.events ?? options.events ?? inProcess();
|
|
461
524
|
const now = o.now ?? options.now ?? (() => new Date());
|
|
462
525
|
const wrap = options.wrap ?? ((_c, next) => next());
|
|
@@ -518,7 +581,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
518
581
|
const failures: { listener: string; error: unknown }[] = [];
|
|
519
582
|
const event = eventByName.get(envelope.name);
|
|
520
583
|
for (const l of byEvent.get(envelope.name) ?? []) {
|
|
521
|
-
const frame: Frame = { scope: envelope.scope, depth: 0,
|
|
584
|
+
const frame: Frame = { scope: envelope.scope, depth: 0, eventDepth };
|
|
522
585
|
try {
|
|
523
586
|
await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
|
|
524
587
|
const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
|
|
@@ -547,18 +610,23 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
547
610
|
}
|
|
548
611
|
|
|
549
612
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
550
|
-
|
|
551
|
-
const
|
|
613
|
+
/** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
|
|
614
|
+
const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
|
|
615
|
+
...frame,
|
|
616
|
+
depth: frame.depth + 1,
|
|
617
|
+
scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
|
|
618
|
+
signal: options?.signal ?? frame.signal,
|
|
619
|
+
abortOn: options?.signal,
|
|
620
|
+
});
|
|
552
621
|
|
|
553
622
|
function queryCtx(frame: Frame, id: string): QueryCtx<any> {
|
|
554
623
|
return {
|
|
555
624
|
errors: errorsFor(id),
|
|
556
625
|
scope: frame.scope,
|
|
626
|
+
config: config as any,
|
|
557
627
|
now,
|
|
558
|
-
signal: frame.opts.signal,
|
|
559
628
|
db: frame.tx ? frame.tx.db : database?.db,
|
|
560
|
-
run: (fn, input) => invoke(fn, input,
|
|
561
|
-
with: (patch) => queryCtx(rescope(frame, patch), id),
|
|
629
|
+
run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
|
|
562
630
|
};
|
|
563
631
|
}
|
|
564
632
|
function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
|
|
@@ -566,10 +634,10 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
566
634
|
return {
|
|
567
635
|
errors: errorsFor(id),
|
|
568
636
|
scope: frame.scope,
|
|
637
|
+
config: config as any,
|
|
569
638
|
now,
|
|
570
|
-
signal: frame.opts.signal,
|
|
571
639
|
db: tx.db,
|
|
572
|
-
run: (fn, input) => invoke(fn, input,
|
|
640
|
+
run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
|
|
573
641
|
emit: (event, payload) => {
|
|
574
642
|
const name = idOf(event);
|
|
575
643
|
payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
|
|
@@ -586,18 +654,17 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
586
654
|
check.catch(() => {}); // surfaced at commit; never an unhandled rejection
|
|
587
655
|
tx.pending.push(check);
|
|
588
656
|
},
|
|
589
|
-
with: (patch) => mutationCtx(rescope(frame, patch), id),
|
|
590
657
|
};
|
|
591
658
|
}
|
|
592
659
|
function actionCtx(frame: Frame, id: string): ActionCtx<any> {
|
|
593
660
|
return {
|
|
594
661
|
errors: errorsFor(id),
|
|
595
662
|
scope: frame.scope,
|
|
663
|
+
config: config as any,
|
|
596
664
|
now,
|
|
597
|
-
signal: frame.
|
|
665
|
+
signal: frame.signal,
|
|
598
666
|
services,
|
|
599
|
-
run: (fn, input) => invoke(fn, input,
|
|
600
|
-
with: (patch) => actionCtx(rescope(frame, patch), id),
|
|
667
|
+
run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
|
|
601
668
|
};
|
|
602
669
|
}
|
|
603
670
|
|
|
@@ -611,7 +678,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
611
678
|
|
|
612
679
|
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
613
680
|
const prepare = async () => {
|
|
614
|
-
frame.
|
|
681
|
+
frame.abortOn?.throwIfAborted();
|
|
615
682
|
if (fn.authorize) {
|
|
616
683
|
const allowed: unknown = fn.authorize(frame.scope);
|
|
617
684
|
if (allowed instanceof Promise || typeof (allowed as any)?.then === "function")
|
|
@@ -682,7 +749,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
682
749
|
async function afterCommit(outbox: Envelope[], frame: Frame) {
|
|
683
750
|
try {
|
|
684
751
|
for (const e of outbox) o.record?.(e);
|
|
685
|
-
const eventDepth = (frame.
|
|
752
|
+
const eventDepth = (frame.eventDepth ?? 0) + 1;
|
|
686
753
|
if (eventDepth > maxEventDepth) {
|
|
687
754
|
report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
|
|
688
755
|
listener: "(dispatcher)",
|
|
@@ -707,11 +774,11 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
707
774
|
}
|
|
708
775
|
}
|
|
709
776
|
|
|
710
|
-
function makeCaller(scope: S
|
|
777
|
+
function makeCaller(scope: S): Caller<S> {
|
|
711
778
|
return {
|
|
712
779
|
scope,
|
|
713
|
-
run: (fn, input) =>
|
|
714
|
-
|
|
780
|
+
run: (fn, input, options) =>
|
|
781
|
+
invoke(fn, input, enter({ scope, depth: -1 }, options as RunOptions | undefined), ["query", "mutation", "action"]), // depth 0
|
|
715
782
|
};
|
|
716
783
|
}
|
|
717
784
|
|
|
@@ -719,7 +786,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
719
786
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
720
787
|
modules: options.modules,
|
|
721
788
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
722
|
-
as: (scope: S
|
|
789
|
+
as: (scope: S): Caller<S> => makeCaller(scope),
|
|
723
790
|
/** Everything the registry can do. Adapters read this. */
|
|
724
791
|
functions: functions as readonly RegisteredFn[],
|
|
725
792
|
events: events as readonly (Registered & { event: EventDef })[],
|
|
@@ -728,9 +795,14 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
728
795
|
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
729
796
|
dispatch,
|
|
730
797
|
/** @internal used by `logic-sdk/testing` */
|
|
731
|
-
[INTERNAL]: {
|
|
798
|
+
[INTERNAL]: {
|
|
799
|
+
options,
|
|
800
|
+
overrides: o,
|
|
801
|
+
config,
|
|
802
|
+
derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) as object | undefined }),
|
|
803
|
+
},
|
|
732
804
|
};
|
|
733
805
|
}
|
|
734
806
|
|
|
735
807
|
/** @internal */
|
|
736
|
-
export const internal = (registry: Registry<any, any>) => registry[INTERNAL];
|
|
808
|
+
export const internal = (registry: Registry<any, any, any>) => registry[INTERNAL];
|
package/src/orpc.ts
CHANGED
|
@@ -48,9 +48,9 @@ export function toORPCRouter<S extends object, Mods extends Record<string, objec
|
|
|
48
48
|
if (!f.exposed) continue;
|
|
49
49
|
let b = base.input(f.fn.inputSchema as StandardSchemaV1);
|
|
50
50
|
if (f.fn.outputSchema) b = b.output(f.fn.outputSchema as StandardSchemaV1) as any;
|
|
51
|
-
(router[f.module] ??= {})[f.name] = b.handler(async ({ input, context }) => {
|
|
51
|
+
(router[f.module] ??= {})[f.name] = b.handler(async ({ input, context, signal }) => {
|
|
52
52
|
try {
|
|
53
|
-
return await context.caller.run(f.fn, input);
|
|
53
|
+
return await context.caller.run(f.fn, input, { signal });
|
|
54
54
|
} catch (e) {
|
|
55
55
|
if (isDomainError(e))
|
|
56
56
|
throw new ORPCError(orpcCodeOf[e.kind], {
|
package/src/testing.ts
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
|
-
import { internal, type Caller, type
|
|
1
|
+
import { internal, type Caller, type DeepPartial, type Envelope, type Fn, type FnIn, type FnOut, type Registry } from "./index.ts";
|
|
2
2
|
|
|
3
|
-
export interface TestOptions {
|
|
3
|
+
export interface TestOptions<Cf = unknown> {
|
|
4
4
|
/** Replace services (e.g. `{ mailer: memoryMailer() }`). */
|
|
5
5
|
services?: object;
|
|
6
|
+
/** Override parts of `config` (e.g. `{ orders: { maxItems: 1 } }`). Merged over the registry's, section by section. */
|
|
7
|
+
config?: DeepPartial<Cf>;
|
|
6
8
|
/** Freeze time. */
|
|
7
9
|
now?: Date | string | (() => Date);
|
|
8
10
|
/** Run listeners inline after each mutation (default), or not at all to test one module in isolation. */
|
|
9
11
|
listeners?: boolean;
|
|
10
12
|
}
|
|
11
13
|
|
|
12
|
-
export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object
|
|
14
|
+
export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
|
|
13
15
|
/** Bind who is calling, exactly like `registry.as(...)`. */
|
|
14
|
-
as(scope: S
|
|
16
|
+
as(scope: S): Caller<S>;
|
|
15
17
|
/** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
|
|
16
18
|
stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
|
|
17
19
|
/** Every event emitted (and committed) so far, in order. */
|
|
@@ -19,7 +21,7 @@ export interface TestTransaction<S extends object, Mods extends Record<string, o
|
|
|
19
21
|
/** The test transaction itself: read rows to assert on them. */
|
|
20
22
|
readonly db: any;
|
|
21
23
|
/** The registry bound to this test transaction, for adapters: `toFetchHandler(tx.registry, …)`. */
|
|
22
|
-
readonly registry: Registry<S, Mods>;
|
|
24
|
+
readonly registry: Registry<S, Mods, Cf>;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
class Rollback extends Error {}
|
|
@@ -29,9 +31,9 @@ class Rollback extends Error {}
|
|
|
29
31
|
* Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes,
|
|
30
32
|
* like it would in production. Run top-level mutations one at a time inside a test (one connection, nested savepoints).
|
|
31
33
|
*/
|
|
32
|
-
export function createTestRegistry<S extends object, Mods extends Record<string, object
|
|
33
|
-
registry: Registry<S, Mods>,
|
|
34
|
-
options: TestOptions = {},
|
|
34
|
+
export function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf>(
|
|
35
|
+
registry: Registry<S, Mods, Cf>,
|
|
36
|
+
options: TestOptions<Cf> = {},
|
|
35
37
|
) {
|
|
36
38
|
const { options: registryOptions } = internal(registry);
|
|
37
39
|
const now =
|
|
@@ -45,7 +47,7 @@ export function createTestRegistry<S extends object, Mods extends Record<string,
|
|
|
45
47
|
})();
|
|
46
48
|
|
|
47
49
|
return {
|
|
48
|
-
async transaction<T>(fn: (t: TestTransaction<S, Mods>) => Promise<T>): Promise<T> {
|
|
50
|
+
async transaction<T>(fn: (t: TestTransaction<S, Mods, Cf>) => Promise<T>): Promise<T> {
|
|
49
51
|
const database = registryOptions.database;
|
|
50
52
|
let result!: T;
|
|
51
53
|
|
|
@@ -55,13 +57,14 @@ export function createTestRegistry<S extends object, Mods extends Record<string,
|
|
|
55
57
|
const derived = internal(registry).derive({
|
|
56
58
|
database: outer !== undefined && database?.nest ? database.nest(outer) : database,
|
|
57
59
|
services: options.services,
|
|
60
|
+
config: options.config as object | undefined,
|
|
58
61
|
now,
|
|
59
62
|
stubs,
|
|
60
63
|
record: (e) => events.push(e),
|
|
61
64
|
events: options.listeners === false ? { deliver: async () => {} } : undefined,
|
|
62
|
-
}) as Registry<S, Mods>;
|
|
65
|
+
}) as Registry<S, Mods, Cf>;
|
|
63
66
|
result = await fn({
|
|
64
|
-
as: (scope
|
|
67
|
+
as: (scope) => derived.as(scope),
|
|
65
68
|
stub: (f, impl) => void stubs.set(f, impl as (input: any, ctx: any) => Promise<any>),
|
|
66
69
|
events,
|
|
67
70
|
db: outer,
|