@fabrika/db 0.9.0-dev.7 → 0.9.0-dev.71

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 (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +69 -13
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +67 -9
  10. package/src/errors.ts +9 -5
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +187 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +216 -77
  24. package/src/orm.ts +417 -158
  25. package/src/policy.ts +2043 -131
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1958 -167
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +39 -4
  35. package/src/testing-shared.ts +872 -148
  36. package/src/testing-sqlite.ts +215 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +172 -26
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +40 -9
  47. package/types/src/errors.d.ts +8 -5
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +35 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +167 -75
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +378 -27
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +7 -1
  70. package/types/src/testing-shared.d.ts +125 -26
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +176 -22
package/src/policy.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { Insertable, Selectable, SelectType, Updateable } from 'kysely'
1
+ import { READ_ANY } from '@fabrika/auth-core'
2
+ import type { Insertable, InsertType, Selectable, SelectType, Updateable } from 'kysely'
3
+ import { z } from 'zod/v4'
2
4
  import {
3
5
  freeze,
4
6
  hasOwn,
@@ -8,21 +10,31 @@ import {
8
10
  type NameSet,
9
11
  nameSet,
10
12
  namesOf,
11
- OBJECT_PROTOTYPE,
12
- ownDescriptor,
13
13
  ownEntry,
14
14
  ownKeys,
15
- ownNames,
16
- ownSymbols,
17
15
  parseList,
18
- prototypeOf,
16
+ plainRecord,
19
17
  setOwn,
20
18
  } from './builtins'
19
+ import {
20
+ type ConditionHop,
21
+ type ConditionModel,
22
+ type ConditionPolicy,
23
+ conditionReach,
24
+ type ConditionTable,
25
+ type HopRule,
26
+ insertProblem,
27
+ parseCondition,
28
+ singleForeignKey,
29
+ splitPath,
30
+ } from './conditions'
31
+ import type { DeclaredJson } from './description'
21
32
  import { PolicyError } from './errors'
22
33
  import { isPlainIdentifier } from './identifier'
34
+ import type { JsonColumnValue, JsonSchema } from './json'
23
35
  import type { Unavailable } from './orm-types'
24
36
  export type { RowOf } from './orm-types'
25
- import type { ColumnTypes, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
37
+ import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
26
38
 
27
39
  export interface DimensionScope<Col extends string> {
28
40
  readonly dimension: string
@@ -50,6 +62,8 @@ export interface ApplicationScope<Col extends string> {
50
62
  /** One action, or a list of them: a table that staff and a public procedure both read names both actions. */
51
63
  export type TableAction<A extends string> = A | readonly A[]
52
64
 
65
+ export { READ_ANY }
66
+
53
67
  export interface TableActions<A extends string> {
54
68
  readonly read: TableAction<A>
55
69
  readonly insert?: TableAction<A>
@@ -57,6 +71,11 @@ export interface TableActions<A extends string> {
57
71
  readonly delete?: TableAction<A>
58
72
  }
59
73
 
74
+ /** An application table's actions: its read may be `'any'` instead of its actions (`READ_ANY`). */
75
+ export interface ApplicationActions<A extends string> extends Omit<TableActions<A>, 'read'> {
76
+ readonly read: TableAction<A> | typeof READ_ANY
77
+ }
78
+
60
79
  /**
61
80
  * A queue table's columns (ADR-0060's drain): `due` is when a row is next claimed, `null` once it is done; `attempts`
62
81
  * counts its claims, and a row with `maxAttempts` (default 10) of them is no longer claimed.
@@ -91,26 +110,147 @@ interface WritablePolicy<Col extends string, A extends string, V extends Col, Ac
91
110
  * file reference. The table's actions are the file's authority.
92
111
  */
93
112
  readonly files?: FilePolicies<Col>
113
+ /** The relations this table's rows confer (`relations` of the vocabulary): each row holds one principal at one node. */
114
+ readonly confers?: { readonly [relation: string]: ConfersPolicy<Col> }
115
+ /** Conditions that narrow an action of this table: a row the condition does not admit is out of that action's reach. */
116
+ readonly when?: { readonly [action in A]?: ConditionPolicy<Col> }
117
+ /**
118
+ * Relation → action → a condition on the rows that relation reaches for that action: it narrows the relation's terms
119
+ * only, never an IAM grant, a member reveal or a path grant of the action.
120
+ */
121
+ readonly relationWhen?: { readonly [relation: string]: { readonly [action in A]?: ConditionPolicy<Col> } }
122
+ /** Relation of this table's own dimension, or of one it reads through → the ancestor node a row the relation reaches reveals. */
123
+ readonly reveals?: { readonly [relation: string]: RevealsPolicy<Col, A> }
124
+ /**
125
+ * Dimension outside the chain → the foreign key column a read reaches a row through: a `Within` of the dimension, or a
126
+ * relation at it, reads the row, and every write follows containment only. No update writes the column. Or
127
+ * `<nearest container column>.<its column>`: the row is read through its nearest container's own read path.
128
+ */
129
+ readonly readThrough?: { readonly [dimension: string]: Col | `${Col}.${string}` }
130
+ /**
131
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds on the table's rows, writes included:
132
+ * a grant of one of them at the node the path names, or above it, reaches the row for that action. Whoever inserts
133
+ * the path's column must hold every listed action at the node it names.
134
+ */
135
+ readonly writeThrough?: { readonly [dimension: string]: readonly A[] }
136
+ /**
137
+ * This table's own dimension, or one it reads through (`readThrough`) → the ancestor node a row reveals to its
138
+ * members: a grant of one of `actions` at the row's own node, or at the node its path names, holds that action at its
139
+ * node in `to` too, while `when` admits the row.
140
+ */
141
+ readonly memberReveals?: { readonly [dimension: string]: MemberRevealsPolicy<Col, A> }
142
+ /**
143
+ * Relation → an access view that lists the rows the relation reaches: the escape path for a rule no structured
144
+ * declaration expresses. The view's SQL decides; the layer binds only the caller's principal and the nodes it holds
145
+ * the relation inside, never a handler value.
146
+ */
147
+ readonly access?: { readonly [relation: string]: AccessPolicy }
148
+ }
149
+
150
+ /** An access view: `row` names this table's key; `principal` is compared to the caller, `member` to the nodes it holds the relation inside. */
151
+ export interface AccessPolicy {
152
+ readonly view: string
153
+ readonly row: string
154
+ readonly principal?: string
155
+ readonly member?: string
156
+ }
157
+
158
+ /** What a row reveals to a caller with a grant at its node: its node in `to`, for `actions`, while `when` admits the row. */
159
+ export interface MemberRevealsPolicy<Col extends string, A extends string> {
160
+ readonly to: string
161
+ readonly actions: readonly A[]
162
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
163
+ readonly when?: ConditionPolicy<Col>
164
+ /** Through a path, on a table with an insert action: the writer picks the node, and `self` lets it pick its own. */
165
+ readonly assign?: { readonly self?: true }
166
+ }
167
+
168
+ /**
169
+ * A row of the table that a relation reaches reveals its node in `to`, an ancestor dimension of its chain: the relation
170
+ * then holds `actions` (those of them its roles list in `via`) there, while `when` admits the row.
171
+ */
172
+ export interface RevealsPolicy<Col extends string, A extends string> {
173
+ readonly to: string
174
+ readonly actions: readonly A[]
175
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
176
+ readonly when?: ConditionPolicy<Col>
177
+ /**
178
+ * Required on a reveal matched through `readThrough` of a table with an insert action: the row's writer picks the node,
179
+ * so an insert delegates. Without `self`, an insert that names a node where its writer holds the relation is refused.
180
+ */
181
+ readonly assign?: { readonly self?: true }
182
+ }
183
+
184
+ /**
185
+ * A relation source: each row says that the principal in `principal` stands in the relation to the node `node` holds,
186
+ * until `expires` (none: no deadline) and while `when` admits the row. Writing a row is delegation.
187
+ */
188
+ export interface ConfersPolicy<Col extends string> {
189
+ /**
190
+ * The column that holds the principal, or `<column>.<principal column>`: one foreign key of the table into the key of
191
+ * the table whose column holds it. The table's `createdBy` names the row's writer (it needs `assign.self`).
192
+ */
193
+ readonly principal: Col | `${Col}.${string}`
194
+ /** The column that names the node; by default the table's column for the relation's dimension (its key or its chain). */
195
+ readonly node?: Col
196
+ /** A timestamp column: the row confers nothing once it passed. */
197
+ readonly expires?: Col
198
+ /** A condition on the row's own columns (no foreign-key path): `{ revoked_at: { isNull: true } }`. */
199
+ readonly when?: ConditionPolicy<Col>
200
+ /**
201
+ * Inserting a row delegates the relation's actions to its principal, bounded by the inserting Ref's node: at most
202
+ * `maxDays` ahead (which needs `expires`), and to the inserting principal itself only with `self`.
203
+ */
204
+ readonly assign?: { readonly maxDays?: number; readonly self?: true }
94
205
  }
95
206
 
96
207
  /** A table's file columns: column → the name of a file kind of the contract (`c.files`). */
97
208
  export type FilePolicies<Col extends string> = { readonly [C in Col]?: string }
98
209
 
210
+ /** A table's JSON columns with a declared shape: column → a zod schema whose output is JSON. */
211
+ export type JsonPolicies<Col extends string> = { readonly [C in Col]?: JsonSchema }
212
+
213
+ /** The JSON columns of a generated row type: those whose write type is a JSON value (`JsonColumnValue`). */
214
+ export type JsonColumn<Row> = {
215
+ [K in keyof Row & string]: [Exclude<InsertType<Row[K]>, null | undefined>] extends [JsonColumnValue]
216
+ ? [JsonColumnValue] extends [Exclude<InsertType<Row[K]>, null | undefined>] ? K : never
217
+ : never
218
+ }[keyof Row & string]
219
+
220
+ /** The schemas table `T`'s policy declares for its JSON columns (`json`); none when it declares none. */
221
+ export type JsonSchemasOf<P, T> = PolicyOf<P, T> extends { readonly json: infer J } ? J : Record<never, never>
222
+
223
+ /** `null` where column `K` of the generated row is nullable. */
224
+ type NullOf<Row, K> = K extends keyof Row ? (null extends InsertType<Row[K]> ? null : never) : never
225
+
226
+ /**
227
+ * A row (`'output'`) or a write (`'input'`) of a table whose policy declares JSON schemas `J`: each declared column is
228
+ * the schema's output or input, and `null` where the column is nullable. A row also carries the declared columns in
229
+ * `DeclaredJson`, which keeps them out of a condition and an order (`ComparableColumn`).
230
+ */
231
+ export type WithJson<R, J, Row, Io extends 'input' | 'output'> = [keyof J] extends [never] ? R
232
+ :
233
+ & {
234
+ [K in keyof R]: K extends keyof J ? J[K] extends JsonSchema ? (Io extends 'output' ? z.output<J[K]> : z.input<J[K]>) | NullOf<Row, K> : R[K]
235
+ : R[K]
236
+ }
237
+ & (Io extends 'output' ? DeclaredJson<keyof J & string> : unknown)
238
+
99
239
  /**
100
- * A column's own actions. `read`: only a capability of exactly that action reads, filters or sorts by the column;
101
- * without one it falls back to the table's read action. `write`: only a capability of that action updates the column,
102
- * and the table's update action does not, so the column is not in `update`.
240
+ * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
241
+ * without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
242
+ * column, so the column is not in `update`; a listed table update action writes it beside its update list.
103
243
  */
104
244
  export type ColumnPolicies<Col extends string, A extends string> = { readonly [C in Col]?: ColumnPolicy<A> }
105
245
 
106
- /** A column's own read action, its own write action, or both. */
246
+ /** A column's own read actions and its own write actions (each one, or a list as a table operation takes), or both. */
107
247
  export interface ColumnPolicy<A extends string> {
108
- readonly read?: A
109
- readonly write?: A
248
+ readonly read?: TableAction<A>
249
+ readonly write?: TableAction<A>
110
250
  }
111
251
 
112
252
  /** A table no handler writes (a reference table) declares column read actions only. */
113
- export type ColumnReadPolicies<Col extends string, A extends string> = { readonly [C in Col]?: { readonly read: A } }
253
+ export type ColumnReadPolicies<Col extends string, A extends string> = { readonly [C in Col]?: { readonly read: TableAction<A> } }
114
254
 
115
255
  export interface DimensionPolicy<Col extends string, A extends string, V extends Col = Col> extends WritablePolicy<Col, A, V, RecordActions<A>> {
116
256
  readonly scope: DimensionScope<Col>
@@ -123,7 +263,9 @@ export interface ChildPolicy<Table extends string, Col extends string, A extends
123
263
  }
124
264
 
125
265
  /** An application table: written like a dimension table, by an `app` endpoint whose action is the operation's. */
126
- export interface ApplicationPolicy<Col extends string, A extends string, V extends Col = Col> extends WritablePolicy<Col, A, V> {
266
+ export interface ApplicationPolicy<Col extends string, A extends string, V extends Col = Col>
267
+ extends WritablePolicy<Col, A, V, ApplicationActions<A>>
268
+ {
127
269
  readonly scope: ApplicationScope<Col>
128
270
  }
129
271
 
@@ -162,6 +304,15 @@ export interface TableColumns<Col extends string = string, Table extends string
162
304
  readonly timestamps?: readonly Col[]
163
305
  /** On SQLite, the columns declared `BOOLEAN`, stored as 0 or 1 and read as a boolean; absent when none. */
164
306
  readonly booleans?: readonly Col[]
307
+ /** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
308
+ readonly json?: readonly Col[]
309
+ /**
310
+ * The columns declared NOT NULL; absent when none. A foreign key that holds a row's tenant needs its ancestor columns
311
+ * among them: under MATCH SIMPLE a null in one skips the whole key.
312
+ */
313
+ readonly notNull?: readonly Col[]
314
+ /** A view: read-only, with no foreign key; absent for a table. */
315
+ readonly view?: true
165
316
  }
166
317
 
167
318
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -178,9 +329,17 @@ export type ScopeModel =
178
329
  | { readonly mode: 'reference'; readonly reason: string }
179
330
  | { readonly mode: 'app'; readonly reason: string; readonly key: string }
180
331
 
181
- /** Each operation's actions: any one of them allows it. `read` names at least one; an empty list allows no operation. */
332
+ /**
333
+ * Each operation's actions: any one of them allows it. `read` names at least one, unless `readAny`; an empty list
334
+ * allows no operation.
335
+ */
182
336
  export interface ActionModel {
183
337
  readonly read: readonly string[]
338
+ /**
339
+ * An application table read with `'any'`: every `app` endpoint, job and webhook reads it, whatever its action; never a
340
+ * public procedure or a scoped site. `read` is empty then, and a `when` narrows only the writes of its action.
341
+ */
342
+ readonly readAny: boolean
184
343
  readonly insert: readonly string[]
185
344
  readonly update: readonly string[]
186
345
  readonly delete: readonly string[]
@@ -215,23 +374,147 @@ export interface TableModel {
215
374
  readonly queue: QueueModel | undefined
216
375
  /** The file columns, each with its file kind: a reference to `fabrika_files`, written only with a file reference. */
217
376
  readonly files: Readonly<Record<string, string>>
218
- /** The columns that declare their own read action, as declared (also those equal to the table's). */
219
- readonly columnReads: Readonly<Record<string, string>>
220
- /** The columns that declare their own write action: only a capability of it updates them. */
221
- readonly columnWrites: Readonly<Record<string, string>>
377
+ /** The columns that declare their own read actions, as declared (also those equal to the table's). */
378
+ readonly columnReads: Readonly<Record<string, readonly string[]>>
379
+ /** The columns that declare their own write actions, as declared: only a capability of one of them updates them. */
380
+ readonly columnWrites: Readonly<Record<string, readonly string[]>>
222
381
  /** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
223
382
  readonly dates: NameSet
224
383
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
225
384
  readonly timestamps: NameSet
226
385
  /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
227
386
  readonly booleans: NameSet
387
+ /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
388
+ readonly json: NameSet
389
+ /** The JSON columns the policy declares a schema for: each write is parsed by it, and each read value too. */
390
+ readonly jsonSchemas: Readonly<Record<string, JsonSchema>>
391
+ /** The columns the column list declares NOT NULL. */
392
+ readonly notNull: NameSet
228
393
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
229
394
  readonly foreignKeys: readonly ForeignKey[]
395
+ /** A view: a child or reference table no operation but a read reaches, whose containment only its SQL states. */
396
+ readonly view: boolean
230
397
  /**
231
398
  * The containment links this table carries a column for, nearest first: a dimension table's container and
232
399
  * the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
233
400
  */
234
401
  readonly chain: readonly Container[]
402
+ /** The relations this table's rows confer, each with its columns, its condition and its delegation bound. */
403
+ readonly confers: readonly RelationSource[]
404
+ /** The condition each action of the table holds a row under; an action without one is not narrowed. */
405
+ readonly when: Readonly<Record<string, ConditionModel>>
406
+ /** Relation → action → the condition the rows that relation reaches hold for that action under; ANDed onto its terms only. */
407
+ readonly relationWhen: Readonly<Record<string, Readonly<Record<string, ConditionModel>>>>
408
+ /** The ancestor nodes this table's rows reveal to a relation of its own dimension or of one it reads through. */
409
+ readonly reveals: readonly RevealModel[]
410
+ /** The secondary read paths: a dimension outside the chain, by the column that holds the row's node in it. */
411
+ readonly readThrough: readonly SecondaryPath[]
412
+ /** The ancestor nodes this table's rows reveal to a grant at their own node. */
413
+ readonly memberReveals: readonly MemberRevealModel[]
414
+ /** The access views of the relations whose reach a view's SQL decides. */
415
+ readonly access: readonly AccessModel[]
416
+ }
417
+
418
+ /** A relation's access view over this table: `T.<key> in (select V.<row> from V where <bindings>)`. */
419
+ export interface AccessModel {
420
+ readonly relation: string
421
+ /** The relation's dimension: a hold inside a node of it alone binds `member`. */
422
+ readonly dimension: string
423
+ readonly view: string
424
+ readonly row: string
425
+ readonly principal: string | undefined
426
+ readonly member: string | undefined
427
+ }
428
+
429
+ /**
430
+ * A read path to a dimension outside the chain: `column` holds a key of `table`, which owns `dimension` and lies in
431
+ * `chain`. The column's foreign key covers every ancestor the two chains share, so the node lies in the row's own tenant.
432
+ */
433
+ export interface SecondaryPath {
434
+ readonly dimension: string
435
+ readonly column: string
436
+ readonly table: string
437
+ readonly key: string
438
+ readonly chain: readonly Container[]
439
+ /**
440
+ * The nearest container whose own path this is: the row's `column` of it, its `table` and `key`. `column` above is
441
+ * then the container's column, and the path is read as `T.<via column> in (select C.<key> from C where …)`.
442
+ */
443
+ readonly via: ContainerHop | undefined
444
+ /** The actions a `Ref` held through the path holds on the table's rows (`writeThrough`); a `Within` reads through every path. */
445
+ readonly writes: readonly string[]
446
+ }
447
+
448
+ /** The row's nearest containment column, and the table and key it names. */
449
+ export interface ContainerHop {
450
+ readonly column: string
451
+ readonly table: string
452
+ readonly key: string
453
+ }
454
+
455
+ /**
456
+ * A row of `table` that `relation` reaches reveals its node in `dimension`, held in `column`: the relation holds
457
+ * `actions` at that node while `when` admits the row.
458
+ */
459
+ export interface RevealModel {
460
+ readonly relation: string
461
+ readonly table: string
462
+ /** The table's key, which the relation's nodes match unless the reveal is matched through `path`. */
463
+ readonly key: string
464
+ /**
465
+ * The secondary path whose node, or an ancestor of it, the relation's nodes match. A reveal matched through one holds
466
+ * a `Ref` of an action only where the path does (`writeThrough`).
467
+ */
468
+ readonly path: SecondaryPath | undefined
469
+ /** The bound on an insert's delegation through `path`: `undefined` when no handler inserts a row of the table. */
470
+ readonly assign: { readonly self: boolean } | undefined
471
+ readonly dimension: string
472
+ readonly column: string
473
+ readonly actions: readonly string[]
474
+ readonly when: ConditionModel | undefined
475
+ }
476
+
477
+ /**
478
+ * A row of `table`, a node of `source` (its own dimension, keyed by `key`), reveals its node in `dimension`, held in
479
+ * `column`: a grant of one of `actions` at the row's node holds the action there too, for a `Within`'s reads, while
480
+ * `when` admits the row. Only a grant at the node itself counts, never one at a container of it: an insert would
481
+ * otherwise reveal the ancestor to the container's members at once.
482
+ */
483
+ export interface MemberRevealModel {
484
+ readonly source: string
485
+ readonly table: string
486
+ /** The column a grant's nodes match: the table's key, or `path`'s column. */
487
+ readonly key: string
488
+ /** The secondary path whose node a grant names; a `Ref` holds an action through it only where the path does. */
489
+ readonly path: SecondaryPath | undefined
490
+ /** The bound on an insert's pick of the node through `path`: `undefined` when no handler inserts a row of the table. */
491
+ readonly assign: { readonly self: boolean } | undefined
492
+ readonly dimension: string
493
+ readonly column: string
494
+ readonly actions: readonly string[]
495
+ readonly when: ConditionModel | undefined
496
+ }
497
+
498
+ /** One relation's source table: what a relation term reads, and what a write of its rows is bounded by. */
499
+ export interface RelationSource {
500
+ readonly relation: string
501
+ readonly dimension: string
502
+ readonly table: string
503
+ /** The source's column that decides the principal: it holds it, or it references the row of `principalPath` that does. */
504
+ readonly principal: string
505
+ readonly principalPath: PrincipalPath | undefined
506
+ readonly node: string
507
+ readonly expires: string | undefined
508
+ readonly when: ConditionModel | undefined
509
+ /** `undefined` when the table has no insert action, so no handler writes a row of it. */
510
+ readonly assign: { readonly maxDays: number | undefined; readonly self: boolean } | undefined
511
+ }
512
+
513
+ /** `S.<principal>` references `key` of `table`, whose `column` holds the principal the source row names. */
514
+ export interface PrincipalPath {
515
+ readonly table: string
516
+ readonly key: string
517
+ readonly column: string
235
518
  }
236
519
 
237
520
  /** A child's `column` and `inherit`, when omitted, are derived from its parent while the tables are linked. */
@@ -245,7 +528,21 @@ type ParsedScope =
245
528
  readonly inherit: readonly string[] | undefined
246
529
  }
247
530
 
248
- type ParsedTable = Omit<TableModel, 'chain' | 'scope'> & { readonly scope: ParsedScope }
531
+ type ParsedTable =
532
+ & Omit<TableModel, 'chain' | 'scope' | 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
533
+ & {
534
+ readonly scope: ParsedScope
535
+ readonly confersInput: unknown
536
+ readonly whenInput: unknown
537
+ readonly relationWhenInput: unknown
538
+ readonly revealsInput: unknown
539
+ readonly readThroughInput: unknown
540
+ readonly writeThroughInput: unknown
541
+ readonly memberRevealsInput: unknown
542
+ readonly accessInput: unknown
543
+ /** The stamped columns the policy did not name: a written table's `version` and `created_by` (`conventional`). */
544
+ readonly byConvention: NameSet
545
+ }
249
546
 
250
547
  let readModels: <DB, P>(tables: Tables<DB, P>) => TableModels
251
548
  let hasModels: (value: object) => boolean = () => false
@@ -301,7 +598,7 @@ export function defineTables<DB, P>(vocabularyInput: unknown, columns: unknown):
301
598
  /** `defineTables(vocabulary, columns)` answers the policies' builder, or names the fix for an untyped column list. */
302
599
  export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never]
303
600
  ? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'>
304
- : DefineVocabularyPolicies<ColumnTypes<C>, V>
601
+ : DefineVocabularyPolicies<ColumnTypes<C>, V, ColumnViews<C>>
305
602
 
306
603
  /**
307
604
  * The same policies read from values nobody type-checked: `src/db/tables.ts` and its vocabulary as the static reader
@@ -318,8 +615,13 @@ type Containment = Readonly<Record<string, { readonly container: string | undefi
318
615
  interface VocabularyModel {
319
616
  readonly dimensions: Containment
320
617
  readonly actions: NameSet
618
+ /** Each relation of the vocabulary, by name, with the dimension its nodes are of. */
619
+ readonly relations: Readonly<Record<string, string>>
321
620
  }
322
621
 
622
+ /** A relation's name: it travels in a token's pseudo-scope `~rel:<name>`, so it is a plain word. */
623
+ const RELATION_NAME = /^[a-z][A-Za-z0-9]*$/
624
+
323
625
  function parseVocabulary(input: unknown): VocabularyModel {
324
626
  const vocabulary = plainRecord(input, 'the vocabulary')
325
627
  const dimensions = plainRecord(ownEntry(vocabulary, 'dimensions'), 'the vocabulary dimensions')
@@ -343,12 +645,58 @@ function parseVocabulary(input: unknown): VocabularyModel {
343
645
  }
344
646
  }
345
647
  const actions = ownKeys(plainRecord(ownEntry(vocabulary, 'actions'), 'the vocabulary actions'))
346
- return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
648
+ if (includes(actions, READ_ANY)) {
649
+ throw new PolicyError(`the vocabulary may not declare the action '${READ_ANY}': a table's actions.read says '${READ_ANY}' for every action`)
650
+ }
651
+ const relationsInput = ownEntry(vocabulary, 'relations')
652
+ const relations: Record<string, string> = {}
653
+ if (relationsInput !== undefined) {
654
+ const declared = plainRecord(relationsInput, 'the vocabulary relations')
655
+ const relationNames = ownKeys(declared)
656
+ for (let index = 0; index < relationNames.length; index++) {
657
+ const relation = relationNames[index] ?? ''
658
+ if (!RELATION_NAME.test(relation)) {
659
+ throw new PolicyError(`the vocabulary relation ${relation}: a relation name must match ${RELATION_NAME.source}`)
660
+ }
661
+ const dimension = ownEntry(plainRecord(ownEntry(declared, relation), `the vocabulary relation ${relation}`), 'dimension')
662
+ if (typeof dimension !== 'string' || !hasOwn(dimensions, dimension)) {
663
+ throw new PolicyError(`the vocabulary relation ${relation} is of ${String(dimension)}, which is not one of its dimensions`)
664
+ }
665
+ setOwn(relations, relation, dimension)
666
+ }
667
+ }
668
+ return freeze({ dimensions: freeze(containment), actions: nameSet(actions), relations: freeze(relations) })
347
669
  }
348
670
 
349
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans'])
671
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'notNull', 'view'])
350
672
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
351
- const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
673
+ const POLICY_FIELDS = nameSet([
674
+ 'scope',
675
+ 'actions',
676
+ 'insert',
677
+ 'update',
678
+ 'version',
679
+ 'createdBy',
680
+ 'columns',
681
+ 'queue',
682
+ 'files',
683
+ 'json',
684
+ 'confers',
685
+ 'when',
686
+ 'relationWhen',
687
+ 'reveals',
688
+ 'readThrough',
689
+ 'writeThrough',
690
+ 'memberReveals',
691
+ 'access',
692
+ ])
693
+ const REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
694
+ const MEMBER_REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
695
+ const REVEAL_ASSIGN_FIELDS = nameSet(['self'])
696
+ const CONFERS_FIELDS = nameSet(['principal', 'node', 'expires', 'when', 'assign'])
697
+ const ASSIGN_FIELDS = nameSet(['maxDays', 'self'])
698
+ /** A delegated row lasts at most ten years ahead: a bound, not a convenience. */
699
+ const MAX_ASSIGN_DAYS = 3650
352
700
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
353
701
  const ACTION_FIELDS = nameSet(['read', 'insert', 'update', 'delete', 'appRead', 'appCount'])
354
702
  const DIMENSION_FIELDS = nameSet(['dimension', 'key', 'in'])
@@ -358,25 +706,6 @@ const REFERENCE_FIELDS = nameSet(['reference'])
358
706
  const APPLICATION_FIELDS = nameSet(['app', 'key'])
359
707
  const COLUMN_FIELDS = nameSet(['read', 'write'])
360
708
 
361
- /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
362
- function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>> {
363
- const prototype: unknown = typeof value === 'object' && value !== null && !isArray(value) ? prototypeOf(value) : undefined
364
- if ((prototype !== OBJECT_PROTOTYPE && prototype !== null) || typeof value !== 'object' || value === null || ownSymbols(value).length > 0) {
365
- throw new PolicyError(`${what} must be a plain object`)
366
- }
367
- const copy: Record<string, unknown> = {}
368
- const keys = ownNames(value)
369
- for (let index = 0; index < keys.length; index++) {
370
- const key = keys[index] ?? ''
371
- const descriptor = ownDescriptor(value, key)
372
- if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
373
- throw new PolicyError(`${what}: ${key} is an accessor; a policy holds plain values`)
374
- }
375
- setOwn(copy, key, descriptor.value)
376
- }
377
- return freeze(copy)
378
- }
379
-
380
709
  /** Unknown keys are refused, not dropped: a misspelt `insrt` would otherwise leave the table without its column list. */
381
710
  function onlyFields(record: Readonly<Record<string, unknown>>, allowed: NameSet, what: string): void {
382
711
  const keys = ownKeys(record)
@@ -400,17 +729,41 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
400
729
  }
401
730
  }
402
731
  const parsed: ParsedTable[] = []
732
+ const views: Record<string, ViewColumns> = {}
403
733
  for (let index = 0; index < tables.length; index++) {
404
734
  const table = tables[index] ?? ''
405
735
  const policy = ownEntry(policies, table)
736
+ const entry = ownEntry(columns, table)
737
+ if (isViewEntry(table, entry)) {
738
+ const names = parseList(ownEntry(plainRecord(entry, `${table}: the column list entry`), 'columns'), (name) => String(name))
739
+ setOwn(views, table, freeze({ columns: nameSet(names ?? []), policy: policy !== undefined }))
740
+ }
741
+ // A view without a policy stays what it was before codegen read views: only ctx.sql reads it.
742
+ if (policy === undefined && isViewEntry(table, entry)) {
743
+ continue
744
+ }
406
745
  if (policy === undefined) {
407
746
  throw new PolicyError(`${table}: every table needs a policy in tables.ts`)
408
747
  }
409
- parsed[index] = parseTable(table, ownEntry(columns, table), policy, vocabulary)
748
+ parsed[parsed.length] = parseTable(table, entry, policy, vocabulary)
749
+ }
750
+ return linkTables(parsed, vocabulary, views)
751
+ }
752
+
753
+ /** Whether a column list entry marks a view: its `view` is `true`, or absent for a table. */
754
+ function isViewEntry(table: string, entry: unknown): boolean {
755
+ const view = ownEntry(plainRecord(entry, `${table}: the column list entry`), 'view')
756
+ if (view !== undefined && view !== true) {
757
+ throw new PolicyError(`${table}: the column list entry's view is true or absent`)
410
758
  }
411
- return linkTables(parsed, vocabulary.dimensions)
759
+ return view === true
412
760
  }
413
761
 
762
+ /** The version column of a written table whose policy names none, when the table has it. */
763
+ const VERSION_COLUMN = 'version'
764
+ /** The `createdBy` column of a written table whose policy names none, when the table has it. */
765
+ const CREATED_BY_COLUMN = 'created_by'
766
+
414
767
  /** How a policy names its columns: one it states must exist, and so must one a convention derives for it. */
415
768
  interface ColumnReader {
416
769
  readonly column: (name: unknown, field: string) => string
@@ -464,6 +817,14 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
464
817
  const scopeInput = plainRecord(ownEntry(policy, 'scope'), `${table}: scope`)
465
818
  const foreignKeys = parseForeignKeys(table, ownEntry(entry, 'foreignKeys'), column)
466
819
  const scope = parseScope(table, scopeInput, { column, columnsOf, derived }, vocabulary.dimensions)
820
+ const view = isViewEntry(table, entry)
821
+ if (view && scope.mode !== 'child' && scope.mode !== 'reference') {
822
+ throw new PolicyError(
823
+ `${table}: a view is read-only, so it takes a child scope, { child, key?, column?, inherit? }, or { reference }; ${
824
+ scope.mode === 'app' ? 'an application' : 'a dimension'
825
+ } table's rows are written`,
826
+ )
827
+ }
467
828
  const action = (value: unknown, field: string): string => {
468
829
  const name = nonEmpty(table, value, field)
469
830
  if (!inSet(vocabulary.actions, name)) {
@@ -476,13 +837,24 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
476
837
  const actions = parseActions(table, scopeInput, ownEntry(policy, 'actions'), action)
477
838
  const insert = nameSet(columnsOf(ownEntry(policy, 'insert'), 'insert'))
478
839
  const update = nameSet(columnsOf(ownEntry(policy, 'update'), 'update'))
840
+ const writable = !view && (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app')
841
+ // A written table's column named by the convention is stamped unless the policy names another (`NormalizedPolicies`).
842
+ const conventional = (name: string): string | undefined => (writable && inSet(columns, name) ? name : undefined)
479
843
  const versionInput = ownEntry(policy, 'version')
480
844
  const createdByInput = ownEntry(policy, 'createdBy')
481
- const version = versionInput === undefined ? undefined : column(versionInput, 'version')
482
- const createdBy = createdByInput === undefined ? undefined : column(createdByInput, 'createdBy')
845
+ const version = versionInput === undefined ? conventional(VERSION_COLUMN) : column(versionInput, 'version')
846
+ const createdBy = createdByInput === undefined ? conventional(CREATED_BY_COLUMN) : column(createdByInput, 'createdBy')
847
+ const unnamed: string[] = []
848
+ if (versionInput === undefined && version !== undefined) {
849
+ unnamed[unnamed.length] = version
850
+ }
851
+ if (createdByInput === undefined && createdBy !== undefined) {
852
+ unnamed[unnamed.length] = createdBy
853
+ }
854
+ const byConvention = nameSet(unnamed)
483
855
  const restricted: string[] = []
484
- const columnReads: Record<string, string> = {}
485
- const columnWrites: Record<string, string> = {}
856
+ const columnReads: Record<string, readonly string[]> = {}
857
+ const columnWrites: Record<string, readonly string[]> = {}
486
858
  const columnsInput = ownEntry(policy, 'columns')
487
859
  const columnPolicies = columnsInput === undefined ? freeze({}) : plainRecord(columnsInput, `${table}: columns`)
488
860
  const declared = ownKeys(columnPolicies)
@@ -496,15 +868,23 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
496
868
  throw new PolicyError(`${table}: columns.${name} declares no action; it takes read, write or both`)
497
869
  }
498
870
  if (readInput !== undefined) {
499
- const read = action(readInput, `columns.${name}.read`)
500
- setOwn(columnReads, name, read)
501
- // With several read actions, a column of one of them is hidden from the others.
502
- if (actions.read.length > 1 || !includes(actions.read, read)) {
871
+ const reads = isArray(readInput)
872
+ ? distinctActions(table, readInput, `columns.${name}.read`, action)
873
+ : freeze([action(readInput, `columns.${name}.read`)])
874
+ setOwn(columnReads, name, reads)
875
+ // Hidden from a table read action its list leaves out; `'any'` names none, so it hides it from every one.
876
+ if (actions.read.length === 0 || !everyIncluded(actions.read, reads)) {
503
877
  restricted[restricted.length] = name
504
878
  }
505
879
  }
880
+ if (writeInput !== undefined && view) {
881
+ throw new PolicyError(viewWrite(table))
882
+ }
506
883
  if (writeInput !== undefined) {
507
- setOwn(columnWrites, name, columnWrite(table, name, action(writeInput, `columns.${name}.write`), actions, update))
884
+ const writes = isArray(writeInput)
885
+ ? distinctActions(table, writeInput, `columns.${name}.write`, action)
886
+ : freeze([action(writeInput, `columns.${name}.write`)])
887
+ setOwn(columnWrites, name, columnWrite(table, name, writes, actions, update))
508
888
  }
509
889
  }
510
890
  const hidden = nameSet(restricted)
@@ -514,21 +894,29 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
514
894
  throw new PolicyError(`${table}: the key ${scope.key} takes no action of its own`)
515
895
  }
516
896
  if (version !== undefined && hasOwn(columnPolicies, version)) {
517
- throw new PolicyError(`${table}: the version ${version} takes no action of its own`)
897
+ throw new PolicyError(`${table}: the version ${version} takes no action of its own${conventionOf(byConvention, version, 'version') ?? ''}`)
518
898
  }
519
- const writable = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app'
520
899
  const queueInput = ownEntry(policy, 'queue')
521
900
  const filesInput = ownEntry(policy, 'files')
901
+ // On a view, an empty insert or update list is refused too: it states a write the view never takes.
902
+ if (view && (hasOwn(policy, 'insert') || hasOwn(policy, 'update'))) {
903
+ throw new PolicyError(viewWrite(table))
904
+ }
522
905
  if (
523
906
  !writable
524
907
  && (namesOf(insert).length > 0 || namesOf(update).length > 0 || version !== undefined || createdBy !== undefined
525
- || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined)
908
+ || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined
909
+ || actions.insert.length > 0 || actions.update.length > 0 || actions.delete.length > 0)
526
910
  ) {
527
- throw new PolicyError(`${table}: a ${scope.mode} table is never written by a handler`)
911
+ throw new PolicyError(view ? viewWrite(table) : `${table}: a ${scope.mode} table is never written by a handler`)
528
912
  }
529
913
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
530
914
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
531
915
  const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
916
+ const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
917
+ const jsonPolicy = ownEntry(policy, 'json')
918
+ const jsonSchemas = jsonPolicy === undefined ? freeze({}) : parseJsonSchemas(table, jsonPolicy, column, json)
919
+ const notNull = parseColumnSet(table, ownEntry(entry, 'notNull'), column, 'notNull')
532
920
  const queue = queueInput === undefined
533
921
  ? undefined
534
922
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -557,7 +945,20 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
557
945
  dates,
558
946
  timestamps,
559
947
  booleans,
948
+ json,
949
+ jsonSchemas,
950
+ notNull,
560
951
  foreignKeys,
952
+ view,
953
+ confersInput: ownEntry(policy, 'confers'),
954
+ whenInput: ownEntry(policy, 'when'),
955
+ relationWhenInput: ownEntry(policy, 'relationWhen'),
956
+ revealsInput: ownEntry(policy, 'reveals'),
957
+ readThroughInput: ownEntry(policy, 'readThrough'),
958
+ writeThroughInput: ownEntry(policy, 'writeThrough'),
959
+ memberRevealsInput: ownEntry(policy, 'memberReveals'),
960
+ accessInput: ownEntry(policy, 'access'),
961
+ byConvention,
561
962
  }
562
963
  }
563
964
 
@@ -613,19 +1014,61 @@ function parseFileColumns(
613
1014
  }
614
1015
 
615
1016
  /**
616
- * A column's own write action takes the column away from the table's update action: one action writes a column, so
617
- * the column is not in `update`, and the action is not the update action (that one lists the column in `update`).
1017
+ * The schemas of `json`: each names a JSON column of the column list, with a zod schema whose output is JSON, which
1018
+ * `z.toJSONSchema` can describe. A `Date`, a `bigint`, a `Map`, a transform or `z.custom()` is refused: the layer
1019
+ * stores the output and parses it again on read, so it must be a JSON value the schema accepts.
1020
+ */
1021
+ function parseJsonSchemas(
1022
+ table: string,
1023
+ input: unknown,
1024
+ column: (name: unknown, field: string) => string,
1025
+ jsonColumns: NameSet,
1026
+ ): Readonly<Record<string, JsonSchema>> {
1027
+ const schemas = plainRecord(input, `${table}: json`)
1028
+ const names = ownKeys(schemas)
1029
+ if (names.length === 0) {
1030
+ throw new PolicyError(`${table}: json declares no column; remove it or name a JSON column and its zod schema`)
1031
+ }
1032
+ const parsed: Record<string, JsonSchema> = {}
1033
+ for (let index = 0; index < names.length; index++) {
1034
+ const name = column(names[index], 'json')
1035
+ if (!inSet(jsonColumns, name)) {
1036
+ const listed = namesOf(jsonColumns).join(', ') || 'none'
1037
+ throw new PolicyError(`${table}: json names ${name}, which is not a JSON column (jsonb, or JSONB on SQLite; JSON columns: ${listed})`)
1038
+ }
1039
+ const schema = ownEntry(schemas, name)
1040
+ if (!(schema instanceof z.core.$ZodType)) {
1041
+ throw new PolicyError(`${table}: json.${name} is not a zod schema (import z from 'zod/v4')`)
1042
+ }
1043
+ try {
1044
+ z.toJSONSchema(schema, { io: 'output' })
1045
+ } catch (error) {
1046
+ const reason = error instanceof Error ? error.message : 'it cannot be described'
1047
+ throw new PolicyError(`${table}: json.${name}'s schema answers a value that is not JSON (${reason})`)
1048
+ }
1049
+ setOwn(parsed, name, schema)
1050
+ }
1051
+ return freeze(parsed)
1052
+ }
1053
+
1054
+ /**
1055
+ * A column's own write actions. A table update action may be one of them: it then writes the column beside its update
1056
+ * list. Naming exactly the table's update actions says what `update` says, so that form is refused.
618
1057
  */
619
- function columnWrite(table: string, name: string, write: string, actions: ActionModel, update: NameSet): string {
1058
+ function columnWrite(table: string, name: string, writes: readonly string[], actions: ActionModel, update: NameSet): readonly string[] {
620
1059
  if (inSet(update, name)) {
621
1060
  throw new PolicyError(
622
- `${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${write}; remove it from update`,
1061
+ `${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${
1062
+ writes.join(', ')
1063
+ }; remove it from update`,
623
1064
  )
624
1065
  }
625
- if (includes(actions.update, write)) {
626
- throw new PolicyError(`${table}: columns.${name}.write names ${write}, the table's update action; list ${name} in update instead`)
1066
+ if (everyIncluded(writes, actions.update) && everyIncluded(actions.update, writes)) {
1067
+ throw new PolicyError(
1068
+ `${table}: columns.${name}.write names ${writes.join(', ')}, the table's update action; list ${name} in update instead`,
1069
+ )
627
1070
  }
628
- return write
1071
+ return writes
629
1072
  }
630
1073
 
631
1074
  /**
@@ -642,7 +1085,7 @@ function parseQueue(
642
1085
  readonly version: string | undefined
643
1086
  readonly actions: ActionModel
644
1087
  readonly update: NameSet
645
- readonly columnWrites: Readonly<Record<string, string>>
1088
+ readonly columnWrites: Readonly<Record<string, readonly string[]>>
646
1089
  },
647
1090
  ): QueueModel {
648
1091
  const queue = plainRecord(input, `${table}: queue`)
@@ -679,7 +1122,10 @@ function parseQueue(
679
1122
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
680
1123
  }
681
1124
 
682
- /** The column list's `date` (`dates`), timestamp (`timestamps`) or boolean (`booleans`) columns, each one of the table's. */
1125
+ /**
1126
+ * The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`), JSON (`json`) or NOT NULL
1127
+ * (`notNull`) columns, each one of the table's.
1128
+ */
683
1129
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
684
1130
  if (input === undefined) {
685
1131
  return nameSet([])
@@ -692,21 +1138,56 @@ function parseColumnSet(table: string, input: unknown, column: (name: unknown, f
692
1138
  }
693
1139
 
694
1140
  /**
695
- * The columns a capability of `action` updates in `model`: the update list for the table's update action, the
696
- * columns that declare it as their own write action for any other; none for an action that writes nothing here.
1141
+ * The columns a capability of `action` updates in `model`: the update list for a table update action, and every
1142
+ * column that lists it among its own write actions; none for an action that writes nothing here.
697
1143
  */
698
1144
  export function updatableBy(model: TableModel, action: string): NameSet {
699
- if (includes(model.actions.update, action)) {
1145
+ const owned = columnsWrittenBy(model, action)
1146
+ if (!includes(model.actions.update, action)) {
1147
+ return nameSet(owned)
1148
+ }
1149
+ if (owned.length === 0) {
700
1150
  return model.update
701
1151
  }
1152
+ const listed = namesOf(model.update)
1153
+ const columns: string[] = []
1154
+ for (let index = 0; index < listed.length; index++) {
1155
+ columns[columns.length] = listed[index] ?? ''
1156
+ }
1157
+ for (let index = 0; index < owned.length; index++) {
1158
+ columns[columns.length] = owned[index] ?? ''
1159
+ }
1160
+ return nameSet(columns)
1161
+ }
1162
+
1163
+ /** The columns that list `action` among their own write actions. */
1164
+ function columnsWrittenBy(model: TableModel, action: string): readonly string[] {
702
1165
  const names = ownKeys(model.columnWrites)
703
1166
  const columns: string[] = []
704
1167
  for (let index = 0; index < names.length; index++) {
705
1168
  const name = names[index] ?? ''
706
- if (model.columnWrites[name] === action) {
1169
+ if (includes(ownEntry(model.columnWrites, name) ?? [], action)) {
707
1170
  columns[columns.length] = name
708
1171
  }
709
1172
  }
1173
+ return columns
1174
+ }
1175
+
1176
+ /**
1177
+ * The columns any of `actions` updates in `model`, as one role holding them: the union of `updatableBy` over them.
1178
+ * One action's set is `updatableBy`'s own.
1179
+ */
1180
+ export function updatableByAny(model: TableModel, actions: readonly string[]): NameSet {
1181
+ if (actions.length === 1) {
1182
+ return updatableBy(model, actions[0] ?? '')
1183
+ }
1184
+ const columns: string[] = []
1185
+ for (let index = 0; index < actions.length; index++) {
1186
+ const names = namesOf(updatableBy(model, actions[index] ?? ''))
1187
+ for (let position = 0; position < names.length; position++) {
1188
+ columns[columns.length] = names[position] ?? ''
1189
+ }
1190
+ }
710
1191
  return nameSet(columns)
711
1192
  }
712
1193
 
@@ -716,32 +1197,81 @@ export function namesAction(model: TableModel, action: string): boolean {
716
1197
  if (includes(read, action) || includes(insert, action) || includes(update, action) || includes(remove, action)) {
717
1198
  return true
718
1199
  }
719
- const columns = ownKeys(model.columnWrites)
720
- for (let index = 0; index < columns.length; index++) {
721
- if (model.columnWrites[columns[index] ?? ''] === action) {
722
- return true
723
- }
724
- }
725
- return false
1200
+ return columnsWrittenBy(model, action).length > 0
726
1201
  }
727
1202
 
728
1203
  /**
729
- * The columns a capability of `action` reads: every one that declares no read action of its own, or exactly this
730
- * one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
1204
+ * The columns a capability of `action` reads: every one that declares no read action of its own, or one whose own
1205
+ * read actions include this one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
731
1206
  */
732
1207
  export function visibleFor(model: TableModel, action: string): readonly string[] {
1208
+ return visibleThrough(model, soleReach(action))
1209
+ }
1210
+
1211
+ /**
1212
+ * The actions whose reach one read answers: an `app` capability's held actions that admit the operation, each row
1213
+ * passing where one of them admits it (`conditionedAny`), and whether their `when` narrows the rows (`narrowed`), which
1214
+ * it does not in a table read with `'any'`.
1215
+ */
1216
+ export interface ReadReach {
1217
+ readonly actions: readonly string[]
1218
+ readonly narrowed: boolean
1219
+ }
1220
+
1221
+ /** The reach of a capability of one action, whose own condition narrows its rows. */
1222
+ export function soleReach(action: string): ReadReach {
1223
+ return freeze({ actions: freeze([action]), narrowed: true })
1224
+ }
1225
+
1226
+ /**
1227
+ * Whether every row a read of `reach` answers is a row `action` reads alone: it is one of the reaching actions, and either
1228
+ * no `when` of its own narrows it or it alone reaches the rows. A column of its own is shown only then, so several held
1229
+ * actions never put one action's column on another action's rows.
1230
+ */
1231
+ export function readsAsAction(model: TableModel, action: string, reach: ReadReach): boolean {
1232
+ if (!includes(reach.actions, action)) {
1233
+ return false
1234
+ }
1235
+ return !reach.narrowed || reach.actions.length === 1 || !hasOwn(model.when, action)
1236
+ }
1237
+
1238
+ /**
1239
+ * The columns a read of `reach` answers, the union of what each reaching action reads alone: every one that declares no
1240
+ * read action of its own, and one that does where that action reads every answered row (`readsAsAction`).
1241
+ */
1242
+ export function visibleThrough(model: TableModel, reach: ReadReach): readonly string[] {
733
1243
  const columns = namesOf(model.columns)
734
1244
  const visible: string[] = []
735
1245
  for (let index = 0; index < columns.length; index++) {
736
1246
  const name = columns[index] ?? ''
737
1247
  const declared = hasOwn(model.columnReads, name) ? model.columnReads[name] : undefined
738
- if (declared === undefined || declared === action) {
1248
+ if (declared === undefined || readsAsOneOf(model, declared, reach)) {
739
1249
  visible[visible.length] = name
740
1250
  }
741
1251
  }
742
1252
  return freeze(visible)
743
1253
  }
744
1254
 
1255
+ /** Whether one of a column's own read actions reads every row a read of `reach` answers (`readsAsAction`). */
1256
+ export function readsAsOneOf(model: TableModel, actions: readonly string[], reach: ReadReach): boolean {
1257
+ for (let index = 0; index < actions.length; index++) {
1258
+ if (readsAsAction(model, actions[index] ?? '', reach)) {
1259
+ return true
1260
+ }
1261
+ }
1262
+ return false
1263
+ }
1264
+
1265
+ /** Whether every one of `actions` is in `list`. */
1266
+ function everyIncluded(actions: readonly string[], list: readonly string[]): boolean {
1267
+ for (let index = 0; index < actions.length; index++) {
1268
+ if (!includes(list, actions[index] ?? '')) {
1269
+ return false
1270
+ }
1271
+ }
1272
+ return true
1273
+ }
1274
+
745
1275
  /** Every action that updates a column of `model`: its update action and each column's own write action. */
746
1276
  export function updateActions(model: TableModel): readonly string[] {
747
1277
  const actions: string[] = []
@@ -750,9 +1280,12 @@ export function updateActions(model: TableModel): readonly string[] {
750
1280
  }
751
1281
  const names = ownKeys(model.columnWrites)
752
1282
  for (let index = 0; index < names.length; index++) {
753
- const write = model.columnWrites[names[index] ?? '']
754
- if (write !== undefined && !includes(actions, write)) {
755
- actions[actions.length] = write
1283
+ const writes = ownEntry(model.columnWrites, names[index] ?? '') ?? []
1284
+ for (let position = 0; position < writes.length; position++) {
1285
+ const write = writes[position] ?? ''
1286
+ if (!includes(actions, write)) {
1287
+ actions[actions.length] = write
1288
+ }
756
1289
  }
757
1290
  }
758
1291
  return actions
@@ -854,6 +1387,10 @@ function parseContainer(
854
1387
  return freeze({ dimension: container, column: columns.column(ownEntry(stated, 'column'), 'scope.in.column') })
855
1388
  }
856
1389
 
1390
+ function viewWrite(table: string): string {
1391
+ return `${table}: a view is never written by a handler, so its policy takes only actions.read, appRead, appCount and column read actions`
1392
+ }
1393
+
857
1394
  function parseActions(
858
1395
  table: string,
859
1396
  scope: Readonly<Record<string, unknown>>,
@@ -875,7 +1412,13 @@ function parseActions(
875
1412
  }
876
1413
  return distinctActions(table, value, `actions.${field}`, action)
877
1414
  }
878
- const read = operation('read')
1415
+ const readAny = ownEntry(actions, 'read') === READ_ANY
1416
+ if (readAny && !hasOwn(scope, 'app')) {
1417
+ throw new PolicyError(
1418
+ `${table}: actions.read 'any' is for an application table; a dimension, child or reference table names its read actions`,
1419
+ )
1420
+ }
1421
+ const read = readAny ? freeze([]) : operation('read')
879
1422
  const records = hasOwn(scope, 'dimension') || hasOwn(scope, 'child')
880
1423
  const kind = hasOwn(scope, 'app') ? 'an application table' : 'a reference table'
881
1424
  const reach = (field: 'appRead' | 'appCount'): readonly string[] => {
@@ -906,7 +1449,7 @@ function parseActions(
906
1449
  throw new PolicyError(`${table}: actions.appRead and actions.appCount both name ${name}`)
907
1450
  }
908
1451
  }
909
- return freeze({ read, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
1452
+ return freeze({ read, readAny, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
910
1453
  }
911
1454
 
912
1455
  /** A plain array of distinct actions of the vocabulary, at least one. */
@@ -940,6 +1483,8 @@ interface Stamp {
940
1483
  readonly role: string
941
1484
  /** An insert may set it: a queue row's first due time. */
942
1485
  readonly insertable?: true
1486
+ /** Why a column the policy may not have named is stamped: its name is the convention's. */
1487
+ readonly convention?: string
943
1488
  }
944
1489
 
945
1490
  /** The columns the layer writes itself: the key, every containment link, the version and the creator. */
@@ -955,10 +1500,10 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
955
1500
  }
956
1501
  }
957
1502
  if (table.version !== undefined) {
958
- stamps[stamps.length] = { column: table.version, role: 'the version' }
1503
+ stamps[stamps.length] = { column: table.version, role: 'the version', convention: conventionOf(table.byConvention, table.version, 'version') }
959
1504
  }
960
1505
  if (table.createdBy !== undefined) {
961
- stamps[stamps.length] = { column: table.createdBy, role: 'createdBy' }
1506
+ stamps[stamps.length] = { column: table.createdBy, role: 'createdBy', convention: conventionOf(table.byConvention, table.createdBy, 'createdBy') }
962
1507
  }
963
1508
  if (table.queue !== undefined) {
964
1509
  stamps[stamps.length] = { column: table.queue.attempts, role: 'queue.attempts' }
@@ -967,6 +1512,11 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
967
1512
  return stamps
968
1513
  }
969
1514
 
1515
+ /** Why a column the policy did not name is stamped, or nothing when the policy named it. */
1516
+ function conventionOf(byConvention: NameSet, column: string, field: string): string | undefined {
1517
+ return inSet(byConvention, column) ? ` (a written table's column named ${column} is its ${field} unless the policy names another)` : undefined
1518
+ }
1519
+
970
1520
  /**
971
1521
  * Each stamped column holds one role and is never written by a handler. A shared column would let one stamp
972
1522
  * overwrite another: `createdBy` on the key inserts the principal as the id, `version` on a container column
@@ -979,6 +1529,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
979
1529
  if (stamp === undefined) {
980
1530
  continue
981
1531
  }
1532
+ // Nothing writes a view, so its key may be its parent column; a predicate still compares each.
1533
+ if (table.view) {
1534
+ if (inSet(table.json, stamp.column)) {
1535
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which no predicate compares as ${stamp.role}; give it a scalar type`)
1536
+ }
1537
+ continue
1538
+ }
982
1539
  for (let other = 0; other < index; other++) {
983
1540
  const earlier = stamps[other]
984
1541
  if (earlier !== undefined && earlier.column === stamp.column) {
@@ -988,10 +1545,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
988
1545
  }
989
1546
  }
990
1547
  if ((stamp.insertable !== true && inSet(table.insert, stamp.column)) || inSet(table.update, stamp.column)) {
991
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update`)
1548
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update${stamp.convention ?? ''}`)
992
1549
  }
993
1550
  if (hasOwn(table.columnWrites, stamp.column)) {
994
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own`)
1551
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own${stamp.convention ?? ''}`)
1552
+ }
1553
+ if (inSet(table.json, stamp.column)) {
1554
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which the layer cannot stamp as ${stamp.role}; give it a scalar type`)
995
1555
  }
996
1556
  }
997
1557
  }
@@ -1018,7 +1578,8 @@ export function includes(names: readonly string[], name: unknown): boolean {
1018
1578
  }
1019
1579
 
1020
1580
  /** Resolves every table's containment chain and refuses a shape the layer cannot enforce. */
1021
- function linkTables(parsed: readonly ParsedTable[], containment: Containment): TableModels {
1581
+ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel, views: Readonly<Record<string, ViewColumns>>): TableModels {
1582
+ const containment = vocabulary.dimensions
1022
1583
  const byName: Record<string, ParsedTable> = {}
1023
1584
  const owners: Record<string, ParsedTable> = {}
1024
1585
  for (let index = 0; index < parsed.length; index++) {
@@ -1068,50 +1629,1306 @@ function linkTables(parsed: readonly ParsedTable[], containment: Containment): T
1068
1629
  return result
1069
1630
  }
1070
1631
 
1632
+ const conditionTable = (name: string): ConditionTable | undefined => ownEntry(byName, name)
1633
+ const linkedTable = (name: string): LinkedTable | undefined => {
1634
+ const target = ownEntry(byName, name)
1635
+ if (target === undefined) return undefined
1636
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, byConvention, ...rest } =
1637
+ target
1638
+ return { ...rest, ...resolve(target, []) }
1639
+ }
1640
+ const hopRule: HopRule = (from, column, to, key, backward) => {
1641
+ const source = ownEntry(byName, from)
1642
+ const target = ownEntry(byName, to)
1643
+ if (target?.scope.mode === 'reference') {
1644
+ return !backward
1645
+ }
1646
+ if (source === undefined || target === undefined) {
1647
+ return false
1648
+ }
1649
+ const into = resolve(target, [])
1650
+ // The hop reads the row its foreign key references, so that must be the row the rules below place: the one with the key.
1651
+ if ((into.scope.mode !== 'dimension' && into.scope.mode !== 'child') || into.scope.key !== key) {
1652
+ return false
1653
+ }
1654
+ const scope = resolve(source, []).scope
1655
+ // A view's parent row is read through its parent subquery, which scopes it; a table's through its covering key.
1656
+ const covered = (): boolean => {
1657
+ if (!source.view) requireNotNullAncestors(`${from}.${column}`, source, containmentPairs(column, key, into.chain))
1658
+ return true
1659
+ }
1660
+ // The container column must lead to the table that owns the container dimension, not to any table its key references.
1661
+ if (
1662
+ scope.mode === 'dimension' && scope.container !== undefined && scope.container.column === column && into.scope.mode === 'dimension'
1663
+ && into.scope.dimension === scope.container.dimension
1664
+ ) {
1665
+ return covered()
1666
+ }
1667
+ if (scope.mode === 'child' && scope.column === column && scope.parent === to) {
1668
+ return covered()
1669
+ }
1670
+ // Any other foreign key reaches a row of the same tenant only when it also holds every ancestor the two share.
1671
+ const pairs = tenantPairs(resolve(source, []), column, into.scope.key, into.chain)
1672
+ if (pairs.length < 2 || !holdsExactly(source.foreignKeys, to, pairs)) {
1673
+ return false
1674
+ }
1675
+ requireNotNullAncestors(`${from}.${column}`, source, pairs)
1676
+ return true
1677
+ }
1678
+ const sources: Record<string, string> = {}
1679
+ const viewed: Record<string, string> = {}
1071
1680
  const models: Record<string, TableModel> = {}
1072
1681
  for (let index = 0; index < parsed.length; index++) {
1073
1682
  const table = parsed[index]
1074
1683
  if (table !== undefined) {
1075
1684
  const { scope, chain } = resolve(table, [])
1076
- setOwn(models, table.name, freeze({ ...table, scope, chain }))
1685
+ const {
1686
+ confersInput,
1687
+ whenInput,
1688
+ relationWhenInput,
1689
+ revealsInput,
1690
+ readThroughInput,
1691
+ writeThroughInput,
1692
+ memberRevealsInput,
1693
+ accessInput,
1694
+ byConvention,
1695
+ ...rest
1696
+ } = table
1697
+ const linked = { ...rest, scope, chain }
1698
+ const ownerOf = (dimension: string): ResolvedOwner | undefined => {
1699
+ const owner = ownEntry(owners, dimension)
1700
+ return owner === undefined ? undefined : { name: owner.name, ...resolve(owner, []) }
1701
+ }
1702
+ // A container's own path, parsed from its own declaration; one through its container in turn is none.
1703
+ const containerPath = (container: string, dimension: string): SecondaryPath | undefined => {
1704
+ const declared = ownEntry(byName, container)?.readThroughInput
1705
+ const column = declared === undefined ? undefined : ownEntry(plainRecord(declared, `${container}: readThrough`), dimension)
1706
+ const target = linkedTable(container)
1707
+ if (target === undefined || typeof column !== 'string' || splitPath(column).length !== 1) return undefined
1708
+ return parseReadThrough(target, { [dimension]: column }, vocabulary, ownerOf, () => undefined)[0]
1709
+ }
1710
+ const readThrough = parseWriteThrough(
1711
+ linked,
1712
+ parseReadThrough(linked, readThroughInput, vocabulary, ownerOf, containerPath),
1713
+ writeThroughInput,
1714
+ vocabulary,
1715
+ )
1716
+ const confers = parseConfers(linked, confersInput, vocabulary.relations, conditionTable, linkedTable, hopRule)
1717
+ for (let position = 0; position < confers.length; position++) {
1718
+ const relation = confers[position]?.relation ?? ''
1719
+ const earlier = ownEntry(sources, relation)
1720
+ if (earlier !== undefined) {
1721
+ throw new PolicyError(`${table.name}: the relation ${relation} is already conferred by ${earlier}; a relation has one source table`)
1722
+ }
1723
+ setOwn(sources, relation, table.name)
1724
+ }
1725
+ const root = conditionRoot(linked, byName)
1726
+ const when = parseWhen(linked, root, whenInput, conditionTable, hopRule)
1727
+ const relationWhen = parseRelationWhen(linked, root, relationWhenInput, vocabulary, conditionTable, hopRule)
1728
+ const reveals = parseReveals(linked, readThrough, revealsInput, vocabulary, conditionTable, hopRule)
1729
+ const memberReveals = parseMemberReveals(linked, readThrough, memberRevealsInput, vocabulary, conditionTable, hopRule)
1730
+ const access = parseAccess(linked, accessInput, vocabulary, views)
1731
+ for (let position = 0; position < access.length; position++) {
1732
+ const relation = access[position]?.relation ?? ''
1733
+ if (!hasOwn(viewed, relation)) setOwn(viewed, relation, table.name)
1734
+ }
1735
+ setOwn(models, table.name, freeze({ ...linked, confers, when, relationWhen, reveals, readThrough, memberReveals, access }))
1077
1736
  }
1078
1737
  }
1738
+ checkRelationWhenReach(models, vocabulary)
1739
+ const relations = ownKeys(vocabulary.relations)
1740
+ for (let index = 0; index < relations.length; index++) {
1741
+ const relation = relations[index] ?? ''
1742
+ if (!hasOwn(sources, relation) && !hasOwn(viewed, relation)) {
1743
+ throw new PolicyError(
1744
+ `the vocabulary relation ${relation} has no source: declare confers.${relation} on the table whose rows hold it, or name an access view for it`,
1745
+ )
1746
+ }
1747
+ }
1748
+ checkRevealSources(models, sources)
1079
1749
  return freeze(models)
1080
1750
  }
1081
1751
 
1082
- /** A table's scope with nothing left to derive, and its containment chain. */
1083
- interface Resolved {
1084
- readonly scope: ScopeModel
1085
- readonly chain: readonly Container[]
1752
+ /** A reveal is matched through the relation's source rows, so a relation that access views alone serve reveals nothing. */
1753
+ function checkRevealSources(models: Readonly<Record<string, TableModel>>, sources: Readonly<Record<string, string>>): void {
1754
+ const tables = ownKeys(models)
1755
+ for (let index = 0; index < tables.length; index++) {
1756
+ const model = ownEntry(models, tables[index] ?? '')
1757
+ const reveals = model?.reveals ?? []
1758
+ for (let position = 0; position < reveals.length; position++) {
1759
+ const relation = reveals[position]?.relation ?? ''
1760
+ if (model !== undefined && !hasOwn(sources, relation)) {
1761
+ throw new PolicyError(
1762
+ `${model.name}: reveals.${relation} is matched through the rows that confer it, and only access views serve it; declare confers.${relation}`,
1763
+ )
1764
+ }
1765
+ }
1766
+ }
1086
1767
  }
1087
1768
 
1088
- function resolveChain(
1089
- table: ParsedTable,
1090
- byName: Readonly<Record<string, ParsedTable>>,
1091
- owners: Readonly<Record<string, ParsedTable>>,
1092
- containment: Containment,
1093
- chainOf: (table: ParsedTable) => readonly Container[],
1094
- ): Resolved {
1095
- /**
1096
- * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
1097
- * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
1098
- */
1099
- const above = (dimension: string): readonly Container[] => {
1100
- const owner = ownEntry(owners, dimension)
1101
- if (owner !== undefined) {
1102
- return chainOf(owner)
1769
+ type LinkedTable = Omit<TableModel, 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
1770
+
1771
+ /** A view of the column list: its columns, and whether a policy makes it a table of the layer. */
1772
+ interface ViewColumns {
1773
+ readonly columns: NameSet
1774
+ readonly policy: boolean
1775
+ }
1776
+
1777
+ const ACCESS_FIELDS = nameSet(['view', 'row', 'principal', 'member'])
1778
+
1779
+ /**
1780
+ * `access`: relation → the view whose rows name the table's rows the relation reaches. The view is one the column list
1781
+ * marks, `row` and each binding are its columns, and at least one binding is stated, so the subquery never reads every
1782
+ * row: `principal` is compared to the caller, `member` to the nodes of the relation's dimension it holds the relation in.
1783
+ */
1784
+ function parseAccess(
1785
+ table: LinkedTable,
1786
+ input: unknown,
1787
+ vocabulary: VocabularyModel,
1788
+ views: Readonly<Record<string, ViewColumns>>,
1789
+ ): readonly AccessModel[] {
1790
+ if (input === undefined) {
1791
+ return freeze([])
1792
+ }
1793
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1794
+ throw new PolicyError(`${table.name}: only a dimension or child table, or a child view, takes access; its rows are what a relation reaches`)
1795
+ }
1796
+ const declared = plainRecord(input, `${table.name}: access`)
1797
+ const relations = ownKeys(declared)
1798
+ const parsed: AccessModel[] = []
1799
+ for (let index = 0; index < relations.length; index++) {
1800
+ const relation = relations[index] ?? ''
1801
+ const what = `${table.name}: access.${relation}`
1802
+ if (!hasOwn(vocabulary.relations, relation)) {
1803
+ throw new PolicyError(`${what} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`)
1103
1804
  }
1104
- const container = ownEntry(containment, dimension)?.container
1105
- return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
1106
- }
1107
- const scope = table.scope
1108
- if (scope.mode === 'dimension') {
1109
- const container = scope.container
1110
- if (container === undefined) {
1111
- return { scope, chain: freeze([]) }
1805
+ const entry = plainRecord(ownEntry(declared, relation), what)
1806
+ onlyFields(entry, ACCESS_FIELDS, what)
1807
+ const view = ownEntry(entry, 'view')
1808
+ const named = typeof view === 'string' ? ownEntry(views, view) : undefined
1809
+ if (typeof view !== 'string' || named === undefined) {
1810
+ throw new PolicyError(`${what}.view names ${String(view)}, which the column list does not mark as a view`)
1112
1811
  }
1113
- const owner = ownEntry(owners, container.dimension)
1114
- if (owner !== undefined) {
1812
+ // Read directly, the view would show the caller who else reaches which row.
1813
+ if (named.policy) {
1814
+ throw new PolicyError(`${what}.view names ${view}, which has a policy; an access view takes none, so only the relation's term reads it`)
1815
+ }
1816
+ const columns = named.columns
1817
+ const viewColumn = (field: string, required: boolean): string | undefined => {
1818
+ const name = ownEntry(entry, field)
1819
+ if (name === undefined && !required) return undefined
1820
+ if (typeof name !== 'string' || !inSet(columns, name)) {
1821
+ throw new PolicyError(`${what}.${field} names ${String(name)}, which is not a column of ${view}`)
1822
+ }
1823
+ return name
1824
+ }
1825
+ const row = viewColumn('row', true) ?? ''
1826
+ const principal = viewColumn('principal', false)
1827
+ const member = viewColumn('member', false)
1828
+ if (principal === undefined && member === undefined) {
1829
+ throw new PolicyError(`${what} binds neither principal nor member: an access view is read for the caller, never whole`)
1830
+ }
1831
+ parsed[parsed.length] = freeze({ relation, dimension: ownEntry(vocabulary.relations, relation) ?? '', view, row, principal, member })
1832
+ }
1833
+ return freeze(parsed)
1834
+ }
1835
+
1836
+ /** Every action a table names: its operations', `appRead`, `appCount` and its columns' own. */
1837
+ function tableActionNames(table: LinkedTable): NameSet {
1838
+ const names: string[] = []
1839
+ const lists = [table.actions.read, table.actions.insert, table.actions.update, table.actions.delete, table.actions.appRead, table.actions.appCount]
1840
+ for (let list = 0; list < lists.length; list++) {
1841
+ const actions = lists[list] ?? []
1842
+ for (let index = 0; index < actions.length; index++) {
1843
+ names[names.length] = actions[index] ?? ''
1844
+ }
1845
+ }
1846
+ const reads = ownKeys(table.columnReads)
1847
+ for (let index = 0; index < reads.length; index++) {
1848
+ const actions = ownEntry(table.columnReads, reads[index] ?? '') ?? []
1849
+ for (let position = 0; position < actions.length; position++) {
1850
+ names[names.length] = actions[position] ?? ''
1851
+ }
1852
+ }
1853
+ const writes = ownKeys(table.columnWrites)
1854
+ for (let index = 0; index < writes.length; index++) {
1855
+ const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
1856
+ for (let position = 0; position < actions.length; position++) {
1857
+ names[names.length] = actions[position] ?? ''
1858
+ }
1859
+ }
1860
+ return nameSet(names)
1861
+ }
1862
+
1863
+ /** The actions that write a table: its insert, update and delete actions and its columns' own write actions. */
1864
+ function writeActionNames(table: LinkedTable): NameSet {
1865
+ const names: string[] = []
1866
+ const lists = [table.actions.insert, table.actions.update, table.actions.delete]
1867
+ for (let list = 0; list < lists.length; list++) {
1868
+ const actions = lists[list] ?? []
1869
+ for (let index = 0; index < actions.length; index++) {
1870
+ names[names.length] = actions[index] ?? ''
1871
+ }
1872
+ }
1873
+ const writes = ownKeys(table.columnWrites)
1874
+ for (let index = 0; index < writes.length; index++) {
1875
+ const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
1876
+ for (let position = 0; position < actions.length; position++) {
1877
+ names[names.length] = actions[position] ?? ''
1878
+ }
1879
+ }
1880
+ return nameSet(names)
1881
+ }
1882
+
1883
+ /**
1884
+ * `when`: action → the condition a row must meet for it. An insert action's condition is judged on the inserted row and
1885
+ * the existing rows its paths reach (`insertProblem`); a reference table is read by every site and takes none.
1886
+ */
1887
+ function parseWhen(
1888
+ table: LinkedTable,
1889
+ root: ConditionTable,
1890
+ input: unknown,
1891
+ tables: (name: string) => ConditionTable | undefined,
1892
+ hops: HopRule,
1893
+ ): Readonly<Record<string, ConditionModel>> {
1894
+ if (input === undefined) {
1895
+ return freeze({})
1896
+ }
1897
+ if (table.scope.mode === 'reference') {
1898
+ throw new PolicyError(`${table.name}: a reference table takes no when; every site reads it`)
1899
+ }
1900
+ const declared = plainRecord(input, `${table.name}: when`)
1901
+ const named = tableActionNames(table)
1902
+ const actions = ownKeys(declared)
1903
+ const when: Record<string, ConditionModel> = {}
1904
+ for (let index = 0; index < actions.length; index++) {
1905
+ const action = actions[index] ?? ''
1906
+ if (!inSet(named, action)) {
1907
+ throw new PolicyError(`${table.name}: when.${action} names an action the table does not name (${namesOf(named).join(', ')})`)
1908
+ }
1909
+ if (table.actions.readAny && !inSet(writeActionNames(table), action)) {
1910
+ throw new PolicyError(
1911
+ `${table.name}: when.${action} narrows nothing: the table is read with 'any', and a when narrows only the writes of an action that inserts, updates or deletes`,
1912
+ )
1913
+ }
1914
+ const what = `${table.name}: when.${action}`
1915
+ const condition = parseCondition(ownEntry(declared, action), root, tables, what, hops)
1916
+ // An insert reads the rows its foreign keys reach in its transaction, locked until the commit (`judgeInserted`).
1917
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1918
+ if (problem !== undefined) {
1919
+ throw new PolicyError(`${what}: ${problem}`)
1920
+ }
1921
+ setOwn(when, action, condition)
1922
+ }
1923
+ return freeze(when)
1924
+ }
1925
+
1926
+ /**
1927
+ * `relationWhen`: relation → action → a condition on the rows the relation reaches for the action, parsed as `when` is
1928
+ * (the same root, hop rule and insert rule). The relation must be the vocabulary's and the action the table's; whether
1929
+ * the relation reaches the table at all is checked once every table is parsed (`checkRelationWhenReach`).
1930
+ */
1931
+ function parseRelationWhen(
1932
+ table: LinkedTable,
1933
+ root: ConditionTable,
1934
+ input: unknown,
1935
+ vocabulary: VocabularyModel,
1936
+ tables: (name: string) => ConditionTable | undefined,
1937
+ hops: HopRule,
1938
+ ): Readonly<Record<string, Readonly<Record<string, ConditionModel>>>> {
1939
+ if (input === undefined) {
1940
+ return freeze({})
1941
+ }
1942
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1943
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table takes no relationWhen; no relation reaches its rows`)
1944
+ }
1945
+ const declared = plainRecord(input, `${table.name}: relationWhen`)
1946
+ const relations = ownKeys(declared)
1947
+ const named = tableActionNames(table)
1948
+ const parsed: Record<string, Readonly<Record<string, ConditionModel>>> = {}
1949
+ for (let index = 0; index < relations.length; index++) {
1950
+ const relation = relations[index] ?? ''
1951
+ if (!hasOwn(vocabulary.relations, relation)) {
1952
+ throw new PolicyError(
1953
+ `${table.name}: relationWhen.${relation} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`,
1954
+ )
1955
+ }
1956
+ const perAction = plainRecord(ownEntry(declared, relation), `${table.name}: relationWhen.${relation}`)
1957
+ const actions = ownKeys(perAction)
1958
+ if (actions.length === 0) {
1959
+ throw new PolicyError(`${table.name}: relationWhen.${relation} names no action`)
1960
+ }
1961
+ const conditions: Record<string, ConditionModel> = {}
1962
+ for (let position = 0; position < actions.length; position++) {
1963
+ const action = actions[position] ?? ''
1964
+ const what = `${table.name}: relationWhen.${relation}.${action}`
1965
+ if (!inSet(named, action)) {
1966
+ throw new PolicyError(`${what} names an action the table does not name (${namesOf(named).join(', ')})`)
1967
+ }
1968
+ const condition = parseCondition(ownEntry(perAction, action), root, tables, what, hops)
1969
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1970
+ if (problem !== undefined) {
1971
+ throw new PolicyError(`${what}: ${problem}`)
1972
+ }
1973
+ setOwn(conditions, action, condition)
1974
+ }
1975
+ setOwn(parsed, relation, freeze(conditions))
1976
+ }
1977
+ return freeze(parsed)
1978
+ }
1979
+
1980
+ /**
1981
+ * Every `relationWhen` names a relation that reaches the table for its action: the relation's dimension is the table's
1982
+ * or on its chain, a secondary path reaches it, or a reveal of the relation for the action reveals a node the table
1983
+ * lies at. A child view is reached through its parent row, so its parent is what the relation must reach.
1984
+ */
1985
+ function checkRelationWhenReach(models: Readonly<Record<string, TableModel>>, vocabulary: VocabularyModel): void {
1986
+ const names = ownKeys(models)
1987
+ const reveals: RevealModel[] = []
1988
+ for (let index = 0; index < names.length; index++) {
1989
+ const model = ownEntry(models, names[index] ?? '')
1990
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
1991
+ const reveal = model.reveals[position]
1992
+ if (reveal !== undefined) reveals[reveals.length] = reveal
1993
+ }
1994
+ }
1995
+ for (let index = 0; index < names.length; index++) {
1996
+ const model = ownEntry(models, names[index] ?? '')
1997
+ if (model === undefined) continue
1998
+ const reached = model.view && model.scope.mode === 'child' ? ownEntry(models, model.scope.parent) ?? model : model
1999
+ const relations = ownKeys(model.relationWhen)
2000
+ for (let position = 0; position < relations.length; position++) {
2001
+ const relation = relations[position] ?? ''
2002
+ const dimension = ownEntry(vocabulary.relations, relation) ?? ''
2003
+ const actions = ownKeys(ownEntry(model.relationWhen, relation) ?? {})
2004
+ for (let next = 0; next < actions.length; next++) {
2005
+ const action = actions[next] ?? ''
2006
+ if (!relationReaches(reached, relation, dimension, action, reveals)) {
2007
+ throw new PolicyError(
2008
+ `${model.name}: relationWhen.${relation}.${action} names a relation that reaches no row of ${reached.name} for ${action}: neither its chain nor a secondary path holds ${dimension}, and no reveal of ${relation} for ${action} names a node it lies at`,
2009
+ )
2010
+ }
2011
+ }
2012
+ }
2013
+ }
2014
+ }
2015
+
2016
+ /** Whether `relation` of `dimension` reaches a row of `model` for `action`, as the relation terms of the store find one. */
2017
+ function relationReaches(model: TableModel, relation: string, dimension: string, action: string, reveals: readonly RevealModel[]): boolean {
2018
+ if (nodeColumnOf(model, dimension) !== undefined || model.access.some((access) => access.relation === relation)) {
2019
+ return true
2020
+ }
2021
+ for (let index = 0; index < model.readThrough.length; index++) {
2022
+ const path = model.readThrough[index]
2023
+ if (path === undefined) continue
2024
+ if (path.dimension === dimension) return true
2025
+ for (let link = 0; link < path.chain.length; link++) {
2026
+ if (path.chain[link]?.dimension === dimension) return true
2027
+ }
2028
+ }
2029
+ for (let index = 0; index < reveals.length; index++) {
2030
+ const reveal = reveals[index]
2031
+ if (
2032
+ reveal !== undefined && reveal.relation === relation && includes(reveal.actions, action) && nodeColumnOf(model, reveal.dimension) !== undefined
2033
+ ) {
2034
+ return true
2035
+ }
2036
+ }
2037
+ return false
2038
+ }
2039
+
2040
+ /**
2041
+ * The table a `when` of `table` starts at. A child view's parent column is a foreign key to its parent's key that no
2042
+ * column list declares, so a path follows it to the parent row, and the parent's own foreign keys from there.
2043
+ */
2044
+ function conditionRoot(table: LinkedTable, byName: Readonly<Record<string, ParsedTable>>): ConditionTable {
2045
+ const parent = table.view && table.scope.mode === 'child' ? ownEntry(byName, table.scope.parent) : undefined
2046
+ if (table.scope.mode !== 'child' || parent === undefined || parent.scope.mode !== 'dimension') {
2047
+ return table
2048
+ }
2049
+ const foreignKeys: ForeignKey[] = []
2050
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2051
+ const key = table.foreignKeys[index]
2052
+ if (key !== undefined) foreignKeys[foreignKeys.length] = key
2053
+ }
2054
+ foreignKeys[foreignKeys.length] = freeze({ columns: freeze([table.scope.column]), table: parent.name, references: freeze([parent.scope.key]) })
2055
+ return freeze({ ...table, foreignKeys: freeze(foreignKeys) })
2056
+ }
2057
+
2058
+ /** A dimension's owning table, resolved: what a secondary path's column references. */
2059
+ interface ResolvedOwner extends Resolved {
2060
+ readonly name: string
2061
+ }
2062
+
2063
+ /**
2064
+ * `readThrough`: dimension → the column a `Within`'s read reaches a row through. The dimension lies outside the row's chain and a table
2065
+ * owns it; the column is a foreign key to that table's key that no update writes, and it covers every ancestor the two
2066
+ * chains share, so the database keeps the node in the row's own tenant. `<column>.<column>` reads the row through its
2067
+ * nearest container's own path instead (`containerPath`).
2068
+ */
2069
+ function parseReadThrough(
2070
+ table: LinkedTable,
2071
+ input: unknown,
2072
+ vocabulary: VocabularyModel,
2073
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
2074
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
2075
+ ): readonly SecondaryPath[] {
2076
+ if (input === undefined) {
2077
+ return freeze([])
2078
+ }
2079
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2080
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table has no containment, so no secondary read path`)
2081
+ }
2082
+ if (table.queue !== undefined) {
2083
+ throw new PolicyError(`${table.name}: a queue table has no secondary read path; a claim follows containment only`)
2084
+ }
2085
+ const declared = plainRecord(input, `${table.name}: readThrough`)
2086
+ const dimensions = ownKeys(declared)
2087
+ const paths: SecondaryPath[] = []
2088
+ for (let index = 0; index < dimensions.length; index++) {
2089
+ const dimension = dimensions[index] ?? ''
2090
+ const what = `${table.name}: readThrough.${dimension}`
2091
+ if (!hasOwn(vocabulary.dimensions, dimension)) {
2092
+ throw new PolicyError(`${what}: ${dimension} is not a dimension of the vocabulary`)
2093
+ }
2094
+ if (nodeColumnOf(table, dimension) !== undefined) {
2095
+ throw new PolicyError(`${what}: ${table.name} already lies in ${dimension}; a secondary path reaches a dimension outside its chain`)
2096
+ }
2097
+ const column = ownEntry(declared, dimension)
2098
+ const segments = typeof column === 'string' ? splitPath(column) : []
2099
+ if (segments.length === 2) {
2100
+ paths[paths.length] = throughContainer(table, segments[0] ?? '', segments[1] ?? '', dimension, ownerOf, containerPath, what)
2101
+ continue
2102
+ }
2103
+ if (typeof column !== 'string' || !inSet(table.columns, column)) {
2104
+ throw new PolicyError(`${what} names ${String(column)}, which is not a column of ${table.name}`)
2105
+ }
2106
+ if (inSet(table.update, column) || hasOwn(table.columnWrites, column) || hasOwn(table.files, column)) {
2107
+ throw new PolicyError(`${what}: ${column} places the row on a read path, so no update writes it`)
2108
+ }
2109
+ if (column === table.version || column === table.createdBy || column === table.scope.key) {
2110
+ throw new PolicyError(`${what}: ${column} is a column the layer writes itself, not a node of ${dimension}`)
2111
+ }
2112
+ for (let position = 0; position < table.chain.length; position++) {
2113
+ if (table.chain[position]?.column === column) {
2114
+ throw new PolicyError(`${what}: ${column} is a containment column of ${table.name}`)
2115
+ }
2116
+ }
2117
+ const owner = ownerOf(dimension)
2118
+ if (owner === undefined || owner.scope.mode !== 'dimension') {
2119
+ throw new PolicyError(`${what}: no table owns ${dimension}, so no foreign key ties ${column} to a node of it`)
2120
+ }
2121
+ const pairs = tenantPairs(table, column, owner.scope.key, owner.chain)
2122
+ const covered = holdsExactly(table.foreignKeys, owner.name, pairs)
2123
+ if (!covered) {
2124
+ const columns: string[] = []
2125
+ const referenced: string[] = []
2126
+ for (let position = 0; position < pairs.length; position++) {
2127
+ columns[position] = pairs[position]?.[0] ?? ''
2128
+ referenced[position] = pairs[position]?.[1] ?? ''
2129
+ }
2130
+ throw new PolicyError(
2131
+ `${what}: ${column} and every ancestor ${table.name} shares with ${owner.name} must be one foreign key of exactly these columns, so the node lies in the row's own tenant; declare foreign key (${
2132
+ columns.join(', ')
2133
+ }) references ${owner.name} (${referenced.join(', ')})`,
2134
+ )
2135
+ }
2136
+ requireNotNullAncestors(what, table, pairs)
2137
+ paths[paths.length] = freeze({ dimension, column, table: owner.name, key: owner.scope.key, chain: owner.chain, via: undefined, writes: freeze([]) })
2138
+ }
2139
+ return freeze(paths)
2140
+ }
2141
+
2142
+ /**
2143
+ * `readThrough.<dimension>: '<link>.<column>'`: the row is read through the path its nearest container declares for the
2144
+ * dimension. `<link>` is the row's nearest containment column, which places it in the container now, and `<column>` the
2145
+ * container's own path column, which no update of the container writes; so the read follows containment and the
2146
+ * container's path, and nothing the row's writer picks.
2147
+ */
2148
+ function throughContainer(
2149
+ table: LinkedTable,
2150
+ link: string,
2151
+ column: string,
2152
+ dimension: string,
2153
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
2154
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
2155
+ what: string,
2156
+ ): SecondaryPath {
2157
+ const nearest = table.chain[0]
2158
+ if (nearest === undefined || nearest.column !== link) {
2159
+ throw new PolicyError(
2160
+ `${what}: ${link} is not ${table.name}'s nearest containment column${
2161
+ nearest === undefined ? '' : ` (${nearest.column})`
2162
+ }; a path through a container starts at the row's own container`,
2163
+ )
2164
+ }
2165
+ const container = ownerOf(nearest.dimension)
2166
+ if (container === undefined || container.scope.mode !== 'dimension') {
2167
+ throw new PolicyError(`${what}: no table owns ${nearest.dimension}, so no container row holds a path to ${dimension}`)
2168
+ }
2169
+ const path = containerPath(container.name, dimension)
2170
+ if (path === undefined) {
2171
+ throw new PolicyError(
2172
+ `${what}: ${container.name} declares no readThrough.${dimension} through a column of its own, so ${table.name} has no container path to follow`,
2173
+ )
2174
+ }
2175
+ if (path.column !== column) {
2176
+ throw new PolicyError(`${what}: ${container.name} reads ${dimension} through ${path.column}, not ${column}`)
2177
+ }
2178
+ return freeze({ ...path, via: freeze({ column: link, table: container.name, key: container.scope.key }), writes: freeze([]) })
2179
+ }
2180
+
2181
+ /**
2182
+ * `writeThrough`: a dimension the table reads through → the actions a `Ref` held through that path holds. Each is an
2183
+ * action of the vocabulary: the table's own, or one a reveal matched through the path or a table below reaches the row
2184
+ * for. The path's column is the delegation: whoever inserts it must hold every listed action at the node it names, and
2185
+ * for a path through the container, whoever inserts the container's column (`pathWriters`).
2186
+ */
2187
+ function parseWriteThrough(
2188
+ table: LinkedTable,
2189
+ readThrough: readonly SecondaryPath[],
2190
+ input: unknown,
2191
+ vocabulary: VocabularyModel,
2192
+ ): readonly SecondaryPath[] {
2193
+ if (input === undefined) {
2194
+ return readThrough
2195
+ }
2196
+ const declared = plainRecord(input, `${table.name}: writeThrough`)
2197
+ const dimensions = ownKeys(declared)
2198
+ const writes: Record<string, readonly string[]> = {}
2199
+ for (let index = 0; index < dimensions.length; index++) {
2200
+ const dimension = dimensions[index] ?? ''
2201
+ const what = `${table.name}: writeThrough.${dimension}`
2202
+ let declaredPath = false
2203
+ for (let position = 0; position < readThrough.length; position++) {
2204
+ if (readThrough[position]?.dimension === dimension) declaredPath = true
2205
+ }
2206
+ if (!declaredPath) {
2207
+ throw new PolicyError(`${what}: ${table.name} reads no path to ${dimension}; declare readThrough.${dimension} first`)
2208
+ }
2209
+ const actions = parseList(ownEntry(declared, dimension), (action) => {
2210
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2211
+ throw new PolicyError(`${what} names ${String(action)}, which is not an action of the vocabulary`)
2212
+ }
2213
+ return action
2214
+ })
2215
+ if (actions === undefined) {
2216
+ throw new PolicyError(`${what} takes a plain array of the vocabulary's actions`)
2217
+ }
2218
+ const listed: string[] = []
2219
+ for (let position = 0; position < actions.length; position++) {
2220
+ const action = actions[position] ?? ''
2221
+ if (!includes(listed, action)) listed[listed.length] = action
2222
+ }
2223
+ if (listed.length === 0) {
2224
+ throw new PolicyError(`${what} names no action; leave the dimension out to hold nothing through the path`)
2225
+ }
2226
+ setOwn(writes, dimension, freeze(listed))
2227
+ }
2228
+ const paths: SecondaryPath[] = []
2229
+ for (let index = 0; index < readThrough.length; index++) {
2230
+ const path = readThrough[index]
2231
+ if (path === undefined) continue
2232
+ const listed = ownEntry(writes, path.dimension)
2233
+ paths[paths.length] = listed === undefined ? path : freeze({ ...path, writes: listed })
2234
+ }
2235
+ return freeze(paths)
2236
+ }
2237
+
2238
+ /**
2239
+ * `reveals`: relation → the ancestor its rows reveal. The relation is of the table's own dimension, so its term
2240
+ * matches the row's key, or of a dimension the table reaches, so it matches that path's column; the ancestor is a link of the chain, whose column the layer stamps and a move rewrites, so the
2241
+ * revealed node follows the row's containment now. A queue table reveals nothing: a claim rewrites its rows.
2242
+ */
2243
+ function parseReveals(
2244
+ table: LinkedTable,
2245
+ readThrough: readonly SecondaryPath[],
2246
+ input: unknown,
2247
+ vocabulary: VocabularyModel,
2248
+ tables: (name: string) => ConditionTable | undefined,
2249
+ hops: HopRule,
2250
+ ): readonly RevealModel[] {
2251
+ if (input === undefined) {
2252
+ return freeze([])
2253
+ }
2254
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2255
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table reveals nothing; its rows lie at no node a relation reaches`)
2256
+ }
2257
+ if (table.queue !== undefined) {
2258
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2259
+ }
2260
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2261
+ const key = table.scope.key
2262
+ const declared = plainRecord(input, `${table.name}: reveals`)
2263
+ const names = ownKeys(declared)
2264
+ const reveals: RevealModel[] = []
2265
+ for (let index = 0; index < names.length; index++) {
2266
+ const relation = names[index] ?? ''
2267
+ const what = `${table.name}: reveals.${relation}`
2268
+ const dimension = ownEntry(vocabulary.relations, relation)
2269
+ if (dimension === undefined) {
2270
+ throw new PolicyError(
2271
+ `${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(vocabulary.relations).join(', ') || 'none'})`,
2272
+ )
2273
+ }
2274
+ const paths: SecondaryPath[] = []
2275
+ for (let position = 0; dimension !== own && position < readThrough.length; position++) {
2276
+ const path = readThrough[position]
2277
+ if (path !== undefined && (path.dimension === dimension || containsLink(path.chain, dimension))) paths[paths.length] = path
2278
+ }
2279
+ if (dimension !== own && paths.length !== 1) {
2280
+ throw new PolicyError(
2281
+ paths.length === 0
2282
+ ? `${what}: ${relation} is of ${dimension}, which is neither ${table.name}'s own dimension nor one it reads through, or above one; a table reveals for a relation that reaches its rows`
2283
+ : `${what}: ${table.name} reads through more than one path to ${dimension}, so the reveal matches no one column`,
2284
+ )
2285
+ }
2286
+ const policy = plainRecord(ownEntry(declared, relation), what)
2287
+ onlyFields(policy, REVEALS_FIELDS, what)
2288
+ const { to, column, actions: listed, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2289
+ const path = paths[0]
2290
+ if (path?.via !== undefined) {
2291
+ // The relation's nodes would sit one subquery below the container's, past the guard's bound under a reveal.
2292
+ throw new PolicyError(
2293
+ `${what}: ${table.name} reads ${dimension} through its container ${path.via.table}, so a reveal matched through it reads too deep; reveal from ${path.via.table} instead`,
2294
+ )
2295
+ }
2296
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2297
+ throw new PolicyError(
2298
+ `${what}.to: ${to} lies above ${table.name}'s nearest container; a move of an ancestor rewrites ${column}, so a reveal through a secondary path reveals the nearest container only`,
2299
+ )
2300
+ }
2301
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2302
+ reveals[reveals.length] = freeze({ relation, table: table.name, key, path, assign, dimension: to, column, actions: listed, when })
2303
+ }
2304
+ return freeze(reveals)
2305
+ }
2306
+
2307
+ /** A reveal's `to`, a dimension of the table's chain with the column that holds it, its listed actions, and its `when`. */
2308
+ function parseRevealed(
2309
+ table: LinkedTable,
2310
+ policy: Readonly<Record<string, unknown>>,
2311
+ what: string,
2312
+ vocabulary: VocabularyModel,
2313
+ tables: (name: string) => ConditionTable | undefined,
2314
+ hops: HopRule,
2315
+ ): { readonly to: string; readonly column: string; readonly actions: readonly string[]; readonly when: ConditionModel | undefined } {
2316
+ const to = ownEntry(policy, 'to')
2317
+ let column: string | undefined
2318
+ for (let position = 0; position < table.chain.length; position++) {
2319
+ const link = table.chain[position]
2320
+ if (link !== undefined && link.dimension === to) column = link.column
2321
+ }
2322
+ if (typeof to !== 'string' || column === undefined) {
2323
+ const above: string[] = []
2324
+ for (let position = 0; position < table.chain.length; position++) {
2325
+ above[above.length] = table.chain[position]?.dimension ?? ''
2326
+ }
2327
+ throw new PolicyError(
2328
+ `${what}.to names ${String(to)}, which is not a dimension of ${table.name}'s chain (${above.join(', ') || 'none'})`,
2329
+ )
2330
+ }
2331
+ const actions = parseList(ownEntry(policy, 'actions'), (action) => {
2332
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2333
+ throw new PolicyError(`${what}.actions names ${String(action)}, which is not an action of the vocabulary`)
2334
+ }
2335
+ return action
2336
+ })
2337
+ if (actions === undefined) {
2338
+ throw new PolicyError(`${what}.actions takes a plain array of the vocabulary's actions`)
2339
+ }
2340
+ const listed: string[] = []
2341
+ for (let position = 0; position < actions.length; position++) {
2342
+ const action = actions[position] ?? ''
2343
+ if (!includes(listed, action)) listed[listed.length] = action
2344
+ }
2345
+ if (listed.length === 0) {
2346
+ throw new PolicyError(`${what}.actions names no action; a reveal holds the actions it lists, and no other`)
2347
+ }
2348
+ const whenInput = ownEntry(policy, 'when')
2349
+ const when = whenInput === undefined ? undefined : parseCondition(whenInput, table, tables, `${what}.when`, hops)
2350
+ return { to, column, actions: freeze(listed), when }
2351
+ }
2352
+
2353
+ /**
2354
+ * `memberReveals`: the table's own dimension, or one it reads through, → the ancestor its rows reveal to a grant at the
2355
+ * node. By its own key only a dimension table reveals so: the layer generates the key, so no writer picks a node someone
2356
+ * already holds a grant at. Through a direct path the writer picks it, so an insertable table states `assign`, and the
2357
+ * row reveals its nearest container only, whose column no move of an ancestor rewrites. A queue table's rows move on
2358
+ * every claim.
2359
+ */
2360
+ function parseMemberReveals(
2361
+ table: LinkedTable,
2362
+ readThrough: readonly SecondaryPath[],
2363
+ input: unknown,
2364
+ vocabulary: VocabularyModel,
2365
+ tables: (name: string) => ConditionTable | undefined,
2366
+ hops: HopRule,
2367
+ ): readonly MemberRevealModel[] {
2368
+ if (input === undefined) {
2369
+ return freeze([])
2370
+ }
2371
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2372
+ throw new PolicyError(
2373
+ `${table.name}: a ${table.scope.mode} table reveals nothing to members; only a dimension or child table's rows name a node a grant is at`,
2374
+ )
2375
+ }
2376
+ if (table.queue !== undefined) {
2377
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2378
+ }
2379
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2380
+ const declared = plainRecord(input, `${table.name}: memberReveals`)
2381
+ const names = ownKeys(declared)
2382
+ const reveals: MemberRevealModel[] = []
2383
+ for (let index = 0; index < names.length; index++) {
2384
+ const source = names[index] ?? ''
2385
+ const what = `${table.name}: memberReveals.${source}`
2386
+ let path: SecondaryPath | undefined
2387
+ for (let position = 0; source !== own && position < readThrough.length; position++) {
2388
+ if (readThrough[position]?.dimension === source) path = readThrough[position]
2389
+ }
2390
+ if (source !== own && path === undefined) {
2391
+ throw new PolicyError(
2392
+ `${what}: ${source} is neither the own dimension of ${table.name} (${
2393
+ own ?? 'none'
2394
+ }) nor one it reads through; a row reveals to a grant at its own node or at the node its path names`,
2395
+ )
2396
+ }
2397
+ const policy = plainRecord(ownEntry(declared, source), what)
2398
+ onlyFields(policy, MEMBER_REVEALS_FIELDS, what)
2399
+ const { to, column, actions, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2400
+ if (path?.via !== undefined) {
2401
+ throw new PolicyError(
2402
+ `${what}: ${table.name} reads ${source} through its container ${path.via.table}; declare the member reveal on ${path.via.table}`,
2403
+ )
2404
+ }
2405
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2406
+ throw new PolicyError(
2407
+ `${what}.to: ${to} lies above ${table.name}'s nearest container; a move of an ancestor rewrites ${column}, so a member reveal through a path reveals the nearest container only`,
2408
+ )
2409
+ }
2410
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2411
+ const key = path === undefined ? table.scope.key : path.column
2412
+ reveals[reveals.length] = freeze({ source, table: table.name, key, path, assign, dimension: to, column, actions, when })
2413
+ }
2414
+ return freeze(reveals)
2415
+ }
2416
+
2417
+ /**
2418
+ * A reveal matched through a secondary path delegates on insert, since the row's writer picks the node: a table with an
2419
+ * insert action states the bound, as a relation source does. A reveal by the row's own key delegates nothing.
2420
+ */
2421
+ function parseRevealAssign(table: LinkedTable, path: SecondaryPath | undefined, input: unknown, what: string): RevealModel['assign'] {
2422
+ if (path === undefined || table.actions.insert.length === 0) {
2423
+ if (input !== undefined) {
2424
+ throw new PolicyError(
2425
+ path === undefined
2426
+ ? `${what}.assign: the reveal matches the row's own key, so no writer picks its node`
2427
+ : `${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`,
2428
+ )
2429
+ }
2430
+ return undefined
2431
+ }
2432
+ if (input === undefined) {
2433
+ throw new PolicyError(
2434
+ `${what}: inserting a row of ${table.name} (${
2435
+ table.actions.insert.join(', ')
2436
+ }) picks the ${path.dimension} node the reveal holds at; state assign: { self? }`,
2437
+ )
2438
+ }
2439
+ const assign = plainRecord(input, `${what}.assign`)
2440
+ onlyFields(assign, REVEAL_ASSIGN_FIELDS, `${what}.assign`)
2441
+ const self = ownEntry(assign, 'self')
2442
+ if (self !== undefined && self !== true) {
2443
+ throw new PolicyError(`${what}.assign.self takes true`)
2444
+ }
2445
+ return freeze({ self: self === true })
2446
+ }
2447
+
2448
+ /**
2449
+ * A row of the table hands out access that its writer places: it confers a relation, reveals through a path, or reveals
2450
+ * its ancestor to the grants at its node. Such a row is written only through the handles, and never moves.
2451
+ */
2452
+ export function delegates(model: TableModel): boolean {
2453
+ for (let index = 0; index < model.reveals.length; index++) {
2454
+ if (model.reveals[index]?.path !== undefined) return true
2455
+ }
2456
+ return model.confers.length > 0 || model.memberReveals.length > 0
2457
+ }
2458
+
2459
+ /**
2460
+ * The tables whose rows hand out access, which no raw statement writes, lowercased as the tag compares names: a relation
2461
+ * source, a path reveal or a path column that holds actions (`writeThrough`), whose writer the layer bounds; a
2462
+ * member-revealing table, whose key the layer generates so no write revives a node a stale grant still names; and the
2463
+ * tables a principal path or a relation's condition reads, whose columns decide whom a source row names and what it
2464
+ * confers.
2465
+ */
2466
+ export function accessTablesOf(models: TableModels): readonly string[] {
2467
+ const tables: string[] = []
2468
+ const names = ownKeys(models)
2469
+ for (let index = 0; index < names.length; index++) {
2470
+ const model = modelOf(models, names[index] ?? '')
2471
+ if (model !== undefined && (delegates(model) || pathWriters(models, model).length > 0)) {
2472
+ tables[tables.length] = model.name.toLowerCase()
2473
+ }
2474
+ for (let position = 0; model !== undefined && position < model.confers.length; position++) {
2475
+ const source = model.confers[position]
2476
+ const path = source?.principalPath
2477
+ if (path !== undefined) tables[tables.length] = path.table.toLowerCase()
2478
+ if (source?.when !== undefined) {
2479
+ conditionReach(source.when, (table) => {
2480
+ tables[tables.length] = table.toLowerCase()
2481
+ })
2482
+ }
2483
+ }
2484
+ }
2485
+ return tables
2486
+ }
2487
+
2488
+ /** A path column whose insert hands out the listed actions at the node it names: the bound its writer is held to. */
2489
+ export interface PathWriter {
2490
+ readonly path: SecondaryPath
2491
+ /** The path's own `writes` and those of every table that reads the same dimension through this table's column. */
2492
+ readonly actions: readonly string[]
2493
+ }
2494
+
2495
+ /**
2496
+ * The columns of `model` whose insert hands out actions through a secondary path: its own paths that hold actions, and
2497
+ * its paths that a table below follows through it (`'<link>.<column>'`) with actions of its own. Such a table is written
2498
+ * only through the handles, so no write sets the column past the bound.
2499
+ */
2500
+ export function pathWriters(models: Readonly<Record<string, TableModel>>, model: TableModel): readonly PathWriter[] {
2501
+ const writers: PathWriter[] = []
2502
+ const names = ownKeys(models)
2503
+ for (let index = 0; index < model.readThrough.length; index++) {
2504
+ const path = model.readThrough[index]
2505
+ if (path === undefined || path.via !== undefined) continue
2506
+ const actions: string[] = []
2507
+ for (let position = 0; position < path.writes.length; position++) {
2508
+ const action = path.writes[position] ?? ''
2509
+ if (!includes(actions, action)) actions[actions.length] = action
2510
+ }
2511
+ for (let position = 0; position < names.length; position++) {
2512
+ const below = ownEntry(models, names[position] ?? '')
2513
+ for (let at = 0; below !== undefined && at < below.readThrough.length; at++) {
2514
+ const through = below.readThrough[at]
2515
+ if (through?.via?.table !== model.name || through.dimension !== path.dimension) continue
2516
+ for (let written = 0; written < through.writes.length; written++) {
2517
+ const action = through.writes[written] ?? ''
2518
+ if (!includes(actions, action)) actions[actions.length] = action
2519
+ }
2520
+ }
2521
+ }
2522
+ if (actions.length > 0) writers[writers.length] = freeze({ path, actions: freeze(actions) })
2523
+ }
2524
+ return freeze(writers)
2525
+ }
2526
+
2527
+ function containsLink(chain: readonly Container[], dimension: string): boolean {
2528
+ for (let index = 0; index < chain.length; index++) {
2529
+ if (chain[index]?.dimension === dimension) return true
2530
+ }
2531
+ return false
2532
+ }
2533
+
2534
+ /** The column of `table` that places a row at a node of `dimension`: its key for its own dimension, else a chain link. */
2535
+ export function nodeColumnOf(table: Pick<TableModel, 'scope' | 'chain'>, dimension: string): string | undefined {
2536
+ if (table.scope.mode === 'dimension' && table.scope.dimension === dimension) {
2537
+ return table.scope.key
2538
+ }
2539
+ for (let index = 0; index < table.chain.length; index++) {
2540
+ const link = table.chain[index]
2541
+ if (link?.dimension === dimension) {
2542
+ return link.column
2543
+ }
2544
+ }
2545
+ return undefined
2546
+ }
2547
+
2548
+ /**
2549
+ * `confers`: relation → its columns on this table. The node is the table's own column for the relation's dimension,
2550
+ * which the layer stamps from the inserting Ref, so a row names only a node its writer acts on. The principal, the
2551
+ * node, the expiry and the condition's columns are never updated: a row that confers more is a new row, which its
2552
+ * insert action bounds (`assign`).
2553
+ */
2554
+ function parseConfers(
2555
+ table: LinkedTable,
2556
+ input: unknown,
2557
+ relations: Readonly<Record<string, string>>,
2558
+ tables: (name: string) => ConditionTable | undefined,
2559
+ linked: (name: string) => LinkedTable | undefined,
2560
+ hops: HopRule,
2561
+ ): readonly RelationSource[] {
2562
+ if (input === undefined) {
2563
+ return freeze([])
2564
+ }
2565
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2566
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table confers no relation; its rows lie at no node`)
2567
+ }
2568
+ if (table.view) {
2569
+ throw new PolicyError(
2570
+ `${table.name}: a view confers no relation; its rows change with every write to the tables it reads, which no delegation bound sees`,
2571
+ )
2572
+ }
2573
+ if (table.queue !== undefined) {
2574
+ // A claim, a requeue and `done: true` rewrite `due` and `version` past every update-column check.
2575
+ throw new PolicyError(`${table.name}: a queue table confers no relation; the layer rewrites its rows on every claim`)
2576
+ }
2577
+ const declared = plainRecord(input, `${table.name}: confers`)
2578
+ const names = ownKeys(declared)
2579
+ const sources: RelationSource[] = []
2580
+ for (let index = 0; index < names.length; index++) {
2581
+ const relation = names[index] ?? ''
2582
+ const what = `${table.name}: confers.${relation}`
2583
+ const dimension = ownEntry(relations, relation)
2584
+ if (dimension === undefined) {
2585
+ throw new PolicyError(`${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(relations).join(', ') || 'none'})`)
2586
+ }
2587
+ const policy = plainRecord(ownEntry(declared, relation), what)
2588
+ onlyFields(policy, CONFERS_FIELDS, what)
2589
+ const column = (value: unknown, field: string): string => {
2590
+ if (!inSet(table.columns, value)) {
2591
+ throw new PolicyError(`${what}.${field} names ${String(value)}, which is not a column of ${table.name}`)
2592
+ }
2593
+ return value
2594
+ }
2595
+ const { column: principal, path: principalPath } = parsePrincipal(table, ownEntry(policy, 'principal'), linked, what)
2596
+ const placed = nodeColumnOf(table, dimension)
2597
+ if (placed === undefined) {
2598
+ throw new PolicyError(`${what}: ${table.name} does not lie in ${dimension}, the relation's dimension, so its rows name no node of it`)
2599
+ }
2600
+ const own = table.scope.mode === 'dimension' && table.scope.dimension === dimension
2601
+ if (!own && table.chain[0]?.column !== placed) {
2602
+ // An inherited column follows a move of an ancestor (ON UPDATE CASCADE), which no delegation bound sees.
2603
+ throw new PolicyError(
2604
+ `${what}: ${dimension} is above ${table.name}'s own container, and a move of an ancestor rewrites ${placed}; a relation's node is the row's key or its own container or parent column`,
2605
+ )
2606
+ }
2607
+ const nodeInput = ownEntry(policy, 'node')
2608
+ const node = nodeInput === undefined ? placed : column(nodeInput, 'node')
2609
+ if (node !== placed) {
2610
+ throw new PolicyError(`${what}.node is ${node}, but a row's ${dimension} is ${placed}: the node is the column the inserting Ref stamps`)
2611
+ }
2612
+ const expiresInput = ownEntry(policy, 'expires')
2613
+ const expires = expiresInput === undefined ? undefined : column(expiresInput, 'expires')
2614
+ if (expires !== undefined && !inSet(table.timestamps, expires)) {
2615
+ throw new PolicyError(`${what}.expires names ${expires}, which is not a timestamp column`)
2616
+ }
2617
+ const whenInput = ownEntry(policy, 'when')
2618
+ const when = whenInput === undefined ? undefined : parseSourceWhen(table, whenInput, tables, linked, hops, `${what}.when`)
2619
+ const fixed: string[] = [principal]
2620
+ if (expires !== undefined) fixed[fixed.length] = expires
2621
+ const read = when === undefined ? [] : conditionColumns(when)
2622
+ for (let position = 0; position < read.length; position++) {
2623
+ fixed[fixed.length] = read[position] ?? ''
2624
+ }
2625
+ for (let position = 0; position < fixed.length; position++) {
2626
+ const name = fixed[position] ?? ''
2627
+ if (name === table.version) {
2628
+ throw new PolicyError(`${what}: ${name} is the version column, which every update rewrites; it decides nothing a row confers`)
2629
+ }
2630
+ if (inSet(table.update, name) || hasOwn(table.columnWrites, name)) {
2631
+ throw new PolicyError(`${what}: ${name} decides what a row confers, so no update writes it; replace the row instead`)
2632
+ }
2633
+ }
2634
+ if (principal === node || principal === table.version || hasOwn(table.files, principal)) {
2635
+ throw new PolicyError(`${what}.principal ${principal} is a column the layer stamps; it holds the principal the row names`)
2636
+ }
2637
+ if (principalPath === undefined) refuseReferencing(table, principal, `${what}.principal`, 'holds the principal', undefined)
2638
+ const assign = parseAssign(table, policy, expires, what)
2639
+ if (principal === table.createdBy && principalPath !== undefined) {
2640
+ throw new PolicyError(`${what}.principal ${principal} is the createdBy column, which holds a principal; a principal path starts at a foreign key`)
2641
+ }
2642
+ // The layer stamps createdBy with the writer, so every row such a source confers names its writer.
2643
+ if (principal === table.createdBy && assign !== undefined && !assign.self) {
2644
+ throw new PolicyError(
2645
+ `${what}.principal ${principal} is the createdBy column, so every inserted row names its writer: state assign: { self: true }`,
2646
+ )
2647
+ }
2648
+ sources[sources.length] = freeze({ relation, dimension, table: table.name, principal, principalPath, node, expires, when, assign })
2649
+ }
2650
+ return freeze(sources)
2651
+ }
2652
+
2653
+ /**
2654
+ * `confers.<relation>.when`: a condition on the source row, which may follow one foreign key to the row it names (the far
2655
+ * side of a many-to-many source). What it reads decides whom the relation reaches, so it is held as the principal is:
2656
+ * no update writes it, on the source or on the far row, and nothing a write elsewhere cascades rewrites it.
2657
+ */
2658
+ function parseSourceWhen(
2659
+ table: LinkedTable,
2660
+ input: unknown,
2661
+ tables: (name: string) => ConditionTable | undefined,
2662
+ linked: (name: string) => LinkedTable | undefined,
2663
+ hops: HopRule,
2664
+ what: string,
2665
+ ): ConditionModel {
2666
+ const condition = parseCondition(input, table, tables, what, hops)
2667
+ const visit = (node: ConditionModel): void => {
2668
+ if (node.kind === 'not') {
2669
+ visit(node.term)
2670
+ } else if (node.kind === 'some') {
2671
+ // Every writer of the naming table adds and removes such rows; no rule holds a set of rows still.
2672
+ throw new PolicyError(
2673
+ `${what}: a relation's condition takes no some or none: the rows naming a source row are written outside its delegation bound`,
2674
+ )
2675
+ } else if (node.kind === 'test') {
2676
+ const hop = node.hops[0]
2677
+ if (node.hops.length > 1) {
2678
+ // The far row is read inside every relation term, beside a principal path, four subqueries deep under a reveal.
2679
+ throw new PolicyError(`${what}: a relation's condition follows at most one foreign key, to the row the source row names`)
2680
+ }
2681
+ if (hop !== undefined) farColumn(table, hop, node.column, linked, what)
2682
+ } else {
2683
+ for (let index = 0; index < node.terms.length; index++) {
2684
+ const term = node.terms[index]
2685
+ if (term !== undefined) visit(term)
2686
+ }
2687
+ }
2688
+ }
2689
+ visit(condition)
2690
+ return condition
2691
+ }
2692
+
2693
+ /** The column a relation's condition tests on the row one foreign key of the source names: fixed like a principal. */
2694
+ function farColumn(
2695
+ table: LinkedTable,
2696
+ hop: ConditionHop,
2697
+ held: string,
2698
+ linked: (name: string) => LinkedTable | undefined,
2699
+ what: string,
2700
+ ): void {
2701
+ refuseReferencing(table, hop.column, what, "starts the condition's path", hop)
2702
+ const target = linked(hop.table)
2703
+ if (target === undefined) {
2704
+ throw new PolicyError(`${what}: ${table.name}.${hop.column} references ${hop.table}, which has no policy`)
2705
+ }
2706
+ if (target.view) {
2707
+ throw new PolicyError(`${what}: ${hop.table} is a view, whose rows change with every write to the tables it reads`)
2708
+ }
2709
+ if (target.queue !== undefined) {
2710
+ throw new PolicyError(`${what}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2711
+ }
2712
+ const scope = target.scope
2713
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2714
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2715
+ throw new PolicyError(
2716
+ `${what}: ${hop.table} is a top-level dimension table, whose key an insert takes from its Ref; a relation's condition reads a row whose key the layer generates`,
2717
+ )
2718
+ }
2719
+ if (scope.mode !== 'reference') {
2720
+ refuseReferencing(target, scope.key, what, "is the key the condition's path follows", undefined)
2721
+ }
2722
+ if (held === target.version) {
2723
+ throw new PolicyError(`${what}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2724
+ }
2725
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2726
+ throw new PolicyError(`${what}: ${hop.table}.${held} decides what a row confers, so no update of ${hop.table} writes it; replace the row instead`)
2727
+ }
2728
+ if (chainColumn(target, held)) {
2729
+ throw new PolicyError(`${what}: ${hop.table}.${held} is a containment column, which a move rewrites; it decides nothing a row confers`)
2730
+ }
2731
+ refuseReferencing(target, held, what, 'decides what a row confers', undefined)
2732
+ }
2733
+
2734
+ /**
2735
+ * `confers.<relation>.principal`: a column of the source, or `<column>.<principal column>`, one single-column foreign key
2736
+ * of the source into the key of a table P whose column holds the principal. Every column that decides the principal is
2737
+ * one no update writes, on P as on the source, so a row names someone else only as a new row its insert bounds.
2738
+ */
2739
+ function parsePrincipal(
2740
+ table: LinkedTable,
2741
+ input: unknown,
2742
+ linked: (name: string) => LinkedTable | undefined,
2743
+ what: string,
2744
+ ): { readonly column: string; readonly path: PrincipalPath | undefined } {
2745
+ const field = `${what}.principal`
2746
+ if (typeof input !== 'string') {
2747
+ throw new PolicyError(`${field} names ${String(input)}, which is not a column of ${table.name}`)
2748
+ }
2749
+ const segments = splitPath(input)
2750
+ if (segments.length === 1) {
2751
+ if (!inSet(table.columns, input)) {
2752
+ throw new PolicyError(`${field} names ${input}, which is not a column of ${table.name}`)
2753
+ }
2754
+ return { column: input, path: undefined }
2755
+ }
2756
+ if (segments.length !== 2) {
2757
+ throw new PolicyError(`${field} ${input} follows more than one foreign key; a principal path is <column>.<principal column>`)
2758
+ }
2759
+ const column = segments[0] ?? ''
2760
+ const held = segments[1] ?? ''
2761
+ // A move rewrites a chain column (ON UPDATE CASCADE), and the layer stamps the key and the version: none is fixed.
2762
+ const own = table.scope.mode === 'reference' ? undefined : table.scope.key
2763
+ if (column === own || column === table.version || hasOwn(table.files, column) || chainColumn(table, column)) {
2764
+ throw new PolicyError(
2765
+ `${field}: ${table.name}.${column} is a key, a containment, a version or a file column, which the layer stamps or a move rewrites; a principal path starts at a foreign key no update writes`,
2766
+ )
2767
+ }
2768
+ const hop = singleForeignKey(table, column, field)
2769
+ const target = linked(hop.table)
2770
+ if (target === undefined) {
2771
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}, which has no policy`)
2772
+ }
2773
+ if (target.view) {
2774
+ throw new PolicyError(`${field}: ${hop.table} is a view, whose rows change with every write to the tables it reads; a table holds the principal`)
2775
+ }
2776
+ if (target.queue !== undefined) {
2777
+ throw new PolicyError(`${field}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2778
+ }
2779
+ const scope = target.scope
2780
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
2781
+ throw new PolicyError(`${field}: ${hop.table} is a ${scope.mode} table; the principal is held by a table whose key ${column} references`)
2782
+ }
2783
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2784
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2785
+ throw new PolicyError(
2786
+ `${field}: ${hop.table} is a top-level dimension table, whose key an insert takes from its Ref; the principal is held by a table whose key the layer generates`,
2787
+ )
2788
+ }
2789
+ if (scope.key !== hop.key) {
2790
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}.${hop.key}, not its key ${scope.key}`)
2791
+ }
2792
+ // Only the hop's own key, or a tenant-holding one that maps the column to the same key, may hold the start column.
2793
+ refuseReferencing(table, column, field, 'starts the principal path', hop)
2794
+ refuseReferencing(target, scope.key, field, 'is the key the principal path follows', undefined)
2795
+ if (!inSet(target.columns, held)) {
2796
+ throw new PolicyError(`${field}: ${held} is not a column of ${hop.table}`)
2797
+ }
2798
+ if (held === target.version) {
2799
+ throw new PolicyError(`${field}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2800
+ }
2801
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2802
+ throw new PolicyError(`${field}: ${hop.table}.${held} decides whom a row names, so no update of ${hop.table} writes it; replace the row instead`)
2803
+ }
2804
+ if (held === scope.key || hasOwn(target.files, held) || inSet(target.json, held) || chainColumn(target, held)) {
2805
+ throw new PolicyError(`${field}: ${hop.table}.${held} is a key, a containment, a file or a JSON column; it holds no principal`)
2806
+ }
2807
+ refuseReferencing(target, held, field, 'holds the principal', undefined)
2808
+ return { column, path: freeze({ table: hop.table, key: hop.key, column: held }) }
2809
+ }
2810
+
2811
+ function chainColumn(table: Pick<TableModel, 'chain'>, column: string): boolean {
2812
+ for (let index = 0; index < table.chain.length; index++) {
2813
+ if (table.chain[index]?.column === column) return true
2814
+ }
2815
+ return false
2816
+ }
2817
+
2818
+ /**
2819
+ * A column that decides whom a row names references nothing but `hop` (a key into `hop.table` that maps it to
2820
+ * `hop.key`): the column list carries no foreign key's actions, and one that cascades on update would let a write to
2821
+ * the referenced table change whom every row names.
2822
+ */
2823
+ function refuseReferencing(
2824
+ table: Pick<TableModel, 'name' | 'foreignKeys'>,
2825
+ column: string,
2826
+ field: string,
2827
+ role: string,
2828
+ hop: { readonly table: string; readonly key: string } | undefined,
2829
+ ): void {
2830
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2831
+ const key = table.foreignKeys[index]
2832
+ if (key === undefined) continue
2833
+ for (let position = 0; position < key.columns.length; position++) {
2834
+ if (key.columns[position] !== column) continue
2835
+ if (hop !== undefined && key.table === hop.table && key.references[position] === hop.key) continue
2836
+ throw new PolicyError(
2837
+ `${field}: ${table.name}.${column} ${role} and is a column of a foreign key to ${key.table}, which an update there may rewrite; it references nothing else`,
2838
+ )
2839
+ }
2840
+ }
2841
+ }
2842
+
2843
+ function parseAssign(
2844
+ table: LinkedTable,
2845
+ policy: Readonly<Record<string, unknown>>,
2846
+ expires: string | undefined,
2847
+ what: string,
2848
+ ): RelationSource['assign'] {
2849
+ const input = ownEntry(policy, 'assign')
2850
+ if (table.actions.insert.length === 0) {
2851
+ if (input !== undefined) {
2852
+ throw new PolicyError(`${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`)
2853
+ }
2854
+ return undefined
2855
+ }
2856
+ if (input === undefined) {
2857
+ throw new PolicyError(
2858
+ `${what}: inserting a row of ${table.name} (${table.actions.insert.join(', ')}) delegates the relation; state assign: { maxDays?, self? }`,
2859
+ )
2860
+ }
2861
+ const assign = plainRecord(input, `${what}.assign`)
2862
+ onlyFields(assign, ASSIGN_FIELDS, `${what}.assign`)
2863
+ const maxDays = ownEntry(assign, 'maxDays')
2864
+ if (maxDays !== undefined && (typeof maxDays !== 'number' || !isSafeInteger(maxDays) || maxDays < 1 || maxDays > MAX_ASSIGN_DAYS)) {
2865
+ throw new PolicyError(`${what}.assign.maxDays takes a whole number of days from 1 to ${MAX_ASSIGN_DAYS}`)
2866
+ }
2867
+ if (maxDays !== undefined && expires === undefined) {
2868
+ throw new PolicyError(`${what}.assign.maxDays bounds a row's expires, which the relation does not declare`)
2869
+ }
2870
+ const self = ownEntry(assign, 'self')
2871
+ if (self !== undefined && self !== true) {
2872
+ throw new PolicyError(`${what}.assign.self takes true`)
2873
+ }
2874
+ return freeze({ maxDays: typeof maxDays === 'number' ? maxDays : undefined, self: self === true })
2875
+ }
2876
+
2877
+ /** The own columns a condition reads. */
2878
+ function conditionColumns(condition: ConditionModel): readonly string[] {
2879
+ if (condition.kind === 'test') {
2880
+ return condition.hops.length === 0 ? [condition.column] : [condition.hops[0]?.column ?? '']
2881
+ }
2882
+ if (condition.kind === 'not') {
2883
+ return conditionColumns(condition.term)
2884
+ }
2885
+ if (condition.kind === 'some') {
2886
+ return [condition.hops[0]?.column ?? condition.key]
2887
+ }
2888
+ const columns: string[] = []
2889
+ for (let index = 0; index < condition.terms.length; index++) {
2890
+ const term = condition.terms[index]
2891
+ const inner = term === undefined ? [] : conditionColumns(term)
2892
+ for (let position = 0; position < inner.length; position++) {
2893
+ columns[columns.length] = inner[position] ?? ''
2894
+ }
2895
+ }
2896
+ return columns
2897
+ }
2898
+
2899
+ /** A table's scope with nothing left to derive, and its containment chain. */
2900
+ interface Resolved {
2901
+ readonly scope: ScopeModel
2902
+ readonly chain: readonly Container[]
2903
+ }
2904
+
2905
+ function resolveChain(
2906
+ table: ParsedTable,
2907
+ byName: Readonly<Record<string, ParsedTable>>,
2908
+ owners: Readonly<Record<string, ParsedTable>>,
2909
+ containment: Containment,
2910
+ chainOf: (table: ParsedTable) => readonly Container[],
2911
+ ): Resolved {
2912
+ /**
2913
+ * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
2914
+ * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
2915
+ */
2916
+ const above = (dimension: string): readonly Container[] => {
2917
+ const owner = ownEntry(owners, dimension)
2918
+ if (owner !== undefined) {
2919
+ return chainOf(owner)
2920
+ }
2921
+ const container = ownEntry(containment, dimension)?.container
2922
+ return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
2923
+ }
2924
+ const scope = table.scope
2925
+ if (scope.mode === 'dimension') {
2926
+ const container = scope.container
2927
+ if (container === undefined) {
2928
+ return { scope, chain: freeze([]) }
2929
+ }
2930
+ const owner = ownEntry(owners, container.dimension)
2931
+ if (owner !== undefined) {
1115
2932
  requireReference(table, container, owner, (column) => `scope.in: { column: '${column}' }`)
1116
2933
  requireCoveringKey(table, container, owner, chainOf(owner))
1117
2934
  }
@@ -1129,6 +2946,20 @@ function resolveChain(
1129
2946
  for (let index = 0; index < parentChain.length; index++) {
1130
2947
  expected[index] = parentChain[index]?.column ?? ''
1131
2948
  }
2949
+ const dimension = parent.scope.dimension
2950
+ const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
2951
+ // A view has no foreign key: its rows are read through the parent row its parent column names (ADR-0072).
2952
+ if (table.view) {
2953
+ const inherit = scope.inherit ?? freeze(carried(table, expected))
2954
+ for (let index = 0; index < inherit.length; index++) {
2955
+ if (!includes(expected, inherit[index])) {
2956
+ throw new PolicyError(
2957
+ `${table.name}: inherits ${inherit[index]}, which is not a containment column of ${scope.parent} (${expected.join(', ') || 'none'})`,
2958
+ )
2959
+ }
2960
+ }
2961
+ return { scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }), chain: freeze([link]) }
2962
+ }
1132
2963
  const inherit = scope.inherit ?? freeze(expected)
1133
2964
  const inherited = nameSet(inherit)
1134
2965
  let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
@@ -1142,8 +2973,6 @@ function resolveChain(
1142
2973
  }), so a composite foreign key keeps it in scope`,
1143
2974
  )
1144
2975
  }
1145
- const dimension = parent.scope.dimension
1146
- const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
1147
2976
  requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1148
2977
  requireCoveringKey(table, link, parent, parentChain)
1149
2978
  return {
@@ -1152,6 +2981,16 @@ function resolveChain(
1152
2981
  }
1153
2982
  }
1154
2983
 
2984
+ /** The columns of `names` that `table` has: the parent's containment columns a view carries, which a join of it compares. */
2985
+ function carried(table: ParsedTable, names: readonly string[]): readonly string[] {
2986
+ const found: string[] = []
2987
+ for (let index = 0; index < names.length; index++) {
2988
+ const name = names[index] ?? ''
2989
+ if (inSet(table.columns, name)) found[found.length] = name
2990
+ }
2991
+ return found
2992
+ }
2993
+
1155
2994
  /** Whether a foreign key of `table` takes `column` to `key` of `target`, alone or as part of a composite key. */
1156
2995
  function references(table: ParsedTable, column: string, target: string, key: string): boolean {
1157
2996
  for (let index = 0; index < table.foreignKeys.length; index++) {
@@ -1231,6 +3070,66 @@ function requireCoveringKey(table: ParsedTable, link: Container, owner: ParsedTa
1231
3070
  )
1232
3071
  }
1233
3072
 
3073
+ /**
3074
+ * The column pairs of the covering key a containment column follows (`requireCoveringKey`): the column and the key,
3075
+ * then each column of the owner's chain, which the contained row carries under the same name.
3076
+ */
3077
+ function containmentPairs(column: string, key: string, ownerChain: readonly Container[]): [string, string][] {
3078
+ const pairs: [string, string][] = [[column, key]]
3079
+ for (let index = 0; index < ownerChain.length; index++) {
3080
+ const link = ownerChain[index]
3081
+ if (link !== undefined) pairs[pairs.length] = [link.column, link.column]
3082
+ }
3083
+ return pairs
3084
+ }
3085
+
3086
+ /**
3087
+ * The column pairs a foreign key from `column` of `table` to a row keyed by `key` with chain `chain` holds to keep that
3088
+ * row in `table`'s own tenant: the column and the key, then each ancestor of `chain` that `table` also lies in.
3089
+ */
3090
+ function tenantPairs(table: Resolved, column: string, key: string, chain: readonly Container[]): [string, string][] {
3091
+ const pairs: [string, string][] = [[column, key]]
3092
+ for (let index = 0; index < chain.length; index++) {
3093
+ const link = chain[index]
3094
+ const shared = link === undefined ? undefined : nodeColumnOf(table, link.dimension)
3095
+ if (link !== undefined && shared !== undefined) pairs[pairs.length] = [shared, link.column]
3096
+ }
3097
+ return pairs
3098
+ }
3099
+
3100
+ /**
3101
+ * The ancestor columns of a tenant key (every pair but the first) must be NOT NULL: under MATCH SIMPLE a null one skips
3102
+ * the key, and a row written raw with it null would reach another tenant's row.
3103
+ */
3104
+ function requireNotNullAncestors(
3105
+ what: string,
3106
+ table: { readonly name: string; readonly notNull: NameSet },
3107
+ pairs: readonly (readonly [string, string])[],
3108
+ ): void {
3109
+ const nullable: string[] = []
3110
+ for (let index = 1; index < pairs.length; index++) {
3111
+ const column = pairs[index]?.[0] ?? ''
3112
+ if (!inSet(table.notNull, column)) nullable[nullable.length] = column
3113
+ }
3114
+ if (nullable.length > 0) {
3115
+ throw new PolicyError(
3116
+ `${what}: ${nullable.join(', ')} of ${table.name} may be null, and a null skips the foreign key that holds the row's tenant; declare ${
3117
+ nullable.join(', ')
3118
+ } not null and run fabrika db codegen`,
3119
+ )
3120
+ }
3121
+ }
3122
+
3123
+ /** One foreign key to `table` of exactly `pairs`: a further nullable column would let the database skip the whole key. */
3124
+ function holdsExactly(foreignKeys: readonly ForeignKey[], table: string, pairs: readonly (readonly [string, string])[]): boolean {
3125
+ for (let index = 0; index < foreignKeys.length; index++) {
3126
+ const foreignKey = foreignKeys[index]
3127
+ if (foreignKey !== undefined && foreignKey.table === table && foreignKey.columns.length === pairs.length && coversPairs(foreignKey, pairs)) {
3128
+ return true
3129
+ }
3130
+ }
3131
+ return false
3132
+ }
1234
3133
  /** Whether every `[column, referenced]` pair is a column of `foreignKey` with that referenced column. */
1235
3134
  function coversPairs(foreignKey: ForeignKey, pairs: readonly (readonly [string, string])[]): boolean {
1236
3135
  for (let index = 0; index < pairs.length; index++) {
@@ -1283,12 +3182,21 @@ type ScopeOf<P, T> = PolicyOf<P, T> extends { readonly scope: infer S } ? S : ne
1283
3182
 
1284
3183
  export type Operation = 'read' | 'insert' | 'update' | 'delete'
1285
3184
 
1286
- /** The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none. */
3185
+ /**
3186
+ * The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none, and for
3187
+ * the read of a table read with `'any'` (`ReadsAny`).
3188
+ */
1287
3189
  export type ActionOf<P, T, Op extends Operation> = PolicyOf<P, T> extends { readonly actions: infer Acts }
1288
- ? Acts extends { readonly [K in Op]: infer A } ? A extends string ? A : A extends readonly (infer L extends string)[] ? L : never
3190
+ ? Acts extends { readonly [K in Op]: infer A } ? A extends typeof READ_ANY ? never
3191
+ : A extends string ? A
3192
+ : A extends readonly (infer L extends string)[] ? L
3193
+ : never
1289
3194
  : never
1290
3195
  : never
1291
3196
 
3197
+ /** Whether table `T` is read with `'any'`: by every `app` endpoint, job and webhook, whatever its action. */
3198
+ export type ReadsAny<P, T> = PolicyOf<P, T> extends { readonly actions: { readonly read: typeof READ_ANY } } ? true : false
3199
+
1292
3200
  export type DimensionOf<P, T> = ScopeOf<P, T> extends { readonly dimension: infer D extends string } ? D : never
1293
3201
  export type ContainerOf<P, T> = ScopeOf<P, T> extends { readonly in: { readonly dimension: infer D extends string } } ? D : never
1294
3202
  /** The dimension that lists and inserts of T are scoped by: its container, or for a top-level table its own. */
@@ -1307,19 +3215,23 @@ type Flat<T> = { [K in keyof T]: T[K] }
1307
3215
 
1308
3216
  type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends { readonly columns: infer C } ? C : never
1309
3217
  type TableReadAction<P, T> = PolicyOf<P, T> extends { readonly scope: { readonly read: infer A } } ? A : ActionOf<P, T, 'read'>
1310
- /** Columns whose own read action is not the table's: no read by the table's read action returns them. */
3218
+ /** Columns whose own read actions leave out one of the table's: no read by the table's read action returns them. */
1311
3219
  type RestrictedColumns<P, T> = [ColumnPoliciesOf<P, T>] extends [never] ? never
1312
3220
  : {
1313
3221
  [K in keyof ColumnPoliciesOf<P, T>]: ColumnPoliciesOf<P, T>[K] extends { readonly read: infer R }
1314
- ? ([TableReadAction<P, T>] extends [R] ? never : K)
3222
+ ? ([TableReadAction<P, T>] extends [R extends readonly (infer L extends string)[] ? L : R] ? never : K)
1315
3223
  : never
1316
3224
  }[keyof ColumnPoliciesOf<P, T>]
1317
3225
 
1318
3226
  /** A row of table `T` as a store reads it, by the table's read action. */
1319
- export type PolicyRow<DB, P, T> = T extends keyof DB ? Flat<Omit<Selectable<DB[T]>, RestrictedColumns<P, T>>> : never
1320
- export type InsertValues<DB, P, T> = T extends keyof DB ? Flat<Pick<Insertable<DB[T]>, ListedColumns<P, T, 'insert'> & keyof Insertable<DB[T]>>>
3227
+ export type PolicyRow<DB, P, T> = T extends keyof DB
3228
+ ? WithJson<Flat<Omit<Selectable<DB[T]>, RestrictedColumns<P, T>>>, JsonSchemasOf<P, T>, DB[T], 'output'>
3229
+ : never
3230
+ export type InsertValues<DB, P, T> = T extends keyof DB
3231
+ ? WithJson<Flat<Pick<Insertable<DB[T]>, ListedColumns<P, T, 'insert'> & keyof Insertable<DB[T]>>>, JsonSchemasOf<P, T>, DB[T], 'input'>
1321
3232
  : never
1322
- export type UpdateValues<DB, P, T> = T extends keyof DB ? Flat<Pick<Updateable<DB[T]>, ListedColumns<P, T, 'update'> & keyof Updateable<DB[T]>>>
3233
+ export type UpdateValues<DB, P, T> = T extends keyof DB
3234
+ ? WithJson<Flat<Pick<Updateable<DB[T]>, ListedColumns<P, T, 'update'> & keyof Updateable<DB[T]>>>, JsonSchemasOf<P, T>, DB[T], 'input'>
1323
3235
  : never
1324
3236
 
1325
3237
  /** The values a store inserts into table `T` of a `defineTables` result: `TableInsert<typeof tables, 'deals'>`. */