@fabrika/db 0.9.0-dev.3 → 0.9.0-dev.30

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 (82) hide show
  1. package/package.json +39 -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 +230 -41
  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 +8 -5
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -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 +181 -0
  24. package/src/migrations.ts +43 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +198 -67
  27. package/src/orm.ts +383 -133
  28. package/src/policy.ts +1933 -122
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +55 -3
  31. package/src/request-receipts.ts +107 -0
  32. package/src/sql.ts +247 -476
  33. package/src/sqlite-bun.ts +149 -0
  34. package/src/sqlite-migrate.ts +242 -0
  35. package/src/sqlite.ts +269 -0
  36. package/src/store.ts +2292 -239
  37. package/src/stored-files.ts +188 -52
  38. package/src/tables.ts +171 -5
  39. package/src/temporal.ts +122 -9
  40. package/src/testing-shared.ts +1348 -0
  41. package/src/testing-sqlite.ts +685 -0
  42. package/src/testing.ts +310 -494
  43. package/src/vocabulary-tables.ts +159 -27
  44. package/types/src/application-rows.d.ts +58 -0
  45. package/types/src/authority.d.ts +147 -0
  46. package/types/src/builtins.d.ts +2 -0
  47. package/types/src/capability.d.ts +55 -2
  48. package/types/src/codegen-sqlite.d.ts +13 -0
  49. package/types/src/codegen.d.ts +79 -5
  50. package/types/src/condition-nodes.d.ts +9 -0
  51. package/types/src/conditions.d.ts +151 -0
  52. package/types/src/database.d.ts +81 -20
  53. package/types/src/description.d.ts +26 -8
  54. package/types/src/errors.d.ts +7 -5
  55. package/types/src/file-columns.d.ts +6 -4
  56. package/types/src/framework.d.ts +12 -5
  57. package/types/src/guard.d.ts +24 -0
  58. package/types/src/index.d.ts +5 -4
  59. package/types/src/job-leases.d.ts +34 -5
  60. package/types/src/job-wakes.d.ts +101 -0
  61. package/types/src/json.d.ts +18 -0
  62. package/types/src/migrations-sqlite.d.ts +4 -0
  63. package/types/src/migrations.d.ts +2 -0
  64. package/types/src/nodes.d.ts +17 -2
  65. package/types/src/orm-types.d.ts +155 -63
  66. package/types/src/orm.d.ts +21 -0
  67. package/types/src/policy.d.ts +344 -16
  68. package/types/src/postgres.d.ts +12 -0
  69. package/types/src/registry.d.ts +40 -3
  70. package/types/src/request-receipts.d.ts +22 -0
  71. package/types/src/sql.d.ts +29 -21
  72. package/types/src/sqlite-bun.d.ts +21 -0
  73. package/types/src/sqlite-migrate.d.ts +28 -0
  74. package/types/src/sqlite.d.ts +24 -0
  75. package/types/src/store.d.ts +143 -34
  76. package/types/src/stored-files.d.ts +6 -2
  77. package/types/src/tables.d.ts +18 -2
  78. package/types/src/temporal.d.ts +24 -0
  79. package/types/src/testing-shared.d.ts +290 -0
  80. package/types/src/testing-sqlite.d.ts +37 -0
  81. package/types/src/testing.d.ts +2 -93
  82. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -2,11 +2,19 @@ import { type DatabaseObject } from '@fabrika/platform-node';
2
2
  import { z } from 'zod/v4';
3
3
  /** Where an application keeps the generated types and column list; committed, never hand-edited. */
4
4
  export declare const SCHEMA_FILE = "src/db/schema.generated.ts";
5
+ /** A column's TypeScript types: what a read returns, and what an insert or update may bind when that differs. */
6
+ export interface ScalarType {
7
+ readonly select: string;
8
+ readonly write?: string;
9
+ }
10
+ /** A JSON column: a read answers the parsed value, which the handler parses with a schema; a write binds a JSON value. */
11
+ export declare const JSON_COLUMN: ScalarType;
5
12
  export declare class CodegenError extends Error {
6
13
  name: string;
7
14
  }
8
15
  declare const catalogColumnSchema: z.ZodObject<{
9
16
  table_name: z.ZodString;
17
+ view: z.ZodBoolean;
10
18
  column_name: z.ZodString;
11
19
  type_name: z.ZodString;
12
20
  type_type: z.ZodString;
@@ -17,6 +25,9 @@ declare const catalogColumnSchema: z.ZodObject<{
17
25
  no: "no";
18
26
  always: "always";
19
27
  }>;
28
+ computed: z.ZodBoolean;
29
+ formatted_type: z.ZodString;
30
+ keyed: z.ZodBoolean;
20
31
  enum_labels: z.ZodArray<z.ZodString>;
21
32
  }, z.core.$strip>;
22
33
  export type CatalogColumn = z.infer<typeof catalogColumnSchema>;
@@ -41,12 +52,75 @@ export interface Catalog {
41
52
  export declare function introspectSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<readonly CatalogColumn[]>;
42
53
  /** `introspectSchema`, with the foreign keys between the schema's tables. */
43
54
  export declare function introspectCatalog(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<Catalog>;
55
+ /** `table.column`: how a message names a column. */
56
+ export declare function columnPath(column: NamedColumn): string;
57
+ /** What the renderer needs of a column beyond its name, whichever database it was read from. */
58
+ export interface DescribedColumn {
59
+ readonly scalar: ScalarType;
60
+ readonly nullable: boolean;
61
+ readonly generated: 'no' | 'default' | 'always';
62
+ /** The column list field that names the column: a day, a timestamp, a JSON column, or (on SQLite) a boolean. */
63
+ readonly list: 'dates' | 'timestamps' | 'booleans' | 'json' | undefined;
64
+ }
65
+ /**
66
+ * A column `describe` leaves out of the module: a generated column, or a view's column, of a type the data layer does
67
+ * not read.
68
+ */
69
+ export interface LeftOut {
70
+ /** The column's type, as its author wrote it (empty: a SQLite view's expression, which has none). */
71
+ readonly leftOut: string;
72
+ readonly of: LeftOutKind;
73
+ }
74
+ /** Why a column is left out rather than refused: it is computed, by a generated column or by a view. */
75
+ export type LeftOutKind = 'generated' | 'view';
76
+ /** A column the module leaves out; only `ctx.sql` reaches it. */
77
+ export interface LeftOutColumn {
78
+ readonly table: string;
79
+ readonly column: string;
80
+ /** Its type, as its author wrote it. */
81
+ readonly type: string;
82
+ readonly of: LeftOutKind;
83
+ }
84
+ /** What codegen says of a left-out column: in the module, `name` is the column; in its output, `table.column`. */
85
+ export declare function leftOutText(name: string, type: string, of: LeftOutKind): string;
86
+ /** Why a left-out column refuses the schema: the table would lose a key, or a foreign key a column. */
87
+ export declare function leftOutRefusal(path: string, what: string): CodegenError;
88
+ /** The text of `SCHEMA_FILE`, and the columns it leaves out, for the command to name. */
89
+ export interface GeneratedModule {
90
+ readonly source: string;
91
+ readonly leftOut: readonly LeftOutColumn[];
92
+ }
93
+ /** A foreign key as the renderer reads it: the columns of `table_name` that reference `referenced_table`. */
94
+ export interface ForeignKeyColumns {
95
+ readonly table_name: string;
96
+ readonly columns: readonly string[];
97
+ readonly referenced_table: string;
98
+ readonly referenced_columns: readonly string[];
99
+ }
100
+ /** A column as the renderer groups it, before its type is described. */
101
+ export interface NamedColumn {
102
+ readonly table_name: string;
103
+ readonly column_name: string;
104
+ }
105
+ /** A column of a table or of a view, as `renderTables` reads it. */
106
+ export interface RelationColumn extends NamedColumn {
107
+ /** The relation is a view: read-only, with no key or foreign key. */
108
+ readonly view: boolean;
109
+ }
110
+ /**
111
+ * The generated module: one interface per application table and view, the `DB` map Kysely and `defineTables` take,
112
+ * and the runtime column list with each table's foreign keys to application tables and each view marked; with the
113
+ * columns it leaves out. Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
114
+ */
115
+ export declare function renderSchema(catalog: readonly CatalogColumn[], foreignKeys?: readonly CatalogForeignKey[]): GeneratedModule;
44
116
  /**
45
- * The generated module: one interface per application table, the `DB` map Kysely and `defineTables` take, and the
46
- * runtime column list with each table's foreign keys to application tables. Deterministic for a given catalog, so
47
- * `fabrika db codegen --verify` can compare text.
117
+ * `renderSchema` over columns of any database: `describe` gives each column's types and list field, refuses a type the
118
+ * data layer does not read, or answers `LeftOut` for a generated column or a view's column of such a type. That column
119
+ * is left out of the module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
120
+ * reaches it; a foreign key that names it, and a table it would leave without a column, are refused, and a view left
121
+ * without a column is left out whole. A foreign key's `constraint_name` is not rendered; keys keep the given order.
48
122
  */
49
- export declare function renderSchema(catalog: readonly CatalogColumn[], foreignKeys?: readonly CatalogForeignKey[]): string;
123
+ export declare function renderTables<C extends RelationColumn>(catalog: readonly C[], foreignKeys: readonly ForeignKeyColumns[], describe: (column: C) => DescribedColumn | LeftOut): GeneratedModule;
50
124
  /** Introspects the migrated schema, checked against the migrations' manifest, and renders the module for `SCHEMA_FILE`. */
51
- export declare function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<string>;
125
+ export declare function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<GeneratedModule>;
52
126
  export {};
@@ -0,0 +1,9 @@
1
+ import { type OperationNode } from 'kysely';
2
+ import { type ConditionModel } from './conditions';
3
+ /** The predicate of `condition` over `table`'s rows; `now` is the statement's clock, bound as a value. */
4
+ export declare function conditionNode(table: string, condition: ConditionModel, now: Date): OperationNode;
5
+ /**
6
+ * `select table.key from table where <where>`: the one subquery shape the guard admits in a scope predicate. Without
7
+ * `where`, every row's key: only a child view's parent subquery takes that form.
8
+ */
9
+ export declare function subquery(table: string, key: string, where?: OperationNode): OperationNode;
@@ -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";
@@ -40,18 +41,19 @@ export declare const QUERY_REFUSALS: {
40
41
  readonly statement_shape: "the compiled statement has a form the guard does not admit";
41
42
  readonly scope_predicate: "the scope predicate is missing or is not a top-level conjunct";
42
43
  readonly list_page: "a list limit, cursor or order outside what a page admits";
44
+ readonly too_many_rows: "all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate";
43
45
  readonly undeclared_reach: "the site reaches data it did not declare (sql or unscoped, or their mode)";
44
46
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
45
47
  readonly sql_statement: "ctx.sql runs one statement of an admitted kind, and none inside another";
46
48
  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";
49
+ readonly sql_name: "ctx.sql names a framework (fabrika_*), catalog (pg_*, sqlite_*) or foreign-schema object, or writes a name in U& form";
48
50
  readonly sql_function: "ctx.sql calls a function that is not a reviewed built-in";
49
51
  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";
52
+ readonly sql_scope: "ctx.sql.scope(…) is interpolated at code level in a statement of its own invocation and site";
51
53
  readonly file_scan: "a scan verdict outside the scan job's lease";
52
54
  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
55
  readonly on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action";
54
- readonly public_reach: "a public procedure updates, removes, locks or claims no row, and an insert's conflict writes nothing";
56
+ readonly public_reach: "a public procedure updates, removes, locks or claims no row, reads none with all(), and an insert's conflict writes nothing";
55
57
  readonly file_value: "a file column takes a file reference this request holds and may read (an incoming file, a put, or a read under the table's read action) of the column's kind, or null";
56
58
  readonly file_scope: "a file is referenced from another top-level scope than the one its first reference set";
57
59
  };
@@ -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,11 @@ 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';
15
+ export type { RequestReceipt, RequestReceipts } from './request-receipts';
14
16
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
15
17
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files';
16
18
  /** Whether `value` is an object `scoped(tables)` created, rather than a look-alike with the same fields. */
@@ -21,8 +23,13 @@ export declare function isScopedDatabase(value: unknown): boolean;
21
23
  */
22
24
  export declare function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): Locator;
23
25
  /**
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.
26
+ * Connects the layer like `bindScopedDatabase`, and answers with its locator the `release` that disconnects it again:
27
+ * a boot that fails releases the layer, so a later boot of the same application binds it. Throws as that does.
28
+ */
29
+ export declare function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLayerRuntime): ProvisionalBinding;
30
+ /**
31
+ * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and wakes, and
32
+ * the admission counters. Each operation needs the layer bound first. Throws for any other value.
26
33
  */
27
34
  export declare function frameworkTablesOf(value: unknown): FrameworkTables;
28
35
  /**