@fabrika/db 0.9.0-dev.5 → 0.9.0-dev.50

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 (75) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +62 -22
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +37 -8
  10. package/src/errors.ts +8 -4
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +124 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +368 -146
  25. package/src/policy.ts +1973 -141
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-bun.ts +41 -14
  31. package/src/sqlite-migrate.ts +102 -1
  32. package/src/sqlite.ts +46 -1
  33. package/src/store.ts +1930 -167
  34. package/src/tables.ts +156 -6
  35. package/src/temporal.ts +8 -1
  36. package/src/testing-shared.ts +758 -140
  37. package/src/testing-sqlite.ts +212 -40
  38. package/src/testing.ts +151 -22
  39. package/src/vocabulary-tables.ts +159 -27
  40. package/types/src/authority.d.ts +147 -0
  41. package/types/src/builtins.d.ts +2 -0
  42. package/types/src/capability.d.ts +50 -2
  43. package/types/src/codegen-sqlite.d.ts +8 -1
  44. package/types/src/codegen.d.ts +54 -10
  45. package/types/src/condition-nodes.d.ts +9 -0
  46. package/types/src/conditions.d.ts +151 -0
  47. package/types/src/description.d.ts +26 -8
  48. package/types/src/errors.d.ts +7 -4
  49. package/types/src/file-columns.d.ts +6 -4
  50. package/types/src/framework.d.ts +5 -2
  51. package/types/src/guard.d.ts +24 -0
  52. package/types/src/index.d.ts +4 -3
  53. package/types/src/job-leases.d.ts +8 -1
  54. package/types/src/job-wakes.d.ts +28 -5
  55. package/types/src/json.d.ts +18 -0
  56. package/types/src/list-cursor.d.ts +13 -0
  57. package/types/src/migrations.d.ts +5 -0
  58. package/types/src/nodes.d.ts +4 -0
  59. package/types/src/notifications.d.ts +37 -0
  60. package/types/src/orm-types.d.ts +165 -73
  61. package/types/src/orm.d.ts +21 -0
  62. package/types/src/policy.d.ts +347 -23
  63. package/types/src/push-subscriptions.d.ts +49 -0
  64. package/types/src/registry.d.ts +36 -1
  65. package/types/src/request-receipts.d.ts +22 -0
  66. package/types/src/sql.d.ts +2 -2
  67. package/types/src/sqlite-bun.d.ts +11 -3
  68. package/types/src/sqlite-migrate.d.ts +32 -0
  69. package/types/src/store.d.ts +118 -31
  70. package/types/src/tables.d.ts +8 -2
  71. package/types/src/temporal.d.ts +4 -1
  72. package/types/src/testing-shared.d.ts +112 -23
  73. package/types/src/testing-sqlite.d.ts +17 -2
  74. package/types/src/testing.d.ts +1 -1
  75. 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;
101
- * without one it falls back to the table's read action. `write`: only a capability of that action updates the column,
102
- * and the table's update action does not, so the column is not in `update`.
208
+ * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
209
+ * without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
210
+ * column, so the column is not in `update`; a listed table update action writes it beside its update list.
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 and its own write actions (each one, or a list as a table operation takes), or both. */
107
215
  export interface ColumnPolicy<A extends string> {
108
- readonly read?: A
109
- readonly write?: A
216
+ readonly read?: TableAction<A>
217
+ readonly write?: TableAction<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
 
@@ -162,6 +272,15 @@ export interface TableColumns<Col extends string = string, Table extends string
162
272
  readonly timestamps?: readonly Col[]
163
273
  /** On SQLite, the columns declared `BOOLEAN`, stored as 0 or 1 and read as a boolean; absent when none. */
164
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
165
284
  }
166
285
 
167
286
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -178,9 +297,17 @@ export type ScopeModel =
178
297
  | { readonly mode: 'reference'; readonly reason: string }
179
298
  | { readonly mode: 'app'; readonly reason: string; readonly key: string }
180
299
 
181
- /** 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
+ */
182
304
  export interface ActionModel {
183
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
184
311
  readonly insert: readonly string[]
185
312
  readonly update: readonly string[]
186
313
  readonly delete: readonly string[]
@@ -215,23 +342,145 @@ export interface TableModel {
215
342
  readonly queue: QueueModel | undefined
216
343
  /** The file columns, each with its file kind: a reference to `fabrika_files`, written only with a file reference. */
217
344
  readonly files: Readonly<Record<string, string>>
218
- /** The columns that declare their own read action, as declared (also those equal to the table's). */
219
- readonly columnReads: Readonly<Record<string, string>>
220
- /** The columns that declare their own write action: only a capability of it updates them. */
221
- readonly columnWrites: Readonly<Record<string, string>>
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[]>>
347
+ /** The columns that declare their own write actions, as declared: only a capability of one of them updates them. */
348
+ readonly columnWrites: Readonly<Record<string, readonly string[]>>
222
349
  /** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
223
350
  readonly dates: NameSet
224
351
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
225
352
  readonly timestamps: NameSet
226
353
  /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
227
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
228
359
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
229
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
230
363
  /**
231
364
  * The containment links this table carries a column for, nearest first: a dimension table's container and
232
365
  * the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
233
366
  */
234
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
235
484
  }
236
485
 
237
486
  /** A child's `column` and `inherit`, when omitted, are derived from its parent while the tables are linked. */
@@ -245,7 +494,21 @@ type ParsedScope =
245
494
  readonly inherit: readonly string[] | undefined
246
495
  }
247
496
 
248
- 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
+ }
249
512
 
250
513
  let readModels: <DB, P>(tables: Tables<DB, P>) => TableModels
251
514
  let hasModels: (value: object) => boolean = () => false
@@ -301,7 +564,7 @@ export function defineTables<DB, P>(vocabularyInput: unknown, columns: unknown):
301
564
  /** `defineTables(vocabulary, columns)` answers the policies' builder, or names the fix for an untyped column list. */
302
565
  export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never]
303
566
  ? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'>
304
- : DefineVocabularyPolicies<ColumnTypes<C>, V>
567
+ : DefineVocabularyPolicies<ColumnTypes<C>, V, ColumnViews<C>>
305
568
 
306
569
  /**
307
570
  * The same policies read from values nobody type-checked: `src/db/tables.ts` and its vocabulary as the static reader
@@ -318,8 +581,13 @@ type Containment = Readonly<Record<string, { readonly container: string | undefi
318
581
  interface VocabularyModel {
319
582
  readonly dimensions: Containment
320
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>>
321
586
  }
322
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
+
323
591
  function parseVocabulary(input: unknown): VocabularyModel {
324
592
  const vocabulary = plainRecord(input, 'the vocabulary')
325
593
  const dimensions = plainRecord(ownEntry(vocabulary, 'dimensions'), 'the vocabulary dimensions')
@@ -343,12 +611,57 @@ function parseVocabulary(input: unknown): VocabularyModel {
343
611
  }
344
612
  }
345
613
  const actions = ownKeys(plainRecord(ownEntry(vocabulary, 'actions'), 'the vocabulary actions'))
346
- 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) })
347
635
  }
348
636
 
349
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans'])
637
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'notNull', 'view'])
350
638
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
351
- 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
352
665
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
353
666
  const ACTION_FIELDS = nameSet(['read', 'insert', 'update', 'delete', 'appRead', 'appCount'])
354
667
  const DIMENSION_FIELDS = nameSet(['dimension', 'key', 'in'])
@@ -358,25 +671,6 @@ const REFERENCE_FIELDS = nameSet(['reference'])
358
671
  const APPLICATION_FIELDS = nameSet(['app', 'key'])
359
672
  const COLUMN_FIELDS = nameSet(['read', 'write'])
360
673
 
361
- /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
362
- function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>> {
363
- const prototype: unknown = typeof value === 'object' && value !== null && !isArray(value) ? prototypeOf(value) : undefined
364
- if ((prototype !== OBJECT_PROTOTYPE && prototype !== null) || typeof value !== 'object' || value === null || ownSymbols(value).length > 0) {
365
- throw new PolicyError(`${what} must be a plain object`)
366
- }
367
- const copy: Record<string, unknown> = {}
368
- const keys = ownNames(value)
369
- for (let index = 0; index < keys.length; index++) {
370
- const key = keys[index] ?? ''
371
- const descriptor = ownDescriptor(value, key)
372
- if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
373
- throw new PolicyError(`${what}: ${key} is an accessor; a policy holds plain values`)
374
- }
375
- setOwn(copy, key, descriptor.value)
376
- }
377
- return freeze(copy)
378
- }
379
-
380
674
  /** Unknown keys are refused, not dropped: a misspelt `insrt` would otherwise leave the table without its column list. */
381
675
  function onlyFields(record: Readonly<Record<string, unknown>>, allowed: NameSet, what: string): void {
382
676
  const keys = ownKeys(record)
@@ -400,17 +694,41 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
400
694
  }
401
695
  }
402
696
  const parsed: ParsedTable[] = []
697
+ const views: Record<string, ViewColumns> = {}
403
698
  for (let index = 0; index < tables.length; index++) {
404
699
  const table = tables[index] ?? ''
405
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
+ }
406
710
  if (policy === undefined) {
407
711
  throw new PolicyError(`${table}: every table needs a policy in tables.ts`)
408
712
  }
409
- 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`)
410
723
  }
411
- return linkTables(parsed, vocabulary.dimensions)
724
+ return view === true
412
725
  }
413
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
+
414
732
  /** How a policy names its columns: one it states must exist, and so must one a convention derives for it. */
415
733
  interface ColumnReader {
416
734
  readonly column: (name: unknown, field: string) => string
@@ -464,6 +782,14 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
464
782
  const scopeInput = plainRecord(ownEntry(policy, 'scope'), `${table}: scope`)
465
783
  const foreignKeys = parseForeignKeys(table, ownEntry(entry, 'foreignKeys'), column)
466
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
+ }
467
793
  const action = (value: unknown, field: string): string => {
468
794
  const name = nonEmpty(table, value, field)
469
795
  if (!inSet(vocabulary.actions, name)) {
@@ -476,13 +802,24 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
476
802
  const actions = parseActions(table, scopeInput, ownEntry(policy, 'actions'), action)
477
803
  const insert = nameSet(columnsOf(ownEntry(policy, 'insert'), 'insert'))
478
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)
479
808
  const versionInput = ownEntry(policy, 'version')
480
809
  const createdByInput = ownEntry(policy, 'createdBy')
481
- const version = versionInput === undefined ? undefined : column(versionInput, 'version')
482
- 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)
483
820
  const restricted: string[] = []
484
- const columnReads: Record<string, string> = {}
485
- const columnWrites: Record<string, string> = {}
821
+ const columnReads: Record<string, readonly string[]> = {}
822
+ const columnWrites: Record<string, readonly string[]> = {}
486
823
  const columnsInput = ownEntry(policy, 'columns')
487
824
  const columnPolicies = columnsInput === undefined ? freeze({}) : plainRecord(columnsInput, `${table}: columns`)
488
825
  const declared = ownKeys(columnPolicies)
@@ -496,15 +833,23 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
496
833
  throw new PolicyError(`${table}: columns.${name} declares no action; it takes read, write or both`)
497
834
  }
498
835
  if (readInput !== undefined) {
499
- const read = action(readInput, `columns.${name}.read`)
500
- setOwn(columnReads, name, read)
501
- // With several read actions, a column of one of them is hidden from the others.
502
- if (actions.read.length > 1 || !includes(actions.read, read)) {
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)) {
503
842
  restricted[restricted.length] = name
504
843
  }
505
844
  }
845
+ if (writeInput !== undefined && view) {
846
+ throw new PolicyError(viewWrite(table))
847
+ }
506
848
  if (writeInput !== undefined) {
507
- setOwn(columnWrites, name, columnWrite(table, name, action(writeInput, `columns.${name}.write`), actions, update))
849
+ const writes = isArray(writeInput)
850
+ ? distinctActions(table, writeInput, `columns.${name}.write`, action)
851
+ : freeze([action(writeInput, `columns.${name}.write`)])
852
+ setOwn(columnWrites, name, columnWrite(table, name, writes, actions, update))
508
853
  }
509
854
  }
510
855
  const hidden = nameSet(restricted)
@@ -514,21 +859,27 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
514
859
  throw new PolicyError(`${table}: the key ${scope.key} takes no action of its own`)
515
860
  }
516
861
  if (version !== undefined && hasOwn(columnPolicies, version)) {
517
- throw new PolicyError(`${table}: the version ${version} takes no action of its own`)
862
+ throw new PolicyError(`${table}: the version ${version} takes no action of its own${conventionOf(byConvention, version, 'version') ?? ''}`)
518
863
  }
519
- const writable = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app'
520
864
  const queueInput = ownEntry(policy, 'queue')
521
865
  const filesInput = ownEntry(policy, 'files')
866
+ // On a view, an empty insert or update list is refused too: it states a write the view never takes.
867
+ if (view && (hasOwn(policy, 'insert') || hasOwn(policy, 'update'))) {
868
+ throw new PolicyError(viewWrite(table))
869
+ }
522
870
  if (
523
871
  !writable
524
872
  && (namesOf(insert).length > 0 || namesOf(update).length > 0 || version !== undefined || createdBy !== undefined
525
- || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined)
873
+ || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined
874
+ || actions.insert.length > 0 || actions.update.length > 0 || actions.delete.length > 0)
526
875
  ) {
527
- throw new PolicyError(`${table}: a ${scope.mode} table is never written by a handler`)
876
+ throw new PolicyError(view ? viewWrite(table) : `${table}: a ${scope.mode} table is never written by a handler`)
528
877
  }
529
878
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
530
879
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
531
880
  const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
881
+ const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
882
+ const notNull = parseColumnSet(table, ownEntry(entry, 'notNull'), column, 'notNull')
532
883
  const queue = queueInput === undefined
533
884
  ? undefined
534
885
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -557,7 +908,19 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
557
908
  dates,
558
909
  timestamps,
559
910
  booleans,
911
+ json,
912
+ notNull,
560
913
  foreignKeys,
914
+ view,
915
+ confersInput: ownEntry(policy, 'confers'),
916
+ whenInput: ownEntry(policy, 'when'),
917
+ relationWhenInput: ownEntry(policy, 'relationWhen'),
918
+ revealsInput: ownEntry(policy, 'reveals'),
919
+ readThroughInput: ownEntry(policy, 'readThrough'),
920
+ writeThroughInput: ownEntry(policy, 'writeThrough'),
921
+ memberRevealsInput: ownEntry(policy, 'memberReveals'),
922
+ accessInput: ownEntry(policy, 'access'),
923
+ byConvention,
561
924
  }
562
925
  }
563
926
 
@@ -613,19 +976,23 @@ function parseFileColumns(
613
976
  }
614
977
 
615
978
  /**
616
- * A column's own write action takes the column away from the table's update action: one action writes a column, so
617
- * the column is not in `update`, and the action is not the update action (that one lists the column in `update`).
979
+ * A column's own write actions. A table update action may be one of them: it then writes the column beside its update
980
+ * list. Naming exactly the table's update actions says what `update` says, so that form is refused.
618
981
  */
619
- function columnWrite(table: string, name: string, write: string, actions: ActionModel, update: NameSet): string {
982
+ function columnWrite(table: string, name: string, writes: readonly string[], actions: ActionModel, update: NameSet): readonly string[] {
620
983
  if (inSet(update, name)) {
621
984
  throw new PolicyError(
622
- `${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${write}; remove it from update`,
985
+ `${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${
986
+ writes.join(', ')
987
+ }; remove it from update`,
623
988
  )
624
989
  }
625
- if (includes(actions.update, write)) {
626
- throw new PolicyError(`${table}: columns.${name}.write names ${write}, the table's update action; list ${name} in update instead`)
990
+ if (everyIncluded(writes, actions.update) && everyIncluded(actions.update, writes)) {
991
+ throw new PolicyError(
992
+ `${table}: columns.${name}.write names ${writes.join(', ')}, the table's update action; list ${name} in update instead`,
993
+ )
627
994
  }
628
- return write
995
+ return writes
629
996
  }
630
997
 
631
998
  /**
@@ -642,7 +1009,7 @@ function parseQueue(
642
1009
  readonly version: string | undefined
643
1010
  readonly actions: ActionModel
644
1011
  readonly update: NameSet
645
- readonly columnWrites: Readonly<Record<string, string>>
1012
+ readonly columnWrites: Readonly<Record<string, readonly string[]>>
646
1013
  },
647
1014
  ): QueueModel {
648
1015
  const queue = plainRecord(input, `${table}: queue`)
@@ -679,7 +1046,10 @@ function parseQueue(
679
1046
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
680
1047
  }
681
1048
 
682
- /** The column list's `date` (`dates`), timestamp (`timestamps`) or boolean (`booleans`) columns, each one of the table's. */
1049
+ /**
1050
+ * The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`), JSON (`json`) or NOT NULL
1051
+ * (`notNull`) columns, each one of the table's.
1052
+ */
683
1053
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
684
1054
  if (input === undefined) {
685
1055
  return nameSet([])
@@ -692,21 +1062,56 @@ function parseColumnSet(table: string, input: unknown, column: (name: unknown, f
692
1062
  }
693
1063
 
694
1064
  /**
695
- * The columns a capability of `action` updates in `model`: the update list for the table's update action, the
696
- * columns that declare it as their own write action for any other; none for an action that writes nothing here.
1065
+ * The columns a capability of `action` updates in `model`: the update list for a table update action, and every
1066
+ * column that lists it among its own write actions; none for an action that writes nothing here.
697
1067
  */
698
1068
  export function updatableBy(model: TableModel, action: string): NameSet {
699
- if (includes(model.actions.update, action)) {
1069
+ const owned = columnsWrittenBy(model, action)
1070
+ if (!includes(model.actions.update, action)) {
1071
+ return nameSet(owned)
1072
+ }
1073
+ if (owned.length === 0) {
700
1074
  return model.update
701
1075
  }
1076
+ const listed = namesOf(model.update)
1077
+ const columns: string[] = []
1078
+ for (let index = 0; index < listed.length; index++) {
1079
+ columns[columns.length] = listed[index] ?? ''
1080
+ }
1081
+ for (let index = 0; index < owned.length; index++) {
1082
+ columns[columns.length] = owned[index] ?? ''
1083
+ }
1084
+ return nameSet(columns)
1085
+ }
1086
+
1087
+ /** The columns that list `action` among their own write actions. */
1088
+ function columnsWrittenBy(model: TableModel, action: string): readonly string[] {
702
1089
  const names = ownKeys(model.columnWrites)
703
1090
  const columns: string[] = []
704
1091
  for (let index = 0; index < names.length; index++) {
705
1092
  const name = names[index] ?? ''
706
- if (model.columnWrites[name] === action) {
1093
+ if (includes(ownEntry(model.columnWrites, name) ?? [], action)) {
707
1094
  columns[columns.length] = name
708
1095
  }
709
1096
  }
1097
+ return columns
1098
+ }
1099
+
1100
+ /**
1101
+ * The columns any of `actions` updates in `model`, as one role holding them: the union of `updatableBy` over them.
1102
+ * One action's set is `updatableBy`'s own.
1103
+ */
1104
+ export function updatableByAny(model: TableModel, actions: readonly string[]): NameSet {
1105
+ if (actions.length === 1) {
1106
+ return updatableBy(model, actions[0] ?? '')
1107
+ }
1108
+ const columns: string[] = []
1109
+ for (let index = 0; index < actions.length; index++) {
1110
+ const names = namesOf(updatableBy(model, actions[index] ?? ''))
1111
+ for (let position = 0; position < names.length; position++) {
1112
+ columns[columns.length] = names[position] ?? ''
1113
+ }
1114
+ }
710
1115
  return nameSet(columns)
711
1116
  }
712
1117
 
@@ -716,32 +1121,81 @@ export function namesAction(model: TableModel, action: string): boolean {
716
1121
  if (includes(read, action) || includes(insert, action) || includes(update, action) || includes(remove, action)) {
717
1122
  return true
718
1123
  }
719
- const columns = ownKeys(model.columnWrites)
720
- for (let index = 0; index < columns.length; index++) {
721
- if (model.columnWrites[columns[index] ?? ''] === action) {
722
- return true
723
- }
724
- }
725
- return false
1124
+ return columnsWrittenBy(model, action).length > 0
726
1125
  }
727
1126
 
728
1127
  /**
729
- * The columns a capability of `action` reads: every one that declares no read action of its own, or exactly this
730
- * one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
1128
+ * The columns a capability of `action` reads: every one that declares no read action of its own, or one whose own
1129
+ * read actions include this one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
731
1130
  */
732
1131
  export function visibleFor(model: TableModel, action: string): readonly string[] {
1132
+ return visibleThrough(model, soleReach(action))
1133
+ }
1134
+
1135
+ /**
1136
+ * The actions whose reach one read answers: an `app` capability's held actions that admit the operation, each row
1137
+ * passing where one of them admits it (`conditionedAny`), and whether their `when` narrows the rows (`narrowed`), which
1138
+ * it does not in a table read with `'any'`.
1139
+ */
1140
+ export interface ReadReach {
1141
+ readonly actions: readonly string[]
1142
+ readonly narrowed: boolean
1143
+ }
1144
+
1145
+ /** The reach of a capability of one action, whose own condition narrows its rows. */
1146
+ export function soleReach(action: string): ReadReach {
1147
+ return freeze({ actions: freeze([action]), narrowed: true })
1148
+ }
1149
+
1150
+ /**
1151
+ * Whether every row a read of `reach` answers is a row `action` reads alone: it is one of the reaching actions, and either
1152
+ * 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
1153
+ * actions never put one action's column on another action's rows.
1154
+ */
1155
+ export function readsAsAction(model: TableModel, action: string, reach: ReadReach): boolean {
1156
+ if (!includes(reach.actions, action)) {
1157
+ return false
1158
+ }
1159
+ return !reach.narrowed || reach.actions.length === 1 || !hasOwn(model.when, action)
1160
+ }
1161
+
1162
+ /**
1163
+ * The columns a read of `reach` answers, the union of what each reaching action reads alone: every one that declares no
1164
+ * read action of its own, and one that does where that action reads every answered row (`readsAsAction`).
1165
+ */
1166
+ export function visibleThrough(model: TableModel, reach: ReadReach): readonly string[] {
733
1167
  const columns = namesOf(model.columns)
734
1168
  const visible: string[] = []
735
1169
  for (let index = 0; index < columns.length; index++) {
736
1170
  const name = columns[index] ?? ''
737
1171
  const declared = hasOwn(model.columnReads, name) ? model.columnReads[name] : undefined
738
- if (declared === undefined || declared === action) {
1172
+ if (declared === undefined || readsAsOneOf(model, declared, reach)) {
739
1173
  visible[visible.length] = name
740
1174
  }
741
1175
  }
742
1176
  return freeze(visible)
743
1177
  }
744
1178
 
1179
+ /** Whether one of a column's own read actions reads every row a read of `reach` answers (`readsAsAction`). */
1180
+ export function readsAsOneOf(model: TableModel, actions: readonly string[], reach: ReadReach): boolean {
1181
+ for (let index = 0; index < actions.length; index++) {
1182
+ if (readsAsAction(model, actions[index] ?? '', reach)) {
1183
+ return true
1184
+ }
1185
+ }
1186
+ return false
1187
+ }
1188
+
1189
+ /** Whether every one of `actions` is in `list`. */
1190
+ function everyIncluded(actions: readonly string[], list: readonly string[]): boolean {
1191
+ for (let index = 0; index < actions.length; index++) {
1192
+ if (!includes(list, actions[index] ?? '')) {
1193
+ return false
1194
+ }
1195
+ }
1196
+ return true
1197
+ }
1198
+
745
1199
  /** Every action that updates a column of `model`: its update action and each column's own write action. */
746
1200
  export function updateActions(model: TableModel): readonly string[] {
747
1201
  const actions: string[] = []
@@ -750,9 +1204,12 @@ export function updateActions(model: TableModel): readonly string[] {
750
1204
  }
751
1205
  const names = ownKeys(model.columnWrites)
752
1206
  for (let index = 0; index < names.length; index++) {
753
- const write = model.columnWrites[names[index] ?? '']
754
- if (write !== undefined && !includes(actions, write)) {
755
- actions[actions.length] = write
1207
+ const writes = ownEntry(model.columnWrites, names[index] ?? '') ?? []
1208
+ for (let position = 0; position < writes.length; position++) {
1209
+ const write = writes[position] ?? ''
1210
+ if (!includes(actions, write)) {
1211
+ actions[actions.length] = write
1212
+ }
756
1213
  }
757
1214
  }
758
1215
  return actions
@@ -854,6 +1311,10 @@ function parseContainer(
854
1311
  return freeze({ dimension: container, column: columns.column(ownEntry(stated, 'column'), 'scope.in.column') })
855
1312
  }
856
1313
 
1314
+ function viewWrite(table: string): string {
1315
+ return `${table}: a view is never written by a handler, so its policy takes only actions.read, appRead, appCount and column read actions`
1316
+ }
1317
+
857
1318
  function parseActions(
858
1319
  table: string,
859
1320
  scope: Readonly<Record<string, unknown>>,
@@ -875,7 +1336,13 @@ function parseActions(
875
1336
  }
876
1337
  return distinctActions(table, value, `actions.${field}`, action)
877
1338
  }
878
- const read = operation('read')
1339
+ const readAny = ownEntry(actions, 'read') === READ_ANY
1340
+ if (readAny && !hasOwn(scope, 'app')) {
1341
+ throw new PolicyError(
1342
+ `${table}: actions.read 'any' is for an application table; a dimension, child or reference table names its read actions`,
1343
+ )
1344
+ }
1345
+ const read = readAny ? freeze([]) : operation('read')
879
1346
  const records = hasOwn(scope, 'dimension') || hasOwn(scope, 'child')
880
1347
  const kind = hasOwn(scope, 'app') ? 'an application table' : 'a reference table'
881
1348
  const reach = (field: 'appRead' | 'appCount'): readonly string[] => {
@@ -906,7 +1373,7 @@ function parseActions(
906
1373
  throw new PolicyError(`${table}: actions.appRead and actions.appCount both name ${name}`)
907
1374
  }
908
1375
  }
909
- return freeze({ read, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
1376
+ return freeze({ read, readAny, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
910
1377
  }
911
1378
 
912
1379
  /** A plain array of distinct actions of the vocabulary, at least one. */
@@ -940,6 +1407,8 @@ interface Stamp {
940
1407
  readonly role: string
941
1408
  /** An insert may set it: a queue row's first due time. */
942
1409
  readonly insertable?: true
1410
+ /** Why a column the policy may not have named is stamped: its name is the convention's. */
1411
+ readonly convention?: string
943
1412
  }
944
1413
 
945
1414
  /** The columns the layer writes itself: the key, every containment link, the version and the creator. */
@@ -955,10 +1424,10 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
955
1424
  }
956
1425
  }
957
1426
  if (table.version !== undefined) {
958
- stamps[stamps.length] = { column: table.version, role: 'the version' }
1427
+ stamps[stamps.length] = { column: table.version, role: 'the version', convention: conventionOf(table.byConvention, table.version, 'version') }
959
1428
  }
960
1429
  if (table.createdBy !== undefined) {
961
- stamps[stamps.length] = { column: table.createdBy, role: 'createdBy' }
1430
+ stamps[stamps.length] = { column: table.createdBy, role: 'createdBy', convention: conventionOf(table.byConvention, table.createdBy, 'createdBy') }
962
1431
  }
963
1432
  if (table.queue !== undefined) {
964
1433
  stamps[stamps.length] = { column: table.queue.attempts, role: 'queue.attempts' }
@@ -967,6 +1436,11 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
967
1436
  return stamps
968
1437
  }
969
1438
 
1439
+ /** Why a column the policy did not name is stamped, or nothing when the policy named it. */
1440
+ function conventionOf(byConvention: NameSet, column: string, field: string): string | undefined {
1441
+ return inSet(byConvention, column) ? ` (a written table's column named ${column} is its ${field} unless the policy names another)` : undefined
1442
+ }
1443
+
970
1444
  /**
971
1445
  * Each stamped column holds one role and is never written by a handler. A shared column would let one stamp
972
1446
  * overwrite another: `createdBy` on the key inserts the principal as the id, `version` on a container column
@@ -979,6 +1453,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
979
1453
  if (stamp === undefined) {
980
1454
  continue
981
1455
  }
1456
+ // Nothing writes a view, so its key may be its parent column; a predicate still compares each.
1457
+ if (table.view) {
1458
+ if (inSet(table.json, stamp.column)) {
1459
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which no predicate compares as ${stamp.role}; give it a scalar type`)
1460
+ }
1461
+ continue
1462
+ }
982
1463
  for (let other = 0; other < index; other++) {
983
1464
  const earlier = stamps[other]
984
1465
  if (earlier !== undefined && earlier.column === stamp.column) {
@@ -988,10 +1469,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
988
1469
  }
989
1470
  }
990
1471
  if ((stamp.insertable !== true && inSet(table.insert, stamp.column)) || inSet(table.update, stamp.column)) {
991
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update`)
1472
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update${stamp.convention ?? ''}`)
992
1473
  }
993
1474
  if (hasOwn(table.columnWrites, stamp.column)) {
994
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own`)
1475
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own${stamp.convention ?? ''}`)
1476
+ }
1477
+ if (inSet(table.json, stamp.column)) {
1478
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which the layer cannot stamp as ${stamp.role}; give it a scalar type`)
995
1479
  }
996
1480
  }
997
1481
  }
@@ -1018,7 +1502,8 @@ export function includes(names: readonly string[], name: unknown): boolean {
1018
1502
  }
1019
1503
 
1020
1504
  /** Resolves every table's containment chain and refuses a shape the layer cannot enforce. */
1021
- function linkTables(parsed: readonly ParsedTable[], containment: Containment): TableModels {
1505
+ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel, views: Readonly<Record<string, ViewColumns>>): TableModels {
1506
+ const containment = vocabulary.dimensions
1022
1507
  const byName: Record<string, ParsedTable> = {}
1023
1508
  const owners: Record<string, ParsedTable> = {}
1024
1509
  for (let index = 0; index < parsed.length; index++) {
@@ -1068,69 +1553,1339 @@ function linkTables(parsed: readonly ParsedTable[], containment: Containment): T
1068
1553
  return result
1069
1554
  }
1070
1555
 
1556
+ const conditionTable = (name: string): ConditionTable | undefined => ownEntry(byName, name)
1557
+ const linkedTable = (name: string): LinkedTable | undefined => {
1558
+ const target = ownEntry(byName, name)
1559
+ if (target === undefined) return undefined
1560
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, byConvention, ...rest } =
1561
+ target
1562
+ return { ...rest, ...resolve(target, []) }
1563
+ }
1564
+ const hopRule: HopRule = (from, column, to, key, backward) => {
1565
+ const source = ownEntry(byName, from)
1566
+ const target = ownEntry(byName, to)
1567
+ if (target?.scope.mode === 'reference') {
1568
+ return !backward
1569
+ }
1570
+ if (source === undefined || target === undefined) {
1571
+ return false
1572
+ }
1573
+ const into = resolve(target, [])
1574
+ // The hop reads the row its foreign key references, so that must be the row the rules below place: the one with the key.
1575
+ if ((into.scope.mode !== 'dimension' && into.scope.mode !== 'child') || into.scope.key !== key) {
1576
+ return false
1577
+ }
1578
+ const scope = resolve(source, []).scope
1579
+ // A view's parent row is read through its parent subquery, which scopes it; a table's through its covering key.
1580
+ const covered = (): boolean => {
1581
+ if (!source.view) requireNotNullAncestors(`${from}.${column}`, source, containmentPairs(column, key, into.chain))
1582
+ return true
1583
+ }
1584
+ // The container column must lead to the table that owns the container dimension, not to any table its key references.
1585
+ if (
1586
+ scope.mode === 'dimension' && scope.container !== undefined && scope.container.column === column && into.scope.mode === 'dimension'
1587
+ && into.scope.dimension === scope.container.dimension
1588
+ ) {
1589
+ return covered()
1590
+ }
1591
+ if (scope.mode === 'child' && scope.column === column && scope.parent === to) {
1592
+ return covered()
1593
+ }
1594
+ // Any other foreign key reaches a row of the same tenant only when it also holds every ancestor the two share.
1595
+ const pairs = tenantPairs(resolve(source, []), column, into.scope.key, into.chain)
1596
+ if (pairs.length < 2 || !holdsExactly(source.foreignKeys, to, pairs)) {
1597
+ return false
1598
+ }
1599
+ requireNotNullAncestors(`${from}.${column}`, source, pairs)
1600
+ return true
1601
+ }
1602
+ const sources: Record<string, string> = {}
1603
+ const viewed: Record<string, string> = {}
1071
1604
  const models: Record<string, TableModel> = {}
1072
1605
  for (let index = 0; index < parsed.length; index++) {
1073
1606
  const table = parsed[index]
1074
1607
  if (table !== undefined) {
1075
1608
  const { scope, chain } = resolve(table, [])
1076
- setOwn(models, table.name, freeze({ ...table, scope, chain }))
1609
+ const {
1610
+ confersInput,
1611
+ whenInput,
1612
+ relationWhenInput,
1613
+ revealsInput,
1614
+ readThroughInput,
1615
+ writeThroughInput,
1616
+ memberRevealsInput,
1617
+ accessInput,
1618
+ byConvention,
1619
+ ...rest
1620
+ } = table
1621
+ const linked = { ...rest, scope, chain }
1622
+ const ownerOf = (dimension: string): ResolvedOwner | undefined => {
1623
+ const owner = ownEntry(owners, dimension)
1624
+ return owner === undefined ? undefined : { name: owner.name, ...resolve(owner, []) }
1625
+ }
1626
+ // A container's own path, parsed from its own declaration; one through its container in turn is none.
1627
+ const containerPath = (container: string, dimension: string): SecondaryPath | undefined => {
1628
+ const declared = ownEntry(byName, container)?.readThroughInput
1629
+ const column = declared === undefined ? undefined : ownEntry(plainRecord(declared, `${container}: readThrough`), dimension)
1630
+ const target = linkedTable(container)
1631
+ if (target === undefined || typeof column !== 'string' || splitPath(column).length !== 1) return undefined
1632
+ return parseReadThrough(target, { [dimension]: column }, vocabulary, ownerOf, () => undefined)[0]
1633
+ }
1634
+ const readThrough = parseWriteThrough(
1635
+ linked,
1636
+ parseReadThrough(linked, readThroughInput, vocabulary, ownerOf, containerPath),
1637
+ writeThroughInput,
1638
+ vocabulary,
1639
+ )
1640
+ const confers = parseConfers(linked, confersInput, vocabulary.relations, conditionTable, linkedTable, hopRule)
1641
+ for (let position = 0; position < confers.length; position++) {
1642
+ const relation = confers[position]?.relation ?? ''
1643
+ const earlier = ownEntry(sources, relation)
1644
+ if (earlier !== undefined) {
1645
+ throw new PolicyError(`${table.name}: the relation ${relation} is already conferred by ${earlier}; a relation has one source table`)
1646
+ }
1647
+ setOwn(sources, relation, table.name)
1648
+ }
1649
+ const root = conditionRoot(linked, byName)
1650
+ const when = parseWhen(linked, root, whenInput, conditionTable, hopRule)
1651
+ const relationWhen = parseRelationWhen(linked, root, relationWhenInput, vocabulary, conditionTable, hopRule)
1652
+ const reveals = parseReveals(linked, readThrough, revealsInput, vocabulary, conditionTable, hopRule)
1653
+ const memberReveals = parseMemberReveals(linked, readThrough, memberRevealsInput, vocabulary, conditionTable, hopRule)
1654
+ const access = parseAccess(linked, accessInput, vocabulary, views)
1655
+ for (let position = 0; position < access.length; position++) {
1656
+ const relation = access[position]?.relation ?? ''
1657
+ if (!hasOwn(viewed, relation)) setOwn(viewed, relation, table.name)
1658
+ }
1659
+ setOwn(models, table.name, freeze({ ...linked, confers, when, relationWhen, reveals, readThrough, memberReveals, access }))
1660
+ }
1661
+ }
1662
+ checkRelationWhenReach(models, vocabulary)
1663
+ const relations = ownKeys(vocabulary.relations)
1664
+ for (let index = 0; index < relations.length; index++) {
1665
+ const relation = relations[index] ?? ''
1666
+ if (!hasOwn(sources, relation) && !hasOwn(viewed, relation)) {
1667
+ throw new PolicyError(
1668
+ `the vocabulary relation ${relation} has no source: declare confers.${relation} on the table whose rows hold it, or name an access view for it`,
1669
+ )
1077
1670
  }
1078
1671
  }
1672
+ checkRevealSources(models, sources)
1079
1673
  return freeze(models)
1080
1674
  }
1081
1675
 
1082
- /** A table's scope with nothing left to derive, and its containment chain. */
1083
- interface Resolved {
1084
- readonly scope: ScopeModel
1085
- readonly chain: readonly Container[]
1676
+ /** A reveal is matched through the relation's source rows, so a relation that access views alone serve reveals nothing. */
1677
+ function checkRevealSources(models: Readonly<Record<string, TableModel>>, sources: Readonly<Record<string, string>>): void {
1678
+ const tables = ownKeys(models)
1679
+ for (let index = 0; index < tables.length; index++) {
1680
+ const model = ownEntry(models, tables[index] ?? '')
1681
+ const reveals = model?.reveals ?? []
1682
+ for (let position = 0; position < reveals.length; position++) {
1683
+ const relation = reveals[position]?.relation ?? ''
1684
+ if (model !== undefined && !hasOwn(sources, relation)) {
1685
+ throw new PolicyError(
1686
+ `${model.name}: reveals.${relation} is matched through the rows that confer it, and only access views serve it; declare confers.${relation}`,
1687
+ )
1688
+ }
1689
+ }
1690
+ }
1086
1691
  }
1087
1692
 
1088
- function resolveChain(
1089
- table: ParsedTable,
1090
- byName: Readonly<Record<string, ParsedTable>>,
1091
- owners: Readonly<Record<string, ParsedTable>>,
1092
- containment: Containment,
1093
- chainOf: (table: ParsedTable) => readonly Container[],
1094
- ): Resolved {
1095
- /**
1096
- * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
1097
- * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
1098
- */
1099
- const above = (dimension: string): readonly Container[] => {
1100
- const owner = ownEntry(owners, dimension)
1101
- if (owner !== undefined) {
1102
- return chainOf(owner)
1693
+ type LinkedTable = Omit<TableModel, 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
1694
+
1695
+ /** A view of the column list: its columns, and whether a policy makes it a table of the layer. */
1696
+ interface ViewColumns {
1697
+ readonly columns: NameSet
1698
+ readonly policy: boolean
1699
+ }
1700
+
1701
+ const ACCESS_FIELDS = nameSet(['view', 'row', 'principal', 'member'])
1702
+
1703
+ /**
1704
+ * `access`: relation → the view whose rows name the table's rows the relation reaches. The view is one the column list
1705
+ * marks, `row` and each binding are its columns, and at least one binding is stated, so the subquery never reads every
1706
+ * row: `principal` is compared to the caller, `member` to the nodes of the relation's dimension it holds the relation in.
1707
+ */
1708
+ function parseAccess(
1709
+ table: LinkedTable,
1710
+ input: unknown,
1711
+ vocabulary: VocabularyModel,
1712
+ views: Readonly<Record<string, ViewColumns>>,
1713
+ ): readonly AccessModel[] {
1714
+ if (input === undefined) {
1715
+ return freeze([])
1716
+ }
1717
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1718
+ throw new PolicyError(`${table.name}: only a dimension or child table, or a child view, takes access; its rows are what a relation reaches`)
1719
+ }
1720
+ const declared = plainRecord(input, `${table.name}: access`)
1721
+ const relations = ownKeys(declared)
1722
+ const parsed: AccessModel[] = []
1723
+ for (let index = 0; index < relations.length; index++) {
1724
+ const relation = relations[index] ?? ''
1725
+ const what = `${table.name}: access.${relation}`
1726
+ if (!hasOwn(vocabulary.relations, relation)) {
1727
+ throw new PolicyError(`${what} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`)
1103
1728
  }
1104
- const container = ownEntry(containment, dimension)?.container
1105
- return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
1106
- }
1107
- const scope = table.scope
1108
- if (scope.mode === 'dimension') {
1109
- const container = scope.container
1110
- if (container === undefined) {
1111
- return { scope, chain: freeze([]) }
1729
+ const entry = plainRecord(ownEntry(declared, relation), what)
1730
+ onlyFields(entry, ACCESS_FIELDS, what)
1731
+ const view = ownEntry(entry, 'view')
1732
+ const named = typeof view === 'string' ? ownEntry(views, view) : undefined
1733
+ if (typeof view !== 'string' || named === undefined) {
1734
+ throw new PolicyError(`${what}.view names ${String(view)}, which the column list does not mark as a view`)
1112
1735
  }
1113
- const owner = ownEntry(owners, container.dimension)
1114
- if (owner !== undefined) {
1115
- requireReference(table, container, owner, (column) => `scope.in: { column: '${column}' }`)
1116
- requireCoveringKey(table, container, owner, chainOf(owner))
1736
+ // Read directly, the view would show the caller who else reaches which row.
1737
+ if (named.policy) {
1738
+ throw new PolicyError(`${what}.view names ${view}, which has a policy; an access view takes none, so only the relation's term reads it`)
1117
1739
  }
1118
- return { scope, chain: prepend(container, above(container.dimension)) }
1740
+ const columns = named.columns
1741
+ const viewColumn = (field: string, required: boolean): string | undefined => {
1742
+ const name = ownEntry(entry, field)
1743
+ if (name === undefined && !required) return undefined
1744
+ if (typeof name !== 'string' || !inSet(columns, name)) {
1745
+ throw new PolicyError(`${what}.${field} names ${String(name)}, which is not a column of ${view}`)
1746
+ }
1747
+ return name
1748
+ }
1749
+ const row = viewColumn('row', true) ?? ''
1750
+ const principal = viewColumn('principal', false)
1751
+ const member = viewColumn('member', false)
1752
+ if (principal === undefined && member === undefined) {
1753
+ throw new PolicyError(`${what} binds neither principal nor member: an access view is read for the caller, never whole`)
1754
+ }
1755
+ parsed[parsed.length] = freeze({ relation, dimension: ownEntry(vocabulary.relations, relation) ?? '', view, row, principal, member })
1119
1756
  }
1120
- if (scope.mode !== 'child') {
1121
- return { scope, chain: freeze([]) }
1757
+ return freeze(parsed)
1758
+ }
1759
+
1760
+ /** Every action a table names: its operations', `appRead`, `appCount` and its columns' own. */
1761
+ function tableActionNames(table: LinkedTable): NameSet {
1762
+ const names: string[] = []
1763
+ const lists = [table.actions.read, table.actions.insert, table.actions.update, table.actions.delete, table.actions.appRead, table.actions.appCount]
1764
+ for (let list = 0; list < lists.length; list++) {
1765
+ const actions = lists[list] ?? []
1766
+ for (let index = 0; index < actions.length; index++) {
1767
+ names[names.length] = actions[index] ?? ''
1768
+ }
1122
1769
  }
1123
- const parent = ownEntry(byName, scope.parent)
1124
- if (parent === undefined || parent.scope.mode !== 'dimension') {
1125
- throw new PolicyError(`${table.name}: the parent ${scope.parent} must be a dimension table`)
1770
+ const reads = ownKeys(table.columnReads)
1771
+ for (let index = 0; index < reads.length; index++) {
1772
+ const actions = ownEntry(table.columnReads, reads[index] ?? '') ?? []
1773
+ for (let position = 0; position < actions.length; position++) {
1774
+ names[names.length] = actions[position] ?? ''
1775
+ }
1126
1776
  }
1127
- const parentChain = chainOf(parent)
1128
- const expected: string[] = []
1129
- for (let index = 0; index < parentChain.length; index++) {
1130
- expected[index] = parentChain[index]?.column ?? ''
1777
+ const writes = ownKeys(table.columnWrites)
1778
+ for (let index = 0; index < writes.length; index++) {
1779
+ const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
1780
+ for (let position = 0; position < actions.length; position++) {
1781
+ names[names.length] = actions[position] ?? ''
1782
+ }
1131
1783
  }
1132
- const inherit = scope.inherit ?? freeze(expected)
1133
- const inherited = nameSet(inherit)
1784
+ return nameSet(names)
1785
+ }
1786
+
1787
+ /** The actions that write a table: its insert, update and delete actions and its columns' own write actions. */
1788
+ function writeActionNames(table: LinkedTable): NameSet {
1789
+ const names: string[] = []
1790
+ const lists = [table.actions.insert, table.actions.update, table.actions.delete]
1791
+ for (let list = 0; list < lists.length; list++) {
1792
+ const actions = lists[list] ?? []
1793
+ for (let index = 0; index < actions.length; index++) {
1794
+ names[names.length] = actions[index] ?? ''
1795
+ }
1796
+ }
1797
+ const writes = ownKeys(table.columnWrites)
1798
+ for (let index = 0; index < writes.length; index++) {
1799
+ const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
1800
+ for (let position = 0; position < actions.length; position++) {
1801
+ names[names.length] = actions[position] ?? ''
1802
+ }
1803
+ }
1804
+ return nameSet(names)
1805
+ }
1806
+
1807
+ /**
1808
+ * `when`: action → the condition a row must meet for it. An insert action's condition is judged on the inserted row and
1809
+ * the existing rows its paths reach (`insertProblem`); a reference table is read by every site and takes none.
1810
+ */
1811
+ function parseWhen(
1812
+ table: LinkedTable,
1813
+ root: ConditionTable,
1814
+ input: unknown,
1815
+ tables: (name: string) => ConditionTable | undefined,
1816
+ hops: HopRule,
1817
+ ): Readonly<Record<string, ConditionModel>> {
1818
+ if (input === undefined) {
1819
+ return freeze({})
1820
+ }
1821
+ if (table.scope.mode === 'reference') {
1822
+ throw new PolicyError(`${table.name}: a reference table takes no when; every site reads it`)
1823
+ }
1824
+ const declared = plainRecord(input, `${table.name}: when`)
1825
+ const named = tableActionNames(table)
1826
+ const actions = ownKeys(declared)
1827
+ const when: Record<string, ConditionModel> = {}
1828
+ for (let index = 0; index < actions.length; index++) {
1829
+ const action = actions[index] ?? ''
1830
+ if (!inSet(named, action)) {
1831
+ throw new PolicyError(`${table.name}: when.${action} names an action the table does not name (${namesOf(named).join(', ')})`)
1832
+ }
1833
+ if (table.actions.readAny && !inSet(writeActionNames(table), action)) {
1834
+ throw new PolicyError(
1835
+ `${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`,
1836
+ )
1837
+ }
1838
+ const what = `${table.name}: when.${action}`
1839
+ const condition = parseCondition(ownEntry(declared, action), root, tables, what, hops)
1840
+ // An insert reads the rows its foreign keys reach in its transaction, locked until the commit (`judgeInserted`).
1841
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1842
+ if (problem !== undefined) {
1843
+ throw new PolicyError(`${what}: ${problem}`)
1844
+ }
1845
+ setOwn(when, action, condition)
1846
+ }
1847
+ return freeze(when)
1848
+ }
1849
+
1850
+ /**
1851
+ * `relationWhen`: relation → action → a condition on the rows the relation reaches for the action, parsed as `when` is
1852
+ * (the same root, hop rule and insert rule). The relation must be the vocabulary's and the action the table's; whether
1853
+ * the relation reaches the table at all is checked once every table is parsed (`checkRelationWhenReach`).
1854
+ */
1855
+ function parseRelationWhen(
1856
+ table: LinkedTable,
1857
+ root: ConditionTable,
1858
+ input: unknown,
1859
+ vocabulary: VocabularyModel,
1860
+ tables: (name: string) => ConditionTable | undefined,
1861
+ hops: HopRule,
1862
+ ): Readonly<Record<string, Readonly<Record<string, ConditionModel>>>> {
1863
+ if (input === undefined) {
1864
+ return freeze({})
1865
+ }
1866
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1867
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table takes no relationWhen; no relation reaches its rows`)
1868
+ }
1869
+ const declared = plainRecord(input, `${table.name}: relationWhen`)
1870
+ const relations = ownKeys(declared)
1871
+ const named = tableActionNames(table)
1872
+ const parsed: Record<string, Readonly<Record<string, ConditionModel>>> = {}
1873
+ for (let index = 0; index < relations.length; index++) {
1874
+ const relation = relations[index] ?? ''
1875
+ if (!hasOwn(vocabulary.relations, relation)) {
1876
+ throw new PolicyError(
1877
+ `${table.name}: relationWhen.${relation} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`,
1878
+ )
1879
+ }
1880
+ const perAction = plainRecord(ownEntry(declared, relation), `${table.name}: relationWhen.${relation}`)
1881
+ const actions = ownKeys(perAction)
1882
+ if (actions.length === 0) {
1883
+ throw new PolicyError(`${table.name}: relationWhen.${relation} names no action`)
1884
+ }
1885
+ const conditions: Record<string, ConditionModel> = {}
1886
+ for (let position = 0; position < actions.length; position++) {
1887
+ const action = actions[position] ?? ''
1888
+ const what = `${table.name}: relationWhen.${relation}.${action}`
1889
+ if (!inSet(named, action)) {
1890
+ throw new PolicyError(`${what} names an action the table does not name (${namesOf(named).join(', ')})`)
1891
+ }
1892
+ const condition = parseCondition(ownEntry(perAction, action), root, tables, what, hops)
1893
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1894
+ if (problem !== undefined) {
1895
+ throw new PolicyError(`${what}: ${problem}`)
1896
+ }
1897
+ setOwn(conditions, action, condition)
1898
+ }
1899
+ setOwn(parsed, relation, freeze(conditions))
1900
+ }
1901
+ return freeze(parsed)
1902
+ }
1903
+
1904
+ /**
1905
+ * Every `relationWhen` names a relation that reaches the table for its action: the relation's dimension is the table's
1906
+ * or on its chain, a secondary path reaches it, or a reveal of the relation for the action reveals a node the table
1907
+ * lies at. A child view is reached through its parent row, so its parent is what the relation must reach.
1908
+ */
1909
+ function checkRelationWhenReach(models: Readonly<Record<string, TableModel>>, vocabulary: VocabularyModel): void {
1910
+ const names = ownKeys(models)
1911
+ const reveals: RevealModel[] = []
1912
+ for (let index = 0; index < names.length; index++) {
1913
+ const model = ownEntry(models, names[index] ?? '')
1914
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
1915
+ const reveal = model.reveals[position]
1916
+ if (reveal !== undefined) reveals[reveals.length] = reveal
1917
+ }
1918
+ }
1919
+ for (let index = 0; index < names.length; index++) {
1920
+ const model = ownEntry(models, names[index] ?? '')
1921
+ if (model === undefined) continue
1922
+ const reached = model.view && model.scope.mode === 'child' ? ownEntry(models, model.scope.parent) ?? model : model
1923
+ const relations = ownKeys(model.relationWhen)
1924
+ for (let position = 0; position < relations.length; position++) {
1925
+ const relation = relations[position] ?? ''
1926
+ const dimension = ownEntry(vocabulary.relations, relation) ?? ''
1927
+ const actions = ownKeys(ownEntry(model.relationWhen, relation) ?? {})
1928
+ for (let next = 0; next < actions.length; next++) {
1929
+ const action = actions[next] ?? ''
1930
+ if (!relationReaches(reached, relation, dimension, action, reveals)) {
1931
+ throw new PolicyError(
1932
+ `${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`,
1933
+ )
1934
+ }
1935
+ }
1936
+ }
1937
+ }
1938
+ }
1939
+
1940
+ /** Whether `relation` of `dimension` reaches a row of `model` for `action`, as the relation terms of the store find one. */
1941
+ function relationReaches(model: TableModel, relation: string, dimension: string, action: string, reveals: readonly RevealModel[]): boolean {
1942
+ if (nodeColumnOf(model, dimension) !== undefined || model.access.some((access) => access.relation === relation)) {
1943
+ return true
1944
+ }
1945
+ for (let index = 0; index < model.readThrough.length; index++) {
1946
+ const path = model.readThrough[index]
1947
+ if (path === undefined) continue
1948
+ if (path.dimension === dimension) return true
1949
+ for (let link = 0; link < path.chain.length; link++) {
1950
+ if (path.chain[link]?.dimension === dimension) return true
1951
+ }
1952
+ }
1953
+ for (let index = 0; index < reveals.length; index++) {
1954
+ const reveal = reveals[index]
1955
+ if (
1956
+ reveal !== undefined && reveal.relation === relation && includes(reveal.actions, action) && nodeColumnOf(model, reveal.dimension) !== undefined
1957
+ ) {
1958
+ return true
1959
+ }
1960
+ }
1961
+ return false
1962
+ }
1963
+
1964
+ /**
1965
+ * 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
1966
+ * column list declares, so a path follows it to the parent row, and the parent's own foreign keys from there.
1967
+ */
1968
+ function conditionRoot(table: LinkedTable, byName: Readonly<Record<string, ParsedTable>>): ConditionTable {
1969
+ const parent = table.view && table.scope.mode === 'child' ? ownEntry(byName, table.scope.parent) : undefined
1970
+ if (table.scope.mode !== 'child' || parent === undefined || parent.scope.mode !== 'dimension') {
1971
+ return table
1972
+ }
1973
+ const foreignKeys: ForeignKey[] = []
1974
+ for (let index = 0; index < table.foreignKeys.length; index++) {
1975
+ const key = table.foreignKeys[index]
1976
+ if (key !== undefined) foreignKeys[foreignKeys.length] = key
1977
+ }
1978
+ foreignKeys[foreignKeys.length] = freeze({ columns: freeze([table.scope.column]), table: parent.name, references: freeze([parent.scope.key]) })
1979
+ return freeze({ ...table, foreignKeys: freeze(foreignKeys) })
1980
+ }
1981
+
1982
+ /** A dimension's owning table, resolved: what a secondary path's column references. */
1983
+ interface ResolvedOwner extends Resolved {
1984
+ readonly name: string
1985
+ }
1986
+
1987
+ /**
1988
+ * `readThrough`: dimension → the column a `Within`'s read reaches a row through. The dimension lies outside the row's chain and a table
1989
+ * owns it; the column is a foreign key to that table's key that no update writes, and it covers every ancestor the two
1990
+ * chains share, so the database keeps the node in the row's own tenant. `<column>.<column>` reads the row through its
1991
+ * nearest container's own path instead (`containerPath`).
1992
+ */
1993
+ function parseReadThrough(
1994
+ table: LinkedTable,
1995
+ input: unknown,
1996
+ vocabulary: VocabularyModel,
1997
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1998
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1999
+ ): readonly SecondaryPath[] {
2000
+ if (input === undefined) {
2001
+ return freeze([])
2002
+ }
2003
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2004
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table has no containment, so no secondary read path`)
2005
+ }
2006
+ if (table.queue !== undefined) {
2007
+ throw new PolicyError(`${table.name}: a queue table has no secondary read path; a claim follows containment only`)
2008
+ }
2009
+ const declared = plainRecord(input, `${table.name}: readThrough`)
2010
+ const dimensions = ownKeys(declared)
2011
+ const paths: SecondaryPath[] = []
2012
+ for (let index = 0; index < dimensions.length; index++) {
2013
+ const dimension = dimensions[index] ?? ''
2014
+ const what = `${table.name}: readThrough.${dimension}`
2015
+ if (!hasOwn(vocabulary.dimensions, dimension)) {
2016
+ throw new PolicyError(`${what}: ${dimension} is not a dimension of the vocabulary`)
2017
+ }
2018
+ if (nodeColumnOf(table, dimension) !== undefined) {
2019
+ throw new PolicyError(`${what}: ${table.name} already lies in ${dimension}; a secondary path reaches a dimension outside its chain`)
2020
+ }
2021
+ const column = ownEntry(declared, dimension)
2022
+ const segments = typeof column === 'string' ? splitPath(column) : []
2023
+ if (segments.length === 2) {
2024
+ paths[paths.length] = throughContainer(table, segments[0] ?? '', segments[1] ?? '', dimension, ownerOf, containerPath, what)
2025
+ continue
2026
+ }
2027
+ if (typeof column !== 'string' || !inSet(table.columns, column)) {
2028
+ throw new PolicyError(`${what} names ${String(column)}, which is not a column of ${table.name}`)
2029
+ }
2030
+ if (inSet(table.update, column) || hasOwn(table.columnWrites, column) || hasOwn(table.files, column)) {
2031
+ throw new PolicyError(`${what}: ${column} places the row on a read path, so no update writes it`)
2032
+ }
2033
+ if (column === table.version || column === table.createdBy || column === table.scope.key) {
2034
+ throw new PolicyError(`${what}: ${column} is a column the layer writes itself, not a node of ${dimension}`)
2035
+ }
2036
+ for (let position = 0; position < table.chain.length; position++) {
2037
+ if (table.chain[position]?.column === column) {
2038
+ throw new PolicyError(`${what}: ${column} is a containment column of ${table.name}`)
2039
+ }
2040
+ }
2041
+ const owner = ownerOf(dimension)
2042
+ if (owner === undefined || owner.scope.mode !== 'dimension') {
2043
+ throw new PolicyError(`${what}: no table owns ${dimension}, so no foreign key ties ${column} to a node of it`)
2044
+ }
2045
+ const pairs = tenantPairs(table, column, owner.scope.key, owner.chain)
2046
+ const covered = holdsExactly(table.foreignKeys, owner.name, pairs)
2047
+ if (!covered) {
2048
+ const columns: string[] = []
2049
+ const referenced: string[] = []
2050
+ for (let position = 0; position < pairs.length; position++) {
2051
+ columns[position] = pairs[position]?.[0] ?? ''
2052
+ referenced[position] = pairs[position]?.[1] ?? ''
2053
+ }
2054
+ throw new PolicyError(
2055
+ `${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 (${
2056
+ columns.join(', ')
2057
+ }) references ${owner.name} (${referenced.join(', ')})`,
2058
+ )
2059
+ }
2060
+ requireNotNullAncestors(what, table, pairs)
2061
+ paths[paths.length] = freeze({ dimension, column, table: owner.name, key: owner.scope.key, chain: owner.chain, via: undefined, writes: freeze([]) })
2062
+ }
2063
+ return freeze(paths)
2064
+ }
2065
+
2066
+ /**
2067
+ * `readThrough.<dimension>: '<link>.<column>'`: the row is read through the path its nearest container declares for the
2068
+ * dimension. `<link>` is the row's nearest containment column, which places it in the container now, and `<column>` the
2069
+ * container's own path column, which no update of the container writes; so the read follows containment and the
2070
+ * container's path, and nothing the row's writer picks.
2071
+ */
2072
+ function throughContainer(
2073
+ table: LinkedTable,
2074
+ link: string,
2075
+ column: string,
2076
+ dimension: string,
2077
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
2078
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
2079
+ what: string,
2080
+ ): SecondaryPath {
2081
+ const nearest = table.chain[0]
2082
+ if (nearest === undefined || nearest.column !== link) {
2083
+ throw new PolicyError(
2084
+ `${what}: ${link} is not ${table.name}'s nearest containment column${
2085
+ nearest === undefined ? '' : ` (${nearest.column})`
2086
+ }; a path through a container starts at the row's own container`,
2087
+ )
2088
+ }
2089
+ const container = ownerOf(nearest.dimension)
2090
+ if (container === undefined || container.scope.mode !== 'dimension') {
2091
+ throw new PolicyError(`${what}: no table owns ${nearest.dimension}, so no container row holds a path to ${dimension}`)
2092
+ }
2093
+ const path = containerPath(container.name, dimension)
2094
+ if (path === undefined) {
2095
+ throw new PolicyError(
2096
+ `${what}: ${container.name} declares no readThrough.${dimension} through a column of its own, so ${table.name} has no container path to follow`,
2097
+ )
2098
+ }
2099
+ if (path.column !== column) {
2100
+ throw new PolicyError(`${what}: ${container.name} reads ${dimension} through ${path.column}, not ${column}`)
2101
+ }
2102
+ return freeze({ ...path, via: freeze({ column: link, table: container.name, key: container.scope.key }), writes: freeze([]) })
2103
+ }
2104
+
2105
+ /**
2106
+ * `writeThrough`: a dimension the table reads through → the actions a `Ref` held through that path holds. Each is an
2107
+ * action of the vocabulary: the table's own, or one a reveal matched through the path or a table below reaches the row
2108
+ * for. The path's column is the delegation: whoever inserts it must hold every listed action at the node it names, and
2109
+ * for a path through the container, whoever inserts the container's column (`pathWriters`).
2110
+ */
2111
+ function parseWriteThrough(
2112
+ table: LinkedTable,
2113
+ readThrough: readonly SecondaryPath[],
2114
+ input: unknown,
2115
+ vocabulary: VocabularyModel,
2116
+ ): readonly SecondaryPath[] {
2117
+ if (input === undefined) {
2118
+ return readThrough
2119
+ }
2120
+ const declared = plainRecord(input, `${table.name}: writeThrough`)
2121
+ const dimensions = ownKeys(declared)
2122
+ const writes: Record<string, readonly string[]> = {}
2123
+ for (let index = 0; index < dimensions.length; index++) {
2124
+ const dimension = dimensions[index] ?? ''
2125
+ const what = `${table.name}: writeThrough.${dimension}`
2126
+ let declaredPath = false
2127
+ for (let position = 0; position < readThrough.length; position++) {
2128
+ if (readThrough[position]?.dimension === dimension) declaredPath = true
2129
+ }
2130
+ if (!declaredPath) {
2131
+ throw new PolicyError(`${what}: ${table.name} reads no path to ${dimension}; declare readThrough.${dimension} first`)
2132
+ }
2133
+ const actions = parseList(ownEntry(declared, dimension), (action) => {
2134
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2135
+ throw new PolicyError(`${what} names ${String(action)}, which is not an action of the vocabulary`)
2136
+ }
2137
+ return action
2138
+ })
2139
+ if (actions === undefined) {
2140
+ throw new PolicyError(`${what} takes a plain array of the vocabulary's actions`)
2141
+ }
2142
+ const listed: string[] = []
2143
+ for (let position = 0; position < actions.length; position++) {
2144
+ const action = actions[position] ?? ''
2145
+ if (!includes(listed, action)) listed[listed.length] = action
2146
+ }
2147
+ if (listed.length === 0) {
2148
+ throw new PolicyError(`${what} names no action; leave the dimension out to hold nothing through the path`)
2149
+ }
2150
+ setOwn(writes, dimension, freeze(listed))
2151
+ }
2152
+ const paths: SecondaryPath[] = []
2153
+ for (let index = 0; index < readThrough.length; index++) {
2154
+ const path = readThrough[index]
2155
+ if (path === undefined) continue
2156
+ const listed = ownEntry(writes, path.dimension)
2157
+ paths[paths.length] = listed === undefined ? path : freeze({ ...path, writes: listed })
2158
+ }
2159
+ return freeze(paths)
2160
+ }
2161
+
2162
+ /**
2163
+ * `reveals`: relation → the ancestor its rows reveal. The relation is of the table's own dimension, so its term
2164
+ * 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
2165
+ * revealed node follows the row's containment now. A queue table reveals nothing: a claim rewrites its rows.
2166
+ */
2167
+ function parseReveals(
2168
+ table: LinkedTable,
2169
+ readThrough: readonly SecondaryPath[],
2170
+ input: unknown,
2171
+ vocabulary: VocabularyModel,
2172
+ tables: (name: string) => ConditionTable | undefined,
2173
+ hops: HopRule,
2174
+ ): readonly RevealModel[] {
2175
+ if (input === undefined) {
2176
+ return freeze([])
2177
+ }
2178
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2179
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table reveals nothing; its rows lie at no node a relation reaches`)
2180
+ }
2181
+ if (table.queue !== undefined) {
2182
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2183
+ }
2184
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2185
+ const key = table.scope.key
2186
+ const declared = plainRecord(input, `${table.name}: reveals`)
2187
+ const names = ownKeys(declared)
2188
+ const reveals: RevealModel[] = []
2189
+ for (let index = 0; index < names.length; index++) {
2190
+ const relation = names[index] ?? ''
2191
+ const what = `${table.name}: reveals.${relation}`
2192
+ const dimension = ownEntry(vocabulary.relations, relation)
2193
+ if (dimension === undefined) {
2194
+ throw new PolicyError(
2195
+ `${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(vocabulary.relations).join(', ') || 'none'})`,
2196
+ )
2197
+ }
2198
+ const paths: SecondaryPath[] = []
2199
+ for (let position = 0; dimension !== own && position < readThrough.length; position++) {
2200
+ const path = readThrough[position]
2201
+ if (path !== undefined && (path.dimension === dimension || containsLink(path.chain, dimension))) paths[paths.length] = path
2202
+ }
2203
+ if (dimension !== own && paths.length !== 1) {
2204
+ throw new PolicyError(
2205
+ paths.length === 0
2206
+ ? `${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`
2207
+ : `${what}: ${table.name} reads through more than one path to ${dimension}, so the reveal matches no one column`,
2208
+ )
2209
+ }
2210
+ const policy = plainRecord(ownEntry(declared, relation), what)
2211
+ onlyFields(policy, REVEALS_FIELDS, what)
2212
+ const { to, column, actions: listed, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2213
+ const path = paths[0]
2214
+ if (path?.via !== undefined) {
2215
+ // The relation's nodes would sit one subquery below the container's, past the guard's bound under a reveal.
2216
+ throw new PolicyError(
2217
+ `${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`,
2218
+ )
2219
+ }
2220
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2221
+ throw new PolicyError(
2222
+ `${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`,
2223
+ )
2224
+ }
2225
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2226
+ reveals[reveals.length] = freeze({ relation, table: table.name, key, path, assign, dimension: to, column, actions: listed, when })
2227
+ }
2228
+ return freeze(reveals)
2229
+ }
2230
+
2231
+ /** A reveal's `to`, a dimension of the table's chain with the column that holds it, its listed actions, and its `when`. */
2232
+ function parseRevealed(
2233
+ table: LinkedTable,
2234
+ policy: Readonly<Record<string, unknown>>,
2235
+ what: string,
2236
+ vocabulary: VocabularyModel,
2237
+ tables: (name: string) => ConditionTable | undefined,
2238
+ hops: HopRule,
2239
+ ): { readonly to: string; readonly column: string; readonly actions: readonly string[]; readonly when: ConditionModel | undefined } {
2240
+ const to = ownEntry(policy, 'to')
2241
+ let column: string | undefined
2242
+ for (let position = 0; position < table.chain.length; position++) {
2243
+ const link = table.chain[position]
2244
+ if (link !== undefined && link.dimension === to) column = link.column
2245
+ }
2246
+ if (typeof to !== 'string' || column === undefined) {
2247
+ const above: string[] = []
2248
+ for (let position = 0; position < table.chain.length; position++) {
2249
+ above[above.length] = table.chain[position]?.dimension ?? ''
2250
+ }
2251
+ throw new PolicyError(
2252
+ `${what}.to names ${String(to)}, which is not a dimension of ${table.name}'s chain (${above.join(', ') || 'none'})`,
2253
+ )
2254
+ }
2255
+ const actions = parseList(ownEntry(policy, 'actions'), (action) => {
2256
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2257
+ throw new PolicyError(`${what}.actions names ${String(action)}, which is not an action of the vocabulary`)
2258
+ }
2259
+ return action
2260
+ })
2261
+ if (actions === undefined) {
2262
+ throw new PolicyError(`${what}.actions takes a plain array of the vocabulary's actions`)
2263
+ }
2264
+ const listed: string[] = []
2265
+ for (let position = 0; position < actions.length; position++) {
2266
+ const action = actions[position] ?? ''
2267
+ if (!includes(listed, action)) listed[listed.length] = action
2268
+ }
2269
+ if (listed.length === 0) {
2270
+ throw new PolicyError(`${what}.actions names no action; a reveal holds the actions it lists, and no other`)
2271
+ }
2272
+ const whenInput = ownEntry(policy, 'when')
2273
+ const when = whenInput === undefined ? undefined : parseCondition(whenInput, table, tables, `${what}.when`, hops)
2274
+ return { to, column, actions: freeze(listed), when }
2275
+ }
2276
+
2277
+ /**
2278
+ * `memberReveals`: the table's own dimension, or one it reads through, → the ancestor its rows reveal to a grant at the
2279
+ * node. By its own key only a dimension table reveals so: the layer generates the key, so no writer picks a node someone
2280
+ * already holds a grant at. Through a direct path the writer picks it, so an insertable table states `assign`, and the
2281
+ * row reveals its nearest container only, whose column no move of an ancestor rewrites. A queue table's rows move on
2282
+ * every claim.
2283
+ */
2284
+ function parseMemberReveals(
2285
+ table: LinkedTable,
2286
+ readThrough: readonly SecondaryPath[],
2287
+ input: unknown,
2288
+ vocabulary: VocabularyModel,
2289
+ tables: (name: string) => ConditionTable | undefined,
2290
+ hops: HopRule,
2291
+ ): readonly MemberRevealModel[] {
2292
+ if (input === undefined) {
2293
+ return freeze([])
2294
+ }
2295
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2296
+ throw new PolicyError(
2297
+ `${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`,
2298
+ )
2299
+ }
2300
+ if (table.queue !== undefined) {
2301
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2302
+ }
2303
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2304
+ const declared = plainRecord(input, `${table.name}: memberReveals`)
2305
+ const names = ownKeys(declared)
2306
+ const reveals: MemberRevealModel[] = []
2307
+ for (let index = 0; index < names.length; index++) {
2308
+ const source = names[index] ?? ''
2309
+ const what = `${table.name}: memberReveals.${source}`
2310
+ let path: SecondaryPath | undefined
2311
+ for (let position = 0; source !== own && position < readThrough.length; position++) {
2312
+ if (readThrough[position]?.dimension === source) path = readThrough[position]
2313
+ }
2314
+ if (source !== own && path === undefined) {
2315
+ throw new PolicyError(
2316
+ `${what}: ${source} is neither the own dimension of ${table.name} (${
2317
+ own ?? 'none'
2318
+ }) nor one it reads through; a row reveals to a grant at its own node or at the node its path names`,
2319
+ )
2320
+ }
2321
+ const policy = plainRecord(ownEntry(declared, source), what)
2322
+ onlyFields(policy, MEMBER_REVEALS_FIELDS, what)
2323
+ const { to, column, actions, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2324
+ if (path?.via !== undefined) {
2325
+ throw new PolicyError(
2326
+ `${what}: ${table.name} reads ${source} through its container ${path.via.table}; declare the member reveal on ${path.via.table}`,
2327
+ )
2328
+ }
2329
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2330
+ throw new PolicyError(
2331
+ `${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`,
2332
+ )
2333
+ }
2334
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2335
+ const key = path === undefined ? table.scope.key : path.column
2336
+ reveals[reveals.length] = freeze({ source, table: table.name, key, path, assign, dimension: to, column, actions, when })
2337
+ }
2338
+ return freeze(reveals)
2339
+ }
2340
+
2341
+ /**
2342
+ * A reveal matched through a secondary path delegates on insert, since the row's writer picks the node: a table with an
2343
+ * insert action states the bound, as a relation source does. A reveal by the row's own key delegates nothing.
2344
+ */
2345
+ function parseRevealAssign(table: LinkedTable, path: SecondaryPath | undefined, input: unknown, what: string): RevealModel['assign'] {
2346
+ if (path === undefined || table.actions.insert.length === 0) {
2347
+ if (input !== undefined) {
2348
+ throw new PolicyError(
2349
+ path === undefined
2350
+ ? `${what}.assign: the reveal matches the row's own key, so no writer picks its node`
2351
+ : `${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`,
2352
+ )
2353
+ }
2354
+ return undefined
2355
+ }
2356
+ if (input === undefined) {
2357
+ throw new PolicyError(
2358
+ `${what}: inserting a row of ${table.name} (${
2359
+ table.actions.insert.join(', ')
2360
+ }) picks the ${path.dimension} node the reveal holds at; state assign: { self? }`,
2361
+ )
2362
+ }
2363
+ const assign = plainRecord(input, `${what}.assign`)
2364
+ onlyFields(assign, REVEAL_ASSIGN_FIELDS, `${what}.assign`)
2365
+ const self = ownEntry(assign, 'self')
2366
+ if (self !== undefined && self !== true) {
2367
+ throw new PolicyError(`${what}.assign.self takes true`)
2368
+ }
2369
+ return freeze({ self: self === true })
2370
+ }
2371
+
2372
+ /**
2373
+ * A row of the table hands out access that its writer places: it confers a relation, reveals through a path, or reveals
2374
+ * its ancestor to the grants at its node. Such a row is written only through the handles, and never moves.
2375
+ */
2376
+ export function delegates(model: TableModel): boolean {
2377
+ for (let index = 0; index < model.reveals.length; index++) {
2378
+ if (model.reveals[index]?.path !== undefined) return true
2379
+ }
2380
+ return model.confers.length > 0 || model.memberReveals.length > 0
2381
+ }
2382
+
2383
+ /**
2384
+ * The tables whose rows hand out access, which no raw statement writes, lowercased as the tag compares names: a relation
2385
+ * source, a path reveal or a path column that holds actions (`writeThrough`), whose writer the layer bounds; a
2386
+ * member-revealing table, whose key the layer generates so no write revives a node a stale grant still names; and the
2387
+ * tables a principal path or a relation's condition reads, whose columns decide whom a source row names and what it
2388
+ * confers.
2389
+ */
2390
+ export function accessTablesOf(models: TableModels): readonly string[] {
2391
+ const tables: string[] = []
2392
+ const names = ownKeys(models)
2393
+ for (let index = 0; index < names.length; index++) {
2394
+ const model = modelOf(models, names[index] ?? '')
2395
+ if (model !== undefined && (delegates(model) || pathWriters(models, model).length > 0)) {
2396
+ tables[tables.length] = model.name.toLowerCase()
2397
+ }
2398
+ for (let position = 0; model !== undefined && position < model.confers.length; position++) {
2399
+ const source = model.confers[position]
2400
+ const path = source?.principalPath
2401
+ if (path !== undefined) tables[tables.length] = path.table.toLowerCase()
2402
+ if (source?.when !== undefined) {
2403
+ conditionReach(source.when, (table) => {
2404
+ tables[tables.length] = table.toLowerCase()
2405
+ })
2406
+ }
2407
+ }
2408
+ }
2409
+ return tables
2410
+ }
2411
+
2412
+ /** A path column whose insert hands out the listed actions at the node it names: the bound its writer is held to. */
2413
+ export interface PathWriter {
2414
+ readonly path: SecondaryPath
2415
+ /** The path's own `writes` and those of every table that reads the same dimension through this table's column. */
2416
+ readonly actions: readonly string[]
2417
+ }
2418
+
2419
+ /**
2420
+ * The columns of `model` whose insert hands out actions through a secondary path: its own paths that hold actions, and
2421
+ * its paths that a table below follows through it (`'<link>.<column>'`) with actions of its own. Such a table is written
2422
+ * only through the handles, so no write sets the column past the bound.
2423
+ */
2424
+ export function pathWriters(models: Readonly<Record<string, TableModel>>, model: TableModel): readonly PathWriter[] {
2425
+ const writers: PathWriter[] = []
2426
+ const names = ownKeys(models)
2427
+ for (let index = 0; index < model.readThrough.length; index++) {
2428
+ const path = model.readThrough[index]
2429
+ if (path === undefined || path.via !== undefined) continue
2430
+ const actions: string[] = []
2431
+ for (let position = 0; position < path.writes.length; position++) {
2432
+ const action = path.writes[position] ?? ''
2433
+ if (!includes(actions, action)) actions[actions.length] = action
2434
+ }
2435
+ for (let position = 0; position < names.length; position++) {
2436
+ const below = ownEntry(models, names[position] ?? '')
2437
+ for (let at = 0; below !== undefined && at < below.readThrough.length; at++) {
2438
+ const through = below.readThrough[at]
2439
+ if (through?.via?.table !== model.name || through.dimension !== path.dimension) continue
2440
+ for (let written = 0; written < through.writes.length; written++) {
2441
+ const action = through.writes[written] ?? ''
2442
+ if (!includes(actions, action)) actions[actions.length] = action
2443
+ }
2444
+ }
2445
+ }
2446
+ if (actions.length > 0) writers[writers.length] = freeze({ path, actions: freeze(actions) })
2447
+ }
2448
+ return freeze(writers)
2449
+ }
2450
+
2451
+ function containsLink(chain: readonly Container[], dimension: string): boolean {
2452
+ for (let index = 0; index < chain.length; index++) {
2453
+ if (chain[index]?.dimension === dimension) return true
2454
+ }
2455
+ return false
2456
+ }
2457
+
2458
+ /** The column of `table` that places a row at a node of `dimension`: its key for its own dimension, else a chain link. */
2459
+ export function nodeColumnOf(table: Pick<TableModel, 'scope' | 'chain'>, dimension: string): string | undefined {
2460
+ if (table.scope.mode === 'dimension' && table.scope.dimension === dimension) {
2461
+ return table.scope.key
2462
+ }
2463
+ for (let index = 0; index < table.chain.length; index++) {
2464
+ const link = table.chain[index]
2465
+ if (link?.dimension === dimension) {
2466
+ return link.column
2467
+ }
2468
+ }
2469
+ return undefined
2470
+ }
2471
+
2472
+ /**
2473
+ * `confers`: relation → its columns on this table. The node is the table's own column for the relation's dimension,
2474
+ * which the layer stamps from the inserting Ref, so a row names only a node its writer acts on. The principal, the
2475
+ * node, the expiry and the condition's columns are never updated: a row that confers more is a new row, which its
2476
+ * insert action bounds (`assign`).
2477
+ */
2478
+ function parseConfers(
2479
+ table: LinkedTable,
2480
+ input: unknown,
2481
+ relations: Readonly<Record<string, string>>,
2482
+ tables: (name: string) => ConditionTable | undefined,
2483
+ linked: (name: string) => LinkedTable | undefined,
2484
+ hops: HopRule,
2485
+ ): readonly RelationSource[] {
2486
+ if (input === undefined) {
2487
+ return freeze([])
2488
+ }
2489
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2490
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table confers no relation; its rows lie at no node`)
2491
+ }
2492
+ if (table.view) {
2493
+ throw new PolicyError(
2494
+ `${table.name}: a view confers no relation; its rows change with every write to the tables it reads, which no delegation bound sees`,
2495
+ )
2496
+ }
2497
+ if (table.queue !== undefined) {
2498
+ // A claim, a requeue and `done: true` rewrite `due` and `version` past every update-column check.
2499
+ throw new PolicyError(`${table.name}: a queue table confers no relation; the layer rewrites its rows on every claim`)
2500
+ }
2501
+ const declared = plainRecord(input, `${table.name}: confers`)
2502
+ const names = ownKeys(declared)
2503
+ const sources: RelationSource[] = []
2504
+ for (let index = 0; index < names.length; index++) {
2505
+ const relation = names[index] ?? ''
2506
+ const what = `${table.name}: confers.${relation}`
2507
+ const dimension = ownEntry(relations, relation)
2508
+ if (dimension === undefined) {
2509
+ throw new PolicyError(`${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(relations).join(', ') || 'none'})`)
2510
+ }
2511
+ const policy = plainRecord(ownEntry(declared, relation), what)
2512
+ onlyFields(policy, CONFERS_FIELDS, what)
2513
+ const column = (value: unknown, field: string): string => {
2514
+ if (!inSet(table.columns, value)) {
2515
+ throw new PolicyError(`${what}.${field} names ${String(value)}, which is not a column of ${table.name}`)
2516
+ }
2517
+ return value
2518
+ }
2519
+ const { column: principal, path: principalPath } = parsePrincipal(table, ownEntry(policy, 'principal'), linked, what)
2520
+ const placed = nodeColumnOf(table, dimension)
2521
+ if (placed === undefined) {
2522
+ throw new PolicyError(`${what}: ${table.name} does not lie in ${dimension}, the relation's dimension, so its rows name no node of it`)
2523
+ }
2524
+ const own = table.scope.mode === 'dimension' && table.scope.dimension === dimension
2525
+ if (!own && table.chain[0]?.column !== placed) {
2526
+ // An inherited column follows a move of an ancestor (ON UPDATE CASCADE), which no delegation bound sees.
2527
+ throw new PolicyError(
2528
+ `${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`,
2529
+ )
2530
+ }
2531
+ const nodeInput = ownEntry(policy, 'node')
2532
+ const node = nodeInput === undefined ? placed : column(nodeInput, 'node')
2533
+ if (node !== placed) {
2534
+ throw new PolicyError(`${what}.node is ${node}, but a row's ${dimension} is ${placed}: the node is the column the inserting Ref stamps`)
2535
+ }
2536
+ const expiresInput = ownEntry(policy, 'expires')
2537
+ const expires = expiresInput === undefined ? undefined : column(expiresInput, 'expires')
2538
+ if (expires !== undefined && !inSet(table.timestamps, expires)) {
2539
+ throw new PolicyError(`${what}.expires names ${expires}, which is not a timestamp column`)
2540
+ }
2541
+ const whenInput = ownEntry(policy, 'when')
2542
+ const when = whenInput === undefined ? undefined : parseSourceWhen(table, whenInput, tables, linked, hops, `${what}.when`)
2543
+ const fixed: string[] = [principal]
2544
+ if (expires !== undefined) fixed[fixed.length] = expires
2545
+ const read = when === undefined ? [] : conditionColumns(when)
2546
+ for (let position = 0; position < read.length; position++) {
2547
+ fixed[fixed.length] = read[position] ?? ''
2548
+ }
2549
+ for (let position = 0; position < fixed.length; position++) {
2550
+ const name = fixed[position] ?? ''
2551
+ if (name === table.version) {
2552
+ throw new PolicyError(`${what}: ${name} is the version column, which every update rewrites; it decides nothing a row confers`)
2553
+ }
2554
+ if (inSet(table.update, name) || hasOwn(table.columnWrites, name)) {
2555
+ throw new PolicyError(`${what}: ${name} decides what a row confers, so no update writes it; replace the row instead`)
2556
+ }
2557
+ }
2558
+ if (principal === node || principal === table.version || hasOwn(table.files, principal)) {
2559
+ throw new PolicyError(`${what}.principal ${principal} is a column the layer stamps; it holds the principal the row names`)
2560
+ }
2561
+ if (principalPath === undefined) refuseReferencing(table, principal, `${what}.principal`, 'holds the principal', undefined)
2562
+ const assign = parseAssign(table, policy, expires, what)
2563
+ if (principal === table.createdBy && principalPath !== undefined) {
2564
+ throw new PolicyError(`${what}.principal ${principal} is the createdBy column, which holds a principal; a principal path starts at a foreign key`)
2565
+ }
2566
+ // The layer stamps createdBy with the writer, so every row such a source confers names its writer.
2567
+ if (principal === table.createdBy && assign !== undefined && !assign.self) {
2568
+ throw new PolicyError(
2569
+ `${what}.principal ${principal} is the createdBy column, so every inserted row names its writer: state assign: { self: true }`,
2570
+ )
2571
+ }
2572
+ sources[sources.length] = freeze({ relation, dimension, table: table.name, principal, principalPath, node, expires, when, assign })
2573
+ }
2574
+ return freeze(sources)
2575
+ }
2576
+
2577
+ /**
2578
+ * `confers.<relation>.when`: a condition on the source row, which may follow one foreign key to the row it names (the far
2579
+ * side of a many-to-many source). What it reads decides whom the relation reaches, so it is held as the principal is:
2580
+ * no update writes it, on the source or on the far row, and nothing a write elsewhere cascades rewrites it.
2581
+ */
2582
+ function parseSourceWhen(
2583
+ table: LinkedTable,
2584
+ input: unknown,
2585
+ tables: (name: string) => ConditionTable | undefined,
2586
+ linked: (name: string) => LinkedTable | undefined,
2587
+ hops: HopRule,
2588
+ what: string,
2589
+ ): ConditionModel {
2590
+ const condition = parseCondition(input, table, tables, what, hops)
2591
+ const visit = (node: ConditionModel): void => {
2592
+ if (node.kind === 'not') {
2593
+ visit(node.term)
2594
+ } else if (node.kind === 'some') {
2595
+ // Every writer of the naming table adds and removes such rows; no rule holds a set of rows still.
2596
+ throw new PolicyError(
2597
+ `${what}: a relation's condition takes no some or none: the rows naming a source row are written outside its delegation bound`,
2598
+ )
2599
+ } else if (node.kind === 'test') {
2600
+ const hop = node.hops[0]
2601
+ if (node.hops.length > 1) {
2602
+ // The far row is read inside every relation term, beside a principal path, four subqueries deep under a reveal.
2603
+ throw new PolicyError(`${what}: a relation's condition follows at most one foreign key, to the row the source row names`)
2604
+ }
2605
+ if (hop !== undefined) farColumn(table, hop, node.column, linked, what)
2606
+ } else {
2607
+ for (let index = 0; index < node.terms.length; index++) {
2608
+ const term = node.terms[index]
2609
+ if (term !== undefined) visit(term)
2610
+ }
2611
+ }
2612
+ }
2613
+ visit(condition)
2614
+ return condition
2615
+ }
2616
+
2617
+ /** The column a relation's condition tests on the row one foreign key of the source names: fixed like a principal. */
2618
+ function farColumn(
2619
+ table: LinkedTable,
2620
+ hop: ConditionHop,
2621
+ held: string,
2622
+ linked: (name: string) => LinkedTable | undefined,
2623
+ what: string,
2624
+ ): void {
2625
+ refuseReferencing(table, hop.column, what, "starts the condition's path", hop)
2626
+ const target = linked(hop.table)
2627
+ if (target === undefined) {
2628
+ throw new PolicyError(`${what}: ${table.name}.${hop.column} references ${hop.table}, which has no policy`)
2629
+ }
2630
+ if (target.view) {
2631
+ throw new PolicyError(`${what}: ${hop.table} is a view, whose rows change with every write to the tables it reads`)
2632
+ }
2633
+ if (target.queue !== undefined) {
2634
+ throw new PolicyError(`${what}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2635
+ }
2636
+ const scope = target.scope
2637
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2638
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2639
+ throw new PolicyError(
2640
+ `${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`,
2641
+ )
2642
+ }
2643
+ if (scope.mode !== 'reference') {
2644
+ refuseReferencing(target, scope.key, what, "is the key the condition's path follows", undefined)
2645
+ }
2646
+ if (held === target.version) {
2647
+ throw new PolicyError(`${what}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2648
+ }
2649
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2650
+ throw new PolicyError(`${what}: ${hop.table}.${held} decides what a row confers, so no update of ${hop.table} writes it; replace the row instead`)
2651
+ }
2652
+ if (chainColumn(target, held)) {
2653
+ throw new PolicyError(`${what}: ${hop.table}.${held} is a containment column, which a move rewrites; it decides nothing a row confers`)
2654
+ }
2655
+ refuseReferencing(target, held, what, 'decides what a row confers', undefined)
2656
+ }
2657
+
2658
+ /**
2659
+ * `confers.<relation>.principal`: a column of the source, or `<column>.<principal column>`, one single-column foreign key
2660
+ * of the source into the key of a table P whose column holds the principal. Every column that decides the principal is
2661
+ * one no update writes, on P as on the source, so a row names someone else only as a new row its insert bounds.
2662
+ */
2663
+ function parsePrincipal(
2664
+ table: LinkedTable,
2665
+ input: unknown,
2666
+ linked: (name: string) => LinkedTable | undefined,
2667
+ what: string,
2668
+ ): { readonly column: string; readonly path: PrincipalPath | undefined } {
2669
+ const field = `${what}.principal`
2670
+ if (typeof input !== 'string') {
2671
+ throw new PolicyError(`${field} names ${String(input)}, which is not a column of ${table.name}`)
2672
+ }
2673
+ const segments = splitPath(input)
2674
+ if (segments.length === 1) {
2675
+ if (!inSet(table.columns, input)) {
2676
+ throw new PolicyError(`${field} names ${input}, which is not a column of ${table.name}`)
2677
+ }
2678
+ return { column: input, path: undefined }
2679
+ }
2680
+ if (segments.length !== 2) {
2681
+ throw new PolicyError(`${field} ${input} follows more than one foreign key; a principal path is <column>.<principal column>`)
2682
+ }
2683
+ const column = segments[0] ?? ''
2684
+ const held = segments[1] ?? ''
2685
+ // A move rewrites a chain column (ON UPDATE CASCADE), and the layer stamps the key and the version: none is fixed.
2686
+ const own = table.scope.mode === 'reference' ? undefined : table.scope.key
2687
+ if (column === own || column === table.version || hasOwn(table.files, column) || chainColumn(table, column)) {
2688
+ throw new PolicyError(
2689
+ `${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`,
2690
+ )
2691
+ }
2692
+ const hop = singleForeignKey(table, column, field)
2693
+ const target = linked(hop.table)
2694
+ if (target === undefined) {
2695
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}, which has no policy`)
2696
+ }
2697
+ if (target.view) {
2698
+ 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`)
2699
+ }
2700
+ if (target.queue !== undefined) {
2701
+ throw new PolicyError(`${field}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2702
+ }
2703
+ const scope = target.scope
2704
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
2705
+ throw new PolicyError(`${field}: ${hop.table} is a ${scope.mode} table; the principal is held by a table whose key ${column} references`)
2706
+ }
2707
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2708
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2709
+ throw new PolicyError(
2710
+ `${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`,
2711
+ )
2712
+ }
2713
+ if (scope.key !== hop.key) {
2714
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}.${hop.key}, not its key ${scope.key}`)
2715
+ }
2716
+ // Only the hop's own key, or a tenant-holding one that maps the column to the same key, may hold the start column.
2717
+ refuseReferencing(table, column, field, 'starts the principal path', hop)
2718
+ refuseReferencing(target, scope.key, field, 'is the key the principal path follows', undefined)
2719
+ if (!inSet(target.columns, held)) {
2720
+ throw new PolicyError(`${field}: ${held} is not a column of ${hop.table}`)
2721
+ }
2722
+ if (held === target.version) {
2723
+ throw new PolicyError(`${field}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2724
+ }
2725
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2726
+ throw new PolicyError(`${field}: ${hop.table}.${held} decides whom a row names, so no update of ${hop.table} writes it; replace the row instead`)
2727
+ }
2728
+ if (held === scope.key || hasOwn(target.files, held) || inSet(target.json, held) || chainColumn(target, held)) {
2729
+ throw new PolicyError(`${field}: ${hop.table}.${held} is a key, a containment, a file or a JSON column; it holds no principal`)
2730
+ }
2731
+ refuseReferencing(target, held, field, 'holds the principal', undefined)
2732
+ return { column, path: freeze({ table: hop.table, key: hop.key, column: held }) }
2733
+ }
2734
+
2735
+ function chainColumn(table: Pick<TableModel, 'chain'>, column: string): boolean {
2736
+ for (let index = 0; index < table.chain.length; index++) {
2737
+ if (table.chain[index]?.column === column) return true
2738
+ }
2739
+ return false
2740
+ }
2741
+
2742
+ /**
2743
+ * A column that decides whom a row names references nothing but `hop` (a key into `hop.table` that maps it to
2744
+ * `hop.key`): the column list carries no foreign key's actions, and one that cascades on update would let a write to
2745
+ * the referenced table change whom every row names.
2746
+ */
2747
+ function refuseReferencing(
2748
+ table: Pick<TableModel, 'name' | 'foreignKeys'>,
2749
+ column: string,
2750
+ field: string,
2751
+ role: string,
2752
+ hop: { readonly table: string; readonly key: string } | undefined,
2753
+ ): void {
2754
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2755
+ const key = table.foreignKeys[index]
2756
+ if (key === undefined) continue
2757
+ for (let position = 0; position < key.columns.length; position++) {
2758
+ if (key.columns[position] !== column) continue
2759
+ if (hop !== undefined && key.table === hop.table && key.references[position] === hop.key) continue
2760
+ throw new PolicyError(
2761
+ `${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`,
2762
+ )
2763
+ }
2764
+ }
2765
+ }
2766
+
2767
+ function parseAssign(
2768
+ table: LinkedTable,
2769
+ policy: Readonly<Record<string, unknown>>,
2770
+ expires: string | undefined,
2771
+ what: string,
2772
+ ): RelationSource['assign'] {
2773
+ const input = ownEntry(policy, 'assign')
2774
+ if (table.actions.insert.length === 0) {
2775
+ if (input !== undefined) {
2776
+ throw new PolicyError(`${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`)
2777
+ }
2778
+ return undefined
2779
+ }
2780
+ if (input === undefined) {
2781
+ throw new PolicyError(
2782
+ `${what}: inserting a row of ${table.name} (${table.actions.insert.join(', ')}) delegates the relation; state assign: { maxDays?, self? }`,
2783
+ )
2784
+ }
2785
+ const assign = plainRecord(input, `${what}.assign`)
2786
+ onlyFields(assign, ASSIGN_FIELDS, `${what}.assign`)
2787
+ const maxDays = ownEntry(assign, 'maxDays')
2788
+ if (maxDays !== undefined && (typeof maxDays !== 'number' || !isSafeInteger(maxDays) || maxDays < 1 || maxDays > MAX_ASSIGN_DAYS)) {
2789
+ throw new PolicyError(`${what}.assign.maxDays takes a whole number of days from 1 to ${MAX_ASSIGN_DAYS}`)
2790
+ }
2791
+ if (maxDays !== undefined && expires === undefined) {
2792
+ throw new PolicyError(`${what}.assign.maxDays bounds a row's expires, which the relation does not declare`)
2793
+ }
2794
+ const self = ownEntry(assign, 'self')
2795
+ if (self !== undefined && self !== true) {
2796
+ throw new PolicyError(`${what}.assign.self takes true`)
2797
+ }
2798
+ return freeze({ maxDays: typeof maxDays === 'number' ? maxDays : undefined, self: self === true })
2799
+ }
2800
+
2801
+ /** The own columns a condition reads. */
2802
+ function conditionColumns(condition: ConditionModel): readonly string[] {
2803
+ if (condition.kind === 'test') {
2804
+ return condition.hops.length === 0 ? [condition.column] : [condition.hops[0]?.column ?? '']
2805
+ }
2806
+ if (condition.kind === 'not') {
2807
+ return conditionColumns(condition.term)
2808
+ }
2809
+ if (condition.kind === 'some') {
2810
+ return [condition.hops[0]?.column ?? condition.key]
2811
+ }
2812
+ const columns: string[] = []
2813
+ for (let index = 0; index < condition.terms.length; index++) {
2814
+ const term = condition.terms[index]
2815
+ const inner = term === undefined ? [] : conditionColumns(term)
2816
+ for (let position = 0; position < inner.length; position++) {
2817
+ columns[columns.length] = inner[position] ?? ''
2818
+ }
2819
+ }
2820
+ return columns
2821
+ }
2822
+
2823
+ /** A table's scope with nothing left to derive, and its containment chain. */
2824
+ interface Resolved {
2825
+ readonly scope: ScopeModel
2826
+ readonly chain: readonly Container[]
2827
+ }
2828
+
2829
+ function resolveChain(
2830
+ table: ParsedTable,
2831
+ byName: Readonly<Record<string, ParsedTable>>,
2832
+ owners: Readonly<Record<string, ParsedTable>>,
2833
+ containment: Containment,
2834
+ chainOf: (table: ParsedTable) => readonly Container[],
2835
+ ): Resolved {
2836
+ /**
2837
+ * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
2838
+ * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
2839
+ */
2840
+ const above = (dimension: string): readonly Container[] => {
2841
+ const owner = ownEntry(owners, dimension)
2842
+ if (owner !== undefined) {
2843
+ return chainOf(owner)
2844
+ }
2845
+ const container = ownEntry(containment, dimension)?.container
2846
+ return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
2847
+ }
2848
+ const scope = table.scope
2849
+ if (scope.mode === 'dimension') {
2850
+ const container = scope.container
2851
+ if (container === undefined) {
2852
+ return { scope, chain: freeze([]) }
2853
+ }
2854
+ const owner = ownEntry(owners, container.dimension)
2855
+ if (owner !== undefined) {
2856
+ requireReference(table, container, owner, (column) => `scope.in: { column: '${column}' }`)
2857
+ requireCoveringKey(table, container, owner, chainOf(owner))
2858
+ }
2859
+ return { scope, chain: prepend(container, above(container.dimension)) }
2860
+ }
2861
+ if (scope.mode !== 'child') {
2862
+ return { scope, chain: freeze([]) }
2863
+ }
2864
+ const parent = ownEntry(byName, scope.parent)
2865
+ if (parent === undefined || parent.scope.mode !== 'dimension') {
2866
+ throw new PolicyError(`${table.name}: the parent ${scope.parent} must be a dimension table`)
2867
+ }
2868
+ const parentChain = chainOf(parent)
2869
+ const expected: string[] = []
2870
+ for (let index = 0; index < parentChain.length; index++) {
2871
+ expected[index] = parentChain[index]?.column ?? ''
2872
+ }
2873
+ const dimension = parent.scope.dimension
2874
+ const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
2875
+ // A view has no foreign key: its rows are read through the parent row its parent column names (ADR-0072).
2876
+ if (table.view) {
2877
+ const inherit = scope.inherit ?? freeze(carried(table, expected))
2878
+ for (let index = 0; index < inherit.length; index++) {
2879
+ if (!includes(expected, inherit[index])) {
2880
+ throw new PolicyError(
2881
+ `${table.name}: inherits ${inherit[index]}, which is not a containment column of ${scope.parent} (${expected.join(', ') || 'none'})`,
2882
+ )
2883
+ }
2884
+ }
2885
+ return { scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }), chain: freeze([link]) }
2886
+ }
2887
+ const inherit = scope.inherit ?? freeze(expected)
2888
+ const inherited = nameSet(inherit)
1134
2889
  let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
1135
2890
  for (let index = 0; index < expected.length; index++) {
1136
2891
  matches = matches && inSet(inherited, expected[index])
@@ -1142,8 +2897,6 @@ function resolveChain(
1142
2897
  }), so a composite foreign key keeps it in scope`,
1143
2898
  )
1144
2899
  }
1145
- const dimension = parent.scope.dimension
1146
- const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
1147
2900
  requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1148
2901
  requireCoveringKey(table, link, parent, parentChain)
1149
2902
  return {
@@ -1152,6 +2905,16 @@ function resolveChain(
1152
2905
  }
1153
2906
  }
1154
2907
 
2908
+ /** The columns of `names` that `table` has: the parent's containment columns a view carries, which a join of it compares. */
2909
+ function carried(table: ParsedTable, names: readonly string[]): readonly string[] {
2910
+ const found: string[] = []
2911
+ for (let index = 0; index < names.length; index++) {
2912
+ const name = names[index] ?? ''
2913
+ if (inSet(table.columns, name)) found[found.length] = name
2914
+ }
2915
+ return found
2916
+ }
2917
+
1155
2918
  /** Whether a foreign key of `table` takes `column` to `key` of `target`, alone or as part of a composite key. */
1156
2919
  function references(table: ParsedTable, column: string, target: string, key: string): boolean {
1157
2920
  for (let index = 0; index < table.foreignKeys.length; index++) {
@@ -1231,6 +2994,66 @@ function requireCoveringKey(table: ParsedTable, link: Container, owner: ParsedTa
1231
2994
  )
1232
2995
  }
1233
2996
 
2997
+ /**
2998
+ * The column pairs of the covering key a containment column follows (`requireCoveringKey`): the column and the key,
2999
+ * then each column of the owner's chain, which the contained row carries under the same name.
3000
+ */
3001
+ function containmentPairs(column: string, key: string, ownerChain: readonly Container[]): [string, string][] {
3002
+ const pairs: [string, string][] = [[column, key]]
3003
+ for (let index = 0; index < ownerChain.length; index++) {
3004
+ const link = ownerChain[index]
3005
+ if (link !== undefined) pairs[pairs.length] = [link.column, link.column]
3006
+ }
3007
+ return pairs
3008
+ }
3009
+
3010
+ /**
3011
+ * The column pairs a foreign key from `column` of `table` to a row keyed by `key` with chain `chain` holds to keep that
3012
+ * row in `table`'s own tenant: the column and the key, then each ancestor of `chain` that `table` also lies in.
3013
+ */
3014
+ function tenantPairs(table: Resolved, column: string, key: string, chain: readonly Container[]): [string, string][] {
3015
+ const pairs: [string, string][] = [[column, key]]
3016
+ for (let index = 0; index < chain.length; index++) {
3017
+ const link = chain[index]
3018
+ const shared = link === undefined ? undefined : nodeColumnOf(table, link.dimension)
3019
+ if (link !== undefined && shared !== undefined) pairs[pairs.length] = [shared, link.column]
3020
+ }
3021
+ return pairs
3022
+ }
3023
+
3024
+ /**
3025
+ * The ancestor columns of a tenant key (every pair but the first) must be NOT NULL: under MATCH SIMPLE a null one skips
3026
+ * the key, and a row written raw with it null would reach another tenant's row.
3027
+ */
3028
+ function requireNotNullAncestors(
3029
+ what: string,
3030
+ table: { readonly name: string; readonly notNull: NameSet },
3031
+ pairs: readonly (readonly [string, string])[],
3032
+ ): void {
3033
+ const nullable: string[] = []
3034
+ for (let index = 1; index < pairs.length; index++) {
3035
+ const column = pairs[index]?.[0] ?? ''
3036
+ if (!inSet(table.notNull, column)) nullable[nullable.length] = column
3037
+ }
3038
+ if (nullable.length > 0) {
3039
+ throw new PolicyError(
3040
+ `${what}: ${nullable.join(', ')} of ${table.name} may be null, and a null skips the foreign key that holds the row's tenant; declare ${
3041
+ nullable.join(', ')
3042
+ } not null and run fabrika db codegen`,
3043
+ )
3044
+ }
3045
+ }
3046
+
3047
+ /** One foreign key to `table` of exactly `pairs`: a further nullable column would let the database skip the whole key. */
3048
+ function holdsExactly(foreignKeys: readonly ForeignKey[], table: string, pairs: readonly (readonly [string, string])[]): boolean {
3049
+ for (let index = 0; index < foreignKeys.length; index++) {
3050
+ const foreignKey = foreignKeys[index]
3051
+ if (foreignKey !== undefined && foreignKey.table === table && foreignKey.columns.length === pairs.length && coversPairs(foreignKey, pairs)) {
3052
+ return true
3053
+ }
3054
+ }
3055
+ return false
3056
+ }
1234
3057
  /** Whether every `[column, referenced]` pair is a column of `foreignKey` with that referenced column. */
1235
3058
  function coversPairs(foreignKey: ForeignKey, pairs: readonly (readonly [string, string])[]): boolean {
1236
3059
  for (let index = 0; index < pairs.length; index++) {
@@ -1283,12 +3106,21 @@ type ScopeOf<P, T> = PolicyOf<P, T> extends { readonly scope: infer S } ? S : ne
1283
3106
 
1284
3107
  export type Operation = 'read' | 'insert' | 'update' | 'delete'
1285
3108
 
1286
- /** The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none. */
3109
+ /**
3110
+ * The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none, and for
3111
+ * the read of a table read with `'any'` (`ReadsAny`).
3112
+ */
1287
3113
  export type ActionOf<P, T, Op extends Operation> = PolicyOf<P, T> extends { readonly actions: infer Acts }
1288
- ? Acts extends { readonly [K in Op]: infer A } ? A extends string ? A : A extends readonly (infer L extends string)[] ? L : never
3114
+ ? Acts extends { readonly [K in Op]: infer A } ? A extends typeof READ_ANY ? never
3115
+ : A extends string ? A
3116
+ : A extends readonly (infer L extends string)[] ? L
3117
+ : never
1289
3118
  : never
1290
3119
  : never
1291
3120
 
3121
+ /** Whether table `T` is read with `'any'`: by every `app` endpoint, job and webhook, whatever its action. */
3122
+ export type ReadsAny<P, T> = PolicyOf<P, T> extends { readonly actions: { readonly read: typeof READ_ANY } } ? true : false
3123
+
1292
3124
  export type DimensionOf<P, T> = ScopeOf<P, T> extends { readonly dimension: infer D extends string } ? D : never
1293
3125
  export type ContainerOf<P, T> = ScopeOf<P, T> extends { readonly in: { readonly dimension: infer D extends string } } ? D : never
1294
3126
  /** The dimension that lists and inserts of T are scoped by: its container, or for a top-level table its own. */
@@ -1307,11 +3139,11 @@ type Flat<T> = { [K in keyof T]: T[K] }
1307
3139
 
1308
3140
  type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends { readonly columns: infer C } ? C : never
1309
3141
  type TableReadAction<P, T> = PolicyOf<P, T> extends { readonly scope: { readonly read: infer A } } ? A : ActionOf<P, T, 'read'>
1310
- /** Columns whose own read action is not the table's: no read by the table's read action returns them. */
3142
+ /** Columns whose own read actions leave out one of the table's: no read by the table's read action returns them. */
1311
3143
  type RestrictedColumns<P, T> = [ColumnPoliciesOf<P, T>] extends [never] ? never
1312
3144
  : {
1313
3145
  [K in keyof ColumnPoliciesOf<P, T>]: ColumnPoliciesOf<P, T>[K] extends { readonly read: infer R }
1314
- ? ([TableReadAction<P, T>] extends [R] ? never : K)
3146
+ ? ([TableReadAction<P, T>] extends [R extends readonly (infer L extends string)[] ? L : R] ? never : K)
1315
3147
  : never
1316
3148
  }[keyof ColumnPoliciesOf<P, T>]
1317
3149