@fabrika/db 0.9.0-dev.6 → 0.9.0-dev.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +59 -11
  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 +55 -9
  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 +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +417 -158
  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-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1933 -168
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +8 -1
  35. package/src/testing-shared.ts +758 -140
  36. package/src/testing-sqlite.ts +212 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +159 -27
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +31 -9
  47. package/types/src/errors.d.ts +7 -4
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +18 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +165 -73
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +347 -23
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +4 -1
  70. package/types/src/testing-shared.d.ts +112 -23
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -1,3 +1,4 @@
1
+ import type { OperationNode } from 'kysely'
1
2
  import { inSet, isSafeInteger, type NameSet, nameSet, namesOf, ownEntry, ownKeys, parseList } from './builtins'
2
3
  import { QueryRefusedError } from './errors'
3
4
  import { isPlainIdentifier } from './identifier'
@@ -59,6 +60,8 @@ export interface TableShape {
59
60
  readonly joinable: Readonly<Record<string, JoinShape>>
60
61
  /** The `date` columns, which a read answers as `YYYY-MM-DD` text. */
61
62
  readonly dates: NameSet
63
+ /** The JSON columns, which a query selects but never compares or orders by. */
64
+ readonly json: NameSet
62
65
  }
63
66
 
64
67
  export interface JoinShape {
@@ -72,6 +75,8 @@ export interface JoinShape {
72
75
  export interface JoinState {
73
76
  readonly join: JoinShape
74
77
  readonly select: SelectState
78
+ /** The child's condition for the action the select holds, which the layer adds to the ON; never the builder's. */
79
+ readonly condition?: OperationNode
75
80
  }
76
81
 
77
82
  export interface SelectState {
@@ -84,18 +89,28 @@ export interface SelectState {
84
89
  readonly limit: number | undefined
85
90
  readonly offset: number | undefined
86
91
  readonly joins: readonly JoinState[]
92
+ /** A `where` named an `in` with an empty list, so no row matches; only an aggregate's filter takes it (`finishFilter`). */
93
+ readonly matchesNone: boolean
87
94
  }
88
95
 
89
96
  type Comparable<V> = Exclude<V, null | undefined>
90
97
  type Columns<Row> = keyof Row & string
98
+ /** The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`. */
99
+ export type ComparableColumn<Row> = { [K in Columns<Row>]: unknown extends Row[K] ? never : K }[Columns<Row>]
91
100
  type StringColumn<Row> = { [K in Columns<Row>]: Comparable<Row[K]> extends string ? K : never }[Columns<Row>]
92
- type NullableColumn<Row> = { [K in Columns<Row>]: null extends Row[K] ? K : never }[Columns<Row>]
101
+ type NullableColumn<Row> = { [K in ComparableColumn<Row>]: null extends Row[K] ? K : never }[ComparableColumn<Row>]
93
102
 
103
+ /**
104
+ * A `[column, operator, value]` condition on `Row`'s columns. A null test (`is`, `is not`) takes a nullable column only;
105
+ * the runtime knows no column's nullability, so an untyped condition that tests a column never null runs and matches no
106
+ * row (`is`) or every row (`is not`).
107
+ */
94
108
  export type ConditionTuple<Row> =
95
109
  | {
96
- [K in Columns<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]]
97
- }[Columns<Row>]
110
+ [K in ComparableColumn<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]]
111
+ }[ComparableColumn<Row>]
98
112
  | { [K in StringColumn<Row>]: readonly [K, PatternOperator | 'contains', string] }[StringColumn<Row>]
113
+ | { [K in NullableColumn<Row>]: readonly [K, NullOperator, null] }[NullableColumn<Row>]
99
114
 
100
115
  type Prefixed<C extends string, J> = { [K in keyof J & string as `${C}.${K}`]: J[K] }
101
116
  export type NoColumns = Record<never, never>
@@ -137,11 +152,20 @@ export class ScopedSelect<Row, Selected, Children> {
137
152
  return this.#next({ columns: names })
138
153
  }
139
154
 
140
- where<C extends Columns<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>
141
- where<C extends Columns<Row>>(column: C, operator: ListOperator, values: readonly Comparable<Row[C]>[]): ScopedSelect<Row, Selected, Children>
155
+ where<C extends ComparableColumn<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>
156
+ where<C extends ComparableColumn<Row>>(
157
+ column: C,
158
+ operator: ListOperator,
159
+ values: readonly Comparable<Row[C]>[],
160
+ ): ScopedSelect<Row, Selected, Children>
142
161
  where<C extends StringColumn<Row>>(column: C, operator: PatternOperator, pattern: string): ScopedSelect<Row, Selected, Children>
143
162
  where<C extends NullableColumn<Row>>(column: C, operator: NullOperator, value: null): ScopedSelect<Row, Selected, Children>
144
163
  where(column: string, operator: string, value: unknown): ScopedSelect<Row, Selected, Children> {
164
+ if (operator === 'in' && parseList(value, (item) => item)?.length === 0) {
165
+ // The column is still held to the shape: an empty list does not make a hidden one nameable.
166
+ comparableColumnOf(this.#shape, column, 'compares')
167
+ return this.#next({ matchesNone: true })
168
+ }
145
169
  return this.#withCondition(this.#parseCondition(column, operator, value))
146
170
  }
147
171
 
@@ -166,11 +190,11 @@ export class ScopedSelect<Row, Selected, Children> {
166
190
  return this.#withCondition(this.#parseCondition(column, 'contains', text))
167
191
  }
168
192
 
169
- orderBy(column: Columns<Row>, direction: 'asc' | 'desc' = 'asc'): ScopedSelect<Row, Selected, Children> {
193
+ orderBy(column: ComparableColumn<Row>, direction: 'asc' | 'desc' = 'asc'): ScopedSelect<Row, Selected, Children> {
170
194
  if (direction !== 'asc' && direction !== 'desc') {
171
195
  throw new QueryRefusedError('list_page', `orderBy direction must be 'asc' or 'desc'`)
172
196
  }
173
- return this.#next({ orderBy: [...this.#state.orderBy, { column: this.#column(column), direction }] })
197
+ return this.#next({ orderBy: [...this.#state.orderBy, { column: comparableColumnOf(this.#shape, column, 'orders by'), direction }] })
174
198
  }
175
199
 
176
200
  limit(limit: number): ScopedSelect<Row, Selected, Children> {
@@ -233,9 +257,21 @@ export function columnOf(shape: TableShape, name: unknown): string {
233
257
  return name
234
258
  }
235
259
 
260
+ /** A column the shape lets a query compare, order or aggregate by: `columnOf`, and never a JSON column. */
261
+ export function comparableColumnOf(shape: TableShape, name: unknown, use: string): string {
262
+ const column = columnOf(shape, name)
263
+ if (inSet(shape.json, column)) {
264
+ throw new QueryRefusedError(
265
+ 'invalid_argument',
266
+ `${column} of ${shape.table} is a JSON column, which the data layer never ${use}; read a path of it with ctx.sql (->>)`,
267
+ )
268
+ }
269
+ return column
270
+ }
271
+
236
272
  /** One `[column, operator, value]` condition over a caller's values, checked before anything reads it further. */
237
273
  export function parseCondition(shape: TableShape, column: unknown, operator: unknown, value: unknown): Compare | Contains {
238
- const name = columnOf(shape, column)
274
+ const name = comparableColumnOf(shape, column, 'compares')
239
275
  if (operator === 'contains') {
240
276
  if (typeof value !== 'string') {
241
277
  throw new QueryRefusedError('invalid_argument', 'contains takes a string')
@@ -280,12 +316,22 @@ export function startSelect<Row, Children>(shape: TableShape): ScopedSelect<Row,
280
316
  limit: undefined,
281
317
  offset: undefined,
282
318
  joins: [],
319
+ matchesNone: false,
283
320
  }
284
321
  return new ScopedSelect(selectToken, state, shape)
285
322
  }
286
323
 
287
- /** The description a callback returned; it must derive from the one it received. */
324
+ /** The description a callback returned; it must derive from the one it received, and an `in` names at least one value. */
288
325
  export function finishSelect<Row, Children>(built: unknown, start: ScopedSelect<Row, Row, Children>): SelectState {
326
+ const state = finishFilter(built, start)
327
+ if (state.matchesNone) {
328
+ throw new QueryRefusedError('invalid_argument', 'in needs a non-empty plain array of values')
329
+ }
330
+ return state
331
+ }
332
+
333
+ /** `finishSelect` for an aggregate's `where`, where an `in` with an empty list matches no row (`matchesNone`). */
334
+ export function finishFilter<Row, Children>(built: unknown, start: ScopedSelect<Row, Row, Children>): SelectState {
289
335
  if (!(built instanceof ScopedSelect)) {
290
336
  throw new QueryRefusedError('invalid_argument', 'the query callback must return the description it received')
291
337
  }
package/src/errors.ts CHANGED
@@ -29,11 +29,13 @@ export class CapabilityError extends Error {
29
29
 
30
30
  /**
31
31
  * Why the layer refused, as a closed catalog: a server log names the reason and its fixed text, never the message,
32
- * which can quote a value the request sent.
32
+ * which can quote a value the request sent. Each text is one string literal, however long: a concatenation keeps the
33
+ * whole catalog in an SPA bundle that imports this module (`web/__tests__/bundle.test.ts`).
33
34
  */
34
35
  export const QUERY_REFUSALS = {
35
36
  invalid_argument: 'a data-layer call took an argument of another shape than its type declares',
36
- invalid_value: 'a value cannot be bound: an invalid or out-of-range date, or a non-finite number',
37
+ invalid_value:
38
+ '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',
37
39
  invalid_name: 'a configured name (application, schema, table or file column) breaks its naming rule',
38
40
  unknown_column: 'a column the table does not declare, or one this operation may not set',
39
41
  unknown_table: 'a table src/db/tables.ts does not declare, or one no store, join or locator reaches',
@@ -46,7 +48,9 @@ export const QUERY_REFUSALS = {
46
48
  unexpected_row: 'the database answered a row in another shape than its migration declares',
47
49
  statement_shape: 'the compiled statement has a form the guard does not admit',
48
50
  scope_predicate: 'the scope predicate is missing or is not a top-level conjunct',
49
- list_page: 'a list limit, cursor or order outside what a page admits',
51
+ list_page: 'a list limit or order outside what a page admits',
52
+ 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",
53
+ too_many_rows: 'all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate',
50
54
  undeclared_reach: 'the site reaches data it did not declare (sql or unscoped, or their mode)',
51
55
  sql_template: 'ctx.sql was not called as one tagged template whose values are interpolated whole',
52
56
  sql_statement: 'ctx.sql runs one statement of an admitted kind, and none inside another',
@@ -58,7 +62,7 @@ export const QUERY_REFUSALS = {
58
62
  file_scan: "a scan verdict outside the scan job's lease",
59
63
  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',
60
64
  on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action",
61
- public_reach: "a public procedure updates, removes, locks or claims no row, and an insert's conflict writes nothing",
65
+ public_reach: "a public procedure updates, removes, locks or claims no row, reads none with all(), and an insert's conflict writes nothing",
62
66
  file_value:
63
67
  "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",
64
68
  file_scope: 'a file is referenced from another top-level scope than the one its first reference set',
@@ -3,13 +3,13 @@
3
3
  // and claims, locks and stamps the file in the write's own transaction. The file's row is `fabrika_files`
4
4
  // (`stored-files.ts`); the column is a foreign key to it, so a file some row references is never deleted.
5
5
 
6
- import { defineValue, ownDescriptor, ownKeys } from './builtins'
6
+ import { defineValue, hasOwn, inSet, type NameSet, nameSet, ownDescriptor, ownKeys } from './builtins'
7
7
  import { runFixedStatement, type Session } from './database'
8
8
  import type { Primitive } from './description'
9
9
  import { NotFoundError, QueryRefusedError } from './errors'
10
10
  import { fileHoldingOf, fileReference, holdsFile } from './file-references'
11
11
  import { isPlainIdentifier } from './identifier'
12
- import type { TableModel } from './policy'
12
+ import { includes, type ReadReach, readsAsAction, readsAsOneOf, type TableModel } from './policy'
13
13
  import { claimStoredFile, lockStoredFile, stampStoredFile, storedFilesMetadata } from './stored-files'
14
14
 
15
15
  /** Where a site's file references belong, and what claiming a pending one needs. */
@@ -24,17 +24,59 @@ export interface FileBinding {
24
24
  scans(kind: string): boolean
25
25
  }
26
26
 
27
- /** Whether a reference read with `action` lets its holder serve, open and copy the file: the table's or the column's read action. */
28
- function readsFile(model: TableModel, column: string, action: string): boolean {
29
- const own = Object.hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
30
- return own === undefined ? model.actions.read.includes(action) : own === action
27
+ /**
28
+ * Whether a reference read under `reach` (one action, or an `anyOf` endpoint's held actions that read the row) lets its
29
+ * holder serve, open and copy the file: a table read action, or one of the column's own read actions, that reads every answered
30
+ * row alone (`readsAsAction`), or a table read action among `held`, the actions a job holds over the whole application.
31
+ * When every action of the reach is a table read action, each answered row was admitted by one that alone reads it,
32
+ * so a column without its own read action is readable. A column with its own read actions is answered only under one of
33
+ * them (`visibleThrough`), so `held` never widens it. A table read with `'any'` admits whoever read the row: the
34
+ * store refused every other reader.
35
+ */
36
+ function readsFile(model: TableModel, column: string, reach: ReadReach, held: NameSet): boolean {
37
+ const own = hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
38
+ if (own !== undefined) {
39
+ return readsAsOneOf(model, own, reach)
40
+ }
41
+ if (model.actions.readAny || readsThroughEvery(model, reach)) {
42
+ return true
43
+ }
44
+ const reads = model.actions.read
45
+ for (let index = 0; index < reads.length; index++) {
46
+ const read = reads[index]
47
+ if (read !== undefined && (readsAsAction(model, read, reach) || inSet(held, read))) {
48
+ return true
49
+ }
50
+ }
51
+ return false
52
+ }
53
+
54
+ /** Whether the reach holds at least one action and each is one of the table's read actions. */
55
+ function readsThroughEvery(model: TableModel, reach: ReadReach): boolean {
56
+ const actions = reach.actions
57
+ for (let index = 0; index < actions.length; index++) {
58
+ if (!includes(model.actions.read, actions[index])) {
59
+ return false
60
+ }
61
+ }
62
+ return actions.length > 0
31
63
  }
32
64
 
65
+ const NONE_HELD: NameSet = nameSet([])
66
+
33
67
  /**
34
- * Puts a file reference in each file column of `rows`, read with `action` in `session`: one statement loads every
35
- * file's metadata. Without a binding (a store's own runner) the columns keep their ids.
68
+ * Puts a file reference in each file column of `rows`, read under `reach` in `session`: one statement loads every
69
+ * file's metadata. Without a binding (a store's own runner) the columns keep their ids. `held` (a queue claim's) adds
70
+ * the actions the site holds over the whole application: a reference is readable when one of them reads the table.
36
71
  */
37
- export async function answerFiles<R>(model: TableModel, binding: FileBinding | undefined, session: Session, rows: R[], action: string): Promise<R[]> {
72
+ export async function answerFiles<R>(
73
+ model: TableModel,
74
+ binding: FileBinding | undefined,
75
+ session: Session,
76
+ rows: R[],
77
+ reach: ReadReach,
78
+ held: NameSet = NONE_HELD,
79
+ ): Promise<R[]> {
38
80
  const columns = ownKeys(model.files)
39
81
  if (binding === undefined || columns.length === 0 || rows.length === 0) {
40
82
  return rows
@@ -62,7 +104,7 @@ export async function answerFiles<R>(model: TableModel, binding: FileBinding | u
62
104
  if (meta === undefined) {
63
105
  throw new QueryRefusedError('unexpected_row', `${model.name}.${column} references a file that is not stored`)
64
106
  }
65
- defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, action)))
107
+ defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, reach, held)))
66
108
  }
67
109
  }
68
110
  return rows
package/src/framework.ts CHANGED
@@ -22,9 +22,12 @@ export type { FileBinding } from './file-columns'
22
22
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references'
23
23
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
24
24
  export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
25
- export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
25
+ export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes'
26
+ export type { NewNotification, NotificationAbout, Notifications, StoredNotification } from './notifications'
26
27
  export type { DataAccess, DataHandles, DataSite } from './orm'
27
- export type { FrameworkTables, Locator, ProvisionalBinding } from './registry'
28
+ export type { PushBinding, PushInboxSubscription, PushRecordOutcome, PushSubscriptionKeys, PushSubscriptions } from './push-subscriptions'
29
+ export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry'
30
+ export type { RequestReceipt, RequestReceipts } from './request-receipts'
28
31
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
29
32
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files'
30
33