@fabrika/db 0.9.0-dev.5 → 0.9.0-dev.51

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 (75) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +62 -22
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +37 -8
  10. package/src/errors.ts +8 -4
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +124 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +368 -146
  25. package/src/policy.ts +1973 -141
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-bun.ts +41 -14
  31. package/src/sqlite-migrate.ts +102 -1
  32. package/src/sqlite.ts +46 -1
  33. package/src/store.ts +1930 -167
  34. package/src/tables.ts +156 -6
  35. package/src/temporal.ts +8 -1
  36. package/src/testing-shared.ts +758 -140
  37. package/src/testing-sqlite.ts +212 -40
  38. package/src/testing.ts +151 -22
  39. package/src/vocabulary-tables.ts +159 -27
  40. package/types/src/authority.d.ts +147 -0
  41. package/types/src/builtins.d.ts +2 -0
  42. package/types/src/capability.d.ts +50 -2
  43. package/types/src/codegen-sqlite.d.ts +8 -1
  44. package/types/src/codegen.d.ts +54 -10
  45. package/types/src/condition-nodes.d.ts +9 -0
  46. package/types/src/conditions.d.ts +151 -0
  47. package/types/src/description.d.ts +26 -8
  48. package/types/src/errors.d.ts +7 -4
  49. package/types/src/file-columns.d.ts +6 -4
  50. package/types/src/framework.d.ts +5 -2
  51. package/types/src/guard.d.ts +24 -0
  52. package/types/src/index.d.ts +4 -3
  53. package/types/src/job-leases.d.ts +8 -1
  54. package/types/src/job-wakes.d.ts +28 -5
  55. package/types/src/json.d.ts +18 -0
  56. package/types/src/list-cursor.d.ts +13 -0
  57. package/types/src/migrations.d.ts +5 -0
  58. package/types/src/nodes.d.ts +4 -0
  59. package/types/src/notifications.d.ts +37 -0
  60. package/types/src/orm-types.d.ts +165 -73
  61. package/types/src/orm.d.ts +21 -0
  62. package/types/src/policy.d.ts +347 -23
  63. package/types/src/push-subscriptions.d.ts +49 -0
  64. package/types/src/registry.d.ts +36 -1
  65. package/types/src/request-receipts.d.ts +22 -0
  66. package/types/src/sql.d.ts +2 -2
  67. package/types/src/sqlite-bun.d.ts +11 -3
  68. package/types/src/sqlite-migrate.d.ts +32 -0
  69. package/types/src/store.d.ts +118 -31
  70. package/types/src/tables.d.ts +8 -2
  71. package/types/src/temporal.d.ts +4 -1
  72. package/types/src/testing-shared.d.ts +112 -23
  73. package/types/src/testing-sqlite.d.ts +17 -2
  74. package/types/src/testing.d.ts +1 -1
  75. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -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,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";
@@ -39,7 +40,9 @@ export declare const QUERY_REFUSALS: {
39
40
  readonly unexpected_row: "the database answered a row in another shape than its migration declares";
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
- readonly list_page: "a list limit, cursor or order outside what a page admits";
43
+ readonly list_page: "a list limit or order outside what a page admits";
44
+ readonly list_cursor: "a list's after is not the next cursor of a page of this same list: undecodable, unsigned or edited, of another shape, table or order";
45
+ readonly too_many_rows: "all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate";
43
46
  readonly undeclared_reach: "the site reaches data it did not declare (sql or unscoped, or their mode)";
44
47
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
45
48
  readonly sql_statement: "ctx.sql runs one statement of an admitted kind, and none inside another";
@@ -51,7 +54,7 @@ export declare const QUERY_REFUSALS: {
51
54
  readonly file_scan: "a scan verdict outside the scan job's lease";
52
55
  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
56
  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";
57
+ 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
58
  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
59
  readonly file_scope: "a file is referenced from another top-level scope than the one its first reference set";
57
60
  };
@@ -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.
@@ -9,9 +9,12 @@ 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
11
  export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
12
- export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
12
+ export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes';
13
+ export type { NewNotification, NotificationAbout, Notifications, StoredNotification } from './notifications';
13
14
  export type { DataAccess, DataHandles, DataSite } from './orm';
14
- export type { FrameworkTables, Locator, ProvisionalBinding } from './registry';
15
+ export type { PushBinding, PushInboxSubscription, PushRecordOutcome, PushSubscriptionKeys, PushSubscriptions } from './push-subscriptions';
16
+ export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry';
17
+ export type { RequestReceipt, RequestReceipts } from './request-receipts';
15
18
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
16
19
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files';
17
20
  /** Whether `value` is an object `scoped(tables)` created, rather than a look-alike with the same fields. */
@@ -18,6 +18,30 @@ export interface GuardContext {
18
18
  readonly lock?: 'share' | 'update' | 'claim';
19
19
  /** An insert that does nothing on a conflict of its listed columns: `on conflict (columns) do nothing`, and no other. */
20
20
  readonly onConflict?: 'nothing';
21
+ /**
22
+ * The tables a scope predicate's subqueries may read, each with the columns one may select: a relation's source by
23
+ * its node column, a condition path's target by its key. Without it, a scope holds no subquery.
24
+ */
25
+ readonly subqueries?: Readonly<Record<string, readonly string[]>>;
26
+ /**
27
+ * A child view's parent: its scope may read the view's rows through `<column> in (select P.<key> from P where <P's
28
+ * reach>)`. Without it, a scope holds no such subquery.
29
+ */
30
+ readonly through?: ViewParentLink | undefined;
31
+ }
32
+ /** The parent a child view's scope reads its rows through: the view's parent column, the parent table and its key. */
33
+ export interface ViewParentLink {
34
+ readonly column: string;
35
+ readonly table: string;
36
+ readonly key: string;
37
+ /** The view's own access views, which list its rows beside the parent's reach (ADR-0076). */
38
+ readonly access?: readonly ViewAccessLink[];
39
+ }
40
+ /** An access view of a child view: `V.<key> in (select A.<row> from A where <bindings>)`. */
41
+ export interface ViewAccessLink {
42
+ readonly key: string;
43
+ readonly view: string;
44
+ readonly row: string;
21
45
  }
22
46
  /** Refuses any operation tree outside the allowlist. Runs on the final tree, immediately before it is compiled. */
23
47
  export declare function assertAllowedTree(root: OperationNode, context: GuardContext): void;
@@ -1,10 +1,11 @@
1
- export type { AppCapability, AppGrant, CapabilityAuthority, CapabilityGrant, ContainerGrant, LeaseFence, Ref, RefGrant, RowGrant, RowRef, Within, WithinGrant, } from './capability';
1
+ export type { AppCapability, AppGrant, CapabilityAuthority, CapabilityGrant, ContainerGrant, LeaseFence, Ref, RefGrant, RelationHold, RowGrant, RowRef, Within, WithinGrant, } from './capability';
2
2
  export { MAX_WITHIN_VALUES } from './capability';
3
3
  export { applicationSchema, Database, type DatabaseEngine, type Executor, type SqlDialect, type TransactionOptions, type TransactionRunner, } from './database';
4
4
  export type { AllowedOperator, ComparisonOperator, ConditionTuple, ListOperator, NoColumns, NullOperator, PatternOperator, Primitive, ScopedSelect, } from './description';
5
5
  export { CAPABILITY_ERRORS, CapabilityError, type CapabilityErrorReason, DatabaseError, LeaseLostError, PolicyError, QUERY_REFUSALS, type QueryRefusal, QueryRefusedError, } from './errors';
6
- export type { AnyDbIndex, ChildRows, ContainedRows, CountOptions, DataKind, DbIndex, IndexedTable, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, Saved, ScopeTarget, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
6
+ export type { JsonColumnValue, JsonValue } from './json';
7
+ export type { AllOptions, AllQuery, AnyDbIndex, ChildRows, ContainedRows, CountOptions, CountQuery, DataKind, DbIndex, IndexedTable, ListOptions, ListPage, ListQuery, NoUnscoped, OrderTerm, OwnerRow, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, Saved, ScopeTarget, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
7
8
  export { type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type InsertValues, isTables, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type RowOf, type TableActions, type TableInsert, Tables, type TableUpdate, type UpdateValues, type VersionColumn, type VocabularyTables, } from './policy';
8
9
  export { type AggregateRow, type AggregateSpec, type ChildListScope, type DataLayer, type DataLayerRuntime, scoped, type ScopedDatabase, } from './store';
9
10
  export { type TablePolicies, tablePolicies } from './tables';
10
- export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
11
+ export type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, VocabularyViewPolicy, } from './vocabulary-tables';
@@ -54,6 +54,12 @@ export interface JobLeases {
54
54
  * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
55
55
  */
56
56
  finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>;
57
+ /**
58
+ * Gives back a lease under which no run started: frees it and leaves every wake as it is, owned ones disowned, and
59
+ * records no run (no status, end or duration). A process schedule's timer releases a lease whose take owned no due
60
+ * wake (ADR-0080). `false` when `fence` no longer held it.
61
+ */
62
+ release(fence: LeaseFence): Promise<boolean>;
57
63
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
58
64
  markPending(job: string): Promise<void>;
59
65
  /**
@@ -98,7 +104,8 @@ export declare function sqliteNowPlus(ms: string): string;
98
104
  export declare function sqliteTimestamp(value: unknown, what: string): Date | null;
99
105
  /**
100
106
  * The database's clock inside `session`'s transaction: a queue claim compares and moves `due` by it, so no process
101
- * clock decides when a row is due.
107
+ * clock decides when a row is due. On Postgres it is rounded up to the millisecond a `Date` holds, so it is never
108
+ * earlier than a `due` that `now()` wrote with microseconds.
102
109
  */
103
110
  export declare function databaseNow(session: Session): Promise<Date>;
104
111
  /**
@@ -31,9 +31,15 @@ export type FinishWakes =
31
31
  /** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
32
32
  {
33
33
  readonly kind: 'completed';
34
+ /**
35
+ * With `scheduled`, the next fire is written only when the stored schedule (`keepSchedule`) declares its key, read
36
+ * in the finish's transaction: under a process schedule, a run of an older deploy writes no removed job's or
37
+ * changed expression's fire (ADR-0080).
38
+ */
34
39
  readonly nextCron?: {
35
40
  readonly expression: string;
36
41
  readonly dueAt: Date;
42
+ readonly scheduled?: boolean;
37
43
  };
38
44
  }
39
45
  /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
@@ -53,18 +59,31 @@ export interface JobWakes {
53
59
  pending(job: string): Promise<readonly Wake[]>;
54
60
  /**
55
61
  * When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
56
- * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given.
62
+ * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given;
63
+ * with `jobs`, of those jobs only, so a wake of a job this process does not run never holds its timer.
57
64
  */
58
- next(using?: Session): Promise<Date | null>;
65
+ next(using?: Session, jobs?: readonly string[]): Promise<Date | null>;
59
66
  /** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
60
- untilNext(using?: Session): Promise<number | null>;
67
+ untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null>;
68
+ /**
69
+ * Where no crontab runs (ADR-0080), in one transaction: raises the stored schedule generation to `generation` when that
70
+ * one is higher in byte order, with the cron keys `fires` declare, and when `generation` is then the stored one,
71
+ * reconciles the wakes against `fires` (as `reconcile`) and adds each fire's wake under its job's cron key where none
72
+ * is pending (an existing one, overdue or not, is left as it is and not locked, so a lease taken meanwhile still owns
73
+ * it). Answers whether `generation` is the stored one; a process of an older one writes nothing. The generation's row stays
74
+ * locked until the transaction commits, so on Postgres a newer generation waits for an older one's seed and reconciles
75
+ * after it, and an older one queued behind a newer one reads the newer and writes nothing. A UUIDv7, lowercase: a
76
+ * later deploy's sorts later.
77
+ */
78
+ keepSchedule(generation: string, fires: readonly ScheduledFire[]): Promise<boolean>;
61
79
  /** The database's clock, read in `using` when given: a wake due now is due by it. */
62
80
  now(using?: Session): Promise<Date>;
63
81
  /**
64
82
  * Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
65
- * each declared job's cron wake whose key names another expression; answers how many it deleted.
83
+ * each declared job's cron wake whose key names another expression; answers how many it deleted. In `using` when
84
+ * given.
66
85
  */
67
- reconcile(declared: readonly DeclaredJob[]): Promise<number>;
86
+ reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number>;
68
87
  /**
69
88
  * The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
70
89
  * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
@@ -76,6 +95,10 @@ export interface JobWakes {
76
95
  */
77
96
  expiredHolders(): Promise<readonly string[]>;
78
97
  }
98
+ /** A declared job and its next fire, which `keepSchedule` seeds; `null` when its expression has none in the window. */
99
+ export interface ScheduledFire extends DeclaredJob {
100
+ readonly dueAt: Date | null;
101
+ }
79
102
  /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
80
103
  export interface DeclaredJob {
81
104
  readonly job: string;
@@ -0,0 +1,18 @@
1
+ /** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
2
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
3
+ readonly [key: string]: JsonValue | undefined;
4
+ };
5
+ /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
6
+ export type JsonColumnValue = Exclude<JsonValue, null>;
7
+ /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
8
+ export declare const MAX_JSON_DEPTH = 64;
9
+ /**
10
+ * A written JSON column value as the text the layer binds: plain objects and arrays, strings, finite numbers, booleans
11
+ * and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
12
+ */
13
+ export declare function jsonInput(value: unknown, where: string): string;
14
+ /**
15
+ * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
16
+ * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
17
+ */
18
+ export declare function sqliteJson(value: unknown, where: string): unknown;
@@ -0,0 +1,13 @@
1
+ import { type Session } from './database';
2
+ /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
3
+ export type CursorValue = string | null;
4
+ /** The database's cursor key, read in `session`; the framework migration wrote it, so its absence is no caller's fault. */
5
+ export declare function cursorKey(session: Session): Promise<CryptoKey>;
6
+ /** The cursor of the page after the row whose order values are `values`, in the list `list` names. */
7
+ export declare function signCursor(key: () => Promise<CryptoKey>, list: string, values: readonly CursorValue[]): Promise<string>;
8
+ /**
9
+ * The order values of `after` when it is a cursor this database signed for the list `list` names, with one plain value
10
+ * per order column (`count`). Anything else is the caller's `list_cursor`: undecodable, unsigned, edited, of another
11
+ * list or order, or of another shape.
12
+ */
13
+ export declare function openCursor(key: () => Promise<CryptoKey>, list: string, after: unknown, count: number): Promise<readonly CursorValue[]>;
@@ -5,12 +5,17 @@ export declare const WEBHOOK_DELIVERIES_TABLE = "fabrika_webhook_deliveries";
5
5
  export declare const JOB_LEASES_TABLE = "fabrika_job_leases";
6
6
  export declare const JOB_KICKS_TABLE = "fabrika_job_kicks";
7
7
  export declare const JOB_WAKES_TABLE = "fabrika_wakes";
8
+ export declare const JOB_SCHEDULE_TABLE = "fabrika_job_schedule";
8
9
  export declare const FORM_ADMISSIONS_TABLE = "fabrika_form_admissions";
9
10
  export declare const FORM_CHALLENGES_TABLE = "fabrika_form_challenges";
10
11
  export declare const FORM_FILES_TABLE = "fabrika_form_files";
11
12
  export declare const FORM_BYTES_TABLE = "fabrika_form_bytes";
12
13
  export declare const FILES_TABLE = "fabrika_files";
13
14
  export declare const FILE_DELETIONS_TABLE = "fabrika_file_deletions";
15
+ export declare const REQUEST_RECEIPTS_TABLE = "fabrika_request_receipts";
16
+ export declare const LIST_CURSOR_KEY_TABLE = "fabrika_list_cursor_key";
17
+ export declare const PUSH_SUBSCRIPTIONS_TABLE = "fabrika_push_subscriptions";
18
+ export declare const NOTIFICATIONS_TABLE = "fabrika_notifications";
14
19
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
15
20
  export declare const FILES_RELEASE_FUNCTION = "fabrika_files_release";
16
21
  /**
@@ -8,6 +8,8 @@ export declare function allOf(nodes: readonly OperationNode[]): OperationNode;
8
8
  /** One node, or the OR of several in a parenthesis: inside an AND, `a and b or c` would read as `(a and b) or c`. */
9
9
  export declare function anyOf(nodes: readonly OperationNode[]): OperationNode;
10
10
  export declare function inList(table: string, name: string, values: readonly string[]): OperationNode;
11
+ /** `($1, $2, …)`: bound values, as the right operand of an `in`. */
12
+ export declare function valueList(values: readonly string[]): OperationNode;
11
13
  /** The scope of a `Within` that is not limited to scope values. */
12
14
  export declare function everything(): OperationNode;
13
15
  /** LIKE treats `\` as its escape character by default, so the text matches literally. */
@@ -39,6 +41,8 @@ export declare function existsNode(table: string, key: string, scope: OperationN
39
41
  export declare function acknowledgementNode(table: string, key: string, version: string | undefined, where: WhereNode): SelectQueryNode;
40
42
  /** `select columns from table where scope limit 1`: the containment columns of one object, for the framework's locator. */
41
43
  export declare function locateNode(table: string, columns: readonly string[], scope: OperationNode): SelectQueryNode;
44
+ /** `select T.<name> from T where <scope> group by T.<name>`: each value of `name` the scoped rows hold, once. */
45
+ export declare function valuesNode(table: string, name: string, scope: OperationNode): SelectQueryNode;
42
46
  /**
43
47
  * The same check, locked: `for share` keeps the row from moving until the transaction that checked it ends, `for
44
48
  * update` also keeps every other writer and locker of it waiting.
@@ -0,0 +1,37 @@
1
+ import { type Session } from './database';
2
+ export declare const NOTIFICATION_LIMITS: Readonly<{
3
+ /** How long a notification is kept and answered: seven days. */
4
+ retentionMs: number;
5
+ }>;
6
+ /** What the recipient must hold to read a notification: an action on one object, or the action as a global grant. */
7
+ export type NotificationAbout = {
8
+ readonly action: string;
9
+ readonly dimension: string;
10
+ readonly value: string;
11
+ } | {
12
+ readonly action: string;
13
+ readonly dimension: null;
14
+ readonly value: null;
15
+ };
16
+ export interface StoredNotification {
17
+ /** A UUIDv7: its order is the order written. */
18
+ readonly id: string;
19
+ readonly title: string;
20
+ readonly body: string;
21
+ readonly path: string;
22
+ readonly about: NotificationAbout;
23
+ }
24
+ export interface NewNotification extends StoredNotification {
25
+ readonly principal: string;
26
+ /** Epoch milliseconds. */
27
+ readonly createdAt: number;
28
+ }
29
+ export interface Notifications {
30
+ /** Writes `notification`, after pruning a batch of rows past the retention. */
31
+ record(session: Session, notification: NewNotification): Promise<void>;
32
+ /** `principal`'s rows written after the notification `after` (all of them for `null`), within the retention at `now`, oldest first, at most `limit`. */
33
+ unseen(session: Session, principal: string, after: string | null, now: number, limit: number): Promise<readonly StoredNotification[]>;
34
+ /** How many of `principal`'s rows within the retention at `now` were written after `after`. */
35
+ countAfter(session: Session, principal: string, after: string | null, now: number): Promise<number>;
36
+ }
37
+ export declare function notifications(): Notifications;