@syncular/typegen 0.73.0 → 0.74.0

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/dist/emit-dart.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * `query`/`readRows` return. The header carries the IR hash so `--check`
15
15
  * verifies freshness byte-exactly.
16
16
  */
17
- import { appColumnType, serializeSchema, } from './ir.js';
17
+ import { appColumnType, readNullable, serializeSchema, } from './ir.js';
18
18
  import { pascalCase, snakeToCamel, stringLiteral } from './naming.js';
19
19
  /** §2.4 column type → honest Dart type. `json`/`blob_ref` are the raw
20
20
  * canonical JSON string; `bytes`/`crdt` are opaque `List<int>`. */
@@ -54,12 +54,12 @@ function emitClass(table) {
54
54
  lines.push(`class ${type} {`);
55
55
  for (const column of table.columns) {
56
56
  const dart = DART_TYPE[appColumnType(column)];
57
- const opt = column.nullable ? '?' : '';
57
+ const opt = readNullable(column) ? '?' : '';
58
58
  lines.push(` final ${dart}${opt} ${snakeToCamel(column.name)};`);
59
59
  }
60
60
  lines.push('');
61
61
  const ctorParams = table.columns
62
- .map((c) => `${c.nullable ? '' : 'required '}this.${snakeToCamel(c.name)}`)
62
+ .map((c) => `${readNullable(c) ? '' : 'required '}this.${snakeToCamel(c.name)}`)
63
63
  .join(', ');
64
64
  lines.push(` const ${type}({${ctorParams}});`);
65
65
  lines.push('');
@@ -67,7 +67,7 @@ function emitClass(table) {
67
67
  lines.push(` /// non-nullable column is missing or mistyped.`);
68
68
  lines.push(` static ${type}? fromRow(Map<String, Object?> row) {`);
69
69
  for (const column of table.columns) {
70
- if (!column.nullable) {
70
+ if (!readNullable(column)) {
71
71
  const name = snakeToCamel(column.name);
72
72
  lines.push(` final ${name} = ${rowAccessor(column)};`);
73
73
  lines.push(` if (${name} == null) return null;`);
@@ -76,7 +76,9 @@ function emitClass(table) {
76
76
  const args = table.columns
77
77
  .map((c) => {
78
78
  const name = snakeToCamel(c.name);
79
- return c.nullable ? `${name}: ${rowAccessor(c)}` : `${name}: ${name}`;
79
+ return readNullable(c)
80
+ ? `${name}: ${rowAccessor(c)}`
81
+ : `${name}: ${name}`;
80
82
  })
81
83
  .join(', ');
82
84
  lines.push(` return ${type}(${args});`);
@@ -12,7 +12,7 @@
12
12
  * `query`/`readRows` return (each row a `JsonValue.Obj`). The header carries
13
13
  * the IR hash so `--check` verifies freshness byte-exactly.
14
14
  */
15
- import { appColumnType, serializeSchema, } from './ir.js';
15
+ import { appColumnType, readNullable, serializeSchema, } from './ir.js';
16
16
  import { pascalCase, snakeToCamel, stringLiteral } from './naming.js';
17
17
  /** §2.4 column type → honest Kotlin type. `json`/`blob_ref` are the raw
18
18
  * canonical JSON string; `bytes`/`crdt` are opaque `ByteArray`. */
@@ -52,7 +52,7 @@ function emitDataClass(table) {
52
52
  lines.push(`data class ${type}(`);
53
53
  for (const column of table.columns) {
54
54
  const kotlin = KOTLIN_TYPE[appColumnType(column)];
55
- const opt = column.nullable ? '?' : '';
55
+ const opt = readNullable(column) ? '?' : '';
56
56
  lines.push(` val ${snakeToCamel(column.name)}: ${kotlin}${opt},`);
57
57
  }
58
58
  lines.push(') {');
@@ -62,7 +62,7 @@ function emitDataClass(table) {
62
62
  for (const column of table.columns) {
63
63
  const name = snakeToCamel(column.name);
64
64
  const accessor = rowAccessor(column);
65
- if (column.nullable) {
65
+ if (readNullable(column)) {
66
66
  lines.push(` val ${name} = ${accessor}`);
67
67
  }
68
68
  else {
@@ -14,7 +14,7 @@
14
14
  * IR hash so `--check` verifies freshness byte-exactly, exactly like the TS
15
15
  * emitter.
16
16
  */
17
- import { appColumnType, serializeSchema, } from './ir.js';
17
+ import { appColumnType, readNullable, serializeSchema, } from './ir.js';
18
18
  import { pascalCase, snakeToCamel, stringLiteral } from './naming.js';
19
19
  /**
20
20
  * §2.4 column type → honest Swift type. `json`/`blob_ref` are the raw
@@ -61,7 +61,7 @@ function emitStruct(table) {
61
61
  lines.push(`public struct ${type}: Sendable, Equatable {`);
62
62
  for (const column of table.columns) {
63
63
  const swift = SWIFT_TYPE[appColumnType(column)];
64
- const opt = column.nullable ? '?' : '';
64
+ const opt = readNullable(column) ? '?' : '';
65
65
  lines.push(` public let ${snakeToCamel(column.name)}: ${swift}${opt}`);
66
66
  }
67
67
  lines.push('');
@@ -69,7 +69,7 @@ function emitStruct(table) {
69
69
  const params = table.columns
70
70
  .map((c) => {
71
71
  const swift = SWIFT_TYPE[appColumnType(c)];
72
- const opt = c.nullable ? '? = nil' : '';
72
+ const opt = readNullable(c) ? '? = nil' : '';
73
73
  return `${snakeToCamel(c.name)}: ${swift}${opt}`;
74
74
  })
75
75
  .join(', ');
@@ -86,7 +86,7 @@ function emitStruct(table) {
86
86
  for (const column of table.columns) {
87
87
  const name = snakeToCamel(column.name);
88
88
  const accessor = rowAccessor(column);
89
- if (column.nullable) {
89
+ if (readNullable(column)) {
90
90
  lines.push(` self.${name} = ${accessor}`);
91
91
  }
92
92
  else {
package/dist/emit.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * The header carries the IR hash so `--check` verifies freshness
13
13
  * byte-exactly.
14
14
  */
15
- import { appColumnType, serializeSchema, } from './ir.js';
15
+ import { appColumnType, readNullable, serializeSchema, } from './ir.js';
16
16
  import { pascalCase, snakeToCamel, stringLiteral, } from './naming.js';
17
17
  const TS_TYPE = {
18
18
  string: 'string',
@@ -43,7 +43,7 @@ function emitRowInterfaces(table, naming) {
43
43
  lines.push(`export interface ${type}Row {`);
44
44
  for (const column of table.columns) {
45
45
  const ts = TS_TYPE[appColumnType(column)];
46
- lines.push(` ${key(column.name)}: ${ts}${column.nullable ? ' | null' : ''};`);
46
+ lines.push(` ${key(column.name)}: ${ts}${readNullable(column) ? ' | null' : ''};`);
47
47
  }
48
48
  lines.push('}');
49
49
  lines.push('');
package/dist/ir.d.ts CHANGED
@@ -21,6 +21,10 @@ export interface IrColumn {
21
21
  * as `bytes`; generated rows expose its declared type (the local mirror is
22
22
  * plaintext). */
23
23
  export declare function appColumnType(column: IrColumn): IrColumnType;
24
+ /** §5.11 sealed apply: a sealed row holds NULL in every encrypted column of
25
+ * the local mirror, so a read sees an encrypted column as nullable whatever
26
+ * its declared nullability. Write shapes keep `nullable`. */
27
+ export declare function readNullable(column: IrColumn): boolean;
24
28
  /** One §3.1 scope pattern, fully resolved (no re-parsing downstream). */
25
29
  export interface IrScope {
26
30
  readonly pattern: string;
package/dist/ir.js CHANGED
@@ -20,6 +20,12 @@ export function appColumnType(column) {
20
20
  ? column.declaredType
21
21
  : column.type;
22
22
  }
23
+ /** §5.11 sealed apply: a sealed row holds NULL in every encrypted column of
24
+ * the local mirror, so a read sees an encrypted column as nullable whatever
25
+ * its declared nullability. Write shapes keep `nullable`. */
26
+ export function readNullable(column) {
27
+ return column.nullable || column.encrypted === true;
28
+ }
23
29
  /** Recursively sort object keys so extension payloads serialize stably. */
24
30
  export function canonicalizeExtensions(value) {
25
31
  if (Array.isArray(value))
package/dist/query.js CHANGED
@@ -88,6 +88,9 @@ const DECLTYPE_MAP = {
88
88
  };
89
89
  /** Local client protocol column; query-only and never part of schema IR. */
90
90
  const SYNC_VERSION_COLUMN = '_sync_version';
91
+ /** §5.11 sealed-apply marker: the missing key id of a sealed row, NULL on an
92
+ * unsealed one. Present only on a table with an encrypted column. */
93
+ const SEALED_KEY_COLUMN = '_sync_sealed_key';
91
94
  /** Stable private identity shared by every declared local FTS5 projection. */
92
95
  const FTS_SOURCE_ID_COLUMN = '_syncular_source_id';
93
96
  /** The window bases (SPEC §4.8) a query's coverage needs, for generated
@@ -940,18 +943,22 @@ function resolveSource(item, refs, ir) {
940
943
  }
941
944
  return matches.length === 1 ? matches[0] : null;
942
945
  }
943
- /** Resolve the one supported query-only protocol column. SQLite still proves
944
- * qualifier/ambiguity against the synthesized local tables. */
945
- function syncVersionSourceNullability(item, refs) {
946
+ /** Resolve the query-only protocol columns: `_sync_version` and the
947
+ * §5.11 `_sync_sealed_key` marker. SQLite still proves qualifier/ambiguity
948
+ * against the synthesized local tables. */
949
+ function protocolColumnSource(item, refs) {
946
950
  const match = PLAIN_REF_RE.exec(item.expr);
951
+ if (match?.[2] === SEALED_KEY_COLUMN)
952
+ return { type: 'string', nullable: true };
947
953
  if (match === null || match[2] !== SYNC_VERSION_COLUMN)
948
954
  return null;
949
955
  const qualifier = match[1];
950
- if (qualifier === undefined) {
951
- return refs.length === 1 ? (refs[0]?.nullable ?? null) : null;
952
- }
953
- const matches = refs.filter((ref) => ref.alias.toLowerCase() === qualifier.toLowerCase());
954
- return matches.length === 1 ? (matches[0]?.nullable ?? null) : null;
956
+ const matches = qualifier === undefined
957
+ ? refs
958
+ : refs.filter((ref) => ref.alias.toLowerCase() === qualifier.toLowerCase());
959
+ return matches.length === 1 && matches[0] !== undefined
960
+ ? { type: 'integer', nullable: matches[0].nullable }
961
+ : null;
955
962
  }
956
963
  // -- param type inference -----------------------------------------------------
957
964
  //
@@ -1144,6 +1151,9 @@ export function synthesizeDdl(ir) {
1144
1151
  // token. It is absent from IR mutation types but may be explicitly aliased
1145
1152
  // by a named read query for optimistic concurrency.
1146
1153
  cols.push(` ${SYNC_VERSION_COLUMN} INTEGER NOT NULL DEFAULT -1`);
1154
+ if (table.columns.some((column) => column.encrypted === true)) {
1155
+ cols.push(` ${SEALED_KEY_COLUMN} TEXT`);
1156
+ }
1147
1157
  lines.push(`CREATE TABLE ${table.name} (\n${cols.join(',\n')}\n);`);
1148
1158
  // Create the declared indexes too — harmless for prepare()/decltype, and
1149
1159
  // keeps the type-check DB's shape honest with what the client materializes.
@@ -1375,6 +1385,10 @@ export function analyzeStatement(name, location, statementText, ir, db, naming =
1375
1385
  }
1376
1386
  catch (error) {
1377
1387
  const message = error instanceof Error ? error.message : String(error);
1388
+ if (message.startsWith('no such column:') &&
1389
+ message.endsWith(SEALED_KEY_COLUMN)) {
1390
+ throw new TypegenError(file, `${SEALED_KEY_COLUMN} exists only on a table with an encrypted column (SPEC §5.11)`, 'typegen.sealed_key_unencrypted', { query: name });
1391
+ }
1378
1392
  throw new TypegenError(file, `SQL rejected by SQLite: ${message}`);
1379
1393
  }
1380
1394
  };
@@ -1460,7 +1474,10 @@ export function analyzeStatement(name, location, statementText, ir, db, naming =
1460
1474
  : resolveSource(item, scoped.tables.filter((ref) => scoped.scopeAt(ref.start) === 'main' &&
1461
1475
  ref.start >= branch.start &&
1462
1476
  ref.start < branch.end), ir);
1463
- return source === null || source.column.nullable || source.nullableByJoin;
1477
+ return (source === null ||
1478
+ source.column.nullable ||
1479
+ source.column.encrypted === true ||
1480
+ source.nullableByJoin);
1464
1481
  });
1465
1482
  const columns = described.columnNames.map((colName, index) => {
1466
1483
  const decl = described.declaredTypes[index];
@@ -1468,28 +1485,33 @@ export function analyzeStatement(name, location, statementText, ir, db, naming =
1468
1485
  const source = item !== undefined ? resolveInScope(item, 'main') : null;
1469
1486
  const sqlName = sqlNames[index] ?? colName;
1470
1487
  const langName = langNames[index] ?? colName;
1471
- const syncVersionNullable = item !== undefined ? syncVersionSourceNullability(item, refs) : null;
1472
- if (syncVersionNullable !== null) {
1473
- if (sqlName === SYNC_VERSION_COLUMN) {
1474
- throw new TypegenError(file, `${SYNC_VERSION_COLUMN} is stripped from app-facing query rows unless explicitly aliased (for example \`${SYNC_VERSION_COLUMN} AS server_version\`)`);
1475
- }
1488
+ // Clients strip every `_sync_` result key from query rows (§7.5).
1489
+ if (sqlName.toLowerCase().startsWith('_sync_') ||
1490
+ langName.toLowerCase().startsWith('_sync_')) {
1491
+ throw new TypegenError(file, 'a result column named with the _sync_ prefix is stripped from query rows; alias it to a name without the prefix (for example `_sync_version AS server_version`)', 'typegen.reserved_result_column', { query: name, column: sqlName });
1492
+ }
1493
+ const protocol = item !== undefined ? protocolColumnSource(item, refs) : null;
1494
+ if (protocol !== null) {
1476
1495
  return {
1477
1496
  name: sqlName,
1478
1497
  langName,
1479
- type: 'integer',
1480
- nullable: syncVersionNullable || branchNullable(index),
1498
+ type: protocol.type,
1499
+ nullable: protocol.nullable || branchNullable(index),
1481
1500
  fidelity: 'exact',
1482
1501
  };
1483
1502
  }
1484
1503
  if (source !== null) {
1485
1504
  // Exact: app-facing queries read the decrypted local mirror. Encrypted
1486
1505
  // columns therefore expose their pre-wire declaredType, while the schema
1487
- // IR and mutation codec continue to carry the bytes wire type.
1506
+ // IR and mutation codec continue to carry the bytes wire type. A sealed
1507
+ // row (§5.11) holds NULL in every encrypted column, so an encrypted
1508
+ // column reads nullable whatever its declared nullability.
1488
1509
  return {
1489
1510
  name: sqlName,
1490
1511
  langName,
1491
1512
  type: applicationColumnType(source.column),
1492
1513
  nullable: source.column.nullable ||
1514
+ source.column.encrypted === true ||
1493
1515
  source.nullableByJoin ||
1494
1516
  branchNullable(index),
1495
1517
  fidelity: 'exact',
@@ -639,6 +639,12 @@ class Validator {
639
639
  if (noColumn !== null) {
640
640
  const first = noColumn[1];
641
641
  const second = noColumn[2];
642
+ if ((second ?? first) === '_sync_sealed_key') {
643
+ return {
644
+ span: this.#sqlSubjectSpan(logical, second === undefined ? first : `${first}.${second}`, 'column') ?? fallback,
645
+ message: '`_sync_sealed_key` exists only on a table with an encrypted column (SPEC §5.11)',
646
+ };
647
+ }
642
648
  if (second !== undefined) {
643
649
  const qualifier = first;
644
650
  const ref = refs.find((candidate) => candidate.alias.toLowerCase() === qualifier.toLowerCase());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/typegen",
3
- "version": "0.73.0",
3
+ "version": "0.74.0",
4
4
  "description": "Syncular schema-to-TypeScript type generator and the `syncular` CLI",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -56,9 +56,9 @@
56
56
  "!dist/**/*.test.d.ts"
57
57
  ],
58
58
  "dependencies": {
59
- "@syncular/core": "0.73.0"
59
+ "@syncular/core": "0.74.0"
60
60
  },
61
61
  "devDependencies": {
62
- "@syncular/server": "0.73.0"
62
+ "@syncular/server": "0.74.0"
63
63
  }
64
64
  }
package/src/emit-dart.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import {
18
18
  appColumnType,
19
+ readNullable,
19
20
  type IrColumnType,
20
21
  type IrDocument,
21
22
  type IrSubscription,
@@ -64,12 +65,15 @@ function emitClass(table: IrTable): string[] {
64
65
  lines.push(`class ${type} {`);
65
66
  for (const column of table.columns) {
66
67
  const dart = DART_TYPE[appColumnType(column)];
67
- const opt = column.nullable ? '?' : '';
68
+ const opt = readNullable(column) ? '?' : '';
68
69
  lines.push(` final ${dart}${opt} ${snakeToCamel(column.name)};`);
69
70
  }
70
71
  lines.push('');
71
72
  const ctorParams = table.columns
72
- .map((c) => `${c.nullable ? '' : 'required '}this.${snakeToCamel(c.name)}`)
73
+ .map(
74
+ (c) =>
75
+ `${readNullable(c) ? '' : 'required '}this.${snakeToCamel(c.name)}`,
76
+ )
73
77
  .join(', ');
74
78
  lines.push(` const ${type}({${ctorParams}});`);
75
79
  lines.push('');
@@ -79,7 +83,7 @@ function emitClass(table: IrTable): string[] {
79
83
  lines.push(` /// non-nullable column is missing or mistyped.`);
80
84
  lines.push(` static ${type}? fromRow(Map<String, Object?> row) {`);
81
85
  for (const column of table.columns) {
82
- if (!column.nullable) {
86
+ if (!readNullable(column)) {
83
87
  const name = snakeToCamel(column.name);
84
88
  lines.push(` final ${name} = ${rowAccessor(column)};`);
85
89
  lines.push(` if (${name} == null) return null;`);
@@ -88,7 +92,9 @@ function emitClass(table: IrTable): string[] {
88
92
  const args = table.columns
89
93
  .map((c) => {
90
94
  const name = snakeToCamel(c.name);
91
- return c.nullable ? `${name}: ${rowAccessor(c)}` : `${name}: ${name}`;
95
+ return readNullable(c)
96
+ ? `${name}: ${rowAccessor(c)}`
97
+ : `${name}: ${name}`;
92
98
  })
93
99
  .join(', ');
94
100
  lines.push(` return ${type}(${args});`);
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import {
16
16
  appColumnType,
17
+ readNullable,
17
18
  type IrColumnType,
18
19
  type IrDocument,
19
20
  type IrSubscription,
@@ -62,7 +63,7 @@ function emitDataClass(table: IrTable): string[] {
62
63
  lines.push(`data class ${type}(`);
63
64
  for (const column of table.columns) {
64
65
  const kotlin = KOTLIN_TYPE[appColumnType(column)];
65
- const opt = column.nullable ? '?' : '';
66
+ const opt = readNullable(column) ? '?' : '';
66
67
  lines.push(` val ${snakeToCamel(column.name)}: ${kotlin}${opt},`);
67
68
  }
68
69
  lines.push(') {');
@@ -74,7 +75,7 @@ function emitDataClass(table: IrTable): string[] {
74
75
  for (const column of table.columns) {
75
76
  const name = snakeToCamel(column.name);
76
77
  const accessor = rowAccessor(column);
77
- if (column.nullable) {
78
+ if (readNullable(column)) {
78
79
  lines.push(` val ${name} = ${accessor}`);
79
80
  } else {
80
81
  lines.push(` val ${name} = ${accessor} ?: return null`);
package/src/emit-swift.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import {
18
18
  appColumnType,
19
+ readNullable,
19
20
  type IrColumnType,
20
21
  type IrDocument,
21
22
  type IrSubscription,
@@ -71,7 +72,7 @@ function emitStruct(table: IrTable): string[] {
71
72
  lines.push(`public struct ${type}: Sendable, Equatable {`);
72
73
  for (const column of table.columns) {
73
74
  const swift = SWIFT_TYPE[appColumnType(column)];
74
- const opt = column.nullable ? '?' : '';
75
+ const opt = readNullable(column) ? '?' : '';
75
76
  lines.push(` public let ${snakeToCamel(column.name)}: ${swift}${opt}`);
76
77
  }
77
78
  lines.push('');
@@ -79,7 +80,7 @@ function emitStruct(table: IrTable): string[] {
79
80
  const params = table.columns
80
81
  .map((c) => {
81
82
  const swift = SWIFT_TYPE[appColumnType(c)];
82
- const opt = c.nullable ? '? = nil' : '';
83
+ const opt = readNullable(c) ? '? = nil' : '';
83
84
  return `${snakeToCamel(c.name)}: ${swift}${opt}`;
84
85
  })
85
86
  .join(', ');
@@ -100,7 +101,7 @@ function emitStruct(table: IrTable): string[] {
100
101
  for (const column of table.columns) {
101
102
  const name = snakeToCamel(column.name);
102
103
  const accessor = rowAccessor(column);
103
- if (column.nullable) {
104
+ if (readNullable(column)) {
104
105
  lines.push(` self.${name} = ${accessor}`);
105
106
  } else {
106
107
  lines.push(` guard let ${name} = ${accessor} else { return nil }`);
package/src/emit.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import {
16
16
  appColumnType,
17
+ readNullable,
17
18
  type IrColumnType,
18
19
  type IrDocument,
19
20
  type IrSubscription,
@@ -61,7 +62,7 @@ function emitRowInterfaces(table: IrTable, naming: NamingMode): string {
61
62
  for (const column of table.columns) {
62
63
  const ts = TS_TYPE[appColumnType(column)];
63
64
  lines.push(
64
- ` ${key(column.name)}: ${ts}${column.nullable ? ' | null' : ''};`,
65
+ ` ${key(column.name)}: ${ts}${readNullable(column) ? ' | null' : ''};`,
65
66
  );
66
67
  }
67
68
  lines.push('}');
package/src/ir.ts CHANGED
@@ -51,6 +51,13 @@ export function appColumnType(column: IrColumn): IrColumnType {
51
51
  : column.type;
52
52
  }
53
53
 
54
+ /** §5.11 sealed apply: a sealed row holds NULL in every encrypted column of
55
+ * the local mirror, so a read sees an encrypted column as nullable whatever
56
+ * its declared nullability. Write shapes keep `nullable`. */
57
+ export function readNullable(column: IrColumn): boolean {
58
+ return column.nullable || column.encrypted === true;
59
+ }
60
+
54
61
  /** One §3.1 scope pattern, fully resolved (no re-parsing downstream). */
55
62
  export interface IrScope {
56
63
  readonly pattern: string;
package/src/query.ts CHANGED
@@ -96,6 +96,9 @@ const DECLTYPE_MAP: Readonly<Record<string, IrColumnType>> = {
96
96
 
97
97
  /** Local client protocol column; query-only and never part of schema IR. */
98
98
  const SYNC_VERSION_COLUMN = '_sync_version';
99
+ /** §5.11 sealed-apply marker: the missing key id of a sealed row, NULL on an
100
+ * unsealed one. Present only on a table with an encrypted column. */
101
+ const SEALED_KEY_COLUMN = '_sync_sealed_key';
99
102
  /** Stable private identity shared by every declared local FTS5 projection. */
100
103
  const FTS_SOURCE_ID_COLUMN = '_syncular_source_id';
101
104
 
@@ -1440,22 +1443,27 @@ function resolveSource(
1440
1443
  return matches.length === 1 ? (matches[0] as ResolvedSource) : null;
1441
1444
  }
1442
1445
 
1443
- /** Resolve the one supported query-only protocol column. SQLite still proves
1444
- * qualifier/ambiguity against the synthesized local tables. */
1445
- function syncVersionSourceNullability(
1446
+ /** Resolve the query-only protocol columns: `_sync_version` and the
1447
+ * §5.11 `_sync_sealed_key` marker. SQLite still proves qualifier/ambiguity
1448
+ * against the synthesized local tables. */
1449
+ function protocolColumnSource(
1446
1450
  item: SelectItem,
1447
1451
  refs: readonly TableRef[],
1448
- ): boolean | null {
1452
+ ): { readonly type: IrColumnType; readonly nullable: boolean } | null {
1449
1453
  const match = PLAIN_REF_RE.exec(item.expr);
1454
+ if (match?.[2] === SEALED_KEY_COLUMN)
1455
+ return { type: 'string', nullable: true };
1450
1456
  if (match === null || match[2] !== SYNC_VERSION_COLUMN) return null;
1451
1457
  const qualifier = match[1];
1452
- if (qualifier === undefined) {
1453
- return refs.length === 1 ? (refs[0]?.nullable ?? null) : null;
1454
- }
1455
- const matches = refs.filter(
1456
- (ref) => ref.alias.toLowerCase() === qualifier.toLowerCase(),
1457
- );
1458
- return matches.length === 1 ? (matches[0]?.nullable ?? null) : null;
1458
+ const matches =
1459
+ qualifier === undefined
1460
+ ? refs
1461
+ : refs.filter(
1462
+ (ref) => ref.alias.toLowerCase() === qualifier.toLowerCase(),
1463
+ );
1464
+ return matches.length === 1 && matches[0] !== undefined
1465
+ ? { type: 'integer', nullable: matches[0].nullable }
1466
+ : null;
1459
1467
  }
1460
1468
 
1461
1469
  // -- param type inference -----------------------------------------------------
@@ -1726,6 +1734,9 @@ export function synthesizeDdl(ir: IrDocument): string {
1726
1734
  // token. It is absent from IR mutation types but may be explicitly aliased
1727
1735
  // by a named read query for optimistic concurrency.
1728
1736
  cols.push(` ${SYNC_VERSION_COLUMN} INTEGER NOT NULL DEFAULT -1`);
1737
+ if (table.columns.some((column) => column.encrypted === true)) {
1738
+ cols.push(` ${SEALED_KEY_COLUMN} TEXT`);
1739
+ }
1729
1740
  lines.push(`CREATE TABLE ${table.name} (\n${cols.join(',\n')}\n);`);
1730
1741
  // Create the declared indexes too — harmless for prepare()/decltype, and
1731
1742
  // keeps the type-check DB's shape honest with what the client materializes.
@@ -2006,6 +2017,17 @@ export function analyzeStatement(
2006
2017
  return db.analyze(candidate);
2007
2018
  } catch (error) {
2008
2019
  const message = error instanceof Error ? error.message : String(error);
2020
+ if (
2021
+ message.startsWith('no such column:') &&
2022
+ message.endsWith(SEALED_KEY_COLUMN)
2023
+ ) {
2024
+ throw new TypegenError(
2025
+ file,
2026
+ `${SEALED_KEY_COLUMN} exists only on a table with an encrypted column (SPEC §5.11)`,
2027
+ 'typegen.sealed_key_unencrypted',
2028
+ { query: name },
2029
+ );
2030
+ }
2009
2031
  throw new TypegenError(file, `SQL rejected by SQLite: ${message}`);
2010
2032
  }
2011
2033
  };
@@ -2147,7 +2169,12 @@ export function analyzeStatement(
2147
2169
  ),
2148
2170
  ir,
2149
2171
  );
2150
- return source === null || source.column.nullable || source.nullableByJoin;
2172
+ return (
2173
+ source === null ||
2174
+ source.column.nullable ||
2175
+ source.column.encrypted === true ||
2176
+ source.nullableByJoin
2177
+ );
2151
2178
  });
2152
2179
  const columns: QueryColumn[] = described.columnNames.map((colName, index) => {
2153
2180
  const decl = described.declaredTypes[index];
@@ -2155,33 +2182,42 @@ export function analyzeStatement(
2155
2182
  const source = item !== undefined ? resolveInScope(item, 'main') : null;
2156
2183
  const sqlName = sqlNames[index] ?? colName;
2157
2184
  const langName = langNames[index] ?? colName;
2158
- const syncVersionNullable =
2159
- item !== undefined ? syncVersionSourceNullability(item, refs) : null;
2160
- if (syncVersionNullable !== null) {
2161
- if (sqlName === SYNC_VERSION_COLUMN) {
2162
- throw new TypegenError(
2163
- file,
2164
- `${SYNC_VERSION_COLUMN} is stripped from app-facing query rows unless explicitly aliased (for example \`${SYNC_VERSION_COLUMN} AS server_version\`)`,
2165
- );
2166
- }
2185
+ // Clients strip every `_sync_` result key from query rows (§7.5).
2186
+ if (
2187
+ sqlName.toLowerCase().startsWith('_sync_') ||
2188
+ langName.toLowerCase().startsWith('_sync_')
2189
+ ) {
2190
+ throw new TypegenError(
2191
+ file,
2192
+ 'a result column named with the _sync_ prefix is stripped from query rows; alias it to a name without the prefix (for example `_sync_version AS server_version`)',
2193
+ 'typegen.reserved_result_column',
2194
+ { query: name, column: sqlName },
2195
+ );
2196
+ }
2197
+ const protocol =
2198
+ item !== undefined ? protocolColumnSource(item, refs) : null;
2199
+ if (protocol !== null) {
2167
2200
  return {
2168
2201
  name: sqlName,
2169
2202
  langName,
2170
- type: 'integer',
2171
- nullable: syncVersionNullable || branchNullable(index),
2203
+ type: protocol.type,
2204
+ nullable: protocol.nullable || branchNullable(index),
2172
2205
  fidelity: 'exact',
2173
2206
  };
2174
2207
  }
2175
2208
  if (source !== null) {
2176
2209
  // Exact: app-facing queries read the decrypted local mirror. Encrypted
2177
2210
  // columns therefore expose their pre-wire declaredType, while the schema
2178
- // IR and mutation codec continue to carry the bytes wire type.
2211
+ // IR and mutation codec continue to carry the bytes wire type. A sealed
2212
+ // row (§5.11) holds NULL in every encrypted column, so an encrypted
2213
+ // column reads nullable whatever its declared nullability.
2179
2214
  return {
2180
2215
  name: sqlName,
2181
2216
  langName,
2182
2217
  type: applicationColumnType(source.column),
2183
2218
  nullable:
2184
2219
  source.column.nullable ||
2220
+ source.column.encrypted === true ||
2185
2221
  source.nullableByJoin ||
2186
2222
  branchNullable(index),
2187
2223
  fidelity: 'exact',
@@ -1039,6 +1039,18 @@ class Validator {
1039
1039
  if (noColumn !== null) {
1040
1040
  const first = noColumn[1] as string;
1041
1041
  const second = noColumn[2];
1042
+ if ((second ?? first) === '_sync_sealed_key') {
1043
+ return {
1044
+ span:
1045
+ this.#sqlSubjectSpan(
1046
+ logical,
1047
+ second === undefined ? first : `${first}.${second}`,
1048
+ 'column',
1049
+ ) ?? fallback,
1050
+ message:
1051
+ '`_sync_sealed_key` exists only on a table with an encrypted column (SPEC §5.11)',
1052
+ };
1053
+ }
1042
1054
  if (second !== undefined) {
1043
1055
  const qualifier = first;
1044
1056
  const ref = refs.find(