logic-sdk 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/errors.d.ts CHANGED
@@ -14,6 +14,12 @@ export declare class DomainError extends Error {
14
14
  }
15
15
  /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
16
16
  export declare const isDomainError: (e: unknown, code?: string) => e is DomainError;
17
+ /** The module part of an id: "bookings" for "bookings.confirm". */
18
+ export declare const moduleOf: (id: string) => string;
19
+ /** How an unnamed private function (one its module's index doesn't export) is named: `files.(private)`. */
20
+ export declare const PRIVATE = "(private)";
21
+ /** What a call its policy refused throws: "bookings.cancel.forbidden", and "files.forbidden" for an unnamed private function. */
22
+ export declare const forbiddenOf: (id: string) => string;
17
23
  /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
18
24
  export declare const errorsFor: (id: string) => Errors;
19
25
  /** What a schema said, as JSON: `[{ message, path }]`. */
package/dist/errors.js CHANGED
@@ -18,14 +18,20 @@ export class DomainError extends Error {
18
18
  }
19
19
  /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
20
20
  export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
21
+ /** The module part of an id: "bookings" for "bookings.confirm". */
22
+ export const moduleOf = (id) => id.slice(0, id.indexOf("."));
23
+ /** How an unnamed private function (one its module's index doesn't export) is named: `files.(private)`. */
24
+ export const PRIVATE = "(private)";
25
+ /** What a call its policy refused throws: "bookings.cancel.forbidden", and "files.forbidden" for an unnamed private function. */
26
+ export const forbiddenOf = (id) => `${id === `${moduleOf(id)}.${PRIVATE}` ? moduleOf(id) : id}.forbidden`;
21
27
  /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
22
28
  export const errorsFor = (id) => {
23
- const module = id.slice(0, id.indexOf("."));
29
+ const module = moduleOf(id);
24
30
  return {
25
31
  reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
26
32
  conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
27
33
  notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
28
- deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
34
+ deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : forbiddenOf(id), details),
29
35
  };
30
36
  };
31
37
  /** What a schema said, as JSON: `[{ message, path }]`. */
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { describeIssues, DomainError, errorsFor } from "./errors.js";
1
+ import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.js";
2
2
  import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.js";
3
3
  import { assertTimeZone, parseSchedule } from "./schedule.js";
4
4
  import { BRAND, INTERNAL } from "./types.js";
@@ -186,9 +186,10 @@ function build(options, o) {
186
186
  console.error("[logic-sdk] onError threw", inner, "while reporting", e);
187
187
  }
188
188
  };
189
+ const noDatabase = "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
190
+ "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.";
189
191
  if (!database && functions.some((f) => f.kind === "mutation"))
190
- throw new Error("[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
191
- "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.");
192
+ throw new Error(noDatabase);
192
193
  for (const l of listeners)
193
194
  if (!ids.has(l.event))
194
195
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
@@ -196,7 +197,8 @@ function build(options, o) {
196
197
  const idOf = (x) => {
197
198
  const id = ids.get(x);
198
199
  if (!id)
199
- throw new Error("[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }).");
200
+ throw new Error("[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }). " +
201
+ "A private function (one the index doesn't export) runs only through ctx.run, from its own module.");
200
202
  return id;
201
203
  };
202
204
  /** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
@@ -241,7 +243,7 @@ function build(options, o) {
241
243
  scope: frame.scope,
242
244
  config: config, // Frozen<Cf> here; each app's ctx types it from its own Config
243
245
  now,
244
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed),
246
+ run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed, moduleOf(id)),
245
247
  });
246
248
  const queryCtx = (frame, id) => ({
247
249
  ...baseCtx(frame, id, ["query"]),
@@ -258,7 +260,10 @@ function build(options, o) {
258
260
  checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
259
261
  },
260
262
  schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
261
- const fnId = idOf(fn);
263
+ const fnId = ids.get(fn);
264
+ if (!fnId)
265
+ throw new Error("[logic-sdk] ctx.schedule needs a function its module's index.ts exports: a scheduled call waits as a name, and a worker finds the code by it. " +
266
+ "A private function runs only through ctx.run.");
262
267
  const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
263
268
  if (!Number.isFinite(seconds) || (!at && seconds < 0))
264
269
  throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
@@ -335,8 +340,10 @@ function build(options, o) {
335
340
  listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
336
341
  });
337
342
  // ── invoke ───────────────────────────────────────────────────────────────
338
- async function invoke(fn, rawInput, outer, allowed) {
339
- const id = idOf(fn);
343
+ /** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
344
+ async function invoke(fn, rawInput, outer, allowed, callerModule) {
345
+ // anything else that runs one finds it by name, and it has none: idOf throws, saying so
346
+ const id = ids.get(fn) ?? (callerModule ? `${callerModule}.${fn.id ?? PRIVATE}` : idOf(fn));
340
347
  if (!allowed.includes(fn.kind))
341
348
  throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
342
349
  const depth = outer.trail.length;
@@ -352,7 +359,7 @@ function build(options, o) {
352
359
  if (fn.authorize) {
353
360
  // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
354
361
  if (fn.authorize(frame.scope) !== true)
355
- throw new DomainError("forbidden", `${id}.forbidden`);
362
+ throw new DomainError("forbidden", forbiddenOf(id));
356
363
  }
357
364
  // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
358
365
  return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
@@ -385,11 +392,13 @@ function build(options, o) {
385
392
  }
386
393
  // top-level mutation: open the transaction, commit, then deliver events.
387
394
  // A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
395
+ // createRegistry checks for one, but a private mutation isn't registered, so it can only be checked here
396
+ if (!database)
397
+ throw new Error(noDatabase);
388
398
  const input = await prepare();
389
399
  let committed;
390
400
  for (let attempt = 1;; attempt++) {
391
401
  try {
392
- // SAFETY: createRegistry refuses mutations without a database that has interactive transactions
393
402
  committed = await database.transaction(async (txDb) => {
394
403
  // fresh per attempt, so a retry never reuses events from a failed attempt
395
404
  const tx = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
@@ -405,7 +414,7 @@ function build(options, o) {
405
414
  break;
406
415
  }
407
416
  catch (e) {
408
- if (attempt < transactionAttempts && database.retryable?.(e)) { // SAFETY: as above
417
+ if (attempt < transactionAttempts && database.retryable?.(e)) {
409
418
  // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
410
419
  await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
411
420
  continue;
package/dist/types.d.ts CHANGED
@@ -101,13 +101,16 @@ type FromInit<C extends Config> = {
101
101
  };
102
102
  };
103
103
  /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
104
- export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any> {
104
+ export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any, IS extends Schema | undefined = Schema | undefined> {
105
105
  readonly [BRAND]: K;
106
106
  readonly kind: K;
107
- /** Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name. */
107
+ /**
108
+ * Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name.
109
+ * A private function (the index doesn't export it) is `notifications.(private)` without one.
110
+ */
108
111
  readonly id?: string;
109
- /** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
110
- readonly input?: Schema;
112
+ /** What callers pass, validated on every call, as you wrote it: `fn.input.pick({ name: true })` for a form. Undefined: the function takes nothing (`run(fn)`). */
113
+ readonly input: IS;
111
114
  /** What callers get back, checked before it leaves. */
112
115
  readonly output?: Schema;
113
116
  /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
@@ -287,7 +290,7 @@ export interface Errors {
287
290
  conflict(code: string, details?: unknown): DomainError;
288
291
  /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
289
292
  notFound(code?: string, details?: unknown): DomainError;
290
- /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
293
+ /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`, or `"<module>.forbidden"` in an unnamed private function. */
291
294
  deny(code?: string, details?: unknown): DomainError;
292
295
  }
293
296
  interface BaseCtx<C extends Config, S> {
@@ -381,7 +384,7 @@ type Def<C extends Config, K extends Kind, IS, OS, R, P, A> = {
381
384
  * instead of "No overload matches this call". Keep `output: OS` plain: `OS & Schema` makes TypeScript compare the whole
382
385
  * schema type structurally on every definition (about 10x slower to check).
383
386
  */
384
- export type Constructor<C extends Config, K extends Kind> = <IS extends Schema = NoInput, OS extends Schema | undefined = undefined, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>, A extends boolean = never>(def: Def<C, K, IS, OS, R, P, A>) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C>;
387
+ export type Constructor<C extends Config, K extends Kind> = <IS extends Schema = NoInput, OS extends Schema | undefined = undefined, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>, A extends boolean = never>(def: Def<C, K, IS, OS, R, P, A>) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C, NoInput extends IS ? undefined : IS>;
385
388
  type OtherInit = SetupError<"Defined with another init(), so it would run with this registry's scope, not its own. Define it with the init() this createRegistry came from">;
386
389
  /** `createRegistry`'s modules: a function, listener or cron defined with another `init` is an error, since it would run with this one's scope. Events have no `init`. */
387
390
  export type OwnModules<C extends Config, Mods> = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
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",
@@ -113,7 +113,7 @@
113
113
  "drizzle-orm": ">=1.0.0-rc.6 <2",
114
114
  "pg-boss": ">=12.39.0 <13",
115
115
  "ai": ">=7 <8",
116
- "@logic-sdk/cli": ">=0.6.0 <0.7.0"
116
+ "@logic-sdk/cli": ">=0.6.2 <0.7.0"
117
117
  },
118
118
  "peerDependenciesMeta": {
119
119
  "@orpc/server": {
@@ -22,7 +22,7 @@ src/
22
22
  actions.ts action({...}) network calls: payments, email, AI, webhooks out
23
23
  events.ts event({...}) things that happened
24
24
  listeners.ts listener({...}) reacting to OTHER modules' events
25
- data.ts private helpers taking ctx (findBooking(ctx, id)) and can* record checks. Never imported by other modules.
25
+ data.ts private: helpers taking ctx (findBooking(ctx, id)), can* record checks, and functions the index doesn't export. Never imported by other modules.
26
26
  schema.ts tables this module owns. Other modules never read them.
27
27
  <module>.test.ts
28
28
  ```
@@ -64,7 +64,7 @@ export const cancel = mutation({
64
64
  1. **Pick the kind by what it touches.** Only reads: `query`. Writes to our database: `mutation`. Talks to the network: `action`. Reacts to another module: `listener`.
65
65
  2. **Never put side effects in a mutation or query.** No email, HTTP or payments. They don't have `services` on purpose. Emit an event and react in a listener, or write an action that runs the mutation.
66
66
  3. **Call other modules only with `run(otherModule.fn, input)`.** Import them as `import * as availability from "../availability"`. Never import their `data.ts` or `schema.ts`, from a module or from routes and pages.
67
- 4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing.
67
+ 4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing. When an action must write, put the mutation in `data.ts` and `ctx.run` it: the index doesn't export it, so nothing outside the module can skip the action's checks. A private function can't be scheduled, run by a cron, published or run from a test: test it through the action.
68
68
  5. **Always filter by `ctx.scope.accountId`** in `data.ts` helpers, writes included. Loading helpers throw `ctx.errors.notFound()`. Scope is who and where (actor, account, locale); input is what.
69
69
  6. **Authorize every function a user, client or AI tool may call.** `authorize: member` (a policy from `policies.ts`) says who may call it: sync, reads only scope, runs on every call including nested ones. Publish a function by listing it in `src/rpc.ts` (`toORPCProcedure(fn)`) or an agent's tools (`toAITool(caller, fn)`); both refuse one without `authorize`. A hand-written route or Server Action can `caller.run` anything, nothing stops it: only call functions that have `authorize` from them. Give published functions an `output` so nothing unintended leaves.
70
70
  7. **Record rules are `can*` predicates.** Load through a scoped helper, then `if (!canX(ctx.scope.actor, record)) throw ctx.errors.deny();`. `can*` is sync, its result is always used, and the same predicate feeds UI flags in list queries: `can: { cancel: canCancel(actor, b) }`. A rule that must hold at commit goes in the write's `WHERE` or a `FOR UPDATE` re-select.
@@ -74,7 +74,7 @@ export const cancel = mutation({
74
74
  11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, change the scope for that call: `ctx.run(fn, input, { scope: { actor: system } })`.
75
75
  12. **Time** comes from `ctx.now()`, never `new Date()`, so tests can freeze it.
76
76
  13. **Use separate `export const`s**, not functions nested in an object. Name them by verb within the module (`bookings.confirm`, not `bookings.confirmBooking`). Names are unique per module. Renaming a listener, event or function that queued jobs may still reference? Keep its id: `listener({ id: "oldName", ... })`. Put one sentence of JSDoc above each (`/** Cancel a booking and free its dates */`): editors show it on hover, and `logic-sdk list` prints it.
77
- 14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`.
77
+ 14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`. A form's schema comes from the function it submits to (`properties.update.input.pick({ name: true })`), not from a schema the module exports.
78
78
  15. **Settings come from `ctx.config`**, never from env inside a module. Declare its shape in `init<Config>()` (`config: { orders: { maxItems: number } }`), fill it from your env at the entry (`createRegistry({ config })`), and read it in any function: `ctx.config.orders.maxItems`. Plain data only. Clients built from secrets go in `services`. Outside modules (the entry, routes, scripts), read env however you like.
79
79
  16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database, jobs: { adapter: databaseQueue(database), scope: { store, load } } })` (your database is the queue, like Laravel's `database` driver; export `jobsTable` from the schema and sweep from a cron trigger or `startTicking`), `outbox(database, cloudflareQueue(env.JOBS))` when another queue runs them (the queue alone works too, and can lose a job on a crash), or `pgBoss(boss)` from `logic-sdk/pg-boss` when the app runs pg-boss (`await boss.start()` in every process, `await work(registry, boss)` in the worker, `boss.stop()` on SIGTERM; tune a listener's queue and workers with `meta: { pgBoss: { queue, worker } }`, never its retries). `store` saves ids, `load` rebuilds the scope when the job runs, with today's roles (`null` discards it: check membership there). `createRegistry` requires `load` with every adapter but `inProcess()`; keep the `system` field of a system scope in both. Never pass a jobs adapter per module, and never enqueue background work by hand from a mutation: `emit` an event. A listener tries once; give it `attempts: 5` when retrying is safe, and `delay: 60` (seconds) to run it later.
80
80
  17. **Scheduled work is a `cron`,** exported from the module like a listener: `cron({ schedule: "0 9 * * MON", run: () => fn, scope: asSystem("reports.weekly") })`, where `asSystem` builds a `System` variant of the app's `Scope` (`actor: null`, `system: name`, never built from a request) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. `run` is an existing function (it keeps its policy); never put the work in the cron itself. On Node, `startTicking(registry)` from `logic-sdk/node` ticks and sweeps (`await stop()` on SIGTERM); with pg-boss, `work(registry, boss)` ticks them; on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)`.
package/src/errors.ts CHANGED
@@ -29,14 +29,23 @@ export class DomainError extends Error {
29
29
  export const isDomainError = (e: unknown, code?: string): e is DomainError =>
30
30
  e instanceof DomainError && (code === undefined || e.code === code);
31
31
 
32
+ /** The module part of an id: "bookings" for "bookings.confirm". */
33
+ export const moduleOf = (id: string) => id.slice(0, id.indexOf("."));
34
+
35
+ /** How an unnamed private function (one its module's index doesn't export) is named: `files.(private)`. */
36
+ export const PRIVATE = "(private)";
37
+
38
+ /** What a call its policy refused throws: "bookings.cancel.forbidden", and "files.forbidden" for an unnamed private function. */
39
+ export const forbiddenOf = (id: string) => `${id === `${moduleOf(id)}.${PRIVATE}` ? moduleOf(id) : id}.forbidden`;
40
+
32
41
  /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
33
42
  export const errorsFor = (id: string): Errors => {
34
- const module = id.slice(0, id.indexOf("."));
43
+ const module = moduleOf(id);
35
44
  return {
36
45
  reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
37
46
  conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
38
47
  notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
39
- deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
48
+ deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : forbiddenOf(id), details),
40
49
  };
41
50
  };
42
51
 
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { describeIssues, DomainError, errorsFor } from "./errors.ts";
1
+ import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
2
2
  import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.ts";
3
3
  import { assertTimeZone, parseSchedule } from "./schedule.ts";
4
4
  import { BRAND, INTERNAL } from "./types.ts";
@@ -394,11 +394,10 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
394
394
  }
395
395
  };
396
396
 
397
- if (!database && functions.some((f) => f.kind === "mutation"))
398
- throw new Error(
399
- "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
400
- "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.",
401
- );
397
+ const noDatabase =
398
+ "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
399
+ "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.";
400
+ if (!database && functions.some((f) => f.kind === "mutation")) throw new Error(noDatabase);
402
401
  for (const l of listeners)
403
402
  if (!ids.has(l.event))
404
403
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
@@ -408,7 +407,8 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
408
407
  const id = ids.get(x);
409
408
  if (!id)
410
409
  throw new Error(
411
- "[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }).",
410
+ "[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }). " +
411
+ "A private function (one the index doesn't export) runs only through ctx.run, from its own module.",
412
412
  );
413
413
  return id;
414
414
  };
@@ -455,7 +455,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
455
455
  scope: frame.scope,
456
456
  config: config as any, // Frozen<Cf> here; each app's ctx types it from its own Config
457
457
  now,
458
- run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed),
458
+ run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed, moduleOf(id)),
459
459
  });
460
460
  const queryCtx = (frame: Frame, id: string): QueryCtx<any> => ({
461
461
  ...baseCtx(frame, id, ["query"]),
@@ -472,7 +472,12 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
472
472
  checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
473
473
  },
474
474
  schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
475
- const fnId = idOf(fn);
475
+ const fnId = ids.get(fn);
476
+ if (!fnId)
477
+ throw new Error(
478
+ "[logic-sdk] ctx.schedule needs a function its module's index.ts exports: a scheduled call waits as a name, and a worker finds the code by it. " +
479
+ "A private function runs only through ctx.run.",
480
+ );
476
481
  const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
477
482
  if (!Number.isFinite(seconds) || (!at && seconds < 0))
478
483
  throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
@@ -547,8 +552,10 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
547
552
  });
548
553
 
549
554
  // ── invoke ───────────────────────────────────────────────────────────────
550
- async function invoke(fn: Fn, rawInput: unknown, outer: Frame, allowed: Kind[]): Promise<any> {
551
- const id = idOf(fn);
555
+ /** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
556
+ async function invoke(fn: Fn, rawInput: unknown, outer: Frame, allowed: Kind[], callerModule?: string): Promise<any> {
557
+ // anything else that runs one finds it by name, and it has none: idOf throws, saying so
558
+ const id = ids.get(fn) ?? (callerModule ? `${callerModule}.${fn.id ?? PRIVATE}` : idOf(fn));
552
559
  if (!allowed.includes(fn.kind))
553
560
  throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
554
561
  const depth = outer.trail.length;
@@ -567,7 +574,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
567
574
  frame.abortOn?.throwIfAborted();
568
575
  if (fn.authorize) {
569
576
  // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
570
- if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", `${id}.forbidden`);
577
+ if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", forbiddenOf(id));
571
578
  }
572
579
  // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
573
580
  return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
@@ -600,12 +607,13 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
600
607
 
601
608
  // top-level mutation: open the transaction, commit, then deliver events.
602
609
  // A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
610
+ // createRegistry checks for one, but a private mutation isn't registered, so it can only be checked here
611
+ if (!database) throw new Error(noDatabase);
603
612
  const input = await prepare();
604
613
  let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
605
614
  for (let attempt = 1; ; attempt++) {
606
615
  try {
607
- // SAFETY: createRegistry refuses mutations without a database that has interactive transactions
608
- committed = await database!.transaction(async (txDb) => {
616
+ committed = await database.transaction(async (txDb) => {
609
617
  // fresh per attempt, so a retry never reuses events from a failed attempt
610
618
  const tx: TxState = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
611
619
  const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
@@ -617,7 +625,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
617
625
  });
618
626
  break;
619
627
  } catch (e) {
620
- if (attempt < transactionAttempts && database!.retryable?.(e)) { // SAFETY: as above
628
+ if (attempt < transactionAttempts && database.retryable?.(e)) {
621
629
  // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
622
630
  await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
623
631
  continue;
package/src/types.ts CHANGED
@@ -99,13 +99,16 @@ export const BRAND: unique symbol = Symbol.for("logic-sdk.brand");
99
99
  type FromInit<C extends Config> = { readonly [types]?: { init: (config: C) => void } };
100
100
 
101
101
  /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
102
- export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any> {
102
+ export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any, IS extends Schema | undefined = Schema | undefined> {
103
103
  readonly [BRAND]: K;
104
104
  readonly kind: K;
105
- /** Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name. */
105
+ /**
106
+ * Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name.
107
+ * A private function (the index doesn't export it) is `notifications.(private)` without one.
108
+ */
106
109
  readonly id?: string;
107
- /** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
108
- readonly input?: Schema;
110
+ /** What callers pass, validated on every call, as you wrote it: `fn.input.pick({ name: true })` for a form. Undefined: the function takes nothing (`run(fn)`). */
111
+ readonly input: IS;
109
112
  /** What callers get back, checked before it leaves. */
110
113
  readonly output?: Schema;
111
114
  /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
@@ -291,7 +294,7 @@ export interface Errors {
291
294
  conflict(code: string, details?: unknown): DomainError;
292
295
  /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
293
296
  notFound(code?: string, details?: unknown): DomainError;
294
- /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
297
+ /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`, or `"<module>.forbidden"` in an unnamed private function. */
295
298
  deny(code?: string, details?: unknown): DomainError;
296
299
  }
297
300
  interface BaseCtx<C extends Config, S> {
@@ -395,7 +398,7 @@ export type Constructor<C extends Config, K extends Kind> = <
395
398
  A extends boolean = never,
396
399
  >(
397
400
  def: Def<C, K, IS, OS, R, P, A>,
398
- ) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C>;
401
+ ) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C, NoInput extends IS ? undefined : IS>;
399
402
 
400
403
  type OtherInit = SetupError<"Defined with another init(), so it would run with this registry's scope, not its own. Define it with the init() this createRegistry came from">;
401
404
  /** `createRegistry`'s modules: a function, listener or cron defined with another `init` is an error, since it would run with this one's scope. Events have no `init`. */