@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.40

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 (84) 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 +10 -6
  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 +228 -55
  20. package/src/job-wakes.ts +600 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/list-cursor.ts +82 -0
  24. package/src/migrations-sqlite.ts +210 -0
  25. package/src/migrations.ts +73 -0
  26. package/src/nodes.ts +84 -14
  27. package/src/orm-types.ts +206 -71
  28. package/src/orm.ts +425 -170
  29. package/src/policy.ts +1979 -141
  30. package/src/postgres.ts +26 -0
  31. package/src/registry.ts +55 -3
  32. package/src/request-receipts.ts +107 -0
  33. package/src/sql.ts +247 -476
  34. package/src/sqlite-bun.ts +149 -0
  35. package/src/sqlite-migrate.ts +242 -0
  36. package/src/sqlite.ts +269 -0
  37. package/src/store.ts +2292 -239
  38. package/src/stored-files.ts +188 -52
  39. package/src/tables.ts +172 -6
  40. package/src/temporal.ts +122 -9
  41. package/src/testing-shared.ts +1351 -0
  42. package/src/testing-sqlite.ts +685 -0
  43. package/src/testing.ts +310 -494
  44. package/src/vocabulary-tables.ts +159 -27
  45. package/types/src/application-rows.d.ts +58 -0
  46. package/types/src/authority.d.ts +147 -0
  47. package/types/src/builtins.d.ts +2 -0
  48. package/types/src/capability.d.ts +55 -2
  49. package/types/src/codegen-sqlite.d.ts +13 -0
  50. package/types/src/codegen.d.ts +79 -5
  51. package/types/src/condition-nodes.d.ts +9 -0
  52. package/types/src/conditions.d.ts +151 -0
  53. package/types/src/database.d.ts +81 -20
  54. package/types/src/description.d.ts +26 -8
  55. package/types/src/errors.d.ts +9 -6
  56. package/types/src/file-columns.d.ts +6 -4
  57. package/types/src/framework.d.ts +12 -5
  58. package/types/src/guard.d.ts +24 -0
  59. package/types/src/index.d.ts +5 -4
  60. package/types/src/job-leases.d.ts +40 -5
  61. package/types/src/job-wakes.d.ts +124 -0
  62. package/types/src/json.d.ts +18 -0
  63. package/types/src/list-cursor.d.ts +13 -0
  64. package/types/src/migrations-sqlite.d.ts +4 -0
  65. package/types/src/migrations.d.ts +4 -0
  66. package/types/src/nodes.d.ts +17 -2
  67. package/types/src/orm-types.d.ts +163 -71
  68. package/types/src/orm.d.ts +21 -0
  69. package/types/src/policy.d.ts +351 -23
  70. package/types/src/postgres.d.ts +12 -0
  71. package/types/src/registry.d.ts +40 -3
  72. package/types/src/request-receipts.d.ts +22 -0
  73. package/types/src/sql.d.ts +29 -21
  74. package/types/src/sqlite-bun.d.ts +21 -0
  75. package/types/src/sqlite-migrate.d.ts +28 -0
  76. package/types/src/sqlite.d.ts +24 -0
  77. package/types/src/store.d.ts +143 -34
  78. package/types/src/stored-files.d.ts +6 -2
  79. package/types/src/tables.d.ts +18 -2
  80. package/types/src/temporal.d.ts +24 -0
  81. package/types/src/testing-shared.d.ts +290 -0
  82. package/types/src/testing-sqlite.d.ts +37 -0
  83. package/types/src/testing.d.ts +2 -93
  84. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -2,8 +2,15 @@ import { z } from 'zod/v4';
2
2
  import { type Session } from './database';
3
3
  /** What a site declares: `'read'` runs queries only, `'write'` also `INSERT`, `UPDATE` and `DELETE`. */
4
4
  export type SqlMode = 'read' | 'write';
5
- /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers (an array). */
5
+ /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers. */
6
6
  export type SqlValue = string | number | boolean | bigint | Date | null | readonly (string | number)[];
7
+ /** The database a statement is classified for: Postgres in the application's schema, or a Durable Object's SQLite. */
8
+ export type SqlDatabase = {
9
+ readonly dialect: 'postgres';
10
+ readonly schema: string;
11
+ } | {
12
+ readonly dialect: 'sqlite';
13
+ };
7
14
  /** One test of a capability's scope on a table: the column holds the value, or one of the list. */
8
15
  export interface ScopeTest {
9
16
  readonly column: string;
@@ -11,21 +18,20 @@ export interface ScopeTest {
11
18
  }
12
19
  /** A capability's predicate on one table: every row (`'all'`), or an OR of AND groups; no group matches nothing. */
13
20
  export type ScopeTerms = 'all' | readonly (readonly ScopeTest[])[];
14
- /** What a fragment's table is to its statement: read, or the target of its UPDATE or DELETE. */
21
+ /** What a fragment's table is to its statement, as its author states it: read, or the target of an UPDATE or DELETE. */
15
22
  export type ScopeUse = 'read' | 'update' | 'delete';
23
+ /** The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not reach it. */
24
+ export type ScopeOf = (capability: unknown, table: string, use: ScopeUse) => ScopeTerms;
25
+ /** The third argument of `ctx.sql.scope`: the table's alias in the statement, and what the statement does with it. */
26
+ export interface SqlScopeOptions {
27
+ /** The table's name in the statement; the table's own name by default. */
28
+ readonly alias?: string;
29
+ /** `'update'` or `'delete'` where the statement writes the table, which needs that operation's action; `'read'` by default. */
30
+ readonly use?: ScopeUse;
31
+ }
16
32
  /**
17
- * The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not
18
- * reach it for that use. `assigned` is the columns an UPDATE's SET names (none when the SET cannot be read with
19
- * certainty), and `undefined` before a statement is known.
20
- */
21
- export type ScopeOf = (capability: unknown, table: string, use: ScopeUse, assigned?: readonly string[]) => ScopeTerms;
22
- /** The operation a write statement performs on one of its targets. */
23
- export type WriteOperation = 'insert' | 'update' | 'delete';
24
- /** Throws for a table no statement may write with `operation`: a reference table. */
25
- export type WriteTarget = (table: string, operation: WriteOperation) => void;
26
- /**
27
- * `ctx.sql.scope(capability, table, alias?)`: the capability's whole predicate on one table, as SQL with bound values.
28
- * A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
33
+ * `ctx.sql.scope(capability, table, { alias, use })`: the capability's whole predicate on one table, as SQL with bound
34
+ * values. A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
29
35
  * methods captured at load, so no object an application builds or changes is ever taken for one.
30
36
  */
31
37
  export interface SqlScope {
@@ -34,7 +40,7 @@ export interface SqlScope {
34
40
  /** `ctx.sql(Row)`: the tag for rows of `Row`, and `scope` for the capability's predicate inside its text. */
35
41
  export interface SqlTag {
36
42
  <S extends z.core.$ZodType>(row: S): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<z.output<S>[]>;
37
- scope(capability: unknown, table: string, alias?: string): SqlScope;
43
+ scope(capability: unknown, table: string, options?: SqlScopeOptions): SqlScope;
38
44
  }
39
45
  /** The site a tag is made for: its mode, its binding to the invocation, and the session its statements run in. */
40
46
  export interface SqlSite {
@@ -46,14 +52,16 @@ export interface SqlSite {
46
52
  fail(): void;
47
53
  }
48
54
  /**
49
- * The SQL `parts` make, with `$1…$n` for the values, or a `QueryRefusedError` that names what is refused: more than
50
- * one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for `'write'`), a nested statement of
51
- * another kind, a qualified name outside `schema`, a `fabrika_*` or `pg_*` name, a function call outside the reviewed
52
- * built-ins, and a value placed where it would not be bound.
55
+ * The SQL `parts` make, with a bound placeholder for each value, or a `QueryRefusedError` that names what is refused.
56
+ * On both dialects: more than one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for
57
+ * `'write'`), a `'read'` statement that writes or locks, a value placed where it would not be bound, and a `fabrika_*`
58
+ * name. On Postgres also a nested statement of another kind, `SELECT … INTO`, a `U&` name, a `pg_*` name, a qualified
59
+ * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
60
+ * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
53
61
  */
54
- export declare function classifySql(parts: readonly string[], mode: SqlMode, schema: string): string;
62
+ export declare function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase, sources?: readonly string[]): string;
55
63
  /**
56
64
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
57
65
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
58
66
  */
59
- export declare function sqlTag(site: SqlSite, schema: string | undefined, termsOf: ScopeOf, writeTarget: WriteTarget): SqlTag;
67
+ export declare function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf, sources: readonly string[]): SqlTag;
@@ -0,0 +1,21 @@
1
+ import { Database, type SQLQueryBindings } from 'bun:sqlite';
2
+ import type { SqliteStorage } from './sqlite';
3
+ export interface BunSqliteStorage extends SqliteStorage {
4
+ /** Runs `fn` in one transaction of its own, as a Durable Object's `storage.transactionSync` does. */
5
+ transactionSync<T>(fn: () => T): T;
6
+ }
7
+ /**
8
+ * Runs each statement of `query` in turn and answers the rows of the last one, as a Durable Object's `sql.exec` does.
9
+ * bun:sqlite's `prepare` compiles only the first statement of a text, and its column count cannot tell a migration from a
10
+ * read (`ALTER TABLE … ADD COLUMN … CHECK (…)` reports one column), so the text is split at the end of each compiled
11
+ * statement. `bindings` belong to a text of one statement. Refuses what workerd's SQLite refuses: more than 100 result
12
+ * columns or parameters in one statement.
13
+ */
14
+ export declare function execStatements(database: Database, query: string, bindings?: readonly SQLQueryBindings[]): Record<string, unknown>[];
15
+ /**
16
+ * `database` (a fresh `:memory:` one by default) with foreign keys enforced, as a Durable Object enforces them. One
17
+ * `transaction` runs at a time; one started inside a callback nests in a savepoint, as workerd nests it, and its
18
+ * siblings wait for each other. A statement outside one runs at once. A text of several statements runs each of them and
19
+ * answers the rows of the last (`execStatements`).
20
+ */
21
+ export declare function bunSqliteStorage(database?: Database): BunSqliteStorage;
@@ -0,0 +1,28 @@
1
+ /** What the runner needs of the database; a Durable Object's `storage.sql.exec` and `storage.transactionSync` fit it. */
2
+ export interface SqliteMigrationTarget {
3
+ /** Runs `query`, which may hold several statements, and answers the rows of the last one. */
4
+ exec(query: string, ...bindings: (string | number | null)[]): {
5
+ toArray(): Record<string, unknown>[];
6
+ };
7
+ /** Runs `fn` in one transaction: commits when it returns, rolls back when it throws. */
8
+ transactionSync<T>(fn: () => T): T;
9
+ }
10
+ export interface SqliteMigrationBundle {
11
+ readonly bundle: string;
12
+ readonly migrations: readonly {
13
+ readonly name: string;
14
+ readonly sql: string;
15
+ }[];
16
+ }
17
+ export declare class SqliteMigrationError extends Error {
18
+ readonly name = "SqliteMigrationError";
19
+ }
20
+ /**
21
+ * Applies every migration the ledger does not record, each in its own transaction together with its ledger row, so a
22
+ * failing one leaves nothing of itself and keeps the ones before it. A bundle's digest is recorded in the transaction
23
+ * of its last file, or alone when nothing of it was pending; while every bundle matches its digest, the ledger is not
24
+ * read. Answers the identities it applied.
25
+ */
26
+ export declare function migrateSqlite(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<{
27
+ readonly applied: readonly string[];
28
+ }>;
@@ -0,0 +1,24 @@
1
+ import { Database } from './database';
2
+ /** A value `sql.exec` binds and answers; a Durable Object's `SqlStorageValue`. */
3
+ export type SqliteValue = ArrayBuffer | string | number | null;
4
+ export interface SqliteCursor {
5
+ toArray(): Record<string, SqliteValue>[];
6
+ readonly rowsWritten: number;
7
+ }
8
+ /** What the engine needs of a Durable Object's `ctx.storage`; `DurableObjectStorage` is assignable to it. */
9
+ export interface SqliteStorage {
10
+ readonly sql: {
11
+ exec(query: string, ...bindings: SqliteValue[]): SqliteCursor;
12
+ };
13
+ /** Commits when `closure` resolves, rolls back when it rejects; the object serves no other event meanwhile. */
14
+ transaction<T>(closure: () => Promise<T>): Promise<T>;
15
+ /** Runs `closure` in one transaction of its own, nested in a savepoint inside an open one; rolls back when it throws. */
16
+ transactionSync<T>(closure: () => T): T;
17
+ }
18
+ /**
19
+ * The data layer's database over a Durable Object's storage. A read-only transaction opens no storage transaction,
20
+ * which would hold back every other event of the object across the work's awaits: each of its statements runs in one
21
+ * of its own, so two of them may see different committed states, as under Postgres's READ COMMITTED. The idle timeout
22
+ * has no SQLite form.
23
+ */
24
+ export declare function openSqlite(storage: SqliteStorage): Database;
@@ -1,18 +1,26 @@
1
1
  import { type OperationNode, type ReturningNode } from 'kysely';
2
+ import { type MemberReveals, type PathRule, type RelationSources } from './authority';
2
3
  import { type NameSet } from './builtins';
3
- import { type AppGrant, type CapabilityAuthority, type Ref, type RefGrant, type Within, type WithinGrant } from './capability';
4
- import { type Database, type Session } from './database';
5
- import { type NoColumns, type Primitive, type ScopedSelect, type TableShape } from './description';
4
+ import { type AppGrant, type CapabilityAuthority, type CapabilityGrant, type Ref, type RefGrant, type Within, type WithinGrant } from './capability';
5
+ import { type ConditionModel } from './conditions';
6
+ import { type Database, type Session, type SqlDialect } from './database';
7
+ import { type ComparableColumn, type Compare, type Contains, type NoColumns, type Primitive, type ScopedSelect, type TableShape } from './description';
6
8
  import { type FileBinding } from './file-columns';
7
- import type { ForeignKeyPair, GuardContext, RootKind } from './guard';
8
- import { type Acknowledgement, type ActionOf, type ChildTableName, type Container, type ContainerOf, type DimensionOf, type DimensionTableName, type InsertValues, type JoinableChildren, type ListDimensionOf, type MoveAcknowledgement, type Operation, type ParentOf, type PolicyRow, type TableModel, type TableModels, type Tables, type UpdateValues, type VersionArguments } from './policy';
9
+ import type { ForeignKeyPair, GuardContext, RootKind, ViewParentLink } from './guard';
10
+ import { type Acknowledgement, type ActionOf, type ChildTableName, type Container, type ContainerOf, type DimensionOf, type DimensionTableName, type InsertValues, type JoinableChildren, type ListDimensionOf, type MoveAcknowledgement, type Operation, type ParentOf, type PathWriter, type PolicyRow, type ReadReach, type SecondaryPath, type TableModel, type TableModels, type Tables, type UpdateValues, type VersionArguments } from './policy';
9
11
  import type { ScopeTerms, ScopeUse } from './sql';
10
12
  import { type TablePolicies } from './tables';
13
+ import { type RowColumns } from './temporal';
11
14
  export interface DataLayerRuntime {
12
15
  readonly database: Database;
13
16
  readonly capabilities: CapabilityAuthority;
14
17
  /** Whether the request running now may only read (an export's); its every statement then runs `READ ONLY`. */
15
18
  readonly readOnly?: () => boolean;
19
+ /**
20
+ * Runs inside the transaction of every change of a job's wakes or lease, after the change: the Cloudflare driver arms
21
+ * the alarm from `wakes.next(transaction)` there, so the alarm commits with the change. A throw rolls the change back.
22
+ */
23
+ readonly projectWakes?: (transaction: Session) => Promise<void>;
16
24
  }
17
25
  /** Empty until the framework connects the layer at boot; every table handle of one `scoped` call shares it. */
18
26
  export interface Connection {
@@ -25,8 +33,36 @@ export interface TableContext {
25
33
  readonly destination: TableModel | undefined;
26
34
  readonly shape: TableShape;
27
35
  readonly joins: Readonly<Record<string, readonly ForeignKeyPair[]>>;
36
+ /** The model of each child a select may join, by its table name. */
37
+ readonly children: Readonly<Record<string, TableModel>>;
28
38
  readonly connection: Connection;
39
+ /** Every relation of the layer with its source table: what a relation term of any table reads. */
40
+ readonly relations: RelationSources;
41
+ /** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
42
+ readonly members: MemberReveals;
43
+ /** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
44
+ readonly subqueries: Readonly<Record<string, readonly string[]>>;
45
+ /** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
46
+ readonly through: ViewParent | undefined;
47
+ /** The path columns whose insert hands out actions, each with the table owning the node it names (`pathWriters`). */
48
+ readonly writers: readonly PathBound[];
49
+ }
50
+ /** A path column an insert writes under its bound, and the table that owns the dimension it names. */
51
+ export interface PathBound extends PathWriter {
52
+ readonly owner: TableModel;
29
53
  }
54
+ /** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
55
+ export interface ViewParent extends ViewParentLink {
56
+ readonly context: TableContext;
57
+ }
58
+ /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
59
+ export declare function dialectOf(context: TableContext): SqlDialect;
60
+ /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
61
+ export declare function rowColumnsOf(model: TableModel): RowColumns;
62
+ /** The values a write binds: on SQLite each timestamp as its stored UTC text, so text order is time order. */
63
+ export declare function boundValues(context: TableContext, values: ReadonlyMap<string, Primitive | null>): ReadonlyMap<string, Primitive | null>;
64
+ /** A list's terms over `model`'s columns, as `boundTerm` binds each. */
65
+ export declare function boundTerms(context: TableContext, model: TableModel, terms: readonly (Compare | Contains)[]): readonly (Compare | Contains)[];
30
66
  export declare function runtimeOf(connection: Connection): DataLayerRuntime;
31
67
  export interface DimensionScopeModel {
32
68
  readonly dimension: string;
@@ -47,33 +83,47 @@ export declare function requiredActions(context: TableContext, operation: Operat
47
83
  export declare function checkAction(context: TableContext, operation: Operation, action: string): void;
48
84
  /** The object a Ref of the model's own dimension names, with every link of its chain. */
49
85
  export declare function selfLinks(model: TableModel): readonly Container[];
50
- /** This object, over the whole chain the Ref carries. */
51
- export declare function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode;
86
+ /** This object, over the whole chain the Ref carries; through the secondary paths `paths` admits, by default its action's. */
87
+ export declare function objectPredicate(context: TableContext, capability: unknown, operation: Operation, paths?: PathRule): OperationNode;
52
88
  /** Rows of a dimension table within the scope values of its list dimension. */
53
89
  export declare function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined;
54
- /** Rows of a child table that belong to the parent object the Ref names, over the whole chain. */
55
- export declare function parentPredicate(context: TableContext, grant: RefGrant): OperationNode;
90
+ /**
91
+ * Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
92
+ * of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
93
+ */
94
+ export declare function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode;
56
95
  export declare function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined;
57
96
  /**
58
97
  * The column that places a row of `model` in `dimension`: the column of that link of its containment chain, or a
59
98
  * top-level table's own key; `undefined` when no `Within` of the dimension reaches the table.
60
99
  */
61
100
  export declare function reachColumn(model: TableModel, dimension: string): string | undefined;
101
+ /**
102
+ * Whether a `Within` of `dimension` lists the table: through its containment chain or a secondary path, and a child
103
+ * view through its parent's, its parent's own dimension included.
104
+ */
105
+ export declare function reachedBy(context: TableContext, dimension: string): boolean;
106
+ /** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
107
+ export declare function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[];
62
108
  /**
63
109
  * Rows of a table a `Within` of any dimension of its chain lists, by the table's read action: tasks under a `Within` of
64
- * `org` through their stamped `org_id`, as under one of `project` through `project_id`.
110
+ * `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
111
+ * table reaches through a secondary path, through that path's column.
65
112
  */
66
113
  export declare function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined;
114
+ /** The actions a grant holds: an `app` grant's (several for an `anyOf` endpoint), or any other grant's one. */
115
+ export declare function grantActions(grant: CapabilityGrant): readonly string[];
67
116
  /**
68
117
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
69
118
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
70
119
  * its read action for a `Within`, an action `ctx.db.app` lists it for with an `app` capability, and its read action
71
- * for a scoped site's read of an application table. A fragment on the statement's UPDATE or DELETE target needs that
72
- * operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's column
73
- * and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container grant on
74
- * its own column, or every row for `all`); an `app` capability, and a scoped read of an application table, every row.
120
+ * for a scoped site's read of an application table. A fragment its author marks `use: 'update'` or `'delete'` needs
121
+ * that operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's
122
+ * column and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container
123
+ * grant on its own column, or every row for `all`); an `app` capability, and a scoped read of an application table,
124
+ * every row.
75
125
  */
76
- export declare function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse, assigned?: readonly string[]): ScopeTerms;
126
+ export declare function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse): ScopeTerms;
77
127
  /**
78
128
  * A `Ref` of `dimension` whose action updates columns of the table: its update action, or a column's own write action.
79
129
  * Which columns it updates follows from the action (`updatableBy`).
@@ -84,18 +134,30 @@ export declare function updatingRef(context: TableContext, capability: unknown,
84
134
  * action or an action of `appRead`; its counts (`count`, `aggregate`) with those or an action of `appCount`.
85
135
  */
86
136
  export type AppReach = 'rows' | 'counts';
137
+ /** What an `app` capability reads of a table: the rows (`predicate`), and the reach whose columns it answers. */
138
+ export interface AppRead {
139
+ readonly predicate: OperationNode;
140
+ readonly reach: ReadReach;
141
+ }
87
142
  /**
88
- * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`: `true`, for an action that
89
- * reaches `reach` (`checkRecordReach`).
143
+ * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`, for its actions that reach
144
+ * `reach` (`recordReach`): each row within the condition of one of them, and the columns they read alone.
90
145
  */
146
+ export declare function appRecordRead(context: TableContext, capability: unknown, reach: AppReach): AppRead;
147
+ /** `appRecordRead`'s rows. */
91
148
  export declare function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode;
92
- /** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
149
+ /**
150
+ * Every row a capability of an `app` endpoint reads in an application table, by the table's read actions it holds or
151
+ * `'any'`, and the reach whose columns it answers.
152
+ */
153
+ export declare function appListRead(context: TableContext, capability: unknown): AppRead;
154
+ /** `appListRead`'s rows. */
93
155
  export declare function appListPredicate(context: TableContext, capability: unknown): OperationNode;
94
156
  /**
95
157
  * Every row of an application table, for a `Ref` or a `Within` of its read action: what `ctx.db.app` of an `on`, `in`
96
158
  * or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
97
159
  */
98
- export declare function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode;
160
+ export declare function scopedApplicationRead(context: TableContext, capability: unknown, branch?: OperationNode | 'all'): OperationNode;
99
161
  /** One row of an application table by its key, for an `app` capability of `operation`'s action. */
100
162
  export declare function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode;
101
163
  /**
@@ -104,6 +166,7 @@ export declare function appRowPredicate(context: TableContext, capability: unkno
104
166
  */
105
167
  export declare function claimScope(context: TableContext, capability: unknown): {
106
168
  readonly grant: AppGrant | WithinGrant;
169
+ readonly action: string;
107
170
  readonly scope: OperationNode | undefined;
108
171
  };
109
172
  /**
@@ -111,13 +174,26 @@ export declare function claimScope(context: TableContext, capability: unknown):
111
174
  * it was claimed, so a row moved since is not reached.
112
175
  */
113
176
  export declare function claimedRowPredicate(context: TableContext, capability: unknown, operation: 'update' | 'delete'): OperationNode;
177
+ /** The row of an application table `key` names, as `actions` reach it: within their conditions, any one admitting it. */
178
+ export declare function appKeyScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode;
179
+ /** The row `key` names, as a read by key with `actions` reaches it: unconditioned in a table read with `'any'`. */
180
+ export declare function appGetScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode;
114
181
  /** The row of an application table `key` names. */
115
182
  export declare function appKeyPredicate(model: TableModel, key: unknown): OperationNode;
116
183
  /**
117
- * The capability of an `app` endpoint whose action updates columns of an application table: its update action, or a
118
- * column's own write action. Which columns it updates follows from the action (`updatableBy`).
184
+ * The actions of an `app` endpoint's capability that update columns of an application table, at least one: its update
185
+ * action, or a column's own write action. Which columns they update follows from them (`updatableByAny`).
119
186
  */
120
- export declare function updatingApp(context: TableContext, capability: unknown): AppGrant;
187
+ export declare function updatingApp(context: TableContext, capability: unknown): readonly string[];
188
+ /**
189
+ * An `app` capability's update of the application table row `key`: `values`, read against the columns its update
190
+ * actions write, and the row's scope under only those actions that write every given column, any one's condition
191
+ * admitting the row. So several held actions never write one action's columns on rows only another one reaches.
192
+ */
193
+ export declare function appUpdate(context: TableContext, capability: unknown, key: unknown, values: unknown): {
194
+ readonly scope: OperationNode;
195
+ readonly changes: Map<string, Primitive | null>;
196
+ };
121
197
  export declare function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode;
122
198
  export declare function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext;
123
199
  /**
@@ -137,7 +213,10 @@ export interface Runner {
137
213
  * lease (`fencedTransaction`): an attempt that lost it, or ran out of time, writes nothing.
138
214
  */
139
215
  export declare function fencedWork<T>(runtime: DataLayerRuntime, work: (transaction: Session) => Promise<T>): Promise<T>;
140
- /** The action a capability holds, which its operation's checks already admitted. */
216
+ /**
217
+ * The one action a capability holds, which its operation's checks already admitted. An `anyOf` endpoint's `app`
218
+ * capability that holds several is refused: it reads through `ctx.db.app`, which reads with every action it holds.
219
+ */
141
220
  export declare function heldAction(context: TableContext, capability: unknown): string;
142
221
  /**
143
222
  * Reads insert or update data through its own property descriptors, so no getter runs and no inherited or
@@ -148,12 +227,13 @@ export declare function readValues(values: unknown, allowed: NameSet, what: 'ins
148
227
  export declare function versionArgument(context: TableContext, options: readonly unknown[]): OperationNode | undefined;
149
228
  /**
150
229
  * One row by its scope predicate, with `visible` columns (the table's read action's, unless a capability reads its own).
151
- * `action` is what read it: each file column then answers a reference that reads the file only under a read action.
230
+ * `reach` is what read it: each file column then answers a reference that reads the file only under a read action.
152
231
  */
153
- export declare function selectOne<O>(context: TableContext, run: Runner, scope: OperationNode, visible?: readonly string[], action?: string): Promise<O>;
232
+ export declare function selectOne<O>(context: TableContext, run: Runner, scope: OperationNode, visible?: readonly string[], reach?: ReadReach): Promise<O>;
154
233
  export declare function answer(context: TableContext): ReturningNode;
155
234
  export declare function keyOf(model: TableModel): string;
156
- export declare function insertRow<O>(context: TableContext, run: Runner, values: ReadonlyMap<string, Primitive | null>, destination: RefGrant | undefined): Promise<O>;
235
+ /** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
236
+ export declare function insertRow<O>(context: TableContext, run: Runner, given: ReadonlyMap<string, Primitive | null>, prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined): Promise<O>;
157
237
  /**
158
238
  * `insert(values, { onConflict: { columns, do } })`: on a conflict of `columns` (a unique index of the table), `nothing`
159
239
  * writes nothing and `update` sets the columns the table's update action writes, from `updates`.
@@ -163,12 +243,14 @@ export interface OnConflict {
163
243
  readonly mode: 'nothing' | 'update';
164
244
  /** The values given for the table's update columns: what `update` sets on the conflicting row. */
165
245
  readonly updates: ReadonlyMap<string, Primitive | null>;
246
+ /** The capability's update actions, one of whose conditions the conflicting row must satisfy to be updated. */
247
+ readonly actions: readonly string[];
166
248
  }
167
249
  /**
168
250
  * The `onConflict` of an insert's options, read through own data properties; `undefined` without options. `'update'`
169
- * also needs the capability's action to be one of the table's update actions.
251
+ * also needs one of the capability's `actions` to be one of the table's update actions.
170
252
  */
171
- export declare function onConflictOf(context: TableContext, options: unknown, action: string, given: ReadonlyMap<string, Primitive | null>): OnConflict | undefined;
253
+ export declare function onConflictOf(context: TableContext, options: unknown, actions: readonly string[], given: ReadonlyMap<string, Primitive | null>): OnConflict | undefined;
172
254
  /**
173
255
  * The rows a write addresses: the scope predicate, and the caller's conditions beside it (an unscoped row's key, whose
174
256
  * scope predicate is `true`).
@@ -181,7 +263,17 @@ export interface Addressed {
181
263
  * Zero changed rows → one follow-up read in the same transaction → 404 when the object is gone, else 409. An update
182
264
  * that sets no column writes nothing, not even the version: it reads the acknowledgement under the same conditions.
183
265
  */
184
- export declare function updateRow<O>(context: TableContext, run: Runner, target: Addressed, changes: ReadonlyMap<string, Primitive | null>, expectedVersion: OperationNode | undefined, destination?: RefGrant): Promise<O>;
266
+ export declare function updateRow<O>(context: TableContext, run: Runner, target: Addressed, given: ReadonlyMap<string, Primitive | null>, expectedVersion: OperationNode | undefined, moved?: MovedRow): Promise<O>;
267
+ /**
268
+ * A move's destination, locked before the write, and the destination's insert conditions, which judge the moved row
269
+ * after it as an insert into the destination judges its row: the insert action's (`judgeInserted`), and each one
270
+ * `relationWhen` puts on a relation the destination `Ref` holds through (`judgeNarrowed`).
271
+ */
272
+ export interface MovedRow {
273
+ readonly destination: RefGrant;
274
+ readonly judged: JudgedInsert | undefined;
275
+ readonly narrowed: readonly NarrowedInsert[];
276
+ }
185
277
  /** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
186
278
  export declare function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void>;
187
279
  type Columns<Row> = keyof Row & string;
@@ -189,11 +281,11 @@ type NumericColumn<Row> = {
189
281
  [K in Columns<Row>]: Exclude<Row[K], null> extends number | bigint | string ? K : never;
190
282
  }[Columns<Row>];
191
283
  export interface AggregateSpec<Row> {
192
- readonly groupBy?: readonly Columns<Row>[];
284
+ readonly groupBy?: readonly ComparableColumn<Row>[];
193
285
  readonly count?: boolean;
194
286
  readonly sum?: readonly NumericColumn<Row>[];
195
- readonly min?: readonly Columns<Row>[];
196
- readonly max?: readonly Columns<Row>[];
287
+ readonly min?: readonly ComparableColumn<Row>[];
288
+ readonly max?: readonly ComparableColumn<Row>[];
197
289
  readonly where?: (q: ScopedSelect<Row, Row, NoColumns>) => ScopedSelect<Row, unknown, NoColumns>;
198
290
  }
199
291
  type Listed<S, K extends 'groupBy' | 'sum' | 'min' | 'max'> = S extends {
@@ -221,8 +313,23 @@ export declare function aggregateRows<Row, O>(context: TableContext, run: Runner
221
313
  /** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
222
314
  export interface PreparedInsert {
223
315
  readonly row: Map<string, Primitive | null>;
316
+ /** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
317
+ readonly writer: string;
224
318
  readonly destination: RefGrant | undefined;
225
319
  readonly conflict: OnConflict | undefined;
320
+ /** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
321
+ readonly judged: JudgedInsert | undefined;
322
+ /** The destination's relations whose `relationWhen` for the insert follows a path: judged on the written row. */
323
+ readonly narrowed: readonly NarrowedInsert[];
324
+ }
325
+ export interface JudgedInsert {
326
+ readonly action: string;
327
+ readonly condition: ConditionModel;
328
+ }
329
+ /** A relation the destination `Ref` holds through, which the inserted table narrows for the insert by a condition with a path. */
330
+ export interface NarrowedInsert {
331
+ readonly relation: string;
332
+ readonly condition: ConditionModel;
226
333
  }
227
334
  /**
228
335
  * A dimension table's insert over a capability nobody type-checked: into a container (a new UUIDv7 key, the chain from
@@ -261,7 +368,9 @@ export declare class DimensionTable<DB, P, T extends string> {
261
368
  /**
262
369
  * Moves the object to another container: the delete action at the source, the insert action at the target,
263
370
  * whose chain is checked against the database. Every chain column changes; children that copy them follow
264
- * through `ON UPDATE CASCADE` on their composite foreign key. Answers the acknowledgement and the new chain.
371
+ * through `ON UPDATE CASCADE` on their composite foreign key. The moved row is judged by the insert action's
372
+ * condition and by the `relationWhen` of each relation the target holds through, as an insert into the target is.
373
+ * Answers the acknowledgement and the new chain.
265
374
  */
266
375
  move(ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>, to: Ref<ContainerOf<P, T>, ActionOf<P, T, 'insert'>>): Promise<MoveAcknowledgement<P, T>>;
267
376
  aggregate<const S extends AggregateSpec<Row<DB, P, T>>>(within: Within<ListDimensionOf<P, T>, ReadAction<P, T>>, spec: S): Promise<AggregateRow<Row<DB, P, T>, S>[]>;
@@ -281,7 +390,7 @@ export declare class ChildTable<DB, P, T extends string> {
281
390
  aggregate<const S extends AggregateSpec<Row<DB, P, T>>>(scope: ChildListScope<P, T>, spec: S): Promise<AggregateRow<Row<DB, P, T>, S>[]>;
282
391
  }
283
392
  /**
284
- * One table's operations without the store types, for `@fabrika/db/testing` only: the generated isolation tests address
393
+ * One table's operations without the store types, for `@fabrika/db/testing` only: the policy isolation kit addresses
285
394
  * a table by name. Every runtime check of a store applies; a child row is addressed by its parent's capability and
286
395
  * `key`, a dimension row by its capability alone.
287
396
  */
@@ -74,9 +74,13 @@ export interface StoredFiles {
74
74
  promote(id: string, sha256: string, version: string): Promise<boolean>;
75
75
  deferScan(id: string, attempts: number, after: Date): Promise<boolean>;
76
76
  reject(id: string): Promise<boolean>;
77
- /** Objects whose rows a sweep deleted and whose own deletion it did not finish. */
78
- unfinishedDeletions(limit: number): Promise<readonly string[]>;
77
+ /** At most `limit` queued object keys recorded at or before `cutoff` (equality is due), oldest first. */
78
+ dueDeletions(limit: number, cutoff: Date): Promise<readonly string[]>;
79
+ /** Takes a due key out of the queue before its object is deleted; `false` when a cancel or a requeue got there first. */
80
+ claimDeletion(objectKey: string, cutoff: Date): Promise<boolean>;
79
81
  forgetDeletion(objectKey: string): Promise<void>;
82
+ /** Takes `objectKeys` out of the queue, so their objects stay: a restore's rows reference them again. The number taken. */
83
+ cancelDeletions(objectKeys: readonly string[]): Promise<number>;
80
84
  /** Clears the legacy marker of every migrated file that one of `columns` references: it is an ordinary file now. */
81
85
  adoptReferenced(columns: readonly FileColumnRef[]): Promise<number>;
82
86
  /** At most `limit` files past the grace that no column of `columns` references (pending ones included), oldest first. */
@@ -1,10 +1,26 @@
1
1
  import type { TablePolicyArtifact } from '@fabrika/auth-core';
2
+ import { type ApplicationRowsPlan } from './application-rows';
2
3
  import { type Tables } from './policy';
4
+ export { applicationRowRefusalText } from './application-rows';
5
+ export type { ApplicationRowRefusal, ApplicationRowsPlan } from './application-rows';
3
6
  export { PolicyError } from './errors';
4
7
  export type { FileReference } from './file-references';
5
- export type { AnyDbIndex, ApplicationRows, ApplicationTables, AppRecordRows, ChildRows, ClaimedRow, ClaimedRowHandle, ClaimOptions, ContainedRows, CountOptions, DataKind, DbIndex, FragmentTable, IndexedTable, InsertConflict, InsertMethod, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, PublicApplicationRows, PublicApplicationTables, PublicInsertMethod, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, RowOf, Saved, ScopedApplicationRows, ScopedApplicationTables, ScopeTarget, TableNameOf, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
8
+ export type { AllOptions, AllQuery, AnyDbIndex, ApplicationRows, ApplicationTables, AppRecordRows, ChildRows, ClaimedRow, ClaimedRowHandle, ClaimOptions, ContainedRows, CountOptions, CountQuery, DataKind, DbIndex, FragmentTable, IndexedTable, InsertConflict, InsertMethod, ListOptions, ListPage, ListQuery, NoUnscoped, OrderTerm, OwnerRow, PublicApplicationRows, PublicApplicationTables, PublicInsertMethod, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, RowOf, Saved, ScopedApplicationRows, ScopedApplicationTables, ScopeTarget, TableNameOf, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
6
9
  export { type ApplicationPolicy, type ApplicationScope, type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type FilePolicies, isTables, type QueuePolicy, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type TableAction, type TableActions, type TableInsert, Tables, type TableUpdate, type VersionColumn, type VocabularyTables, } from './policy';
7
- export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
10
+ export type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, VocabularyViewPolicy, } from './vocabulary-tables';
11
+ /**
12
+ * The plan of seeding one row of each application table `rows` names (table → column → value), as an endpoint access
13
+ * case seeds its `appRows`: the order, the foreign keys that link one given row to another, and every refusal.
14
+ * `@fabrika/check` reports the refusals from source; `@fabrika/db/testing` throws the first, both in the words of
15
+ * `applicationRowRefusalText`.
16
+ */
17
+ export declare function applicationRowsPlan<DB, P>(tables: Tables<DB, P>, rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>): ApplicationRowsPlan;
18
+ /**
19
+ * The tables whose rows hand out access, lowercased: a relation source or a path reveal, a member-revealing table, and
20
+ * the tables a principal path or a relation's condition reads. Only the data layer writes them; the migration classifier
21
+ * refuses database code that does.
22
+ */
23
+ export declare function accessTables<DB, P>(tables: Tables<DB, P>): readonly string[];
8
24
  /** Every table's policy in the form the contract artifact carries, by table name. */
9
25
  export type TablePolicies = Readonly<Record<string, TablePolicyArtifact>>;
10
26
  /** The artifact form of every policy `defineTables` (or `readTables`) checked. */
@@ -1,4 +1,5 @@
1
1
  import { type NameSet } from './builtins';
2
+ import type { SqlDialect } from './database';
2
3
  /**
3
4
  * A day as the layer answers it: the database's `YYYY-MM-DD` text, or a decoded `Date` that is exactly a UTC midnight
4
5
  * in 0001–9999 — the only `Date` `Bun.SQL` decodes correctly from a `date`, whatever the process's time zone.
@@ -10,3 +11,26 @@ export declare function answerDays<R>(table: string, days: NameSet, rows: R[]):
10
11
  export declare function dayInput(value: string, where: string): string;
11
12
  /** A timestamp a write binds as text: strict ISO 8601 with `Z` or an offset, every field in range. */
12
13
  export declare function timestampInput(value: string, where: string): string;
14
+ /**
15
+ * What a write or a comparison binds for a timestamp on SQLite: the instant of a `Date`, or of the text `timestampInput`
16
+ * admits, as stored text. Digits past the millisecond are dropped; an instant outside the years 0000–9999 UTC is
17
+ * refused, since its text would not sort.
18
+ */
19
+ export declare function storedTimestamp(value: string | Date, where: string): string;
20
+ /** The columns of a read's rows the layer answers in a form of its own, by the name each arrives under. */
21
+ export interface RowColumns {
22
+ /** `date` columns: `YYYY-MM-DD` text. */
23
+ readonly days: NameSet;
24
+ /** Timestamps: a `Date` (SQLite answers its stored text). */
25
+ readonly timestamps: NameSet;
26
+ /** Booleans: `true` or `false` (SQLite answers 1 or 0). */
27
+ readonly booleans: NameSet;
28
+ /** JSON columns: the parsed value (SQLite answers its text). */
29
+ readonly json: NameSet;
30
+ }
31
+ /**
32
+ * Every row of a read as the layer answers it, in place: each day as `YYYY-MM-DD` text, and on SQLite each timestamp as
33
+ * a `Date`, each boolean as `true` or `false` and each JSON column as its parsed value, so a handler reads the same
34
+ * values on both dialects.
35
+ */
36
+ export declare function answerRows<R>(dialect: SqlDialect, table: string, columns: RowColumns, rows: R[]): R[];