@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.20

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 (80) hide show
  1. package/package.json +35 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +229 -40
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
@@ -0,0 +1,151 @@
1
+ import type { ConditionArtifact } from '@fabrika/auth-core';
2
+ import { type NameSet } from './builtins';
3
+ import type { Primitive } from './description';
4
+ /** A literal a condition compares with. `{ now: true }` is the statement's clock, never the text `now`. */
5
+ export type ConditionLiteral = string | number | boolean;
6
+ export interface NowOperand {
7
+ readonly now: true;
8
+ }
9
+ /** The parsed clock operand, compared by identity: no literal, the text `now` included, is ever it. */
10
+ export declare const NOW: NowOperand;
11
+ /** One test of a column: exactly one operator. */
12
+ export interface ColumnTest {
13
+ readonly eq?: ConditionLiteral;
14
+ readonly notEq?: ConditionLiteral;
15
+ readonly in?: readonly ConditionLiteral[];
16
+ readonly notIn?: readonly ConditionLiteral[];
17
+ readonly isNull?: boolean;
18
+ readonly lt?: ConditionLiteral | NowOperand;
19
+ readonly lte?: ConditionLiteral | NowOperand;
20
+ readonly gt?: ConditionLiteral | NowOperand;
21
+ readonly gte?: ConditionLiteral | NowOperand;
22
+ }
23
+ /** `{ some: { table: … } }` or `{ none: { table: … } }` at the end of a path: over the rows naming the row it reaches. */
24
+ export type RowsTest = {
25
+ readonly some: {
26
+ readonly [table: string]: ConditionPolicy;
27
+ };
28
+ } | {
29
+ readonly none: {
30
+ readonly [table: string]: ConditionPolicy;
31
+ };
32
+ };
33
+ /**
34
+ * A condition as a policy writes it: `{ column: test, … }` (all of them), `{ 'fk_column.column': test }` along a
35
+ * foreign key, `{ anyOf: […] }`, `{ allOf: […] }`, `{ not: … }`, or `{ some: { table: … } }` and `{ none: { table: … } }`
36
+ * over the rows of `table` whose foreign key names the row; `{ 'fk_column': { some: { table: … } } }` over the rows
37
+ * naming the row a path reaches.
38
+ */
39
+ export type ConditionPolicy<Col extends string = string> = {
40
+ readonly anyOf: readonly ConditionPolicy<Col>[];
41
+ } | {
42
+ readonly allOf: readonly ConditionPolicy<Col>[];
43
+ } | {
44
+ readonly not: ConditionPolicy<Col>;
45
+ } | {
46
+ readonly some: {
47
+ readonly [table: string]: ConditionPolicy;
48
+ };
49
+ } | {
50
+ readonly none: {
51
+ readonly [table: string]: ConditionPolicy;
52
+ };
53
+ } | {
54
+ readonly [C in Col | `${Col}.${string}`]?: ColumnTest | RowsTest;
55
+ };
56
+ export type ConditionOperator = 'eq' | 'notEq' | 'in' | 'notIn' | 'isNull' | 'lt' | 'lte' | 'gt' | 'gte';
57
+ /** One foreign-key hop of a path: `column` of the table it leaves references `key` of `table`. */
58
+ export interface ConditionHop {
59
+ readonly column: string;
60
+ readonly table: string;
61
+ readonly key: string;
62
+ }
63
+ export type ConditionModel = {
64
+ readonly kind: 'all';
65
+ readonly terms: readonly ConditionModel[];
66
+ } | {
67
+ readonly kind: 'any';
68
+ readonly terms: readonly ConditionModel[];
69
+ } | {
70
+ readonly kind: 'not';
71
+ readonly term: ConditionModel;
72
+ } | {
73
+ /**
74
+ * `key in (select table.column from table where <term>)`, or its negation for `none`, over the row `hops` reach
75
+ * from the condition's own row (none: the row itself).
76
+ */
77
+ readonly kind: 'some';
78
+ readonly hops: readonly ConditionHop[];
79
+ readonly negated: boolean;
80
+ readonly key: string;
81
+ readonly table: string;
82
+ readonly column: string;
83
+ readonly term: ConditionModel;
84
+ } | {
85
+ readonly kind: 'test';
86
+ readonly hops: readonly ConditionHop[];
87
+ readonly column: string;
88
+ readonly operator: ConditionOperator;
89
+ readonly value: ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand;
90
+ };
91
+ /** What the parse reads of each table: its columns, its foreign keys and its typed columns. */
92
+ export interface ConditionTable {
93
+ readonly name: string;
94
+ readonly columns: NameSet;
95
+ readonly foreignKeys: readonly {
96
+ readonly columns: readonly string[];
97
+ readonly table: string;
98
+ readonly references: readonly string[];
99
+ }[];
100
+ readonly timestamps: NameSet;
101
+ readonly json: NameSet;
102
+ /** The columns the column list declares NOT NULL: a path under `not` follows only these. */
103
+ readonly notNull: NameSet;
104
+ }
105
+ /** A path follows at most this many foreign keys: each hop is one more subquery in every statement the condition scopes. */
106
+ export declare const MAX_CONDITION_HOPS = 3;
107
+ /**
108
+ * Whether a path may follow `from.column` to the row of `to` whose `key` it holds. A hop reads its target unscoped, so
109
+ * the rule admits only one that stays where the row is (its own container or parent), stays in its tenant (a foreign
110
+ * key that also holds every ancestor the two tables share), or reaches what every site reads (a reference table).
111
+ * `backward` is a `some` reading the rows of `from` that name a row of `to`: those must stay in that row's tenant, so
112
+ * a reference row, which every tenant's rows name, is no shortcut there.
113
+ */
114
+ export type HopRule = (from: string, column: string, to: string, key: string, backward: boolean) => boolean;
115
+ /** Parses `input` as a condition over `table`. `hops` is the rule a path's foreign keys are held to. */
116
+ export declare function parseCondition(input: unknown, table: ConditionTable, tables: (name: string) => ConditionTable | undefined, what: string, hops: HopRule): ConditionModel;
117
+ export declare function splitPath(path: string): readonly string[];
118
+ export declare function singleForeignKey(table: ConditionTable, name: string, what: string): ConditionHop;
119
+ /** The tables a condition's subqueries read, each with the column it selects: what the guard admits under it. */
120
+ export declare function conditionReach(condition: ConditionModel, select: (table: string, column: string) => void): void;
121
+ /** A test's single literal; a list is compared only with in or notIn. */
122
+ export declare function scalar(value: ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand): ConditionLiteral;
123
+ /**
124
+ * One step of the rows an insert's condition reads: from the rows reached so far, the rows of `table` whose `to` column
125
+ * holds their `from` column. A path's hop goes to the row a foreign key names (`from` the key column, `to` the target's
126
+ * key); a `some` goes back to the rows naming it (`from` the referenced key, `to` the naming column).
127
+ */
128
+ export interface ReadStep {
129
+ readonly from: string;
130
+ readonly table: string;
131
+ readonly to: string;
132
+ }
133
+ /**
134
+ * Every sequence of steps from an insert's own row to the rows its condition reads, each one no other extends: the rows
135
+ * the insert locks, step by step, before it judges them. Empty when the condition reads the row alone.
136
+ */
137
+ export declare function readPaths(condition: ConditionModel): readonly (readonly ReadStep[])[];
138
+ /**
139
+ * Why `condition` cannot be judged on an inserted row, or `undefined` when it can. The insert locks every row its
140
+ * condition reads, which holds a column test and a row a `some` found until the commit, but not a row inserted meanwhile:
141
+ * that turns `none`, and a `some` under `not`, false. And no row names the inserted row before it exists.
142
+ */
143
+ export declare function insertProblem(condition: ConditionModel, table: string): string | undefined;
144
+ /**
145
+ * The value of `condition` on an insert's own row, under SQL's three-valued logic: a NULL compared is unknown, `not`
146
+ * of unknown stays unknown, and only `true` passes. A condition with a path is judged in SQL on the written row instead.
147
+ */
148
+ export declare function rowSatisfies(condition: ConditionModel, row: ReadonlyMap<string, Primitive | null>, now: Date): boolean;
149
+ export declare function hasOwnCondition(record: Readonly<Record<string, ConditionModel>>, action: string): boolean;
150
+ /** A condition as the artifact records it: the policy's own form, a path written back as `fk_column.column`. */
151
+ export declare function conditionArtifact(condition: ConditionModel): ConditionArtifact;
@@ -1,30 +1,64 @@
1
- import { type Dialect, Kysely, type RootOperationNode } from 'kysely';
1
+ import { type Dialect, Kysely, type QueryCompiler, type RootOperationNode } from 'kysely';
2
2
  import { type GuardContext } from './guard';
3
- type LooseDB = Record<string, Record<string, unknown>>;
4
- type Executor = Pick<Kysely<LooseDB>, 'executeQuery'>;
3
+ export type LooseDB = Record<string, Record<string, unknown>>;
4
+ /** What a statement runs on: the database's own executor, or the one of the transaction it runs in. */
5
+ export type Executor = Pick<Kysely<LooseDB>, 'executeQuery'>;
6
+ /** The SQL a database speaks: Postgres on Bun, SQLite in a Cloudflare Durable Object (ADR-0065). */
7
+ export type SqlDialect = 'postgres' | 'sqlite';
8
+ export interface TransactionOptions {
9
+ /**
10
+ * A `READ ONLY` transaction on Postgres. SQLite opens none: each statement runs in a transaction of its own, which
11
+ * rolls back a statement that wrote. A read-only session refuses writes either way.
12
+ */
13
+ readonly readOnly: boolean;
14
+ /** How long the transaction may sit idle before the database ends it; a database without the setting ignores it. */
15
+ readonly idleTimeoutMs?: number;
16
+ }
17
+ /**
18
+ * Runs `body` in one transaction, on the executor it hands it: commits when `body` resolves, rolls back when it
19
+ * rejects, and rejects with `body`'s error. Its BEGIN, COMMIT and ROLLBACK failures reject with the driver's error.
20
+ */
21
+ export type TransactionRunner = <T>(options: TransactionOptions, body: (executor: Executor) => Promise<T>) => Promise<T>;
22
+ /** What a `Database` runs on: the driver, the compiler of its dialect, and how it opens a transaction. */
23
+ export interface DatabaseEngine {
24
+ readonly dialect: SqlDialect;
25
+ readonly kysely: Kysely<LooseDB>;
26
+ /** Compiles every guarded tree; frozen, since a patch to it after the guard ran would bypass the guard. */
27
+ readonly compiler: QueryCompiler;
28
+ readonly transaction: TransactionRunner;
29
+ /** The application's schema, the connection's `search_path`; `undefined` where the database has none. */
30
+ readonly schema?: string;
31
+ /**
32
+ * SQLite's: runs each statement in a transaction of its own (a savepoint inside an open one) and refuses, rolling it
33
+ * back, one that wrote. A `ctx.sql` site that declares `'read'` runs on it in a writable invocation too.
34
+ */
35
+ readonly reads?: Executor;
36
+ }
37
+ /**
38
+ * The compiler turns the guarded tree into SQL, so a patch to it after the guard ran would bypass the guard.
39
+ * Freezing it when this module loads, before application modules, makes such a patch throw instead.
40
+ */
41
+ export declare function freezePrototypeChain(object: object): void;
5
42
  /**
6
43
  * `app_<id>`, the schema an application's migrations create (ADR-0017). `@fabrika/platform-node`'s
7
44
  * `applicationDatabaseSchema` derives the same name for the migration runner; the two must agree.
8
45
  */
9
46
  export declare function applicationSchema(appId: string): string;
10
- export interface PostgresOptions {
11
- readonly url: string;
12
- /** The application's schema (`app_<id>`), set as the connection's `search_path`. */
13
- readonly schema: string;
14
- readonly max?: number;
15
- }
16
47
  /** The connection the data layer runs on. It has no public query method: everything goes through a store. */
17
48
  export declare class Database {
18
49
  #private;
19
50
  private constructor();
20
51
  /**
21
- * Over `Bun.SQL` with `prepare: false`: Bun otherwise keeps one prepared statement per distinct SQL text per
22
- * connection, and `in` lists of different lengths make that grow without bound.
52
+ * Any Kysely Postgres dialect: `@fabrika/db/postgres` opens Bun.SQL through it, tests use one that records statements
53
+ * instead of sending them.
23
54
  */
24
- static postgres(options: PostgresOptions): Database;
25
- /** Any Kysely Postgres dialect; tests use one that records statements instead of sending them. */
26
- static fromDialect(dialect: Dialect): Database;
27
- /** The application's schema, the connection's `search_path`; `undefined` over a bare dialect. */
55
+ static fromDialect(dialect: Dialect, options?: {
56
+ readonly schema?: string;
57
+ }): Database;
58
+ /** A database of another dialect (`@fabrika/db/sqlite`), with its own frozen compiler and transaction runner. */
59
+ static fromEngine(engine: DatabaseEngine): Database;
60
+ get dialect(): SqlDialect;
61
+ /** The application's schema, the connection's `search_path`; `undefined` over a bare dialect and on SQLite. */
28
62
  get schema(): string | undefined;
29
63
  close(): Promise<void>;
30
64
  }
@@ -58,8 +92,10 @@ interface SessionHooks {
58
92
  */
59
93
  export declare class Session {
60
94
  #private;
61
- constructor(executor: Executor, kysely: Kysely<LooseDB> | undefined, readOnly: boolean, hooks?: SessionHooks);
95
+ constructor(executor: Executor, engine: DatabaseEngine, inTransaction: boolean, readOnly: boolean, hooks?: SessionHooks);
62
96
  get readOnly(): boolean;
97
+ /** The dialect of the database this session runs on: a framework statement picks its text by it. */
98
+ get dialect(): SqlDialect;
63
99
  /** Fails the transaction this session runs in, so it commits nothing: a statement refused before it was sent. */
64
100
  fail(): void;
65
101
  run<O>(node: RootOperationNode, context: GuardContext): Promise<O[]>;
@@ -72,6 +108,17 @@ export declare class Session {
72
108
  }
73
109
  /** How long an invocation's transaction may sit idle before Postgres ends it, and its connection with it. */
74
110
  export declare const INVOCATION_IDLE_TIMEOUT_MS = 30000;
111
+ /** A writing invocation that holds its object's storage transaction longer than this logs one line. */
112
+ export declare const TRANSACTION_HELD_LOG_MS = 1000;
113
+ /** A writing invocation that holds its object's storage transaction longer than this is also reported. */
114
+ export declare const TRANSACTION_HELD_REPORT_MS = 5000;
115
+ /** Where an enclosure tells how long it held its object: every other event of the object waited that long. */
116
+ export interface HoldWatch {
117
+ /** The site the invocation serves, which the log line names. */
118
+ readonly site: string;
119
+ /** Hears a hold longer than `TRANSACTION_HELD_REPORT_MS`, in whole ms. */
120
+ readonly held: (heldMs: number) => void;
121
+ }
75
122
  /**
76
123
  * The one transaction of an invocation (a request, a webhook delivery): opened by its first statement, then ended
77
124
  * once by the framework — committed after the handler returned and its output passed validation, rolled back
@@ -81,7 +128,8 @@ export declare const INVOCATION_IDLE_TIMEOUT_MS = 30000;
81
128
  */
82
129
  export declare class InvocationTransaction {
83
130
  #private;
84
- constructor(database: Database, readOnly: boolean);
131
+ /** `now` is the clock an enclosure's hold is measured by. */
132
+ constructor(database: Database, readOnly: boolean, now?: () => number);
85
133
  /** A `READ ONLY` transaction: a query's or an export's. */
86
134
  get readOnly(): boolean;
87
135
  /** Whether the transaction was opened: an invocation that reached no data commits nothing. */
@@ -92,6 +140,18 @@ export declare class InvocationTransaction {
92
140
  get ended(): boolean;
93
141
  /** Its connection is back in the pool (or it never took one). */
94
142
  get released(): boolean;
143
+ /**
144
+ * Runs `work`: the invocation from its handler to its `commit()`. On SQLite a writing invocation's transaction
145
+ * encloses `work`, opened before it: a Durable Object's transaction holds back every other event, the answers to the
146
+ * object's own I/O included, until its callback ends, so the handler runs inside it. There `commit()` and `rollback()`
147
+ * decide, the COMMIT runs once `work` returned, and a failed COMMIT rejects with a `DatabaseError`. A read-only
148
+ * invocation, and every invocation elsewhere, runs `work` as is: a read-only one on SQLite holds no storage
149
+ * transaction, so the object serves other events while it awaits.
150
+ *
151
+ * Only the SQLite enclosure is measured for `watch`, from entering the transaction until it settled: it holds the
152
+ * whole object, where a Postgres transaction holds one pooled connection and other requests go on.
153
+ */
154
+ enclose<T>(work: () => Promise<T>, watch: HoldWatch): Promise<T>;
95
155
  /** The session the invocation's statements run in; the first call opens the transaction. */
96
156
  session(): Promise<Session>;
97
157
  /**
@@ -100,7 +160,7 @@ export declare class InvocationTransaction {
100
160
  * `DatabaseError`, after the connection is back in the pool.
101
161
  */
102
162
  commit(): Promise<void>;
103
- /** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back. */
163
+ /** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back (inside `enclose`, it only decides). */
104
164
  rollback(): Promise<void>;
105
165
  }
106
166
  /**
@@ -118,7 +178,8 @@ export declare function runFixedStatement(session: Session, text: string, parame
118
178
  export type SqlParameter = string | number | boolean | bigint | null;
119
179
  /**
120
180
  * One `ctx.sql` statement, whose text `sql.ts` classified and whose values are bound parameters only. It runs through the
121
- * session's one path to the connection, so a statement the database refuses fails the invocation it runs in.
181
+ * session's one path to the connection, so a statement the database refuses fails the invocation it runs in. A `'read'`
182
+ * statement runs on the engine's `reads` where it has one (SQLite), so one that wrote is refused and rolled back.
122
183
  */
123
- export declare function runApplicationStatement(session: Session, text: string, parameters: readonly SqlParameter[]): Promise<readonly unknown[]>;
184
+ export declare function runApplicationStatement(session: Session, text: string, parameters: readonly SqlParameter[], mode: 'read' | 'write'): Promise<readonly unknown[]>;
124
185
  export {};
@@ -1,3 +1,4 @@
1
+ import type { OperationNode } from 'kysely';
1
2
  import { type NameSet } from './builtins';
2
3
  export type Primitive = string | number | bigint | boolean | Date;
3
4
  export type ComparisonOperator = '=' | '<>' | '<' | '<=' | '>' | '>=';
@@ -29,6 +30,8 @@ export interface TableShape {
29
30
  readonly joinable: Readonly<Record<string, JoinShape>>;
30
31
  /** The `date` columns, which a read answers as `YYYY-MM-DD` text. */
31
32
  readonly dates: NameSet;
33
+ /** The JSON columns, which a query selects but never compares or orders by. */
34
+ readonly json: NameSet;
32
35
  }
33
36
  export interface JoinShape {
34
37
  readonly shape: TableShape;
@@ -43,6 +46,8 @@ export interface JoinShape {
43
46
  export interface JoinState {
44
47
  readonly join: JoinShape;
45
48
  readonly select: SelectState;
49
+ /** The child's condition for the action the select holds, which the layer adds to the ON; never the builder's. */
50
+ readonly condition?: OperationNode;
46
51
  }
47
52
  export interface SelectState {
48
53
  /** Identifies the description a callback received, so it cannot return one from elsewhere. */
@@ -60,17 +65,28 @@ export interface SelectState {
60
65
  }
61
66
  type Comparable<V> = Exclude<V, null | undefined>;
62
67
  type Columns<Row> = keyof Row & string;
68
+ /** The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`. */
69
+ export type ComparableColumn<Row> = {
70
+ [K in Columns<Row>]: unknown extends Row[K] ? never : K;
71
+ }[Columns<Row>];
63
72
  type StringColumn<Row> = {
64
73
  [K in Columns<Row>]: Comparable<Row[K]> extends string ? K : never;
65
74
  }[Columns<Row>];
66
75
  type NullableColumn<Row> = {
67
- [K in Columns<Row>]: null extends Row[K] ? K : never;
68
- }[Columns<Row>];
76
+ [K in ComparableColumn<Row>]: null extends Row[K] ? K : never;
77
+ }[ComparableColumn<Row>];
78
+ /**
79
+ * A `[column, operator, value]` condition on `Row`'s columns. A null test (`is`, `is not`) takes a nullable column only;
80
+ * the runtime knows no column's nullability, so an untyped condition that tests a column never null runs and matches no
81
+ * row (`is`) or every row (`is not`).
82
+ */
69
83
  export type ConditionTuple<Row> = {
70
- [K in Columns<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]];
71
- }[Columns<Row>] | {
84
+ [K in ComparableColumn<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]];
85
+ }[ComparableColumn<Row>] | {
72
86
  [K in StringColumn<Row>]: readonly [K, PatternOperator | 'contains', string];
73
- }[StringColumn<Row>];
87
+ }[StringColumn<Row>] | {
88
+ [K in NullableColumn<Row>]: readonly [K, NullOperator, null];
89
+ }[NullableColumn<Row>];
74
90
  type Prefixed<C extends string, J> = {
75
91
  [K in keyof J & string as `${C}.${K}`]: J[K];
76
92
  };
@@ -84,15 +100,15 @@ export declare class ScopedSelect<Row, Selected, Children> {
84
100
  constructor(token: symbol, state: SelectState, shape: TableShape);
85
101
  /** The columns to return; without it, every visible column. */
86
102
  columns<const C extends Columns<Row>>(columns: readonly C[]): ScopedSelect<Row, Pick<Row, C>, Children>;
87
- where<C extends Columns<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>;
88
- where<C extends Columns<Row>>(column: C, operator: ListOperator, values: readonly Comparable<Row[C]>[]): ScopedSelect<Row, Selected, Children>;
103
+ where<C extends ComparableColumn<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>;
104
+ where<C extends ComparableColumn<Row>>(column: C, operator: ListOperator, values: readonly Comparable<Row[C]>[]): ScopedSelect<Row, Selected, Children>;
89
105
  where<C extends StringColumn<Row>>(column: C, operator: PatternOperator, pattern: string): ScopedSelect<Row, Selected, Children>;
90
106
  where<C extends NullableColumn<Row>>(column: C, operator: NullOperator, value: null): ScopedSelect<Row, Selected, Children>;
91
107
  /** One OR group of conditions on this table's columns. */
92
108
  whereAny(conditions: readonly ConditionTuple<Row>[]): ScopedSelect<Row, Selected, Children>;
93
109
  /** A case-insensitive substring match in which `%` and `_` in the text match themselves. */
94
110
  contains(column: StringColumn<Row>, text: string): ScopedSelect<Row, Selected, Children>;
95
- orderBy(column: Columns<Row>, direction?: 'asc' | 'desc'): ScopedSelect<Row, Selected, Children>;
111
+ orderBy(column: ComparableColumn<Row>, direction?: 'asc' | 'desc'): ScopedSelect<Row, Selected, Children>;
96
112
  limit(limit: number): ScopedSelect<Row, Selected, Children>;
97
113
  offset(offset: number): ScopedSelect<Row, Selected, Children>;
98
114
  /** An inner join to a declared child; its columns come back prefixed (`note_comments.body`). */
@@ -100,6 +116,8 @@ export declare class ScopedSelect<Row, Selected, Children> {
100
116
  }
101
117
  /** A column the shape lets a query name; a hidden one is refused like a missing one. */
102
118
  export declare function columnOf(shape: TableShape, name: unknown): string;
119
+ /** A column the shape lets a query compare, order or aggregate by: `columnOf`, and never a JSON column. */
120
+ export declare function comparableColumnOf(shape: TableShape, name: unknown, use: string): string;
103
121
  /** One `[column, operator, value]` condition over a caller's values, checked before anything reads it further. */
104
122
  export declare function parseCondition(shape: TableShape, column: unknown, operator: unknown, value: unknown): Compare | Contains;
105
123
  export declare function startSelect<Row, Children>(shape: TableShape): ScopedSelect<Row, Row, Children>;
@@ -22,11 +22,12 @@ export declare class CapabilityError extends Error {
22
22
  }
23
23
  /**
24
24
  * Why the layer refused, as a closed catalog: a server log names the reason and its fixed text, never the message,
25
- * which can quote a value the request sent.
25
+ * which can quote a value the request sent. Each text is one string literal, however long: a concatenation keeps the
26
+ * whole catalog in an SPA bundle that imports this module (`web/__tests__/bundle.test.ts`).
26
27
  */
27
28
  export declare const QUERY_REFUSALS: {
28
29
  readonly invalid_argument: "a data-layer call took an argument of another shape than its type declares";
29
- readonly invalid_value: "a value cannot be bound: an invalid or out-of-range date, or a non-finite number";
30
+ readonly invalid_value: "a value cannot be bound: undefined, a function, symbol or object of a kind the database does not bind, a list item other than a string or finite number, a date or timestamp that is neither a valid Date nor well-formed text or lies out of range, a non-finite number, or on SQLite a bigint outside the safe integer range";
30
31
  readonly invalid_name: "a configured name (application, schema, table or file column) breaks its naming rule";
31
32
  readonly unknown_column: "a column the table does not declare, or one this operation may not set";
32
33
  readonly unknown_table: "a table src/db/tables.ts does not declare, or one no store, join or locator reaches";
@@ -44,10 +45,10 @@ export declare const QUERY_REFUSALS: {
44
45
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
45
46
  readonly sql_statement: "ctx.sql runs one statement of an admitted kind, and none inside another";
46
47
  readonly sql_read_only: "sql: 'read' runs queries only; declare sql: 'write' on a mutation, a job or a webhook";
47
- readonly sql_name: "ctx.sql names a framework, catalog or foreign-schema object, or writes a name in U& form";
48
+ readonly sql_name: "ctx.sql names a framework (fabrika_*), catalog (pg_*, sqlite_*) or foreign-schema object, or writes a name in U& form";
48
49
  readonly sql_function: "ctx.sql calls a function that is not a reviewed built-in";
49
50
  readonly sql_outside_transaction: "a job runs ctx.sql only inside ctx.transaction((tx) => …), as tx.sql";
50
- readonly sql_scope: "ctx.sql.scope(…) stands alone, joined by AND, in a WHERE or JOIN … ON clause of its own invocation";
51
+ readonly sql_scope: "ctx.sql.scope(…) is interpolated at code level in a statement of its own invocation and site";
51
52
  readonly file_scan: "a scan verdict outside the scan job's lease";
52
53
  readonly claim_site: "claim leases rows in a transaction of its own: a job calls it on ctx.db, never inside ctx.transaction or a request";
53
54
  readonly on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action";
@@ -1,6 +1,7 @@
1
+ import { type NameSet } from './builtins';
1
2
  import { type Session } from './database';
2
3
  import type { Primitive } from './description';
3
- import type { TableModel } from './policy';
4
+ import { type ReadReach, type TableModel } from './policy';
4
5
  /** Where a site's file references belong, and what claiming a pending one needs. */
5
6
  export interface FileBinding {
6
7
  /** The work a reference of this site belongs to: one request, or one job attempt. */
@@ -13,10 +14,11 @@ export interface FileBinding {
13
14
  scans(kind: string): boolean;
14
15
  }
15
16
  /**
16
- * Puts a file reference in each file column of `rows`, read with `action` in `session`: one statement loads every
17
- * file's metadata. Without a binding (a store's own runner) the columns keep their ids.
17
+ * Puts a file reference in each file column of `rows`, read under `reach` in `session`: one statement loads every
18
+ * file's metadata. Without a binding (a store's own runner) the columns keep their ids. `held` (a queue claim's) adds
19
+ * the actions the site holds over the whole application: a reference is readable when one of them reads the table.
18
20
  */
19
- export declare function answerFiles<R>(model: TableModel, binding: FileBinding | undefined, session: Session, rows: R[], action: string): Promise<R[]>;
21
+ export declare function answerFiles<R>(model: TableModel, binding: FileBinding | undefined, session: Session, rows: R[], reach: ReadReach, held?: NameSet): Promise<R[]>;
20
22
  /**
21
23
  * A write's value for a file column: `null`, or the id of a file reference of the column's kind. A string id, a copied
22
24
  * object or a reference of another kind is refused; whether the site holds it is checked where the write runs.
@@ -1,5 +1,5 @@
1
1
  import type { DataAccess } from './orm';
2
- import { type FrameworkTables, type Locator } from './registry';
2
+ import { type FrameworkTables, type Locator, type ProvisionalBinding } from './registry';
3
3
  import type { DataLayerRuntime } from './store';
4
4
  export type { Admissions } from './admissions';
5
5
  export type { LeaseFence } from './capability';
@@ -8,9 +8,10 @@ export { CAPABILITY_ERRORS, CapabilityError, type CapabilityErrorReason, LeaseLo
8
8
  export type { FileBinding } from './file-columns';
9
9
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references';
10
10
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables';
11
- export type { JobLeases, JobLeaseState, JobOutcome, OverdueClaim } from './job-leases';
11
+ export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
12
+ export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
12
13
  export type { DataAccess, DataHandles, DataSite } from './orm';
13
- export type { FrameworkTables, Locator } from './registry';
14
+ export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry';
14
15
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
15
16
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files';
16
17
  /** Whether `value` is an object `scoped(tables)` created, rather than a look-alike with the same fields. */
@@ -21,8 +22,13 @@ export declare function isScopedDatabase(value: unknown): boolean;
21
22
  */
22
23
  export declare function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): Locator;
23
24
  /**
24
- * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and the
25
- * admission counters. Each operation needs the layer bound first. Throws for any other value.
25
+ * Connects the layer like `bindScopedDatabase`, and answers with its locator the `release` that disconnects it again:
26
+ * a boot that fails releases the layer, so a later boot of the same application binds it. Throws as that does.
27
+ */
28
+ export declare function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLayerRuntime): ProvisionalBinding;
29
+ /**
30
+ * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and wakes, and
31
+ * the admission counters. Each operation needs the layer bound first. Throws for any other value.
26
32
  */
27
33
  export declare function frameworkTablesOf(value: unknown): FrameworkTables;
28
34
  /**
@@ -18,6 +18,30 @@ export interface GuardContext {
18
18
  readonly lock?: 'share' | 'update' | 'claim';
19
19
  /** An insert that does nothing on a conflict of its listed columns: `on conflict (columns) do nothing`, and no other. */
20
20
  readonly onConflict?: 'nothing';
21
+ /**
22
+ * The tables a scope predicate's subqueries may read, each with the columns one may select: a relation's source by
23
+ * its node column, a condition path's target by its key. Without it, a scope holds no subquery.
24
+ */
25
+ readonly subqueries?: Readonly<Record<string, readonly string[]>>;
26
+ /**
27
+ * A child view's parent: its scope may read the view's rows through `<column> in (select P.<key> from P where <P's
28
+ * reach>)`. Without it, a scope holds no such subquery.
29
+ */
30
+ readonly through?: ViewParentLink | undefined;
31
+ }
32
+ /** The parent a child view's scope reads its rows through: the view's parent column, the parent table and its key. */
33
+ export interface ViewParentLink {
34
+ readonly column: string;
35
+ readonly table: string;
36
+ readonly key: string;
37
+ /** The view's own access views, which list its rows beside the parent's reach (ADR-0076). */
38
+ readonly access?: readonly ViewAccessLink[];
39
+ }
40
+ /** An access view of a child view: `V.<key> in (select A.<row> from A where <bindings>)`. */
41
+ export interface ViewAccessLink {
42
+ readonly key: string;
43
+ readonly view: string;
44
+ readonly row: string;
21
45
  }
22
46
  /** Refuses any operation tree outside the allowlist. Runs on the final tree, immediately before it is compiled. */
23
47
  export declare function assertAllowedTree(root: OperationNode, context: GuardContext): void;
@@ -1,10 +1,11 @@
1
- export type { AppCapability, AppGrant, CapabilityAuthority, CapabilityGrant, ContainerGrant, LeaseFence, Ref, RefGrant, RowGrant, RowRef, Within, WithinGrant, } from './capability';
1
+ export type { AppCapability, AppGrant, CapabilityAuthority, CapabilityGrant, ContainerGrant, LeaseFence, Ref, RefGrant, RelationHold, RowGrant, RowRef, Within, WithinGrant, } from './capability';
2
2
  export { MAX_WITHIN_VALUES } from './capability';
3
- export { applicationSchema, Database, type PostgresOptions } from './database';
3
+ export { applicationSchema, Database, type DatabaseEngine, type Executor, type SqlDialect, type TransactionOptions, type TransactionRunner, } from './database';
4
4
  export type { AllowedOperator, ComparisonOperator, ConditionTuple, ListOperator, NoColumns, NullOperator, PatternOperator, Primitive, ScopedSelect, } from './description';
5
5
  export { CAPABILITY_ERRORS, CapabilityError, type CapabilityErrorReason, DatabaseError, LeaseLostError, PolicyError, QUERY_REFUSALS, type QueryRefusal, QueryRefusedError, } from './errors';
6
+ export type { JsonColumnValue, JsonValue } from './json';
6
7
  export type { AnyDbIndex, ChildRows, ContainedRows, CountOptions, DataKind, DbIndex, IndexedTable, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, Saved, ScopeTarget, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
7
8
  export { type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type InsertValues, isTables, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type RowOf, type TableActions, type TableInsert, Tables, type TableUpdate, type UpdateValues, type VersionColumn, type VocabularyTables, } from './policy';
8
9
  export { type AggregateRow, type AggregateSpec, type ChildListScope, type DataLayer, type DataLayerRuntime, scoped, type ScopedDatabase, } from './store';
9
10
  export { type TablePolicies, tablePolicies } from './tables';
10
- export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
11
+ export type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, VocabularyViewPolicy, } from './vocabulary-tables';
@@ -1,5 +1,6 @@
1
1
  import type { LeaseFence } from './capability';
2
- import { type Session } from './database';
2
+ import { type Session, type SqlDialect } from './database';
3
+ import { type FinishWakes } from './job-wakes';
3
4
  import type { DataLayerRuntime } from './store';
4
5
  export type JobOutcome = 'succeeded' | 'failed';
5
6
  export interface JobLeaseState {
@@ -48,8 +49,11 @@ export interface JobLeases {
48
49
  * now on. `null` when `fence` no longer holds it.
49
50
  */
50
51
  renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null>;
51
- /** Frees the lease and records the run's outcome and duration; `false` when `fence` no longer held it. */
52
- finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean>;
52
+ /**
53
+ * Frees the lease and records the run's outcome and duration, and in the same transaction applies `wakes` to the wakes
54
+ * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
55
+ */
56
+ finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>;
53
57
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
54
58
  markPending(job: string): Promise<void>;
55
59
  /**
@@ -69,9 +73,33 @@ export interface JobLeases {
69
73
  cancelInFlight(fence: LeaseFence): Promise<void>;
70
74
  state(job: string): Promise<JobLeaseState | null>;
71
75
  }
76
+ /**
77
+ * What a lease statement changed: a crashed holder reaped, a lease taken or handed on, or a run finished with what its
78
+ * wakes become (`null` leaves them).
79
+ */
80
+ export type LeaseChange = {
81
+ readonly kind: 'reaped' | 'acquired' | 'renewed';
82
+ } | {
83
+ readonly kind: 'finished';
84
+ readonly wakes: FinishWakes | null;
85
+ };
86
+ /**
87
+ * Runs in the transaction of every lease statement that changed the lease, so a table that follows the lease (the
88
+ * wakes, `job-wakes.ts`) commits with it or not at all. A statement that changed nothing, a lost lease's, runs none.
89
+ */
90
+ export type LeaseProjection = (transaction: Session, job: string, change: LeaseChange) => Promise<void>;
91
+ /** One framework statement in each dialect's text; a session runs the text of its own. */
92
+ export type DialectTexts = Readonly<Record<SqlDialect, string>>;
93
+ /** SQLite's clock, as a stored timestamp: ISO text, so a comparison of two is a text comparison. */
94
+ export declare const SQLITE_NOW = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
95
+ /** SQLite's clock moved by `ms`, an SQL expression of milliseconds (negative is earlier). */
96
+ export declare function sqliteNowPlus(ms: string): string;
97
+ /** A stored SQLite timestamp (`SQLITE_NOW_FORMAT`) as a `Date`, or `null`; anything else is refused. */
98
+ export declare function sqliteTimestamp(value: unknown, what: string): Date | null;
72
99
  /**
73
100
  * The database's clock inside `session`'s transaction: a queue claim compares and moves `due` by it, so no process
74
- * clock decides when a row is due.
101
+ * clock decides when a row is due. On Postgres it is rounded up to the millisecond a `Date` holds, so it is never
102
+ * earlier than a `due` that `now()` wrote with microseconds.
75
103
  */
76
104
  export declare function databaseNow(session: Session): Promise<Date>;
77
105
  /**
@@ -79,6 +107,7 @@ export declare function databaseNow(session: Session): Promise<Date>;
79
107
  * stays locked `for share` until the commit (a takeover or a renewal waits), and every statement is bounded by the
80
108
  * attempt's remaining time. After it, just before the commit: the attempt still holds the lease within its deadline.
81
109
  * Otherwise the transaction rolls back with `LeaseLostError`; so does a statement the deadline or the runner cancelled.
110
+ * On SQLite only the two checks run: no other event reaches the Durable Object while the transaction is open.
82
111
  */
83
112
  export declare function fencedTransaction<T>(session: Session, fence: LeaseFence, work: (transaction: Session) => Promise<T>): Promise<T>;
84
- export declare function jobLeases(runtime: () => DataLayerRuntime): JobLeases;
113
+ export declare function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProjection): JobLeases;