@fabrika/db 0.9.0-dev.69 → 0.9.0-dev.70

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-dev.69",
3
+ "version": "0.9.0-dev.70",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/testing.ts",
@@ -96,9 +96,9 @@
96
96
  "test": "bun test"
97
97
  },
98
98
  "dependencies": {
99
- "@fabrika/auth-core": "0.9.0-dev.69",
100
- "@fabrika/platform": "0.9.0-dev.69",
101
- "@fabrika/platform-node": "0.9.0-dev.69",
99
+ "@fabrika/auth-core": "0.9.0-dev.70",
100
+ "@fabrika/platform": "0.9.0-dev.70",
101
+ "@fabrika/platform-node": "0.9.0-dev.70",
102
102
  "kysely": "0.29.6",
103
103
  "kysely-postgres-js": "5.0.1",
104
104
  "zod": "^3.25.76"
@@ -95,8 +95,20 @@ export interface SelectState {
95
95
 
96
96
  type Comparable<V> = Exclude<V, null | undefined>
97
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>]
98
+ declare const declaredJson: unique symbol
99
+
100
+ /** Type-only: the JSON columns a row types by their declared schema (`json`). No row value has the property. */
101
+ export interface DeclaredJson<C extends string> {
102
+ readonly [declaredJson]?: C
103
+ }
104
+
105
+ type DeclaredJsonOf<Row> = typeof declaredJson extends keyof Row ? Row extends DeclaredJson<infer C> ? C : never : never
106
+
107
+ /**
108
+ * The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`, or its
109
+ * declared schema's output (`DeclaredJson`).
110
+ */
111
+ export type ComparableColumn<Row> = { [K in Columns<Row>]: unknown extends Row[K] ? never : K extends DeclaredJsonOf<Row> ? never : K }[Columns<Row>]
100
112
  type StringColumn<Row> = { [K in Columns<Row>]: Comparable<Row[K]> extends string ? K : never }[Columns<Row>]
101
113
  type NullableColumn<Row> = { [K in ComparableColumn<Row>]: null extends Row[K] ? K : never }[ComparableColumn<Row>]
102
114
 
package/src/errors.ts CHANGED
@@ -35,7 +35,7 @@ export class CapabilityError extends Error {
35
35
  export const QUERY_REFUSALS = {
36
36
  invalid_argument: 'a data-layer call took an argument of another shape than its type declares',
37
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',
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, or a value of a JSON column that the schema its policy declares refuses',
39
39
  invalid_name: 'a configured name (application, schema, table or file column) breaks its naming rule',
40
40
  unknown_column: 'a column the table does not declare, or one this operation may not set',
41
41
  unknown_table: 'a table src/db/tables.ts does not declare, or one no store, join or locator reaches',
@@ -45,7 +45,7 @@ export const QUERY_REFUSALS = {
45
45
  read_only: 'a read-only request, query or table was asked to write or lock a row',
46
46
  ended: 'the transaction, invocation or handle has ended or belongs to other work',
47
47
  statement_failed: 'a statement of this transaction failed, so nothing it wrote commits',
48
- unexpected_row: 'the database answered a row in another shape than its migration declares',
48
+ unexpected_row: 'the database answered a row in another shape than its migration declares, or a JSON value the schema its policy declares refuses',
49
49
  statement_shape: 'the compiled statement has a form the guard does not admit',
50
50
  scope_predicate: 'the scope predicate is missing or is not a top-level conjunct',
51
51
  list_page: 'a list limit or order outside what a page admits',
package/src/json.ts CHANGED
@@ -3,8 +3,10 @@
3
3
  // an untyped text parameter into `jsonb`, SQLite stores the text. A read answers the parsed value: `Bun.SQL` decodes
4
4
  // `jsonb` itself, and `sqliteJson` parses SQLite's text. JS `null` is SQL NULL in both directions, so a top-level JSON
5
5
  // `null` written by `ctx.sql` reads as `null` too. A JSON column is never compared, ordered, grouped or aggregated by
6
- // the layer; a path condition is `ctx.sql`'s (`->>`).
6
+ // the layer; a path condition is `ctx.sql`'s (`->>`). A column the policy declares a zod schema for (`json`) is checked
7
+ // against it: a write's value is parsed before it is serialized, and every value a read answers is parsed again.
7
8
 
9
+ import { z } from 'zod/v4'
8
10
  import { hasOwn, isArray, OBJECT_PROTOTYPE, ownDescriptor, ownNames, ownSymbols, parseList, prototypeOf } from './builtins'
9
11
  import { QueryRefusedError } from './errors'
10
12
 
@@ -18,6 +20,54 @@ export type JsonValue = string | number | boolean | null | readonly JsonValue[]
18
20
  /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
19
21
  export type JsonColumnValue = Exclude<JsonValue, null>
20
22
 
23
+ /** The zod schema a table policy declares for a JSON column (`json: { <column>: schema }`); its output is JSON. */
24
+ export type JsonSchema = z.core.$ZodType
25
+
26
+ /**
27
+ * What a failed parse says of the value: the first issue's code, and the type it expected. No path, message or key: a
28
+ * key or a message can quote the value, as a row error of `ctx.sql` never does.
29
+ */
30
+ function issueText(error: z.core.$ZodError): string {
31
+ const [issue] = error.issues
32
+ if (issue === undefined) {
33
+ return 'refused'
34
+ }
35
+ return issue.code === 'invalid_type' ? `${issue.code}, expected ${issue.expected}` : issue.code
36
+ }
37
+
38
+ /**
39
+ * The text a column with a declared schema binds for a written value, or `null` (SQL NULL) where the schema answers
40
+ * `null`. The value is first read as `jsonInput` reads any JSON column's (plain data only, so no getter, `toJSON` or
41
+ * class instance reaches the schema), then parsed, and the schema's output is what is stored. A value the schema
42
+ * refuses, and an output the schema would refuse on read, are `invalid_value` before anything is sent.
43
+ */
44
+ export function schemaInput(schema: JsonSchema, value: unknown, where: string): string | null {
45
+ const parsed = z.safeParse(schema, parse(jsonInput(value, where)))
46
+ if (!parsed.success) {
47
+ throw new QueryRefusedError('invalid_value', `${where} does not match its JSON schema (${issueText(parsed.error)})`)
48
+ }
49
+ if (parsed.data === null) {
50
+ return null
51
+ }
52
+ const text = jsonInput(parsed.data, where)
53
+ if (!z.safeParse(schema, parse(text)).success) {
54
+ throw new QueryRefusedError('invalid_value', `${where}: its JSON schema refuses its own output, which every read parses again`)
55
+ }
56
+ return text
57
+ }
58
+
59
+ /**
60
+ * A read value of a column with a declared schema, parsed by it: a stored value the schema refuses (written by
61
+ * `ctx.sql`, a migration, or before the schema tightened) is `unexpected_row`, so no handler sees it.
62
+ */
63
+ export function schemaOutput(schema: JsonSchema, value: unknown, where: string): unknown {
64
+ const parsed = z.safeParse(schema, value)
65
+ if (!parsed.success) {
66
+ throw new QueryRefusedError('unexpected_row', `${where} came back in a shape its JSON schema refuses (${issueText(parsed.error)})`)
67
+ }
68
+ return parsed.data
69
+ }
70
+
21
71
  /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
22
72
  export const MAX_JSON_DEPTH = 64
23
73
 
@@ -105,6 +155,19 @@ export function jsonInput(value: unknown, where: string): string {
105
155
  return written(value, where, 0)
106
156
  }
107
157
 
158
+ /** Whether `value` is one a JSON column takes: a JSON value `jsonInput` serializes, other than `null`. */
159
+ export function isJsonColumnValue(value: unknown): value is JsonColumnValue {
160
+ if (value === null) {
161
+ return false
162
+ }
163
+ try {
164
+ written(value, '', 0)
165
+ return true
166
+ } catch {
167
+ return false
168
+ }
169
+ }
170
+
108
171
  /**
109
172
  * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
110
173
  * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
package/src/orm-types.ts CHANGED
@@ -13,11 +13,13 @@ import type {
13
13
  DimensionOf,
14
14
  DimensionTableName,
15
15
  InsertValues,
16
+ JsonSchemasOf,
16
17
  ListDimensionOf,
17
18
  ParentOf,
18
19
  ReadsAny,
19
20
  Tables,
20
21
  UpdateValues,
22
+ WithJson,
21
23
  } from './policy'
22
24
  import type { AggregateRow, AggregateSpec } from './store'
23
25
  import type { VocabularyContainerOf } from './vocabulary-tables'
@@ -74,8 +76,11 @@ type ColumnsWrittenBy<C, A> = { [K in keyof C]: [A] extends [WriteActionsOf<C[K]
74
76
  type UpdatesOf<DB, P, T extends keyof DB> =
75
77
  & { readonly [A in ActionOf<P, T, 'update'>]: UpdateValues<DB, P, T> }
76
78
  & {
77
- readonly [A in ColumnWriteAction<ColumnPoliciesOf<P, T>>]: Flat<
78
- Pick<Updateable<DB[T]>, ColumnsWrittenBy<ColumnPoliciesOf<P, T>, A> & keyof Updateable<DB[T]>>
79
+ readonly [A in ColumnWriteAction<ColumnPoliciesOf<P, T>>]: WithJson<
80
+ Flat<Pick<Updateable<DB[T]>, ColumnsWrittenBy<ColumnPoliciesOf<P, T>, A> & keyof Updateable<DB[T]>>>,
81
+ JsonSchemasOf<P, T>,
82
+ DB[T],
83
+ 'input'
79
84
  >
80
85
  }
81
86
 
@@ -135,7 +140,7 @@ type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> =
135
140
  readonly readsAny: ReadsAny<P, T>
136
141
  readonly appRead: AppActionsOf<P, T, 'appRead'>
137
142
  readonly appCount: AppActionsOf<P, T, 'appCount'>
138
- readonly row: WithFiles<RowType<DB[T]>, FileColumnsOf<P, T>>
143
+ readonly row: WithJson<WithFiles<RowType<DB[T]>, FileColumnsOf<P, T>>, JsonSchemasOf<P, T>, DB[T], 'output'>
139
144
  readonly reads: ColumnReadsOf<P, T>
140
145
  readonly conditioned: ConditionedOf<P, T>
141
146
  readonly insert: WithFiles<InsertValues<DB, P, T>, FileColumnsOf<P, T>>
package/src/policy.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { READ_ANY } from '@fabrika/auth-core'
2
- import type { Insertable, Selectable, SelectType, Updateable } from 'kysely'
2
+ import type { Insertable, InsertType, Selectable, SelectType, Updateable } from 'kysely'
3
+ import { z } from 'zod/v4'
3
4
  import {
4
5
  freeze,
5
6
  hasOwn,
@@ -27,8 +28,10 @@ import {
27
28
  singleForeignKey,
28
29
  splitPath,
29
30
  } from './conditions'
31
+ import type { DeclaredJson } from './description'
30
32
  import { PolicyError } from './errors'
31
33
  import { isPlainIdentifier } from './identifier'
34
+ import type { JsonColumnValue, JsonSchema } from './json'
32
35
  import type { Unavailable } from './orm-types'
33
36
  export type { RowOf } from './orm-types'
34
37
  import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
@@ -204,6 +207,35 @@ export interface ConfersPolicy<Col extends string> {
204
207
  /** A table's file columns: column → the name of a file kind of the contract (`c.files`). */
205
208
  export type FilePolicies<Col extends string> = { readonly [C in Col]?: string }
206
209
 
210
+ /** A table's JSON columns with a declared shape: column → a zod schema whose output is JSON. */
211
+ export type JsonPolicies<Col extends string> = { readonly [C in Col]?: JsonSchema }
212
+
213
+ /** The JSON columns of a generated row type: those whose write type is a JSON value (`JsonColumnValue`). */
214
+ export type JsonColumn<Row> = {
215
+ [K in keyof Row & string]: [Exclude<InsertType<Row[K]>, null | undefined>] extends [JsonColumnValue]
216
+ ? [JsonColumnValue] extends [Exclude<InsertType<Row[K]>, null | undefined>] ? K : never
217
+ : never
218
+ }[keyof Row & string]
219
+
220
+ /** The schemas table `T`'s policy declares for its JSON columns (`json`); none when it declares none. */
221
+ export type JsonSchemasOf<P, T> = PolicyOf<P, T> extends { readonly json: infer J } ? J : Record<never, never>
222
+
223
+ /** `null` where column `K` of the generated row is nullable. */
224
+ type NullOf<Row, K> = K extends keyof Row ? (null extends InsertType<Row[K]> ? null : never) : never
225
+
226
+ /**
227
+ * A row (`'output'`) or a write (`'input'`) of a table whose policy declares JSON schemas `J`: each declared column is
228
+ * the schema's output or input, and `null` where the column is nullable. A row also carries the declared columns in
229
+ * `DeclaredJson`, which keeps them out of a condition and an order (`ComparableColumn`).
230
+ */
231
+ export type WithJson<R, J, Row, Io extends 'input' | 'output'> = [keyof J] extends [never] ? R
232
+ :
233
+ & {
234
+ [K in keyof R]: K extends keyof J ? J[K] extends JsonSchema ? (Io extends 'output' ? z.output<J[K]> : z.input<J[K]>) | NullOf<Row, K> : R[K]
235
+ : R[K]
236
+ }
237
+ & (Io extends 'output' ? DeclaredJson<keyof J & string> : unknown)
238
+
207
239
  /**
208
240
  * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
209
241
  * without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
@@ -354,6 +386,8 @@ export interface TableModel {
354
386
  readonly booleans: NameSet
355
387
  /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
356
388
  readonly json: NameSet
389
+ /** The JSON columns the policy declares a schema for: each write is parsed by it, and each read value too. */
390
+ readonly jsonSchemas: Readonly<Record<string, JsonSchema>>
357
391
  /** The columns the column list declares NOT NULL. */
358
392
  readonly notNull: NameSet
359
393
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
@@ -646,6 +680,7 @@ const POLICY_FIELDS = nameSet([
646
680
  'columns',
647
681
  'queue',
648
682
  'files',
683
+ 'json',
649
684
  'confers',
650
685
  'when',
651
686
  'relationWhen',
@@ -879,6 +914,8 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
879
914
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
880
915
  const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
881
916
  const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
917
+ const jsonPolicy = ownEntry(policy, 'json')
918
+ const jsonSchemas = jsonPolicy === undefined ? freeze({}) : parseJsonSchemas(table, jsonPolicy, column, json)
882
919
  const notNull = parseColumnSet(table, ownEntry(entry, 'notNull'), column, 'notNull')
883
920
  const queue = queueInput === undefined
884
921
  ? undefined
@@ -909,6 +946,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
909
946
  timestamps,
910
947
  booleans,
911
948
  json,
949
+ jsonSchemas,
912
950
  notNull,
913
951
  foreignKeys,
914
952
  view,
@@ -975,6 +1013,44 @@ function parseFileColumns(
975
1013
  return freeze(parsed)
976
1014
  }
977
1015
 
1016
+ /**
1017
+ * The schemas of `json`: each names a JSON column of the column list, with a zod schema whose output is JSON, which
1018
+ * `z.toJSONSchema` can describe. A `Date`, a `bigint`, a `Map`, a transform or `z.custom()` is refused: the layer
1019
+ * stores the output and parses it again on read, so it must be a JSON value the schema accepts.
1020
+ */
1021
+ function parseJsonSchemas(
1022
+ table: string,
1023
+ input: unknown,
1024
+ column: (name: unknown, field: string) => string,
1025
+ jsonColumns: NameSet,
1026
+ ): Readonly<Record<string, JsonSchema>> {
1027
+ const schemas = plainRecord(input, `${table}: json`)
1028
+ const names = ownKeys(schemas)
1029
+ if (names.length === 0) {
1030
+ throw new PolicyError(`${table}: json declares no column; remove it or name a JSON column and its zod schema`)
1031
+ }
1032
+ const parsed: Record<string, JsonSchema> = {}
1033
+ for (let index = 0; index < names.length; index++) {
1034
+ const name = column(names[index], 'json')
1035
+ if (!inSet(jsonColumns, name)) {
1036
+ const listed = namesOf(jsonColumns).join(', ') || 'none'
1037
+ throw new PolicyError(`${table}: json names ${name}, which is not a JSON column (jsonb, or JSONB on SQLite; JSON columns: ${listed})`)
1038
+ }
1039
+ const schema = ownEntry(schemas, name)
1040
+ if (!(schema instanceof z.core.$ZodType)) {
1041
+ throw new PolicyError(`${table}: json.${name} is not a zod schema (import z from 'zod/v4')`)
1042
+ }
1043
+ try {
1044
+ z.toJSONSchema(schema, { io: 'output' })
1045
+ } catch (error) {
1046
+ const reason = error instanceof Error ? error.message : 'it cannot be described'
1047
+ throw new PolicyError(`${table}: json.${name}'s schema answers a value that is not JSON (${reason})`)
1048
+ }
1049
+ setOwn(parsed, name, schema)
1050
+ }
1051
+ return freeze(parsed)
1052
+ }
1053
+
978
1054
  /**
979
1055
  * A column's own write actions. A table update action may be one of them: it then writes the column beside its update
980
1056
  * list. Naming exactly the table's update actions says what `update` says, so that form is refused.
@@ -3148,10 +3224,14 @@ type RestrictedColumns<P, T> = [ColumnPoliciesOf<P, T>] extends [never] ? never
3148
3224
  }[keyof ColumnPoliciesOf<P, T>]
3149
3225
 
3150
3226
  /** A row of table `T` as a store reads it, by the table's read action. */
3151
- export type PolicyRow<DB, P, T> = T extends keyof DB ? Flat<Omit<Selectable<DB[T]>, RestrictedColumns<P, T>>> : never
3152
- export type InsertValues<DB, P, T> = T extends keyof DB ? Flat<Pick<Insertable<DB[T]>, ListedColumns<P, T, 'insert'> & keyof Insertable<DB[T]>>>
3227
+ export type PolicyRow<DB, P, T> = T extends keyof DB
3228
+ ? WithJson<Flat<Omit<Selectable<DB[T]>, RestrictedColumns<P, T>>>, JsonSchemasOf<P, T>, DB[T], 'output'>
3229
+ : never
3230
+ export type InsertValues<DB, P, T> = T extends keyof DB
3231
+ ? WithJson<Flat<Pick<Insertable<DB[T]>, ListedColumns<P, T, 'insert'> & keyof Insertable<DB[T]>>>, JsonSchemasOf<P, T>, DB[T], 'input'>
3153
3232
  : never
3154
- export type UpdateValues<DB, P, T> = T extends keyof DB ? Flat<Pick<Updateable<DB[T]>, ListedColumns<P, T, 'update'> & keyof Updateable<DB[T]>>>
3233
+ export type UpdateValues<DB, P, T> = T extends keyof DB
3234
+ ? WithJson<Flat<Pick<Updateable<DB[T]>, ListedColumns<P, T, 'update'> & keyof Updateable<DB[T]>>>, JsonSchemasOf<P, T>, DB[T], 'input'>
3155
3235
  : never
3156
3236
 
3157
3237
  /** The values a store inserts into table `T` of a `defineTables` result: `TableInsert<typeof tables, 'deals'>`. */
package/src/store.ts CHANGED
@@ -92,7 +92,7 @@ import { webhookTables } from './framework-tables'
92
92
  import type { ForeignKeyPair, GuardContext, RootKind, ViewAccessLink, ViewParentLink } from './guard'
93
93
  import { fencedTransaction, jobLeases } from './job-leases'
94
94
  import { jobWakes, leaseProjection } from './job-wakes'
95
- import { jsonInput } from './json'
95
+ import { jsonInput, type JsonSchema, schemaInput } from './json'
96
96
  import { linksPredicate, type LinkValue, linkValues } from './links'
97
97
  import {
98
98
  acknowledgement,
@@ -230,7 +230,7 @@ export function dialectOf(context: TableContext): SqlDialect {
230
230
 
231
231
  /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
232
232
  export function rowColumnsOf(model: TableModel): RowColumns {
233
- return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans, json: model.json }
233
+ return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans, json: model.json, jsonSchemas: model.jsonSchemas }
234
234
  }
235
235
 
236
236
  /** A timestamp's bound value on SQLite: its stored UTC text. Postgres takes a `Date` or ISO text as it is. */
@@ -1547,7 +1547,7 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
1547
1547
  continue
1548
1548
  }
1549
1549
  if (inSet(model.json, key)) {
1550
- copied.set(key, value === null ? null : jsonInput(value, `${table}.${key}`))
1550
+ copied.set(key, value === null ? null : jsonText(model, key, value))
1551
1551
  continue
1552
1552
  }
1553
1553
  if (value !== null && !isPrimitive(value)) {
@@ -1558,6 +1558,13 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
1558
1558
  return copied
1559
1559
  }
1560
1560
 
1561
+ /** A JSON column's bound text: its declared schema's output, or the value itself where none is declared. */
1562
+ function jsonText(model: TableModel, column: string, value: unknown): string | null {
1563
+ const schema = ownEntry(model.jsonSchemas, column)
1564
+ const where = `${model.name}.${column}`
1565
+ return schema === undefined ? jsonInput(value, where) : schemaInput(schema, value, where)
1566
+ }
1567
+
1561
1568
  /** A day's or a timestamp's text, checked before it is bound; any other column's text as it is. */
1562
1569
  function temporalText(model: TableModel, column: string, value: string): string {
1563
1570
  if (inSet(model.dates, column)) {
@@ -1676,11 +1683,29 @@ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1676
1683
  }
1677
1684
  return nameSet(names)
1678
1685
  }
1686
+ const jsonSchemas: Record<string, JsonSchema> = {}
1687
+ const owned = ownKeys(own.jsonSchemas)
1688
+ for (let index = 0; index < owned.length; index++) {
1689
+ const column = owned[index] ?? ''
1690
+ const schema = ownEntry(own.jsonSchemas, column)
1691
+ if (schema !== undefined) setOwn(jsonSchemas, column, schema)
1692
+ }
1693
+ for (let index = 0; index < state.joins.length; index++) {
1694
+ const table = state.joins[index]?.join.shape.table ?? ''
1695
+ const schemas = ownEntry(context.children, table)?.jsonSchemas ?? {}
1696
+ const columns = ownKeys(schemas)
1697
+ for (let position = 0; position < columns.length; position++) {
1698
+ const column = columns[position] ?? ''
1699
+ const schema = ownEntry(schemas, column)
1700
+ if (schema !== undefined) setOwn(jsonSchemas, `${table}.${column}`, schema)
1701
+ }
1702
+ }
1679
1703
  return {
1680
1704
  days: joined((columns) => columns.days),
1681
1705
  timestamps: joined((columns) => columns.timestamps),
1682
1706
  booleans: joined((columns) => columns.booleans),
1683
1707
  json: joined((columns) => columns.json),
1708
+ jsonSchemas: freeze(jsonSchemas),
1684
1709
  }
1685
1710
  }
1686
1711
 
@@ -2227,6 +2252,7 @@ export async function aggregateRows<Row, O>(
2227
2252
  timestamps: aggregated(own.timestamps, columns),
2228
2253
  booleans: aggregated(own.booleans, columns),
2229
2254
  json: nameSet([]),
2255
+ jsonSchemas: freeze({}),
2230
2256
  }, rows)
2231
2257
  return dialect === 'postgres' ? answered : sqliteAggregates(context.model.name, columns, answered)
2232
2258
  }
package/src/temporal.ts CHANGED
@@ -9,10 +9,10 @@
9
9
  // and a boolean as 0 or 1: `storedTimestamp` is what a write binds and `answerRows` turns both back into what Postgres's
10
10
  // driver answers.
11
11
 
12
- import { defineValue, inSet, type NameSet, ownDescriptor, ownKeys } from './builtins'
12
+ import { defineValue, inSet, type NameSet, ownDescriptor, ownEntry, ownKeys } from './builtins'
13
13
  import type { SqlDialect } from './database'
14
14
  import { QueryRefusedError } from './errors'
15
- import { sqliteJson } from './json'
15
+ import { type JsonSchema, schemaOutput, sqliteJson } from './json'
16
16
 
17
17
  /** The text Postgres prints for a day in 0001–9999 under its default `DateStyle` (ISO). */
18
18
  const DAY_TEXT = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/
@@ -147,6 +147,8 @@ export interface RowColumns {
147
147
  readonly booleans: NameSet
148
148
  /** JSON columns: the parsed value (SQLite answers its text). */
149
149
  readonly json: NameSet
150
+ /** The JSON columns with a declared schema, by the name each arrives under: a read value is parsed by it. */
151
+ readonly jsonSchemas: Readonly<Record<string, JsonSchema>>
150
152
  }
151
153
 
152
154
  function unexpected(where: string, expected: string): QueryRefusedError {
@@ -182,9 +184,35 @@ function sqliteValue(columns: RowColumns, where: string, key: string, value: unk
182
184
  * values on both dialects.
183
185
  */
184
186
  export function answerRows<R>(dialect: SqlDialect, table: string, columns: RowColumns, rows: R[]): R[] {
185
- if (dialect === 'postgres') {
186
- return answerDays(table, columns.days, rows)
187
+ return answerJson(table, columns.jsonSchemas, dialect === 'postgres' ? answerDays(table, columns.days, rows) : answerSqlite(table, columns, rows))
188
+ }
189
+
190
+ /** Each value of a JSON column with a declared schema, in place, as the schema parses it; SQL NULL stays `null`. */
191
+ function answerJson<R>(table: string, schemas: Readonly<Record<string, JsonSchema>>, rows: R[]): R[] {
192
+ const keys = ownKeys(schemas)
193
+ if (keys.length === 0) {
194
+ return rows
195
+ }
196
+ for (let index = 0; index < rows.length; index++) {
197
+ const row = rows[index]
198
+ if (typeof row !== 'object' || row === null) {
199
+ continue
200
+ }
201
+ for (let position = 0; position < keys.length; position++) {
202
+ const key = keys[position] ?? ''
203
+ const schema = ownEntry(schemas, key)
204
+ const descriptor = ownDescriptor(row, key)
205
+ const value: unknown = descriptor?.value
206
+ if (schema === undefined || descriptor === undefined || value === null) {
207
+ continue
208
+ }
209
+ defineValue(row, key, schemaOutput(schema, value, `${table}.${key}`))
210
+ }
187
211
  }
212
+ return rows
213
+ }
214
+
215
+ function answerSqlite<R>(table: string, columns: RowColumns, rows: R[]): R[] {
188
216
  for (let index = 0; index < rows.length; index++) {
189
217
  const row = rows[index]
190
218
  if (typeof row !== 'object' || row === null) {
@@ -3,27 +3,127 @@
3
3
  // probe. Not a subpath: each kit refuses a production process before it imports this module.
4
4
 
5
5
  import { createHash } from 'node:crypto'
6
+ import { z } from 'zod/v4'
6
7
  import { type ApplicationRowRefusal, applicationRowRefusalText, type ApplicationRowsPlan, planApplicationRows } from './application-rows'
7
- import { inSet, namesOf } from './builtins'
8
+ import { inSet, namesOf, ownEntry } from './builtins'
8
9
  import type { Database } from './database'
9
- import type { Primitive } from './description'
10
- import { jsonInput } from './json'
10
+ import { isPrimitive, type Primitive } from './description'
11
+ import { isJsonColumnValue, type JsonColumnValue, jsonInput, type JsonSchema } from './json'
11
12
  import { FILES_TABLE } from './migrations'
12
13
  import { type Container, type ForeignKey, modelOf, type TableModel, type TableModels, tableModels, type Tables } from './policy'
13
14
  import { refuseInProduction } from './production'
14
15
  import { frameworkSideOf } from './registry'
15
16
  import type { TableProbe } from './store'
16
17
 
17
- /** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
18
- export type SampleValue = Primitive | null
18
+ /**
19
+ * A value a test row holds in a column; `null` for a nullable column the fixture left empty. Only a JSON column holds
20
+ * an object or an array: the sample of one whose policy declares a schema (`jsonSample`).
21
+ */
22
+ export type SampleValue = Primitive | JsonColumnValue | null
19
23
 
20
24
  /**
21
25
  * A seeded value as a backend binds it: a JSON column's value as the JSON text the layer would write for it, so a
22
26
  * seeded row and the kits' cases that write the same value through the layer hold the same JSON.
23
27
  */
24
- export function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): SampleValue {
25
- if (value === null || !columns.some((column) => column.table === table && column.name === name && column.json)) return value
26
- return jsonInput(value, `${table}.${name}`)
28
+ export function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): Primitive | null {
29
+ if (value !== null && columns.some((column) => column.table === table && column.name === name && column.json)) {
30
+ return jsonInput(value, `${table}.${name}`)
31
+ }
32
+ if (value === null || isPrimitive(value)) return value
33
+ throw new SeedLimitError(`the isolation fixture cannot write an object or an array into ${table}.${name}, which is no JSON column`)
34
+ }
35
+
36
+ /** A string of a JSON Schema `format` zod emits, which a plain sample would not pass. */
37
+ const FORMAT_SAMPLES: Readonly<Record<string, string>> = {
38
+ uuid: '00000000-0000-4000-8000-000000000000',
39
+ email: 'sample@example.test',
40
+ uri: 'https://example.test/',
41
+ 'date-time': '2026-01-01T00:00:00.000Z',
42
+ date: '2026-01-01',
43
+ time: '12:00:00',
44
+ duration: 'PT1H',
45
+ }
46
+
47
+ /** How deep a sample follows nested schemas and references: a recursive schema's sample stops at its optional members. */
48
+ const MAX_SAMPLE_DEPTH = 16
49
+
50
+ /**
51
+ * A value JSON Schema `node` admits, built the plain way (`const`, a default, the first enum member or branch, an
52
+ * object's required members, the least array, a string or number its bounds admit); `undefined` where none is built.
53
+ */
54
+ function jsonSchemaSample(node: z.core.JSONSchema._JSONSchema, root: z.core.JSONSchema.JSONSchema, depth: number): unknown {
55
+ if (typeof node === 'boolean') return node ? 'sample' : undefined
56
+ if (depth > MAX_SAMPLE_DEPTH) return undefined
57
+ if (node.$ref !== undefined) {
58
+ const name = node.$ref.startsWith('#/$defs/') ? node.$ref.slice('#/$defs/'.length) : undefined
59
+ const target = node.$ref === '#' ? root : name === undefined ? undefined : root.$defs?.[name]
60
+ return target === undefined ? undefined : jsonSchemaSample(target, root, depth + 1)
61
+ }
62
+ if (node.const !== undefined) return node.const
63
+ if (node.default !== undefined) return node.default
64
+ if (node.enum !== undefined) return node.enum[0]
65
+ for (const branch of node.anyOf ?? node.oneOf ?? []) {
66
+ const sample = jsonSchemaSample(branch, root, depth + 1)
67
+ if (sample !== undefined) return sample
68
+ }
69
+ if (node.allOf !== undefined) {
70
+ const parts = node.allOf.map((part) => jsonSchemaSample(part, root, depth + 1))
71
+ return parts.every((part) => typeof part === 'object' && part !== null && !Array.isArray(part)) ? Object.assign({}, ...parts) : parts[0]
72
+ }
73
+ switch (node.type) {
74
+ case 'object': {
75
+ const sample: Record<string, unknown> = {}
76
+ for (const key of node.required ?? []) {
77
+ const member = node.properties?.[key]
78
+ const value = member === undefined ? undefined : jsonSchemaSample(member, root, depth + 1)
79
+ if (value === undefined) return undefined
80
+ sample[key] = value
81
+ }
82
+ return sample
83
+ }
84
+ case 'array': {
85
+ if (node.prefixItems !== undefined) return node.prefixItems.map((item) => jsonSchemaSample(item, root, depth + 1))
86
+ const items = node.items
87
+ const item = items === undefined || Array.isArray(items) ? 'sample' : jsonSchemaSample(items, root, depth + 1)
88
+ return Array.from({ length: node.minItems ?? 0 }, () => item)
89
+ }
90
+ case 'string': {
91
+ if (node.format !== undefined) return FORMAT_SAMPLES[node.format]
92
+ const least = node.minLength ?? 0
93
+ return 'sample'.padEnd(least, 'x').slice(0, Math.max(least, node.maxLength ?? 6))
94
+ }
95
+ case 'number':
96
+ case 'integer': {
97
+ const least = node.minimum ?? (node.exclusiveMinimum === undefined ? undefined : node.exclusiveMinimum + 1)
98
+ const most = node.maximum ?? (node.exclusiveMaximum === undefined ? undefined : node.exclusiveMaximum - 1)
99
+ const value = least ?? (most !== undefined && most < 0 ? most : 0)
100
+ return node.type === 'integer' ? Math.ceil(value) : value
101
+ }
102
+ case 'boolean':
103
+ return false
104
+ case 'null':
105
+ return null
106
+ default:
107
+ return 'sample'
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The sample of a JSON column whose policy declares `schema`: built from the schema's JSON Schema and parsed by the
113
+ * schema, which answers the value the layer would store. A `SeedLimitError` when the sample does not pass (a pattern,
114
+ * a refinement), as for a type the fixture has no sample of.
115
+ */
116
+ export function jsonSample(schema: JsonSchema, where: string): JsonColumnValue {
117
+ const described = z.toJSONSchema(schema, { io: 'input' })
118
+ const parsed = z.safeParse(schema, jsonSchemaSample(described, described, 0))
119
+ if (!parsed.success) {
120
+ throw new SeedLimitError(`the isolation fixture cannot fill ${where}: the sample it builds from its JSON schema does not pass it`)
121
+ }
122
+ const value: unknown = parsed.data
123
+ if (!isJsonColumnValue(value)) {
124
+ throw new SeedLimitError(`the isolation fixture cannot fill ${where}: its JSON schema answers no JSON value for the sample`)
125
+ }
126
+ return value
27
127
  }
28
128
 
29
129
  /** One seeded row and where it lies. */
@@ -626,10 +726,16 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
626
726
  }
627
727
 
628
728
  /** A required column's sample where the row is not at hand: an `IN` list's first value where a CHECK names one, else a sample of its type. */
629
- async function requiredSample(table: string, column: SeedColumn): Promise<SampleValue> {
630
- const checked = await checkedValue(table, column)
729
+ async function requiredSample(model: TableModel, column: SeedColumn): Promise<SampleValue> {
730
+ const checked = await checkedValue(model.name, column)
631
731
  if (checked !== undefined) return checked
632
- return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample(0)
732
+ return (await numbered(model.name, column)) ? nextNumberOf(model.name, column, new Map()) : sampleOf(model, column, 0)
733
+ }
734
+
735
+ /** A sample of `column`'s type; of a JSON column whose policy declares a schema, one the schema accepts (`jsonSample`). */
736
+ function sampleOf(model: TableModel | undefined, column: SeedColumn, variant: number): SampleValue {
737
+ const schema = model === undefined ? undefined : ownEntry(model.jsonSchemas, column.name)
738
+ return model === undefined || schema === undefined ? column.sample(variant) : jsonSample(schema, `${model.name}.${column.name}`)
633
739
  }
634
740
 
635
741
  function columnsOf(table: string): readonly SeedColumn[] {
@@ -649,9 +755,9 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
649
755
  }
650
756
 
651
757
  /** A column the seeded row left to its default: null only where the column admits it. */
652
- async function updateSample(table: string, name: string): Promise<SampleValue> {
653
- const column = columnOf(table, name)
654
- return column.nullable ? null : requiredSample(table, column)
758
+ async function updateSample(model: TableModel, name: string): Promise<SampleValue> {
759
+ const column = columnOf(model.name, name)
760
+ return column.nullable ? null : requiredSample(model, column)
655
761
  }
656
762
 
657
763
  /** Whether the fixture writes a marker into `column`: text that holds no foreign key and that no CHECK names. */
@@ -828,7 +934,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
828
934
  ): Promise<Slot> {
829
935
  const name = column.name
830
936
  const single = (value: SampleValue): ReadonlyMap<string, SampleValue> => new Map([[name, value]])
831
- const sampled = (variant: number): SlotOption => ({ grouped: false, values: async () => single(column.sample(variant)) })
937
+ const sampled = (variant: number): SlotOption => ({ grouped: false, values: async () => single(sampleOf(model, column, variant)) })
832
938
  const samples = Array.from({ length: SAMPLE_VARIANTS }, (_, variant) => sampled(variant))
833
939
  const next: SlotOption = { grouped: true, values: async (row) => single(await nextNumberOf(table, column, row, ungrouped)) }
834
940
  const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
@@ -1210,7 +1316,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
1210
1316
  for (const name of namesOf(model.update)) {
1211
1317
  const written = row.get(name)
1212
1318
  const kept = written === undefined ? plainValue(stored[name]) : written
1213
- updates[name] = kept === undefined ? await updateSample(model.name, name) : kept
1319
+ updates[name] = kept === undefined ? await updateSample(model, name) : kept
1214
1320
  }
1215
1321
  return updates
1216
1322
  }
@@ -501,6 +501,9 @@ function binding(value: SampleValue): SqliteValue {
501
501
  if (!Number.isSafeInteger(number)) throw new SeedLimitError('the isolation fixture cannot write a bigint outside the safe integer range on SQLite')
502
502
  return number
503
503
  }
504
+ if (value !== null && typeof value === 'object') {
505
+ throw new SeedLimitError("the isolation fixture binds an object or an array only as a JSON column's text")
506
+ }
504
507
  return value
505
508
  }
506
509
 
@@ -9,6 +9,8 @@ import type {
9
9
  ColumnPolicies,
10
10
  ConfersPolicy,
11
11
  FilePolicies,
12
+ JsonColumn,
13
+ JsonPolicies,
12
14
  MemberRevealsPolicy,
13
15
  RecordActions,
14
16
  ReferencePolicy,
@@ -276,14 +278,26 @@ type AnyViewPolicy<DB, V, T extends keyof DB & string> = VocabularyViewPolicy<ke
276
278
  */
277
279
  export type VocabularyPolicyMap<DB, V, P = unknown, Views extends string = never> =
278
280
  & {
279
- readonly [T in Exclude<keyof DB & string, Views>]: AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T>
280
- : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>
281
+ readonly [T in Exclude<keyof DB & string, Views>]:
282
+ & (AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T>
283
+ : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>)
284
+ & JsonField<DB[T]>
281
285
  }
282
286
  & {
283
- readonly [T in Views & keyof DB & string]?: AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T>
284
- : VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>
287
+ readonly [T in Views & keyof DB & string]?:
288
+ & (AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T>
289
+ : VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>)
290
+ & JsonField<DB[T]>
285
291
  }
286
292
 
293
+ /**
294
+ * Column → the zod schema of a JSON column (`jsonb`, or `JSONB` on SQLite): each write is parsed by it before it is
295
+ * stored, and each read value too; the handle types read its output and write its input.
296
+ */
297
+ interface JsonField<Row> {
298
+ readonly json?: JsonPolicies<JsonColumn<Row>>
299
+ }
300
+
287
301
  type Flat<T> = { [K in keyof T]: T[K] }
288
302
 
289
303
  type KeyOf<S> = S extends { readonly key: infer K extends string } ? K : 'id'
@@ -67,9 +67,18 @@ export interface SelectState {
67
67
  }
68
68
  type Comparable<V> = Exclude<V, null | undefined>;
69
69
  type Columns<Row> = keyof Row & string;
70
- /** The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`. */
70
+ declare const declaredJson: unique symbol;
71
+ /** Type-only: the JSON columns a row types by their declared schema (`json`). No row value has the property. */
72
+ export interface DeclaredJson<C extends string> {
73
+ readonly [declaredJson]?: C;
74
+ }
75
+ type DeclaredJsonOf<Row> = typeof declaredJson extends keyof Row ? Row extends DeclaredJson<infer C> ? C : never : never;
76
+ /**
77
+ * The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`, or its
78
+ * declared schema's output (`DeclaredJson`).
79
+ */
71
80
  export type ComparableColumn<Row> = {
72
- [K in Columns<Row>]: unknown extends Row[K] ? never : K;
81
+ [K in Columns<Row>]: unknown extends Row[K] ? never : K extends DeclaredJsonOf<Row> ? never : K;
73
82
  }[Columns<Row>];
74
83
  type StringColumn<Row> = {
75
84
  [K in Columns<Row>]: Comparable<Row[K]> extends string ? K : never;
@@ -27,7 +27,7 @@ export declare class CapabilityError extends Error {
27
27
  */
28
28
  export declare const QUERY_REFUSALS: {
29
29
  readonly invalid_argument: "a data-layer call took an argument of another shape than its type declares";
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
+ 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, or a value of a JSON column that the schema its policy declares refuses";
31
31
  readonly invalid_name: "a configured name (application, schema, table or file column) breaks its naming rule";
32
32
  readonly unknown_column: "a column the table does not declare, or one this operation may not set";
33
33
  readonly unknown_table: "a table src/db/tables.ts does not declare, or one no store, join or locator reaches";
@@ -37,7 +37,7 @@ export declare const QUERY_REFUSALS: {
37
37
  readonly read_only: "a read-only request, query or table was asked to write or lock a row";
38
38
  readonly ended: "the transaction, invocation or handle has ended or belongs to other work";
39
39
  readonly statement_failed: "a statement of this transaction failed, so nothing it wrote commits";
40
- readonly unexpected_row: "the database answered a row in another shape than its migration declares";
40
+ readonly unexpected_row: "the database answered a row in another shape than its migration declares, or a JSON value the schema its policy declares refuses";
41
41
  readonly statement_shape: "the compiled statement has a form the guard does not admit";
42
42
  readonly scope_predicate: "the scope predicate is missing or is not a top-level conjunct";
43
43
  readonly list_page: "a list limit or order outside what a page admits";
@@ -1,9 +1,24 @@
1
+ import { z } from 'zod/v4';
1
2
  /** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
2
3
  export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
3
4
  readonly [key: string]: JsonValue | undefined;
4
5
  };
5
6
  /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
6
7
  export type JsonColumnValue = Exclude<JsonValue, null>;
8
+ /** The zod schema a table policy declares for a JSON column (`json: { <column>: schema }`); its output is JSON. */
9
+ export type JsonSchema = z.core.$ZodType;
10
+ /**
11
+ * The text a column with a declared schema binds for a written value, or `null` (SQL NULL) where the schema answers
12
+ * `null`. The value is first read as `jsonInput` reads any JSON column's (plain data only, so no getter, `toJSON` or
13
+ * class instance reaches the schema), then parsed, and the schema's output is what is stored. A value the schema
14
+ * refuses, and an output the schema would refuse on read, are `invalid_value` before anything is sent.
15
+ */
16
+ export declare function schemaInput(schema: JsonSchema, value: unknown, where: string): string | null;
17
+ /**
18
+ * A read value of a column with a declared schema, parsed by it: a stored value the schema refuses (written by
19
+ * `ctx.sql`, a migration, or before the schema tightened) is `unexpected_row`, so no handler sees it.
20
+ */
21
+ export declare function schemaOutput(schema: JsonSchema, value: unknown, where: string): unknown;
7
22
  /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
8
23
  export declare const MAX_JSON_DEPTH = 64;
9
24
  /**
@@ -11,6 +26,8 @@ export declare const MAX_JSON_DEPTH = 64;
11
26
  * and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
12
27
  */
13
28
  export declare function jsonInput(value: unknown, where: string): string;
29
+ /** Whether `value` is one a JSON column takes: a JSON value `jsonInput` serializes, other than `null`. */
30
+ export declare function isJsonColumnValue(value: unknown): value is JsonColumnValue;
14
31
  /**
15
32
  * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
16
33
  * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
@@ -2,7 +2,7 @@ import type { Selectable, Updateable } from 'kysely';
2
2
  import type { RowRef } from './capability';
3
3
  import type { ComparableColumn, ConditionTuple } from './description';
4
4
  import type { FileReference } from './file-references';
5
- import type { ActionOf, ApplicationTableName, ChildTableName, DimensionOf, DimensionTableName, InsertValues, ListDimensionOf, ParentOf, ReadsAny, Tables, UpdateValues } from './policy';
5
+ import type { ActionOf, ApplicationTableName, ChildTableName, DimensionOf, DimensionTableName, InsertValues, JsonSchemasOf, ListDimensionOf, ParentOf, ReadsAny, Tables, UpdateValues, WithJson } from './policy';
6
6
  import type { AggregateRow, AggregateSpec } from './store';
7
7
  import type { VocabularyContainerOf } from './vocabulary-tables';
8
8
  /** A member an endpoint may not use. It has no call signature, so a call fails at its line with this message. */
@@ -64,7 +64,7 @@ type ColumnsWrittenBy<C, A> = {
64
64
  type UpdatesOf<DB, P, T extends keyof DB> = {
65
65
  readonly [A in ActionOf<P, T, 'update'>]: UpdateValues<DB, P, T>;
66
66
  } & {
67
- readonly [A in ColumnWriteAction<ColumnPoliciesOf<P, T>>]: Flat<Pick<Updateable<DB[T]>, ColumnsWrittenBy<ColumnPoliciesOf<P, T>, A> & keyof Updateable<DB[T]>>>;
67
+ readonly [A in ColumnWriteAction<ColumnPoliciesOf<P, T>>]: WithJson<Flat<Pick<Updateable<DB[T]>, ColumnsWrittenBy<ColumnPoliciesOf<P, T>, A> & keyof Updateable<DB[T]>>>, JsonSchemasOf<P, T>, DB[T], 'input'>;
68
68
  };
69
69
  type ColumnWriteAction<C> = {
70
70
  [K in keyof C]: WriteActionsOf<C[K]>;
@@ -127,7 +127,7 @@ type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> =
127
127
  readonly readsAny: ReadsAny<P, T>;
128
128
  readonly appRead: AppActionsOf<P, T, 'appRead'>;
129
129
  readonly appCount: AppActionsOf<P, T, 'appCount'>;
130
- readonly row: WithFiles<RowType<DB[T]>, FileColumnsOf<P, T>>;
130
+ readonly row: WithJson<WithFiles<RowType<DB[T]>, FileColumnsOf<P, T>>, JsonSchemasOf<P, T>, DB[T], 'output'>;
131
131
  readonly reads: ColumnReadsOf<P, T>;
132
132
  readonly conditioned: ConditionedOf<P, T>;
133
133
  readonly insert: WithFiles<InsertValues<DB, P, T>, FileColumnsOf<P, T>>;
@@ -1,7 +1,10 @@
1
1
  import { READ_ANY } from '@fabrika/auth-core';
2
- import type { Insertable, Selectable, SelectType, Updateable } from 'kysely';
2
+ import type { Insertable, InsertType, Selectable, SelectType, Updateable } from 'kysely';
3
+ import { z } from 'zod/v4';
3
4
  import { type NameSet } from './builtins';
4
5
  import { type ConditionModel, type ConditionPolicy } from './conditions';
6
+ import type { DeclaredJson } from './description';
7
+ import type { JsonColumnValue, JsonSchema } from './json';
5
8
  import type { Unavailable } from './orm-types';
6
9
  export type { RowOf } from './orm-types';
7
10
  import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables';
@@ -190,6 +193,28 @@ export interface ConfersPolicy<Col extends string> {
190
193
  export type FilePolicies<Col extends string> = {
191
194
  readonly [C in Col]?: string;
192
195
  };
196
+ /** A table's JSON columns with a declared shape: column → a zod schema whose output is JSON. */
197
+ export type JsonPolicies<Col extends string> = {
198
+ readonly [C in Col]?: JsonSchema;
199
+ };
200
+ /** The JSON columns of a generated row type: those whose write type is a JSON value (`JsonColumnValue`). */
201
+ export type JsonColumn<Row> = {
202
+ [K in keyof Row & string]: [Exclude<InsertType<Row[K]>, null | undefined>] extends [JsonColumnValue] ? [JsonColumnValue] extends [Exclude<InsertType<Row[K]>, null | undefined>] ? K : never : never;
203
+ }[keyof Row & string];
204
+ /** The schemas table `T`'s policy declares for its JSON columns (`json`); none when it declares none. */
205
+ export type JsonSchemasOf<P, T> = PolicyOf<P, T> extends {
206
+ readonly json: infer J;
207
+ } ? J : Record<never, never>;
208
+ /** `null` where column `K` of the generated row is nullable. */
209
+ type NullOf<Row, K> = K extends keyof Row ? (null extends InsertType<Row[K]> ? null : never) : never;
210
+ /**
211
+ * A row (`'output'`) or a write (`'input'`) of a table whose policy declares JSON schemas `J`: each declared column is
212
+ * the schema's output or input, and `null` where the column is nullable. A row also carries the declared columns in
213
+ * `DeclaredJson`, which keeps them out of a condition and an order (`ComparableColumn`).
214
+ */
215
+ export type WithJson<R, J, Row, Io extends 'input' | 'output'> = [keyof J] extends [never] ? R : {
216
+ [K in keyof R]: K extends keyof J ? J[K] extends JsonSchema ? (Io extends 'output' ? z.output<J[K]> : z.input<J[K]>) | NullOf<Row, K> : R[K] : R[K];
217
+ } & (Io extends 'output' ? DeclaredJson<keyof J & string> : unknown);
193
218
  /**
194
219
  * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
195
220
  * without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
@@ -345,6 +370,8 @@ export interface TableModel {
345
370
  readonly booleans: NameSet;
346
371
  /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
347
372
  readonly json: NameSet;
373
+ /** The JSON columns the policy declares a schema for: each write is parsed by it, and each read value too. */
374
+ readonly jsonSchemas: Readonly<Record<string, JsonSchema>>;
348
375
  /** The columns the column list declares NOT NULL. */
349
376
  readonly notNull: NameSet;
350
377
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
@@ -646,9 +673,9 @@ type RestrictedColumns<P, T> = [ColumnPoliciesOf<P, T>] extends [never] ? never
646
673
  } ? ([TableReadAction<P, T>] extends [R extends readonly (infer L extends string)[] ? L : R] ? never : K) : never;
647
674
  }[keyof ColumnPoliciesOf<P, T>];
648
675
  /** A row of table `T` as a store reads it, by the table's read action. */
649
- export type PolicyRow<DB, P, T> = T extends keyof DB ? Flat<Omit<Selectable<DB[T]>, RestrictedColumns<P, T>>> : never;
650
- export type InsertValues<DB, P, T> = T extends keyof DB ? Flat<Pick<Insertable<DB[T]>, ListedColumns<P, T, 'insert'> & keyof Insertable<DB[T]>>> : never;
651
- export type UpdateValues<DB, P, T> = T extends keyof DB ? Flat<Pick<Updateable<DB[T]>, ListedColumns<P, T, 'update'> & keyof Updateable<DB[T]>>> : never;
676
+ export type PolicyRow<DB, P, T> = T extends keyof DB ? WithJson<Flat<Omit<Selectable<DB[T]>, RestrictedColumns<P, T>>>, JsonSchemasOf<P, T>, DB[T], 'output'> : never;
677
+ export type InsertValues<DB, P, T> = T extends keyof DB ? WithJson<Flat<Pick<Insertable<DB[T]>, ListedColumns<P, T, 'insert'> & keyof Insertable<DB[T]>>>, JsonSchemasOf<P, T>, DB[T], 'input'> : never;
678
+ export type UpdateValues<DB, P, T> = T extends keyof DB ? WithJson<Flat<Pick<Updateable<DB[T]>, ListedColumns<P, T, 'update'> & keyof Updateable<DB[T]>>>, JsonSchemasOf<P, T>, DB[T], 'input'> : never;
652
679
  /** The values a store inserts into table `T` of a `defineTables` result: `TableInsert<typeof tables, 'deals'>`. */
653
680
  export type TableInsert<Tb, T> = Tb extends Tables<infer DB, infer P> ? InsertValues<DB, P, T> : never;
654
681
  /** The values a store updates in table `T` of a `defineTables` result: `TableUpdate<typeof tables, 'deals'>`. */
@@ -1,5 +1,6 @@
1
1
  import { type NameSet } from './builtins';
2
2
  import type { SqlDialect } from './database';
3
+ import { type JsonSchema } from './json';
3
4
  /**
4
5
  * A day as the layer answers it: the database's `YYYY-MM-DD` text, or a decoded `Date` that is exactly a UTC midnight
5
6
  * in 0001–9999 — the only `Date` `Bun.SQL` decodes correctly from a `date`, whatever the process's time zone.
@@ -27,6 +28,8 @@ export interface RowColumns {
27
28
  readonly booleans: NameSet;
28
29
  /** JSON columns: the parsed value (SQLite answers its text). */
29
30
  readonly json: NameSet;
31
+ /** The JSON columns with a declared schema, by the name each arrives under: a read value is parsed by it. */
32
+ readonly jsonSchemas: Readonly<Record<string, JsonSchema>>;
30
33
  }
31
34
  /**
32
35
  * 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
@@ -1,14 +1,24 @@
1
1
  import type { Database } from './database';
2
- import type { Primitive } from './description';
2
+ import { type Primitive } from './description';
3
+ import { type JsonColumnValue, type JsonSchema } from './json';
3
4
  import { type Tables } from './policy';
4
5
  import type { TableProbe } from './store';
5
- /** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
6
- export type SampleValue = Primitive | null;
6
+ /**
7
+ * A value a test row holds in a column; `null` for a nullable column the fixture left empty. Only a JSON column holds
8
+ * an object or an array: the sample of one whose policy declares a schema (`jsonSample`).
9
+ */
10
+ export type SampleValue = Primitive | JsonColumnValue | null;
7
11
  /**
8
12
  * A seeded value as a backend binds it: a JSON column's value as the JSON text the layer would write for it, so a
9
13
  * seeded row and the kits' cases that write the same value through the layer hold the same JSON.
10
14
  */
11
- export declare function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): SampleValue;
15
+ export declare function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): Primitive | null;
16
+ /**
17
+ * The sample of a JSON column whose policy declares `schema`: built from the schema's JSON Schema and parsed by the
18
+ * schema, which answers the value the layer would store. A `SeedLimitError` when the sample does not pass (a pattern,
19
+ * a refinement), as for a type the fixture has no sample of.
20
+ */
21
+ export declare function jsonSample(schema: JsonSchema, where: string): JsonColumnValue;
12
22
  /** One seeded row and where it lies. */
13
23
  export interface WorldRow {
14
24
  /** The row's key: the dimension value of a dimension table's row, a child's own key. */
@@ -1,5 +1,5 @@
1
1
  import type { ConditionPolicy } from './conditions';
2
- import type { AccessPolicy, ApplicationActions, ColumnList, ColumnPolicies, ConfersPolicy, FilePolicies, MemberRevealsPolicy, RecordActions, ReferencePolicy, RevealsPolicy, TableAction, TableActions, Tables, VersionColumn } from './policy';
2
+ import type { AccessPolicy, ApplicationActions, ColumnList, ColumnPolicies, ConfersPolicy, FilePolicies, JsonColumn, JsonPolicies, MemberRevealsPolicy, RecordActions, ReferencePolicy, RevealsPolicy, TableAction, TableActions, Tables, VersionColumn } from './policy';
3
3
  declare const databaseType: unique symbol;
4
4
  declare const viewNames: unique symbol;
5
5
  /**
@@ -291,10 +291,17 @@ type AnyViewPolicy<DB, V, T extends keyof DB & string> = VocabularyViewPolicy<ke
291
291
  * form.
292
292
  */
293
293
  export type VocabularyPolicyMap<DB, V, P = unknown, Views extends string = never> = {
294
- readonly [T in Exclude<keyof DB & string, Views>]: AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T> : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>;
294
+ readonly [T in Exclude<keyof DB & string, Views>]: (AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T> : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>) & JsonField<DB[T]>;
295
295
  } & {
296
- readonly [T in Views & keyof DB & string]?: AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T> : VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>;
296
+ readonly [T in Views & keyof DB & string]?: (AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T> : VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>) & JsonField<DB[T]>;
297
297
  };
298
+ /**
299
+ * Column → the zod schema of a JSON column (`jsonb`, or `JSONB` on SQLite): each write is parsed by it before it is
300
+ * stored, and each read value too; the handle types read its output and write its input.
301
+ */
302
+ interface JsonField<Row> {
303
+ readonly json?: JsonPolicies<JsonColumn<Row>>;
304
+ }
298
305
  type Flat<T> = {
299
306
  [K in keyof T]: T[K];
300
307
  };