@fabrika/db 0.9.0-dev.3 → 0.9.0-dev.30

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 (82) hide show
  1. package/package.json +39 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +230 -41
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +8 -5
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +181 -0
  24. package/src/migrations.ts +43 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +198 -67
  27. package/src/orm.ts +383 -133
  28. package/src/policy.ts +1933 -122
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +55 -3
  31. package/src/request-receipts.ts +107 -0
  32. package/src/sql.ts +247 -476
  33. package/src/sqlite-bun.ts +149 -0
  34. package/src/sqlite-migrate.ts +242 -0
  35. package/src/sqlite.ts +269 -0
  36. package/src/store.ts +2292 -239
  37. package/src/stored-files.ts +188 -52
  38. package/src/tables.ts +171 -5
  39. package/src/temporal.ts +122 -9
  40. package/src/testing-shared.ts +1348 -0
  41. package/src/testing-sqlite.ts +685 -0
  42. package/src/testing.ts +310 -494
  43. package/src/vocabulary-tables.ts +159 -27
  44. package/types/src/application-rows.d.ts +58 -0
  45. package/types/src/authority.d.ts +147 -0
  46. package/types/src/builtins.d.ts +2 -0
  47. package/types/src/capability.d.ts +55 -2
  48. package/types/src/codegen-sqlite.d.ts +13 -0
  49. package/types/src/codegen.d.ts +79 -5
  50. package/types/src/condition-nodes.d.ts +9 -0
  51. package/types/src/conditions.d.ts +151 -0
  52. package/types/src/database.d.ts +81 -20
  53. package/types/src/description.d.ts +26 -8
  54. package/types/src/errors.d.ts +7 -5
  55. package/types/src/file-columns.d.ts +6 -4
  56. package/types/src/framework.d.ts +12 -5
  57. package/types/src/guard.d.ts +24 -0
  58. package/types/src/index.d.ts +5 -4
  59. package/types/src/job-leases.d.ts +34 -5
  60. package/types/src/job-wakes.d.ts +101 -0
  61. package/types/src/json.d.ts +18 -0
  62. package/types/src/migrations-sqlite.d.ts +4 -0
  63. package/types/src/migrations.d.ts +2 -0
  64. package/types/src/nodes.d.ts +17 -2
  65. package/types/src/orm-types.d.ts +155 -63
  66. package/types/src/orm.d.ts +21 -0
  67. package/types/src/policy.d.ts +344 -16
  68. package/types/src/postgres.d.ts +12 -0
  69. package/types/src/registry.d.ts +40 -3
  70. package/types/src/request-receipts.d.ts +22 -0
  71. package/types/src/sql.d.ts +29 -21
  72. package/types/src/sqlite-bun.d.ts +21 -0
  73. package/types/src/sqlite-migrate.d.ts +28 -0
  74. package/types/src/sqlite.d.ts +24 -0
  75. package/types/src/store.d.ts +143 -34
  76. package/types/src/stored-files.d.ts +6 -2
  77. package/types/src/tables.d.ts +18 -2
  78. package/types/src/temporal.d.ts +24 -0
  79. package/types/src/testing-shared.d.ts +290 -0
  80. package/types/src/testing-sqlite.d.ts +37 -0
  81. package/types/src/testing.d.ts +2 -93
  82. package/types/src/vocabulary-tables.d.ts +169 -22
package/src/policy.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { READ_ANY } from '@fabrika/auth-core'
1
2
  import type { Insertable, Selectable, SelectType, Updateable } from 'kysely'
2
3
  import {
3
4
  freeze,
@@ -8,21 +9,29 @@ import {
8
9
  type NameSet,
9
10
  nameSet,
10
11
  namesOf,
11
- OBJECT_PROTOTYPE,
12
- ownDescriptor,
13
12
  ownEntry,
14
13
  ownKeys,
15
- ownNames,
16
- ownSymbols,
17
14
  parseList,
18
- prototypeOf,
15
+ plainRecord,
19
16
  setOwn,
20
17
  } from './builtins'
18
+ import {
19
+ type ConditionHop,
20
+ type ConditionModel,
21
+ type ConditionPolicy,
22
+ conditionReach,
23
+ type ConditionTable,
24
+ type HopRule,
25
+ insertProblem,
26
+ parseCondition,
27
+ singleForeignKey,
28
+ splitPath,
29
+ } from './conditions'
21
30
  import { PolicyError } from './errors'
22
31
  import { isPlainIdentifier } from './identifier'
23
32
  import type { Unavailable } from './orm-types'
24
33
  export type { RowOf } from './orm-types'
25
- import type { ColumnTypes, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
34
+ import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
26
35
 
27
36
  export interface DimensionScope<Col extends string> {
28
37
  readonly dimension: string
@@ -50,6 +59,8 @@ export interface ApplicationScope<Col extends string> {
50
59
  /** One action, or a list of them: a table that staff and a public procedure both read names both actions. */
51
60
  export type TableAction<A extends string> = A | readonly A[]
52
61
 
62
+ export { READ_ANY }
63
+
53
64
  export interface TableActions<A extends string> {
54
65
  readonly read: TableAction<A>
55
66
  readonly insert?: TableAction<A>
@@ -57,6 +68,11 @@ export interface TableActions<A extends string> {
57
68
  readonly delete?: TableAction<A>
58
69
  }
59
70
 
71
+ /** An application table's actions: its read may be `'any'` instead of its actions (`READ_ANY`). */
72
+ export interface ApplicationActions<A extends string> extends Omit<TableActions<A>, 'read'> {
73
+ readonly read: TableAction<A> | typeof READ_ANY
74
+ }
75
+
60
76
  /**
61
77
  * A queue table's columns (ADR-0060's drain): `due` is when a row is next claimed, `null` once it is done; `attempts`
62
78
  * counts its claims, and a row with `maxAttempts` (default 10) of them is no longer claimed.
@@ -91,26 +107,118 @@ interface WritablePolicy<Col extends string, A extends string, V extends Col, Ac
91
107
  * file reference. The table's actions are the file's authority.
92
108
  */
93
109
  readonly files?: FilePolicies<Col>
110
+ /** The relations this table's rows confer (`relations` of the vocabulary): each row holds one principal at one node. */
111
+ readonly confers?: { readonly [relation: string]: ConfersPolicy<Col> }
112
+ /** Conditions that narrow an action of this table: a row the condition does not admit is out of that action's reach. */
113
+ readonly when?: { readonly [action in A]?: ConditionPolicy<Col> }
114
+ /**
115
+ * Relation → action → a condition on the rows that relation reaches for that action: it narrows the relation's terms
116
+ * only, never an IAM grant, a member reveal or a path grant of the action.
117
+ */
118
+ readonly relationWhen?: { readonly [relation: string]: { readonly [action in A]?: ConditionPolicy<Col> } }
119
+ /** Relation of this table's own dimension, or of one it reads through → the ancestor node a row the relation reaches reveals. */
120
+ readonly reveals?: { readonly [relation: string]: RevealsPolicy<Col, A> }
121
+ /**
122
+ * Dimension outside the chain → the foreign key column a read reaches a row through: a `Within` of the dimension, or a
123
+ * relation at it, reads the row, and every write follows containment only. No update writes the column. Or
124
+ * `<nearest container column>.<its column>`: the row is read through its nearest container's own read path.
125
+ */
126
+ readonly readThrough?: { readonly [dimension: string]: Col | `${Col}.${string}` }
127
+ /**
128
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds on the table's rows, writes included:
129
+ * a grant of one of them at the node the path names, or above it, reaches the row for that action. Whoever inserts
130
+ * the path's column must hold every listed action at the node it names.
131
+ */
132
+ readonly writeThrough?: { readonly [dimension: string]: readonly A[] }
133
+ /**
134
+ * This table's own dimension, or one it reads through (`readThrough`) → the ancestor node a row reveals to its
135
+ * 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
136
+ * node in `to` too, while `when` admits the row.
137
+ */
138
+ readonly memberReveals?: { readonly [dimension: string]: MemberRevealsPolicy<Col, A> }
139
+ /**
140
+ * Relation → an access view that lists the rows the relation reaches: the escape path for a rule no structured
141
+ * declaration expresses. The view's SQL decides; the layer binds only the caller's principal and the nodes it holds
142
+ * the relation inside, never a handler value.
143
+ */
144
+ readonly access?: { readonly [relation: string]: AccessPolicy }
145
+ }
146
+
147
+ /** An access view: `row` names this table's key; `principal` is compared to the caller, `member` to the nodes it holds the relation inside. */
148
+ export interface AccessPolicy {
149
+ readonly view: string
150
+ readonly row: string
151
+ readonly principal?: string
152
+ readonly member?: string
153
+ }
154
+
155
+ /** What a row reveals to a caller with a grant at its node: its node in `to`, for `actions`, while `when` admits the row. */
156
+ export interface MemberRevealsPolicy<Col extends string, A extends string> {
157
+ readonly to: string
158
+ readonly actions: readonly A[]
159
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
160
+ readonly when?: ConditionPolicy<Col>
161
+ /** Through a path, on a table with an insert action: the writer picks the node, and `self` lets it pick its own. */
162
+ readonly assign?: { readonly self?: true }
163
+ }
164
+
165
+ /**
166
+ * A row of the table that a relation reaches reveals its node in `to`, an ancestor dimension of its chain: the relation
167
+ * then holds `actions` (those of them its roles list in `via`) there, while `when` admits the row.
168
+ */
169
+ export interface RevealsPolicy<Col extends string, A extends string> {
170
+ readonly to: string
171
+ readonly actions: readonly A[]
172
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
173
+ readonly when?: ConditionPolicy<Col>
174
+ /**
175
+ * Required on a reveal matched through `readThrough` of a table with an insert action: the row's writer picks the node,
176
+ * so an insert delegates. Without `self`, an insert that names a node where its writer holds the relation is refused.
177
+ */
178
+ readonly assign?: { readonly self?: true }
179
+ }
180
+
181
+ /**
182
+ * A relation source: each row says that the principal in `principal` stands in the relation to the node `node` holds,
183
+ * until `expires` (none: no deadline) and while `when` admits the row. Writing a row is delegation.
184
+ */
185
+ export interface ConfersPolicy<Col extends string> {
186
+ /**
187
+ * The column that holds the principal, or `<column>.<principal column>`: one foreign key of the table into the key of
188
+ * the table whose column holds it. The table's `createdBy` names the row's writer (it needs `assign.self`).
189
+ */
190
+ readonly principal: Col | `${Col}.${string}`
191
+ /** The column that names the node; by default the table's column for the relation's dimension (its key or its chain). */
192
+ readonly node?: Col
193
+ /** A timestamp column: the row confers nothing once it passed. */
194
+ readonly expires?: Col
195
+ /** A condition on the row's own columns (no foreign-key path): `{ revoked_at: { isNull: true } }`. */
196
+ readonly when?: ConditionPolicy<Col>
197
+ /**
198
+ * Inserting a row delegates the relation's actions to its principal, bounded by the inserting Ref's node: at most
199
+ * `maxDays` ahead (which needs `expires`), and to the inserting principal itself only with `self`.
200
+ */
201
+ readonly assign?: { readonly maxDays?: number; readonly self?: true }
94
202
  }
95
203
 
96
204
  /** A table's file columns: column → the name of a file kind of the contract (`c.files`). */
97
205
  export type FilePolicies<Col extends string> = { readonly [C in Col]?: string }
98
206
 
99
207
  /**
100
- * A column's own actions. `read`: only a capability of exactly that action reads, filters or sorts by the column;
208
+ * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
101
209
  * without one it falls back to the table's read action. `write`: only a capability of that action updates the column,
102
210
  * and the table's update action does not, so the column is not in `update`.
103
211
  */
104
212
  export type ColumnPolicies<Col extends string, A extends string> = { readonly [C in Col]?: ColumnPolicy<A> }
105
213
 
106
- /** A column's own read action, its own write action, or both. */
214
+ /** A column's own read actions (one, or a list as a table's read takes), its own write action, or both. */
107
215
  export interface ColumnPolicy<A extends string> {
108
- readonly read?: A
216
+ readonly read?: TableAction<A>
109
217
  readonly write?: A
110
218
  }
111
219
 
112
220
  /** 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 } }
221
+ export type ColumnReadPolicies<Col extends string, A extends string> = { readonly [C in Col]?: { readonly read: TableAction<A> } }
114
222
 
115
223
  export interface DimensionPolicy<Col extends string, A extends string, V extends Col = Col> extends WritablePolicy<Col, A, V, RecordActions<A>> {
116
224
  readonly scope: DimensionScope<Col>
@@ -123,7 +231,9 @@ export interface ChildPolicy<Table extends string, Col extends string, A extends
123
231
  }
124
232
 
125
233
  /** 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> {
234
+ export interface ApplicationPolicy<Col extends string, A extends string, V extends Col = Col>
235
+ extends WritablePolicy<Col, A, V, ApplicationActions<A>>
236
+ {
127
237
  readonly scope: ApplicationScope<Col>
128
238
  }
129
239
 
@@ -160,6 +270,17 @@ export interface TableColumns<Col extends string = string, Table extends string
160
270
  readonly dates?: readonly Col[]
161
271
  /** The `timestamp` and `timestamptz` columns, which a write takes as a `Date` or strict ISO 8601 text; absent when none. */
162
272
  readonly timestamps?: readonly Col[]
273
+ /** On SQLite, the columns declared `BOOLEAN`, stored as 0 or 1 and read as a boolean; absent when none. */
274
+ readonly booleans?: readonly Col[]
275
+ /** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
276
+ readonly json?: readonly Col[]
277
+ /**
278
+ * The columns declared NOT NULL; absent when none. A foreign key that holds a row's tenant needs its ancestor columns
279
+ * among them: under MATCH SIMPLE a null in one skips the whole key.
280
+ */
281
+ readonly notNull?: readonly Col[]
282
+ /** A view: read-only, with no foreign key; absent for a table. */
283
+ readonly view?: true
163
284
  }
164
285
 
165
286
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -176,9 +297,17 @@ export type ScopeModel =
176
297
  | { readonly mode: 'reference'; readonly reason: string }
177
298
  | { readonly mode: 'app'; readonly reason: string; readonly key: string }
178
299
 
179
- /** Each operation's actions: any one of them allows it. `read` names at least one; an empty list allows no operation. */
300
+ /**
301
+ * Each operation's actions: any one of them allows it. `read` names at least one, unless `readAny`; an empty list
302
+ * allows no operation.
303
+ */
180
304
  export interface ActionModel {
181
305
  readonly read: readonly string[]
306
+ /**
307
+ * An application table read with `'any'`: every `app` endpoint, job and webhook reads it, whatever its action; never a
308
+ * public procedure or a scoped site. `read` is empty then, and a `when` narrows only the writes of its action.
309
+ */
310
+ readonly readAny: boolean
182
311
  readonly insert: readonly string[]
183
312
  readonly update: readonly string[]
184
313
  readonly delete: readonly string[]
@@ -213,21 +342,145 @@ export interface TableModel {
213
342
  readonly queue: QueueModel | undefined
214
343
  /** The file columns, each with its file kind: a reference to `fabrika_files`, written only with a file reference. */
215
344
  readonly files: Readonly<Record<string, string>>
216
- /** The columns that declare their own read action, as declared (also those equal to the table's). */
217
- readonly columnReads: Readonly<Record<string, string>>
345
+ /** The columns that declare their own read actions, as declared (also those equal to the table's). */
346
+ readonly columnReads: Readonly<Record<string, readonly string[]>>
218
347
  /** The columns that declare their own write action: only a capability of it updates them. */
219
348
  readonly columnWrites: Readonly<Record<string, string>>
220
349
  /** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
221
350
  readonly dates: NameSet
222
351
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
223
352
  readonly timestamps: NameSet
353
+ /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
354
+ readonly booleans: NameSet
355
+ /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
356
+ readonly json: NameSet
357
+ /** The columns the column list declares NOT NULL. */
358
+ readonly notNull: NameSet
224
359
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
225
360
  readonly foreignKeys: readonly ForeignKey[]
361
+ /** A view: a child or reference table no operation but a read reaches, whose containment only its SQL states. */
362
+ readonly view: boolean
226
363
  /**
227
364
  * The containment links this table carries a column for, nearest first: a dimension table's container and
228
365
  * the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
229
366
  */
230
367
  readonly chain: readonly Container[]
368
+ /** The relations this table's rows confer, each with its columns, its condition and its delegation bound. */
369
+ readonly confers: readonly RelationSource[]
370
+ /** The condition each action of the table holds a row under; an action without one is not narrowed. */
371
+ readonly when: Readonly<Record<string, ConditionModel>>
372
+ /** Relation → action → the condition the rows that relation reaches hold for that action under; ANDed onto its terms only. */
373
+ readonly relationWhen: Readonly<Record<string, Readonly<Record<string, ConditionModel>>>>
374
+ /** The ancestor nodes this table's rows reveal to a relation of its own dimension or of one it reads through. */
375
+ readonly reveals: readonly RevealModel[]
376
+ /** The secondary read paths: a dimension outside the chain, by the column that holds the row's node in it. */
377
+ readonly readThrough: readonly SecondaryPath[]
378
+ /** The ancestor nodes this table's rows reveal to a grant at their own node. */
379
+ readonly memberReveals: readonly MemberRevealModel[]
380
+ /** The access views of the relations whose reach a view's SQL decides. */
381
+ readonly access: readonly AccessModel[]
382
+ }
383
+
384
+ /** A relation's access view over this table: `T.<key> in (select V.<row> from V where <bindings>)`. */
385
+ export interface AccessModel {
386
+ readonly relation: string
387
+ /** The relation's dimension: a hold inside a node of it alone binds `member`. */
388
+ readonly dimension: string
389
+ readonly view: string
390
+ readonly row: string
391
+ readonly principal: string | undefined
392
+ readonly member: string | undefined
393
+ }
394
+
395
+ /**
396
+ * A read path to a dimension outside the chain: `column` holds a key of `table`, which owns `dimension` and lies in
397
+ * `chain`. The column's foreign key covers every ancestor the two chains share, so the node lies in the row's own tenant.
398
+ */
399
+ export interface SecondaryPath {
400
+ readonly dimension: string
401
+ readonly column: string
402
+ readonly table: string
403
+ readonly key: string
404
+ readonly chain: readonly Container[]
405
+ /**
406
+ * The nearest container whose own path this is: the row's `column` of it, its `table` and `key`. `column` above is
407
+ * then the container's column, and the path is read as `T.<via column> in (select C.<key> from C where …)`.
408
+ */
409
+ readonly via: ContainerHop | undefined
410
+ /** The actions a `Ref` held through the path holds on the table's rows (`writeThrough`); a `Within` reads through every path. */
411
+ readonly writes: readonly string[]
412
+ }
413
+
414
+ /** The row's nearest containment column, and the table and key it names. */
415
+ export interface ContainerHop {
416
+ readonly column: string
417
+ readonly table: string
418
+ readonly key: string
419
+ }
420
+
421
+ /**
422
+ * A row of `table` that `relation` reaches reveals its node in `dimension`, held in `column`: the relation holds
423
+ * `actions` at that node while `when` admits the row.
424
+ */
425
+ export interface RevealModel {
426
+ readonly relation: string
427
+ readonly table: string
428
+ /** The table's key, which the relation's nodes match unless the reveal is matched through `path`. */
429
+ readonly key: string
430
+ /**
431
+ * The secondary path whose node, or an ancestor of it, the relation's nodes match. A reveal matched through one holds
432
+ * a `Ref` of an action only where the path does (`writeThrough`).
433
+ */
434
+ readonly path: SecondaryPath | undefined
435
+ /** The bound on an insert's delegation through `path`: `undefined` when no handler inserts a row of the table. */
436
+ readonly assign: { readonly self: boolean } | undefined
437
+ readonly dimension: string
438
+ readonly column: string
439
+ readonly actions: readonly string[]
440
+ readonly when: ConditionModel | undefined
441
+ }
442
+
443
+ /**
444
+ * A row of `table`, a node of `source` (its own dimension, keyed by `key`), reveals its node in `dimension`, held in
445
+ * `column`: a grant of one of `actions` at the row's node holds the action there too, for a `Within`'s reads, while
446
+ * `when` admits the row. Only a grant at the node itself counts, never one at a container of it: an insert would
447
+ * otherwise reveal the ancestor to the container's members at once.
448
+ */
449
+ export interface MemberRevealModel {
450
+ readonly source: string
451
+ readonly table: string
452
+ /** The column a grant's nodes match: the table's key, or `path`'s column. */
453
+ readonly key: string
454
+ /** The secondary path whose node a grant names; a `Ref` holds an action through it only where the path does. */
455
+ readonly path: SecondaryPath | undefined
456
+ /** The bound on an insert's pick of the node through `path`: `undefined` when no handler inserts a row of the table. */
457
+ readonly assign: { readonly self: boolean } | undefined
458
+ readonly dimension: string
459
+ readonly column: string
460
+ readonly actions: readonly string[]
461
+ readonly when: ConditionModel | undefined
462
+ }
463
+
464
+ /** One relation's source table: what a relation term reads, and what a write of its rows is bounded by. */
465
+ export interface RelationSource {
466
+ readonly relation: string
467
+ readonly dimension: string
468
+ readonly table: string
469
+ /** The source's column that decides the principal: it holds it, or it references the row of `principalPath` that does. */
470
+ readonly principal: string
471
+ readonly principalPath: PrincipalPath | undefined
472
+ readonly node: string
473
+ readonly expires: string | undefined
474
+ readonly when: ConditionModel | undefined
475
+ /** `undefined` when the table has no insert action, so no handler writes a row of it. */
476
+ readonly assign: { readonly maxDays: number | undefined; readonly self: boolean } | undefined
477
+ }
478
+
479
+ /** `S.<principal>` references `key` of `table`, whose `column` holds the principal the source row names. */
480
+ export interface PrincipalPath {
481
+ readonly table: string
482
+ readonly key: string
483
+ readonly column: string
231
484
  }
232
485
 
233
486
  /** A child's `column` and `inherit`, when omitted, are derived from its parent while the tables are linked. */
@@ -241,7 +494,21 @@ type ParsedScope =
241
494
  readonly inherit: readonly string[] | undefined
242
495
  }
243
496
 
244
- type ParsedTable = Omit<TableModel, 'chain' | 'scope'> & { readonly scope: ParsedScope }
497
+ type ParsedTable =
498
+ & Omit<TableModel, 'chain' | 'scope' | 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
499
+ & {
500
+ readonly scope: ParsedScope
501
+ readonly confersInput: unknown
502
+ readonly whenInput: unknown
503
+ readonly relationWhenInput: unknown
504
+ readonly revealsInput: unknown
505
+ readonly readThroughInput: unknown
506
+ readonly writeThroughInput: unknown
507
+ readonly memberRevealsInput: unknown
508
+ readonly accessInput: unknown
509
+ /** The stamped columns the policy did not name: a written table's `version` and `created_by` (`conventional`). */
510
+ readonly byConvention: NameSet
511
+ }
245
512
 
246
513
  let readModels: <DB, P>(tables: Tables<DB, P>) => TableModels
247
514
  let hasModels: (value: object) => boolean = () => false
@@ -297,7 +564,7 @@ export function defineTables<DB, P>(vocabularyInput: unknown, columns: unknown):
297
564
  /** `defineTables(vocabulary, columns)` answers the policies' builder, or names the fix for an untyped column list. */
298
565
  export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never]
299
566
  ? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'>
300
- : DefineVocabularyPolicies<ColumnTypes<C>, V>
567
+ : DefineVocabularyPolicies<ColumnTypes<C>, V, ColumnViews<C>>
301
568
 
302
569
  /**
303
570
  * The same policies read from values nobody type-checked: `src/db/tables.ts` and its vocabulary as the static reader
@@ -314,8 +581,13 @@ type Containment = Readonly<Record<string, { readonly container: string | undefi
314
581
  interface VocabularyModel {
315
582
  readonly dimensions: Containment
316
583
  readonly actions: NameSet
584
+ /** Each relation of the vocabulary, by name, with the dimension its nodes are of. */
585
+ readonly relations: Readonly<Record<string, string>>
317
586
  }
318
587
 
588
+ /** A relation's name: it travels in a token's pseudo-scope `~rel:<name>`, so it is a plain word. */
589
+ const RELATION_NAME = /^[a-z][A-Za-z0-9]*$/
590
+
319
591
  function parseVocabulary(input: unknown): VocabularyModel {
320
592
  const vocabulary = plainRecord(input, 'the vocabulary')
321
593
  const dimensions = plainRecord(ownEntry(vocabulary, 'dimensions'), 'the vocabulary dimensions')
@@ -339,12 +611,57 @@ function parseVocabulary(input: unknown): VocabularyModel {
339
611
  }
340
612
  }
341
613
  const actions = ownKeys(plainRecord(ownEntry(vocabulary, 'actions'), 'the vocabulary actions'))
342
- return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
614
+ if (includes(actions, READ_ANY)) {
615
+ throw new PolicyError(`the vocabulary may not declare the action '${READ_ANY}': a table's actions.read says '${READ_ANY}' for every action`)
616
+ }
617
+ const relationsInput = ownEntry(vocabulary, 'relations')
618
+ const relations: Record<string, string> = {}
619
+ if (relationsInput !== undefined) {
620
+ const declared = plainRecord(relationsInput, 'the vocabulary relations')
621
+ const relationNames = ownKeys(declared)
622
+ for (let index = 0; index < relationNames.length; index++) {
623
+ const relation = relationNames[index] ?? ''
624
+ if (!RELATION_NAME.test(relation)) {
625
+ throw new PolicyError(`the vocabulary relation ${relation}: a relation name must match ${RELATION_NAME.source}`)
626
+ }
627
+ const dimension = ownEntry(plainRecord(ownEntry(declared, relation), `the vocabulary relation ${relation}`), 'dimension')
628
+ if (typeof dimension !== 'string' || !hasOwn(dimensions, dimension)) {
629
+ throw new PolicyError(`the vocabulary relation ${relation} is of ${String(dimension)}, which is not one of its dimensions`)
630
+ }
631
+ setOwn(relations, relation, dimension)
632
+ }
633
+ }
634
+ return freeze({ dimensions: freeze(containment), actions: nameSet(actions), relations: freeze(relations) })
343
635
  }
344
636
 
345
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps'])
637
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'notNull', 'view'])
346
638
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
347
- const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
639
+ const POLICY_FIELDS = nameSet([
640
+ 'scope',
641
+ 'actions',
642
+ 'insert',
643
+ 'update',
644
+ 'version',
645
+ 'createdBy',
646
+ 'columns',
647
+ 'queue',
648
+ 'files',
649
+ 'confers',
650
+ 'when',
651
+ 'relationWhen',
652
+ 'reveals',
653
+ 'readThrough',
654
+ 'writeThrough',
655
+ 'memberReveals',
656
+ 'access',
657
+ ])
658
+ const REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
659
+ const MEMBER_REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
660
+ const REVEAL_ASSIGN_FIELDS = nameSet(['self'])
661
+ const CONFERS_FIELDS = nameSet(['principal', 'node', 'expires', 'when', 'assign'])
662
+ const ASSIGN_FIELDS = nameSet(['maxDays', 'self'])
663
+ /** A delegated row lasts at most ten years ahead: a bound, not a convenience. */
664
+ const MAX_ASSIGN_DAYS = 3650
348
665
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
349
666
  const ACTION_FIELDS = nameSet(['read', 'insert', 'update', 'delete', 'appRead', 'appCount'])
350
667
  const DIMENSION_FIELDS = nameSet(['dimension', 'key', 'in'])
@@ -354,25 +671,6 @@ const REFERENCE_FIELDS = nameSet(['reference'])
354
671
  const APPLICATION_FIELDS = nameSet(['app', 'key'])
355
672
  const COLUMN_FIELDS = nameSet(['read', 'write'])
356
673
 
357
- /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
358
- function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>> {
359
- const prototype: unknown = typeof value === 'object' && value !== null && !isArray(value) ? prototypeOf(value) : undefined
360
- if ((prototype !== OBJECT_PROTOTYPE && prototype !== null) || typeof value !== 'object' || value === null || ownSymbols(value).length > 0) {
361
- throw new PolicyError(`${what} must be a plain object`)
362
- }
363
- const copy: Record<string, unknown> = {}
364
- const keys = ownNames(value)
365
- for (let index = 0; index < keys.length; index++) {
366
- const key = keys[index] ?? ''
367
- const descriptor = ownDescriptor(value, key)
368
- if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
369
- throw new PolicyError(`${what}: ${key} is an accessor; a policy holds plain values`)
370
- }
371
- setOwn(copy, key, descriptor.value)
372
- }
373
- return freeze(copy)
374
- }
375
-
376
674
  /** Unknown keys are refused, not dropped: a misspelt `insrt` would otherwise leave the table without its column list. */
377
675
  function onlyFields(record: Readonly<Record<string, unknown>>, allowed: NameSet, what: string): void {
378
676
  const keys = ownKeys(record)
@@ -396,17 +694,41 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
396
694
  }
397
695
  }
398
696
  const parsed: ParsedTable[] = []
697
+ const views: Record<string, ViewColumns> = {}
399
698
  for (let index = 0; index < tables.length; index++) {
400
699
  const table = tables[index] ?? ''
401
700
  const policy = ownEntry(policies, table)
701
+ const entry = ownEntry(columns, table)
702
+ if (isViewEntry(table, entry)) {
703
+ const names = parseList(ownEntry(plainRecord(entry, `${table}: the column list entry`), 'columns'), (name) => String(name))
704
+ setOwn(views, table, freeze({ columns: nameSet(names ?? []), policy: policy !== undefined }))
705
+ }
706
+ // A view without a policy stays what it was before codegen read views: only ctx.sql reads it.
707
+ if (policy === undefined && isViewEntry(table, entry)) {
708
+ continue
709
+ }
402
710
  if (policy === undefined) {
403
711
  throw new PolicyError(`${table}: every table needs a policy in tables.ts`)
404
712
  }
405
- parsed[index] = parseTable(table, ownEntry(columns, table), policy, vocabulary)
713
+ parsed[parsed.length] = parseTable(table, entry, policy, vocabulary)
714
+ }
715
+ return linkTables(parsed, vocabulary, views)
716
+ }
717
+
718
+ /** Whether a column list entry marks a view: its `view` is `true`, or absent for a table. */
719
+ function isViewEntry(table: string, entry: unknown): boolean {
720
+ const view = ownEntry(plainRecord(entry, `${table}: the column list entry`), 'view')
721
+ if (view !== undefined && view !== true) {
722
+ throw new PolicyError(`${table}: the column list entry's view is true or absent`)
406
723
  }
407
- return linkTables(parsed, vocabulary.dimensions)
724
+ return view === true
408
725
  }
409
726
 
727
+ /** The version column of a written table whose policy names none, when the table has it. */
728
+ const VERSION_COLUMN = 'version'
729
+ /** The `createdBy` column of a written table whose policy names none, when the table has it. */
730
+ const CREATED_BY_COLUMN = 'created_by'
731
+
410
732
  /** How a policy names its columns: one it states must exist, and so must one a convention derives for it. */
411
733
  interface ColumnReader {
412
734
  readonly column: (name: unknown, field: string) => string
@@ -460,6 +782,14 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
460
782
  const scopeInput = plainRecord(ownEntry(policy, 'scope'), `${table}: scope`)
461
783
  const foreignKeys = parseForeignKeys(table, ownEntry(entry, 'foreignKeys'), column)
462
784
  const scope = parseScope(table, scopeInput, { column, columnsOf, derived }, vocabulary.dimensions)
785
+ const view = isViewEntry(table, entry)
786
+ if (view && scope.mode !== 'child' && scope.mode !== 'reference') {
787
+ throw new PolicyError(
788
+ `${table}: a view is read-only, so it takes a child scope, { child, key?, column?, inherit? }, or { reference }; ${
789
+ scope.mode === 'app' ? 'an application' : 'a dimension'
790
+ } table's rows are written`,
791
+ )
792
+ }
463
793
  const action = (value: unknown, field: string): string => {
464
794
  const name = nonEmpty(table, value, field)
465
795
  if (!inSet(vocabulary.actions, name)) {
@@ -472,12 +802,23 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
472
802
  const actions = parseActions(table, scopeInput, ownEntry(policy, 'actions'), action)
473
803
  const insert = nameSet(columnsOf(ownEntry(policy, 'insert'), 'insert'))
474
804
  const update = nameSet(columnsOf(ownEntry(policy, 'update'), 'update'))
805
+ const writable = !view && (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app')
806
+ // A written table's column named by the convention is stamped unless the policy names another (`NormalizedPolicies`).
807
+ const conventional = (name: string): string | undefined => (writable && inSet(columns, name) ? name : undefined)
475
808
  const versionInput = ownEntry(policy, 'version')
476
809
  const createdByInput = ownEntry(policy, 'createdBy')
477
- const version = versionInput === undefined ? undefined : column(versionInput, 'version')
478
- const createdBy = createdByInput === undefined ? undefined : column(createdByInput, 'createdBy')
810
+ const version = versionInput === undefined ? conventional(VERSION_COLUMN) : column(versionInput, 'version')
811
+ const createdBy = createdByInput === undefined ? conventional(CREATED_BY_COLUMN) : column(createdByInput, 'createdBy')
812
+ const unnamed: string[] = []
813
+ if (versionInput === undefined && version !== undefined) {
814
+ unnamed[unnamed.length] = version
815
+ }
816
+ if (createdByInput === undefined && createdBy !== undefined) {
817
+ unnamed[unnamed.length] = createdBy
818
+ }
819
+ const byConvention = nameSet(unnamed)
479
820
  const restricted: string[] = []
480
- const columnReads: Record<string, string> = {}
821
+ const columnReads: Record<string, readonly string[]> = {}
481
822
  const columnWrites: Record<string, string> = {}
482
823
  const columnsInput = ownEntry(policy, 'columns')
483
824
  const columnPolicies = columnsInput === undefined ? freeze({}) : plainRecord(columnsInput, `${table}: columns`)
@@ -492,13 +833,18 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
492
833
  throw new PolicyError(`${table}: columns.${name} declares no action; it takes read, write or both`)
493
834
  }
494
835
  if (readInput !== undefined) {
495
- const read = action(readInput, `columns.${name}.read`)
496
- setOwn(columnReads, name, read)
497
- // With several read actions, a column of one of them is hidden from the others.
498
- if (actions.read.length > 1 || !includes(actions.read, read)) {
836
+ const reads = isArray(readInput)
837
+ ? distinctActions(table, readInput, `columns.${name}.read`, action)
838
+ : freeze([action(readInput, `columns.${name}.read`)])
839
+ setOwn(columnReads, name, reads)
840
+ // Hidden from a table read action its list leaves out; `'any'` names none, so it hides it from every one.
841
+ if (actions.read.length === 0 || !everyIncluded(actions.read, reads)) {
499
842
  restricted[restricted.length] = name
500
843
  }
501
844
  }
845
+ if (writeInput !== undefined && view) {
846
+ throw new PolicyError(viewWrite(table))
847
+ }
502
848
  if (writeInput !== undefined) {
503
849
  setOwn(columnWrites, name, columnWrite(table, name, action(writeInput, `columns.${name}.write`), actions, update))
504
850
  }
@@ -510,20 +856,27 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
510
856
  throw new PolicyError(`${table}: the key ${scope.key} takes no action of its own`)
511
857
  }
512
858
  if (version !== undefined && hasOwn(columnPolicies, version)) {
513
- throw new PolicyError(`${table}: the version ${version} takes no action of its own`)
859
+ throw new PolicyError(`${table}: the version ${version} takes no action of its own${conventionOf(byConvention, version, 'version') ?? ''}`)
514
860
  }
515
- const writable = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app'
516
861
  const queueInput = ownEntry(policy, 'queue')
517
862
  const filesInput = ownEntry(policy, 'files')
863
+ // On a view, an empty insert or update list is refused too: it states a write the view never takes.
864
+ if (view && (hasOwn(policy, 'insert') || hasOwn(policy, 'update'))) {
865
+ throw new PolicyError(viewWrite(table))
866
+ }
518
867
  if (
519
868
  !writable
520
869
  && (namesOf(insert).length > 0 || namesOf(update).length > 0 || version !== undefined || createdBy !== undefined
521
- || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined)
870
+ || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined
871
+ || actions.insert.length > 0 || actions.update.length > 0 || actions.delete.length > 0)
522
872
  ) {
523
- throw new PolicyError(`${table}: a ${scope.mode} table is never written by a handler`)
873
+ throw new PolicyError(view ? viewWrite(table) : `${table}: a ${scope.mode} table is never written by a handler`)
524
874
  }
525
875
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
526
876
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
877
+ const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
878
+ const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
879
+ const notNull = parseColumnSet(table, ownEntry(entry, 'notNull'), column, 'notNull')
527
880
  const queue = queueInput === undefined
528
881
  ? undefined
529
882
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -551,7 +904,20 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
551
904
  columnWrites: freeze(columnWrites),
552
905
  dates,
553
906
  timestamps,
907
+ booleans,
908
+ json,
909
+ notNull,
554
910
  foreignKeys,
911
+ view,
912
+ confersInput: ownEntry(policy, 'confers'),
913
+ whenInput: ownEntry(policy, 'when'),
914
+ relationWhenInput: ownEntry(policy, 'relationWhen'),
915
+ revealsInput: ownEntry(policy, 'reveals'),
916
+ readThroughInput: ownEntry(policy, 'readThrough'),
917
+ writeThroughInput: ownEntry(policy, 'writeThrough'),
918
+ memberRevealsInput: ownEntry(policy, 'memberReveals'),
919
+ accessInput: ownEntry(policy, 'access'),
920
+ byConvention,
555
921
  }
556
922
  }
557
923
 
@@ -673,7 +1039,10 @@ function parseQueue(
673
1039
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
674
1040
  }
675
1041
 
676
- /** The column list's `date` (`dates`) or timestamp (`timestamps`) columns, each one of the table's. */
1042
+ /**
1043
+ * The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`), JSON (`json`) or NOT NULL
1044
+ * (`notNull`) columns, each one of the table's.
1045
+ */
677
1046
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
678
1047
  if (input === undefined) {
679
1048
  return nameSet([])
@@ -704,6 +1073,24 @@ export function updatableBy(model: TableModel, action: string): NameSet {
704
1073
  return nameSet(columns)
705
1074
  }
706
1075
 
1076
+ /**
1077
+ * The columns any of `actions` updates in `model`, as one role holding them: the union of `updatableBy` over them.
1078
+ * One action's set is `updatableBy`'s own.
1079
+ */
1080
+ export function updatableByAny(model: TableModel, actions: readonly string[]): NameSet {
1081
+ if (actions.length === 1) {
1082
+ return updatableBy(model, actions[0] ?? '')
1083
+ }
1084
+ const columns: string[] = []
1085
+ for (let index = 0; index < actions.length; index++) {
1086
+ const names = namesOf(updatableBy(model, actions[index] ?? ''))
1087
+ for (let position = 0; position < names.length; position++) {
1088
+ columns[columns.length] = names[position] ?? ''
1089
+ }
1090
+ }
1091
+ return nameSet(columns)
1092
+ }
1093
+
707
1094
  /** Whether the table names `action`: one of its table actions, or a column's own write action. */
708
1095
  export function namesAction(model: TableModel, action: string): boolean {
709
1096
  const { read, insert, update, delete: remove } = model.actions
@@ -720,22 +1107,77 @@ export function namesAction(model: TableModel, action: string): boolean {
720
1107
  }
721
1108
 
722
1109
  /**
723
- * The columns a capability of `action` reads: every one that declares no read action of its own, or exactly this
724
- * one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
1110
+ * The columns a capability of `action` reads: every one that declares no read action of its own, or one whose own
1111
+ * 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.
725
1112
  */
726
1113
  export function visibleFor(model: TableModel, action: string): readonly string[] {
1114
+ return visibleThrough(model, soleReach(action))
1115
+ }
1116
+
1117
+ /**
1118
+ * The actions whose reach one read answers: an `app` capability's held actions that admit the operation, each row
1119
+ * passing where one of them admits it (`conditionedAny`), and whether their `when` narrows the rows (`narrowed`), which
1120
+ * it does not in a table read with `'any'`.
1121
+ */
1122
+ export interface ReadReach {
1123
+ readonly actions: readonly string[]
1124
+ readonly narrowed: boolean
1125
+ }
1126
+
1127
+ /** The reach of a capability of one action, whose own condition narrows its rows. */
1128
+ export function soleReach(action: string): ReadReach {
1129
+ return freeze({ actions: freeze([action]), narrowed: true })
1130
+ }
1131
+
1132
+ /**
1133
+ * Whether every row a read of `reach` answers is a row `action` reads alone: it is one of the reaching actions, and either
1134
+ * 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
1135
+ * actions never put one action's column on another action's rows.
1136
+ */
1137
+ export function readsAsAction(model: TableModel, action: string, reach: ReadReach): boolean {
1138
+ if (!includes(reach.actions, action)) {
1139
+ return false
1140
+ }
1141
+ return !reach.narrowed || reach.actions.length === 1 || !hasOwn(model.when, action)
1142
+ }
1143
+
1144
+ /**
1145
+ * The columns a read of `reach` answers, the union of what each reaching action reads alone: every one that declares no
1146
+ * read action of its own, and one that does where that action reads every answered row (`readsAsAction`).
1147
+ */
1148
+ export function visibleThrough(model: TableModel, reach: ReadReach): readonly string[] {
727
1149
  const columns = namesOf(model.columns)
728
1150
  const visible: string[] = []
729
1151
  for (let index = 0; index < columns.length; index++) {
730
1152
  const name = columns[index] ?? ''
731
1153
  const declared = hasOwn(model.columnReads, name) ? model.columnReads[name] : undefined
732
- if (declared === undefined || declared === action) {
1154
+ if (declared === undefined || readsAsOneOf(model, declared, reach)) {
733
1155
  visible[visible.length] = name
734
1156
  }
735
1157
  }
736
1158
  return freeze(visible)
737
1159
  }
738
1160
 
1161
+ /** Whether one of a column's own read actions reads every row a read of `reach` answers (`readsAsAction`). */
1162
+ export function readsAsOneOf(model: TableModel, actions: readonly string[], reach: ReadReach): boolean {
1163
+ for (let index = 0; index < actions.length; index++) {
1164
+ if (readsAsAction(model, actions[index] ?? '', reach)) {
1165
+ return true
1166
+ }
1167
+ }
1168
+ return false
1169
+ }
1170
+
1171
+ /** Whether every one of `actions` is in `list`. */
1172
+ function everyIncluded(actions: readonly string[], list: readonly string[]): boolean {
1173
+ for (let index = 0; index < actions.length; index++) {
1174
+ if (!includes(list, actions[index] ?? '')) {
1175
+ return false
1176
+ }
1177
+ }
1178
+ return true
1179
+ }
1180
+
739
1181
  /** Every action that updates a column of `model`: its update action and each column's own write action. */
740
1182
  export function updateActions(model: TableModel): readonly string[] {
741
1183
  const actions: string[] = []
@@ -848,6 +1290,10 @@ function parseContainer(
848
1290
  return freeze({ dimension: container, column: columns.column(ownEntry(stated, 'column'), 'scope.in.column') })
849
1291
  }
850
1292
 
1293
+ function viewWrite(table: string): string {
1294
+ return `${table}: a view is never written by a handler, so its policy takes only actions.read, appRead, appCount and column read actions`
1295
+ }
1296
+
851
1297
  function parseActions(
852
1298
  table: string,
853
1299
  scope: Readonly<Record<string, unknown>>,
@@ -869,7 +1315,13 @@ function parseActions(
869
1315
  }
870
1316
  return distinctActions(table, value, `actions.${field}`, action)
871
1317
  }
872
- const read = operation('read')
1318
+ const readAny = ownEntry(actions, 'read') === READ_ANY
1319
+ if (readAny && !hasOwn(scope, 'app')) {
1320
+ throw new PolicyError(
1321
+ `${table}: actions.read 'any' is for an application table; a dimension, child or reference table names its read actions`,
1322
+ )
1323
+ }
1324
+ const read = readAny ? freeze([]) : operation('read')
873
1325
  const records = hasOwn(scope, 'dimension') || hasOwn(scope, 'child')
874
1326
  const kind = hasOwn(scope, 'app') ? 'an application table' : 'a reference table'
875
1327
  const reach = (field: 'appRead' | 'appCount'): readonly string[] => {
@@ -900,7 +1352,7 @@ function parseActions(
900
1352
  throw new PolicyError(`${table}: actions.appRead and actions.appCount both name ${name}`)
901
1353
  }
902
1354
  }
903
- return freeze({ read, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
1355
+ return freeze({ read, readAny, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
904
1356
  }
905
1357
 
906
1358
  /** A plain array of distinct actions of the vocabulary, at least one. */
@@ -934,6 +1386,8 @@ interface Stamp {
934
1386
  readonly role: string
935
1387
  /** An insert may set it: a queue row's first due time. */
936
1388
  readonly insertable?: true
1389
+ /** Why a column the policy may not have named is stamped: its name is the convention's. */
1390
+ readonly convention?: string
937
1391
  }
938
1392
 
939
1393
  /** The columns the layer writes itself: the key, every containment link, the version and the creator. */
@@ -949,10 +1403,10 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
949
1403
  }
950
1404
  }
951
1405
  if (table.version !== undefined) {
952
- stamps[stamps.length] = { column: table.version, role: 'the version' }
1406
+ stamps[stamps.length] = { column: table.version, role: 'the version', convention: conventionOf(table.byConvention, table.version, 'version') }
953
1407
  }
954
1408
  if (table.createdBy !== undefined) {
955
- stamps[stamps.length] = { column: table.createdBy, role: 'createdBy' }
1409
+ stamps[stamps.length] = { column: table.createdBy, role: 'createdBy', convention: conventionOf(table.byConvention, table.createdBy, 'createdBy') }
956
1410
  }
957
1411
  if (table.queue !== undefined) {
958
1412
  stamps[stamps.length] = { column: table.queue.attempts, role: 'queue.attempts' }
@@ -961,6 +1415,11 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
961
1415
  return stamps
962
1416
  }
963
1417
 
1418
+ /** Why a column the policy did not name is stamped, or nothing when the policy named it. */
1419
+ function conventionOf(byConvention: NameSet, column: string, field: string): string | undefined {
1420
+ return inSet(byConvention, column) ? ` (a written table's column named ${column} is its ${field} unless the policy names another)` : undefined
1421
+ }
1422
+
964
1423
  /**
965
1424
  * Each stamped column holds one role and is never written by a handler. A shared column would let one stamp
966
1425
  * overwrite another: `createdBy` on the key inserts the principal as the id, `version` on a container column
@@ -973,6 +1432,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
973
1432
  if (stamp === undefined) {
974
1433
  continue
975
1434
  }
1435
+ // Nothing writes a view, so its key may be its parent column; a predicate still compares each.
1436
+ if (table.view) {
1437
+ if (inSet(table.json, stamp.column)) {
1438
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which no predicate compares as ${stamp.role}; give it a scalar type`)
1439
+ }
1440
+ continue
1441
+ }
976
1442
  for (let other = 0; other < index; other++) {
977
1443
  const earlier = stamps[other]
978
1444
  if (earlier !== undefined && earlier.column === stamp.column) {
@@ -982,10 +1448,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
982
1448
  }
983
1449
  }
984
1450
  if ((stamp.insertable !== true && inSet(table.insert, stamp.column)) || inSet(table.update, stamp.column)) {
985
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update`)
1451
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update${stamp.convention ?? ''}`)
986
1452
  }
987
1453
  if (hasOwn(table.columnWrites, stamp.column)) {
988
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own`)
1454
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own${stamp.convention ?? ''}`)
1455
+ }
1456
+ if (inSet(table.json, stamp.column)) {
1457
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which the layer cannot stamp as ${stamp.role}; give it a scalar type`)
989
1458
  }
990
1459
  }
991
1460
  }
@@ -1012,7 +1481,8 @@ export function includes(names: readonly string[], name: unknown): boolean {
1012
1481
  }
1013
1482
 
1014
1483
  /** Resolves every table's containment chain and refuses a shape the layer cannot enforce. */
1015
- function linkTables(parsed: readonly ParsedTable[], containment: Containment): TableModels {
1484
+ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel, views: Readonly<Record<string, ViewColumns>>): TableModels {
1485
+ const containment = vocabulary.dimensions
1016
1486
  const byName: Record<string, ParsedTable> = {}
1017
1487
  const owners: Record<string, ParsedTable> = {}
1018
1488
  for (let index = 0; index < parsed.length; index++) {
@@ -1062,83 +1532,1345 @@ function linkTables(parsed: readonly ParsedTable[], containment: Containment): T
1062
1532
  return result
1063
1533
  }
1064
1534
 
1535
+ const conditionTable = (name: string): ConditionTable | undefined => ownEntry(byName, name)
1536
+ const linkedTable = (name: string): LinkedTable | undefined => {
1537
+ const target = ownEntry(byName, name)
1538
+ if (target === undefined) return undefined
1539
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, byConvention, ...rest } =
1540
+ target
1541
+ return { ...rest, ...resolve(target, []) }
1542
+ }
1543
+ const hopRule: HopRule = (from, column, to, key, backward) => {
1544
+ const source = ownEntry(byName, from)
1545
+ const target = ownEntry(byName, to)
1546
+ if (target?.scope.mode === 'reference') {
1547
+ return !backward
1548
+ }
1549
+ if (source === undefined || target === undefined) {
1550
+ return false
1551
+ }
1552
+ const into = resolve(target, [])
1553
+ // The hop reads the row its foreign key references, so that must be the row the rules below place: the one with the key.
1554
+ if ((into.scope.mode !== 'dimension' && into.scope.mode !== 'child') || into.scope.key !== key) {
1555
+ return false
1556
+ }
1557
+ const scope = resolve(source, []).scope
1558
+ // A view's parent row is read through its parent subquery, which scopes it; a table's through its covering key.
1559
+ const covered = (): boolean => {
1560
+ if (!source.view) requireNotNullAncestors(`${from}.${column}`, source, containmentPairs(column, key, into.chain))
1561
+ return true
1562
+ }
1563
+ // The container column must lead to the table that owns the container dimension, not to any table its key references.
1564
+ if (
1565
+ scope.mode === 'dimension' && scope.container !== undefined && scope.container.column === column && into.scope.mode === 'dimension'
1566
+ && into.scope.dimension === scope.container.dimension
1567
+ ) {
1568
+ return covered()
1569
+ }
1570
+ if (scope.mode === 'child' && scope.column === column && scope.parent === to) {
1571
+ return covered()
1572
+ }
1573
+ // Any other foreign key reaches a row of the same tenant only when it also holds every ancestor the two share.
1574
+ const pairs = tenantPairs(resolve(source, []), column, into.scope.key, into.chain)
1575
+ if (pairs.length < 2 || !holdsExactly(source.foreignKeys, to, pairs)) {
1576
+ return false
1577
+ }
1578
+ requireNotNullAncestors(`${from}.${column}`, source, pairs)
1579
+ return true
1580
+ }
1581
+ const sources: Record<string, string> = {}
1582
+ const viewed: Record<string, string> = {}
1065
1583
  const models: Record<string, TableModel> = {}
1066
1584
  for (let index = 0; index < parsed.length; index++) {
1067
1585
  const table = parsed[index]
1068
1586
  if (table !== undefined) {
1069
1587
  const { scope, chain } = resolve(table, [])
1070
- setOwn(models, table.name, freeze({ ...table, scope, chain }))
1588
+ const {
1589
+ confersInput,
1590
+ whenInput,
1591
+ relationWhenInput,
1592
+ revealsInput,
1593
+ readThroughInput,
1594
+ writeThroughInput,
1595
+ memberRevealsInput,
1596
+ accessInput,
1597
+ byConvention,
1598
+ ...rest
1599
+ } = table
1600
+ const linked = { ...rest, scope, chain }
1601
+ const ownerOf = (dimension: string): ResolvedOwner | undefined => {
1602
+ const owner = ownEntry(owners, dimension)
1603
+ return owner === undefined ? undefined : { name: owner.name, ...resolve(owner, []) }
1604
+ }
1605
+ // A container's own path, parsed from its own declaration; one through its container in turn is none.
1606
+ const containerPath = (container: string, dimension: string): SecondaryPath | undefined => {
1607
+ const declared = ownEntry(byName, container)?.readThroughInput
1608
+ const column = declared === undefined ? undefined : ownEntry(plainRecord(declared, `${container}: readThrough`), dimension)
1609
+ const target = linkedTable(container)
1610
+ if (target === undefined || typeof column !== 'string' || splitPath(column).length !== 1) return undefined
1611
+ return parseReadThrough(target, { [dimension]: column }, vocabulary, ownerOf, () => undefined)[0]
1612
+ }
1613
+ const readThrough = parseWriteThrough(
1614
+ linked,
1615
+ parseReadThrough(linked, readThroughInput, vocabulary, ownerOf, containerPath),
1616
+ writeThroughInput,
1617
+ vocabulary,
1618
+ )
1619
+ const confers = parseConfers(linked, confersInput, vocabulary.relations, conditionTable, linkedTable, hopRule)
1620
+ for (let position = 0; position < confers.length; position++) {
1621
+ const relation = confers[position]?.relation ?? ''
1622
+ const earlier = ownEntry(sources, relation)
1623
+ if (earlier !== undefined) {
1624
+ throw new PolicyError(`${table.name}: the relation ${relation} is already conferred by ${earlier}; a relation has one source table`)
1625
+ }
1626
+ setOwn(sources, relation, table.name)
1627
+ }
1628
+ const root = conditionRoot(linked, byName)
1629
+ const when = parseWhen(linked, root, whenInput, conditionTable, hopRule)
1630
+ const relationWhen = parseRelationWhen(linked, root, relationWhenInput, vocabulary, conditionTable, hopRule)
1631
+ const reveals = parseReveals(linked, readThrough, revealsInput, vocabulary, conditionTable, hopRule)
1632
+ const memberReveals = parseMemberReveals(linked, readThrough, memberRevealsInput, vocabulary, conditionTable, hopRule)
1633
+ const access = parseAccess(linked, accessInput, vocabulary, views)
1634
+ for (let position = 0; position < access.length; position++) {
1635
+ const relation = access[position]?.relation ?? ''
1636
+ if (!hasOwn(viewed, relation)) setOwn(viewed, relation, table.name)
1637
+ }
1638
+ setOwn(models, table.name, freeze({ ...linked, confers, when, relationWhen, reveals, readThrough, memberReveals, access }))
1639
+ }
1640
+ }
1641
+ checkRelationWhenReach(models, vocabulary)
1642
+ const relations = ownKeys(vocabulary.relations)
1643
+ for (let index = 0; index < relations.length; index++) {
1644
+ const relation = relations[index] ?? ''
1645
+ if (!hasOwn(sources, relation) && !hasOwn(viewed, relation)) {
1646
+ throw new PolicyError(
1647
+ `the vocabulary relation ${relation} has no source: declare confers.${relation} on the table whose rows hold it, or name an access view for it`,
1648
+ )
1071
1649
  }
1072
1650
  }
1651
+ checkRevealSources(models, sources)
1073
1652
  return freeze(models)
1074
1653
  }
1075
1654
 
1076
- /** A table's scope with nothing left to derive, and its containment chain. */
1077
- interface Resolved {
1078
- readonly scope: ScopeModel
1079
- readonly chain: readonly Container[]
1655
+ /** A reveal is matched through the relation's source rows, so a relation that access views alone serve reveals nothing. */
1656
+ function checkRevealSources(models: Readonly<Record<string, TableModel>>, sources: Readonly<Record<string, string>>): void {
1657
+ const tables = ownKeys(models)
1658
+ for (let index = 0; index < tables.length; index++) {
1659
+ const model = ownEntry(models, tables[index] ?? '')
1660
+ const reveals = model?.reveals ?? []
1661
+ for (let position = 0; position < reveals.length; position++) {
1662
+ const relation = reveals[position]?.relation ?? ''
1663
+ if (model !== undefined && !hasOwn(sources, relation)) {
1664
+ throw new PolicyError(
1665
+ `${model.name}: reveals.${relation} is matched through the rows that confer it, and only access views serve it; declare confers.${relation}`,
1666
+ )
1667
+ }
1668
+ }
1669
+ }
1080
1670
  }
1081
1671
 
1082
- function resolveChain(
1083
- table: ParsedTable,
1084
- byName: Readonly<Record<string, ParsedTable>>,
1085
- owners: Readonly<Record<string, ParsedTable>>,
1086
- containment: Containment,
1087
- chainOf: (table: ParsedTable) => readonly Container[],
1088
- ): Resolved {
1089
- /**
1090
- * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
1091
- * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
1092
- */
1093
- const above = (dimension: string): readonly Container[] => {
1094
- const owner = ownEntry(owners, dimension)
1095
- if (owner !== undefined) {
1096
- return chainOf(owner)
1672
+ type LinkedTable = Omit<TableModel, 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
1673
+
1674
+ /** A view of the column list: its columns, and whether a policy makes it a table of the layer. */
1675
+ interface ViewColumns {
1676
+ readonly columns: NameSet
1677
+ readonly policy: boolean
1678
+ }
1679
+
1680
+ const ACCESS_FIELDS = nameSet(['view', 'row', 'principal', 'member'])
1681
+
1682
+ /**
1683
+ * `access`: relation → the view whose rows name the table's rows the relation reaches. The view is one the column list
1684
+ * marks, `row` and each binding are its columns, and at least one binding is stated, so the subquery never reads every
1685
+ * row: `principal` is compared to the caller, `member` to the nodes of the relation's dimension it holds the relation in.
1686
+ */
1687
+ function parseAccess(
1688
+ table: LinkedTable,
1689
+ input: unknown,
1690
+ vocabulary: VocabularyModel,
1691
+ views: Readonly<Record<string, ViewColumns>>,
1692
+ ): readonly AccessModel[] {
1693
+ if (input === undefined) {
1694
+ return freeze([])
1695
+ }
1696
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1697
+ throw new PolicyError(`${table.name}: only a dimension or child table, or a child view, takes access; its rows are what a relation reaches`)
1698
+ }
1699
+ const declared = plainRecord(input, `${table.name}: access`)
1700
+ const relations = ownKeys(declared)
1701
+ const parsed: AccessModel[] = []
1702
+ for (let index = 0; index < relations.length; index++) {
1703
+ const relation = relations[index] ?? ''
1704
+ const what = `${table.name}: access.${relation}`
1705
+ if (!hasOwn(vocabulary.relations, relation)) {
1706
+ throw new PolicyError(`${what} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`)
1097
1707
  }
1098
- const container = ownEntry(containment, dimension)?.container
1099
- return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
1100
- }
1101
- const scope = table.scope
1102
- if (scope.mode === 'dimension') {
1103
- const container = scope.container
1104
- if (container === undefined) {
1105
- return { scope, chain: freeze([]) }
1708
+ const entry = plainRecord(ownEntry(declared, relation), what)
1709
+ onlyFields(entry, ACCESS_FIELDS, what)
1710
+ const view = ownEntry(entry, 'view')
1711
+ const named = typeof view === 'string' ? ownEntry(views, view) : undefined
1712
+ if (typeof view !== 'string' || named === undefined) {
1713
+ throw new PolicyError(`${what}.view names ${String(view)}, which the column list does not mark as a view`)
1106
1714
  }
1107
- const owner = ownEntry(owners, container.dimension)
1108
- if (owner !== undefined) {
1109
- requireReference(table, container, owner, (column) => `scope.in: { column: '${column}' }`)
1110
- requireCoveringKey(table, container, owner, chainOf(owner))
1715
+ // Read directly, the view would show the caller who else reaches which row.
1716
+ if (named.policy) {
1717
+ throw new PolicyError(`${what}.view names ${view}, which has a policy; an access view takes none, so only the relation's term reads it`)
1111
1718
  }
1112
- return { scope, chain: prepend(container, above(container.dimension)) }
1719
+ const columns = named.columns
1720
+ const viewColumn = (field: string, required: boolean): string | undefined => {
1721
+ const name = ownEntry(entry, field)
1722
+ if (name === undefined && !required) return undefined
1723
+ if (typeof name !== 'string' || !inSet(columns, name)) {
1724
+ throw new PolicyError(`${what}.${field} names ${String(name)}, which is not a column of ${view}`)
1725
+ }
1726
+ return name
1727
+ }
1728
+ const row = viewColumn('row', true) ?? ''
1729
+ const principal = viewColumn('principal', false)
1730
+ const member = viewColumn('member', false)
1731
+ if (principal === undefined && member === undefined) {
1732
+ throw new PolicyError(`${what} binds neither principal nor member: an access view is read for the caller, never whole`)
1733
+ }
1734
+ parsed[parsed.length] = freeze({ relation, dimension: ownEntry(vocabulary.relations, relation) ?? '', view, row, principal, member })
1113
1735
  }
1114
- if (scope.mode !== 'child') {
1115
- return { scope, chain: freeze([]) }
1736
+ return freeze(parsed)
1737
+ }
1738
+
1739
+ /** Every action a table names: its operations', `appRead`, `appCount` and its columns' own. */
1740
+ function tableActionNames(table: LinkedTable): NameSet {
1741
+ const names: string[] = []
1742
+ const lists = [table.actions.read, table.actions.insert, table.actions.update, table.actions.delete, table.actions.appRead, table.actions.appCount]
1743
+ for (let list = 0; list < lists.length; list++) {
1744
+ const actions = lists[list] ?? []
1745
+ for (let index = 0; index < actions.length; index++) {
1746
+ names[names.length] = actions[index] ?? ''
1747
+ }
1116
1748
  }
1117
- const parent = ownEntry(byName, scope.parent)
1118
- if (parent === undefined || parent.scope.mode !== 'dimension') {
1119
- throw new PolicyError(`${table.name}: the parent ${scope.parent} must be a dimension table`)
1749
+ const reads = ownKeys(table.columnReads)
1750
+ for (let index = 0; index < reads.length; index++) {
1751
+ const actions = ownEntry(table.columnReads, reads[index] ?? '') ?? []
1752
+ for (let position = 0; position < actions.length; position++) {
1753
+ names[names.length] = actions[position] ?? ''
1754
+ }
1120
1755
  }
1121
- const parentChain = chainOf(parent)
1122
- const expected: string[] = []
1123
- for (let index = 0; index < parentChain.length; index++) {
1124
- expected[index] = parentChain[index]?.column ?? ''
1756
+ const writes = ownKeys(table.columnWrites)
1757
+ for (let index = 0; index < writes.length; index++) {
1758
+ names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1125
1759
  }
1126
- const inherit = scope.inherit ?? freeze(expected)
1127
- const inherited = nameSet(inherit)
1128
- let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
1129
- for (let index = 0; index < expected.length; index++) {
1130
- matches = matches && inSet(inherited, expected[index])
1760
+ return nameSet(names)
1761
+ }
1762
+
1763
+ /** The actions that write a table: its insert, update and delete actions and its columns' own write actions. */
1764
+ function writeActionNames(table: LinkedTable): NameSet {
1765
+ const names: string[] = []
1766
+ const lists = [table.actions.insert, table.actions.update, table.actions.delete]
1767
+ for (let list = 0; list < lists.length; list++) {
1768
+ const actions = lists[list] ?? []
1769
+ for (let index = 0; index < actions.length; index++) {
1770
+ names[names.length] = actions[index] ?? ''
1771
+ }
1131
1772
  }
1132
- if (!matches) {
1133
- throw new PolicyError(
1134
- `${table.name}: must inherit exactly the containment columns of ${scope.parent} (${
1135
- expected.join(', ') || 'none'
1136
- }), so a composite foreign key keeps it in scope`,
1137
- )
1773
+ const writes = ownKeys(table.columnWrites)
1774
+ for (let index = 0; index < writes.length; index++) {
1775
+ names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1138
1776
  }
1139
- const dimension = parent.scope.dimension
1140
- const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
1141
- requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1777
+ return nameSet(names)
1778
+ }
1779
+
1780
+ /**
1781
+ * `when`: action → the condition a row must meet for it. An insert action's condition is judged on the inserted row and
1782
+ * the existing rows its paths reach (`insertProblem`); a reference table is read by every site and takes none.
1783
+ */
1784
+ function parseWhen(
1785
+ table: LinkedTable,
1786
+ root: ConditionTable,
1787
+ input: unknown,
1788
+ tables: (name: string) => ConditionTable | undefined,
1789
+ hops: HopRule,
1790
+ ): Readonly<Record<string, ConditionModel>> {
1791
+ if (input === undefined) {
1792
+ return freeze({})
1793
+ }
1794
+ if (table.scope.mode === 'reference') {
1795
+ throw new PolicyError(`${table.name}: a reference table takes no when; every site reads it`)
1796
+ }
1797
+ const declared = plainRecord(input, `${table.name}: when`)
1798
+ const named = tableActionNames(table)
1799
+ const actions = ownKeys(declared)
1800
+ const when: Record<string, ConditionModel> = {}
1801
+ for (let index = 0; index < actions.length; index++) {
1802
+ const action = actions[index] ?? ''
1803
+ if (!inSet(named, action)) {
1804
+ throw new PolicyError(`${table.name}: when.${action} names an action the table does not name (${namesOf(named).join(', ')})`)
1805
+ }
1806
+ if (table.actions.readAny && !inSet(writeActionNames(table), action)) {
1807
+ throw new PolicyError(
1808
+ `${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`,
1809
+ )
1810
+ }
1811
+ const what = `${table.name}: when.${action}`
1812
+ const condition = parseCondition(ownEntry(declared, action), root, tables, what, hops)
1813
+ // An insert reads the rows its foreign keys reach in its transaction, locked until the commit (`judgeInserted`).
1814
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1815
+ if (problem !== undefined) {
1816
+ throw new PolicyError(`${what}: ${problem}`)
1817
+ }
1818
+ setOwn(when, action, condition)
1819
+ }
1820
+ return freeze(when)
1821
+ }
1822
+
1823
+ /**
1824
+ * `relationWhen`: relation → action → a condition on the rows the relation reaches for the action, parsed as `when` is
1825
+ * (the same root, hop rule and insert rule). The relation must be the vocabulary's and the action the table's; whether
1826
+ * the relation reaches the table at all is checked once every table is parsed (`checkRelationWhenReach`).
1827
+ */
1828
+ function parseRelationWhen(
1829
+ table: LinkedTable,
1830
+ root: ConditionTable,
1831
+ input: unknown,
1832
+ vocabulary: VocabularyModel,
1833
+ tables: (name: string) => ConditionTable | undefined,
1834
+ hops: HopRule,
1835
+ ): Readonly<Record<string, Readonly<Record<string, ConditionModel>>>> {
1836
+ if (input === undefined) {
1837
+ return freeze({})
1838
+ }
1839
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1840
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table takes no relationWhen; no relation reaches its rows`)
1841
+ }
1842
+ const declared = plainRecord(input, `${table.name}: relationWhen`)
1843
+ const relations = ownKeys(declared)
1844
+ const named = tableActionNames(table)
1845
+ const parsed: Record<string, Readonly<Record<string, ConditionModel>>> = {}
1846
+ for (let index = 0; index < relations.length; index++) {
1847
+ const relation = relations[index] ?? ''
1848
+ if (!hasOwn(vocabulary.relations, relation)) {
1849
+ throw new PolicyError(
1850
+ `${table.name}: relationWhen.${relation} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`,
1851
+ )
1852
+ }
1853
+ const perAction = plainRecord(ownEntry(declared, relation), `${table.name}: relationWhen.${relation}`)
1854
+ const actions = ownKeys(perAction)
1855
+ if (actions.length === 0) {
1856
+ throw new PolicyError(`${table.name}: relationWhen.${relation} names no action`)
1857
+ }
1858
+ const conditions: Record<string, ConditionModel> = {}
1859
+ for (let position = 0; position < actions.length; position++) {
1860
+ const action = actions[position] ?? ''
1861
+ const what = `${table.name}: relationWhen.${relation}.${action}`
1862
+ if (!inSet(named, action)) {
1863
+ throw new PolicyError(`${what} names an action the table does not name (${namesOf(named).join(', ')})`)
1864
+ }
1865
+ const condition = parseCondition(ownEntry(perAction, action), root, tables, what, hops)
1866
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1867
+ if (problem !== undefined) {
1868
+ throw new PolicyError(`${what}: ${problem}`)
1869
+ }
1870
+ setOwn(conditions, action, condition)
1871
+ }
1872
+ setOwn(parsed, relation, freeze(conditions))
1873
+ }
1874
+ return freeze(parsed)
1875
+ }
1876
+
1877
+ /**
1878
+ * Every `relationWhen` names a relation that reaches the table for its action: the relation's dimension is the table's
1879
+ * or on its chain, a secondary path reaches it, or a reveal of the relation for the action reveals a node the table
1880
+ * lies at. A child view is reached through its parent row, so its parent is what the relation must reach.
1881
+ */
1882
+ function checkRelationWhenReach(models: Readonly<Record<string, TableModel>>, vocabulary: VocabularyModel): void {
1883
+ const names = ownKeys(models)
1884
+ const reveals: RevealModel[] = []
1885
+ for (let index = 0; index < names.length; index++) {
1886
+ const model = ownEntry(models, names[index] ?? '')
1887
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
1888
+ const reveal = model.reveals[position]
1889
+ if (reveal !== undefined) reveals[reveals.length] = reveal
1890
+ }
1891
+ }
1892
+ for (let index = 0; index < names.length; index++) {
1893
+ const model = ownEntry(models, names[index] ?? '')
1894
+ if (model === undefined) continue
1895
+ const reached = model.view && model.scope.mode === 'child' ? ownEntry(models, model.scope.parent) ?? model : model
1896
+ const relations = ownKeys(model.relationWhen)
1897
+ for (let position = 0; position < relations.length; position++) {
1898
+ const relation = relations[position] ?? ''
1899
+ const dimension = ownEntry(vocabulary.relations, relation) ?? ''
1900
+ const actions = ownKeys(ownEntry(model.relationWhen, relation) ?? {})
1901
+ for (let next = 0; next < actions.length; next++) {
1902
+ const action = actions[next] ?? ''
1903
+ if (!relationReaches(reached, relation, dimension, action, reveals)) {
1904
+ throw new PolicyError(
1905
+ `${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`,
1906
+ )
1907
+ }
1908
+ }
1909
+ }
1910
+ }
1911
+ }
1912
+
1913
+ /** Whether `relation` of `dimension` reaches a row of `model` for `action`, as the relation terms of the store find one. */
1914
+ function relationReaches(model: TableModel, relation: string, dimension: string, action: string, reveals: readonly RevealModel[]): boolean {
1915
+ if (nodeColumnOf(model, dimension) !== undefined || model.access.some((access) => access.relation === relation)) {
1916
+ return true
1917
+ }
1918
+ for (let index = 0; index < model.readThrough.length; index++) {
1919
+ const path = model.readThrough[index]
1920
+ if (path === undefined) continue
1921
+ if (path.dimension === dimension) return true
1922
+ for (let link = 0; link < path.chain.length; link++) {
1923
+ if (path.chain[link]?.dimension === dimension) return true
1924
+ }
1925
+ }
1926
+ for (let index = 0; index < reveals.length; index++) {
1927
+ const reveal = reveals[index]
1928
+ if (
1929
+ reveal !== undefined && reveal.relation === relation && includes(reveal.actions, action) && nodeColumnOf(model, reveal.dimension) !== undefined
1930
+ ) {
1931
+ return true
1932
+ }
1933
+ }
1934
+ return false
1935
+ }
1936
+
1937
+ /**
1938
+ * 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
1939
+ * column list declares, so a path follows it to the parent row, and the parent's own foreign keys from there.
1940
+ */
1941
+ function conditionRoot(table: LinkedTable, byName: Readonly<Record<string, ParsedTable>>): ConditionTable {
1942
+ const parent = table.view && table.scope.mode === 'child' ? ownEntry(byName, table.scope.parent) : undefined
1943
+ if (table.scope.mode !== 'child' || parent === undefined || parent.scope.mode !== 'dimension') {
1944
+ return table
1945
+ }
1946
+ const foreignKeys: ForeignKey[] = []
1947
+ for (let index = 0; index < table.foreignKeys.length; index++) {
1948
+ const key = table.foreignKeys[index]
1949
+ if (key !== undefined) foreignKeys[foreignKeys.length] = key
1950
+ }
1951
+ foreignKeys[foreignKeys.length] = freeze({ columns: freeze([table.scope.column]), table: parent.name, references: freeze([parent.scope.key]) })
1952
+ return freeze({ ...table, foreignKeys: freeze(foreignKeys) })
1953
+ }
1954
+
1955
+ /** A dimension's owning table, resolved: what a secondary path's column references. */
1956
+ interface ResolvedOwner extends Resolved {
1957
+ readonly name: string
1958
+ }
1959
+
1960
+ /**
1961
+ * `readThrough`: dimension → the column a `Within`'s read reaches a row through. The dimension lies outside the row's chain and a table
1962
+ * owns it; the column is a foreign key to that table's key that no update writes, and it covers every ancestor the two
1963
+ * chains share, so the database keeps the node in the row's own tenant. `<column>.<column>` reads the row through its
1964
+ * nearest container's own path instead (`containerPath`).
1965
+ */
1966
+ function parseReadThrough(
1967
+ table: LinkedTable,
1968
+ input: unknown,
1969
+ vocabulary: VocabularyModel,
1970
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1971
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1972
+ ): readonly SecondaryPath[] {
1973
+ if (input === undefined) {
1974
+ return freeze([])
1975
+ }
1976
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1977
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table has no containment, so no secondary read path`)
1978
+ }
1979
+ if (table.queue !== undefined) {
1980
+ throw new PolicyError(`${table.name}: a queue table has no secondary read path; a claim follows containment only`)
1981
+ }
1982
+ const declared = plainRecord(input, `${table.name}: readThrough`)
1983
+ const dimensions = ownKeys(declared)
1984
+ const paths: SecondaryPath[] = []
1985
+ for (let index = 0; index < dimensions.length; index++) {
1986
+ const dimension = dimensions[index] ?? ''
1987
+ const what = `${table.name}: readThrough.${dimension}`
1988
+ if (!hasOwn(vocabulary.dimensions, dimension)) {
1989
+ throw new PolicyError(`${what}: ${dimension} is not a dimension of the vocabulary`)
1990
+ }
1991
+ if (nodeColumnOf(table, dimension) !== undefined) {
1992
+ throw new PolicyError(`${what}: ${table.name} already lies in ${dimension}; a secondary path reaches a dimension outside its chain`)
1993
+ }
1994
+ const column = ownEntry(declared, dimension)
1995
+ const segments = typeof column === 'string' ? splitPath(column) : []
1996
+ if (segments.length === 2) {
1997
+ paths[paths.length] = throughContainer(table, segments[0] ?? '', segments[1] ?? '', dimension, ownerOf, containerPath, what)
1998
+ continue
1999
+ }
2000
+ if (typeof column !== 'string' || !inSet(table.columns, column)) {
2001
+ throw new PolicyError(`${what} names ${String(column)}, which is not a column of ${table.name}`)
2002
+ }
2003
+ if (inSet(table.update, column) || hasOwn(table.columnWrites, column) || hasOwn(table.files, column)) {
2004
+ throw new PolicyError(`${what}: ${column} places the row on a read path, so no update writes it`)
2005
+ }
2006
+ if (column === table.version || column === table.createdBy || column === table.scope.key) {
2007
+ throw new PolicyError(`${what}: ${column} is a column the layer writes itself, not a node of ${dimension}`)
2008
+ }
2009
+ for (let position = 0; position < table.chain.length; position++) {
2010
+ if (table.chain[position]?.column === column) {
2011
+ throw new PolicyError(`${what}: ${column} is a containment column of ${table.name}`)
2012
+ }
2013
+ }
2014
+ const owner = ownerOf(dimension)
2015
+ if (owner === undefined || owner.scope.mode !== 'dimension') {
2016
+ throw new PolicyError(`${what}: no table owns ${dimension}, so no foreign key ties ${column} to a node of it`)
2017
+ }
2018
+ const pairs = tenantPairs(table, column, owner.scope.key, owner.chain)
2019
+ const covered = holdsExactly(table.foreignKeys, owner.name, pairs)
2020
+ if (!covered) {
2021
+ const columns: string[] = []
2022
+ const referenced: string[] = []
2023
+ for (let position = 0; position < pairs.length; position++) {
2024
+ columns[position] = pairs[position]?.[0] ?? ''
2025
+ referenced[position] = pairs[position]?.[1] ?? ''
2026
+ }
2027
+ throw new PolicyError(
2028
+ `${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 (${
2029
+ columns.join(', ')
2030
+ }) references ${owner.name} (${referenced.join(', ')})`,
2031
+ )
2032
+ }
2033
+ requireNotNullAncestors(what, table, pairs)
2034
+ paths[paths.length] = freeze({ dimension, column, table: owner.name, key: owner.scope.key, chain: owner.chain, via: undefined, writes: freeze([]) })
2035
+ }
2036
+ return freeze(paths)
2037
+ }
2038
+
2039
+ /**
2040
+ * `readThrough.<dimension>: '<link>.<column>'`: the row is read through the path its nearest container declares for the
2041
+ * dimension. `<link>` is the row's nearest containment column, which places it in the container now, and `<column>` the
2042
+ * container's own path column, which no update of the container writes; so the read follows containment and the
2043
+ * container's path, and nothing the row's writer picks.
2044
+ */
2045
+ function throughContainer(
2046
+ table: LinkedTable,
2047
+ link: string,
2048
+ column: string,
2049
+ dimension: string,
2050
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
2051
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
2052
+ what: string,
2053
+ ): SecondaryPath {
2054
+ const nearest = table.chain[0]
2055
+ if (nearest === undefined || nearest.column !== link) {
2056
+ throw new PolicyError(
2057
+ `${what}: ${link} is not ${table.name}'s nearest containment column${
2058
+ nearest === undefined ? '' : ` (${nearest.column})`
2059
+ }; a path through a container starts at the row's own container`,
2060
+ )
2061
+ }
2062
+ const container = ownerOf(nearest.dimension)
2063
+ if (container === undefined || container.scope.mode !== 'dimension') {
2064
+ throw new PolicyError(`${what}: no table owns ${nearest.dimension}, so no container row holds a path to ${dimension}`)
2065
+ }
2066
+ const path = containerPath(container.name, dimension)
2067
+ if (path === undefined) {
2068
+ throw new PolicyError(
2069
+ `${what}: ${container.name} declares no readThrough.${dimension} through a column of its own, so ${table.name} has no container path to follow`,
2070
+ )
2071
+ }
2072
+ if (path.column !== column) {
2073
+ throw new PolicyError(`${what}: ${container.name} reads ${dimension} through ${path.column}, not ${column}`)
2074
+ }
2075
+ return freeze({ ...path, via: freeze({ column: link, table: container.name, key: container.scope.key }), writes: freeze([]) })
2076
+ }
2077
+
2078
+ /**
2079
+ * `writeThrough`: a dimension the table reads through → the actions a `Ref` held through that path holds. Each is an
2080
+ * action of the vocabulary: the table's own, or one a reveal matched through the path or a table below reaches the row
2081
+ * for. The path's column is the delegation: whoever inserts it must hold every listed action at the node it names, and
2082
+ * for a path through the container, whoever inserts the container's column (`pathWriters`).
2083
+ */
2084
+ function parseWriteThrough(
2085
+ table: LinkedTable,
2086
+ readThrough: readonly SecondaryPath[],
2087
+ input: unknown,
2088
+ vocabulary: VocabularyModel,
2089
+ ): readonly SecondaryPath[] {
2090
+ if (input === undefined) {
2091
+ return readThrough
2092
+ }
2093
+ const declared = plainRecord(input, `${table.name}: writeThrough`)
2094
+ const dimensions = ownKeys(declared)
2095
+ const writes: Record<string, readonly string[]> = {}
2096
+ for (let index = 0; index < dimensions.length; index++) {
2097
+ const dimension = dimensions[index] ?? ''
2098
+ const what = `${table.name}: writeThrough.${dimension}`
2099
+ let declaredPath = false
2100
+ for (let position = 0; position < readThrough.length; position++) {
2101
+ if (readThrough[position]?.dimension === dimension) declaredPath = true
2102
+ }
2103
+ if (!declaredPath) {
2104
+ throw new PolicyError(`${what}: ${table.name} reads no path to ${dimension}; declare readThrough.${dimension} first`)
2105
+ }
2106
+ const actions = parseList(ownEntry(declared, dimension), (action) => {
2107
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2108
+ throw new PolicyError(`${what} names ${String(action)}, which is not an action of the vocabulary`)
2109
+ }
2110
+ return action
2111
+ })
2112
+ if (actions === undefined) {
2113
+ throw new PolicyError(`${what} takes a plain array of the vocabulary's actions`)
2114
+ }
2115
+ const listed: string[] = []
2116
+ for (let position = 0; position < actions.length; position++) {
2117
+ const action = actions[position] ?? ''
2118
+ if (!includes(listed, action)) listed[listed.length] = action
2119
+ }
2120
+ if (listed.length === 0) {
2121
+ throw new PolicyError(`${what} names no action; leave the dimension out to hold nothing through the path`)
2122
+ }
2123
+ setOwn(writes, dimension, freeze(listed))
2124
+ }
2125
+ const paths: SecondaryPath[] = []
2126
+ for (let index = 0; index < readThrough.length; index++) {
2127
+ const path = readThrough[index]
2128
+ if (path === undefined) continue
2129
+ const listed = ownEntry(writes, path.dimension)
2130
+ paths[paths.length] = listed === undefined ? path : freeze({ ...path, writes: listed })
2131
+ }
2132
+ return freeze(paths)
2133
+ }
2134
+
2135
+ /**
2136
+ * `reveals`: relation → the ancestor its rows reveal. The relation is of the table's own dimension, so its term
2137
+ * 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
2138
+ * revealed node follows the row's containment now. A queue table reveals nothing: a claim rewrites its rows.
2139
+ */
2140
+ function parseReveals(
2141
+ table: LinkedTable,
2142
+ readThrough: readonly SecondaryPath[],
2143
+ input: unknown,
2144
+ vocabulary: VocabularyModel,
2145
+ tables: (name: string) => ConditionTable | undefined,
2146
+ hops: HopRule,
2147
+ ): readonly RevealModel[] {
2148
+ if (input === undefined) {
2149
+ return freeze([])
2150
+ }
2151
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2152
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table reveals nothing; its rows lie at no node a relation reaches`)
2153
+ }
2154
+ if (table.queue !== undefined) {
2155
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2156
+ }
2157
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2158
+ const key = table.scope.key
2159
+ const declared = plainRecord(input, `${table.name}: reveals`)
2160
+ const names = ownKeys(declared)
2161
+ const reveals: RevealModel[] = []
2162
+ for (let index = 0; index < names.length; index++) {
2163
+ const relation = names[index] ?? ''
2164
+ const what = `${table.name}: reveals.${relation}`
2165
+ const dimension = ownEntry(vocabulary.relations, relation)
2166
+ if (dimension === undefined) {
2167
+ throw new PolicyError(
2168
+ `${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(vocabulary.relations).join(', ') || 'none'})`,
2169
+ )
2170
+ }
2171
+ const paths: SecondaryPath[] = []
2172
+ for (let position = 0; dimension !== own && position < readThrough.length; position++) {
2173
+ const path = readThrough[position]
2174
+ if (path !== undefined && (path.dimension === dimension || containsLink(path.chain, dimension))) paths[paths.length] = path
2175
+ }
2176
+ if (dimension !== own && paths.length !== 1) {
2177
+ throw new PolicyError(
2178
+ paths.length === 0
2179
+ ? `${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`
2180
+ : `${what}: ${table.name} reads through more than one path to ${dimension}, so the reveal matches no one column`,
2181
+ )
2182
+ }
2183
+ const policy = plainRecord(ownEntry(declared, relation), what)
2184
+ onlyFields(policy, REVEALS_FIELDS, what)
2185
+ const { to, column, actions: listed, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2186
+ const path = paths[0]
2187
+ if (path?.via !== undefined) {
2188
+ // The relation's nodes would sit one subquery below the container's, past the guard's bound under a reveal.
2189
+ throw new PolicyError(
2190
+ `${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`,
2191
+ )
2192
+ }
2193
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2194
+ throw new PolicyError(
2195
+ `${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`,
2196
+ )
2197
+ }
2198
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2199
+ reveals[reveals.length] = freeze({ relation, table: table.name, key, path, assign, dimension: to, column, actions: listed, when })
2200
+ }
2201
+ return freeze(reveals)
2202
+ }
2203
+
2204
+ /** A reveal's `to`, a dimension of the table's chain with the column that holds it, its listed actions, and its `when`. */
2205
+ function parseRevealed(
2206
+ table: LinkedTable,
2207
+ policy: Readonly<Record<string, unknown>>,
2208
+ what: string,
2209
+ vocabulary: VocabularyModel,
2210
+ tables: (name: string) => ConditionTable | undefined,
2211
+ hops: HopRule,
2212
+ ): { readonly to: string; readonly column: string; readonly actions: readonly string[]; readonly when: ConditionModel | undefined } {
2213
+ const to = ownEntry(policy, 'to')
2214
+ let column: string | undefined
2215
+ for (let position = 0; position < table.chain.length; position++) {
2216
+ const link = table.chain[position]
2217
+ if (link !== undefined && link.dimension === to) column = link.column
2218
+ }
2219
+ if (typeof to !== 'string' || column === undefined) {
2220
+ const above: string[] = []
2221
+ for (let position = 0; position < table.chain.length; position++) {
2222
+ above[above.length] = table.chain[position]?.dimension ?? ''
2223
+ }
2224
+ throw new PolicyError(
2225
+ `${what}.to names ${String(to)}, which is not a dimension of ${table.name}'s chain (${above.join(', ') || 'none'})`,
2226
+ )
2227
+ }
2228
+ const actions = parseList(ownEntry(policy, 'actions'), (action) => {
2229
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2230
+ throw new PolicyError(`${what}.actions names ${String(action)}, which is not an action of the vocabulary`)
2231
+ }
2232
+ return action
2233
+ })
2234
+ if (actions === undefined) {
2235
+ throw new PolicyError(`${what}.actions takes a plain array of the vocabulary's actions`)
2236
+ }
2237
+ const listed: string[] = []
2238
+ for (let position = 0; position < actions.length; position++) {
2239
+ const action = actions[position] ?? ''
2240
+ if (!includes(listed, action)) listed[listed.length] = action
2241
+ }
2242
+ if (listed.length === 0) {
2243
+ throw new PolicyError(`${what}.actions names no action; a reveal holds the actions it lists, and no other`)
2244
+ }
2245
+ const whenInput = ownEntry(policy, 'when')
2246
+ const when = whenInput === undefined ? undefined : parseCondition(whenInput, table, tables, `${what}.when`, hops)
2247
+ return { to, column, actions: freeze(listed), when }
2248
+ }
2249
+
2250
+ /**
2251
+ * `memberReveals`: the table's own dimension, or one it reads through, → the ancestor its rows reveal to a grant at the
2252
+ * node. By its own key only a dimension table reveals so: the layer generates the key, so no writer picks a node someone
2253
+ * already holds a grant at. Through a direct path the writer picks it, so an insertable table states `assign`, and the
2254
+ * row reveals its nearest container only, whose column no move of an ancestor rewrites. A queue table's rows move on
2255
+ * every claim.
2256
+ */
2257
+ function parseMemberReveals(
2258
+ table: LinkedTable,
2259
+ readThrough: readonly SecondaryPath[],
2260
+ input: unknown,
2261
+ vocabulary: VocabularyModel,
2262
+ tables: (name: string) => ConditionTable | undefined,
2263
+ hops: HopRule,
2264
+ ): readonly MemberRevealModel[] {
2265
+ if (input === undefined) {
2266
+ return freeze([])
2267
+ }
2268
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2269
+ throw new PolicyError(
2270
+ `${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`,
2271
+ )
2272
+ }
2273
+ if (table.queue !== undefined) {
2274
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2275
+ }
2276
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2277
+ const declared = plainRecord(input, `${table.name}: memberReveals`)
2278
+ const names = ownKeys(declared)
2279
+ const reveals: MemberRevealModel[] = []
2280
+ for (let index = 0; index < names.length; index++) {
2281
+ const source = names[index] ?? ''
2282
+ const what = `${table.name}: memberReveals.${source}`
2283
+ let path: SecondaryPath | undefined
2284
+ for (let position = 0; source !== own && position < readThrough.length; position++) {
2285
+ if (readThrough[position]?.dimension === source) path = readThrough[position]
2286
+ }
2287
+ if (source !== own && path === undefined) {
2288
+ throw new PolicyError(
2289
+ `${what}: ${source} is neither the own dimension of ${table.name} (${
2290
+ own ?? 'none'
2291
+ }) nor one it reads through; a row reveals to a grant at its own node or at the node its path names`,
2292
+ )
2293
+ }
2294
+ const policy = plainRecord(ownEntry(declared, source), what)
2295
+ onlyFields(policy, MEMBER_REVEALS_FIELDS, what)
2296
+ const { to, column, actions, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2297
+ if (path?.via !== undefined) {
2298
+ throw new PolicyError(
2299
+ `${what}: ${table.name} reads ${source} through its container ${path.via.table}; declare the member reveal on ${path.via.table}`,
2300
+ )
2301
+ }
2302
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2303
+ throw new PolicyError(
2304
+ `${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`,
2305
+ )
2306
+ }
2307
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2308
+ const key = path === undefined ? table.scope.key : path.column
2309
+ reveals[reveals.length] = freeze({ source, table: table.name, key, path, assign, dimension: to, column, actions, when })
2310
+ }
2311
+ return freeze(reveals)
2312
+ }
2313
+
2314
+ /**
2315
+ * A reveal matched through a secondary path delegates on insert, since the row's writer picks the node: a table with an
2316
+ * insert action states the bound, as a relation source does. A reveal by the row's own key delegates nothing.
2317
+ */
2318
+ function parseRevealAssign(table: LinkedTable, path: SecondaryPath | undefined, input: unknown, what: string): RevealModel['assign'] {
2319
+ if (path === undefined || table.actions.insert.length === 0) {
2320
+ if (input !== undefined) {
2321
+ throw new PolicyError(
2322
+ path === undefined
2323
+ ? `${what}.assign: the reveal matches the row's own key, so no writer picks its node`
2324
+ : `${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`,
2325
+ )
2326
+ }
2327
+ return undefined
2328
+ }
2329
+ if (input === undefined) {
2330
+ throw new PolicyError(
2331
+ `${what}: inserting a row of ${table.name} (${
2332
+ table.actions.insert.join(', ')
2333
+ }) picks the ${path.dimension} node the reveal holds at; state assign: { self? }`,
2334
+ )
2335
+ }
2336
+ const assign = plainRecord(input, `${what}.assign`)
2337
+ onlyFields(assign, REVEAL_ASSIGN_FIELDS, `${what}.assign`)
2338
+ const self = ownEntry(assign, 'self')
2339
+ if (self !== undefined && self !== true) {
2340
+ throw new PolicyError(`${what}.assign.self takes true`)
2341
+ }
2342
+ return freeze({ self: self === true })
2343
+ }
2344
+
2345
+ /**
2346
+ * A row of the table hands out access that its writer places: it confers a relation, reveals through a path, or reveals
2347
+ * its ancestor to the grants at its node. Such a row is written only through the handles, and never moves.
2348
+ */
2349
+ export function delegates(model: TableModel): boolean {
2350
+ for (let index = 0; index < model.reveals.length; index++) {
2351
+ if (model.reveals[index]?.path !== undefined) return true
2352
+ }
2353
+ return model.confers.length > 0 || model.memberReveals.length > 0
2354
+ }
2355
+
2356
+ /**
2357
+ * The tables whose rows hand out access, which no raw statement writes, lowercased as the tag compares names: a relation
2358
+ * source, a path reveal or a path column that holds actions (`writeThrough`), whose writer the layer bounds; a
2359
+ * member-revealing table, whose key the layer generates so no write revives a node a stale grant still names; and the
2360
+ * tables a principal path or a relation's condition reads, whose columns decide whom a source row names and what it
2361
+ * confers.
2362
+ */
2363
+ export function accessTablesOf(models: TableModels): readonly string[] {
2364
+ const tables: string[] = []
2365
+ const names = ownKeys(models)
2366
+ for (let index = 0; index < names.length; index++) {
2367
+ const model = modelOf(models, names[index] ?? '')
2368
+ if (model !== undefined && (delegates(model) || pathWriters(models, model).length > 0)) {
2369
+ tables[tables.length] = model.name.toLowerCase()
2370
+ }
2371
+ for (let position = 0; model !== undefined && position < model.confers.length; position++) {
2372
+ const source = model.confers[position]
2373
+ const path = source?.principalPath
2374
+ if (path !== undefined) tables[tables.length] = path.table.toLowerCase()
2375
+ if (source?.when !== undefined) {
2376
+ conditionReach(source.when, (table) => {
2377
+ tables[tables.length] = table.toLowerCase()
2378
+ })
2379
+ }
2380
+ }
2381
+ }
2382
+ return tables
2383
+ }
2384
+
2385
+ /** A path column whose insert hands out the listed actions at the node it names: the bound its writer is held to. */
2386
+ export interface PathWriter {
2387
+ readonly path: SecondaryPath
2388
+ /** The path's own `writes` and those of every table that reads the same dimension through this table's column. */
2389
+ readonly actions: readonly string[]
2390
+ }
2391
+
2392
+ /**
2393
+ * The columns of `model` whose insert hands out actions through a secondary path: its own paths that hold actions, and
2394
+ * its paths that a table below follows through it (`'<link>.<column>'`) with actions of its own. Such a table is written
2395
+ * only through the handles, so no write sets the column past the bound.
2396
+ */
2397
+ export function pathWriters(models: Readonly<Record<string, TableModel>>, model: TableModel): readonly PathWriter[] {
2398
+ const writers: PathWriter[] = []
2399
+ const names = ownKeys(models)
2400
+ for (let index = 0; index < model.readThrough.length; index++) {
2401
+ const path = model.readThrough[index]
2402
+ if (path === undefined || path.via !== undefined) continue
2403
+ const actions: string[] = []
2404
+ for (let position = 0; position < path.writes.length; position++) {
2405
+ const action = path.writes[position] ?? ''
2406
+ if (!includes(actions, action)) actions[actions.length] = action
2407
+ }
2408
+ for (let position = 0; position < names.length; position++) {
2409
+ const below = ownEntry(models, names[position] ?? '')
2410
+ for (let at = 0; below !== undefined && at < below.readThrough.length; at++) {
2411
+ const through = below.readThrough[at]
2412
+ if (through?.via?.table !== model.name || through.dimension !== path.dimension) continue
2413
+ for (let written = 0; written < through.writes.length; written++) {
2414
+ const action = through.writes[written] ?? ''
2415
+ if (!includes(actions, action)) actions[actions.length] = action
2416
+ }
2417
+ }
2418
+ }
2419
+ if (actions.length > 0) writers[writers.length] = freeze({ path, actions: freeze(actions) })
2420
+ }
2421
+ return freeze(writers)
2422
+ }
2423
+
2424
+ function containsLink(chain: readonly Container[], dimension: string): boolean {
2425
+ for (let index = 0; index < chain.length; index++) {
2426
+ if (chain[index]?.dimension === dimension) return true
2427
+ }
2428
+ return false
2429
+ }
2430
+
2431
+ /** The column of `table` that places a row at a node of `dimension`: its key for its own dimension, else a chain link. */
2432
+ export function nodeColumnOf(table: Pick<TableModel, 'scope' | 'chain'>, dimension: string): string | undefined {
2433
+ if (table.scope.mode === 'dimension' && table.scope.dimension === dimension) {
2434
+ return table.scope.key
2435
+ }
2436
+ for (let index = 0; index < table.chain.length; index++) {
2437
+ const link = table.chain[index]
2438
+ if (link?.dimension === dimension) {
2439
+ return link.column
2440
+ }
2441
+ }
2442
+ return undefined
2443
+ }
2444
+
2445
+ /**
2446
+ * `confers`: relation → its columns on this table. The node is the table's own column for the relation's dimension,
2447
+ * which the layer stamps from the inserting Ref, so a row names only a node its writer acts on. The principal, the
2448
+ * node, the expiry and the condition's columns are never updated: a row that confers more is a new row, which its
2449
+ * insert action bounds (`assign`).
2450
+ */
2451
+ function parseConfers(
2452
+ table: LinkedTable,
2453
+ input: unknown,
2454
+ relations: Readonly<Record<string, string>>,
2455
+ tables: (name: string) => ConditionTable | undefined,
2456
+ linked: (name: string) => LinkedTable | undefined,
2457
+ hops: HopRule,
2458
+ ): readonly RelationSource[] {
2459
+ if (input === undefined) {
2460
+ return freeze([])
2461
+ }
2462
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2463
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table confers no relation; its rows lie at no node`)
2464
+ }
2465
+ if (table.view) {
2466
+ throw new PolicyError(
2467
+ `${table.name}: a view confers no relation; its rows change with every write to the tables it reads, which no delegation bound sees`,
2468
+ )
2469
+ }
2470
+ if (table.queue !== undefined) {
2471
+ // A claim, a requeue and `done: true` rewrite `due` and `version` past every update-column check.
2472
+ throw new PolicyError(`${table.name}: a queue table confers no relation; the layer rewrites its rows on every claim`)
2473
+ }
2474
+ const declared = plainRecord(input, `${table.name}: confers`)
2475
+ const names = ownKeys(declared)
2476
+ const sources: RelationSource[] = []
2477
+ for (let index = 0; index < names.length; index++) {
2478
+ const relation = names[index] ?? ''
2479
+ const what = `${table.name}: confers.${relation}`
2480
+ const dimension = ownEntry(relations, relation)
2481
+ if (dimension === undefined) {
2482
+ throw new PolicyError(`${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(relations).join(', ') || 'none'})`)
2483
+ }
2484
+ const policy = plainRecord(ownEntry(declared, relation), what)
2485
+ onlyFields(policy, CONFERS_FIELDS, what)
2486
+ const column = (value: unknown, field: string): string => {
2487
+ if (!inSet(table.columns, value)) {
2488
+ throw new PolicyError(`${what}.${field} names ${String(value)}, which is not a column of ${table.name}`)
2489
+ }
2490
+ return value
2491
+ }
2492
+ const { column: principal, path: principalPath } = parsePrincipal(table, ownEntry(policy, 'principal'), linked, what)
2493
+ const placed = nodeColumnOf(table, dimension)
2494
+ if (placed === undefined) {
2495
+ throw new PolicyError(`${what}: ${table.name} does not lie in ${dimension}, the relation's dimension, so its rows name no node of it`)
2496
+ }
2497
+ const own = table.scope.mode === 'dimension' && table.scope.dimension === dimension
2498
+ if (!own && table.chain[0]?.column !== placed) {
2499
+ // An inherited column follows a move of an ancestor (ON UPDATE CASCADE), which no delegation bound sees.
2500
+ throw new PolicyError(
2501
+ `${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`,
2502
+ )
2503
+ }
2504
+ const nodeInput = ownEntry(policy, 'node')
2505
+ const node = nodeInput === undefined ? placed : column(nodeInput, 'node')
2506
+ if (node !== placed) {
2507
+ throw new PolicyError(`${what}.node is ${node}, but a row's ${dimension} is ${placed}: the node is the column the inserting Ref stamps`)
2508
+ }
2509
+ const expiresInput = ownEntry(policy, 'expires')
2510
+ const expires = expiresInput === undefined ? undefined : column(expiresInput, 'expires')
2511
+ if (expires !== undefined && !inSet(table.timestamps, expires)) {
2512
+ throw new PolicyError(`${what}.expires names ${expires}, which is not a timestamp column`)
2513
+ }
2514
+ const whenInput = ownEntry(policy, 'when')
2515
+ const when = whenInput === undefined ? undefined : parseSourceWhen(table, whenInput, tables, linked, hops, `${what}.when`)
2516
+ const fixed: string[] = [principal]
2517
+ if (expires !== undefined) fixed[fixed.length] = expires
2518
+ const read = when === undefined ? [] : conditionColumns(when)
2519
+ for (let position = 0; position < read.length; position++) {
2520
+ fixed[fixed.length] = read[position] ?? ''
2521
+ }
2522
+ for (let position = 0; position < fixed.length; position++) {
2523
+ const name = fixed[position] ?? ''
2524
+ if (name === table.version) {
2525
+ throw new PolicyError(`${what}: ${name} is the version column, which every update rewrites; it decides nothing a row confers`)
2526
+ }
2527
+ if (inSet(table.update, name) || hasOwn(table.columnWrites, name)) {
2528
+ throw new PolicyError(`${what}: ${name} decides what a row confers, so no update writes it; replace the row instead`)
2529
+ }
2530
+ }
2531
+ if (principal === node || principal === table.version || hasOwn(table.files, principal)) {
2532
+ throw new PolicyError(`${what}.principal ${principal} is a column the layer stamps; it holds the principal the row names`)
2533
+ }
2534
+ if (principalPath === undefined) refuseReferencing(table, principal, `${what}.principal`, 'holds the principal', undefined)
2535
+ const assign = parseAssign(table, policy, expires, what)
2536
+ if (principal === table.createdBy && principalPath !== undefined) {
2537
+ throw new PolicyError(`${what}.principal ${principal} is the createdBy column, which holds a principal; a principal path starts at a foreign key`)
2538
+ }
2539
+ // The layer stamps createdBy with the writer, so every row such a source confers names its writer.
2540
+ if (principal === table.createdBy && assign !== undefined && !assign.self) {
2541
+ throw new PolicyError(
2542
+ `${what}.principal ${principal} is the createdBy column, so every inserted row names its writer: state assign: { self: true }`,
2543
+ )
2544
+ }
2545
+ sources[sources.length] = freeze({ relation, dimension, table: table.name, principal, principalPath, node, expires, when, assign })
2546
+ }
2547
+ return freeze(sources)
2548
+ }
2549
+
2550
+ /**
2551
+ * `confers.<relation>.when`: a condition on the source row, which may follow one foreign key to the row it names (the far
2552
+ * side of a many-to-many source). What it reads decides whom the relation reaches, so it is held as the principal is:
2553
+ * no update writes it, on the source or on the far row, and nothing a write elsewhere cascades rewrites it.
2554
+ */
2555
+ function parseSourceWhen(
2556
+ table: LinkedTable,
2557
+ input: unknown,
2558
+ tables: (name: string) => ConditionTable | undefined,
2559
+ linked: (name: string) => LinkedTable | undefined,
2560
+ hops: HopRule,
2561
+ what: string,
2562
+ ): ConditionModel {
2563
+ const condition = parseCondition(input, table, tables, what, hops)
2564
+ const visit = (node: ConditionModel): void => {
2565
+ if (node.kind === 'not') {
2566
+ visit(node.term)
2567
+ } else if (node.kind === 'some') {
2568
+ // Every writer of the naming table adds and removes such rows; no rule holds a set of rows still.
2569
+ throw new PolicyError(
2570
+ `${what}: a relation's condition takes no some or none: the rows naming a source row are written outside its delegation bound`,
2571
+ )
2572
+ } else if (node.kind === 'test') {
2573
+ const hop = node.hops[0]
2574
+ if (node.hops.length > 1) {
2575
+ // The far row is read inside every relation term, beside a principal path, four subqueries deep under a reveal.
2576
+ throw new PolicyError(`${what}: a relation's condition follows at most one foreign key, to the row the source row names`)
2577
+ }
2578
+ if (hop !== undefined) farColumn(table, hop, node.column, linked, what)
2579
+ } else {
2580
+ for (let index = 0; index < node.terms.length; index++) {
2581
+ const term = node.terms[index]
2582
+ if (term !== undefined) visit(term)
2583
+ }
2584
+ }
2585
+ }
2586
+ visit(condition)
2587
+ return condition
2588
+ }
2589
+
2590
+ /** The column a relation's condition tests on the row one foreign key of the source names: fixed like a principal. */
2591
+ function farColumn(
2592
+ table: LinkedTable,
2593
+ hop: ConditionHop,
2594
+ held: string,
2595
+ linked: (name: string) => LinkedTable | undefined,
2596
+ what: string,
2597
+ ): void {
2598
+ refuseReferencing(table, hop.column, what, "starts the condition's path", hop)
2599
+ const target = linked(hop.table)
2600
+ if (target === undefined) {
2601
+ throw new PolicyError(`${what}: ${table.name}.${hop.column} references ${hop.table}, which has no policy`)
2602
+ }
2603
+ if (target.view) {
2604
+ throw new PolicyError(`${what}: ${hop.table} is a view, whose rows change with every write to the tables it reads`)
2605
+ }
2606
+ if (target.queue !== undefined) {
2607
+ throw new PolicyError(`${what}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2608
+ }
2609
+ const scope = target.scope
2610
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2611
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2612
+ throw new PolicyError(
2613
+ `${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`,
2614
+ )
2615
+ }
2616
+ if (scope.mode !== 'reference') {
2617
+ refuseReferencing(target, scope.key, what, "is the key the condition's path follows", undefined)
2618
+ }
2619
+ if (held === target.version) {
2620
+ throw new PolicyError(`${what}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2621
+ }
2622
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2623
+ throw new PolicyError(`${what}: ${hop.table}.${held} decides what a row confers, so no update of ${hop.table} writes it; replace the row instead`)
2624
+ }
2625
+ if (chainColumn(target, held)) {
2626
+ throw new PolicyError(`${what}: ${hop.table}.${held} is a containment column, which a move rewrites; it decides nothing a row confers`)
2627
+ }
2628
+ refuseReferencing(target, held, what, 'decides what a row confers', undefined)
2629
+ }
2630
+
2631
+ /**
2632
+ * `confers.<relation>.principal`: a column of the source, or `<column>.<principal column>`, one single-column foreign key
2633
+ * of the source into the key of a table P whose column holds the principal. Every column that decides the principal is
2634
+ * one no update writes, on P as on the source, so a row names someone else only as a new row its insert bounds.
2635
+ */
2636
+ function parsePrincipal(
2637
+ table: LinkedTable,
2638
+ input: unknown,
2639
+ linked: (name: string) => LinkedTable | undefined,
2640
+ what: string,
2641
+ ): { readonly column: string; readonly path: PrincipalPath | undefined } {
2642
+ const field = `${what}.principal`
2643
+ if (typeof input !== 'string') {
2644
+ throw new PolicyError(`${field} names ${String(input)}, which is not a column of ${table.name}`)
2645
+ }
2646
+ const segments = splitPath(input)
2647
+ if (segments.length === 1) {
2648
+ if (!inSet(table.columns, input)) {
2649
+ throw new PolicyError(`${field} names ${input}, which is not a column of ${table.name}`)
2650
+ }
2651
+ return { column: input, path: undefined }
2652
+ }
2653
+ if (segments.length !== 2) {
2654
+ throw new PolicyError(`${field} ${input} follows more than one foreign key; a principal path is <column>.<principal column>`)
2655
+ }
2656
+ const column = segments[0] ?? ''
2657
+ const held = segments[1] ?? ''
2658
+ // A move rewrites a chain column (ON UPDATE CASCADE), and the layer stamps the key and the version: none is fixed.
2659
+ const own = table.scope.mode === 'reference' ? undefined : table.scope.key
2660
+ if (column === own || column === table.version || hasOwn(table.files, column) || chainColumn(table, column)) {
2661
+ throw new PolicyError(
2662
+ `${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`,
2663
+ )
2664
+ }
2665
+ const hop = singleForeignKey(table, column, field)
2666
+ const target = linked(hop.table)
2667
+ if (target === undefined) {
2668
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}, which has no policy`)
2669
+ }
2670
+ if (target.view) {
2671
+ 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`)
2672
+ }
2673
+ if (target.queue !== undefined) {
2674
+ throw new PolicyError(`${field}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2675
+ }
2676
+ const scope = target.scope
2677
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
2678
+ throw new PolicyError(`${field}: ${hop.table} is a ${scope.mode} table; the principal is held by a table whose key ${column} references`)
2679
+ }
2680
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2681
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2682
+ throw new PolicyError(
2683
+ `${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`,
2684
+ )
2685
+ }
2686
+ if (scope.key !== hop.key) {
2687
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}.${hop.key}, not its key ${scope.key}`)
2688
+ }
2689
+ // Only the hop's own key, or a tenant-holding one that maps the column to the same key, may hold the start column.
2690
+ refuseReferencing(table, column, field, 'starts the principal path', hop)
2691
+ refuseReferencing(target, scope.key, field, 'is the key the principal path follows', undefined)
2692
+ if (!inSet(target.columns, held)) {
2693
+ throw new PolicyError(`${field}: ${held} is not a column of ${hop.table}`)
2694
+ }
2695
+ if (held === target.version) {
2696
+ throw new PolicyError(`${field}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2697
+ }
2698
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2699
+ throw new PolicyError(`${field}: ${hop.table}.${held} decides whom a row names, so no update of ${hop.table} writes it; replace the row instead`)
2700
+ }
2701
+ if (held === scope.key || hasOwn(target.files, held) || inSet(target.json, held) || chainColumn(target, held)) {
2702
+ throw new PolicyError(`${field}: ${hop.table}.${held} is a key, a containment, a file or a JSON column; it holds no principal`)
2703
+ }
2704
+ refuseReferencing(target, held, field, 'holds the principal', undefined)
2705
+ return { column, path: freeze({ table: hop.table, key: hop.key, column: held }) }
2706
+ }
2707
+
2708
+ function chainColumn(table: Pick<TableModel, 'chain'>, column: string): boolean {
2709
+ for (let index = 0; index < table.chain.length; index++) {
2710
+ if (table.chain[index]?.column === column) return true
2711
+ }
2712
+ return false
2713
+ }
2714
+
2715
+ /**
2716
+ * A column that decides whom a row names references nothing but `hop` (a key into `hop.table` that maps it to
2717
+ * `hop.key`): the column list carries no foreign key's actions, and one that cascades on update would let a write to
2718
+ * the referenced table change whom every row names.
2719
+ */
2720
+ function refuseReferencing(
2721
+ table: Pick<TableModel, 'name' | 'foreignKeys'>,
2722
+ column: string,
2723
+ field: string,
2724
+ role: string,
2725
+ hop: { readonly table: string; readonly key: string } | undefined,
2726
+ ): void {
2727
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2728
+ const key = table.foreignKeys[index]
2729
+ if (key === undefined) continue
2730
+ for (let position = 0; position < key.columns.length; position++) {
2731
+ if (key.columns[position] !== column) continue
2732
+ if (hop !== undefined && key.table === hop.table && key.references[position] === hop.key) continue
2733
+ throw new PolicyError(
2734
+ `${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`,
2735
+ )
2736
+ }
2737
+ }
2738
+ }
2739
+
2740
+ function parseAssign(
2741
+ table: LinkedTable,
2742
+ policy: Readonly<Record<string, unknown>>,
2743
+ expires: string | undefined,
2744
+ what: string,
2745
+ ): RelationSource['assign'] {
2746
+ const input = ownEntry(policy, 'assign')
2747
+ if (table.actions.insert.length === 0) {
2748
+ if (input !== undefined) {
2749
+ throw new PolicyError(`${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`)
2750
+ }
2751
+ return undefined
2752
+ }
2753
+ if (input === undefined) {
2754
+ throw new PolicyError(
2755
+ `${what}: inserting a row of ${table.name} (${table.actions.insert.join(', ')}) delegates the relation; state assign: { maxDays?, self? }`,
2756
+ )
2757
+ }
2758
+ const assign = plainRecord(input, `${what}.assign`)
2759
+ onlyFields(assign, ASSIGN_FIELDS, `${what}.assign`)
2760
+ const maxDays = ownEntry(assign, 'maxDays')
2761
+ if (maxDays !== undefined && (typeof maxDays !== 'number' || !isSafeInteger(maxDays) || maxDays < 1 || maxDays > MAX_ASSIGN_DAYS)) {
2762
+ throw new PolicyError(`${what}.assign.maxDays takes a whole number of days from 1 to ${MAX_ASSIGN_DAYS}`)
2763
+ }
2764
+ if (maxDays !== undefined && expires === undefined) {
2765
+ throw new PolicyError(`${what}.assign.maxDays bounds a row's expires, which the relation does not declare`)
2766
+ }
2767
+ const self = ownEntry(assign, 'self')
2768
+ if (self !== undefined && self !== true) {
2769
+ throw new PolicyError(`${what}.assign.self takes true`)
2770
+ }
2771
+ return freeze({ maxDays: typeof maxDays === 'number' ? maxDays : undefined, self: self === true })
2772
+ }
2773
+
2774
+ /** The own columns a condition reads. */
2775
+ function conditionColumns(condition: ConditionModel): readonly string[] {
2776
+ if (condition.kind === 'test') {
2777
+ return condition.hops.length === 0 ? [condition.column] : [condition.hops[0]?.column ?? '']
2778
+ }
2779
+ if (condition.kind === 'not') {
2780
+ return conditionColumns(condition.term)
2781
+ }
2782
+ if (condition.kind === 'some') {
2783
+ return [condition.hops[0]?.column ?? condition.key]
2784
+ }
2785
+ const columns: string[] = []
2786
+ for (let index = 0; index < condition.terms.length; index++) {
2787
+ const term = condition.terms[index]
2788
+ const inner = term === undefined ? [] : conditionColumns(term)
2789
+ for (let position = 0; position < inner.length; position++) {
2790
+ columns[columns.length] = inner[position] ?? ''
2791
+ }
2792
+ }
2793
+ return columns
2794
+ }
2795
+
2796
+ /** A table's scope with nothing left to derive, and its containment chain. */
2797
+ interface Resolved {
2798
+ readonly scope: ScopeModel
2799
+ readonly chain: readonly Container[]
2800
+ }
2801
+
2802
+ function resolveChain(
2803
+ table: ParsedTable,
2804
+ byName: Readonly<Record<string, ParsedTable>>,
2805
+ owners: Readonly<Record<string, ParsedTable>>,
2806
+ containment: Containment,
2807
+ chainOf: (table: ParsedTable) => readonly Container[],
2808
+ ): Resolved {
2809
+ /**
2810
+ * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
2811
+ * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
2812
+ */
2813
+ const above = (dimension: string): readonly Container[] => {
2814
+ const owner = ownEntry(owners, dimension)
2815
+ if (owner !== undefined) {
2816
+ return chainOf(owner)
2817
+ }
2818
+ const container = ownEntry(containment, dimension)?.container
2819
+ return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
2820
+ }
2821
+ const scope = table.scope
2822
+ if (scope.mode === 'dimension') {
2823
+ const container = scope.container
2824
+ if (container === undefined) {
2825
+ return { scope, chain: freeze([]) }
2826
+ }
2827
+ const owner = ownEntry(owners, container.dimension)
2828
+ if (owner !== undefined) {
2829
+ requireReference(table, container, owner, (column) => `scope.in: { column: '${column}' }`)
2830
+ requireCoveringKey(table, container, owner, chainOf(owner))
2831
+ }
2832
+ return { scope, chain: prepend(container, above(container.dimension)) }
2833
+ }
2834
+ if (scope.mode !== 'child') {
2835
+ return { scope, chain: freeze([]) }
2836
+ }
2837
+ const parent = ownEntry(byName, scope.parent)
2838
+ if (parent === undefined || parent.scope.mode !== 'dimension') {
2839
+ throw new PolicyError(`${table.name}: the parent ${scope.parent} must be a dimension table`)
2840
+ }
2841
+ const parentChain = chainOf(parent)
2842
+ const expected: string[] = []
2843
+ for (let index = 0; index < parentChain.length; index++) {
2844
+ expected[index] = parentChain[index]?.column ?? ''
2845
+ }
2846
+ const dimension = parent.scope.dimension
2847
+ const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
2848
+ // A view has no foreign key: its rows are read through the parent row its parent column names (ADR-0072).
2849
+ if (table.view) {
2850
+ const inherit = scope.inherit ?? freeze(carried(table, expected))
2851
+ for (let index = 0; index < inherit.length; index++) {
2852
+ if (!includes(expected, inherit[index])) {
2853
+ throw new PolicyError(
2854
+ `${table.name}: inherits ${inherit[index]}, which is not a containment column of ${scope.parent} (${expected.join(', ') || 'none'})`,
2855
+ )
2856
+ }
2857
+ }
2858
+ return { scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }), chain: freeze([link]) }
2859
+ }
2860
+ const inherit = scope.inherit ?? freeze(expected)
2861
+ const inherited = nameSet(inherit)
2862
+ let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
2863
+ for (let index = 0; index < expected.length; index++) {
2864
+ matches = matches && inSet(inherited, expected[index])
2865
+ }
2866
+ if (!matches) {
2867
+ throw new PolicyError(
2868
+ `${table.name}: must inherit exactly the containment columns of ${scope.parent} (${
2869
+ expected.join(', ') || 'none'
2870
+ }), so a composite foreign key keeps it in scope`,
2871
+ )
2872
+ }
2873
+ requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1142
2874
  requireCoveringKey(table, link, parent, parentChain)
1143
2875
  return {
1144
2876
  scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }),
@@ -1146,6 +2878,16 @@ function resolveChain(
1146
2878
  }
1147
2879
  }
1148
2880
 
2881
+ /** The columns of `names` that `table` has: the parent's containment columns a view carries, which a join of it compares. */
2882
+ function carried(table: ParsedTable, names: readonly string[]): readonly string[] {
2883
+ const found: string[] = []
2884
+ for (let index = 0; index < names.length; index++) {
2885
+ const name = names[index] ?? ''
2886
+ if (inSet(table.columns, name)) found[found.length] = name
2887
+ }
2888
+ return found
2889
+ }
2890
+
1149
2891
  /** Whether a foreign key of `table` takes `column` to `key` of `target`, alone or as part of a composite key. */
1150
2892
  function references(table: ParsedTable, column: string, target: string, key: string): boolean {
1151
2893
  for (let index = 0; index < table.foreignKeys.length; index++) {
@@ -1225,6 +2967,66 @@ function requireCoveringKey(table: ParsedTable, link: Container, owner: ParsedTa
1225
2967
  )
1226
2968
  }
1227
2969
 
2970
+ /**
2971
+ * The column pairs of the covering key a containment column follows (`requireCoveringKey`): the column and the key,
2972
+ * then each column of the owner's chain, which the contained row carries under the same name.
2973
+ */
2974
+ function containmentPairs(column: string, key: string, ownerChain: readonly Container[]): [string, string][] {
2975
+ const pairs: [string, string][] = [[column, key]]
2976
+ for (let index = 0; index < ownerChain.length; index++) {
2977
+ const link = ownerChain[index]
2978
+ if (link !== undefined) pairs[pairs.length] = [link.column, link.column]
2979
+ }
2980
+ return pairs
2981
+ }
2982
+
2983
+ /**
2984
+ * The column pairs a foreign key from `column` of `table` to a row keyed by `key` with chain `chain` holds to keep that
2985
+ * row in `table`'s own tenant: the column and the key, then each ancestor of `chain` that `table` also lies in.
2986
+ */
2987
+ function tenantPairs(table: Resolved, column: string, key: string, chain: readonly Container[]): [string, string][] {
2988
+ const pairs: [string, string][] = [[column, key]]
2989
+ for (let index = 0; index < chain.length; index++) {
2990
+ const link = chain[index]
2991
+ const shared = link === undefined ? undefined : nodeColumnOf(table, link.dimension)
2992
+ if (link !== undefined && shared !== undefined) pairs[pairs.length] = [shared, link.column]
2993
+ }
2994
+ return pairs
2995
+ }
2996
+
2997
+ /**
2998
+ * The ancestor columns of a tenant key (every pair but the first) must be NOT NULL: under MATCH SIMPLE a null one skips
2999
+ * the key, and a row written raw with it null would reach another tenant's row.
3000
+ */
3001
+ function requireNotNullAncestors(
3002
+ what: string,
3003
+ table: { readonly name: string; readonly notNull: NameSet },
3004
+ pairs: readonly (readonly [string, string])[],
3005
+ ): void {
3006
+ const nullable: string[] = []
3007
+ for (let index = 1; index < pairs.length; index++) {
3008
+ const column = pairs[index]?.[0] ?? ''
3009
+ if (!inSet(table.notNull, column)) nullable[nullable.length] = column
3010
+ }
3011
+ if (nullable.length > 0) {
3012
+ throw new PolicyError(
3013
+ `${what}: ${nullable.join(', ')} of ${table.name} may be null, and a null skips the foreign key that holds the row's tenant; declare ${
3014
+ nullable.join(', ')
3015
+ } not null and run fabrika db codegen`,
3016
+ )
3017
+ }
3018
+ }
3019
+
3020
+ /** One foreign key to `table` of exactly `pairs`: a further nullable column would let the database skip the whole key. */
3021
+ function holdsExactly(foreignKeys: readonly ForeignKey[], table: string, pairs: readonly (readonly [string, string])[]): boolean {
3022
+ for (let index = 0; index < foreignKeys.length; index++) {
3023
+ const foreignKey = foreignKeys[index]
3024
+ if (foreignKey !== undefined && foreignKey.table === table && foreignKey.columns.length === pairs.length && coversPairs(foreignKey, pairs)) {
3025
+ return true
3026
+ }
3027
+ }
3028
+ return false
3029
+ }
1228
3030
  /** Whether every `[column, referenced]` pair is a column of `foreignKey` with that referenced column. */
1229
3031
  function coversPairs(foreignKey: ForeignKey, pairs: readonly (readonly [string, string])[]): boolean {
1230
3032
  for (let index = 0; index < pairs.length; index++) {
@@ -1277,12 +3079,21 @@ type ScopeOf<P, T> = PolicyOf<P, T> extends { readonly scope: infer S } ? S : ne
1277
3079
 
1278
3080
  export type Operation = 'read' | 'insert' | 'update' | 'delete'
1279
3081
 
1280
- /** The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none. */
3082
+ /**
3083
+ * The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none, and for
3084
+ * the read of a table read with `'any'` (`ReadsAny`).
3085
+ */
1281
3086
  export type ActionOf<P, T, Op extends Operation> = PolicyOf<P, T> extends { readonly actions: infer Acts }
1282
- ? Acts extends { readonly [K in Op]: infer A } ? A extends string ? A : A extends readonly (infer L extends string)[] ? L : never
3087
+ ? Acts extends { readonly [K in Op]: infer A } ? A extends typeof READ_ANY ? never
3088
+ : A extends string ? A
3089
+ : A extends readonly (infer L extends string)[] ? L
3090
+ : never
1283
3091
  : never
1284
3092
  : never
1285
3093
 
3094
+ /** Whether table `T` is read with `'any'`: by every `app` endpoint, job and webhook, whatever its action. */
3095
+ export type ReadsAny<P, T> = PolicyOf<P, T> extends { readonly actions: { readonly read: typeof READ_ANY } } ? true : false
3096
+
1286
3097
  export type DimensionOf<P, T> = ScopeOf<P, T> extends { readonly dimension: infer D extends string } ? D : never
1287
3098
  export type ContainerOf<P, T> = ScopeOf<P, T> extends { readonly in: { readonly dimension: infer D extends string } } ? D : never
1288
3099
  /** The dimension that lists and inserts of T are scoped by: its container, or for a top-level table its own. */
@@ -1301,11 +3112,11 @@ type Flat<T> = { [K in keyof T]: T[K] }
1301
3112
 
1302
3113
  type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends { readonly columns: infer C } ? C : never
1303
3114
  type TableReadAction<P, T> = PolicyOf<P, T> extends { readonly scope: { readonly read: infer A } } ? A : ActionOf<P, T, 'read'>
1304
- /** Columns whose own read action is not the table's: no read by the table's read action returns them. */
3115
+ /** Columns whose own read actions leave out one of the table's: no read by the table's read action returns them. */
1305
3116
  type RestrictedColumns<P, T> = [ColumnPoliciesOf<P, T>] extends [never] ? never
1306
3117
  : {
1307
3118
  [K in keyof ColumnPoliciesOf<P, T>]: ColumnPoliciesOf<P, T>[K] extends { readonly read: infer R }
1308
- ? ([TableReadAction<P, T>] extends [R] ? never : K)
3119
+ ? ([TableReadAction<P, T>] extends [R extends readonly (infer L extends string)[] ? L : R] ? never : K)
1309
3120
  : never
1310
3121
  }[keyof ColumnPoliciesOf<P, T>]
1311
3122