@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,24 @@
1
1
  import type { Database } from './database';
2
- import type { Primitive } from './description';
2
+ import { type Primitive } from './description';
3
+ import { type JsonColumnValue, type JsonSchema } from './json';
3
4
  import { type Tables } from './policy';
4
5
  import type { TableProbe } from './store';
5
- /** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
6
- export type SampleValue = Primitive | null;
6
+ /**
7
+ * A value a test row holds in a column; `null` for a nullable column the fixture left empty. Only a JSON column holds
8
+ * an object or an array: the sample of one whose policy declares a schema (`jsonSample`).
9
+ */
10
+ export type SampleValue = Primitive | JsonColumnValue | null;
11
+ /**
12
+ * A seeded value as a backend binds it: a JSON column's value as the JSON text the layer would write for it, so a
13
+ * seeded row and the kits' cases that write the same value through the layer hold the same JSON.
14
+ */
15
+ export declare function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): Primitive | null;
16
+ /**
17
+ * The sample of a JSON column whose policy declares `schema`: built from the schema's JSON Schema and parsed by the
18
+ * schema, which answers the value the layer would store. A `SeedLimitError` when the sample does not pass (a pattern,
19
+ * a refinement), as for a type the fixture has no sample of.
20
+ */
21
+ export declare function jsonSample(schema: JsonSchema, where: string): JsonColumnValue;
7
22
  /** One seeded row and where it lies. */
8
23
  export interface WorldRow {
9
24
  /** The row's key: the dimension value of a dimension table's row, a child's own key. */
@@ -20,18 +35,23 @@ export interface WorldRow {
20
35
  readonly type: string;
21
36
  readonly value: string;
22
37
  }[];
23
- /** The row's values of the policy's update columns, as seeded. */
38
+ /** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
24
39
  readonly updates: Readonly<Record<string, SampleValue>>;
25
40
  /**
26
41
  * The distinct value written into every text column the fixture filled itself, in this row and in its containers.
27
42
  * Each occurs in no other fixture, so one found in an answer to another scope is a leaked row.
28
43
  */
29
44
  readonly markers: readonly string[];
45
+ /**
46
+ * The values of the text columns of a row the table already held under a known scope value (`seedWorlds`' `scopes`),
47
+ * which no fixture wrote and other rows may share; empty for a row the fixture inserted.
48
+ */
49
+ readonly stored: readonly string[];
30
50
  }
31
51
  /** One seeded row of an application table, which lies in no dimension. */
32
52
  export interface ApplicationRow {
33
53
  readonly key: string;
34
- /** The row's values of the policy's update columns, as seeded. */
54
+ /** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
35
55
  readonly updates: Readonly<Record<string, SampleValue>>;
36
56
  /** The distinct value written into every text column the fixture filled itself. */
37
57
  readonly markers: readonly string[];
@@ -51,15 +71,30 @@ export interface SeededApplicationRows {
51
71
  export interface SeededRow {
52
72
  readonly key: string;
53
73
  readonly markers: readonly string[];
74
+ /** Deletes the row, the rows its foreign keys made the fixture insert, and every row that refers to them. */
75
+ readonly remove: () => Promise<void>;
54
76
  }
55
77
  /**
56
- * What the isolation fixture cannot seed for a schema: a CHECK its values fail, a required foreign key to a scoped table
57
- * outside the containment chain. It is a limit of the generator, named with the constraint or the column, never a
58
- * failure of the handler or the policy a case is about.
78
+ * What the isolation fixture cannot seed for a schema: a CHECK or a unique index no row it tries passes, a required
79
+ * foreign key whose referenced row it cannot seed. It is a limit of the generator, named with the constraint or the
80
+ * column, never a failure of the handler or the policy a case is about.
59
81
  */
60
82
  export declare class SeedLimitError extends Error {
61
83
  readonly name = "SeedLimitError";
62
84
  }
85
+ /** The constraint a seeded row failed, as a backend reads it off the database's error. */
86
+ export interface Violation {
87
+ readonly kind: 'check' | 'unique' | 'foreign';
88
+ /** The constraint's name, or for an unnamed CHECK on SQLite its expression, as the database reports it. */
89
+ readonly name: string;
90
+ /** The columns the database names (SQLite's unique error); `undefined` where the seeding looks them up by `name`. */
91
+ readonly columns?: readonly string[];
92
+ }
93
+ /** A seed limit of a row the database refused, with the constraint it failed: the seeding tries another row. */
94
+ export declare class ConstraintLimitError extends SeedLimitError {
95
+ readonly violation: Violation;
96
+ constructor(message: string, violation: Violation);
97
+ }
63
98
  /** One row of a table in each of two containment chains that share no value. */
64
99
  export interface IsolationWorlds {
65
100
  /**
@@ -70,11 +105,20 @@ export interface IsolationWorlds {
70
105
  readonly own: WorldRow;
71
106
  readonly other: WorldRow;
72
107
  /**
73
- * Deletes both rows of the table and every row that refers to them, however deep; the containers stay. A case whose
74
- * rows hold pinned values removes them, so the next case can pin the same values again under a unique index.
108
+ * Deletes both rows of the table it inserted, every container row it inserted when it was given known scope values,
109
+ * and every row that refers to them, however deep; the other containers stay. A case whose rows hold pinned values or
110
+ * known scope values removes them, so the next case can seed the same values again under a unique index.
75
111
  */
76
112
  readonly remove: () => Promise<void>;
77
113
  }
114
+ /**
115
+ * Known values of dimensions, by dimension: the own world's and the other world's, which differ. A dimension whose values
116
+ * are a fixed set (an enum the input names it by) takes these instead of fresh ones.
117
+ */
118
+ export type ScopeValues = Readonly<Record<string, {
119
+ readonly own: string;
120
+ readonly other: string;
121
+ }>>;
78
122
  /** What a test kit seeds through, over its migrated schema. */
79
123
  export interface TestSeeding {
80
124
  /**
@@ -83,9 +127,12 @@ export interface TestSeeding {
83
127
  * marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
84
128
  * `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
85
129
  * counts among the other row's markers, so a leak of it is still found. A pin of a column that places the row, or of
86
- * no text column, throws.
130
+ * no text column, throws. `scopes` place each world in known values of a dimension instead of fresh ones: a row of
131
+ * the table that owns it with that key is used as it is stored (a migration wrote it), its containers' values with it,
132
+ * and is inserted otherwise. A stored row of `table` itself takes no `values` or `pins`: they throw. A seed that throws
133
+ * removes what it inserted.
87
134
  */
88
- seedWorlds<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>, pins?: Readonly<Record<string, string>>): Promise<IsolationWorlds>;
135
+ seedWorlds<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>, pins?: Readonly<Record<string, string>>, scopes?: ScopeValues): Promise<IsolationWorlds>;
89
136
  /**
90
137
  * Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
91
138
  * as given, a text column too, every other column sampled. A value for a stamped column or a file column throws.
@@ -100,13 +147,19 @@ export interface TestSeeding {
100
147
  */
101
148
  seedApplicationRows<DB, P>(tables: Tables<DB, P>, rows: Readonly<Record<string, Readonly<Record<string, SampleValue>>>>): Promise<SeededApplicationRows>;
102
149
  /**
103
- * Seeds one row of `table`, a child or dimension table that lies in the object of `under` (a row `seedWorlds`
104
- * seeded), placed in that row's chain: the row a fixture names by id, such as a note's comment. Answers its key and
105
- * the markers it holds.
150
+ * Seeds one row of `table`, a child or dimension table that lies in the object `under`'s chain starts at (a row
151
+ * `seedWorlds` seeded, or a value of its chain with the values outside it), placed in that chain: the row a fixture
152
+ * names by id, such as a note's comment. Answers its key and the markers it holds.
153
+ */
154
+ seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: Pick<WorldRow, 'chain'>): Promise<SeededRow>;
155
+ /**
156
+ * Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file
157
+ * column a seeded file. `beside` is a row `seedWorlds` seeded that the inserted row will lie beside, in the same
158
+ * containers. A number column a unique index covers takes the next number above the largest the table holds now in the
159
+ * row's group (the index's other columns as the row will have them, its containers' from `beside`), so insert the
160
+ * values before taking the next sample, or the two share it.
106
161
  */
107
- seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: WorldRow): Promise<SeededRow>;
108
- /** Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file column a seeded file. */
109
- sampleInsert<DB, P>(tables: Tables<DB, P>, table: string): Promise<Readonly<Record<string, SampleValue>>>;
162
+ sampleInsert<DB, P>(tables: Tables<DB, P>, table: string, beside?: WorldRow): Promise<Readonly<Record<string, SampleValue>>>;
110
163
  /**
111
164
  * The object key of every file the fixture seeded into a file column, oldest first. Each stands for an empty object,
112
165
  * which a test's object store holds when a handler serves or opens the file.
@@ -134,8 +187,16 @@ export interface SeedColumn {
134
187
  readonly text: boolean;
135
188
  /** A uuid type: a key or containment column of it holds a random uuid as its scope value. */
136
189
  readonly uuid: boolean;
137
- /** A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it cannot fill. */
138
- readonly sample: () => Primitive;
190
+ /** A number type: where a unique index covers it, the fixture writes the next number of the row's group instead of its sample. */
191
+ readonly number: boolean;
192
+ /** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
193
+ readonly json: boolean;
194
+ /**
195
+ * A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it
196
+ * cannot fill. `variant` 0 is the plain sample; a higher one differs from the lower ones where the type allows (another
197
+ * day, the other boolean, a larger number), for a unique index whose other columns the row cannot vary.
198
+ */
199
+ readonly sample: (variant: number) => Primitive;
139
200
  }
140
201
  /** A CHECK constraint of the schema, by the columns it names. */
141
202
  export interface CheckConstraint {
@@ -143,7 +204,22 @@ export interface CheckConstraint {
143
204
  readonly table: string;
144
205
  readonly columns: readonly string[];
145
206
  /** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
146
- readonly values: readonly string[];
207
+ readonly values: readonly CheckLiteral[];
208
+ /** Every text and number literal of the expression: what the fixture tries in the columns it names when a row fails it. */
209
+ readonly literals: readonly CheckLiteral[];
210
+ }
211
+ /** A literal of a CHECK expression. */
212
+ export type CheckLiteral = string | number;
213
+ /**
214
+ * A unique index of the schema (a primary key's or a UNIQUE constraint's included), by its key columns. Only an index of
215
+ * plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
216
+ */
217
+ export interface UniqueIndex {
218
+ readonly name: string;
219
+ readonly table: string;
220
+ readonly columns: readonly string[];
221
+ /** `NULLS NOT DISTINCT`: a null in a key column collides with another row's null there. */
222
+ readonly nullsNotDistinct: boolean;
147
223
  }
148
224
  /** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it. */
149
225
  export interface SeededFile {
@@ -167,10 +243,21 @@ export interface SeedingBackend {
167
243
  readonly columns: readonly SeedColumn[];
168
244
  /** Every CHECK constraint of the schema's tables; read once, on the first column that needs them. */
169
245
  checks(): Promise<readonly CheckConstraint[]>;
170
- /** Inserts one row and answers it as stored; a CHECK or foreign key it fails is a `SeedLimitError` (`checkLimit`, `foreignKeyLimit`). */
246
+ /** Every unique index of plain columns and no predicate of the schema's tables; read once, on the first column that needs them. */
247
+ uniqueIndexes(): Promise<readonly UniqueIndex[]>;
248
+ /**
249
+ * The smallest whole number above every value `column` holds in the rows of `table` that match one of `groups`
250
+ * (`groupsWhere`), and at least 1, as the column's type holds it; `undefined` when the type holds no such number, or
251
+ * the largest is no finite number.
252
+ */
253
+ nextNumber(table: string, column: string, groups: readonly ReadonlyMap<string, SampleValue>[]): Promise<Primitive | undefined>;
254
+ /**
255
+ * Inserts one row and answers it as stored; a CHECK, foreign key or unique index it fails is a `SeedLimitError`
256
+ * (`checkLimit`, `foreignKeyLimit`, `uniqueValueLimit`).
257
+ */
171
258
  insert(table: string, values: ReadonlyMap<string, SampleValue>): Promise<Readonly<Record<string, unknown>>>;
172
- /** One row of `table`, of `columns`, or `undefined` when it has none. */
173
- firstRow(table: string, columns: readonly string[]): Promise<Readonly<Record<string, unknown>> | undefined>;
259
+ /** One row of `table` that holds `where` (column → value; every row when empty), of `columns`, or `undefined` when none does. */
260
+ firstRow(table: string, columns: readonly string[], where?: ReadonlyMap<string, SampleValue>): Promise<Readonly<Record<string, unknown>> | undefined>;
174
261
  insertFile(file: SeededFile): Promise<void>;
175
262
  /**
176
263
  * Deletes `rows` (each found by its `match`; one already gone is skipped) and every row that refers to one of them,
@@ -180,11 +267,23 @@ export interface SeedingBackend {
180
267
  remove(rows: readonly InsertedRow[]): Promise<void>;
181
268
  }
182
269
  /** The seed limit of a CHECK a seeded row fails. */
183
- export declare function checkLimit(constraint: string, table: string): SeedLimitError;
270
+ export declare function checkLimit(constraint: string, table: string): ConstraintLimitError;
184
271
  /** The seed limit of a foreign key a seeded row breaks. */
185
- export declare function foreignKeyLimit(constraint: string, table: string): SeedLimitError;
272
+ export declare function foreignKeyLimit(constraint: string, table: string): ConstraintLimitError;
273
+ /** The seed limit of a number column a unique index covers whose type holds no number above the largest of the row's group. */
274
+ export declare function uniqueLimit(index: string, table: string, column: string): SeedLimitError;
275
+ /** The seed limit of a row whose values another row of the table already holds under a unique index. */
276
+ export declare function uniqueValueLimit(index: string, table: string, columns?: readonly string[]): ConstraintLimitError;
186
277
  /** The seed limit of a required column whose type the fixture has no sample of. */
187
278
  export declare function typeLimit(table: string, column: string, type: string): SeedLimitError;
279
+ /**
280
+ * A condition that matches a row holding every value of one of `groups` (column → value, `null` matched by `IS NULL`; an
281
+ * empty group matches every row, no group none), in the dialect's quoting and placeholders, with the values it binds.
282
+ */
283
+ export declare function groupsWhere(groups: readonly ReadonlyMap<string, SampleValue>[], quote: (identifier: string) => string, placeholder: (position: number) => string): {
284
+ where: string;
285
+ values: SampleValue[];
286
+ };
188
287
  export declare function randomHex(): string;
189
288
  /**
190
289
  * The object version a seeded file was scanned at: whoever stocks its empty object (`seededObjects`) stores it under
@@ -1,17 +1,32 @@
1
1
  import type { TableProbe } from './store';
2
2
  import { type TestDatabase } from './testing-shared';
3
3
  export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store';
4
- export { type ApplicationRow, type IsolationWorlds, type SampleValue, SEEDED_OBJECT_VERSION, type SeededApplicationRows, type SeededRow, SeedLimitError, type TestDatabase, type WorldRow, } from './testing-shared';
4
+ export { type ApplicationRow, type IsolationWorlds, type SampleValue, type ScopeValues, SEEDED_OBJECT_VERSION, type SeededApplicationRows, type SeededRow, SeedLimitError, type TestDatabase, type WorldRow, } from './testing-shared';
5
5
  export interface TestDatabaseOptions {
6
6
  /** The application's `db/migrations/` directory. */
7
7
  readonly migrations: string | URL;
8
8
  /** The test file. `@fabrika/db/testing` names it when it skips; this kit never skips. */
9
9
  readonly label: string;
10
+ /** A database migrated and seeded once (`testDatabaseTemplate`), which this one starts as a copy of. */
11
+ readonly template?: TestDatabaseTemplate;
10
12
  }
13
+ /** A migrated database with its base seed, as an image every `testDatabase({ template })` copies. */
14
+ export interface TestDatabaseTemplate {
15
+ /** The migrations it was migrated with: a database of other migrations does not start from it. */
16
+ readonly migrations: string;
17
+ readonly image: Uint8Array;
18
+ }
19
+ /**
20
+ * Migrates a database once, runs `seed` in it, and keeps it as the image each `testDatabase({ template })` starts as a
21
+ * copy of: in milliseconds, without migrating or seeding again.
22
+ */
23
+ export declare function testDatabaseTemplate(options: Omit<TestDatabaseOptions, 'template'> & {
24
+ readonly seed?: (database: TestDatabase) => Promise<void>;
25
+ }): Promise<TestDatabaseTemplate>;
11
26
  /**
12
27
  * A fresh in-memory database with the framework's and the application's migrations applied by the runner a Durable
13
28
  * Object boots with (`@fabrika/db/sqlite-migrate`), opened with its engine (`@fabrika/db/sqlite`). Never `null`: it
14
- * needs no backend, so it never skips; its type is still assignable to `@fabrika/db/testing`'s, so a generated test
29
+ * needs no backend, so it never skips; its type is still assignable to `@fabrika/db/testing`'s, so a test
15
30
  * that checks for `null` compiles against both kits.
16
31
  */
17
32
  export declare function testDatabase(options: TestDatabaseOptions): Promise<TestDatabase>;
@@ -1,7 +1,7 @@
1
1
  import type { TableProbe } from './store';
2
2
  import { type TestDatabase } from './testing-shared';
3
3
  export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store';
4
- export { type ApplicationRow, type IsolationWorlds, type SampleValue, SEEDED_OBJECT_VERSION, type SeededApplicationRows, type SeededRow, SeedLimitError, type TestDatabase, type WorldRow, } from './testing-shared';
4
+ export { type ApplicationRow, type IsolationWorlds, type SampleValue, type ScopeValues, SEEDED_OBJECT_VERSION, type SeededApplicationRows, type SeededRow, SeedLimitError, type TestDatabase, type WorldRow, } from './testing-shared';
5
5
  export declare const TEST_POSTGRES_URL = "FABRIKA_TEST_POSTGRES_URL";
6
6
  /** Set to `1` by the platform build: a missing test database is then a failure, not a skip. */
7
7
  export declare const TEST_POSTGRES_REQUIRED = "FABRIKA_TEST_POSTGRES_REQUIRED";
@@ -1,16 +1,28 @@
1
- import type { ColumnList, ColumnPolicies, FilePolicies, RecordActions, ReferencePolicy, TableActions, Tables, VersionColumn } from './policy';
1
+ import type { ConditionPolicy } from './conditions';
2
+ import type { AccessPolicy, ApplicationActions, ColumnList, ColumnPolicies, ConfersPolicy, FilePolicies, JsonColumn, JsonPolicies, MemberRevealsPolicy, RecordActions, ReferencePolicy, RevealsPolicy, TableAction, TableActions, Tables, VersionColumn } from './policy';
2
3
  declare const databaseType: unique symbol;
4
+ declare const viewNames: unique symbol;
3
5
  /**
4
- * The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types, so that
5
- * `defineTables(vocabulary, columns)` takes no type argument. The brand is type-only: no value has the property.
6
+ * The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types and the names of
7
+ * its views, so that `defineTables(vocabulary, columns)` takes no type argument. The brands are type-only: no value
8
+ * has either property.
6
9
  */
7
- export type TypedColumnList<DB> = ColumnList<DB> & {
10
+ export type TypedColumnList<DB, Views extends keyof DB & string = never> = ColumnList<DB> & {
8
11
  readonly [databaseType]?: DB;
12
+ readonly [viewNames]?: {
13
+ readonly views: Views;
14
+ };
9
15
  };
10
16
  /** The row types a typed column list carries; `never` for a list without them. */
11
17
  export type ColumnTypes<C> = typeof databaseType extends keyof C ? C extends {
12
18
  readonly [databaseType]?: infer DB;
13
19
  } ? Exclude<DB, undefined> : never : never;
20
+ /** The views a typed column list names; `never` for a list without views. */
21
+ export type ColumnViews<C> = typeof viewNames extends keyof C ? C extends {
22
+ readonly [viewNames]?: {
23
+ readonly views: infer Views extends string;
24
+ };
25
+ } ? Views : never : never;
14
26
  /**
15
27
  * What `defineTables(vocabulary, columns)` reads of `@fabrika/app/contract`'s `defineVocabulary` result: the action
16
28
  * and dimension names, and each dimension's container. `@fabrika/db` does not import `@fabrika/app`.
@@ -24,6 +36,11 @@ export interface TableVocabulary {
24
36
  readonly in?: string;
25
37
  };
26
38
  };
39
+ readonly relations?: {
40
+ readonly [relation: string]: {
41
+ readonly dimension: string;
42
+ };
43
+ };
27
44
  }
28
45
  export type VocabularyAction<V> = V extends {
29
46
  readonly actions: infer A;
@@ -72,15 +89,64 @@ export type VocabularyChildScope<Table extends string, Col extends string> = {
72
89
  readonly column?: Col;
73
90
  readonly inherit?: readonly Col[];
74
91
  } & KeyField<Col>;
75
- interface WritableFields<Col extends string, A extends string, Ver extends Col, Acts = TableActions<A>> {
92
+ /** A written table whose `version` column is not an INTEGER names its version column: `version` would be it otherwise. */
93
+ interface NamesItsVersionColumn<Ver extends string> {
94
+ readonly version: Ver;
95
+ }
96
+ /** `version` defaults to the `version` column, so it is required only where that column holds no number. */
97
+ type VersionField<Col extends string, Ver extends Col> = 'version' extends Col ? 'version' extends Ver ? {
98
+ readonly version?: Ver;
99
+ } : NamesItsVersionColumn<Ver> : {
100
+ readonly version?: Ver;
101
+ };
102
+ interface WritableFields<Col extends string, A extends string, Acts = TableActions<A>> {
76
103
  readonly actions: Acts;
77
104
  readonly insert?: readonly Col[];
78
105
  readonly update?: readonly Col[];
79
- readonly version?: Ver;
80
106
  readonly createdBy?: Col;
81
107
  readonly columns?: ColumnPolicies<Col, A>;
82
108
  /** The file columns, each with the file kind it holds (`c.files`): a `uuid` foreign key to `fabrika_files`. */
83
109
  readonly files?: FilePolicies<Col>;
110
+ /** Relation → how a row of this table confers it: whom it names, at which node, until when. */
111
+ readonly confers?: {
112
+ readonly [relation: string]: ConfersPolicy<Col>;
113
+ };
114
+ /** Action → the condition a row must meet for it, whoever holds it. */
115
+ readonly when?: {
116
+ readonly [action in A]?: ConditionPolicy<Col>;
117
+ };
118
+ /** Relation → action → the condition a row that relation reaches must meet for it; IAM grants are not narrowed. */
119
+ readonly relationWhen?: {
120
+ readonly [relation: string]: {
121
+ readonly [action in A]?: ConditionPolicy<Col>;
122
+ };
123
+ };
124
+ /** Relation of the table's own dimension → the ancestor node a row it reaches reveals, and for which actions. */
125
+ readonly reveals?: {
126
+ readonly [relation: string]: RevealsPolicy<Col, A>;
127
+ };
128
+ /**
129
+ * Dimension outside the chain → the foreign key column a `Within`'s read reaches a row through, no update writes it; or
130
+ * `<nearest container column>.<its column>`, the nearest container's own path.
131
+ */
132
+ readonly readThrough?: {
133
+ readonly [dimension: string]: Col | `${Col}.${string}`;
134
+ };
135
+ /**
136
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds, writes included; whoever inserts the
137
+ * path's column must hold each at the node it names.
138
+ */
139
+ readonly writeThrough?: {
140
+ readonly [dimension: string]: readonly A[];
141
+ };
142
+ /** The table's own dimension → the ancestor node a row reveals to a grant at its node, for a `Within`'s reads. */
143
+ readonly memberReveals?: {
144
+ readonly [dimension: string]: MemberRevealsPolicy<Col, A>;
145
+ };
146
+ /** Relation → the access view that lists the rows it reaches: the escape path, decided by the view's SQL. */
147
+ readonly access?: {
148
+ readonly [relation: string]: AccessPolicy;
149
+ };
84
150
  }
85
151
  /**
86
152
  * The scope of the dimension the policy states (`S`, its scope as written); for any other name, the dimension alone,
@@ -128,14 +194,72 @@ type ChildScopes<Table extends string, Col extends string, S, P> = unknown exten
128
194
  } ? T : never;
129
195
  }[keyof P] & string;
130
196
  } : ChildTableScope<Parent, StatedDimensionOf<P, Parent>, Col> : VocabularyChildScope<Table, Col>;
131
- type AuthoredDimensionPolicy<Col extends string, A extends string, V, Ver extends Col, S> = WritableFields<Col, A, Ver, RecordActions<A>> & {
197
+ type AuthoredDimensionPolicy<Col extends string, A extends string, V, Ver extends Col, S> = WritableFields<Col, A, RecordActions<A>> & VersionField<Col, Ver> & {
132
198
  readonly scope: DimensionScopes<V, Col, S>;
133
199
  };
134
- type AuthoredChildPolicy<Table extends string, Col extends string, A extends string, Ver extends Col, S, P> = WritableFields<Col, A, Ver, RecordActions<A>> & {
200
+ type AuthoredChildPolicy<Table extends string, Col extends string, A extends string, Ver extends Col, S, P> = WritableFields<Col, A, RecordActions<A>> & VersionField<Col, Ver> & {
135
201
  readonly scope: ChildScopes<Table, Col, S, P>;
136
202
  };
203
+ /** What a view's policy holds besides its scope: read actions only, no write list and no stamped column. */
204
+ type ViewIsReadOnly = 'a view is never written: its actions are read, appRead and appCount';
205
+ /** The write actions a view's policy may not name, each typed as the message: a literal is not checked for excess keys. */
206
+ interface NoWriteActions {
207
+ readonly insert?: ViewIsReadOnly;
208
+ readonly update?: ViewIsReadOnly;
209
+ readonly delete?: ViewIsReadOnly;
210
+ }
211
+ interface ReadOnlyFields<Col extends string, A extends string> {
212
+ readonly actions: {
213
+ readonly read: TableAction<A>;
214
+ readonly appRead?: readonly A[];
215
+ readonly appCount?: readonly A[];
216
+ } & NoWriteActions;
217
+ readonly insert?: never;
218
+ readonly update?: never;
219
+ readonly version?: never;
220
+ readonly createdBy?: never;
221
+ readonly queue?: never;
222
+ readonly files?: never;
223
+ readonly columns?: {
224
+ readonly [C in Col]?: {
225
+ readonly read: TableAction<A>;
226
+ readonly write?: never;
227
+ };
228
+ };
229
+ }
230
+ /**
231
+ * A view read as a child table: its parent's `Ref` and `Within` read it; nothing writes it (ADR-0072). Its `when` and
232
+ * `relationWhen` narrow its read actions; a path may start at its parent column, to the parent row.
233
+ */
234
+ type AuthoredChildViewPolicy<Table extends string, Col extends string, A extends string, S, P> = ReadOnlyFields<Col, A> & {
235
+ readonly scope: ChildScopes<Table, Col, S, P>;
236
+ readonly when?: {
237
+ readonly [action in A]?: ConditionPolicy<Col>;
238
+ };
239
+ /** Relation → action → the condition a row the relation reaches through the parent row must meet for it. */
240
+ readonly relationWhen?: {
241
+ readonly [relation: string]: {
242
+ readonly [action in A]?: ConditionPolicy<Col>;
243
+ };
244
+ };
245
+ };
246
+ /** A view's policy as written: a read-only child, or a reference table every site reads. */
247
+ export type VocabularyViewPolicy<Table extends string, Col extends string, A extends string, S = unknown, P = unknown> = S extends {
248
+ readonly child: unknown;
249
+ } ? AuthoredChildViewPolicy<Table, Col, A, S, P> : S extends {
250
+ readonly reference: unknown;
251
+ } ? ReferenceViewPolicy<Col, A> : AuthoredChildViewPolicy<Table, Col, A, S, P> | ReferenceViewPolicy<Col, A>;
252
+ type ReferenceViewPolicy<Col extends string, A extends string> = ReferencePolicy<Col, A> & {
253
+ readonly actions: NoWriteActions;
254
+ readonly columns?: {
255
+ readonly [C in Col]?: {
256
+ readonly read: TableAction<A>;
257
+ readonly write?: never;
258
+ };
259
+ };
260
+ };
137
261
  /** An application table's scope: why its rows belong to no dimension; `key` defaults to `id`. */
138
- type AuthoredApplicationPolicy<Col extends string, A extends string, Ver extends Col> = WritableFields<Col, A, Ver> & {
262
+ type AuthoredApplicationPolicy<Col extends string, A extends string, Ver extends Col> = WritableFields<Col, A, ApplicationActions<A>> & VersionField<Col, Ver> & {
139
263
  readonly scope: {
140
264
  readonly app: string;
141
265
  } & KeyField<Col>;
@@ -158,14 +282,26 @@ type StatedScope<P, T> = T extends keyof P ? P[T] extends {
158
282
  } ? S : unknown : unknown;
159
283
  /** The policy of table `T` with nothing stated: every form, every dimension's scope, any parent. */
160
284
  type AnyTablePolicy<DB, V, T extends keyof DB & string> = VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>>;
285
+ /** The policy of view `T` with nothing stated: both forms, any parent. */
286
+ type AnyViewPolicy<DB, V, T extends keyof DB & string> = VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>>;
161
287
  /**
162
- * Every table of the schema, and no other, maps to a policy; a misspelt action or dimension fails at its own line.
163
- * `P` is the policies as written, which picks each table's form by the scope it states; a policy written under this
164
- * map's own annotation states nothing narrower, so it is checked against every form.
288
+ * Every table of the schema, and no other, maps to a policy; a view `Views` names may (ADR-0072). A misspelt action or
289
+ * dimension fails at its own line. `P` is the policies as written, which picks each table's form by the scope it
290
+ * states; a policy written under this map's own annotation states nothing narrower, so it is checked against every
291
+ * form.
165
292
  */
166
- export type VocabularyPolicyMap<DB, V, P = unknown> = {
167
- readonly [T in keyof DB & string]: AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T> : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>;
293
+ export type VocabularyPolicyMap<DB, V, P = unknown, Views extends string = never> = {
294
+ readonly [T in Exclude<keyof DB & string, Views>]: (AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T> : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>) & JsonField<DB[T]>;
295
+ } & {
296
+ readonly [T in Views & keyof DB & string]?: (AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T> : VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>) & JsonField<DB[T]>;
168
297
  };
298
+ /**
299
+ * Column → the zod schema of a JSON column (`jsonb`, or `JSONB` on SQLite): each write is parsed by it before it is
300
+ * stored, and each read value too; the handle types read its output and write its input.
301
+ */
302
+ interface JsonField<Row> {
303
+ readonly json?: JsonPolicies<JsonColumn<Row>>;
304
+ }
169
305
  type Flat<T> = {
170
306
  [K in keyof T]: T[K];
171
307
  };
@@ -207,19 +343,37 @@ type NormalScope<S, V, P> = S extends {
207
343
  readonly app: R;
208
344
  readonly key: KeyOf<S>;
209
345
  } : S;
346
+ /** A view's normalized policy says so, which the handle types read: no site writes it. */
347
+ type ViewMark<T, Views> = T extends Views ? {
348
+ readonly view: true;
349
+ } : unknown;
350
+ /** A written table's `version` and `created_by` columns are its version and creator unless its policy names others. */
351
+ type Conventions<Row, Pol> = (Pol extends {
352
+ readonly version: string;
353
+ } ? unknown : 'version' extends keyof Row ? {
354
+ readonly version: 'version';
355
+ } : unknown) & (Pol extends {
356
+ readonly createdBy: string;
357
+ } ? unknown : 'created_by' extends keyof Row ? {
358
+ readonly createdBy: 'created_by';
359
+ } : unknown);
360
+ /** Only a dimension, child or application table is written; a view and a reference table get no convention. */
361
+ type WrittenConventions<DB, T, Pol, S, Views> = T extends Views ? unknown : S extends {
362
+ readonly reference: unknown;
363
+ } ? unknown : Conventions<T extends keyof DB ? DB[T] : never, Pol>;
210
364
  /**
211
- * The policies as the layer models them: every dimension table's key and container, and every child's key and
212
- * column, stated as the vocabulary and the conventions derive them.
365
+ * The policies as the layer models them: every dimension table's key and container, every child's key and column,
366
+ * and a written table's version and creator, stated as the vocabulary and the conventions derive them; each view marked.
213
367
  */
214
- export type NormalizedPolicies<P, V> = {
368
+ export type NormalizedPolicies<DB, P, V, Views = never> = {
215
369
  readonly [T in keyof P]: P[T] extends {
216
370
  readonly scope: infer S;
217
- } ? Flat<Omit<P[T], 'scope'> & {
371
+ } ? Flat<Omit<P[T], 'scope' | 'view'> & {
218
372
  readonly scope: NormalScope<S, V, P>;
219
- }> : P[T];
373
+ } & ViewMark<T, Views> & WrittenConventions<DB, T, P[T], S, Views>> : P[T];
220
374
  };
221
- /** Takes the policies of exactly the tables of the schema, written in the vocabulary form. */
222
- export type DefineVocabularyPolicies<DB, V> = <const P extends VocabularyPolicyMap<DB, V, P>>(policies: P & {
375
+ /** Takes the policies of exactly the tables of the schema, and of any of its views, written in the vocabulary form. */
376
+ export type DefineVocabularyPolicies<DB, V, Views extends string = never> = <const P extends VocabularyPolicyMap<DB, V, P, Views>>(policies: P & {
223
377
  readonly [K in Exclude<keyof P, keyof DB>]: never;
224
- }) => Tables<DB, NormalizedPolicies<P, V>>;
378
+ }) => Tables<DB, NormalizedPolicies<DB, P, V, Views>>;
225
379
  export {};