@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.21

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.
Files changed (80) hide show
  1. package/package.json +35 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +229 -40
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
@@ -0,0 +1,101 @@
1
+ import type { LeaseFence } from './capability';
2
+ import { type Session } from './database';
3
+ import type { JobOutcome, LeaseProjection } from './job-leases';
4
+ import type { DataLayerRuntime } from './store';
5
+ export declare const WAKE_REASONS: readonly ["cron", "kick", "claim", "retry"];
6
+ export type WakeReason = (typeof WAKE_REASONS)[number];
7
+ export interface NewWake {
8
+ readonly job: string;
9
+ readonly reason: WakeReason;
10
+ readonly dueAt: Date;
11
+ /** Wakes under one key are one row: `cron:<job>:<expr>`, `claim:<job>`, `kick:<job>:<due second>`. */
12
+ readonly dedupe?: string;
13
+ }
14
+ export interface Wake {
15
+ readonly id: string;
16
+ readonly job: string;
17
+ readonly reason: WakeReason;
18
+ readonly dueAt: Date;
19
+ /** How many failed runs moved this wake (`retry`). */
20
+ readonly attempt: number;
21
+ readonly dedupe: string | null;
22
+ /** Taken by the run that holds its job's lease, when that run took it: that run's finish consumes or retries it. */
23
+ readonly owned: boolean;
24
+ }
25
+ /**
26
+ * What a run's finish does with the wakes it owned (those due when it took the lease), applied in the finish's
27
+ * transaction and only when the finish still held the lease. Without one, a success is `completed` and a failure
28
+ * leaves the wakes as they are.
29
+ */
30
+ export type FinishWakes =
31
+ /** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
32
+ {
33
+ readonly kind: 'completed';
34
+ readonly nextCron?: {
35
+ readonly expression: string;
36
+ readonly dueAt: Date;
37
+ };
38
+ }
39
+ /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
40
+ | {
41
+ readonly kind: 'retry';
42
+ readonly at: Date;
43
+ };
44
+ export interface JobWakes {
45
+ /**
46
+ * Records a pending wake, in `using` when given (the transaction of the write it belongs to). A key already pending
47
+ * keeps one row at the earlier due time: a later wake never postpones an earlier one. A merge takes the row from the
48
+ * run that owns it, except a cron wake's, whose next fire that run's finish schedules. Answers the row that holds it;
49
+ * a key another job holds is refused.
50
+ */
51
+ schedule(wake: NewWake, using?: Session): Promise<Wake>;
52
+ /** The pending wakes of `job`, earliest first. */
53
+ pending(job: string): Promise<readonly Wake[]>;
54
+ /**
55
+ * When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
56
+ * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given.
57
+ */
58
+ next(using?: Session): Promise<Date | null>;
59
+ /** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
60
+ untilNext(using?: Session): Promise<number | null>;
61
+ /** The database's clock, read in `using` when given: a wake due now is due by it. */
62
+ now(using?: Session): Promise<Date>;
63
+ /**
64
+ * Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
65
+ * each declared job's cron wake whose key names another expression; answers how many it deleted.
66
+ */
67
+ reconcile(declared: readonly DeclaredJob[]): Promise<number>;
68
+ /**
69
+ * The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
70
+ * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
71
+ */
72
+ hasten(ids: readonly string[]): Promise<number>;
73
+ /**
74
+ * The jobs whose lease a run holds past its expiry, declared or not: a removed job's crashed holder still arms the
75
+ * alarm through `next` until someone reaps it.
76
+ */
77
+ expiredHolders(): Promise<readonly string[]>;
78
+ }
79
+ /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
80
+ export interface DeclaredJob {
81
+ readonly job: string;
82
+ readonly expression: string;
83
+ }
84
+ /**
85
+ * A finish's instruction checked before its statement runs, with the default filled in: `null` leaves the wakes. The
86
+ * lease store calls it, so a malformed instruction refuses the finish and leaves the lease held.
87
+ */
88
+ export declare function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined): FinishWakes | null;
89
+ /**
90
+ * The lease store's projection, all in the lease statement's transaction: a taken lease marks the wakes its run owns, a
91
+ * fenced finish applies its wake instruction to them, a finish or a reap leaves none owned, and every lease change then
92
+ * runs the runtime's projection.
93
+ */
94
+ export declare function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjection;
95
+ /**
96
+ * Sets the claim wake of `fence`'s job to `dueAt`, or removes it for `null`, in `transaction`: the claim's fenced
97
+ * transaction, so the re-arm commits with the rows it leased. The attempt's first claim replaces what an earlier run
98
+ * left; each later claim keeps the earliest re-arm of the attempt.
99
+ */
100
+ export declare function rearmClaim(runtime: DataLayerRuntime, transaction: Session, fence: LeaseFence, dueAt: Date | null): Promise<void>;
101
+ export declare function jobWakes(runtime: () => DataLayerRuntime): JobWakes;
@@ -0,0 +1,18 @@
1
+ /** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
2
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
3
+ readonly [key: string]: JsonValue | undefined;
4
+ };
5
+ /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
6
+ export type JsonColumnValue = Exclude<JsonValue, null>;
7
+ /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
8
+ export declare const MAX_JSON_DEPTH = 64;
9
+ /**
10
+ * A written JSON column value as the text the layer binds: plain objects and arrays, strings, finite numbers, booleans
11
+ * and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
12
+ */
13
+ export declare function jsonInput(value: unknown, where: string): string;
14
+ /**
15
+ * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
16
+ * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
17
+ */
18
+ export declare function sqliteJson(value: unknown, where: string): unknown;
@@ -0,0 +1,4 @@
1
+ import { type FrameworkMigration } from './migrations';
2
+ /** The `strftime` format of a stored timestamp; `strftime(SQLITE_NOW_FORMAT, 'now')` is the database's clock. */
3
+ export declare const SQLITE_NOW_FORMAT = "%Y-%m-%dT%H:%M:%fZ";
4
+ export declare const SQLITE_FRAMEWORK_MIGRATIONS: readonly FrameworkMigration[];
@@ -4,6 +4,7 @@ export declare const WEBHOOK_BINDINGS_TABLE = "fabrika_webhook_bindings";
4
4
  export declare const WEBHOOK_DELIVERIES_TABLE = "fabrika_webhook_deliveries";
5
5
  export declare const JOB_LEASES_TABLE = "fabrika_job_leases";
6
6
  export declare const JOB_KICKS_TABLE = "fabrika_job_kicks";
7
+ export declare const JOB_WAKES_TABLE = "fabrika_wakes";
7
8
  export declare const FORM_ADMISSIONS_TABLE = "fabrika_form_admissions";
8
9
  export declare const FORM_CHALLENGES_TABLE = "fabrika_form_challenges";
9
10
  export declare const FORM_FILES_TABLE = "fabrika_form_files";
@@ -1,5 +1,6 @@
1
1
  import { type DeleteQueryNode, type InsertQueryNode, type OperationNode, ReferenceNode, ReturningNode, type SelectQueryNode, type UpdateQueryNode, WhereNode } from 'kysely';
2
2
  import { type NameSet } from './builtins';
3
+ import type { SqlDialect } from './database';
3
4
  import type { Condition, Primitive, SelectState } from './description';
4
5
  export declare function column(table: string, name: string): ReferenceNode;
5
6
  export declare function equals(table: string, name: string, value: Primitive): OperationNode;
@@ -7,6 +8,8 @@ export declare function allOf(nodes: readonly OperationNode[]): OperationNode;
7
8
  /** One node, or the OR of several in a parenthesis: inside an AND, `a and b or c` would read as `(a and b) or c`. */
8
9
  export declare function anyOf(nodes: readonly OperationNode[]): OperationNode;
9
10
  export declare function inList(table: string, name: string, values: readonly string[]): OperationNode;
11
+ /** `($1, $2, …)`: bound values, as the right operand of an `in`. */
12
+ export declare function valueList(values: readonly string[]): OperationNode;
10
13
  /** The scope of a `Within` that is not limited to scope values. */
11
14
  export declare function everything(): OperationNode;
12
15
  /** LIKE treats `\` as its escape character by default, so the text matches literally. */
@@ -19,7 +22,7 @@ export declare function scopedWhere(conditions: OperationNode | undefined, scope
19
22
  /** `returning key as id[, version as version]`: a mutation's acknowledgement, never row data. */
20
23
  export declare function acknowledgement(table: string, key: string, version: string | undefined): ReturningNode;
21
24
  /** `after` is a keyset page's position, ANDed to the caller's conditions inside their parenthesis. */
22
- export declare function selectNode(state: SelectState, visible: readonly string[], scope: OperationNode, after?: OperationNode, days?: NameSet): SelectQueryNode;
25
+ export declare function selectNode(state: SelectState, visible: readonly string[], scope: OperationNode, after?: OperationNode, days?: NameSet, dialect?: SqlDialect): SelectQueryNode;
23
26
  export interface AggregateColumns {
24
27
  readonly groupBy: readonly string[];
25
28
  readonly count: boolean;
@@ -38,6 +41,8 @@ export declare function existsNode(table: string, key: string, scope: OperationN
38
41
  export declare function acknowledgementNode(table: string, key: string, version: string | undefined, where: WhereNode): SelectQueryNode;
39
42
  /** `select columns from table where scope limit 1`: the containment columns of one object, for the framework's locator. */
40
43
  export declare function locateNode(table: string, columns: readonly string[], scope: OperationNode): SelectQueryNode;
44
+ /** `select T.<name> from T where <scope> group by T.<name>`: each value of `name` the scoped rows hold, once. */
45
+ export declare function valuesNode(table: string, name: string, scope: OperationNode): SelectQueryNode;
41
46
  /**
42
47
  * The same check, locked: `for share` keeps the row from moving until the transaction that checked it ends, `for
43
48
  * update` also keeps every other writer and locker of it waiting.
@@ -57,6 +62,16 @@ export declare function claimNode(state: SelectState, columns: readonly string[]
57
62
  readonly attempts: string;
58
63
  readonly now: Date;
59
64
  readonly maxAttempts: number;
60
- }, scope: OperationNode, days: NameSet): SelectQueryNode;
65
+ }, scope: OperationNode, days: NameSet, dialect?: SqlDialect): SelectQueryNode;
66
+ /**
67
+ * When the same claim next finds a row: `select <due> from table where (<conditions> and (<due> > $now and <attempts> <
68
+ * $max)) and scope order by <due> limit 1`, with `state` the claim's conditions ordered by `<due>`, limited to one.
69
+ */
70
+ export declare function nextClaimNode(state: SelectState, due: {
71
+ readonly due: string;
72
+ readonly attempts: string;
73
+ readonly now: Date;
74
+ readonly maxAttempts: number;
75
+ }, scope: OperationNode, days: NameSet, dialect?: SqlDialect): SelectQueryNode;
61
76
  /** `select <columns> from table where scope for update`: a mutation's precondition read of its own target. */
62
77
  export declare function lockedSelectNode(table: string, columns: readonly string[], scope: OperationNode, days?: NameSet): SelectQueryNode;
@@ -1,8 +1,8 @@
1
1
  import type { Selectable, Updateable } from 'kysely';
2
2
  import type { RowRef } from './capability';
3
- import type { ConditionTuple } from './description';
3
+ import type { ComparableColumn, ConditionTuple } from './description';
4
4
  import type { FileReference } from './file-references';
5
- import type { ActionOf, ApplicationTableName, ChildTableName, ContainerOf, DimensionOf, DimensionTableName, InsertValues, ListDimensionOf, ParentOf, Tables, UpdateValues } from './policy';
5
+ import type { ActionOf, ApplicationTableName, ChildTableName, ContainerOf, DimensionOf, DimensionTableName, InsertValues, ListDimensionOf, ParentOf, ReadsAny, Tables, UpdateValues } from './policy';
6
6
  import type { AggregateRow, AggregateSpec } from './store';
7
7
  import type { VocabularyContainerOf } from './vocabulary-tables';
8
8
  /** A member an endpoint may not use. It has no call signature, so a call fails at its line with this message. */
@@ -74,12 +74,15 @@ export interface IndexedTable {
74
74
  readonly list: string;
75
75
  /** A child table's parent table. */
76
76
  readonly parent: string;
77
+ /** `read` is `never` for a table read with `'any'` (`readsAny`). */
77
78
  readonly actions: {
78
79
  readonly read: string;
79
80
  readonly insert: string;
80
81
  readonly update: string;
81
82
  readonly delete: string;
82
83
  };
84
+ /** An application table read with `'any'`: every `app` endpoint, job and webhook reads it, no public procedure or scoped site. */
85
+ readonly readsAny: boolean;
83
86
  /** The actions besides `read` with which an `app` endpoint lists every row (`actions.appRead`). */
84
87
  readonly appRead: string;
85
88
  /** The actions with which an `app` endpoint only counts every row (`actions.appCount`). */
@@ -101,6 +104,8 @@ export interface IndexedTable {
101
104
  readonly versioned: boolean;
102
105
  /** A queue table: its rows are claimed and finished through `row.ref`. */
103
106
  readonly queued: boolean;
107
+ /** A view: read like its scope's tables, written by no site (ADR-0072). */
108
+ readonly view: boolean;
104
109
  }
105
110
  type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> = {
106
111
  readonly mode: ModeOf<P, T>;
@@ -113,6 +118,7 @@ type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> =
113
118
  readonly update: ActionOf<P, T, 'update'>;
114
119
  readonly delete: ActionOf<P, T, 'delete'>;
115
120
  };
121
+ readonly readsAny: ReadsAny<P, T>;
116
122
  readonly appRead: AppActionsOf<P, T, 'appRead'>;
117
123
  readonly appCount: AppActionsOf<P, T, 'appCount'>;
118
124
  readonly row: WithFiles<RowType<DB[T]>, FileColumnsOf<P, T>>;
@@ -131,6 +137,9 @@ type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> =
131
137
  readonly queued: PolicyOf<P, T> extends {
132
138
  readonly queue: object;
133
139
  } ? true : false;
140
+ readonly view: PolicyOf<P, T> extends {
141
+ readonly view: true;
142
+ } ? true : false;
134
143
  };
135
144
  type OwnerTable<P, D> = {
136
145
  [K in keyof P]: P[K] extends {
@@ -168,6 +177,18 @@ type ChainDimensions<P, T, V> = PolicyOf<P, T> extends {
168
177
  } ? DimensionOf<P, Parent> | ChainDimensions<P, Parent, V> : never : never;
169
178
  /** The dimensions whose `Within` lists table `T`: every dimension of its chain, and a top-level table's own. */
170
179
  type ReachOf<P, T, V> = [ContainerOf<P, T>] extends [never] ? DimensionOf<P, T> | ChainDimensions<P, T, V> : ChainDimensions<P, T, V>;
180
+ /**
181
+ * The dimensions outside its chain whose `Within` reads table `T` through a foreign key (`readThrough`); a child view's
182
+ * are its parent's, as it is read through its parent row.
183
+ */
184
+ type ReadThroughOf<P, T> = PolicyOf<P, T> extends {
185
+ readonly readThrough: infer R;
186
+ } ? keyof R & string : PolicyOf<P, T> extends {
187
+ readonly view: true;
188
+ readonly scope: {
189
+ readonly child: infer Parent extends string;
190
+ };
191
+ } ? ReadThroughOf<P, Parent> : never;
171
192
  /**
172
193
  * A row as reads return it: the generated interface itself where no column has a separate write type, so a
173
194
  * diagnostic names it (`DealsTable`), and Kysely's `Selectable` of it otherwise.
@@ -209,9 +230,12 @@ export type DbIndex<DB, P, V = unknown> = {
209
230
  readonly listed: {
210
231
  readonly [T in DimensionTableName<P> as ListDimensionOf<P, T>]: T;
211
232
  };
212
- /** Dimension → the tables an `over` of it lists: each whose containment chain holds it, and a top-level table its own. */
233
+ /**
234
+ * Dimension → the tables an `over` of it lists: each whose containment chain holds it, a top-level table its own, and
235
+ * each that reads through it (`readThrough`).
236
+ */
213
237
  readonly within: {
214
- readonly [T in DimensionTableName<P> | ChildTableName<P> as ReachOf<P, T, V>]: T;
238
+ readonly [T in DimensionTableName<P> | ChildTableName<P> as ReachOf<P, T, V> | ReadThroughOf<P, T>]: T;
215
239
  };
216
240
  readonly references: ReferenceTableName<P>;
217
241
  /** The application tables: an `app` endpoint reads and writes them. */
@@ -269,7 +293,7 @@ type InsertValuesOf<E extends IndexedTable> = {
269
293
  /** `onConflict` of an insert: the columns of a unique index the migrations create, and what a conflict does. */
270
294
  export interface InsertConflict<E extends IndexedTable, M extends 'nothing' | 'update'> {
271
295
  readonly onConflict: {
272
- readonly columns: readonly (keyof E['row'] & string)[];
296
+ readonly columns: readonly ComparableColumn<E['row']>[];
273
297
  readonly do: M;
274
298
  };
275
299
  }
@@ -324,27 +348,39 @@ export interface ClaimedRowHandle<T extends string, E extends IndexedTable, A ex
324
348
  /** The actions table `E` names: its read, insert, update and delete actions, and each column's own write action. */
325
349
  type NamedActions<E extends IndexedTable> = (E['actions'][keyof E['actions']] | keyof E['writes']) & string;
326
350
  type Names<E extends IndexedTable, A extends string> = [A] extends [NamedActions<E>] ? true : false;
351
+ /**
352
+ * Whether an action of `A` is one of `Allowed`. An `app` capability of several actions, an `anyOf` endpoint's, allows
353
+ * what any of them allows, as one role holding them; the runtime refuses an operation none of the held ones allows.
354
+ */
355
+ type AnyAllowed<A extends string, Allowed> = [Extract<A, Allowed>] extends [never] ? false : true;
356
+ /** `U`'s members as one object: the columns any action of an `app` capability updates, with their values. */
357
+ type Merged<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void ? I : never;
327
358
  type Operation = 'insert' | 'update' | 'delete';
328
- /** `Member` in a mutation whose action is the table's `Op` action; otherwise the message that says which fix applies. */
329
- type Write<T extends string, E extends IndexedTable, Op extends Operation, A extends string, K extends DataKind, Member> = K extends 'mutation' ? [A] extends [E['actions'][Op]] ? Member : Unavailable<`${Op} on ${T} needs the action '${E['actions'][Op] & string}', and this endpoint holds '${A}'`> : K extends 'job' ? Unavailable<'a job writes inside ctx.transaction((tx) => …): use tx.db there'> : Unavailable<`${Op extends 'delete' ? 'remove' : Op} writes, so it runs only in a mutation: declare the endpoint with r.mutation`>;
359
+ /**
360
+ * `Member` in a mutation whose action is the table's `Op` action (`Allowed`, any action of an `app` capability's);
361
+ * otherwise the message that says which fix applies.
362
+ */
363
+ type Write<T extends string, E extends IndexedTable, Op extends Operation, A extends string, K extends DataKind, Member, Allowed extends boolean = [A] extends [E['actions'][Op]] ? true : false> = K extends 'mutation' ? Allowed extends true ? Member : Unavailable<`${Op} on ${T} needs the action '${E['actions'][Op] & string}', and this endpoint holds '${A}'`> : K extends 'job' ? Unavailable<'a job writes inside ctx.transaction((tx) => …): use tx.db there'> : Unavailable<`${Op extends 'delete' ? 'remove' : Op} writes, so it runs only in a mutation: declare the endpoint with r.mutation`>;
330
364
  /** What an update of `T` needs, for a capability of `A` that updates nothing of it. */
331
365
  type UpdateRefusal<T extends string, E extends IndexedTable, A extends string> = [Exclude<keyof E['writes'], E['actions']['update']>] extends [never] ? `update on ${T} needs the action '${E['actions']['update'] & string}', and this endpoint holds '${A}'` : [E['actions']['update']] extends [never] ? `update on ${T} needs a column's own write action, and this endpoint holds '${A}'` : `update on ${T} needs the action '${E['actions']['update'] & string}' or a column's own write action, and this endpoint holds '${A}'`;
332
366
  /**
333
367
  * `Member` in a mutation whose action updates columns of the table (the update action, or a column's own write
334
- * action); otherwise the message that says which fix applies.
368
+ * action; `Allowed`, any action of an `app` capability's); otherwise the message that says which fix applies.
335
369
  */
336
- type Update<T extends string, E extends IndexedTable, A extends string, K extends DataKind, Member> = K extends 'mutation' ? [A] extends [keyof E['writes']] ? Member : Unavailable<UpdateRefusal<T, E, A>> : K extends 'job' ? Unavailable<'a job writes inside ctx.transaction((tx) => …): use tx.db there'> : Unavailable<'update writes, so it runs only in a mutation: declare the endpoint with r.mutation'>;
370
+ type Update<T extends string, E extends IndexedTable, A extends string, K extends DataKind, Member, Allowed extends boolean = [A] extends [keyof E['writes']] ? true : false> = K extends 'mutation' ? Allowed extends true ? Member : Unavailable<UpdateRefusal<T, E, A>> : K extends 'job' ? Unavailable<'a job writes inside ctx.transaction((tx) => …): use tx.db there'> : Unavailable<'update writes, so it runs only in a mutation: declare the endpoint with r.mutation'>;
337
371
  /** An update's values: any non-empty subset of the columns a capability of `A` updates; an empty one is refused. */
338
372
  type UpdateValuesOf<E extends IndexedTable, A extends string> = E['writes'][A & keyof E['writes']];
339
- type Read<T extends string, E extends IndexedTable, A extends string, Member> = Names<E, A> extends true ? Member : Unavailable<`${T} does not name the action '${A}': read it from an endpoint whose action ${T} names, or declare unscoped`>;
373
+ /** An `app` capability's update values: the columns any of its actions updates, one action's as `UpdateValuesOf`. */
374
+ type AppUpdateValuesOf<E extends IndexedTable, A extends string> = Merged<UpdateValuesOf<E, A>>;
375
+ type Read<T extends string, E extends IndexedTable, A extends string, Member, Allowed extends boolean = Names<E, A>> = Allowed extends true ? Member : Unavailable<`${T} does not name the action '${A}': read it from an endpoint whose action ${T} names, or declare unscoped`>;
340
376
  /** One page of a keyset list; `next` is the cursor `after` takes, `null` on the last page. */
341
377
  export interface ListPage<Row> {
342
378
  readonly items: Row[];
343
379
  readonly next: string | null;
344
380
  }
345
381
  export type OrderTerm<Row> = {
346
- [C in keyof Row & string]: readonly [C, 'asc' | 'desc'];
347
- }[keyof Row & string];
382
+ [C in ComparableColumn<Row>]: readonly [C, 'asc' | 'desc'];
383
+ }[ComparableColumn<Row>];
348
384
  export interface ListOptions<Row> {
349
385
  readonly where?: readonly ConditionTuple<Row>[];
350
386
  readonly orderBy?: readonly OrderTerm<Row>[];
@@ -379,15 +415,15 @@ export interface UnownedTarget<D extends string> {
379
415
  readonly update: Unavailable<`no table owns the dimension ${D}, so ctx.db.target has no row of its own`>;
380
416
  readonly remove: Unavailable<`no table owns the dimension ${D}, so ctx.db.target has no row of its own`>;
381
417
  }
382
- /** A child table of the target: its rows are addressed by their own key under the target. */
418
+ /** A child table of the target: its rows are addressed by their own key under the target; a view's are only read. */
383
419
  export interface ChildRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
384
420
  readonly list: Read<T, E, A, (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>>>;
385
421
  readonly get: Read<T, E, A, (key: string) => Promise<RowFor<E, A>>>;
386
- readonly insert: Write<T, E, 'insert', A, K, InsertMethod<E>>;
387
- readonly update: Update<T, E, A, K, (key: string, values: {
422
+ readonly insert: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Write<T, E, 'insert', A, K, InsertMethod<E>>;
423
+ readonly update: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Update<T, E, A, K, (key: string, values: {
388
424
  [C in keyof UpdateValuesOf<E, A>]: UpdateValuesOf<E, A>[C];
389
425
  }, ...version: VersionArguments<E>) => Promise<Saved<E>>>;
390
- readonly remove: Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>;
426
+ readonly remove: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>;
391
427
  }
392
428
  /** A dimension table the target contains: listed in it, and inserted into it by a mutation of its insert action. */
393
429
  export interface ContainedRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
@@ -422,22 +458,35 @@ type ListRefusal<T extends string, E extends IndexedTable, A extends string> = `
422
458
  export type WithinTables<Ix extends AnyDbIndex, D extends string, A extends string, K extends DataKind> = {
423
459
  readonly [T in WithinIn<Ix, D>]: WithinRows<T, Ix['tables'][T], A, K>;
424
460
  };
425
- /** An application table under the capability of an `app` endpoint of action `A`, in a site of kind `K`. */
461
+ /**
462
+ * `Member` where `ctx.db.app` of action `A` lists the application table: by its read action, or any action for `'any'`;
463
+ * an action of `A`'s does for an `anyOf` endpoint.
464
+ */
465
+ type AppList<T extends string, E extends IndexedTable, A extends string, Member> = [E['readsAny']] extends [true] ? Member : AnyAllowed<A, E['actions']['read']> extends true ? Member : Unavailable<ListRefusal<T, E, A>>;
466
+ /** `Member` where `ctx.db.app` of action `A` (any of them) reads a row of the application table by its key. */
467
+ type AppGet<T extends string, E extends IndexedTable, A extends string, Member> = [E['readsAny']] extends [true] ? Member : Read<T, E, A, Member, AnyAllowed<A, NamedActions<E>>>;
468
+ /** `Member` where a public procedure of action `A` reads the application table: under its read action, never `'any'`. */
469
+ type PublicRead<T extends string, E extends IndexedTable, A extends string, Member> = [E['readsAny']] extends [true] ? Unavailable<`a public procedure does not read ${T}: it is read with 'any', which an app endpoint, a job and a webhook hold`> : A extends E['actions']['read'] ? Member : Unavailable<ListRefusal<T, E, A>>;
470
+ /**
471
+ * An application table under the capability of an `app` endpoint of action `A`, in a site of kind `K`; an `anyOf`
472
+ * endpoint's `A` is its listed actions, and an operation any of them allows is typed. A column with its own read action
473
+ * stays hidden there (`RowFor`): which listed actions the caller holds is known only at run time.
474
+ */
426
475
  export interface ApplicationRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
427
- readonly list: A extends E['actions']['read'] ? (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>> : Unavailable<ListRefusal<T, E, A>>;
428
- readonly count: A extends E['actions']['read'] ? (options?: CountOptions<RowFor<E, A>>) => Promise<number> : Unavailable<ListRefusal<T, E, A>>;
429
- readonly aggregate: A extends E['actions']['read'] ? <const S extends AggregateSpec<RowFor<E, A>>>(spec: S) => Promise<AggregateRow<RowFor<E, A>, S>[]> : Unavailable<ListRefusal<T, E, A>>;
476
+ readonly list: AppList<T, E, A, (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>>>;
477
+ readonly count: AppList<T, E, A, (options?: CountOptions<RowFor<E, A>>) => Promise<number>>;
478
+ readonly aggregate: AppList<T, E, A, <const S extends AggregateSpec<RowFor<E, A>>>(spec: S) => Promise<AggregateRow<RowFor<E, A>, S>[]>>;
430
479
  /** One row by its key; a column that declares another read action than `A` is hidden. */
431
- readonly get: Read<T, E, A, (key: string) => Promise<RowFor<E, A>>>;
480
+ readonly get: AppGet<T, E, A, (key: string) => Promise<RowFor<E, A>>>;
432
481
  /** `SELECT … FOR UPDATE` of one row by its key: a precondition read that no concurrent write overtakes. */
433
- readonly getForUpdate: K extends 'mutation' ? Read<T, E, A, (key: string) => Promise<RowFor<E, A>>> : K extends 'job' ? Unavailable<'a job writes inside ctx.transaction((tx) => …): use tx.db there'> : Unavailable<'getForUpdate locks the row, so it runs only in a mutation: declare the endpoint with r.mutation'>;
482
+ readonly getForUpdate: K extends 'mutation' ? AppGet<T, E, A, (key: string) => Promise<RowFor<E, A>>> : K extends 'job' ? Unavailable<'a job writes inside ctx.transaction((tx) => …): use tx.db there'> : Unavailable<'getForUpdate locks the row, so it runs only in a mutation: declare the endpoint with r.mutation'>;
434
483
  /** Leases due rows of a queue table: a job's drain, before its transactions. */
435
484
  readonly claim: Claim<T, E, A, K>;
436
- readonly insert: Write<T, E, 'insert', A, K, InsertMethod<E>>;
485
+ readonly insert: Write<T, E, 'insert', A, K, InsertMethod<E>, AnyAllowed<A, E['actions']['insert']>>;
437
486
  readonly update: Update<T, E, A, K, (key: string, values: {
438
- [C in keyof UpdateValuesOf<E, A>]: UpdateValuesOf<E, A>[C];
439
- }, ...version: VersionArguments<E>) => Promise<Saved<E>>>;
440
- readonly remove: Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>;
487
+ [C in keyof AppUpdateValuesOf<E, A>]: AppUpdateValuesOf<E, A>[C];
488
+ }, ...version: VersionArguments<E>) => Promise<Saved<E>>, AnyAllowed<A, keyof E['writes']>>;
489
+ readonly remove: Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>, AnyAllowed<A, E['actions']['delete']>>;
441
490
  }
442
491
  /**
443
492
  * A public procedure's insert: it answers the new row's key (and version), which the data layer generated, and reads
@@ -460,10 +509,10 @@ type PublicVersioned<T extends string, E extends IndexedTable, Member> = E['vers
460
509
  * under `expectVersion`; never locked or claimed.
461
510
  */
462
511
  export interface PublicApplicationRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
463
- readonly list: ApplicationRows<T, E, A, K>['list'];
464
- readonly count: ApplicationRows<T, E, A, K>['count'];
465
- readonly aggregate: ApplicationRows<T, E, A, K>['aggregate'];
466
- readonly get: A extends E['actions']['read'] ? (key: string) => Promise<RowFor<E, A>> : Unavailable<ListRefusal<T, E, A>>;
512
+ readonly list: PublicRead<T, E, A, (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>>>;
513
+ readonly count: PublicRead<T, E, A, (options?: CountOptions<RowFor<E, A>>) => Promise<number>>;
514
+ readonly aggregate: PublicRead<T, E, A, <const S extends AggregateSpec<RowFor<E, A>>>(spec: S) => Promise<AggregateRow<RowFor<E, A>, S>[]>>;
515
+ readonly get: PublicRead<T, E, A, (key: string) => Promise<RowFor<E, A>>>;
467
516
  readonly getForUpdate: PublicRefusal<'lock'>;
468
517
  readonly claim: PublicRefusal<'claim'>;
469
518
  /** By the id a verified signed token of the request carries; answers only the new version. */
@@ -489,9 +538,9 @@ export type PublicApplicationTables<Ix extends AnyDbIndex, A extends string, K e
489
538
  * (`RowFor`), or only how many rows match. A count-only action has no `aggregate`: a group or a minimum is a value.
490
539
  */
491
540
  export interface AppRecordRows<T extends string, E extends IndexedTable, A extends string> {
492
- readonly list: [A] extends [E['actions']['read'] | E['appRead']] ? (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>> : Unavailable<`a list of ${T} needs its read action '${E['actions']['read'] & string}' or an action of its appRead, and this endpoint holds '${A}'`>;
493
- readonly count: [A] extends [E['actions']['read'] | E['appRead'] | E['appCount']] ? (options?: CountOptions<RowFor<E, A>>) => Promise<number> : Unavailable<`a count of ${T} needs its read action '${E['actions']['read'] & string}' or an action of its appRead or appCount, and this endpoint holds '${A}'`>;
494
- readonly aggregate: [A] extends [E['actions']['read'] | E['appRead']] ? <const S extends AggregateSpec<RowFor<E, A>>>(spec: S) => Promise<AggregateRow<RowFor<E, A>, S>[]> : Unavailable<`an aggregate of ${T} needs its read action '${E['actions']['read'] & string}' or an action of its appRead, and this endpoint holds '${A}': an appCount action only counts`>;
541
+ readonly list: AnyAllowed<A, E['actions']['read'] | E['appRead']> extends true ? (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>> : Unavailable<`a list of ${T} needs its read action '${E['actions']['read'] & string}' or an action of its appRead, and this endpoint holds '${A}'`>;
542
+ readonly count: AnyAllowed<A, E['actions']['read'] | E['appRead'] | E['appCount']> extends true ? (options?: CountOptions<RowFor<E, A>>) => Promise<number> : Unavailable<`a count of ${T} needs its read action '${E['actions']['read'] & string}' or an action of its appRead or appCount, and this endpoint holds '${A}'`>;
543
+ readonly aggregate: AnyAllowed<A, E['actions']['read'] | E['appRead']> extends true ? <const S extends AggregateSpec<RowFor<E, A>>>(spec: S) => Promise<AggregateRow<RowFor<E, A>, S>[]> : Unavailable<`an aggregate of ${T} needs its read action '${E['actions']['read'] & string}' or an action of its appRead, and this endpoint holds '${A}': an appCount action only counts`>;
495
544
  }
496
545
  /**
497
546
  * `ctx.db.app` of an `app` endpoint: every application table, and every dimension and child table read-only, all
@@ -525,7 +574,7 @@ export interface ScopedApplicationRows<E extends IndexedTable> {
525
574
  * read-only; any other is the message that names its read action.
526
575
  */
527
576
  export type ScopedApplicationTables<Ix extends AnyDbIndex, A extends string> = {
528
- readonly [T in Ix['applications']]: [A] extends [Ix['tables'][T]['actions']['read']] ? ScopedApplicationRows<Ix['tables'][T]> : Unavailable<`a scoped endpoint reads ${T} with its read action '${Ix['tables'][T]['actions']['read'] & string}', and this endpoint holds '${A}'`>;
577
+ readonly [T in Ix['applications']]: [Ix['tables'][T]['readsAny']] extends [true] ? Unavailable<`a scoped endpoint does not read ${T}: it is read with 'any', which an app endpoint, a job and a webhook hold`> : [A] extends [Ix['tables'][T]['actions']['read']] ? ScopedApplicationRows<Ix['tables'][T]> : Unavailable<`a scoped endpoint reads ${T} with its read action '${Ix['tables'][T]['actions']['read'] & string}', and this endpoint holds '${A}'`>;
529
578
  };
530
579
  /** A reference table: every endpoint reads it, through its read action, and none writes it. */
531
580
  export interface ReferenceRows<E extends IndexedTable> {
@@ -543,16 +592,16 @@ export type UnscopedDeclaration<Table extends string, Mode extends UnscopedMode>
543
592
  readonly [T in Table]?: Mode;
544
593
  };
545
594
  /**
546
- * The tables of `U` whose mode may be `'write'` that no site writes: a reference table. A union or optional mode that
547
- * admits `'write'` counts, because the declaration it types may hold it.
595
+ * The tables of `U` whose mode may be `'write'` that no site writes: a reference table or a view. A union or optional
596
+ * mode that admits `'write'` counts, because the declaration it types may hold it.
548
597
  */
549
598
  type ReadOnlyWritten<Ix extends AnyDbIndex, U> = {
550
- [T in keyof U & TableName<Ix>]: 'write' extends U[T] ? Ix['tables'][T]['mode'] extends 'reference' ? T : never : never;
599
+ [T in keyof U & TableName<Ix>]: 'write' extends U[T] ? Ix['tables'][T]['mode'] extends 'reference' ? T : Ix['tables'][T]['view'] extends true ? T : never : never;
551
600
  }[keyof U & TableName<Ix>];
552
- type ReadOnlyMessage<T extends string> = `${T} is a reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`;
601
+ type ReadOnlyMessage<T extends string, E extends IndexedTable> = E['view'] extends true ? `${T} is a view, which no site writes: its rows come from the tables it reads, so declare unscoped: { ${T}: 'read' }` : `${T} is a reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`;
553
602
  /** An `unscoped` declaration's `'write'` of a reference table, refused at its own line. */
554
603
  export type ReadOnlyUnscoped<Ix extends AnyDbIndex, U> = [ReadOnlyWritten<Ix, U>] extends [never] ? unknown : {
555
- readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T>>;
604
+ readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T, Ix['tables'][T]>>;
556
605
  };
557
606
  type KeylessMessage<T extends string> = `${T} is a reference table, which has no key: read it with list`;
558
607
  /** A table a site declared `unscoped`: its scope predicate is `true`, and `'read'` writes nothing. */
@@ -604,8 +653,8 @@ type RefFragment<Ix extends AnyDbIndex, D extends string, A extends string> = {
604
653
  [T in TableName<Ix>]: Ix['tables'][T]['mode'] extends 'app' ? (A extends Ix['tables'][T]['actions']['read'] ? T : never) : D extends Ix['tables'][T]['refs'] ? (A extends NamedActions<Ix['tables'][T]> ? T : never) : never;
605
654
  }[TableName<Ix>];
606
655
  /**
607
- * What a `Within` writes on a `'write'` site: the target of an UPDATE or DELETE whose action it holds, a column's own
608
- * write action included (the statement's SET is checked against its columns at run time).
656
+ * What a `Within` writes on a `'write'` site: the table of a fragment of `use: 'update'` or `'delete'` whose action it
657
+ * holds, a column's own write action included (the statement's columns are the approver's to review, not checked).
609
658
  */
610
659
  type WithinWrites<E extends IndexedTable, M extends 'read' | 'write'> = M extends 'write' ? E['actions']['update'] | E['actions']['delete'] | (keyof E['writes'] & string) : never;
611
660
  /** The tables a fragment of a `Within` of `D` and `A` reaches: those it lists by their read action, or writes on `M`. */
@@ -614,7 +663,7 @@ type WithinFragment<Ix extends AnyDbIndex, D extends string, A extends string, M
614
663
  }[TableName<Ix>];
615
664
  /** The tables a fragment of an `app` capability of `A` reaches: as `ctx.db.app` lists them for that action. */
616
665
  type AppFragment<Ix extends AnyDbIndex, A extends string> = {
617
- [T in TableName<Ix>]: Ix['tables'][T]['mode'] extends 'app' ? (A extends NamedActions<Ix['tables'][T]> ? T : never) : Ix['tables'][T]['mode'] extends 'dimension' | 'child' ? (A extends Ix['tables'][T]['actions']['read'] | Ix['tables'][T]['appRead'] ? T : never) : never;
666
+ [T in TableName<Ix>]: Ix['tables'][T]['mode'] extends 'app' ? ([Ix['tables'][T]['readsAny']] extends [true] ? T : A extends NamedActions<Ix['tables'][T]> ? T : never) : Ix['tables'][T]['mode'] extends 'dimension' | 'child' ? (A extends Ix['tables'][T]['actions']['read'] | Ix['tables'][T]['appRead'] ? T : never) : never;
618
667
  }[TableName<Ix>];
619
668
  /**
620
669
  * The tables `ctx.sql.scope(capability, table)` takes for a capability of type `C` on a site of mode `M`: those its
@@ -28,6 +28,11 @@ export interface DataSite {
28
28
  * only one it holds. Absent where the framework serves no file; the columns then read as ids and refuse every write.
29
29
  */
30
30
  readonly files?: FileBinding;
31
+ /**
32
+ * The actions a job holds over the whole application: those it declares that its key's token carries. A queue claim
33
+ * answers a file reference its holder may open when one of them reads the table, as a re-read of the row would.
34
+ */
35
+ readonly holds?: readonly string[];
31
36
  /** The texts the verified signed tokens of a public procedure's request carry: the row ids it may update or remove. */
32
37
  readonly carried?: ReadonlySet<string>;
33
38
  /** Throws unless the work running now is the invocation these handles were made for. */
@@ -75,3 +80,8 @@ export interface DataLayerParts {
75
80
  fenced<T>(runtime: DataLayerRuntime, work: (session: Session) => Promise<T>): Promise<T>;
76
81
  }
77
82
  export declare function dataAccess(parts: DataLayerParts): DataAccess;
83
+ /**
84
+ * When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
85
+ * at the next due row it would take but no sooner than a second after it, or never when it would take none.
86
+ */
87
+ export declare function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null;