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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +69 -13
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +67 -9
  10. package/src/errors.ts +9 -5
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +187 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +216 -77
  24. package/src/orm.ts +417 -158
  25. package/src/policy.ts +2043 -131
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1958 -167
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +39 -4
  35. package/src/testing-shared.ts +872 -148
  36. package/src/testing-sqlite.ts +215 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +172 -26
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +40 -9
  47. package/types/src/errors.d.ts +8 -5
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +35 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +167 -75
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +378 -27
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +7 -1
  70. package/types/src/testing-shared.d.ts +125 -26
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +176 -22
package/src/store.ts CHANGED
@@ -1,6 +1,36 @@
1
1
  import { uuidv7 } from '@fabrika/platform'
2
- import { BinaryOperationNode, type OperationNode, OperatorNode, type ReturningNode, ValueNode } from 'kysely'
2
+ import { AndNode, BinaryOperationNode, type OperationNode, OperatorNode, ParensNode, type ReturningNode, ValueNode } from 'kysely'
3
3
  import { admissions } from './admissions'
4
+ import {
5
+ accessReach,
6
+ type AccessRelation,
7
+ activeRow,
8
+ conditioned,
9
+ conditionedAny,
10
+ everyPath,
11
+ gateTerms,
12
+ heldThrough,
13
+ holdsBesides,
14
+ isIn,
15
+ knownRelation,
16
+ type LayerRelation,
17
+ type MemberReveals,
18
+ memberTerms,
19
+ namesPrincipal,
20
+ noPath,
21
+ type PathRule,
22
+ pathTerms,
23
+ refScope,
24
+ relationCondition,
25
+ relationGate,
26
+ relationSource,
27
+ type RelationSources,
28
+ relationTerms,
29
+ revealedNodes,
30
+ type SplitReach,
31
+ throughPath,
32
+ viewScope,
33
+ } from './authority'
4
34
  import {
5
35
  defineValue,
6
36
  freeze,
@@ -25,21 +55,29 @@ import {
25
55
  type AppGrant,
26
56
  type CapabilityAuthority,
27
57
  type CapabilityGrant,
58
+ type ContainerGrant,
28
59
  describeGrant,
29
60
  MAX_WITHIN_VALUES,
30
61
  type Ref,
31
62
  type RefGrant,
63
+ type RelationHold,
32
64
  type Within,
33
65
  type WithinGrant,
34
66
  } from './capability'
67
+ import { conditionNode, subquery } from './condition-nodes'
68
+ import { type ConditionModel, conditionReach, readPaths, rowSatisfies } from './conditions'
35
69
  import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
36
70
  import {
71
+ type ComparableColumn,
72
+ comparableColumnOf,
37
73
  type Compare,
38
74
  type Condition,
39
75
  type Contains,
76
+ finishFilter,
40
77
  finishSelect,
41
78
  isPrimitive,
42
79
  type JoinShape,
80
+ type JoinState,
43
81
  type NoColumns,
44
82
  type Primitive,
45
83
  type ScopedSelect,
@@ -51,9 +89,10 @@ import { CapabilityError, ConflictError, NotFoundError, PolicyError, QueryRefuse
51
89
  import { answerFiles, type FileBinding, fileValue, referenceFiles, rowScope, storedRowScope } from './file-columns'
52
90
  import { fileReference } from './file-references'
53
91
  import { webhookTables } from './framework-tables'
54
- import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
92
+ import type { ForeignKeyPair, GuardContext, RootKind, ViewAccessLink, ViewParentLink } from './guard'
55
93
  import { fencedTransaction, jobLeases } from './job-leases'
56
94
  import { jobWakes, leaseProjection } from './job-wakes'
95
+ import { jsonInput, type JsonSchema, schemaInput } from './json'
57
96
  import { linksPredicate, type LinkValue, linkValues } from './links'
58
97
  import {
59
98
  acknowledgement,
@@ -74,7 +113,10 @@ import {
74
113
  scopedWhere,
75
114
  selectNode,
76
115
  updateNode,
116
+ valueList,
117
+ valuesNode,
77
118
  } from './nodes'
119
+ import { notifications } from './notifications'
78
120
  import { dataAccess } from './orm'
79
121
  import {
80
122
  type Acknowledgement,
@@ -82,28 +124,41 @@ import {
82
124
  type ChildTableName,
83
125
  type Container,
84
126
  type ContainerOf,
127
+ delegates,
85
128
  type DimensionOf,
86
129
  type DimensionTableName,
87
130
  includes,
88
131
  type InsertValues,
89
132
  type JoinableChildren,
90
133
  type ListDimensionOf,
134
+ type MemberRevealModel,
91
135
  modelOf,
92
136
  type MoveAcknowledgement,
93
137
  namesAction,
138
+ nodeColumnOf,
94
139
  type Operation,
95
140
  type ParentOf,
141
+ type PathWriter,
142
+ pathWriters,
96
143
  type PolicyRow,
144
+ type ReadReach,
145
+ type RevealModel,
146
+ type SecondaryPath,
97
147
  type TableModel,
98
148
  type TableModels,
99
149
  tableModels,
100
150
  type Tables,
151
+ updatableBy,
152
+ updatableByAny,
101
153
  updateActions,
102
154
  type UpdateValues,
103
155
  type VersionArguments,
104
156
  visibleFor,
157
+ visibleThrough,
105
158
  } from './policy'
159
+ import { pushSubscriptions } from './push-subscriptions'
106
160
  import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
161
+ import { requestReceipts } from './request-receipts'
107
162
  import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
108
163
  import { storedFiles, storedFilesMetadata } from './stored-files'
109
164
  import { type TablePolicies, tablePolicies } from './tables'
@@ -136,6 +191,36 @@ export interface TableContext {
136
191
  /** The model of each child a select may join, by its table name. */
137
192
  readonly children: Readonly<Record<string, TableModel>>
138
193
  readonly connection: Connection
194
+ /** Every relation of the layer with its source table: what a relation term of any table reads. */
195
+ readonly relations: RelationSources
196
+ /** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
197
+ readonly members: MemberReveals
198
+ /** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
199
+ readonly subqueries: Readonly<Record<string, readonly string[]>>
200
+ /** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
201
+ readonly through: ViewParent | undefined
202
+ /** The path columns whose insert hands out actions, each with the table owning the node it names (`pathWriters`). */
203
+ readonly writers: readonly PathBound[]
204
+ }
205
+
206
+ /** A path column an insert writes under its bound, and the table that owns the dimension it names. */
207
+ export interface PathBound extends PathWriter {
208
+ readonly owner: TableModel
209
+ }
210
+
211
+ /** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
212
+ export interface ViewParent extends ViewParentLink {
213
+ readonly context: TableContext
214
+ }
215
+
216
+ /** A child view's access views, as the guard admits them on its statements: its key in each view's row column. */
217
+ function viewAccessLinks(model: TableModel, key: string): readonly ViewAccessLink[] {
218
+ const links: ViewAccessLink[] = []
219
+ for (let index = 0; index < model.access.length; index++) {
220
+ const access = model.access[index]
221
+ if (access !== undefined) links[links.length] = freeze({ key, view: access.view, row: access.row })
222
+ }
223
+ return freeze(links)
139
224
  }
140
225
 
141
226
  /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
@@ -145,7 +230,7 @@ export function dialectOf(context: TableContext): SqlDialect {
145
230
 
146
231
  /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
147
232
  export function rowColumnsOf(model: TableModel): RowColumns {
148
- return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans }
233
+ return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans, json: model.json, jsonSchemas: model.jsonSchemas }
149
234
  }
150
235
 
151
236
  /** A timestamp's bound value on SQLite: its stored UTC text. Postgres takes a `Date` or ISO text as it is. */
@@ -296,13 +381,17 @@ function withinGrant(context: TableContext, capability: unknown, dimension: stri
296
381
  return grant
297
382
  }
298
383
 
299
- /** The chain links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. */
384
+ /**
385
+ * The links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. A dimension
386
+ * table's own dimension counts, so its containers lie above a `Within` of it.
387
+ */
300
388
  function linksAbove(model: TableModel, dimension: string): readonly Container[] {
301
- for (let index = 0; index < model.chain.length; index++) {
302
- if (model.chain[index]?.dimension === dimension) {
389
+ const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
390
+ for (let index = 0; index < links.length; index++) {
391
+ if (links[index]?.dimension === dimension) {
303
392
  const above: Container[] = []
304
- for (let position = index + 1; position < model.chain.length; position++) {
305
- const link = model.chain[position]
393
+ for (let position = index + 1; position < links.length; position++) {
394
+ const link = links[position]
306
395
  if (link !== undefined) {
307
396
  above[above.length] = link
308
397
  }
@@ -380,6 +469,9 @@ function withinCount(grant: WithinGrant): number {
380
469
  for (let index = 0; index < grant.contained.length; index++) {
381
470
  count += grant.contained[index]?.values.length ?? 0
382
471
  }
472
+ for (let index = 0; index < grant.revealing.length; index++) {
473
+ count += grant.revealing[index]?.values.length ?? 0
474
+ }
383
475
  return count
384
476
  }
385
477
 
@@ -388,9 +480,11 @@ function withinCount(grant: WithinGrant): number {
388
480
  * the statement itself judges each row by the chain it carries now. Undefined for an empty `Within`: the caller
389
481
  * answers `[]` without a query.
390
482
  */
391
- function withinPredicate(model: TableModel, column: string, grant: WithinGrant): OperationNode | undefined {
483
+ function withinPredicate(context: TableContext, column: string, grant: WithinGrant, operation: Operation): OperationNode | undefined {
484
+ const model = context.model
485
+ const now = new Date()
392
486
  if (grant.values === 'all') {
393
- return everything()
487
+ return conditioned(model, grant.action, 'all', now)
394
488
  }
395
489
  const above = linksAbove(model, grant.dimension)
396
490
  const predicates: OperationNode[] = []
@@ -424,7 +518,80 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
424
518
  if (count > MAX_WITHIN_VALUES) {
425
519
  throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${count}`)
426
520
  }
427
- return predicates.length === 0 ? undefined : anyOf(predicates)
521
+ addRelationTerms(context, grant, operation === 'read', predicates, now)
522
+ if (operation === 'read') addMemberTerms(context, grant, predicates, now)
523
+ return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
524
+ }
525
+
526
+ /** A `Within`'s read also reaches the rows under a node its member reveals hold the action at; no write does. */
527
+ function addMemberTerms(context: TableContext, grant: WithinGrant, predicates: OperationNode[], now: Date): void {
528
+ const terms = memberTerms(context.members, context.model, grant, now)
529
+ for (let index = 0; index < terms.length; index++) {
530
+ const term = terms[index]
531
+ if (term !== undefined) predicates[predicates.length] = term
532
+ }
533
+ }
534
+
535
+ /** The relation terms of a `Within`'s relations; a relation whose dimension this table lies at no node of reaches none of its rows. */
536
+ function addRelationTerms(context: TableContext, grant: WithinGrant, reads: boolean, predicates: OperationNode[], now: Date): void {
537
+ for (let index = 0; index < grant.relations.length; index++) {
538
+ const hold = grant.relations[index]
539
+ if (hold === undefined) continue
540
+ const terms = relationTerms(
541
+ context.relations,
542
+ context.model,
543
+ hold,
544
+ grant.principal,
545
+ grant.action,
546
+ now,
547
+ reads ? everyPath : noPath,
548
+ )
549
+ for (let position = 0; position < terms.length; position++) {
550
+ const term = terms[position]
551
+ if (term !== undefined) predicates[predicates.length] = term
552
+ }
553
+ }
554
+ }
555
+
556
+ /**
557
+ * The rows a `Within` of a dimension outside the chain reads through `paths`, the ones that reach it: per path
558
+ * `T.<column> in (values)` at the path's own dimension or `T.<column> in (select D.<key> from D where D.<link> in
559
+ * (values))` above it, the same for each container, then the relations' terms. A grant on a dimension inside the
560
+ * Within's lies at no node the column holds, so it reaches no row here.
561
+ */
562
+ function secondaryPredicate(context: TableContext, paths: readonly SecondaryPath[], grant: WithinGrant): OperationNode | undefined {
563
+ const model = context.model
564
+ const now = new Date()
565
+ if (grant.values === 'all') {
566
+ return conditioned(model, grant.action, 'all', now)
567
+ }
568
+ if (withinCount(grant) > MAX_WITHIN_VALUES) {
569
+ throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${withinCount(grant)}`)
570
+ }
571
+ const predicates: OperationNode[] = []
572
+ for (let index = 0; index < paths.length; index++) {
573
+ const path = paths[index]
574
+ if (path === undefined) continue
575
+ if (grant.values.length > 0) {
576
+ const own = throughPath(model.name, path, grant.dimension, valueList(grant.values))
577
+ if (own !== undefined) predicates[predicates.length] = own
578
+ }
579
+ for (let position = 0; position < grant.containers.length; position++) {
580
+ const container = grant.containers[position]
581
+ if (container === undefined || container.values.length === 0) continue
582
+ const above = throughPath(model.name, path, container.dimension, valueList(container.values))
583
+ if (above === undefined) {
584
+ throw new CapabilityError(
585
+ 'unenforceable',
586
+ `the Within of ${grant.dimension} reaches through ${container.dimension}, which ${path.table} carries no column for; the layer cannot enforce it`,
587
+ )
588
+ }
589
+ predicates[predicates.length] = above
590
+ }
591
+ }
592
+ addRelationTerms(context, grant, true, predicates, now)
593
+ addMemberTerms(context, grant, predicates, now)
594
+ return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
428
595
  }
429
596
 
430
597
  /** The object a Ref of the model's own dimension names, with every link of its chain. */
@@ -440,23 +607,126 @@ export function selfLinks(model: TableModel): readonly Container[] {
440
607
  return links
441
608
  }
442
609
 
443
- /** This object, over the whole chain the Ref carries. */
444
- export function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode {
610
+ /** This object, over the whole chain the Ref carries; through the secondary paths `paths` admits, by default its action's. */
611
+ export function objectPredicate(context: TableContext, capability: unknown, operation: Operation, paths?: PathRule): OperationNode {
445
612
  const scope = dimensionScope(context.model)
446
613
  const grant = refGrant(context, capability, scope.dimension, operation)
447
- return linksPredicate(context.model.name, linkValues(context.model.name, selfLinks(context.model), grant))
614
+ return refScope(context, context.model, selfLinks(context.model), grant, new Date(), undefined, paths ?? heldThrough(grant.action))
448
615
  }
449
616
 
450
617
  /** Rows of a dimension table within the scope values of its list dimension. */
451
618
  export function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
452
619
  const scope = dimensionScope(context.model)
453
620
  const grant = withinGrant(context, capability, listDimension(scope), operation)
454
- return withinPredicate(context.model, scope.container?.column ?? scope.key, grant)
621
+ return withinPredicate(context, scope.container?.column ?? scope.key, grant, operation)
622
+ }
623
+
624
+ /**
625
+ * Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
626
+ * of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
627
+ */
628
+ export function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode {
629
+ const row = key === undefined ? undefined : equals(context.model.name, childScope(context).key, key)
630
+ const through = context.through
631
+ if (through !== undefined) {
632
+ const parent = through.context
633
+ const now = new Date()
634
+ const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
635
+ const reached = narrowed.length === 0
636
+ ? refScope(parent, parent.model, selfLinks(parent.model), grant, now)
637
+ : splitRefReach(context.model, parent, grant, narrowed, now)
638
+ return viewScope(context.model, through, grant.action, reached, now, row)
639
+ }
640
+ return refScope(context, context.model, context.model.chain, grant, new Date(), row)
641
+ }
642
+
643
+ /** Of `holds`, the relations a child view's `relationWhen` narrows for `action`: each reads the parent through a part of its own. */
644
+ function viewNarrowed(view: TableModel, holds: readonly RelationHold[], action: string): readonly string[] {
645
+ const narrowed: string[] = []
646
+ for (let index = 0; index < holds.length; index++) {
647
+ const relation = holds[index]?.relation ?? ''
648
+ if (relationCondition(view, relation, action) !== undefined && !includes(narrowed, relation)) narrowed[narrowed.length] = relation
649
+ }
650
+ return narrowed
651
+ }
652
+
653
+ /**
654
+ * A Ref's reach of a view's parent, split by the relations the view narrows: the chain with the terms of its other
655
+ * relations, member reveals and paths, and the chain with each narrowed relation's own terms. A part that reaches no
656
+ * parent row adds nothing; none left is unenforceable, never unconditioned.
657
+ */
658
+ function splitRefReach(view: TableModel, parent: TableContext, grant: RefGrant, narrowed: readonly string[], now: Date): SplitReach {
659
+ const model = parent.model
660
+ const chain = linksPredicate(model.name, linkValues(model.name, selfLinks(model), grant))
661
+ const paths = heldThrough(grant.action)
662
+ const others = holdsBesides(grant.relations, narrowed)
663
+ const rest: RefGrant = { ...grant, relations: others }
664
+ const restTerms = others.length === 0 && rest.revealing.length === 0 && rest.paths.length === 0 ? [] : gateTerms(parent, model, rest, now, paths)
665
+ const relations: { reached: OperationNode; condition: ConditionModel }[] = []
666
+ for (let index = 0; index < grant.relations.length; index++) {
667
+ const hold = grant.relations[index]
668
+ const condition = hold === undefined || !includes(narrowed, hold.relation) ? undefined : relationCondition(view, hold.relation, grant.action)
669
+ const terms = hold === undefined || condition === undefined
670
+ ? []
671
+ : relationTerms(parent.relations, model, hold, grant.principal, grant.action, now, paths)
672
+ if (condition !== undefined && terms.length > 0) relations[relations.length] = { reached: allOf([chain, anyOf(terms)]), condition }
673
+ }
674
+ if (restTerms.length === 0 && relations.length === 0) {
675
+ throw new CapabilityError(
676
+ 'unenforceable',
677
+ `the Ref of ${grant.dimension} is held through relations, member reveals or secondary paths, none of which reaches a row of ${model.name} for ${grant.action}`,
678
+ )
679
+ }
680
+ return { rest: restTerms.length === 0 ? undefined : allOf([chain, anyOf(restTerms)]), relations }
455
681
  }
456
682
 
457
- /** Rows of a child table that belong to the parent object the Ref names, over the whole chain. */
458
- export function parentPredicate(context: TableContext, grant: RefGrant): OperationNode {
459
- return linksPredicate(context.model.name, linkValues(context.model.name, context.model.chain, grant))
683
+ /**
684
+ * A child view's rows a `Within` reaches: those whose parent row `reach` admits over the parent's context; for `all`,
685
+ * those whose parent row exists. A relation the view narrows (`relationWhen`) reaches the parent through a part of its
686
+ * own, ANDed with the view's condition. The view's own access views list rows beside them. Undefined where nothing is
687
+ * reached: the empty `Within`.
688
+ */
689
+ function throughParent(
690
+ context: TableContext,
691
+ through: ViewParent,
692
+ grant: WithinGrant,
693
+ reach: (parent: TableContext, grant: WithinGrant) => OperationNode | undefined,
694
+ ): OperationNode | undefined {
695
+ const now = new Date()
696
+ if (grant.values === 'all') {
697
+ return viewScope(context.model, through, grant.action, 'all', now)
698
+ }
699
+ const own: OperationNode[] = []
700
+ for (let index = 0; index < grant.relations.length; index++) {
701
+ const hold = grant.relations[index]
702
+ const terms = hold === undefined ? [] : accessReach(context.model, hold, grant.principal, grant.action, now)
703
+ for (let position = 0; position < terms.length; position++) {
704
+ const term = terms[position]
705
+ if (term !== undefined) own[own.length] = term
706
+ }
707
+ }
708
+ const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
709
+ if (narrowed.length === 0) {
710
+ const reached = reach(through.context, grant)
711
+ return reached === undefined && own.length === 0 ? undefined : viewScope(context.model, through, grant.action, reached, now, undefined, own)
712
+ }
713
+ const rest = reach(through.context, { ...grant, relations: holdsBesides(grant.relations, narrowed) })
714
+ const relations: { reached: OperationNode; condition: ConditionModel }[] = []
715
+ for (let index = 0; index < grant.relations.length; index++) {
716
+ const hold = grant.relations[index]
717
+ const condition = hold === undefined || !includes(narrowed, hold.relation)
718
+ ? undefined
719
+ : relationCondition(context.model, hold.relation, grant.action)
720
+ const alone: WithinGrant | undefined = hold === undefined
721
+ ? undefined
722
+ : { ...grant, values: [], containers: [], contained: [], revealing: [], relations: [hold] }
723
+ const reached = condition === undefined || alone === undefined ? undefined : reach(through.context, alone)
724
+ if (condition !== undefined && reached !== undefined) relations[relations.length] = { reached, condition }
725
+ }
726
+ if (rest === undefined && relations.length === 0 && own.length === 0) {
727
+ return undefined
728
+ }
729
+ return viewScope(context.model, through, grant.action, { rest, relations }, now, undefined, own)
460
730
  }
461
731
 
462
732
  export function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
@@ -470,29 +740,38 @@ export function childListPredicate(context: TableContext, capability: unknown, o
470
740
  throw new CapabilityError('wrong_capability', `a list of ${context.model.name} by its parent needs a Ref or a Within, got ${describeGrant(grant)}`)
471
741
  }
472
742
  checkGrant(context, grant, listDimension(scope.parent), operation)
473
- return withinPredicate(context.model, scope.parent.container?.column ?? scope.column, grant)
743
+ if (context.through !== undefined) {
744
+ const column = scope.parent.container?.column ?? scope.parent.key
745
+ return throughParent(context, context.through, grant, (parent, part) => withinPredicate(parent, column, part, operation))
746
+ }
747
+ return withinPredicate(context, scope.parent.container?.column ?? scope.column, grant, operation)
474
748
  }
475
749
 
476
750
  /**
477
- * The column that places a row of `model` in `dimension`: the column of that link of its containment chain, or a
478
- * top-level table's own key; `undefined` when no `Within` of the dimension reaches the table.
751
+ * Whether a `Within` of `dimension` lists the table: a dimension table its own dimension's, then through its containment
752
+ * chain or a secondary path; a child view through its parent's.
479
753
  */
480
- export function reachColumn(model: TableModel, dimension: string): string | undefined {
481
- if (model.scope.mode === 'dimension' && model.scope.container === undefined && model.scope.dimension === dimension) {
482
- return model.scope.key
483
- }
484
- for (let index = 0; index < model.chain.length; index++) {
485
- const link = model.chain[index]
486
- if (link?.dimension === dimension) {
487
- return link.column
754
+ export function reachedBy(context: TableContext, dimension: string): boolean {
755
+ const model = context.through?.context.model ?? context.model
756
+ return nodeColumnOf(model, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
757
+ }
758
+
759
+ /** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
760
+ export function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[] {
761
+ const paths: SecondaryPath[] = []
762
+ for (let index = 0; index < model.readThrough.length; index++) {
763
+ const path = model.readThrough[index]
764
+ if (path !== undefined && (path.dimension === dimension || linkOf(path.chain, dimension) !== undefined)) {
765
+ paths[paths.length] = path
488
766
  }
489
767
  }
490
- return undefined
768
+ return paths
491
769
  }
492
770
 
493
771
  /**
494
772
  * Rows of a table a `Within` of any dimension of its chain lists, by the table's read action: tasks under a `Within` of
495
- * `org` through their stamped `org_id`, as under one of `project` through `project_id`.
773
+ * `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
774
+ * table reaches through a secondary path, through that path's column.
496
775
  */
497
776
  export function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined {
498
777
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
@@ -501,14 +780,25 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
501
780
  throw new CapabilityError('wrong_capability', `a list of ${table} needs a Within, got ${describeGrant(grant)}`)
502
781
  }
503
782
  checkAction(context, 'read', grant.action)
504
- const column = reachColumn(context.model, grant.dimension)
505
- if (column === undefined) {
783
+ if (!reachedBy(context, grant.dimension)) {
506
784
  throw new CapabilityError(
507
785
  'out_of_reach',
508
- `a Within of ${grant.dimension} does not reach ${table}: its containment chain does not hold ${grant.dimension}`,
786
+ `a Within of ${grant.dimension} does not reach ${table}: neither its containment chain nor a secondary path holds ${grant.dimension}`,
509
787
  )
510
788
  }
511
- return withinPredicate(context.model, column, grant)
789
+ if (context.through !== undefined) {
790
+ return throughParent(context, context.through, grant, withinReach)
791
+ }
792
+ return withinReach(context, grant)
793
+ }
794
+
795
+ /** A `Within`'s read of a table it reaches: through the column that places a row in its dimension, or its secondary paths. */
796
+ function withinReach(context: TableContext, grant: WithinGrant): OperationNode | undefined {
797
+ const column = nodeColumnOf(context.model, grant.dimension)
798
+ if (column !== undefined) {
799
+ return withinPredicate(context, column, grant, 'read')
800
+ }
801
+ return secondaryPredicate(context, secondaryPathsOf(context.model, grant.dimension), grant)
512
802
  }
513
803
 
514
804
  /**
@@ -527,7 +817,8 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
527
817
  throw new CapabilityError('table_kind', `a scoped site writes no application table: ${statement} needs the capability of an app endpoint`)
528
818
  }
529
819
  const actions = model.actions[use]
530
- if (includes(actions, grant.action)) {
820
+ const held = grantActions(grant)
821
+ if (admitted(held, actions).length > 0) {
531
822
  return
532
823
  }
533
824
  const columnWrites: string[] = []
@@ -539,11 +830,39 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
539
830
  if (actions.length === 0 && columnWrites.length === 0) {
540
831
  throw new CapabilityError('undeclared_operation', `${statement}: its policy declares no ${use} action`)
541
832
  }
542
- if (!includes(columnWrites, grant.action)) {
833
+ if (admitted(held, columnWrites).length === 0) {
543
834
  const needs = actions.length === 0 ? [] : [`its ${use} action ${actions.join(' or ')}`]
544
835
  if (columnWrites.length > 0) needs[needs.length] = `a column's own write action (${columnWrites.join(', ')})`
545
- throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${grant.action}`)
836
+ throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${held.join(', ')}`)
837
+ }
838
+ }
839
+
840
+ /** The actions a grant holds: an `app` grant's (several for an `anyOf` endpoint), or any other grant's one. */
841
+ export function grantActions(grant: CapabilityGrant): readonly string[] {
842
+ return grant.kind === 'app' ? grant.actions : [grant.action]
843
+ }
844
+
845
+ /** The actions of `held` that `allowed` lists: those that allow an operation, as any one of them does. */
846
+ function admitted(held: readonly string[], allowed: readonly string[]): string[] {
847
+ const found: string[] = []
848
+ for (let index = 0; index < held.length; index++) {
849
+ const action = held[index]
850
+ if (action !== undefined && includes(allowed, action)) {
851
+ found[found.length] = action
852
+ }
853
+ }
854
+ return found
855
+ }
856
+
857
+ /** The first of `actions` the table narrows with a `when`: a fragment, which renders column tests only, cannot hold it. */
858
+ function heldCondition(model: TableModel, actions: readonly string[]): string | undefined {
859
+ for (let index = 0; index < actions.length; index++) {
860
+ const action = actions[index]
861
+ if (action !== undefined && hasOwn(model.when, action)) {
862
+ return action
863
+ }
546
864
  }
865
+ return undefined
547
866
  }
548
867
 
549
868
  /**
@@ -565,8 +884,29 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
565
884
  if (use !== 'read') {
566
885
  checkWriteTarget(context, grant, use)
567
886
  }
887
+ // The fragment renders column tests only; a relation's, a member reveal's or a path's subquery, or an action's condition, would be left out.
888
+ const held = grant.kind !== 'app'
889
+ && (grant.relations.length > 0 || (grant.kind === 'ref' && (grant.revealing.length > 0 || grant.paths.length > 0)))
890
+ // An `'any'` read is unconditioned: a `when` keyed by the action narrows only its writes.
891
+ const readsEvery = grant.kind === 'app' && use === 'read' && readsAny(context, grant)
892
+ const conditionedBy = readsEvery ? undefined : heldCondition(model, grantActions(grant))
893
+ if (held || conditionedBy !== undefined) {
894
+ throw new CapabilityError(
895
+ 'unenforceable',
896
+ `ctx.sql.scope cannot render a relation, a member reveal, a secondary path or a condition of ${
897
+ conditionedBy ?? grantActions(grant).join(', ')
898
+ } on ${model.name}: read it through ctx.db`,
899
+ )
900
+ }
901
+ // Nor the subquery through the parent row, which alone places a child view's rows.
902
+ if (grant.kind !== 'app' && context.through !== undefined) {
903
+ throw new CapabilityError(
904
+ 'unenforceable',
905
+ `ctx.sql.scope cannot render the read of the view ${model.name} through its parent: read it through ctx.db`,
906
+ )
907
+ }
568
908
  if (grant.kind === 'app') {
569
- if (use === 'read') {
909
+ if (use === 'read' && !readsEvery) {
570
910
  // The action is held as a global grant, so its scope is every row of a table it reaches.
571
911
  checkAppReach(context, grant)
572
912
  }
@@ -608,7 +948,7 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
608
948
  }
609
949
  return [tests]
610
950
  }
611
- const column = reachColumn(model, grant.dimension)
951
+ const column = nodeColumnOf(model, grant.dimension)
612
952
  if (column === undefined) {
613
953
  throw new CapabilityError(
614
954
  'out_of_reach',
@@ -690,32 +1030,63 @@ export function updatingRef(context: TableContext, capability: unknown, dimensio
690
1030
  */
691
1031
  export type AppReach = 'rows' | 'counts'
692
1032
 
693
- /** Refuses an `app` capability whose action does not reach `reach` of a dimension or child table. */
694
- function checkRecordReach(context: TableContext, grant: AppGrant, reach: AppReach): void {
1033
+ /**
1034
+ * The actions of an `app` capability that reach `reach` of a dimension or child table, at least one: its read action and
1035
+ * its `appRead`, and for `counts` its `appCount` too. Refuses a capability none of whose actions does.
1036
+ */
1037
+ function recordReach(context: TableContext, grant: AppGrant, reach: AppReach): readonly string[] {
695
1038
  const model = context.model
696
1039
  const { appRead, appCount } = model.actions
697
1040
  const read = model.actions.read.join(' or ')
698
- if (
699
- includes(model.actions.read, grant.action) || includes(appRead, grant.action) || (reach === 'counts' && includes(appCount, grant.action))
700
- ) {
701
- return
1041
+ const reaching = admitted(grant.actions, model.actions.read)
1042
+ const reads = admitted(grant.actions, appRead)
1043
+ for (let index = 0; index < reads.length; index++) {
1044
+ reaching[reaching.length] = reads[index] ?? ''
1045
+ }
1046
+ const counts = admitted(grant.actions, appCount)
1047
+ if (reach === 'counts') {
1048
+ for (let index = 0; index < counts.length; index++) {
1049
+ reaching[reaching.length] = counts[index] ?? ''
1050
+ }
702
1051
  }
703
- if (includes(appCount, grant.action)) {
1052
+ if (reaching.length > 0) {
1053
+ return reaching
1054
+ }
1055
+ const held = grant.actions.join(', ')
1056
+ if (counts.length > 0) {
704
1057
  throw new CapabilityError(
705
1058
  'wrong_action',
706
- `an app capability of ${grant.action} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
1059
+ `an app capability of ${held} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
707
1060
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
708
1061
  }`,
709
1062
  )
710
1063
  }
711
1064
  throw new CapabilityError(
712
1065
  'wrong_action',
713
- `an app capability of ${grant.action} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
1066
+ `an app capability of ${held} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
714
1067
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
715
1068
  } only`,
716
1069
  )
717
1070
  }
718
1071
 
1072
+ /** The actions of an `app` capability the application table names; refuses a capability none of whose actions it names. */
1073
+ function namedActions(model: TableModel, grant: AppGrant): readonly string[] {
1074
+ const named: string[] = []
1075
+ for (let index = 0; index < grant.actions.length; index++) {
1076
+ const action = grant.actions[index]
1077
+ if (action !== undefined && namesAction(model, action)) {
1078
+ named[named.length] = action
1079
+ }
1080
+ }
1081
+ if (named.length === 0) {
1082
+ throw new CapabilityError(
1083
+ 'wrong_action',
1084
+ `an app capability of ${grant.actions.join(', ')} does not reach ${model.name}: ${model.name} does not name the action`,
1085
+ )
1086
+ }
1087
+ return named
1088
+ }
1089
+
719
1090
  /**
720
1091
  * Refuses a table `ctx.db.app` does not list for the capability (`applicationTables` in `orm.ts`): it lists an
721
1092
  * application table under any action the table names, and the rows of a dimension or child table under its read
@@ -725,12 +1096,7 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
725
1096
  const model = context.model
726
1097
  const mode = model.scope.mode
727
1098
  if (mode === 'app') {
728
- if (!namesAction(model, grant.action)) {
729
- throw new CapabilityError(
730
- 'wrong_action',
731
- `an app capability of ${grant.action} does not reach ${model.name}: ${model.name} does not name the action`,
732
- )
733
- }
1099
+ namedActions(model, grant)
734
1100
  return
735
1101
  }
736
1102
  if (mode !== 'dimension' && mode !== 'child') {
@@ -739,14 +1105,20 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
739
1105
  `an app capability does not reach ${model.name}: ctx.db.app lists application, dimension and child tables only`,
740
1106
  )
741
1107
  }
742
- checkRecordReach(context, grant, 'rows')
1108
+ recordReach(context, grant, 'rows')
1109
+ }
1110
+
1111
+ /** What an `app` capability reads of a table: the rows (`predicate`), and the reach whose columns it answers. */
1112
+ export interface AppRead {
1113
+ readonly predicate: OperationNode
1114
+ readonly reach: ReadReach
743
1115
  }
744
1116
 
745
1117
  /**
746
- * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`: `true`, for an action that
747
- * reaches `reach` (`checkRecordReach`).
1118
+ * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`, for its actions that reach
1119
+ * `reach` (`recordReach`): each row within the condition of one of them, and the columns they read alone.
748
1120
  */
749
- export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1121
+ export function appRecordRead(context: TableContext, capability: unknown, reach: AppReach): AppRead {
750
1122
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
751
1123
  const model = context.model
752
1124
  if (grant.kind !== 'app') {
@@ -758,8 +1130,13 @@ export function appRecordPredicate(context: TableContext, capability: unknown, r
758
1130
  if (model.scope.mode !== 'dimension' && model.scope.mode !== 'child') {
759
1131
  throw new CapabilityError('table_kind', `${model.name} is not a dimension or child table`)
760
1132
  }
761
- checkRecordReach(context, grant, reach)
762
- return everything()
1133
+ const actions = recordReach(context, grant, reach)
1134
+ return { predicate: conditionedAny(model, actions, 'all', new Date()), reach: freeze({ actions, narrowed: true }) }
1135
+ }
1136
+
1137
+ /** `appRecordRead`'s rows. */
1138
+ export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1139
+ return appRecordRead(context, capability, reach).predicate
763
1140
  }
764
1141
 
765
1142
  /** An `app` capability addresses a row by its key, and writes, only in an application table. */
@@ -773,10 +1150,11 @@ function checkApplicationTable(context: TableContext, operation: Operation): voi
773
1150
  }
774
1151
 
775
1152
  /**
776
- * The capability of an `app` endpoint for `operation` on `table`: its action is that operation's. An application table
777
- * is written with it, and a dimension or child table read with it.
1153
+ * The capability of an `app` endpoint for `operation` on `table`, and its actions that are that operation's, at least
1154
+ * one. An application table is written with it, and a dimension or child
1155
+ * table read with it.
778
1156
  */
779
- function appGrant(context: TableContext, capability: unknown, operation: Operation): AppGrant {
1157
+ function appGrant(context: TableContext, capability: unknown, operation: Operation): AppOperation {
780
1158
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
781
1159
  const table = context.model.name
782
1160
  if (grant.kind !== 'app') {
@@ -785,22 +1163,82 @@ function appGrant(context: TableContext, capability: unknown, operation: Operati
785
1163
  if (operation !== 'read') {
786
1164
  checkApplicationTable(context, operation)
787
1165
  }
1166
+ if (operation === 'read' && readsAny(context, grant)) {
1167
+ return { grant, actions: grant.actions, narrowed: false }
1168
+ }
788
1169
  checkAppReach(context, grant)
789
- checkAction(context, operation, grant.action)
790
- return grant
1170
+ return { grant, actions: operationActions(context, operation, grant), narrowed: true }
1171
+ }
1172
+
1173
+ /**
1174
+ * An `app` capability and those of its actions that allow one operation: every one it holds for a read of a table read
1175
+ * with `'any'`, which no `when` narrows.
1176
+ */
1177
+ interface AppOperation extends ReadReach {
1178
+ readonly grant: AppGrant
1179
+ }
1180
+
1181
+ /** The actions of `grant` that allow `operation` on the table, at least one; `checkAction` over a set. */
1182
+ function operationActions(context: TableContext, operation: Operation, grant: AppGrant): readonly string[] {
1183
+ const actions = requiredActions(context, operation)
1184
+ const allowing = admitted(grant.actions, actions)
1185
+ if (allowing.length === 0) {
1186
+ throw new CapabilityError(
1187
+ 'wrong_action',
1188
+ `${operation} on ${context.model.name} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`,
1189
+ )
1190
+ }
1191
+ return allowing
1192
+ }
1193
+
1194
+ /**
1195
+ * Whether `grant` reads `context`'s table because it is read with `'any'`: every `app` grant but a public procedure's,
1196
+ * which is refused there. The read is unconditioned: a `when` of the grant's action narrows only its writes.
1197
+ */
1198
+ function readsAny(context: TableContext, grant: AppGrant): boolean {
1199
+ const model = context.model
1200
+ if (model.scope.mode !== 'app' || !model.actions.readAny) {
1201
+ return false
1202
+ }
1203
+ if (grant.public) {
1204
+ throw new CapabilityError(
1205
+ 'wrong_capability',
1206
+ `a public procedure does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1207
+ )
1208
+ }
1209
+ return true
1210
+ }
1211
+
1212
+ /**
1213
+ * The rows `held`, the read actions of an `app` capability, read of `context`'s table within `branch`: narrowed by their
1214
+ * conditions, any one admitting a row, unless the table is read with `'any'`.
1215
+ */
1216
+ function appReadPredicate(context: TableContext, held: AppOperation, branch: OperationNode | 'all'): OperationNode {
1217
+ if (context.model.scope.mode === 'app' && context.model.actions.readAny) {
1218
+ return branch === 'all' ? ValueNode.createImmediate(true) : branch
1219
+ }
1220
+ return conditionedAny(context.model, held.actions, branch, new Date())
1221
+ }
1222
+
1223
+ /**
1224
+ * Every row a capability of an `app` endpoint reads in an application table, by the table's read actions it holds or
1225
+ * `'any'`, and the reach whose columns it answers.
1226
+ */
1227
+ export function appListRead(context: TableContext, capability: unknown): AppRead {
1228
+ const held = appGrant(context, capability, 'read')
1229
+ return { predicate: appReadPredicate(context, held, 'all'), reach: freeze({ actions: held.actions, narrowed: held.narrowed }) }
791
1230
  }
792
1231
 
793
- /** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
1232
+ /** `appListRead`'s rows. */
794
1233
  export function appListPredicate(context: TableContext, capability: unknown): OperationNode {
795
- appGrant(context, capability, 'read')
796
- return everything()
1234
+ return appListRead(context, capability).predicate
797
1235
  }
798
1236
 
799
1237
  /**
800
1238
  * Every row of an application table, for a `Ref` or a `Within` of its read action: what `ctx.db.app` of an `on`, `in`
801
1239
  * or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
802
1240
  */
803
- export function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode {
1241
+ export function scopedApplicationRead(context: TableContext, capability: unknown, branch: OperationNode | 'all' = 'all'): OperationNode {
804
1242
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
805
1243
  const model = context.model
806
1244
  if (model.scope.mode !== 'app') {
@@ -809,6 +1247,12 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
809
1247
  if (grant.kind === 'app') {
810
1248
  throw new CapabilityError('wrong_capability', `a read of ${model.name} from a scoped site needs a Ref or a Within, got ${describeGrant(grant)}`)
811
1249
  }
1250
+ if (model.actions.readAny) {
1251
+ throw new CapabilityError(
1252
+ 'wrong_capability',
1253
+ `a scoped site does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1254
+ )
1255
+ }
812
1256
  const read = requiredActions(context, 'read')
813
1257
  if (!includes(read, grant.action)) {
814
1258
  throw new CapabilityError(
@@ -816,14 +1260,15 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
816
1260
  `a scoped site reads ${model.name} with its read action ${read.join(' or ')} only; the capability holds ${grant.action}`,
817
1261
  )
818
1262
  }
819
- return everything()
1263
+ return conditioned(model, grant.action, branch, new Date())
820
1264
  }
821
1265
 
822
1266
  /** One row of an application table by its key, for an `app` capability of `operation`'s action. */
823
1267
  export function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode {
824
1268
  checkApplicationTable(context, operation)
825
- appGrant(context, capability, operation)
826
- return appKeyPredicate(context.model, key)
1269
+ const held = appGrant(context, capability, operation)
1270
+ const row = appKeyPredicate(context.model, key)
1271
+ return operation === 'read' ? appReadPredicate(context, held, row) : conditionedAny(context.model, held.actions, row, new Date())
827
1272
  }
828
1273
 
829
1274
  /**
@@ -833,14 +1278,20 @@ export function appRowPredicate(context: TableContext, capability: unknown, key:
833
1278
  export function claimScope(
834
1279
  context: TableContext,
835
1280
  capability: unknown,
836
- ): { readonly grant: AppGrant | WithinGrant; readonly scope: OperationNode | undefined } {
1281
+ ): { readonly grant: AppGrant | WithinGrant; readonly action: string; readonly scope: OperationNode | undefined } {
837
1282
  const model = context.model
838
1283
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
839
1284
  if (model.queue === undefined) {
840
1285
  throw new CapabilityError('undeclared_operation', `${model.name} is not a queue table: its policy declares no queue`)
841
1286
  }
842
1287
  if (grant.kind === 'app') {
843
- return { grant: appGrant(context, capability, 'update'), scope: everything() }
1288
+ const [action, ...more] = grant.actions
1289
+ // A claimed row's `row.ref` is finished under one action; only a job claims, and its `ctx.app(action)` holds one.
1290
+ if (more.length > 0) {
1291
+ throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a capability of one action, got one of ${grant.actions.join(', ')}`)
1292
+ }
1293
+ appGrant(context, capability, 'update')
1294
+ return { grant, action, scope: conditioned(model, action, 'all', new Date()) }
844
1295
  }
845
1296
  if (grant.kind !== 'within') {
846
1297
  throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a Within or an app capability, got ${describeGrant(grant)}`)
@@ -849,14 +1300,14 @@ export function claimScope(
849
1300
  throw new CapabilityError('table_kind', `${model.name} is an application table: claim it through ctx.db.app`)
850
1301
  }
851
1302
  checkAction(context, 'update', grant.action)
852
- const column = reachColumn(model, grant.dimension)
1303
+ const column = nodeColumnOf(model, grant.dimension)
853
1304
  if (column === undefined) {
854
1305
  throw new CapabilityError(
855
1306
  'out_of_reach',
856
1307
  `a Within of ${grant.dimension} does not reach ${model.name}: its containment chain does not hold ${grant.dimension}`,
857
1308
  )
858
1309
  }
859
- return { grant, scope: withinPredicate(model, column, grant) }
1310
+ return { grant, action: grant.action, scope: withinPredicate(context, column, grant, 'update') }
860
1311
  }
861
1312
 
862
1313
  /**
@@ -879,7 +1330,17 @@ export function claimedRowPredicate(context: TableContext, capability: unknown,
879
1330
  }
880
1331
  terms[terms.length] = equals(model.name, link.column, value)
881
1332
  }
882
- return allOf(terms)
1333
+ return conditioned(model, grant.action, allOf(terms), new Date())
1334
+ }
1335
+
1336
+ /** The row of an application table `key` names, as `actions` reach it: within their conditions, any one admitting it. */
1337
+ export function appKeyScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1338
+ return conditionedAny(model, actions, appKeyPredicate(model, key), new Date())
1339
+ }
1340
+
1341
+ /** The row `key` names, as a read by key with `actions` reaches it: unconditioned in a table read with `'any'`. */
1342
+ export function appGetScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1343
+ return model.actions.readAny ? appKeyPredicate(model, key) : appKeyScope(model, actions, key)
883
1344
  }
884
1345
 
885
1346
  /** The row of an application table `key` names. */
@@ -891,10 +1352,10 @@ export function appKeyPredicate(model: TableModel, key: unknown): OperationNode
891
1352
  }
892
1353
 
893
1354
  /**
894
- * The capability of an `app` endpoint whose action updates columns of an application table: its update action, or a
895
- * column's own write action. Which columns it updates follows from the action (`updatableBy`).
1355
+ * The actions of an `app` endpoint's capability that update columns of an application table, at least one: its update
1356
+ * action, or a column's own write action. Which columns they update follows from them (`updatableByAny`).
896
1357
  */
897
- export function updatingApp(context: TableContext, capability: unknown): AppGrant {
1358
+ export function updatingApp(context: TableContext, capability: unknown): readonly string[] {
898
1359
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
899
1360
  const table = context.model.name
900
1361
  if (grant.kind !== 'app') {
@@ -905,12 +1366,63 @@ export function updatingApp(context: TableContext, capability: unknown): AppGran
905
1366
  if (actions.length === 0) {
906
1367
  throw new CapabilityError('undeclared_operation', `${table} allows no update; its policy declares no update action`)
907
1368
  }
908
- for (let index = 0; index < actions.length; index++) {
909
- if (actions[index] === grant.action) {
910
- return grant
1369
+ const updating = admitted(grant.actions, actions)
1370
+ if (updating.length === 0) {
1371
+ throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`)
1372
+ }
1373
+ return updating
1374
+ }
1375
+
1376
+ /**
1377
+ * An `app` capability's update of the application table row `key`: `values`, read against the columns its update
1378
+ * actions write, and the row's scope under only those actions that write every given column, any one's condition
1379
+ * admitting the row. So several held actions never write one action's columns on rows only another one reaches.
1380
+ */
1381
+ export function appUpdate(
1382
+ context: TableContext,
1383
+ capability: unknown,
1384
+ key: unknown,
1385
+ values: unknown,
1386
+ ): { readonly scope: OperationNode; readonly changes: Map<string, Primitive | null> } {
1387
+ const model = context.model
1388
+ const updating = updatingApp(context, capability)
1389
+ const writable = updatableByAny(model, updating)
1390
+ const changes = readValues(values, writable, 'update', model)
1391
+ // `readValues` took only columns of `writable`, so those of them `changes` sets are every column it sets.
1392
+ const columns = namesOf(writable)
1393
+ const written: string[] = []
1394
+ for (let index = 0; index < columns.length; index++) {
1395
+ const name = columns[index] ?? ''
1396
+ if (changes.has(name)) {
1397
+ written[written.length] = name
911
1398
  }
912
1399
  }
913
- throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.action}`)
1400
+ const covering: string[] = []
1401
+ for (let index = 0; index < updating.length; index++) {
1402
+ const action = updating[index]
1403
+ if (action !== undefined && writesEvery(updatableBy(model, action), written)) {
1404
+ covering[covering.length] = action
1405
+ }
1406
+ }
1407
+ if (covering.length === 0) {
1408
+ throw new CapabilityError(
1409
+ 'wrong_action',
1410
+ `no action of ${updating.join(', ')} updates every column of this update of ${model.name} (${
1411
+ written.join(', ')
1412
+ }): update the columns of each action apart`,
1413
+ )
1414
+ }
1415
+ return { scope: appKeyScope(model, covering, key), changes }
1416
+ }
1417
+
1418
+ /** Whether `columns` holds each of `written`. */
1419
+ function writesEvery(columns: NameSet, written: readonly string[]): boolean {
1420
+ for (let index = 0; index < written.length; index++) {
1421
+ if (!inSet(columns, written[index])) {
1422
+ return false
1423
+ }
1424
+ }
1425
+ return true
914
1426
  }
915
1427
 
916
1428
  export function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode {
@@ -919,11 +1431,22 @@ export function childObjectPredicate(context: TableContext, parent: unknown, key
919
1431
  throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its parent Ref and its ${scope.key}`)
920
1432
  }
921
1433
  const grant = refGrant(context, parent, scope.parent.dimension, operation)
922
- return allOf([equals(context.model.name, scope.key, key), parentPredicate(context, grant)])
1434
+ return parentPredicate(context, grant, key)
923
1435
  }
924
1436
 
925
1437
  export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
926
- return { root, table: context.model.name, joins: root === 'SelectQueryNode' ? context.joins : {}, scope }
1438
+ // Every store write reaches its statement through here: a view's rows are its tables', never written (ADR-0072).
1439
+ if (context.model.view && root !== 'SelectQueryNode') {
1440
+ throw new QueryRefusedError('read_only', `${context.model.name} is a view, which no handler writes`)
1441
+ }
1442
+ return {
1443
+ root,
1444
+ table: context.model.name,
1445
+ joins: root === 'SelectQueryNode' ? context.joins : {},
1446
+ scope,
1447
+ subqueries: context.subqueries,
1448
+ through: context.through,
1449
+ }
927
1450
  }
928
1451
 
929
1452
  /**
@@ -949,9 +1472,29 @@ export function fencedWork<T>(runtime: DataLayerRuntime, work: (transaction: Ses
949
1472
  return fence === null ? session.transaction(work) : fencedTransaction(session, fence, work)
950
1473
  }
951
1474
 
952
- /** The action a capability holds, which its operation's checks already admitted. */
1475
+ /**
1476
+ * The one action a capability holds, which its operation's checks already admitted. An `anyOf` endpoint's `app`
1477
+ * capability that holds several is refused: it reads through `ctx.db.app`, which reads with every action it holds.
1478
+ */
953
1479
  export function heldAction(context: TableContext, capability: unknown): string {
954
- return runtimeOf(context.connection).capabilities.resolve(capability).action
1480
+ const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1481
+ if (grant.kind !== 'app') {
1482
+ return grant.action
1483
+ }
1484
+ const [action, ...more] = grant.actions
1485
+ if (more.length > 0) {
1486
+ throw new CapabilityError(
1487
+ 'wrong_capability',
1488
+ `this read takes a capability of one action, got one of ${grant.actions.join(', ')}: read through ctx.db.app`,
1489
+ )
1490
+ }
1491
+ return action
1492
+ }
1493
+
1494
+ /** The one action a capability holds, or `undefined` for an `anyOf` endpoint's `app` capability that holds several. */
1495
+ function soleAction(context: TableContext, capability: unknown): string | undefined {
1496
+ const actions = grantActions(runtimeOf(context.connection).capabilities.resolve(capability))
1497
+ return actions.length === 1 ? actions[0] : undefined
955
1498
  }
956
1499
 
957
1500
  function storeRunner(context: TableContext): Runner {
@@ -1003,6 +1546,10 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
1003
1546
  copied.set(key, fileValue(model, key, value))
1004
1547
  continue
1005
1548
  }
1549
+ if (inSet(model.json, key)) {
1550
+ copied.set(key, value === null ? null : jsonText(model, key, value))
1551
+ continue
1552
+ }
1006
1553
  if (value !== null && !isPrimitive(value)) {
1007
1554
  throw new QueryRefusedError('invalid_argument', `${table}.${key} takes a plain value (string, number, bigint, boolean, Date or null)`)
1008
1555
  }
@@ -1011,6 +1558,13 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
1011
1558
  return copied
1012
1559
  }
1013
1560
 
1561
+ /** A JSON column's bound text: its declared schema's output, or the value itself where none is declared. */
1562
+ function jsonText(model: TableModel, column: string, value: unknown): string | null {
1563
+ const schema = ownEntry(model.jsonSchemas, column)
1564
+ const where = `${model.name}.${column}`
1565
+ return schema === undefined ? jsonInput(value, where) : schemaInput(schema, value, where)
1566
+ }
1567
+
1014
1568
  /** A day's or a timestamp's text, checked before it is bound; any other column's text as it is. */
1015
1569
  function temporalText(model: TableModel, column: string, value: string): string {
1016
1570
  if (inSet(model.dates, column)) {
@@ -1052,28 +1606,61 @@ async function selectRows<S>(
1052
1606
  context: TableContext,
1053
1607
  scope: OperationNode | undefined,
1054
1608
  state: SelectState,
1055
- action: string,
1609
+ action: string | undefined,
1056
1610
  visible: readonly string[] = context.model.visible,
1057
1611
  ): Promise<S[]> {
1058
1612
  const run = storeRunner(context)
1613
+ const now = new Date()
1614
+ const joins: JoinState[] = []
1059
1615
  for (let index = 0; index < state.joins.length; index++) {
1060
1616
  const join = state.joins[index]
1061
- if (join !== undefined && !includes(join.join.readActions, action)) {
1617
+ if (join === undefined) continue
1618
+ if (action === undefined) {
1619
+ throw new CapabilityError('wrong_capability', `joining ${join.join.shape.table} takes a capability of one action, whose condition narrows it`)
1620
+ }
1621
+ if (!includes(join.join.readActions, action)) {
1062
1622
  throw new CapabilityError(
1063
1623
  'wrong_action',
1064
1624
  `joining ${join.join.shape.table} requires ${join.join.readActions.join(' or ')}; the capability holds ${action}`,
1065
1625
  )
1066
1626
  }
1627
+ joins[joins.length] = heldJoin(context, join, action, now)
1067
1628
  }
1068
1629
  if (scope === undefined) {
1069
1630
  return []
1070
1631
  }
1071
1632
  const dialect = dialectOf(context)
1072
- const node = selectNode(boundState(context, state), visible, scope, undefined, context.model.dates, dialect)
1633
+ const node = selectNode(boundState(context, { ...state, joins }), visible, scope, undefined, context.model.dates, dialect)
1073
1634
  const rows = await (await run.read()).run<S>(node, guard(context, 'SelectQueryNode', scope))
1074
1635
  return answerRows(dialect, context.model.name, joinedColumns(context, state), rows)
1075
1636
  }
1076
1637
 
1638
+ /**
1639
+ * `join` narrowed by the child's condition of `action`, as a read of the child narrows its rows. The guard admits no
1640
+ * subquery in an ON, so a condition that reads other rows (a path, `some`, `none`) refuses the join.
1641
+ */
1642
+ function heldJoin(context: TableContext, join: JoinState, action: string, now: Date): JoinState {
1643
+ const child = ownEntry(context.children, join.join.shape.table)
1644
+ if (child === undefined) {
1645
+ throw new QueryRefusedError('unknown_table', `${join.join.shape.table} is not a joinable child of ${context.model.name}`)
1646
+ }
1647
+ const condition = ownEntry(child.when, action)
1648
+ if (condition === undefined) {
1649
+ return join
1650
+ }
1651
+ let reads = false
1652
+ conditionReach(condition, () => {
1653
+ reads = true
1654
+ })
1655
+ if (reads) {
1656
+ throw new CapabilityError(
1657
+ 'unenforceable',
1658
+ `joining ${child.name} cannot hold its condition of ${action}, which reads other rows; read ${child.name} through its own handle`,
1659
+ )
1660
+ }
1661
+ return { ...join, condition: conditionNode(child.name, condition, now) }
1662
+ }
1663
+
1077
1664
  /** The column sets of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
1078
1665
  function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1079
1666
  const own = rowColumnsOf(context.model)
@@ -1096,23 +1683,42 @@ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1096
1683
  }
1097
1684
  return nameSet(names)
1098
1685
  }
1686
+ const jsonSchemas: Record<string, JsonSchema> = {}
1687
+ const owned = ownKeys(own.jsonSchemas)
1688
+ for (let index = 0; index < owned.length; index++) {
1689
+ const column = owned[index] ?? ''
1690
+ const schema = ownEntry(own.jsonSchemas, column)
1691
+ if (schema !== undefined) setOwn(jsonSchemas, column, schema)
1692
+ }
1693
+ for (let index = 0; index < state.joins.length; index++) {
1694
+ const table = state.joins[index]?.join.shape.table ?? ''
1695
+ const schemas = ownEntry(context.children, table)?.jsonSchemas ?? {}
1696
+ const columns = ownKeys(schemas)
1697
+ for (let position = 0; position < columns.length; position++) {
1698
+ const column = columns[position] ?? ''
1699
+ const schema = ownEntry(schemas, column)
1700
+ if (schema !== undefined) setOwn(jsonSchemas, `${table}.${column}`, schema)
1701
+ }
1702
+ }
1099
1703
  return {
1100
1704
  days: joined((columns) => columns.days),
1101
1705
  timestamps: joined((columns) => columns.timestamps),
1102
1706
  booleans: joined((columns) => columns.booleans),
1707
+ json: joined((columns) => columns.json),
1708
+ jsonSchemas: freeze(jsonSchemas),
1103
1709
  }
1104
1710
  }
1105
1711
 
1106
1712
  /**
1107
1713
  * One row by its scope predicate, with `visible` columns (the table's read action's, unless a capability reads its own).
1108
- * `action` is what read it: each file column then answers a reference that reads the file only under a read action.
1714
+ * `reach` is what read it: each file column then answers a reference that reads the file only under a read action.
1109
1715
  */
1110
1716
  export async function selectOne<O>(
1111
1717
  context: TableContext,
1112
1718
  run: Runner,
1113
1719
  scope: OperationNode,
1114
1720
  visible = context.model.visible,
1115
- action?: string,
1721
+ reach?: ReadReach,
1116
1722
  ): Promise<O> {
1117
1723
  const start = startSelect(context.shape)
1118
1724
  const state = finishSelect(start, start)
@@ -1124,8 +1730,8 @@ export async function selectOne<O>(
1124
1730
  if (row === undefined) {
1125
1731
  throw new NotFoundError(`${context.model.name} not found`)
1126
1732
  }
1127
- if (action !== undefined) {
1128
- await answerFiles(context.model, run.files, session, [row], action)
1733
+ if (reach !== undefined) {
1734
+ await answerFiles(context.model, run.files, session, [row], reach)
1129
1735
  }
1130
1736
  return row
1131
1737
  }
@@ -1195,29 +1801,55 @@ export function keyOf(model: TableModel): string {
1195
1801
  * Locks the destination row `for share` and checks that it still lies where the Ref's chain says. Without it, a
1196
1802
  * Ref minted before its object moved would insert into, or move rows into, the object's new container.
1197
1803
  */
1198
- async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
1804
+ async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<void> {
1805
+ if (!(await destinationHeld(transaction, context, grant, paths))) {
1806
+ throw context.destination === undefined
1807
+ ? new NotFoundError(`no row holds ${grant.action} for the Ref's principal at ${grant.dimension} ${grant.id} any more; obtain a fresh Ref`)
1808
+ : new NotFoundError(`${context.destination.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
1809
+ }
1810
+ }
1811
+
1812
+ /** Whether the destination still lies where `grant`'s chain says and still holds it, locked `for share` (`lockDestination`). */
1813
+ async function destinationHeld(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
1199
1814
  const owner = context.destination
1200
1815
  if (owner === undefined) {
1201
- return
1816
+ // No table owns the destination, so a Ref held through relations or member reveals is checked on the rows that hold it.
1817
+ return grant.relations.length === 0 && grant.revealing.length === 0 ? true : await holdingRowLocked(transaction, context, grant)
1202
1818
  }
1203
- const scope = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
1819
+ const chain = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
1820
+ // A Ref held through a relation or a member reveal inserts only while a row of it still holds the destination.
1821
+ const gate = relationGate(context, owner, grant, new Date(), paths ?? heldThrough(grant.action))
1822
+ const scope = gate === undefined ? chain : allOf([chain, gate])
1204
1823
  const node = lockNode(owner.name, keyOf(owner), scope)
1205
- const rows = await transaction.run(node, { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, lock: 'share' })
1206
- if (rows.length === 0) {
1207
- throw new NotFoundError(`${owner.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
1208
- }
1824
+ const rows = await transaction.run(node, {
1825
+ root: 'SelectQueryNode',
1826
+ table: owner.name,
1827
+ joins: {},
1828
+ scope,
1829
+ lock: 'share',
1830
+ subqueries: context.subqueries,
1831
+ })
1832
+ return rows.length > 0
1209
1833
  }
1210
1834
 
1835
+ /** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
1211
1836
  export async function insertRow<O>(
1212
1837
  context: TableContext,
1213
1838
  run: Runner,
1214
1839
  given: ReadonlyMap<string, Primitive | null>,
1215
- destination: RefGrant | undefined,
1840
+ prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined,
1216
1841
  ): Promise<O> {
1217
1842
  const values = boundValues(context, given)
1218
1843
  return run.write(async (transaction) => {
1219
- if (destination !== undefined) {
1220
- await lockDestination(transaction, context, destination)
1844
+ if (prepared?.destination !== undefined) {
1845
+ await lockDestination(transaction, context, prepared.destination)
1846
+ }
1847
+ const before = await narrowedHolds(transaction, context, prepared)
1848
+ if (prepared !== undefined) {
1849
+ await checkPrincipalAssign(transaction, context, prepared.writer, given)
1850
+ await checkRevealAssign(transaction, context, prepared.writer, given)
1851
+ await checkMemberRevealAssign(transaction, context, prepared.writer, given)
1852
+ await checkPathWriters(transaction, context, prepared.writer, given)
1221
1853
  }
1222
1854
  const [row] = await transaction.run<O>(insertNode(context.model.name, values, answer(context)), guard(context, 'InsertQueryNode', undefined))
1223
1855
  if (row === undefined) {
@@ -1225,6 +1857,8 @@ export async function insertRow<O>(
1225
1857
  }
1226
1858
  checkVersion(context, row)
1227
1859
  await referenceInserted(context, run, transaction, values)
1860
+ await judgeInserted(transaction, context, prepared?.judged, values.get(keyOf(context.model)))
1861
+ await judgeNarrowed(transaction, context, prepared, before, values.get(keyOf(context.model)))
1228
1862
  return row
1229
1863
  })
1230
1864
  }
@@ -1238,18 +1872,20 @@ export interface OnConflict {
1238
1872
  readonly mode: 'nothing' | 'update'
1239
1873
  /** The values given for the table's update columns: what `update` sets on the conflicting row. */
1240
1874
  readonly updates: ReadonlyMap<string, Primitive | null>
1875
+ /** The capability's update actions, one of whose conditions the conflicting row must satisfy to be updated. */
1876
+ readonly actions: readonly string[]
1241
1877
  }
1242
1878
 
1243
1879
  const CONFLICT_FIELDS = nameSet(['columns', 'do'])
1244
1880
 
1245
1881
  /**
1246
1882
  * The `onConflict` of an insert's options, read through own data properties; `undefined` without options. `'update'`
1247
- * also needs the capability's action to be one of the table's update actions.
1883
+ * also needs one of the capability's `actions` to be one of the table's update actions.
1248
1884
  */
1249
1885
  export function onConflictOf(
1250
1886
  context: TableContext,
1251
1887
  options: unknown,
1252
- action: string,
1888
+ actions: readonly string[],
1253
1889
  given: ReadonlyMap<string, Primitive | null>,
1254
1890
  ): OnConflict | undefined {
1255
1891
  if (options === undefined) {
@@ -1266,6 +1902,10 @@ export function onConflictOf(
1266
1902
  if (!inSet(model.columns, name)) {
1267
1903
  throw new QueryRefusedError('on_conflict', `onConflict names ${String(name)}, which is not a column of ${model.name}`)
1268
1904
  }
1905
+ if (inSet(model.json, name)) {
1906
+ // jsonb compares by value and SQLite's text by spelling: the two dialects would disagree about a conflict.
1907
+ throw new QueryRefusedError('on_conflict', `onConflict names ${name}, a JSON column of ${model.name}, which the data layer never compares`)
1908
+ }
1269
1909
  return name
1270
1910
  })
1271
1911
  if (columns === undefined || columns.length === 0) {
@@ -1276,13 +1916,14 @@ export function onConflictOf(
1276
1916
  throw new QueryRefusedError('on_conflict', "onConflict.do takes 'nothing' or 'update'")
1277
1917
  }
1278
1918
  const updates = new Map<string, Primitive | null>()
1919
+ const updating = admitted(actions, model.actions.update)
1279
1920
  if (mode === 'update') {
1280
- if (!includes(model.actions.update, action)) {
1921
+ if (updating.length === 0) {
1281
1922
  throw new CapabilityError(
1282
1923
  'wrong_action',
1283
1924
  `an insert of ${model.name} that updates on a conflict also needs its update action ${
1284
1925
  model.actions.update.join(' or ') || '(none)'
1285
- }; the capability holds ${action}`,
1926
+ }; the capability holds ${actions.join(', ')}`,
1286
1927
  )
1287
1928
  }
1288
1929
  const columns = namesOf(model.update)
@@ -1294,7 +1935,7 @@ export function onConflictOf(
1294
1935
  }
1295
1936
  }
1296
1937
  }
1297
- return freeze({ columns: freeze(columns), mode, updates })
1938
+ return freeze({ columns: freeze(columns), mode, updates, actions: freeze(updating) })
1298
1939
  }
1299
1940
 
1300
1941
  /** A plain object's own data properties, each one of `allowed`; the options of an insert or its `onConflict`. */
@@ -1349,8 +1990,8 @@ function insertedScope(context: TableContext, values: ReadonlyMap<string, Primit
1349
1990
 
1350
1991
  /**
1351
1992
  * `insert … on conflict (columns) do nothing`, and for `update` the conflicting row's update in the same transaction,
1352
- * within the insert's own containment. A row deleted between the two is inserted on the second try; a conflicting row
1353
- * the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
1993
+ * within the insert's own containment and the action's condition on the stored row. A row deleted between the two is
1994
+ * inserted on the second try; a conflicting row the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
1354
1995
  * false }` after an update, and `{ inserted: false }` when `nothing` wrote nothing.
1355
1996
  */
1356
1997
  async function insertOnConflict(
@@ -1372,7 +2013,7 @@ async function insertOnConflict(
1372
2013
  }
1373
2014
  matches[matches.length] = equals(model.name, name, value)
1374
2015
  }
1375
- const scope = conflict.mode === 'update' ? insertedScope(context, values) : undefined
2016
+ const scope = conflict.mode === 'update' ? conditionedAny(model, conflict.actions, insertedScope(context, values), new Date()) : undefined
1376
2017
  for (let attempt = 0; attempt < 2; attempt++) {
1377
2018
  const node = insertNode(model.name, values, answer(context), conflict.columns)
1378
2019
  const [row] = await transaction.run<Readonly<Record<string, unknown>>>(node, {
@@ -1453,7 +2094,7 @@ export async function updateRow<O>(
1453
2094
  target: Addressed,
1454
2095
  given: ReadonlyMap<string, Primitive | null>,
1455
2096
  expectedVersion: OperationNode | undefined,
1456
- destination?: RefGrant,
2097
+ moved?: MovedRow,
1457
2098
  ): Promise<O> {
1458
2099
  const { name: table, version } = context.model
1459
2100
  const changes = boundValues(context, given)
@@ -1463,19 +2104,42 @@ export async function updateRow<O>(
1463
2104
  ? acknowledgementNode(table, keyOf(context.model), version, where)
1464
2105
  : updateNode(table, changes, version, where, answer(context))
1465
2106
  return run.write(async (transaction) => {
1466
- if (destination !== undefined) {
1467
- await lockDestination(transaction, context, destination)
2107
+ // A move follows containment, so a path never holds its destination.
2108
+ if (moved !== undefined) {
2109
+ await lockDestination(transaction, context, moved.destination, noPath)
1468
2110
  }
2111
+ const before = moved === undefined ? undefined : await narrowedHolds(transaction, context, moved, noPath)
1469
2112
  const [row] = await transaction.run<O>(node, guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', target.scope))
1470
2113
  if (row !== undefined) {
1471
2114
  checkVersion(context, row)
1472
2115
  await referenceUpdated(context, run, transaction, changes, row)
2116
+ if (moved !== undefined) {
2117
+ await judgeInserted(transaction, context, moved.judged, rowKey(context, row))
2118
+ await judgeNarrowed(transaction, context, moved, before, rowKey(context, row))
2119
+ }
1473
2120
  return row
1474
2121
  }
1475
2122
  return missingOrChanged(context, transaction, target, expectedVersion)
1476
2123
  })
1477
2124
  }
1478
2125
 
2126
+ /**
2127
+ * A move's destination, locked before the write, and the destination's insert conditions, which judge the moved row
2128
+ * after it as an insert into the destination judges its row: the insert action's (`judgeInserted`), and each one
2129
+ * `relationWhen` puts on a relation the destination `Ref` holds through (`judgeNarrowed`).
2130
+ */
2131
+ export interface MovedRow {
2132
+ readonly destination: RefGrant
2133
+ readonly judged: JudgedInsert | undefined
2134
+ readonly narrowed: readonly NarrowedInsert[]
2135
+ }
2136
+
2137
+ /** The key `row`, a write's acknowledgement, answers; `undefined` when it answers none as text. */
2138
+ function rowKey(context: TableContext, row: unknown): string | undefined {
2139
+ const value: unknown = typeof row === 'object' && row !== null ? ownDescriptor(row, keyOf(context.model))?.value : undefined
2140
+ return typeof value === 'string' ? value : undefined
2141
+ }
2142
+
1479
2143
  /** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
1480
2144
  export async function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void> {
1481
2145
  const node = deleteNode(context.model.name, scopedWhere(conditionsWith(target, expectedVersion), target.scope), keyOf(context.model))
@@ -1491,11 +2155,11 @@ type Columns<Row> = keyof Row & string
1491
2155
  type NumericColumn<Row> = { [K in Columns<Row>]: Exclude<Row[K], null> extends number | bigint | string ? K : never }[Columns<Row>]
1492
2156
 
1493
2157
  export interface AggregateSpec<Row> {
1494
- readonly groupBy?: readonly Columns<Row>[]
2158
+ readonly groupBy?: readonly ComparableColumn<Row>[]
1495
2159
  readonly count?: boolean
1496
2160
  readonly sum?: readonly NumericColumn<Row>[]
1497
- readonly min?: readonly Columns<Row>[]
1498
- readonly max?: readonly Columns<Row>[]
2161
+ readonly min?: readonly ComparableColumn<Row>[]
2162
+ readonly max?: readonly ComparableColumn<Row>[]
1499
2163
  readonly where?: (q: ScopedSelect<Row, Row, NoColumns>) => ScopedSelect<Row, unknown, NoColumns>
1500
2164
  }
1501
2165
 
@@ -1532,7 +2196,7 @@ function aggregateColumns(table: string, shape: TableShape, spec: AggregateInput
1532
2196
  if (!inSet(shape.visible, name)) {
1533
2197
  throw new QueryRefusedError('unknown_column', `${String(name)} is not a column of ${table} (columns: ${namesOf(shape.visible).join(', ')})`)
1534
2198
  }
1535
- return name
2199
+ return comparableColumnOf(shape, name, 'aggregates')
1536
2200
  })
1537
2201
  if (names === undefined) {
1538
2202
  throw new QueryRefusedError('invalid_argument', `aggregate ${field} takes a plain array of column names`)
@@ -1555,7 +2219,7 @@ function aggregateFilter<Row>(shape: TableShape, where: AggregateSpec<Row>['wher
1555
2219
  throw new QueryRefusedError('invalid_argument', 'aggregate where takes a callback')
1556
2220
  }
1557
2221
  const start = startSelect<Row, NoColumns>(shape)
1558
- const state = finishSelect(where(start), start)
2222
+ const state = finishFilter(where(start), start)
1559
2223
  if (state.columns !== undefined || state.orderBy.length > 0 || state.limit !== undefined || state.offset !== undefined || state.joins.length > 0) {
1560
2224
  throw new QueryRefusedError('invalid_argument', 'aggregate where takes where conditions only')
1561
2225
  }
@@ -1574,7 +2238,8 @@ export async function aggregateRows<Row, O>(
1574
2238
  }
1575
2239
  const columns = aggregateColumns(context.model.name, shape, spec)
1576
2240
  const filter = aggregateFilter(shape, spec.where)
1577
- if (scope === undefined) {
2241
+ // An `in` with an empty list answers what an empty `Within` does, and sends no statement.
2242
+ if (scope === undefined || filter?.matchesNone === true) {
1578
2243
  return []
1579
2244
  }
1580
2245
  const dialect = dialectOf(context)
@@ -1586,6 +2251,8 @@ export async function aggregateRows<Row, O>(
1586
2251
  days: aggregated(own.days, columns),
1587
2252
  timestamps: aggregated(own.timestamps, columns),
1588
2253
  booleans: aggregated(own.booleans, columns),
2254
+ json: nameSet([]),
2255
+ jsonSchemas: freeze({}),
1589
2256
  }, rows)
1590
2257
  return dialect === 'postgres' ? answered : sqliteAggregates(context.model.name, columns, answered)
1591
2258
  }
@@ -1641,8 +2308,25 @@ function sqliteAggregates<O>(table: string, columns: AggregateColumns, rows: O[]
1641
2308
  /** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
1642
2309
  export interface PreparedInsert {
1643
2310
  readonly row: Map<string, Primitive | null>
2311
+ /** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
2312
+ readonly writer: string
1644
2313
  readonly destination: RefGrant | undefined
1645
2314
  readonly conflict: OnConflict | undefined
2315
+ /** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
2316
+ readonly judged: JudgedInsert | undefined
2317
+ /** The destination's relations whose `relationWhen` for the insert follows a path: judged on the written row. */
2318
+ readonly narrowed: readonly NarrowedInsert[]
2319
+ }
2320
+
2321
+ export interface JudgedInsert {
2322
+ readonly action: string
2323
+ readonly condition: ConditionModel
2324
+ }
2325
+
2326
+ /** A relation the destination `Ref` holds through, which the inserted table narrows for the insert by a condition with a path. */
2327
+ export interface NarrowedInsert {
2328
+ readonly relation: string
2329
+ readonly condition: ConditionModel
1646
2330
  }
1647
2331
 
1648
2332
  /**
@@ -1653,25 +2337,66 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
1653
2337
  const scope = dimensionScope(context.model)
1654
2338
  const grant = refGrant(context, target, listDimension(scope), 'insert')
1655
2339
  const row = readValues(values, context.model.insert, 'insert', context.model)
1656
- const conflict = onConflictOf(context, options, grant.action, row)
2340
+ const conflict = onConflictOf(context, options, [grant.action], row)
1657
2341
  if (scope.container === undefined) {
1658
2342
  // The object does not exist yet; this only refuses a chain the table has no column for.
1659
2343
  linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
1660
2344
  stampInsert(context, grant, row, scope.key, grant.id)
1661
- return { row, destination: undefined, conflict }
2345
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2346
+ // No destination to check again after the write, so a condition with a path holds nothing here.
2347
+ narrowedDestination(context, grant, row, false)
2348
+ return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
1662
2349
  }
1663
2350
  stampInsert(context, grant, row, scope.key, uuidv7())
1664
2351
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1665
- return { row, destination: grant, conflict }
2352
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2353
+ const held = narrowedDestination(context, grant, row, true)
2354
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
1666
2355
  }
1667
2356
 
1668
2357
  /** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
1669
2358
  export function prepareApplicationInsert(context: TableContext, capability: unknown, values: unknown, options?: unknown): PreparedInsert {
1670
- const grant = appGrant(context, capability, 'insert')
2359
+ const { grant, actions } = appGrant(context, capability, 'insert')
2360
+ // Every insert action writes the table's one insert list, so each held one writes all of `values`: only their conditions differ.
1671
2361
  const row = readValues(values, context.model.insert, 'insert', context.model)
1672
- const conflict = onConflictOf(context, options, grant.action, row)
2362
+ // Only an insert action that also updates may update on a conflict: never one action's insert with another's update.
2363
+ const declared = onConflictOf(context, options, actions, row)
1673
2364
  stampInsert(context, grant, row, keyOf(context.model), uuidv7())
1674
- return { row, destination: undefined, conflict }
2365
+ const conflict = declared?.mode === 'update' ? upsertingActions(context.model, declared, row) : declared
2366
+ const judged = checkInserted(context, conflict?.mode === 'update' ? conflict.actions : actions, grant.principal, row)
2367
+ return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
2368
+ }
2369
+
2370
+ /**
2371
+ * An upsert under several actions that each insert and update: only those whose own condition admits the inserted row
2372
+ * may update the conflicting one, so the update runs under an action whose insert alone was allowed. A condition that
2373
+ * follows a path is judged only in the transaction, after the update chose its actions, so several such are refused.
2374
+ */
2375
+ function upsertingActions(model: TableModel, conflict: OnConflict, row: ReadonlyMap<string, Primitive | null>): OnConflict {
2376
+ if (conflict.actions.length < 2) {
2377
+ return conflict
2378
+ }
2379
+ const now = new Date()
2380
+ const admitting: string[] = []
2381
+ for (let index = 0; index < conflict.actions.length; index++) {
2382
+ const action = conflict.actions[index] ?? ''
2383
+ const condition = ownEntry(model.when, action)
2384
+ if (condition !== undefined && readPaths(condition).length > 0) {
2385
+ throw new CapabilityError(
2386
+ 'unenforceable',
2387
+ `an insert into ${model.name} that updates on a conflict under ${
2388
+ conflict.actions.join(', ')
2389
+ } would pair a condition that follows a path with another action's: upsert from an endpoint of one of them`,
2390
+ )
2391
+ }
2392
+ if (condition === undefined || rowSatisfies(condition, row, now)) {
2393
+ admitting[admitting.length] = action
2394
+ }
2395
+ }
2396
+ // None admits the row: keep them all, and the insert's own check refuses it.
2397
+ return admitting.length === 0
2398
+ ? conflict
2399
+ : freeze({ columns: conflict.columns, mode: conflict.mode, updates: conflict.updates, actions: freeze(admitting) })
1675
2400
  }
1676
2401
 
1677
2402
  /** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
@@ -1679,52 +2404,574 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
1679
2404
  const scope = childScope(context)
1680
2405
  const grant = refGrant(context, parent, scope.parent.dimension, 'insert')
1681
2406
  const row = readValues(values, context.model.insert, 'insert', context.model)
1682
- const conflict = onConflictOf(context, options, grant.action, row)
2407
+ const conflict = onConflictOf(context, options, [grant.action], row)
1683
2408
  stampInsert(context, grant, row, scope.key, uuidv7())
1684
2409
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1685
- return { row, destination: grant, conflict }
2410
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2411
+ const held = narrowedDestination(context, grant, row, true)
2412
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
1686
2413
  }
1687
2414
 
1688
- /** Writes each chain column the destination `Ref` settles into an insert's row. */
1689
- function stampChain(row: Map<string, Primitive | null>, values: readonly LinkValue[]): void {
1690
- for (let index = 0; index < values.length; index++) {
1691
- const entry = values[index]
1692
- if (entry !== undefined) {
1693
- row.set(entry.link.column, entry.value)
1694
- }
1695
- }
1696
- }
2415
+ const DAY_MS = 86_400_000
1697
2416
 
1698
- /** A prepared insert, with its conflict handling when the caller named one. */
1699
- export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
1700
- const conflict = prepared.conflict
1701
- if (conflict === undefined) {
1702
- return insertRow(context, run, prepared.row, prepared.destination)
1703
- }
1704
- return run.write(async (transaction) => {
2417
+ /**
2418
+ * An inserted row as its insert action's condition judges it, on its final values, and, for a relation source, within
2419
+ * its delegation bound: a row naming the inserting principal only with `assign.self`, an expiry at most `maxDays`
2420
+ * ahead. Its node is the inserting Ref's, stamped above, so a row confers only where its writer acts. A condition
2421
+ * that follows a path is answered for the transaction to judge.
2422
+ */
2423
+ function checkInserted(
2424
+ context: TableContext,
2425
+ actions: readonly string[],
2426
+ principal: string,
2427
+ row: ReadonlyMap<string, Primitive | null>,
2428
+ ): JudgedInsert | undefined {
2429
+ const model = context.model
2430
+ const now = new Date()
2431
+ const judged = insertCondition(model, actions, row, now)
2432
+ for (let index = 0; index < model.confers.length; index++) {
2433
+ const source = model.confers[index]
2434
+ if (source === undefined) {
2435
+ continue
2436
+ }
2437
+ const assign = source.assign
2438
+ if (assign === undefined) {
2439
+ throw new CapabilityError('undeclared_operation', `${model.name} confers ${source.relation} and states no assign, so no handler inserts a row`)
2440
+ }
2441
+ // A principal through a path is resolved in the insert's transaction (`checkPrincipalAssign`).
2442
+ if (!assign.self && source.principalPath === undefined && row.get(source.principal) === principal) {
2443
+ throw new ConflictError(`a row of ${model.name} names its writer in ${source.relation}, which assign.self does not allow`)
2444
+ }
2445
+ if (assign.maxDays !== undefined && source.expires !== undefined) {
2446
+ const value = row.get(source.expires)
2447
+ const until = value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : Number.NaN
2448
+ if (Number.isNaN(until) || until > now.getTime() + assign.maxDays * DAY_MS) {
2449
+ throw new ConflictError(
2450
+ `a row of ${model.name} confers ${source.relation} until ${source.expires}, at most ${assign.maxDays} days ahead`,
2451
+ )
2452
+ }
2453
+ }
2454
+ }
2455
+ return judged
2456
+ }
2457
+
2458
+ /**
2459
+ * The insert actions' condition on the row, as one role holding `actions` is narrowed: a row any of them admits passes,
2460
+ * and one without a condition admits every row. A pathless condition is judged here; one that follows a path is
2461
+ * answered for the transaction to judge, which holds one such condition only, so several are refused.
2462
+ */
2463
+ function insertCondition(
2464
+ model: TableModel,
2465
+ actions: readonly string[],
2466
+ row: ReadonlyMap<string, Primitive | null>,
2467
+ now: Date,
2468
+ ): JudgedInsert | undefined {
2469
+ const pathed: JudgedInsert[] = []
2470
+ for (let index = 0; index < actions.length; index++) {
2471
+ const action = actions[index]
2472
+ if (action === undefined) continue
2473
+ const condition = ownEntry(model.when, action)
2474
+ if (condition === undefined) {
2475
+ return undefined
2476
+ }
2477
+ if (readPaths(condition).length > 0) {
2478
+ pathed[pathed.length] = { action, condition }
2479
+ } else if (rowSatisfies(condition, row, now)) {
2480
+ return undefined
2481
+ }
2482
+ }
2483
+ const [only, ...more] = pathed
2484
+ if (only === undefined) {
2485
+ throw new ConflictError(`the row is outside what ${actions.join(' or ')} inserts into ${model.name}`)
2486
+ }
2487
+ if (more.length > 0) {
2488
+ throw new CapabilityError(
2489
+ 'unenforceable',
2490
+ `an insert into ${model.name} under ${
2491
+ actions.join(', ')
2492
+ } would be judged by several conditions that follow paths: insert from an endpoint of one of them`,
2493
+ )
2494
+ }
2495
+ return only
2496
+ }
2497
+
2498
+ /**
2499
+ * The destination `Ref` an insert locks, without the relations the inserted table's `relationWhen` narrows for the insert
2500
+ * and the written row fails: a pathless condition judged here, on the row's final values; one with a path answered for
2501
+ * the transaction to judge (`judgeNarrowed`), or, without a destination to check again (`defer` false), held to fail. A Ref held by nothing else then is refused (409): the relation's membership
2502
+ * is never judged on the written row, so the row never counts towards its own insert.
2503
+ */
2504
+ function narrowedDestination(
2505
+ context: TableContext,
2506
+ grant: RefGrant,
2507
+ row: ReadonlyMap<string, Primitive | null>,
2508
+ defer: boolean,
2509
+ ): { readonly destination: RefGrant; readonly narrowed: readonly NarrowedInsert[] } {
2510
+ const now = new Date()
2511
+ const kept: RelationHold[] = []
2512
+ const narrowed: NarrowedInsert[] = []
2513
+ for (let index = 0; index < grant.relations.length; index++) {
2514
+ const hold = grant.relations[index]
2515
+ if (hold === undefined) continue
2516
+ const relation = hold.relation
2517
+ const condition = relationCondition(context.model, relation, grant.action)
2518
+ const pathed = condition !== undefined && readPaths(condition).length > 0
2519
+ if (condition !== undefined && pathed && defer && !judgesRelation(narrowed, relation)) {
2520
+ narrowed[narrowed.length] = { relation, condition }
2521
+ }
2522
+ if (condition === undefined || (pathed ? defer : rowSatisfies(condition, row, now))) {
2523
+ kept[kept.length] = hold
2524
+ }
2525
+ }
2526
+ if (kept.length === grant.relations.length) {
2527
+ return { destination: grant, narrowed }
2528
+ }
2529
+ if (kept.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
2530
+ throw new ConflictError(`the row is outside what ${grant.action} inserts into ${context.model.name} through its relations`)
2531
+ }
2532
+ return { destination: { ...grant, relations: kept }, narrowed }
2533
+ }
2534
+
2535
+ /** Whether `narrowed` already judges `relation`: two holds of one relation are judged once. */
2536
+ function judgesRelation(narrowed: readonly NarrowedInsert[], relation: string): boolean {
2537
+ for (let index = 0; index < narrowed.length; index++) {
2538
+ if (narrowed[index]?.relation === relation) return true
2539
+ }
2540
+ return false
2541
+ }
2542
+
2543
+ /**
2544
+ * What held an insert's destination before the write, apart from the relations narrowed by a path: the rest of the
2545
+ * `Ref`, and, with several such relations, each of them alone. Decided before the row exists, so it never counts it.
2546
+ */
2547
+ interface NarrowedHolds {
2548
+ readonly rest: boolean
2549
+ readonly alone: readonly string[]
2550
+ }
2551
+
2552
+ /** `NarrowedHolds` of a prepared insert, locked `for share` in its transaction before the write; `undefined` with nothing narrowed. */
2553
+ async function narrowedHolds(
2554
+ transaction: Session,
2555
+ context: TableContext,
2556
+ prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
2557
+ paths?: PathRule,
2558
+ ): Promise<NarrowedHolds | undefined> {
2559
+ const destination = prepared?.destination
2560
+ if (prepared === undefined || destination === undefined || prepared.narrowed.length === 0) {
2561
+ return undefined
2562
+ }
2563
+ const relations: string[] = []
2564
+ for (let index = 0; index < prepared.narrowed.length; index++) {
2565
+ const entry = prepared.narrowed[index]
2566
+ if (entry !== undefined) relations[relations.length] = entry.relation
2567
+ }
2568
+ const rest = await heldBy(transaction, context, { ...destination, relations: holdsBesides(destination.relations, relations) }, paths)
2569
+ const alone: string[] = []
2570
+ // One narrowed relation that passes leaves the destination as `lockDestination` found it; only with several may it be another's.
2571
+ for (let index = 0; relations.length > 1 && index < relations.length; index++) {
2572
+ const relation = relations[index] ?? ''
2573
+ const holds: RelationHold[] = []
2574
+ for (let position = 0; position < destination.relations.length; position++) {
2575
+ const hold = destination.relations[position]
2576
+ if (hold !== undefined && hold.relation === relation) holds[holds.length] = hold
2577
+ }
2578
+ if (await heldBy(transaction, context, { ...destination, relations: holds, revealing: [], paths: [] }, paths)) alone[alone.length] = relation
2579
+ }
2580
+ return { rest, alone }
2581
+ }
2582
+
2583
+ /** Whether `grant` holds the destination: with no part left, never. */
2584
+ async function heldBy(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
2585
+ if (grant.relations.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
2586
+ return false
2587
+ }
2588
+ return await destinationHeld(transaction, context, grant, paths)
2589
+ }
2590
+
2591
+ /**
2592
+ * The destination's relations whose condition for the insert follows a path, judged on the row just written as
2593
+ * `judgeInserted` judges `when`. When the row fails one, the insert stands only on what held the destination before the
2594
+ * write without it (`before`): the rest of the `Ref`, or a narrowed relation the row meets that held it alone. Otherwise
2595
+ * the transaction fails with a 409.
2596
+ */
2597
+ async function judgeNarrowed(
2598
+ transaction: Session,
2599
+ context: TableContext,
2600
+ prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
2601
+ before: NarrowedHolds | undefined,
2602
+ key: Primitive | null | undefined,
2603
+ ): Promise<void> {
2604
+ const destination = prepared?.destination
2605
+ if (prepared === undefined || destination === undefined || before === undefined) {
2606
+ return
2607
+ }
2608
+ let failed = false
2609
+ let held = before.rest
2610
+ for (let index = 0; index < prepared.narrowed.length; index++) {
2611
+ const entry = prepared.narrowed[index]
2612
+ if (entry === undefined) continue
2613
+ if (!(await rowMeets(transaction, context, destination.action, entry.condition, key))) {
2614
+ failed = true
2615
+ } else if (includes(before.alone, entry.relation)) {
2616
+ held = true
2617
+ }
2618
+ }
2619
+ if (failed && !held) {
2620
+ transaction.fail()
2621
+ throw new ConflictError(`the row is outside what ${destination.action} inserts into ${context.model.name} through its relations`)
2622
+ }
2623
+ }
2624
+
2625
+ /**
2626
+ * An insert's condition that follows a path, judged on the row just written, in its transaction. The database has then
2627
+ * held the row's foreign keys, so a path reads only the rows they name in the row's tenant. Every row each read path
2628
+ * reaches is locked `FOR SHARE` first (a `some`'s rows: every row naming the row it reached), so none changes or goes
2629
+ * before the commit; then the condition is judged as a read of the row judges it. A refused row fails the transaction,
2630
+ * so it commits nothing even when the handler catches the refusal.
2631
+ */
2632
+ async function judgeInserted(
2633
+ transaction: Session,
2634
+ context: TableContext,
2635
+ judged: JudgedInsert | undefined,
2636
+ key: Primitive | null | undefined,
2637
+ ): Promise<void> {
2638
+ if (judged === undefined) {
2639
+ return
2640
+ }
2641
+ if (!(await rowMeets(transaction, context, judged.action, judged.condition, key))) {
2642
+ transaction.fail()
2643
+ throw new ConflictError(`the row is outside what ${judged.action} inserts into ${context.model.name}`)
2644
+ }
2645
+ }
2646
+
2647
+ /**
2648
+ * Whether the row just written meets `condition`, in the insert's transaction: every row each of its paths reaches is
2649
+ * locked `FOR SHARE` first, then the condition is judged as a read of the row judges it.
2650
+ */
2651
+ async function rowMeets(
2652
+ transaction: Session,
2653
+ context: TableContext,
2654
+ action: string,
2655
+ condition: ConditionModel,
2656
+ key: Primitive | null | undefined,
2657
+ ): Promise<boolean> {
2658
+ const model = context.model
2659
+ if (key === undefined || key === null) {
2660
+ throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${action} has no key`)
2661
+ }
2662
+ const paths = readPaths(condition)
2663
+ for (let index = 0; index < paths.length; index++) {
2664
+ const steps = paths[index] ?? []
2665
+ // The rows a path reaches, step by step from the inserted row; each statement admits the columns it walks.
2666
+ let reached = subquery(model.name, steps[0]?.from ?? '', equals(model.name, keyOf(model), key))
2667
+ const walked: Record<string, string[]> = { [model.name]: [steps[0]?.from ?? ''] }
2668
+ for (let position = 0; position < steps.length; position++) {
2669
+ const step = steps[position]
2670
+ if (step === undefined) continue
2671
+ const scope = BinaryOperationNode.create(column(step.table, step.to), OperatorNode.create('in'), reached)
2672
+ await transaction.run(lockNode(step.table, step.to, scope), {
2673
+ root: 'SelectQueryNode',
2674
+ table: step.table,
2675
+ joins: {},
2676
+ scope,
2677
+ lock: 'share',
2678
+ subqueries: withColumns(context.subqueries, walked),
2679
+ })
2680
+ const next = steps[position + 1]
2681
+ if (next !== undefined) {
2682
+ reached = subquery(step.table, next.from, scope)
2683
+ walked[step.table] = [...(walked[step.table] ?? []), next.from]
2684
+ }
2685
+ }
2686
+ }
2687
+ const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, condition, new Date())))
2688
+ const rows = await transaction.run(locateNode(model.name, [keyOf(model)], scope), {
2689
+ root: 'SelectQueryNode',
2690
+ table: model.name,
2691
+ joins: {},
2692
+ scope,
2693
+ subqueries: context.subqueries,
2694
+ })
2695
+ return rows.length > 0
2696
+ }
2697
+
2698
+ /** `admitted` with `more` added: the columns one statement the layer builds may select in its subqueries. */
2699
+ function withColumns(
2700
+ admitted: Readonly<Record<string, readonly string[]>>,
2701
+ more: Readonly<Record<string, readonly string[]>>,
2702
+ ): Readonly<Record<string, readonly string[]>> {
2703
+ const merged: Record<string, readonly string[]> = { ...admitted }
2704
+ const tables = ownKeys(more)
2705
+ for (let index = 0; index < tables.length; index++) {
2706
+ const table = tables[index] ?? ''
2707
+ setOwn(merged, table, [...(ownEntry(admitted, table) ?? []), ...(ownEntry(more, table) ?? [])])
2708
+ }
2709
+ return merged
2710
+ }
2711
+
2712
+ /** Writes each chain column the destination `Ref` settles into an insert's row. */
2713
+ function stampChain(row: Map<string, Primitive | null>, values: readonly LinkValue[]): void {
2714
+ for (let index = 0; index < values.length; index++) {
2715
+ const entry = values[index]
2716
+ if (entry !== undefined) {
2717
+ row.set(entry.link.column, entry.value)
2718
+ }
2719
+ }
2720
+ }
2721
+
2722
+ /** A prepared insert, with its conflict handling when the caller named one. */
2723
+ export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
2724
+ const conflict = prepared.conflict
2725
+ if (conflict === undefined) {
2726
+ return insertRow(context, run, prepared.row, prepared)
2727
+ }
2728
+ return run.write(async (transaction) => {
1705
2729
  if (prepared.destination !== undefined) {
1706
2730
  await lockDestination(transaction, context, prepared.destination)
1707
2731
  }
1708
- return insertOnConflict(context, run, transaction, prepared.row, conflict)
2732
+ const before = await narrowedHolds(transaction, context, prepared)
2733
+ await checkPrincipalAssign(transaction, context, prepared.writer, prepared.row)
2734
+ await checkRevealAssign(transaction, context, prepared.writer, prepared.row)
2735
+ await checkMemberRevealAssign(transaction, context, prepared.writer, prepared.row)
2736
+ await checkPathWriters(transaction, context, prepared.writer, prepared.row)
2737
+ const written = await insertOnConflict(context, run, transaction, prepared.row, conflict)
2738
+ // A conflict writes no new row: `nothing` reads none, and `update` is judged on the stored row.
2739
+ if (written['inserted'] === true) {
2740
+ await judgeInserted(transaction, context, prepared.judged, prepared.row.get(keyOf(context.model)))
2741
+ await judgeNarrowed(transaction, context, prepared, before, prepared.row.get(keyOf(context.model)))
2742
+ }
2743
+ return written
1709
2744
  })
1710
2745
  }
1711
2746
 
2747
+ /**
2748
+ * A source row whose principal its path's table holds, under `assign.self`: without it, the insert is refused while the
2749
+ * row its column names there names the writer. That row is locked `FOR SHARE` first, so it keeps its principal and
2750
+ * stays until the commit. One lock and one guarded select per such source, in the insert's transaction.
2751
+ */
2752
+ async function checkPrincipalAssign(
2753
+ transaction: Session,
2754
+ context: TableContext,
2755
+ writer: string,
2756
+ row: ReadonlyMap<string, Primitive | null>,
2757
+ ): Promise<void> {
2758
+ const model = context.model
2759
+ for (let index = 0; index < model.confers.length; index++) {
2760
+ const source = model.confers[index]
2761
+ const path = source?.principalPath
2762
+ const value = source === undefined ? undefined : row.get(source.principal)
2763
+ if (source === undefined || path === undefined || source.assign === undefined || source.assign.self || value === undefined || value === null) {
2764
+ continue
2765
+ }
2766
+ const keyed = equals(path.table, path.key, value)
2767
+ await transaction.run(lockNode(path.table, path.key, keyed), { root: 'SelectQueryNode', table: path.table, joins: {}, scope: keyed, lock: 'share' })
2768
+ const named = allOf([keyed, equals(path.table, path.column, writer)])
2769
+ const rows = await transaction.run(locateNode(path.table, [path.key], named), {
2770
+ root: 'SelectQueryNode',
2771
+ table: path.table,
2772
+ joins: {},
2773
+ scope: named,
2774
+ })
2775
+ if (rows.length > 0) {
2776
+ throw new ConflictError(
2777
+ `a row of ${model.name} names its writer in ${source.relation} through ${source.principal}, which assign.self does not allow`,
2778
+ )
2779
+ }
2780
+ }
2781
+ }
2782
+
2783
+ /**
2784
+ * An inserted row whose `readThrough` column a reveal matches through, under the reveal's `assign`: without `self`, the
2785
+ * insert is refused while its writer holds the reveal's relation at the node the column names, or at the ancestor of it
2786
+ * the relation is at. One guarded select per such reveal, in the insert's transaction.
2787
+ */
2788
+ async function checkRevealAssign(
2789
+ transaction: Session,
2790
+ context: TableContext,
2791
+ writer: string,
2792
+ row: ReadonlyMap<string, Primitive | null>,
2793
+ ): Promise<void> {
2794
+ const model = context.model
2795
+ const now = new Date()
2796
+ for (let index = 0; index < model.reveals.length; index++) {
2797
+ const reveal = model.reveals[index]
2798
+ const path = reveal?.path
2799
+ const value = path === undefined ? undefined : row.get(path.column)
2800
+ if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || typeof value !== 'string') continue
2801
+ const source = relationSource(context.relations, reveal.relation)
2802
+ const tests: OperationNode[] = []
2803
+ const rest: OperationNode[] = [...activeRow(source, now)]
2804
+ if (source.dimension === path.dimension) {
2805
+ tests[tests.length] = equals(source.table, source.node, value)
2806
+ } else {
2807
+ const link = linkOf(path.chain, source.dimension)
2808
+ if (link === undefined) continue
2809
+ const above = subquery(path.table, link.column, equals(path.table, path.key, value))
2810
+ rest.unshift(BinaryOperationNode.create(column(source.table, source.node), OperatorNode.create('in'), above))
2811
+ }
2812
+ // The principal test comes last: an equality, or a path's membership after the node's equality.
2813
+ tests[tests.length] = namesPrincipal(source, writer)
2814
+ const address = allOf(tests)
2815
+ const scope = rest.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(rest)))
2816
+ const rows = await transaction.run(locateNode(source.table, [source.node], scope), {
2817
+ root: 'SelectQueryNode',
2818
+ table: source.table,
2819
+ joins: {},
2820
+ scope,
2821
+ subqueries: context.subqueries,
2822
+ })
2823
+ if (rows.length > 0) {
2824
+ throw new ConflictError(
2825
+ `a row of ${model.name} names in ${path.column} a node where its writer holds ${reveal.relation}, which the reveal's assign.self does not allow`,
2826
+ )
2827
+ }
2828
+ }
2829
+ }
2830
+
2831
+ /**
2832
+ * An inserted row whose path column a member reveal matches through, under the reveal's `assign`: without `self`, the
2833
+ * insert is refused while its writer holds a grant the reveal counts (one of its actions, at the node itself) at the
2834
+ * node the column names. The grants are the request's own; the database compares them with the node's key, so every
2835
+ * spelling of a key it reads as one (a `uuid`) is that node. Work with no request caller has none to judge, and is
2836
+ * refused.
2837
+ */
2838
+ async function checkMemberRevealAssign(
2839
+ transaction: Session,
2840
+ context: TableContext,
2841
+ writer: string,
2842
+ row: ReadonlyMap<string, Primitive | null>,
2843
+ ): Promise<void> {
2844
+ const model = context.model
2845
+ const authority = runtimeOf(context.connection).capabilities
2846
+ for (let index = 0; index < model.memberReveals.length; index++) {
2847
+ const reveal = model.memberReveals[index]
2848
+ const path = reveal?.path
2849
+ const value = path === undefined ? undefined : row.get(path.column)
2850
+ if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || value === undefined || value === null) {
2851
+ continue
2852
+ }
2853
+ for (let position = 0; position < reveal.actions.length; position++) {
2854
+ const action = reveal.actions[position] ?? ''
2855
+ const standing = authority.standing?.(path.dimension, action)
2856
+ if (standing === undefined || standing.principal !== writer) {
2857
+ throw new ConflictError(
2858
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} its member reveal reveals to, and its writer's grants cannot be judged under assign without self: work with no request caller`,
2859
+ )
2860
+ }
2861
+ if (standing.values === 'all' || standing.values.length === 0) continue
2862
+ const scope = AndNode.create(equals(path.table, path.key, value), inList(path.table, path.key, standing.values))
2863
+ const rows = await transaction.run(locateNode(path.table, [path.key], scope), {
2864
+ root: 'SelectQueryNode',
2865
+ table: path.table,
2866
+ joins: {},
2867
+ scope,
2868
+ })
2869
+ if (rows.length > 0) {
2870
+ throw new ConflictError(
2871
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer holds a grant the member reveal counts, which the reveal's assign.self does not allow`,
2872
+ )
2873
+ }
2874
+ }
2875
+ }
2876
+ }
2877
+
2878
+ /**
2879
+ * An inserted row's path column that hands out actions (`writeThrough`): its writer must hold every one of them at the
2880
+ * node the column names, as a grant there or above it, a relation row naming it there (of a relation no `relationWhen`
2881
+ * narrows for the action), or a revealing row. The node's
2882
+ * row is locked `FOR SHARE` first, so it stays where it lies until the commit, and so is each row the writer holds it
2883
+ * through; IAM grants are the request's own. Judged before the insert, so the inserted row never counts. A writer
2884
+ * outside the bound, or work with no caller, is a 409 and nothing is written.
2885
+ */
2886
+ async function checkPathWriters(
2887
+ transaction: Session,
2888
+ context: TableContext,
2889
+ writer: string,
2890
+ row: ReadonlyMap<string, Primitive | null>,
2891
+ ): Promise<void> {
2892
+ const model = context.model
2893
+ const authority = runtimeOf(context.connection).capabilities
2894
+ for (let index = 0; index < context.writers.length; index++) {
2895
+ const bound = context.writers[index]
2896
+ const value = bound === undefined ? undefined : row.get(bound.path.column)
2897
+ if (bound === undefined || value === undefined || value === null) continue
2898
+ const { path, owner } = bound
2899
+ const refused = (action: string) =>
2900
+ new ConflictError(
2901
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer does not hold ${action}, which the path hands out (writeThrough)`,
2902
+ )
2903
+ const keyed = equals(owner.name, keyOf(owner), value)
2904
+ const locked = await transaction.run(lockNode(owner.name, keyOf(owner), keyed), {
2905
+ root: 'SelectQueryNode',
2906
+ table: owner.name,
2907
+ joins: {},
2908
+ scope: keyed,
2909
+ lock: 'share',
2910
+ })
2911
+ const chain = locked.length === 0 ? null : await chainOf(owner, transaction, String(value))
2912
+ for (let position = 0; position < bound.actions.length; position++) {
2913
+ const action = bound.actions[position] ?? ''
2914
+ const standing = authority.standing?.(path.dimension, action)
2915
+ if (chain === null || standing === undefined || standing.principal !== writer) throw refused(action)
2916
+ if (holdsByGrant(standing, String(value), chain)) continue
2917
+ const holding: RefGrant = {
2918
+ kind: 'ref',
2919
+ dimension: path.dimension,
2920
+ action,
2921
+ principal: writer,
2922
+ id: String(value),
2923
+ chain,
2924
+ relations: unnarrowed(context.relations, standing.relations, action),
2925
+ revealing: standing.revealing,
2926
+ paths: [],
2927
+ }
2928
+ if (!(await holdingRowLocked(transaction, context, holding))) throw refused(action)
2929
+ }
2930
+ }
2931
+ }
2932
+
2933
+ /**
2934
+ * Of `relations`, those no table's `relationWhen` narrows for `action`: a relation that holds the action on some rows only
2935
+ * does not bound a writer who hands it out at a node.
2936
+ */
2937
+ function unnarrowed(relations: RelationSources, held: readonly RelationHold[], action: string): readonly RelationHold[] {
2938
+ const kept: RelationHold[] = []
2939
+ for (let index = 0; index < held.length; index++) {
2940
+ const hold = held[index]
2941
+ if (hold !== undefined && !includes(knownRelation(relations, hold.relation).narrowed, action)) kept[kept.length] = hold
2942
+ }
2943
+ return kept
2944
+ }
2945
+
2946
+ /** Whether `standing`'s grants hold its action at `node`: everywhere, there, or at a container `chain` places it in. */
2947
+ function holdsByGrant(standing: WithinGrant, node: string, chain: ReadonlyMap<string, string>): boolean {
2948
+ if (standing.values === 'all' || includes(standing.values, node)) {
2949
+ return true
2950
+ }
2951
+ for (let index = 0; index < standing.containers.length; index++) {
2952
+ const container = standing.containers[index]
2953
+ const at = container === undefined ? undefined : chain.get(container.dimension)
2954
+ if (container !== undefined && at !== undefined && includes(container.values, at)) return true
2955
+ }
2956
+ return false
2957
+ }
2958
+
1712
2959
  /** `DimensionTable.insert` over a capability nobody type-checked; the table probe of `@fabrika/db/testing` calls it too. */
1713
2960
  export function insertIntoDimension<O>(context: TableContext, run: Runner, target: unknown, values: unknown): Promise<O> {
1714
2961
  const prepared = prepareDimensionInsert(context, target, values)
1715
- return insertRow(context, run, prepared.row, prepared.destination)
2962
+ return insertRow(context, run, prepared.row, prepared)
1716
2963
  }
1717
2964
 
1718
2965
  /** An application table's insert, for an `app` capability of its insert action. */
1719
2966
  export function insertIntoApplication<O>(context: TableContext, run: Runner, capability: unknown, values: unknown): Promise<O> {
1720
2967
  const prepared = prepareApplicationInsert(context, capability, values)
1721
- return insertRow(context, run, prepared.row, prepared.destination)
2968
+ return insertRow(context, run, prepared.row, prepared)
1722
2969
  }
1723
2970
 
1724
2971
  /** `ChildTable.insert` over a capability nobody type-checked. */
1725
2972
  export function insertIntoChild<O>(context: TableContext, run: Runner, parent: unknown, values: unknown): Promise<O> {
1726
2973
  const prepared = prepareChildInsert(context, parent, values)
1727
- return insertRow(context, run, prepared.row, prepared.destination)
2974
+ return insertRow(context, run, prepared.row, prepared)
1728
2975
  }
1729
2976
 
1730
2977
  type ReadAction<P, T> = ActionOf<P, T, 'read'>
@@ -1784,7 +3031,9 @@ export class DimensionTable<DB, P, T extends string> {
1784
3031
  /**
1785
3032
  * Moves the object to another container: the delete action at the source, the insert action at the target,
1786
3033
  * whose chain is checked against the database. Every chain column changes; children that copy them follow
1787
- * through `ON UPDATE CASCADE` on their composite foreign key. Answers the acknowledgement and the new chain.
3034
+ * through `ON UPDATE CASCADE` on their composite foreign key. The moved row is judged by the insert action's
3035
+ * condition and by the `relationWhen` of each relation the target holds through, as an insert into the target is.
3036
+ * Answers the acknowledgement and the new chain.
1788
3037
  */
1789
3038
  async move(
1790
3039
  ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>,
@@ -1795,8 +3044,21 @@ export class DimensionTable<DB, P, T extends string> {
1795
3044
  if (container === undefined) {
1796
3045
  throw new CapabilityError('table_kind', `${context.model.name} has no container to move between`)
1797
3046
  }
1798
- const scope = objectPredicate(context, ref, 'delete')
3047
+ if (delegates(context.model)) {
3048
+ throw new CapabilityError(
3049
+ 'table_kind',
3050
+ `${context.model.name} hands out access, so a row is never moved: insert a new one`,
3051
+ )
3052
+ }
3053
+ // A move rewrites containment, which a grant at a node a path names gives no standing in: both Refs follow containment.
1799
3054
  const target = refGrant(context, to, container.dimension, 'insert')
3055
+ if (refGrant(context, ref, dimensionScope(context.model).dimension, 'delete').paths.length > 0 || target.paths.length > 0) {
3056
+ throw new CapabilityError(
3057
+ 'unenforceable',
3058
+ `a Ref held through a secondary path never moves a row of ${context.model.name}: a move follows containment`,
3059
+ )
3060
+ }
3061
+ const scope = objectPredicate(context, ref, 'delete', noPath)
1800
3062
  const values = linkValues(context.model.name, context.model.chain, target)
1801
3063
  const changes = new Map<string, Primitive | null>()
1802
3064
  stampChain(changes, values)
@@ -1807,7 +3069,16 @@ export class DimensionTable<DB, P, T extends string> {
1807
3069
  setOwn(chain, entry.link.dimension, entry.value)
1808
3070
  }
1809
3071
  }
1810
- const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, target)
3072
+ const condition = ownEntry(context.model.when, target.action)
3073
+ const narrowed: NarrowedInsert[] = []
3074
+ for (let index = 0; index < target.relations.length; index++) {
3075
+ const relation = target.relations[index]?.relation ?? ''
3076
+ const narrowing = relationCondition(context.model, relation, target.action)
3077
+ if (narrowing !== undefined && !judgesRelation(narrowed, relation)) narrowed[narrowed.length] = { relation, condition: narrowing }
3078
+ }
3079
+ const judged = condition === undefined ? undefined : { action: target.action, condition }
3080
+ const moved: MovedRow = { destination: target, judged, narrowed }
3081
+ const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, moved)
1811
3082
  return { ...acknowledged, chain }
1812
3083
  }
1813
3084
 
@@ -1910,7 +3181,7 @@ function probeRunner(context: TableContext): { readonly run: Runner; readonly he
1910
3181
  }
1911
3182
 
1912
3183
  /**
1913
- * One table's operations without the store types, for `@fabrika/db/testing` only: the generated isolation tests address
3184
+ * One table's operations without the store types, for `@fabrika/db/testing` only: the policy isolation kit addresses
1914
3185
  * a table by name. Every runtime check of a store applies; a child row is addressed by its parent's capability and
1915
3186
  * `key`, a dimension row by its capability alone.
1916
3187
  */
@@ -1938,15 +3209,19 @@ function probeOf(context: TableContext): TableProbe {
1938
3209
  }
1939
3210
  return objectPredicate(context, capability, operation)
1940
3211
  }
3212
+ const app = (capability: unknown): boolean => runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app'
1941
3213
  // An `app` capability reads every row through ctx.db.app: its rows with appRead, its counts with appCount too.
1942
3214
  const list = (capability: unknown, reach: AppReach): OperationNode | undefined => {
1943
- if (runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app') {
3215
+ if (app(capability)) {
1944
3216
  return appRecordPredicate(context, capability, reach)
1945
3217
  }
1946
3218
  return child ? childListPredicate(context, capability, 'read') : dimensionListPredicate(context, capability, 'read')
1947
3219
  }
1948
- // A capability reads the columns of its own action, as ctx.db does.
1949
- const visible = (capability: unknown): readonly string[] => visibleFor(context.model, heldAction(context, capability))
3220
+ // A capability reads the columns of its own action, as ctx.db does; an `app` one those its reaching actions read alone.
3221
+ const visible = (capability: unknown): readonly string[] =>
3222
+ app(capability)
3223
+ ? visibleThrough(context.model, appRecordRead(context, capability, 'rows').reach)
3224
+ : visibleFor(context.model, heldAction(context, capability))
1950
3225
  const { run, held } = probeRunner(context)
1951
3226
  return freeze({
1952
3227
  mode: child ? 'child' : 'dimension',
@@ -1957,12 +3232,12 @@ function probeOf(context: TableContext): TableProbe {
1957
3232
  context,
1958
3233
  list(capability, 'rows'),
1959
3234
  finishSelect(start, start),
1960
- heldAction(context, capability),
3235
+ soleAction(context, capability),
1961
3236
  visible(capability),
1962
3237
  )
1963
3238
  },
1964
3239
  group: async (capability: unknown, columns: readonly string[]) =>
1965
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(
3240
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(
1966
3241
  context,
1967
3242
  run,
1968
3243
  list(capability, 'rows'),
@@ -2018,8 +3293,7 @@ function appProbeOf(context: TableContext): TableProbe {
2018
3293
  mode: 'app',
2019
3294
  get: async (capability: unknown, key?: string) => {
2020
3295
  if (scoped(capability)) {
2021
- scopedApplicationRead(context, capability)
2022
- return selectOne<Readonly<Record<string, unknown>>>(context, run, appKeyPredicate(context.model, key))
3296
+ return selectOne<Readonly<Record<string, unknown>>>(context, run, scopedApplicationRead(context, capability, appKeyPredicate(context.model, key)))
2023
3297
  }
2024
3298
  return selectOne<Readonly<Record<string, unknown>>>(context, run, appRowPredicate(context, capability, key, 'read'))
2025
3299
  },
@@ -2029,12 +3303,12 @@ function appProbeOf(context: TableContext): TableProbe {
2029
3303
  context,
2030
3304
  every(capability),
2031
3305
  finishSelect(start, start),
2032
- heldAction(context, capability),
3306
+ soleAction(context, capability),
2033
3307
  )
2034
3308
  },
2035
3309
  count,
2036
3310
  group: async (capability: unknown, columns: readonly string[]) =>
2037
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
3311
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
2038
3312
  groupBy: columns,
2039
3313
  count: true,
2040
3314
  }),
@@ -2068,11 +3342,11 @@ function destinationOf(models: TableModels, model: TableModel, parent: TableMode
2068
3342
 
2069
3343
  /** What a select or an aggregate of a capability that reads `visible` may name: those columns, and no join. */
2070
3344
  export function actionShape(model: TableModel, visible: readonly string[]): TableShape {
2071
- return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates })
3345
+ return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates, json: model.json })
2072
3346
  }
2073
3347
 
2074
3348
  function shapeOf(model: TableModel, joinable: Readonly<Record<string, JoinShape>>): TableShape {
2075
- return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates })
3349
+ return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates, json: model.json })
2076
3350
  }
2077
3351
 
2078
3352
  function joinShapes(models: TableModels, parent: TableModel): Readonly<Record<string, JoinShape>> {
@@ -2120,6 +3394,8 @@ export interface ScopedDatabase<DB, P> extends DataLayer {
2120
3394
  export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2121
3395
  const models = tableModels(tables)
2122
3396
  const connection: Connection = { runtime: undefined }
3397
+ const layer = layerReach(models)
3398
+ const { relations, members, subqueries } = layer
2123
3399
 
2124
3400
  function contextFor(table: string, mode: 'dimension' | 'child' | 'app'): TableContext {
2125
3401
  const model = typeof table === 'string' ? modelOf(models, table) : undefined
@@ -2131,6 +3407,15 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2131
3407
 
2132
3408
  function contextOf(model: TableModel): TableContext {
2133
3409
  const parent = model.scope.mode === 'child' ? modelOf(models, model.scope.parent) : undefined
3410
+ const through = model.view && model.scope.mode === 'child' && parent?.scope.mode === 'dimension'
3411
+ ? freeze({
3412
+ column: model.scope.column,
3413
+ table: parent.name,
3414
+ key: parent.scope.key,
3415
+ access: viewAccessLinks(model, model.scope.key),
3416
+ context: contextOf(freeze({ ...parent, when: freeze({}), relationWhen: freeze({}) })),
3417
+ })
3418
+ : undefined
2134
3419
  const joinable = joinShapes(models, model)
2135
3420
  const joins: Record<string, readonly ForeignKeyPair[]> = {}
2136
3421
  const children = ownKeys(joinable)
@@ -2149,6 +3434,13 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2149
3434
  }
2150
3435
  }
2151
3436
  const shape = shapeOf(model, joinable)
3437
+ const writers: PathBound[] = []
3438
+ const declared = pathWriters(models, model)
3439
+ for (let index = 0; index < declared.length; index++) {
3440
+ const writer = declared[index]
3441
+ const owner = writer === undefined ? undefined : modelOf(models, writer.path.table)
3442
+ if (writer !== undefined && owner !== undefined) writers[writers.length] = freeze({ ...writer, owner })
3443
+ }
2152
3444
  return freeze({
2153
3445
  model,
2154
3446
  parent,
@@ -2157,6 +3449,11 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2157
3449
  joins: freeze(joins),
2158
3450
  children: freeze(childModels),
2159
3451
  connection,
3452
+ relations,
3453
+ members,
3454
+ subqueries,
3455
+ through,
3456
+ writers: freeze(writers),
2160
3457
  })
2161
3458
  }
2162
3459
 
@@ -2186,6 +3483,20 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2186
3483
  connection.runtime = bound
2187
3484
  return freeze({
2188
3485
  locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
3486
+ relates: async (relation: string, node: string, principal: string) =>
3487
+ relationHolds(models, relations, subqueries, bound, relation, node, principal),
3488
+ reveals: async (relation: string, dimension: string, node: string, principal: string, action: string) =>
3489
+ revealHolds(relations, subqueries, bound, relation, dimension, node, principal, action),
3490
+ holdsThrough: async (
3491
+ dimension: string,
3492
+ id: string,
3493
+ action: string,
3494
+ principal: string,
3495
+ relations: readonly RelationHold[],
3496
+ paths: readonly ContainerGrant[],
3497
+ ) => heldThroughPaths(models, layer, bound, dimension, id, action, principal, relations, paths),
3498
+ revealsToMembers: async (revealing: string, values: readonly string[], dimension: string, node: string, action: string) =>
3499
+ membersRevealed(members, subqueries, bound, revealing, values, dimension, node, action),
2189
3500
  release() {
2190
3501
  if (connection.runtime === bound) {
2191
3502
  connection.runtime = undefined
@@ -2199,6 +3510,9 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2199
3510
  wakes: jobWakes(() => runtimeOf(connection)),
2200
3511
  admissions: admissions(() => runtimeOf(connection)),
2201
3512
  files: storedFiles(() => runtimeOf(connection)),
3513
+ receipts: requestReceipts(),
3514
+ push: pushSubscriptions(),
3515
+ notifications: notifications(),
2202
3516
  }),
2203
3517
  data: dataAccess({
2204
3518
  models,
@@ -2218,6 +3532,150 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2218
3532
  return database
2219
3533
  }
2220
3534
 
3535
+ /**
3536
+ * Every relation of the layer by name, and the tables a scope predicate's subqueries read (a relation's source by its
3537
+ * node column, a condition path's target by its key), which the guard admits and nothing else.
3538
+ */
3539
+ function layerReach(
3540
+ models: TableModels,
3541
+ ): { readonly relations: RelationSources; readonly members: MemberReveals; readonly subqueries: Readonly<Record<string, readonly string[]>> } {
3542
+ const relations: Record<string, LayerRelation | AccessRelation> = {}
3543
+ const members: Record<string, MemberRevealModel[]> = {}
3544
+ const selected: Record<string, string[]> = {}
3545
+ const select = (table: string, column: string): void => {
3546
+ const columns = ownEntry(selected, table) ?? []
3547
+ if (!includes(columns, column)) columns[columns.length] = column
3548
+ setOwn(selected, table, columns)
3549
+ }
3550
+ const names = ownKeys(models)
3551
+ const reveals: Record<string, RevealModel[]> = {}
3552
+ const narrowed: Record<string, string[]> = {}
3553
+ for (let index = 0; index < names.length; index++) {
3554
+ const model = modelOf(models, names[index] ?? '')
3555
+ const conditioned = model === undefined ? [] : ownKeys(model.relationWhen)
3556
+ for (let position = 0; model !== undefined && position < conditioned.length; position++) {
3557
+ const relation = conditioned[position] ?? ''
3558
+ const conditions = ownEntry(model.relationWhen, relation) ?? {}
3559
+ const actions = ownKeys(conditions)
3560
+ const listed = ownEntry(narrowed, relation) ?? []
3561
+ for (let next = 0; next < actions.length; next++) {
3562
+ const action = actions[next] ?? ''
3563
+ if (!includes(listed, action)) listed[listed.length] = action
3564
+ const condition = ownEntry(conditions, action)
3565
+ if (condition !== undefined) addReach(condition, select)
3566
+ }
3567
+ setOwn(narrowed, relation, listed)
3568
+ }
3569
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
3570
+ const reveal = model.reveals[position]
3571
+ if (reveal === undefined) continue
3572
+ const listed = ownEntry(reveals, reveal.relation) ?? []
3573
+ listed[listed.length] = reveal
3574
+ setOwn(reveals, reveal.relation, listed)
3575
+ select(reveal.table, reveal.column)
3576
+ if (reveal.when !== undefined) addReach(reveal.when, select)
3577
+ }
3578
+ for (let position = 0; model !== undefined && position < model.memberReveals.length; position++) {
3579
+ const reveal = model.memberReveals[position]
3580
+ if (reveal === undefined) continue
3581
+ const listed = ownEntry(members, reveal.source) ?? []
3582
+ listed[listed.length] = reveal
3583
+ setOwn(members, reveal.source, listed)
3584
+ select(reveal.table, reveal.column)
3585
+ if (reveal.when !== undefined) addReach(reveal.when, select)
3586
+ }
3587
+ }
3588
+ for (let index = 0; index < names.length; index++) {
3589
+ const model = modelOf(models, names[index] ?? '')
3590
+ if (model === undefined) continue
3591
+ for (let position = 0; position < model.confers.length; position++) {
3592
+ const source = model.confers[position]
3593
+ if (source === undefined) continue
3594
+ const revealed = ownEntry(reveals, source.relation) ?? []
3595
+ const placed: Record<string, Readonly<Record<string, string>>> = {}
3596
+ setOwn(placed, model.name, placementOf(model))
3597
+ for (let next = 0; next < revealed.length; next++) {
3598
+ const table = revealed[next]?.table ?? ''
3599
+ const at = modelOf(models, table)
3600
+ if (at !== undefined) setOwn(placed, table, placementOf(at))
3601
+ }
3602
+ setOwn(
3603
+ relations,
3604
+ source.relation,
3605
+ freeze({
3606
+ ...source,
3607
+ kind: 'source',
3608
+ reveals: freeze(revealed),
3609
+ narrowed: freeze(ownEntry(narrowed, source.relation) ?? []),
3610
+ placed: freeze(placed),
3611
+ }),
3612
+ )
3613
+ select(source.table, source.node)
3614
+ if (source.principalPath !== undefined) select(source.principalPath.table, source.principalPath.key)
3615
+ if (source.when !== undefined) addReach(source.when, select)
3616
+ }
3617
+ for (let position = 0; position < model.access.length; position++) {
3618
+ const access = model.access[position]
3619
+ if (access === undefined) continue
3620
+ select(access.view, access.row)
3621
+ }
3622
+ for (let position = 0; position < model.readThrough.length; position++) {
3623
+ const path = model.readThrough[position]
3624
+ if (path === undefined) continue
3625
+ select(path.table, path.key)
3626
+ if (path.via !== undefined) select(path.via.table, path.via.key)
3627
+ for (let link = 0; link < path.chain.length; link++) select(path.table, path.chain[link]?.column ?? path.key)
3628
+ }
3629
+ const actions = ownKeys(model.when)
3630
+ for (let position = 0; position < actions.length; position++) {
3631
+ const condition = ownEntry(model.when, actions[position] ?? '')
3632
+ if (condition !== undefined) addReach(condition, select)
3633
+ }
3634
+ }
3635
+ // A relation no table confers is served by the access views alone; a table that confers it adds them to its source.
3636
+ for (let index = 0; index < names.length; index++) {
3637
+ const model = modelOf(models, names[index] ?? '')
3638
+ for (let position = 0; model !== undefined && position < model.access.length; position++) {
3639
+ const access = model.access[position]
3640
+ if (access === undefined || ownEntry(relations, access.relation) !== undefined) continue
3641
+ const relation = access.relation
3642
+ setOwn(
3643
+ relations,
3644
+ relation,
3645
+ freeze({ kind: 'access', relation, dimension: access.dimension, narrowed: freeze(ownEntry(narrowed, relation) ?? []) }),
3646
+ )
3647
+ }
3648
+ }
3649
+ const subqueries: Record<string, readonly string[]> = {}
3650
+ const tablesRead = ownKeys(selected)
3651
+ for (let index = 0; index < tablesRead.length; index++) {
3652
+ const table = tablesRead[index] ?? ''
3653
+ setOwn(subqueries, table, freeze(ownEntry(selected, table) ?? []))
3654
+ }
3655
+ const revealing: Record<string, readonly MemberRevealModel[]> = {}
3656
+ const sources = ownKeys(members)
3657
+ for (let index = 0; index < sources.length; index++) {
3658
+ const source = sources[index] ?? ''
3659
+ setOwn(revealing, source, freeze(ownEntry(members, source) ?? []))
3660
+ }
3661
+ return { relations: freeze(relations), members: freeze(revealing), subqueries: freeze(subqueries) }
3662
+ }
3663
+
3664
+ /** `model`'s column for each dimension a row of it lies at: its key at its own dimension, then each link of its chain. */
3665
+ function placementOf(model: TableModel): Readonly<Record<string, string>> {
3666
+ const placed: Record<string, string> = {}
3667
+ if (model.scope.mode === 'dimension') setOwn(placed, model.scope.dimension, model.scope.key)
3668
+ for (let index = 0; index < model.chain.length; index++) {
3669
+ const link = model.chain[index]
3670
+ if (link !== undefined && ownEntry(placed, link.dimension) === undefined) setOwn(placed, link.dimension, link.column)
3671
+ }
3672
+ return freeze(placed)
3673
+ }
3674
+
3675
+ function addReach(condition: Parameters<typeof conditionReach>[0], select: (table: string, column: string) => void): void {
3676
+ conditionReach(condition, select)
3677
+ }
3678
+
2221
3679
  /** The context of `table` in the layer `scoped` created, for the framework's own store builders below. */
2222
3680
  function storeContext(database: DataLayer, table: string, mode: 'dimension' | 'child'): TableContext {
2223
3681
  const side = frameworkSideOf(database)
@@ -2260,6 +3718,42 @@ export function ownerOf(models: TableModels, dimension: string): TableModel | un
2260
3718
  return undefined
2261
3719
  }
2262
3720
 
3721
+ /**
3722
+ * Whether an access view of `relation` lists `node` for `principal`: a guarded select of the row of the table that owns
3723
+ * the relation's dimension, by its key, under the access term. Only a principal-bound view answers; one bound to a
3724
+ * member node lists nothing for a hold anywhere, which is all `relates` asks about.
3725
+ */
3726
+ async function accessHolds(
3727
+ models: TableModels,
3728
+ subqueries: Readonly<Record<string, readonly string[]>>,
3729
+ runtime: DataLayerRuntime,
3730
+ relation: string,
3731
+ dimension: string,
3732
+ node: string,
3733
+ principal: string,
3734
+ ): Promise<boolean> {
3735
+ const names = ownKeys(models)
3736
+ for (let index = 0; index < names.length; index++) {
3737
+ const model = modelOf(models, names[index] ?? '')
3738
+ if (model === undefined || model.scope.mode !== 'dimension' || model.scope.dimension !== dimension) continue
3739
+ const terms = relationTerms(
3740
+ { [relation]: freeze({ kind: 'access', relation, dimension, narrowed: freeze([]) }) },
3741
+ model,
3742
+ { relation, inside: null },
3743
+ principal,
3744
+ '',
3745
+ new Date(),
3746
+ noPath,
3747
+ )
3748
+ if (terms.length === 0) continue
3749
+ const scope = AndNode.create(equals(model.name, keyOf(model), node), anyOf(terms))
3750
+ const context: GuardContext = { root: 'SelectQueryNode', table: model.name, joins: {}, scope, subqueries }
3751
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(model.name, [keyOf(model)], scope), context)
3752
+ if (rows.length > 0) return true
3753
+ }
3754
+ return false
3755
+ }
3756
+
2263
3757
  /** The table that owns `dimension`, which the locator reads; a dimension no table owns is located by nothing. */
2264
3758
  function locatedOwner(models: TableModels, dimension: unknown): TableModel {
2265
3759
  const owner = typeof dimension === 'string' ? ownerOf(models, dimension) : undefined
@@ -2269,6 +3763,298 @@ function locatedOwner(models: TableModels, dimension: unknown): TableModel {
2269
3763
  return owner
2270
3764
  }
2271
3765
 
3766
+ /** One guarded select of a source row naming `principal` at `node` that confers `relation` now. */
3767
+ async function relationHolds(
3768
+ models: TableModels,
3769
+ relations: RelationSources,
3770
+ subqueries: Readonly<Record<string, readonly string[]>>,
3771
+ runtime: DataLayerRuntime,
3772
+ relation: string,
3773
+ node: string,
3774
+ principal: string,
3775
+ ): Promise<boolean> {
3776
+ if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
3777
+ throw new QueryRefusedError('row_address', `a ${relation} row is addressed by its node and its principal, non-empty strings`)
3778
+ }
3779
+ const known = knownRelation(relations, relation)
3780
+ if (known.kind === 'access') {
3781
+ return accessHolds(models, subqueries, runtime, relation, known.dimension, node, principal)
3782
+ }
3783
+ const source = relationSource(relations, relation)
3784
+ const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, principal)])
3785
+ const active = activeRow(source, new Date())
3786
+ const scope = active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active)))
3787
+ const context: GuardContext = { root: 'SelectQueryNode', table: source.table, joins: {}, scope, subqueries }
3788
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(source.table, [source.node], scope), context)
3789
+ // A relation with a source table may also name access views: the same term answers through them.
3790
+ return rows.length > 0 || accessHolds(models, subqueries, runtime, relation, source.dimension, node, principal)
3791
+ }
3792
+
3793
+ /**
3794
+ * Locks the first row that holds `grant`'s action for its principal at its object or a container on its chain, if any:
3795
+ * a source row naming it there, a row the relation reaches that reveals that node, or a row at a node the Ref's
3796
+ * revealing grants name that reveals it to its members.
3797
+ */
3798
+ async function holdingRowLocked(transaction: Session, context: TableContext, grant: RefGrant): Promise<boolean> {
3799
+ const now = new Date()
3800
+ const nodeOf = (dimension: string) => (dimension === grant.dimension ? grant.id : grant.chain.get(dimension))
3801
+ const candidates: { table: string; column: string; scope: OperationNode }[] = []
3802
+ for (let index = 0; index < grant.revealing.length; index++) {
3803
+ const revealing = grant.revealing[index]
3804
+ const reveals = revealing === undefined ? [] : ownEntry(context.members, revealing.dimension) ?? []
3805
+ for (let position = 0; revealing !== undefined && position < reveals.length; position++) {
3806
+ const reveal = reveals[position]
3807
+ const held = reveal !== undefined && includes(reveal.actions, grant.action)
3808
+ && (reveal.path === undefined || includes(reveal.path.writes, grant.action))
3809
+ const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
3810
+ if (reveal === undefined || revealed === undefined || revealing.values.length === 0) continue
3811
+ candidates[candidates.length] = { table: reveal.table, column: reveal.key, scope: memberAddress(reveal, revealing.values, revealed, now) }
3812
+ }
3813
+ }
3814
+ for (let index = 0; index < grant.relations.length; index++) {
3815
+ const hold = grant.relations[index]
3816
+ // An access view's base rows are not the data layer's to lock (ADR-0076): such a hold holds no destination here.
3817
+ if (hold === undefined || knownRelation(context.relations, hold.relation).kind === 'access') continue
3818
+ const source = relationSource(context.relations, hold.relation)
3819
+ const node = nodeOf(source.dimension)
3820
+ const sourceInside = insideRow(source, source.table, hold)
3821
+ if (node !== undefined && sourceInside !== null) {
3822
+ const parts = [equals(source.table, source.node, node), namesPrincipal(source, grant.principal)]
3823
+ if (sourceInside !== undefined) parts[parts.length] = sourceInside
3824
+ const address = allOf(parts)
3825
+ const active = activeRow(source, now)
3826
+ candidates[candidates.length] = {
3827
+ table: source.table,
3828
+ column: source.node,
3829
+ scope: active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active))),
3830
+ }
3831
+ }
3832
+ for (let position = 0; position < source.reveals.length; position++) {
3833
+ const reveal = source.reveals[position]
3834
+ const held = reveal !== undefined && includes(reveal.actions, grant.action)
3835
+ && (reveal.path === undefined || includes(reveal.path.writes, grant.action))
3836
+ const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
3837
+ const revealInside = reveal === undefined ? null : insideRow(source, reveal.table, hold)
3838
+ if (reveal !== undefined && revealed !== undefined && revealInside !== null) {
3839
+ const address = revealAddress(source, reveal, revealed, grant.principal, now)
3840
+ candidates[candidates.length] = {
3841
+ table: reveal.table,
3842
+ column: reveal.column,
3843
+ scope: revealInside === undefined ? address : allOf([address, revealInside]),
3844
+ }
3845
+ }
3846
+ }
3847
+ }
3848
+ for (let position = 0; position < candidates.length; position++) {
3849
+ const candidate = candidates[position]
3850
+ if (candidate === undefined) continue
3851
+ const rows = await transaction.run(lockNode(candidate.table, candidate.column, candidate.scope), {
3852
+ root: 'SelectQueryNode',
3853
+ table: candidate.table,
3854
+ joins: {},
3855
+ scope: candidate.scope,
3856
+ lock: 'share',
3857
+ subqueries: context.subqueries,
3858
+ })
3859
+ if (rows.length > 0) return true
3860
+ }
3861
+ return false
3862
+ }
3863
+
3864
+ /**
3865
+ * What a row of `table` (the relation's source or a reveal's table) must meet to hold under `hold`: nothing
3866
+ * (`undefined`) for a hold anywhere, its column for the hold's dimension among the hold's values for one inside a node,
3867
+ * and null when it has no such column, so it is not inside and holds nothing.
3868
+ */
3869
+ function insideRow(source: LayerRelation, table: string, hold: RelationHold): OperationNode | undefined | null {
3870
+ if (hold.inside === null) {
3871
+ return undefined
3872
+ }
3873
+ const placed = ownEntry(source.placed, table)
3874
+ const column = placed === undefined ? undefined : ownEntry(placed, hold.inside.dimension)
3875
+ return column === undefined || hold.inside.values.length === 0 ? null : isIn(table, column, valueList(hold.inside.values))
3876
+ }
3877
+
3878
+ /** `R.<ancestor> = $node and (R.<key> in (values) and <when>)`: a row at a node `values` name that reveals `node` now. */
3879
+ function memberAddress(reveal: MemberRevealModel, values: readonly string[], node: string, now: Date): OperationNode {
3880
+ const named = inList(reveal.table, reveal.key, values)
3881
+ const held = reveal.when === undefined ? named : allOf([named, conditionNode(reveal.table, reveal.when, now)])
3882
+ return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(held))
3883
+ }
3884
+
3885
+ /** `R.<ancestor> = $node and (R.<ancestor> in (<revealed nodes>))`: a row of the reveal's table revealing `node` now. */
3886
+ function revealAddress(source: LayerRelation, reveal: RevealModel, node: string, principal: string, now: Date): OperationNode {
3887
+ const revealed = BinaryOperationNode.create(
3888
+ column(reveal.table, reveal.column),
3889
+ OperatorNode.create('in'),
3890
+ revealedNodes(source, reveal, principal, now),
3891
+ )
3892
+ return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(revealed))
3893
+ }
3894
+
3895
+ /** One guarded select of a row that `relation` reaches for `principal` and that reveals `node` of `dimension` now. */
3896
+ async function revealHolds(
3897
+ relations: RelationSources,
3898
+ subqueries: Readonly<Record<string, readonly string[]>>,
3899
+ runtime: DataLayerRuntime,
3900
+ relation: string,
3901
+ dimension: string,
3902
+ node: string,
3903
+ principal: string,
3904
+ action: string,
3905
+ ): Promise<boolean> {
3906
+ if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
3907
+ throw new QueryRefusedError('row_address', `a node ${relation} reveals is addressed by its node and its principal, non-empty strings`)
3908
+ }
3909
+ const source = relationSource(relations, relation)
3910
+ for (let index = 0; index < source.reveals.length; index++) {
3911
+ const reveal = source.reveals[index]
3912
+ // A reveal matched through a secondary path holds a Ref's action only where the path holds it (`writeThrough`).
3913
+ if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
3914
+ if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
3915
+ const address = revealAddress(source, reveal, node, principal, new Date())
3916
+ const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope: address, subqueries }
3917
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(reveal.table, [reveal.column], address), context)
3918
+ if (rows.length > 0) return true
3919
+ }
3920
+ return false
3921
+ }
3922
+
3923
+ /**
3924
+ * Of `values`, nodes of `revealing` at which the caller holds `action`, the ones whose row reveals `node` of `dimension`
3925
+ * for it now: one guarded select per member reveal of `revealing` to `dimension` that lists `action`.
3926
+ */
3927
+ async function membersRevealed(
3928
+ members: MemberReveals,
3929
+ subqueries: Readonly<Record<string, readonly string[]>>,
3930
+ runtime: DataLayerRuntime,
3931
+ revealing: string,
3932
+ values: readonly string[],
3933
+ dimension: string,
3934
+ node: string,
3935
+ action: string,
3936
+ ): Promise<readonly string[]> {
3937
+ if (typeof node !== 'string' || node.length === 0 || !isArray(values) || values.length > MAX_WITHIN_VALUES) {
3938
+ throw new QueryRefusedError('row_address', `a node ${revealing} reveals is addressed by its node and at most ${MAX_WITHIN_VALUES} grants`)
3939
+ }
3940
+ for (let index = 0; index < values.length; index++) {
3941
+ if (typeof values[index] !== 'string' || values[index] === '') {
3942
+ throw new QueryRefusedError('row_address', `a grant at ${revealing} names its node, a non-empty string`)
3943
+ }
3944
+ }
3945
+ const reveals = ownEntry(members, revealing) ?? []
3946
+ const found: string[] = []
3947
+ for (let index = 0; values.length > 0 && index < reveals.length; index++) {
3948
+ const reveal = reveals[index]
3949
+ if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
3950
+ if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
3951
+ const scope = memberAddress(reveal, values, node, new Date())
3952
+ const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope, subqueries }
3953
+ // Grouped, not limited: through a path many rows name one grant's node, and every grant matched is carried.
3954
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(valuesNode(reveal.table, reveal.key, scope), context)
3955
+ for (let position = 0; position < rows.length; position++) {
3956
+ const key = ownEntry(rows[position] ?? {}, reveal.key)
3957
+ if (typeof key === 'string' && !includes(found, key)) found[found.length] = key
3958
+ }
3959
+ }
3960
+ return freeze(found)
3961
+ }
3962
+
3963
+ /**
3964
+ * Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
3965
+ * through a relation row, a reveal or a secondary path that holds the action for a `Ref` (`writeThrough`): one guarded
3966
+ * select per candidate. What `on` and `in` mint a `Ref` held through a path with, and through a relation held inside a
3967
+ * node: the statement compares the object's column for the node's dimension with the held values, and the relation
3968
+ * comes back held inside the node that column stores, so every spelling the database equates is one node.
3969
+ */
3970
+ async function heldThroughPaths(
3971
+ models: TableModels,
3972
+ layer: ReturnType<typeof layerReach>,
3973
+ runtime: DataLayerRuntime,
3974
+ dimension: string,
3975
+ id: string,
3976
+ action: string,
3977
+ principal: string,
3978
+ relations: readonly RelationHold[],
3979
+ paths: readonly ContainerGrant[],
3980
+ ): Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }> {
3981
+ const owner = locatedOwner(models, dimension)
3982
+ if (typeof id !== 'string' || id.length === 0 || typeof principal !== 'string' || principal.length === 0 || typeof action !== 'string') {
3983
+ throw new QueryRefusedError('row_address', `a ${dimension} held through a path is addressed by its key, the principal and the action`)
3984
+ }
3985
+ let count = 0
3986
+ const grantOf = (grant: unknown, what: string): ContainerGrant => {
3987
+ const at: unknown = typeof grant === 'object' && grant !== null ? ownDescriptor(grant, 'dimension')?.value : undefined
3988
+ const values = typeof grant === 'object' && grant !== null
3989
+ ? parseList(ownDescriptor(grant, 'values')?.value, (value) => {
3990
+ if (typeof value !== 'string' || value === '') throw new QueryRefusedError('row_address', 'a grant names its node, a non-empty string')
3991
+ return value
3992
+ })
3993
+ : undefined
3994
+ if (typeof at !== 'string' || values === undefined) {
3995
+ throw new QueryRefusedError('row_address', `${what} names its dimension and its nodes`)
3996
+ }
3997
+ count += values.length
3998
+ return freeze({ dimension: at, values: freeze(values) })
3999
+ }
4000
+ const named = parseList(relations, (hold): RelationHold => {
4001
+ const relation: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'relation')?.value : undefined
4002
+ const inside: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'inside')?.value : undefined
4003
+ if (typeof relation !== 'string') throw new QueryRefusedError('row_address', 'a relation is named by its name')
4004
+ return freeze({ relation, inside: inside === null ? null : grantOf(inside, 'a relation held inside a node') })
4005
+ })
4006
+ const grants = parseList(paths, (grant): ContainerGrant => grantOf(grant, 'a grant of a path'))
4007
+ if (named === undefined || grants === undefined) {
4008
+ throw new QueryRefusedError('row_address', 'the candidates of a path are plain arrays')
4009
+ }
4010
+ if (count > MAX_WITHIN_VALUES) {
4011
+ throw new QueryRefusedError('row_address', `the grants of a path carry at most ${MAX_WITHIN_VALUES} nodes`)
4012
+ }
4013
+ const now = new Date()
4014
+ const session = sessionOf(runtime)
4015
+ const reached = async (
4016
+ terms: readonly OperationNode[],
4017
+ column: string,
4018
+ inside?: readonly string[],
4019
+ ): Promise<Readonly<Record<string, unknown>> | undefined> => {
4020
+ if (terms.length === 0) return undefined
4021
+ const found = AndNode.create(equals(owner.name, keyOf(owner), id), anyOf(terms))
4022
+ // A member-bound access term is not narrowed to the node (ADR-0076): the object's own column is, as the database compares it.
4023
+ const scope = inside === undefined ? found : AndNode.create(found, ParensNode.create(isIn(owner.name, column, valueList(inside))))
4024
+ const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, subqueries: layer.subqueries }
4025
+ const columns = column === keyOf(owner) ? [column] : [keyOf(owner), column]
4026
+ const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
4027
+ return row
4028
+ }
4029
+ const held: RelationHold[] = []
4030
+ for (let index = 0; index < named.length; index++) {
4031
+ const hold = named[index]
4032
+ if (hold === undefined) continue
4033
+ const column = hold.inside === null ? keyOf(owner) : nodeColumnOf(owner, hold.inside.dimension)
4034
+ const row = column === undefined
4035
+ ? undefined
4036
+ : await reached(relationTerms(layer.relations, owner, hold, principal, action, now, heldThrough(action)), column, hold.inside?.values)
4037
+ if (row === undefined || column === undefined) continue
4038
+ if (hold.inside === null) {
4039
+ held[held.length] = hold
4040
+ continue
4041
+ }
4042
+ const node = ownEntry(row, column)
4043
+ if (typeof node !== 'string') {
4044
+ throw new PolicyError(`${owner.name}.${column} came back as ${typeof node}; a containment column holds its scope value as text`)
4045
+ }
4046
+ held[held.length] = freeze({ relation: hold.relation, inside: freeze({ dimension: hold.inside.dimension, values: freeze([node]) }) })
4047
+ }
4048
+ const through: ContainerGrant[] = []
4049
+ for (let index = 0; index < grants.length; index++) {
4050
+ const grant = grants[index]
4051
+ if (grant !== undefined && (await reached(pathTerms(owner, [grant], heldThrough(action)), keyOf(owner))) !== undefined) {
4052
+ through[through.length] = grant
4053
+ }
4054
+ }
4055
+ return freeze({ relations: freeze(held), paths: freeze(through) })
4056
+ }
4057
+
2272
4058
  /** One guarded select by key of the containment columns the policy declares; the generated locator of the dimension. */
2273
4059
  async function locateObject(
2274
4060
  models: TableModels,
@@ -2281,6 +4067,11 @@ async function locateObject(
2281
4067
  if (typeof id !== 'string' || id.length === 0) {
2282
4068
  throw new QueryRefusedError('row_address', `a ${dimension} is located by its ${keyOf(owner)}, a non-empty string`)
2283
4069
  }
4070
+ return chainOf(owner, using ?? sessionOf(runtime), id)
4071
+ }
4072
+
4073
+ /** The containers of `owner`'s row keyed `id`, by dimension, read in `session`; `null` for no such row. */
4074
+ async function chainOf(owner: TableModel, session: Session, id: string): Promise<ReadonlyMap<string, string> | null> {
2284
4075
  const key = keyOf(owner)
2285
4076
  const scope = equals(owner.name, key, id)
2286
4077
  const columns: string[] = [key]
@@ -2288,7 +4079,7 @@ async function locateObject(
2288
4079
  columns[columns.length] = owner.chain[index]?.column ?? ''
2289
4080
  }
2290
4081
  const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope }
2291
- const [row] = await (using ?? sessionOf(runtime)).run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
4082
+ const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
2292
4083
  if (row === undefined) {
2293
4084
  return null
2294
4085
  }