logic-sdk 0.1.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 +20 -16
- package/dist/ai.d.ts +20 -7
- package/dist/ai.js +36 -24
- package/dist/fetch.d.ts +7 -5
- package/dist/fetch.js +8 -9
- package/dist/index.d.ts +116 -72
- package/dist/index.js +97 -49
- package/dist/orpc.d.ts +1 -1
- package/dist/orpc.js +2 -2
- package/dist/testing.d.ts +9 -7
- package/dist/testing.js +2 -1
- package/package.json +8 -8
- package/src/ai.ts +48 -28
- package/src/fetch.ts +10 -12
- package/src/index.ts +202 -113
- package/src/orpc.ts +3 -3
- package/src/testing.ts +14 -11
package/src/index.ts
CHANGED
|
@@ -7,7 +7,6 @@ import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
|
7
7
|
type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
|
|
8
8
|
type In<S> = S extends Schema<infer I, any> ? I : never;
|
|
9
9
|
type Out<S> = S extends Schema<any, infer O> ? O : never;
|
|
10
|
-
type Awaitable<T> = T | Promise<T>;
|
|
11
10
|
|
|
12
11
|
/** What you declare once in `init<...>()`. */
|
|
13
12
|
export interface Config {
|
|
@@ -19,6 +18,11 @@ export interface Config {
|
|
|
19
18
|
reader?: unknown;
|
|
20
19
|
/** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
|
|
21
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;
|
|
22
26
|
/** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
|
|
23
27
|
meta?: object;
|
|
24
28
|
}
|
|
@@ -27,6 +31,18 @@ type DbOf<C extends Config> = C extends { db: infer D } ? D : never;
|
|
|
27
31
|
type ReaderOf<C extends Config> = C extends { reader: infer R } ? R : DbOf<C>;
|
|
28
32
|
type ServicesOf<C extends Config> = C extends { services: infer S } ? S : {};
|
|
29
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]> };
|
|
30
46
|
|
|
31
47
|
export type Kind = "query" | "mutation" | "action";
|
|
32
48
|
|
|
@@ -42,13 +58,15 @@ export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean =
|
|
|
42
58
|
readonly outputSchema?: Schema;
|
|
43
59
|
/** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
|
|
44
60
|
readonly meta?: any;
|
|
45
|
-
/**
|
|
46
|
-
readonly
|
|
61
|
+
/** Who may call it (from `authorize`). Runs on every call, before validation. */
|
|
62
|
+
readonly authorize?: Policy<any>;
|
|
63
|
+
/** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
|
|
64
|
+
readonly expose?: true;
|
|
47
65
|
readonly execute: (input: any, ctx: any) => Promise<any>;
|
|
48
66
|
/** Phantom types, never set at runtime. */
|
|
49
67
|
readonly [types]?: { input: I; output: O; exposed: E };
|
|
50
68
|
}
|
|
51
|
-
/** A function with `expose`: adapters publish it. */
|
|
69
|
+
/** A function with `expose: true`: adapters may publish it. */
|
|
52
70
|
export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
|
|
53
71
|
/** What callers pass to a function. */
|
|
54
72
|
export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
|
|
@@ -85,14 +103,27 @@ export interface Listener<O = any> {
|
|
|
85
103
|
readonly execute: (payload: O, ctx: any) => Promise<unknown>;
|
|
86
104
|
}
|
|
87
105
|
|
|
88
|
-
|
|
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>>;
|
|
89
120
|
|
|
90
121
|
/**
|
|
91
|
-
* Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.reject("not_pending")` has
|
|
122
|
+
* Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
|
|
92
123
|
* code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
|
|
93
124
|
*/
|
|
94
|
-
interface
|
|
95
|
-
/** A business rule said no, and trying again won't help. `throw ctx.reject("not_pending", { status })` */
|
|
125
|
+
export interface Errors {
|
|
126
|
+
/** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
|
|
96
127
|
reject(code: string, details?: unknown): DomainError;
|
|
97
128
|
/** Someone else got there first, or it already exists. Refreshing and retrying may work. */
|
|
98
129
|
conflict(code: string, details?: unknown): DomainError;
|
|
@@ -101,46 +132,49 @@ interface Fail {
|
|
|
101
132
|
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
|
|
102
133
|
deny(code?: string, details?: unknown): DomainError;
|
|
103
134
|
}
|
|
104
|
-
interface BaseCtx<
|
|
135
|
+
interface BaseCtx<C extends Config, S> {
|
|
105
136
|
scope: S;
|
|
137
|
+
/** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
|
|
138
|
+
config: Frozen<ConfigOf<C>>;
|
|
139
|
+
/** Expected failures: `throw ctx.errors.reject("not_pending")`. */
|
|
140
|
+
errors: Errors;
|
|
106
141
|
/** Current time. Fixed in tests. */
|
|
107
142
|
now: () => Date;
|
|
108
143
|
}
|
|
109
144
|
/** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
|
|
110
|
-
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> {
|
|
111
146
|
db: ReaderOf<C>;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
signal: AbortSignal | undefined;
|
|
115
|
-
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>>;
|
|
116
149
|
}
|
|
117
|
-
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> {
|
|
118
151
|
db: DbOf<C>;
|
|
119
|
-
|
|
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>>;
|
|
120
157
|
/** Queue an event. Delivered to listeners only after the transaction commits. */
|
|
121
158
|
emit<I>(event: EventDef<I, any>, payload: I): void;
|
|
122
|
-
signal: AbortSignal | undefined;
|
|
123
|
-
with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
|
|
124
159
|
}
|
|
125
|
-
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> {
|
|
126
161
|
services: ServicesOf<C>;
|
|
127
|
-
/** Each mutation you run
|
|
128
|
-
run: Run<Kind
|
|
129
|
-
/** 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). */
|
|
130
165
|
signal: AbortSignal | undefined;
|
|
131
|
-
with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
|
|
132
166
|
}
|
|
133
167
|
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
134
168
|
event: Envelope<unknown, ScopeOf<C>> & { payload: O };
|
|
135
169
|
}
|
|
136
170
|
|
|
137
|
-
/**
|
|
171
|
+
/**
|
|
172
|
+
* Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
|
|
173
|
+
* Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
|
|
174
|
+
* Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
|
|
175
|
+
*/
|
|
138
176
|
export type Policy<S> = (scope: S) => boolean;
|
|
139
177
|
type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
|
|
140
|
-
type Inline<C extends Config, IS extends Schema> = (scope: ScopeOf<C>, input: Out<IS>) => Awaitable<boolean>;
|
|
141
|
-
/** A policy name from `init`, or an inline check that also sees the input. */
|
|
142
|
-
type Exposure<C extends Config, P, IS extends Schema> = (keyof P & string) | Inline<C, IS>;
|
|
143
|
-
type ScopeFor<C extends Config, P, E> = E extends keyof P ? Guarded<P[E], ScopeOf<C>> : ScopeOf<C>;
|
|
144
178
|
type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
|
|
145
179
|
? QueryCtx<C, S>
|
|
146
180
|
: K extends "mutation"
|
|
@@ -153,19 +187,31 @@ type Def<IS extends Schema, Ctx, R> = {
|
|
|
153
187
|
inputSchema: IS;
|
|
154
188
|
execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
|
|
155
189
|
};
|
|
156
|
-
type
|
|
190
|
+
type NotExposed = { expose?: undefined };
|
|
191
|
+
type NoPolicy = { authorize?: undefined };
|
|
157
192
|
type WithMeta<C extends Config> = { meta?: MetaOf<C> };
|
|
158
193
|
type WithOutput<OS extends Schema> = { outputSchema: OS };
|
|
159
194
|
|
|
160
|
-
/**
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
195
|
+
/**
|
|
196
|
+
* `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
|
|
197
|
+
* and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
|
|
198
|
+
*/
|
|
199
|
+
interface Constructor<C extends Config, K extends Kind> {
|
|
200
|
+
<IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
|
|
201
|
+
def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> &
|
|
202
|
+
WithOutput<OS> &
|
|
203
|
+
WithMeta<C> & { authorize: P; expose: true },
|
|
164
204
|
): Fn<K, In<IS>, Out<OS>, true>;
|
|
205
|
+
<IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
|
|
206
|
+
def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { authorize: P } & NotExposed,
|
|
207
|
+
): Fn<K, In<IS>, Out<OS>, false>;
|
|
208
|
+
<IS extends Schema, R, P extends Policy<ScopeOf<C>>>(
|
|
209
|
+
def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & { authorize: P } & NotExposed,
|
|
210
|
+
): Fn<K, In<IS>, R, false>;
|
|
165
211
|
<IS extends Schema, OS extends Schema>(
|
|
166
|
-
def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> &
|
|
212
|
+
def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed,
|
|
167
213
|
): Fn<K, In<IS>, Out<OS>, false>;
|
|
168
|
-
<IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> &
|
|
214
|
+
<IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
|
|
169
215
|
}
|
|
170
216
|
|
|
171
217
|
/* ────────────────────────────────────────────────────────────────────────────
|
|
@@ -192,15 +238,12 @@ export class DomainError extends Error {
|
|
|
192
238
|
this.details = details;
|
|
193
239
|
}
|
|
194
240
|
}
|
|
195
|
-
/** For the edge (`resolveScope`): no valid session. Inside modules, use `ctx.deny()`. */
|
|
196
|
-
export const unauthenticated = (code = "unauthenticated", details?: unknown) =>
|
|
197
|
-
new DomainError("unauthenticated", code, details);
|
|
198
241
|
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
199
242
|
export const isDomainError = (e: unknown, code?: string): e is DomainError =>
|
|
200
243
|
e instanceof DomainError && (code === undefined || e.code === code);
|
|
201
244
|
|
|
202
|
-
/** `ctx.
|
|
203
|
-
const
|
|
245
|
+
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
246
|
+
const errorsFor = (id: string): Errors => {
|
|
204
247
|
const module = id.slice(0, id.indexOf("."));
|
|
205
248
|
return {
|
|
206
249
|
reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
|
|
@@ -255,6 +298,8 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
255
298
|
modules: Mods;
|
|
256
299
|
database?: DatabaseAdapter<any, any>;
|
|
257
300
|
services?: object;
|
|
301
|
+
/** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
|
|
302
|
+
config?: object;
|
|
258
303
|
events?: Dispatcher;
|
|
259
304
|
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
260
305
|
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
@@ -277,16 +322,11 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
277
322
|
retry?: { attempts?: number };
|
|
278
323
|
}
|
|
279
324
|
|
|
280
|
-
|
|
281
|
-
/** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
|
|
282
|
-
signal?: AbortSignal;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
/** A registry bound to a scope: `const caller = registry.as(scope)`. */
|
|
325
|
+
/** A registry bound to who is calling: `const caller = registry.as(scope)`. */
|
|
286
326
|
export interface Caller<S extends object = object> {
|
|
287
327
|
readonly scope: S;
|
|
288
|
-
|
|
289
|
-
|
|
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>>;
|
|
290
330
|
}
|
|
291
331
|
|
|
292
332
|
export interface Registered {
|
|
@@ -297,7 +337,7 @@ export interface Registered {
|
|
|
297
337
|
export interface RegisteredFn extends Registered {
|
|
298
338
|
fn: Fn;
|
|
299
339
|
kind: Kind;
|
|
300
|
-
/** Has `expose`: adapters publish it. */
|
|
340
|
+
/** Has `expose: true`: adapters may publish it. */
|
|
301
341
|
exposed: boolean;
|
|
302
342
|
}
|
|
303
343
|
|
|
@@ -310,53 +350,49 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
|
|
|
310
350
|
wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
|
|
311
351
|
} &
|
|
312
352
|
({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
|
|
353
|
+
({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
|
|
313
354
|
([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
|
|
314
355
|
|
|
356
|
+
/** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
|
|
357
|
+
type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
|
|
358
|
+
|
|
315
359
|
/**
|
|
316
|
-
* Typed constructors for your app
|
|
360
|
+
* Typed constructors for your app:
|
|
317
361
|
*
|
|
318
362
|
* ```ts
|
|
319
|
-
* export const { query, mutation, action, event, on, createRegistry } = init<Config>()
|
|
320
|
-
* policies: { public: () => true, staff: (s): s is Staff => isStaff(s) },
|
|
321
|
-
* });
|
|
363
|
+
* export const { query, mutation, action, event, on, createRegistry } = init<Config>();
|
|
322
364
|
* ```
|
|
323
365
|
*/
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
export function init<C extends Config & OnlyKnownKeys<C>>(): Init<C> {
|
|
328
|
-
return ((options?: { policies?: Record<string, Policy<any>> }) => constructors<C, {}>(options?.policies ?? {})) as Init<C>;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
interface Init<C extends Config> {
|
|
332
|
-
(): Constructors<C, {}>;
|
|
333
|
-
<P extends Record<string, Policy<ScopeOf<C>>>>(options: { policies: P }): Constructors<C, P>;
|
|
366
|
+
export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
367
|
+
return constructors<C>();
|
|
334
368
|
}
|
|
335
|
-
type Constructors<C extends Config, P> = ReturnType<typeof constructors<C, P>>;
|
|
336
369
|
|
|
337
|
-
function constructors<C extends Config
|
|
370
|
+
function constructors<C extends Config>() {
|
|
338
371
|
const make =
|
|
339
372
|
<K extends Kind>(kind: K) =>
|
|
340
|
-
(
|
|
341
|
-
|
|
342
|
-
if (typeof
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
373
|
+
(def: any): any => {
|
|
374
|
+
const where = def?.description ? `"${def.description}"` : `a ${kind}`;
|
|
375
|
+
if (def.authorize !== undefined && typeof def.authorize !== "function")
|
|
376
|
+
throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
|
|
377
|
+
if (def.expose !== undefined && def.expose !== true)
|
|
378
|
+
throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
|
|
379
|
+
if (def.expose && !def.authorize)
|
|
380
|
+
throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
|
|
381
|
+
if (def.expose && !def.outputSchema)
|
|
382
|
+
throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
|
|
383
|
+
return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
|
|
348
384
|
};
|
|
349
385
|
|
|
350
386
|
return {
|
|
351
387
|
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
352
388
|
createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
|
|
353
|
-
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
|
|
354
390
|
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
355
|
-
query: make("query") as Constructor<C, "query"
|
|
391
|
+
query: make("query") as Constructor<C, "query">,
|
|
356
392
|
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
357
|
-
mutation: make("mutation") as Constructor<C, "mutation"
|
|
393
|
+
mutation: make("mutation") as Constructor<C, "mutation">,
|
|
358
394
|
/** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
|
|
359
|
-
action: make("action") as Constructor<C, "action"
|
|
395
|
+
action: make("action") as Constructor<C, "action">,
|
|
360
396
|
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
361
397
|
event: <S extends Schema>(def: { schema: S; description?: string }): EventDef<In<S>, Out<S>> =>
|
|
362
398
|
Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
|
|
@@ -392,21 +428,27 @@ interface TxState {
|
|
|
392
428
|
interface Frame {
|
|
393
429
|
scope: object;
|
|
394
430
|
depth: number;
|
|
395
|
-
|
|
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;
|
|
396
436
|
tx?: TxState;
|
|
397
437
|
}
|
|
398
438
|
|
|
399
439
|
export interface Overrides {
|
|
400
440
|
database?: DatabaseAdapter<any, any>;
|
|
401
441
|
services?: object;
|
|
442
|
+
/** Merged over the registry's config, section by section. */
|
|
443
|
+
config?: object;
|
|
402
444
|
events?: Dispatcher;
|
|
403
445
|
now?: () => Date;
|
|
404
446
|
stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
|
|
405
447
|
record?: (envelope: Envelope) => void;
|
|
406
448
|
}
|
|
407
449
|
|
|
408
|
-
export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object
|
|
409
|
-
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>
|
|
410
452
|
>;
|
|
411
453
|
|
|
412
454
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
@@ -416,6 +458,33 @@ export function createRegistry<S extends object = object, const Mods extends Rec
|
|
|
416
458
|
return build<S, Mods>(options, {});
|
|
417
459
|
}
|
|
418
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
|
+
|
|
419
488
|
const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
|
|
420
489
|
issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
|
|
421
490
|
|
|
@@ -439,17 +508,18 @@ export function describeModules(modules: Record<string, object>) {
|
|
|
439
508
|
else if (kind === "listener") {
|
|
440
509
|
const listener = value as Listener;
|
|
441
510
|
listeners.push({ id, module, name, listener, event: listener.event() });
|
|
442
|
-
} else functions.push({ id, module, name, kind, fn: value as Fn, exposed:
|
|
511
|
+
} else functions.push({ id, module, name, kind, fn: value as Fn, exposed: (value as Fn).expose === true });
|
|
443
512
|
}
|
|
444
513
|
}
|
|
445
514
|
return { ids, functions, events, listeners };
|
|
446
515
|
}
|
|
447
516
|
|
|
448
|
-
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) {
|
|
449
518
|
const { ids, functions, events, listeners } = describeModules(options.modules);
|
|
450
519
|
|
|
451
520
|
const database = o.database ?? options.database;
|
|
452
521
|
const services = o.services ?? options.services ?? {};
|
|
522
|
+
const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
|
|
453
523
|
const dispatcher = o.events ?? options.events ?? inProcess();
|
|
454
524
|
const now = o.now ?? options.now ?? (() => new Date());
|
|
455
525
|
const wrap = options.wrap ?? ((_c, next) => next());
|
|
@@ -476,14 +546,20 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
476
546
|
|
|
477
547
|
const idOf = (x: object) => {
|
|
478
548
|
const id = ids.get(x);
|
|
479
|
-
if (!id)
|
|
549
|
+
if (!id)
|
|
550
|
+
throw new Error(
|
|
551
|
+
"[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }).",
|
|
552
|
+
);
|
|
480
553
|
return id;
|
|
481
554
|
};
|
|
482
555
|
|
|
483
|
-
|
|
556
|
+
/** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
|
|
557
|
+
async function parseInput(schema: Schema, value: unknown, id: string, nested: boolean) {
|
|
484
558
|
const r = await schema["~standard"].validate(value);
|
|
485
|
-
if (r.issues)
|
|
486
|
-
|
|
559
|
+
if (!r.issues) return r.value;
|
|
560
|
+
const issues = describeIssues(r.issues);
|
|
561
|
+
if (nested) throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
|
|
562
|
+
throw new DomainError("invalid", `${id}.invalid_input`, { issues });
|
|
487
563
|
}
|
|
488
564
|
/** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
|
|
489
565
|
async function parseOwn(schema: Schema, value: unknown, what: string) {
|
|
@@ -505,7 +581,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
505
581
|
const failures: { listener: string; error: unknown }[] = [];
|
|
506
582
|
const event = eventByName.get(envelope.name);
|
|
507
583
|
for (const l of byEvent.get(envelope.name) ?? []) {
|
|
508
|
-
const frame: Frame = { scope: envelope.scope, depth: 0,
|
|
584
|
+
const frame: Frame = { scope: envelope.scope, depth: 0, eventDepth };
|
|
509
585
|
try {
|
|
510
586
|
await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
|
|
511
587
|
const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
|
|
@@ -534,29 +610,34 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
534
610
|
}
|
|
535
611
|
|
|
536
612
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
537
|
-
|
|
538
|
-
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
|
+
});
|
|
539
621
|
|
|
540
622
|
function queryCtx(frame: Frame, id: string): QueryCtx<any> {
|
|
541
623
|
return {
|
|
542
|
-
|
|
624
|
+
errors: errorsFor(id),
|
|
543
625
|
scope: frame.scope,
|
|
626
|
+
config: config as any,
|
|
544
627
|
now,
|
|
545
|
-
signal: frame.opts.signal,
|
|
546
628
|
db: frame.tx ? frame.tx.db : database?.db,
|
|
547
|
-
run: (fn, input) => invoke(fn, input,
|
|
548
|
-
with: (patch) => queryCtx(rescope(frame, patch), id),
|
|
629
|
+
run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
|
|
549
630
|
};
|
|
550
631
|
}
|
|
551
632
|
function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
|
|
552
633
|
const tx = frame.tx!;
|
|
553
634
|
return {
|
|
554
|
-
|
|
635
|
+
errors: errorsFor(id),
|
|
555
636
|
scope: frame.scope,
|
|
637
|
+
config: config as any,
|
|
556
638
|
now,
|
|
557
|
-
signal: frame.opts.signal,
|
|
558
639
|
db: tx.db,
|
|
559
|
-
run: (fn, input) => invoke(fn, input,
|
|
640
|
+
run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
|
|
560
641
|
emit: (event, payload) => {
|
|
561
642
|
const name = idOf(event);
|
|
562
643
|
payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
|
|
@@ -573,18 +654,17 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
573
654
|
check.catch(() => {}); // surfaced at commit; never an unhandled rejection
|
|
574
655
|
tx.pending.push(check);
|
|
575
656
|
},
|
|
576
|
-
with: (patch) => mutationCtx(rescope(frame, patch), id),
|
|
577
657
|
};
|
|
578
658
|
}
|
|
579
659
|
function actionCtx(frame: Frame, id: string): ActionCtx<any> {
|
|
580
660
|
return {
|
|
581
|
-
|
|
661
|
+
errors: errorsFor(id),
|
|
582
662
|
scope: frame.scope,
|
|
663
|
+
config: config as any,
|
|
583
664
|
now,
|
|
584
|
-
signal: frame.
|
|
665
|
+
signal: frame.signal,
|
|
585
666
|
services,
|
|
586
|
-
run: (fn, input) => invoke(fn, input,
|
|
587
|
-
with: (patch) => actionCtx(rescope(frame, patch), id),
|
|
667
|
+
run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
|
|
588
668
|
};
|
|
589
669
|
}
|
|
590
670
|
|
|
@@ -596,12 +676,16 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
596
676
|
|
|
597
677
|
const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
|
|
598
678
|
|
|
599
|
-
/**
|
|
679
|
+
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
600
680
|
const prepare = async () => {
|
|
601
|
-
frame.
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
681
|
+
frame.abortOn?.throwIfAborted();
|
|
682
|
+
if (fn.authorize) {
|
|
683
|
+
const allowed: unknown = fn.authorize(frame.scope);
|
|
684
|
+
if (allowed instanceof Promise || typeof (allowed as any)?.then === "function")
|
|
685
|
+
throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
|
|
686
|
+
if (allowed !== true) throw new DomainError("forbidden", `${id}.forbidden`);
|
|
687
|
+
}
|
|
688
|
+
return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
|
|
605
689
|
};
|
|
606
690
|
const execute = async (input: unknown, ctx: unknown) => {
|
|
607
691
|
const stub = o.stubs?.get(fn);
|
|
@@ -665,7 +749,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
665
749
|
async function afterCommit(outbox: Envelope[], frame: Frame) {
|
|
666
750
|
try {
|
|
667
751
|
for (const e of outbox) o.record?.(e);
|
|
668
|
-
const eventDepth = (frame.
|
|
752
|
+
const eventDepth = (frame.eventDepth ?? 0) + 1;
|
|
669
753
|
if (eventDepth > maxEventDepth) {
|
|
670
754
|
report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
|
|
671
755
|
listener: "(dispatcher)",
|
|
@@ -690,11 +774,11 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
690
774
|
}
|
|
691
775
|
}
|
|
692
776
|
|
|
693
|
-
function makeCaller(scope: S
|
|
777
|
+
function makeCaller(scope: S): Caller<S> {
|
|
694
778
|
return {
|
|
695
779
|
scope,
|
|
696
|
-
run: (fn, input) =>
|
|
697
|
-
|
|
780
|
+
run: (fn, input, options) =>
|
|
781
|
+
invoke(fn, input, enter({ scope, depth: -1 }, options as RunOptions | undefined), ["query", "mutation", "action"]), // depth 0
|
|
698
782
|
};
|
|
699
783
|
}
|
|
700
784
|
|
|
@@ -702,7 +786,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
702
786
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
703
787
|
modules: options.modules,
|
|
704
788
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
705
|
-
as: (scope: S
|
|
789
|
+
as: (scope: S): Caller<S> => makeCaller(scope),
|
|
706
790
|
/** Everything the registry can do. Adapters read this. */
|
|
707
791
|
functions: functions as readonly RegisteredFn[],
|
|
708
792
|
events: events as readonly (Registered & { event: EventDef })[],
|
|
@@ -711,9 +795,14 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
|
|
|
711
795
|
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
712
796
|
dispatch,
|
|
713
797
|
/** @internal used by `logic-sdk/testing` */
|
|
714
|
-
[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
|
+
},
|
|
715
804
|
};
|
|
716
805
|
}
|
|
717
806
|
|
|
718
807
|
/** @internal */
|
|
719
|
-
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
|
@@ -10,7 +10,7 @@ type ProcedureOf<S extends object, F> =
|
|
|
10
10
|
? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}>
|
|
11
11
|
: never;
|
|
12
12
|
|
|
13
|
-
/** `{ bookings: { confirm, cancel, … } }`: only functions with `expose`. */
|
|
13
|
+
/** `{ bookings: { confirm, cancel, … } }`: only functions with `expose: true`. */
|
|
14
14
|
export type ORPCRouterOf<S extends object, Mods> = {
|
|
15
15
|
[M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
|
|
16
16
|
[N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
|
|
@@ -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], {
|