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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +69 -13
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +67 -9
  10. package/src/errors.ts +9 -5
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +187 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +216 -77
  24. package/src/orm.ts +417 -158
  25. package/src/policy.ts +2043 -131
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1958 -167
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +39 -4
  35. package/src/testing-shared.ts +872 -148
  36. package/src/testing-sqlite.ts +215 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +172 -26
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +40 -9
  47. package/types/src/errors.d.ts +8 -5
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +35 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +167 -75
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +378 -27
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +7 -1
  70. package/types/src/testing-shared.d.ts +125 -26
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +176 -22
@@ -1,9 +1,13 @@
1
1
  import type { Admissions } from './admissions';
2
+ import type { ContainerGrant, RelationHold } from './capability';
2
3
  import type { Session } from './database';
3
4
  import type { WebhookTables } from './framework-tables';
4
5
  import type { JobLeases } from './job-leases';
5
6
  import type { JobWakes } from './job-wakes';
7
+ import type { Notifications } from './notifications';
6
8
  import type { DataAccess } from './orm';
9
+ import type { PushSubscriptions } from './push-subscriptions';
10
+ import type { RequestReceipts } from './request-receipts';
7
11
  import type { DataLayerRuntime, TableContext, TableProbe } from './store';
8
12
  import type { StoredFiles } from './stored-files';
9
13
  /**
@@ -11,6 +15,27 @@ import type { StoredFiles } from './stored-files';
11
15
  * the session to read in (a job's transaction, which sees the object it just wrote); a statement of its own otherwise.
12
16
  */
13
17
  export type Locator = (dimension: string, id: string, using?: Session) => Promise<ReadonlyMap<string, string> | null>;
18
+ /** Whether an active row of `relation`'s source names `principal` at `node`: what a Ref held through it is minted on. */
19
+ export type RelationCheck = (relation: string, node: string, principal: string) => Promise<boolean>;
20
+ /**
21
+ * Whether a row `relation` reaches for `principal` reveals `node` of `dimension` now: what a Ref held through a reveal
22
+ * is minted on.
23
+ */
24
+ export type RevealCheck = (relation: string, dimension: string, node: string, principal: string, action: string) => Promise<boolean>;
25
+ /**
26
+ * Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
27
+ * through a secondary path that holds the action for a Ref (`writeThrough`), or through a relation row or reveal: what a
28
+ * Ref held through a path is minted on, and carries.
29
+ */
30
+ export type PathCheck = (dimension: string, id: string, action: string, principal: string, relations: readonly RelationHold[], paths: readonly ContainerGrant[]) => Promise<{
31
+ readonly relations: readonly RelationHold[];
32
+ readonly paths: readonly ContainerGrant[];
33
+ }>;
34
+ /**
35
+ * Of `values`, the caller's grants of `action` at nodes of `revealing`, those whose row reveals `node` of `dimension` to
36
+ * its members now: what a Ref held through member reveals is minted on, and carries.
37
+ */
38
+ export type MemberRevealCheck = (revealing: string, values: readonly string[], dimension: string, node: string, action: string) => Promise<readonly string[]>;
14
39
  /** What the framework writes itself: its own `fabrika_*` tables. Usable once bound. */
15
40
  export interface FrameworkTables {
16
41
  readonly webhooks: WebhookTables;
@@ -21,17 +46,27 @@ export interface FrameworkTables {
21
46
  readonly admissions: Admissions;
22
47
  /** Every stored file (`fabrika_files`): staged before its object, claimed at its first reference, swept unreferenced. */
23
48
  readonly files: StoredFiles;
49
+ /** The answers of keyed mutations, read and written in the invocation's transaction (ADR-0078). */
50
+ readonly receipts: RequestReceipts;
51
+ /** The browsers' Web Push subscriptions (ADR-0088), read and written in the invocation's transaction. */
52
+ readonly push: PushSubscriptions;
53
+ /** The notifications written for people (ADR-0088 §6), which the inbox answers. */
54
+ readonly notifications: Notifications;
24
55
  }
25
56
  /** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
26
57
  export interface ProvisionalBinding {
27
58
  readonly locate: Locator;
59
+ readonly relates: RelationCheck;
60
+ readonly reveals: RevealCheck;
61
+ readonly holdsThrough: PathCheck;
62
+ readonly revealsToMembers: MemberRevealCheck;
28
63
  release(): void;
29
64
  }
30
65
  export interface FrameworkSide {
31
66
  /** Connects the layer once and answers its binding; a call while one is connected throws. */
32
67
  bind(runtime: DataLayerRuntime): ProvisionalBinding;
33
68
  readonly framework: FrameworkTables;
34
- /** The untyped handle over one table that `@fabrika/db/testing` hands the isolation tests. */
69
+ /** The untyped handle over one table that `@fabrika/db/testing` hands the policy isolation kit. */
35
70
  probe(table: string): TableProbe;
36
71
  /** One table's context, for the framework's own store builders (`defineStore`, `@fabrika/db/testing`). */
37
72
  tableContext(table: string, mode: 'dimension' | 'child'): TableContext;
@@ -0,0 +1,22 @@
1
+ import { type Session } from './database';
2
+ /** What a receipt records of the request it answers: its operation, the digest of its input, and the output's JSON. */
3
+ export interface RequestReceipt {
4
+ readonly operation: string;
5
+ readonly identity: string;
6
+ readonly output: string;
7
+ }
8
+ export interface RequestReceipts {
9
+ /**
10
+ * The receipt of `principal`'s `key`, read in `session`; `null` when there is none. On Postgres it first takes the
11
+ * key's transaction lock, so a concurrent copy of the request waits for this transaction and then reads its receipt
12
+ * instead of running too; SQLite's one writer already serializes them.
13
+ */
14
+ find(session: Session, principal: string, key: string): Promise<RequestReceipt | null>;
15
+ /**
16
+ * Records `receipt` under `principal`'s `key` in `session`, created at `now` (epoch ms), after pruning a batch of
17
+ * receipts created before `retainedSince`. `false` when the key already has a receipt: another copy of the request
18
+ * recorded it meanwhile, and this one's transaction must not commit.
19
+ */
20
+ record(session: Session, principal: string, key: string, receipt: RequestReceipt, now: number, retainedSince: number): Promise<boolean>;
21
+ }
22
+ export declare function requestReceipts(): RequestReceipts;
@@ -59,9 +59,9 @@ export interface SqlSite {
59
59
  * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
60
60
  * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
61
61
  */
62
- export declare function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase): string;
62
+ export declare function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase, sources?: readonly string[]): string;
63
63
  /**
64
64
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
65
65
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
66
66
  */
67
- export declare function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf): SqlTag;
67
+ export declare function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf, sources: readonly string[]): SqlTag;
@@ -26,3 +26,35 @@ export declare class SqliteMigrationError extends Error {
26
26
  export declare function migrateSqlite(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<{
27
27
  readonly applied: readonly string[];
28
28
  }>;
29
+ /** One row of the ledger, as a migration record names it: the identity and the checksum, without the time it ran. */
30
+ export interface SqliteLedgerEntry {
31
+ readonly bundle: string;
32
+ readonly name: string;
33
+ readonly checksum: string;
34
+ }
35
+ /** The ledger's rows in `(bundle, name)` order, and their digest. */
36
+ export interface SqliteLedger {
37
+ readonly entries: readonly SqliteLedgerEntry[];
38
+ readonly digest: string;
39
+ }
40
+ /** The SHA-256 of the rows' `bundle name checksum` lines in `(bundle, name)` order: neither part holds a space or a newline. */
41
+ export declare function sqliteLedgerDigest(entries: readonly SqliteLedgerEntry[]): Promise<string>;
42
+ /** The ledger as it stands; empty while the table does not exist. */
43
+ export declare function readSqliteLedger(target: SqliteMigrationTarget): Promise<SqliteLedger>;
44
+ /** What the database needs to reach the bundles: nothing, a digest only, or pending files. */
45
+ export interface SqliteMigrationPlan {
46
+ /** The ledger the plan starts from; `null` when every bundle matched its digest and the ledger was not read. */
47
+ readonly ledger: SqliteLedger | null;
48
+ /** The files to apply, the bundles in the order given and each bundle's files in name order. */
49
+ readonly pending: readonly SqliteLedgerEntry[];
50
+ /** Whether `apply` writes anything: a pending file, or a bundle digest that is out of date. */
51
+ readonly writes: boolean;
52
+ /**
53
+ * Applies every pending file with its ledger row, and records every out-of-date bundle digest, in one transaction
54
+ * that ends with `PRAGMA foreign_key_check`: a failing file or a row the check returns rolls the whole set back.
55
+ * Answers the identities it applied.
56
+ */
57
+ apply(): readonly string[];
58
+ }
59
+ /** Plans the bundles against the ledger without writing; refuses what `migrateSqlite` refuses, before anything runs. */
60
+ export declare function planSqliteMigrations(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<SqliteMigrationPlan>;
@@ -1,11 +1,13 @@
1
1
  import { type OperationNode, type ReturningNode } from 'kysely';
2
+ import { type MemberReveals, type PathRule, type RelationSources } from './authority';
2
3
  import { type NameSet } from './builtins';
3
- import { type AppGrant, type CapabilityAuthority, type Ref, type RefGrant, type Within, type WithinGrant } from './capability';
4
+ import { type AppGrant, type CapabilityAuthority, type CapabilityGrant, type Ref, type RefGrant, type Within, type WithinGrant } from './capability';
5
+ import { type ConditionModel } from './conditions';
4
6
  import { type Database, type Session, type SqlDialect } from './database';
5
- import { type Compare, type Contains, type NoColumns, type Primitive, type ScopedSelect, type TableShape } from './description';
7
+ import { type ComparableColumn, type Compare, type Contains, type NoColumns, type Primitive, type ScopedSelect, type TableShape } from './description';
6
8
  import { type FileBinding } from './file-columns';
7
- import type { ForeignKeyPair, GuardContext, RootKind } from './guard';
8
- import { type Acknowledgement, type ActionOf, type ChildTableName, type Container, type ContainerOf, type DimensionOf, type DimensionTableName, type InsertValues, type JoinableChildren, type ListDimensionOf, type MoveAcknowledgement, type Operation, type ParentOf, type PolicyRow, type TableModel, type TableModels, type Tables, type UpdateValues, type VersionArguments } from './policy';
9
+ import type { ForeignKeyPair, GuardContext, RootKind, ViewParentLink } from './guard';
10
+ import { type Acknowledgement, type ActionOf, type ChildTableName, type Container, type ContainerOf, type DimensionOf, type DimensionTableName, type InsertValues, type JoinableChildren, type ListDimensionOf, type MoveAcknowledgement, type Operation, type ParentOf, type PathWriter, type PolicyRow, type ReadReach, type SecondaryPath, type TableModel, type TableModels, type Tables, type UpdateValues, type VersionArguments } from './policy';
9
11
  import type { ScopeTerms, ScopeUse } from './sql';
10
12
  import { type TablePolicies } from './tables';
11
13
  import { type RowColumns } from './temporal';
@@ -34,6 +36,24 @@ export interface TableContext {
34
36
  /** The model of each child a select may join, by its table name. */
35
37
  readonly children: Readonly<Record<string, TableModel>>;
36
38
  readonly connection: Connection;
39
+ /** Every relation of the layer with its source table: what a relation term of any table reads. */
40
+ readonly relations: RelationSources;
41
+ /** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
42
+ readonly members: MemberReveals;
43
+ /** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
44
+ readonly subqueries: Readonly<Record<string, readonly string[]>>;
45
+ /** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
46
+ readonly through: ViewParent | undefined;
47
+ /** The path columns whose insert hands out actions, each with the table owning the node it names (`pathWriters`). */
48
+ readonly writers: readonly PathBound[];
49
+ }
50
+ /** A path column an insert writes under its bound, and the table that owns the dimension it names. */
51
+ export interface PathBound extends PathWriter {
52
+ readonly owner: TableModel;
53
+ }
54
+ /** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
55
+ export interface ViewParent extends ViewParentLink {
56
+ readonly context: TableContext;
37
57
  }
38
58
  /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
39
59
  export declare function dialectOf(context: TableContext): SqlDialect;
@@ -63,23 +83,31 @@ export declare function requiredActions(context: TableContext, operation: Operat
63
83
  export declare function checkAction(context: TableContext, operation: Operation, action: string): void;
64
84
  /** The object a Ref of the model's own dimension names, with every link of its chain. */
65
85
  export declare function selfLinks(model: TableModel): readonly Container[];
66
- /** This object, over the whole chain the Ref carries. */
67
- export declare function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode;
86
+ /** This object, over the whole chain the Ref carries; through the secondary paths `paths` admits, by default its action's. */
87
+ export declare function objectPredicate(context: TableContext, capability: unknown, operation: Operation, paths?: PathRule): OperationNode;
68
88
  /** Rows of a dimension table within the scope values of its list dimension. */
69
89
  export declare function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined;
70
- /** Rows of a child table that belong to the parent object the Ref names, over the whole chain. */
71
- export declare function parentPredicate(context: TableContext, grant: RefGrant): OperationNode;
90
+ /**
91
+ * Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
92
+ * of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
93
+ */
94
+ export declare function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode;
72
95
  export declare function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined;
73
96
  /**
74
- * The column that places a row of `model` in `dimension`: the column of that link of its containment chain, or a
75
- * top-level table's own key; `undefined` when no `Within` of the dimension reaches the table.
97
+ * Whether a `Within` of `dimension` lists the table: a dimension table its own dimension's, then through its containment
98
+ * chain or a secondary path; a child view through its parent's.
76
99
  */
77
- export declare function reachColumn(model: TableModel, dimension: string): string | undefined;
100
+ export declare function reachedBy(context: TableContext, dimension: string): boolean;
101
+ /** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
102
+ export declare function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[];
78
103
  /**
79
104
  * Rows of a table a `Within` of any dimension of its chain lists, by the table's read action: tasks under a `Within` of
80
- * `org` through their stamped `org_id`, as under one of `project` through `project_id`.
105
+ * `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
106
+ * table reaches through a secondary path, through that path's column.
81
107
  */
82
108
  export declare function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined;
109
+ /** The actions a grant holds: an `app` grant's (several for an `anyOf` endpoint), or any other grant's one. */
110
+ export declare function grantActions(grant: CapabilityGrant): readonly string[];
83
111
  /**
84
112
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
85
113
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
@@ -101,18 +129,30 @@ export declare function updatingRef(context: TableContext, capability: unknown,
101
129
  * action or an action of `appRead`; its counts (`count`, `aggregate`) with those or an action of `appCount`.
102
130
  */
103
131
  export type AppReach = 'rows' | 'counts';
132
+ /** What an `app` capability reads of a table: the rows (`predicate`), and the reach whose columns it answers. */
133
+ export interface AppRead {
134
+ readonly predicate: OperationNode;
135
+ readonly reach: ReadReach;
136
+ }
104
137
  /**
105
- * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`: `true`, for an action that
106
- * reaches `reach` (`checkRecordReach`).
138
+ * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`, for its actions that reach
139
+ * `reach` (`recordReach`): each row within the condition of one of them, and the columns they read alone.
107
140
  */
141
+ export declare function appRecordRead(context: TableContext, capability: unknown, reach: AppReach): AppRead;
142
+ /** `appRecordRead`'s rows. */
108
143
  export declare function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode;
109
- /** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
144
+ /**
145
+ * Every row a capability of an `app` endpoint reads in an application table, by the table's read actions it holds or
146
+ * `'any'`, and the reach whose columns it answers.
147
+ */
148
+ export declare function appListRead(context: TableContext, capability: unknown): AppRead;
149
+ /** `appListRead`'s rows. */
110
150
  export declare function appListPredicate(context: TableContext, capability: unknown): OperationNode;
111
151
  /**
112
152
  * Every row of an application table, for a `Ref` or a `Within` of its read action: what `ctx.db.app` of an `on`, `in`
113
153
  * or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
114
154
  */
115
- export declare function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode;
155
+ export declare function scopedApplicationRead(context: TableContext, capability: unknown, branch?: OperationNode | 'all'): OperationNode;
116
156
  /** One row of an application table by its key, for an `app` capability of `operation`'s action. */
117
157
  export declare function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode;
118
158
  /**
@@ -121,6 +161,7 @@ export declare function appRowPredicate(context: TableContext, capability: unkno
121
161
  */
122
162
  export declare function claimScope(context: TableContext, capability: unknown): {
123
163
  readonly grant: AppGrant | WithinGrant;
164
+ readonly action: string;
124
165
  readonly scope: OperationNode | undefined;
125
166
  };
126
167
  /**
@@ -128,13 +169,26 @@ export declare function claimScope(context: TableContext, capability: unknown):
128
169
  * it was claimed, so a row moved since is not reached.
129
170
  */
130
171
  export declare function claimedRowPredicate(context: TableContext, capability: unknown, operation: 'update' | 'delete'): OperationNode;
172
+ /** The row of an application table `key` names, as `actions` reach it: within their conditions, any one admitting it. */
173
+ export declare function appKeyScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode;
174
+ /** The row `key` names, as a read by key with `actions` reaches it: unconditioned in a table read with `'any'`. */
175
+ export declare function appGetScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode;
131
176
  /** The row of an application table `key` names. */
132
177
  export declare function appKeyPredicate(model: TableModel, key: unknown): OperationNode;
133
178
  /**
134
- * The capability of an `app` endpoint whose action updates columns of an application table: its update action, or a
135
- * column's own write action. Which columns it updates follows from the action (`updatableBy`).
179
+ * The actions of an `app` endpoint's capability that update columns of an application table, at least one: its update
180
+ * action, or a column's own write action. Which columns they update follows from them (`updatableByAny`).
181
+ */
182
+ export declare function updatingApp(context: TableContext, capability: unknown): readonly string[];
183
+ /**
184
+ * An `app` capability's update of the application table row `key`: `values`, read against the columns its update
185
+ * actions write, and the row's scope under only those actions that write every given column, any one's condition
186
+ * admitting the row. So several held actions never write one action's columns on rows only another one reaches.
136
187
  */
137
- export declare function updatingApp(context: TableContext, capability: unknown): AppGrant;
188
+ export declare function appUpdate(context: TableContext, capability: unknown, key: unknown, values: unknown): {
189
+ readonly scope: OperationNode;
190
+ readonly changes: Map<string, Primitive | null>;
191
+ };
138
192
  export declare function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode;
139
193
  export declare function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext;
140
194
  /**
@@ -154,7 +208,10 @@ export interface Runner {
154
208
  * lease (`fencedTransaction`): an attempt that lost it, or ran out of time, writes nothing.
155
209
  */
156
210
  export declare function fencedWork<T>(runtime: DataLayerRuntime, work: (transaction: Session) => Promise<T>): Promise<T>;
157
- /** The action a capability holds, which its operation's checks already admitted. */
211
+ /**
212
+ * The one action a capability holds, which its operation's checks already admitted. An `anyOf` endpoint's `app`
213
+ * capability that holds several is refused: it reads through `ctx.db.app`, which reads with every action it holds.
214
+ */
158
215
  export declare function heldAction(context: TableContext, capability: unknown): string;
159
216
  /**
160
217
  * Reads insert or update data through its own property descriptors, so no getter runs and no inherited or
@@ -165,12 +222,13 @@ export declare function readValues(values: unknown, allowed: NameSet, what: 'ins
165
222
  export declare function versionArgument(context: TableContext, options: readonly unknown[]): OperationNode | undefined;
166
223
  /**
167
224
  * One row by its scope predicate, with `visible` columns (the table's read action's, unless a capability reads its own).
168
- * `action` is what read it: each file column then answers a reference that reads the file only under a read action.
225
+ * `reach` is what read it: each file column then answers a reference that reads the file only under a read action.
169
226
  */
170
- export declare function selectOne<O>(context: TableContext, run: Runner, scope: OperationNode, visible?: readonly string[], action?: string): Promise<O>;
227
+ export declare function selectOne<O>(context: TableContext, run: Runner, scope: OperationNode, visible?: readonly string[], reach?: ReadReach): Promise<O>;
171
228
  export declare function answer(context: TableContext): ReturningNode;
172
229
  export declare function keyOf(model: TableModel): string;
173
- export declare function insertRow<O>(context: TableContext, run: Runner, given: ReadonlyMap<string, Primitive | null>, destination: RefGrant | undefined): Promise<O>;
230
+ /** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
231
+ export declare function insertRow<O>(context: TableContext, run: Runner, given: ReadonlyMap<string, Primitive | null>, prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined): Promise<O>;
174
232
  /**
175
233
  * `insert(values, { onConflict: { columns, do } })`: on a conflict of `columns` (a unique index of the table), `nothing`
176
234
  * writes nothing and `update` sets the columns the table's update action writes, from `updates`.
@@ -180,12 +238,14 @@ export interface OnConflict {
180
238
  readonly mode: 'nothing' | 'update';
181
239
  /** The values given for the table's update columns: what `update` sets on the conflicting row. */
182
240
  readonly updates: ReadonlyMap<string, Primitive | null>;
241
+ /** The capability's update actions, one of whose conditions the conflicting row must satisfy to be updated. */
242
+ readonly actions: readonly string[];
183
243
  }
184
244
  /**
185
245
  * The `onConflict` of an insert's options, read through own data properties; `undefined` without options. `'update'`
186
- * also needs the capability's action to be one of the table's update actions.
246
+ * also needs one of the capability's `actions` to be one of the table's update actions.
187
247
  */
188
- export declare function onConflictOf(context: TableContext, options: unknown, action: string, given: ReadonlyMap<string, Primitive | null>): OnConflict | undefined;
248
+ export declare function onConflictOf(context: TableContext, options: unknown, actions: readonly string[], given: ReadonlyMap<string, Primitive | null>): OnConflict | undefined;
189
249
  /**
190
250
  * The rows a write addresses: the scope predicate, and the caller's conditions beside it (an unscoped row's key, whose
191
251
  * scope predicate is `true`).
@@ -198,7 +258,17 @@ export interface Addressed {
198
258
  * Zero changed rows → one follow-up read in the same transaction → 404 when the object is gone, else 409. An update
199
259
  * that sets no column writes nothing, not even the version: it reads the acknowledgement under the same conditions.
200
260
  */
201
- export declare function updateRow<O>(context: TableContext, run: Runner, target: Addressed, given: ReadonlyMap<string, Primitive | null>, expectedVersion: OperationNode | undefined, destination?: RefGrant): Promise<O>;
261
+ export declare function updateRow<O>(context: TableContext, run: Runner, target: Addressed, given: ReadonlyMap<string, Primitive | null>, expectedVersion: OperationNode | undefined, moved?: MovedRow): Promise<O>;
262
+ /**
263
+ * A move's destination, locked before the write, and the destination's insert conditions, which judge the moved row
264
+ * after it as an insert into the destination judges its row: the insert action's (`judgeInserted`), and each one
265
+ * `relationWhen` puts on a relation the destination `Ref` holds through (`judgeNarrowed`).
266
+ */
267
+ export interface MovedRow {
268
+ readonly destination: RefGrant;
269
+ readonly judged: JudgedInsert | undefined;
270
+ readonly narrowed: readonly NarrowedInsert[];
271
+ }
202
272
  /** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
203
273
  export declare function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void>;
204
274
  type Columns<Row> = keyof Row & string;
@@ -206,11 +276,11 @@ type NumericColumn<Row> = {
206
276
  [K in Columns<Row>]: Exclude<Row[K], null> extends number | bigint | string ? K : never;
207
277
  }[Columns<Row>];
208
278
  export interface AggregateSpec<Row> {
209
- readonly groupBy?: readonly Columns<Row>[];
279
+ readonly groupBy?: readonly ComparableColumn<Row>[];
210
280
  readonly count?: boolean;
211
281
  readonly sum?: readonly NumericColumn<Row>[];
212
- readonly min?: readonly Columns<Row>[];
213
- readonly max?: readonly Columns<Row>[];
282
+ readonly min?: readonly ComparableColumn<Row>[];
283
+ readonly max?: readonly ComparableColumn<Row>[];
214
284
  readonly where?: (q: ScopedSelect<Row, Row, NoColumns>) => ScopedSelect<Row, unknown, NoColumns>;
215
285
  }
216
286
  type Listed<S, K extends 'groupBy' | 'sum' | 'min' | 'max'> = S extends {
@@ -238,8 +308,23 @@ export declare function aggregateRows<Row, O>(context: TableContext, run: Runner
238
308
  /** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
239
309
  export interface PreparedInsert {
240
310
  readonly row: Map<string, Primitive | null>;
311
+ /** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
312
+ readonly writer: string;
241
313
  readonly destination: RefGrant | undefined;
242
314
  readonly conflict: OnConflict | undefined;
315
+ /** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
316
+ readonly judged: JudgedInsert | undefined;
317
+ /** The destination's relations whose `relationWhen` for the insert follows a path: judged on the written row. */
318
+ readonly narrowed: readonly NarrowedInsert[];
319
+ }
320
+ export interface JudgedInsert {
321
+ readonly action: string;
322
+ readonly condition: ConditionModel;
323
+ }
324
+ /** A relation the destination `Ref` holds through, which the inserted table narrows for the insert by a condition with a path. */
325
+ export interface NarrowedInsert {
326
+ readonly relation: string;
327
+ readonly condition: ConditionModel;
243
328
  }
244
329
  /**
245
330
  * A dimension table's insert over a capability nobody type-checked: into a container (a new UUIDv7 key, the chain from
@@ -278,7 +363,9 @@ export declare class DimensionTable<DB, P, T extends string> {
278
363
  /**
279
364
  * Moves the object to another container: the delete action at the source, the insert action at the target,
280
365
  * whose chain is checked against the database. Every chain column changes; children that copy them follow
281
- * through `ON UPDATE CASCADE` on their composite foreign key. Answers the acknowledgement and the new chain.
366
+ * through `ON UPDATE CASCADE` on their composite foreign key. The moved row is judged by the insert action's
367
+ * condition and by the `relationWhen` of each relation the target holds through, as an insert into the target is.
368
+ * Answers the acknowledgement and the new chain.
282
369
  */
283
370
  move(ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>, to: Ref<ContainerOf<P, T>, ActionOf<P, T, 'insert'>>): Promise<MoveAcknowledgement<P, T>>;
284
371
  aggregate<const S extends AggregateSpec<Row<DB, P, T>>>(within: Within<ListDimensionOf<P, T>, ReadAction<P, T>>, spec: S): Promise<AggregateRow<Row<DB, P, T>, S>[]>;
@@ -298,7 +385,7 @@ export declare class ChildTable<DB, P, T extends string> {
298
385
  aggregate<const S extends AggregateSpec<Row<DB, P, T>>>(scope: ChildListScope<P, T>, spec: S): Promise<AggregateRow<Row<DB, P, T>, S>[]>;
299
386
  }
300
387
  /**
301
- * One table's operations without the store types, for `@fabrika/db/testing` only: the generated isolation tests address
388
+ * One table's operations without the store types, for `@fabrika/db/testing` only: the policy isolation kit addresses
302
389
  * a table by name. Every runtime check of a store applies; a child row is addressed by its parent's capability and
303
390
  * `key`, a dimension row by its capability alone.
304
391
  */
@@ -5,9 +5,9 @@ export { applicationRowRefusalText } from './application-rows';
5
5
  export type { ApplicationRowRefusal, ApplicationRowsPlan } from './application-rows';
6
6
  export { PolicyError } from './errors';
7
7
  export type { FileReference } from './file-references';
8
- export type { AnyDbIndex, ApplicationRows, ApplicationTables, AppRecordRows, ChildRows, ClaimedRow, ClaimedRowHandle, ClaimOptions, ContainedRows, CountOptions, DataKind, DbIndex, FragmentTable, IndexedTable, InsertConflict, InsertMethod, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, PublicApplicationRows, PublicApplicationTables, PublicInsertMethod, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, RowOf, Saved, ScopedApplicationRows, ScopedApplicationTables, ScopeTarget, TableNameOf, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
8
+ export type { AllOptions, AllQuery, AnyDbIndex, ApplicationRows, ApplicationTables, AppRecordRows, ChildRows, ClaimedRow, ClaimedRowHandle, ClaimOptions, ContainedRows, CountOptions, CountQuery, DataKind, DbIndex, FragmentTable, IndexedTable, InsertConflict, InsertMethod, ListOptions, ListPage, ListQuery, NoUnscoped, OrderTerm, OwnerRow, PublicApplicationRows, PublicApplicationTables, PublicInsertMethod, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, RowOf, Saved, ScopedApplicationRows, ScopedApplicationTables, ScopeTarget, TableNameOf, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
9
9
  export { type ApplicationPolicy, type ApplicationScope, type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type FilePolicies, isTables, type QueuePolicy, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type TableAction, type TableActions, type TableInsert, Tables, type TableUpdate, type VersionColumn, type VocabularyTables, } from './policy';
10
- export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
10
+ export type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, VocabularyViewPolicy, } from './vocabulary-tables';
11
11
  /**
12
12
  * The plan of seeding one row of each application table `rows` names (table → column → value), as an endpoint access
13
13
  * case seeds its `appRows`: the order, the foreign keys that link one given row to another, and every refusal.
@@ -15,6 +15,12 @@ export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVo
15
15
  * `applicationRowRefusalText`.
16
16
  */
17
17
  export declare function applicationRowsPlan<DB, P>(tables: Tables<DB, P>, rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>): ApplicationRowsPlan;
18
+ /**
19
+ * The tables whose rows hand out access, lowercased: a relation source or a path reveal, a member-revealing table, and
20
+ * the tables a principal path or a relation's condition reads. Only the data layer writes them; the migration classifier
21
+ * refuses database code that does.
22
+ */
23
+ export declare function accessTables<DB, P>(tables: Tables<DB, P>): readonly string[];
18
24
  /** Every table's policy in the form the contract artifact carries, by table name. */
19
25
  export type TablePolicies = Readonly<Record<string, TablePolicyArtifact>>;
20
26
  /** The artifact form of every policy `defineTables` (or `readTables`) checked. */
@@ -1,5 +1,6 @@
1
1
  import { type NameSet } from './builtins';
2
2
  import type { SqlDialect } from './database';
3
+ import { type JsonSchema } from './json';
3
4
  /**
4
5
  * A day as the layer answers it: the database's `YYYY-MM-DD` text, or a decoded `Date` that is exactly a UTC midnight
5
6
  * in 0001–9999 — the only `Date` `Bun.SQL` decodes correctly from a `date`, whatever the process's time zone.
@@ -25,9 +26,14 @@ export interface RowColumns {
25
26
  readonly timestamps: NameSet;
26
27
  /** Booleans: `true` or `false` (SQLite answers 1 or 0). */
27
28
  readonly booleans: NameSet;
29
+ /** JSON columns: the parsed value (SQLite answers its text). */
30
+ readonly json: NameSet;
31
+ /** The JSON columns with a declared schema, by the name each arrives under: a read value is parsed by it. */
32
+ readonly jsonSchemas: Readonly<Record<string, JsonSchema>>;
28
33
  }
29
34
  /**
30
35
  * Every row of a read as the layer answers it, in place: each day as `YYYY-MM-DD` text, and on SQLite each timestamp as
31
- * a `Date` and each boolean as `true` or `false`, so a handler reads the same values on both dialects.
36
+ * a `Date`, each boolean as `true` or `false` and each JSON column as its parsed value, so a handler reads the same
37
+ * values on both dialects.
32
38
  */
33
39
  export declare function answerRows<R>(dialect: SqlDialect, table: string, columns: RowColumns, rows: R[]): R[];