@syncular/typegen 0.57.0 → 0.59.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.
Files changed (60) hide show
  1. package/README.md +43 -25
  2. package/dist/cli.js +8 -3
  3. package/dist/emit-dart.d.ts +4 -3
  4. package/dist/emit-dart.js +39 -88
  5. package/dist/emit-kotlin.d.ts +3 -3
  6. package/dist/emit-kotlin.js +39 -86
  7. package/dist/emit-queries-dart.d.ts +1 -1
  8. package/dist/emit-queries-dart.js +17 -26
  9. package/dist/emit-queries-kotlin.d.ts +1 -1
  10. package/dist/emit-queries-kotlin.js +15 -24
  11. package/dist/emit-queries-rust.d.ts +1 -1
  12. package/dist/emit-queries-rust.js +1 -6
  13. package/dist/emit-queries-swift.d.ts +1 -1
  14. package/dist/emit-queries-swift.js +22 -26
  15. package/dist/emit-queries.d.ts +1 -1
  16. package/dist/emit-queries.js +1 -6
  17. package/dist/emit-swift.d.ts +3 -3
  18. package/dist/emit-swift.js +41 -89
  19. package/dist/emit.d.ts +1 -1
  20. package/dist/emit.js +33 -98
  21. package/dist/errors.d.ts +6 -2
  22. package/dist/errors.js +10 -2
  23. package/dist/generate.d.ts +4 -3
  24. package/dist/generate.js +32 -49
  25. package/dist/init.js +1 -1
  26. package/dist/ir.d.ts +11 -0
  27. package/dist/ir.js +66 -47
  28. package/dist/lower.d.ts +0 -7
  29. package/dist/lower.js +0 -62
  30. package/dist/migration-lock.d.ts +32 -23
  31. package/dist/migration-lock.js +115 -92
  32. package/dist/naming.d.ts +25 -0
  33. package/dist/naming.js +92 -0
  34. package/dist/query.d.ts +54 -14
  35. package/dist/query.js +484 -462
  36. package/dist/sql.js +18 -3
  37. package/dist/syql-lowering.js +10 -1
  38. package/dist/syql-validator.js +13 -220
  39. package/package.json +3 -3
  40. package/src/cli.ts +9 -3
  41. package/src/emit-dart.ts +41 -102
  42. package/src/emit-kotlin.ts +38 -102
  43. package/src/emit-queries-dart.ts +23 -32
  44. package/src/emit-queries-kotlin.ts +20 -30
  45. package/src/emit-queries-rust.ts +7 -12
  46. package/src/emit-queries-swift.ts +26 -32
  47. package/src/emit-queries.ts +5 -11
  48. package/src/emit-swift.ts +42 -104
  49. package/src/emit.ts +33 -116
  50. package/src/errors.ts +13 -2
  51. package/src/generate.ts +74 -76
  52. package/src/init.ts +4 -1
  53. package/src/ir.ts +87 -50
  54. package/src/lower.ts +0 -53
  55. package/src/migration-lock.ts +192 -137
  56. package/src/naming.ts +154 -0
  57. package/src/query.ts +615 -504
  58. package/src/sql.ts +30 -3
  59. package/src/syql-lowering.ts +15 -1
  60. package/src/syql-validator.ts +21 -279
@@ -14,11 +14,11 @@
14
14
  */
15
15
  import type { IrColumnType } from './ir';
16
16
  import { snakeToCamel } from './naming';
17
- import type {
18
- AnalyzedQuery,
19
- QueryColumn,
20
- QuerySyqlPlanBind,
21
- QuerySyqlPublicInput,
17
+ import {
18
+ type AnalyzedQuery,
19
+ type QueryColumn,
20
+ type QuerySyqlPlanBind,
21
+ syqlInput,
22
22
  } from './query';
23
23
 
24
24
  const SWIFT_TYPE: Readonly<Record<IrColumnType, string>> = {
@@ -36,11 +36,6 @@ const SYQL_SWIFT_TYPE: Readonly<Record<IrColumnType, string>> = {
36
36
  integer: 'Int64',
37
37
  };
38
38
 
39
- /** Language-facing field name — the pinned §12 naming map. */
40
- function camelCase(name: string): string {
41
- return snakeToCamel(name);
42
- }
43
-
44
39
  /** The query function/type name: already camelCase; PascalCase for the type. */
45
40
  function typeName(name: string): string {
46
41
  return name.charAt(0).toUpperCase() + name.slice(1);
@@ -102,22 +97,16 @@ function optionalParamValue(type: IrColumnType, name: string): string {
102
97
  }
103
98
  }
104
99
 
105
- function syqlInput(query: AnalyzedQuery, name: string): QuerySyqlPublicInput {
106
- const input = query.syql?.inputs.find((candidate) => candidate.name === name);
107
- if (input === undefined) throw new Error(`unknown SYQL input ${name}`);
108
- return input;
109
- }
110
-
111
100
  function syqlSwiftType(type: IrColumnType, nullable: boolean): string {
112
101
  return `${SYQL_SWIFT_TYPE[type]}${nullable ? '?' : ''}`;
113
102
  }
114
103
 
115
104
  function syqlControlActive(query: AnalyzedQuery, name: string): string {
116
105
  const input = syqlInput(query, name);
117
- const access = camelCase(input.langName);
106
+ const access = snakeToCamel(input.langName);
118
107
  if (input.kind === 'value' && input.default === false) return access;
119
108
  if (input.kind === 'value' && input.nullable) {
120
- return `{ if case .present = ${access} { return true }; return false }()`;
109
+ return `${access}.isPresent`;
121
110
  }
122
111
  if (input.kind === 'value' || input.kind === 'group') {
123
112
  return `${access} != nil`;
@@ -137,7 +126,7 @@ function syqlBindExpr(query: AnalyzedQuery, bind: QuerySyqlPlanBind): string {
137
126
  return `.bool(${active})`;
138
127
  }
139
128
  const input = syqlInput(query, bind.input);
140
- const access = camelCase(input.langName);
129
+ const access = snakeToCamel(input.langName);
141
130
  if (bind.kind === 'limit')
142
131
  return `.number(Double(effective${typeName(access)}))`;
143
132
  if (bind.kind === 'group-member') {
@@ -147,7 +136,7 @@ function syqlBindExpr(query: AnalyzedQuery, bind: QuerySyqlPlanBind): string {
147
136
  );
148
137
  if (member === undefined)
149
138
  throw new Error(`unknown group member ${bind.member}`);
150
- const memberName = camelCase(member.langName);
139
+ const memberName = snakeToCamel(member.langName);
151
140
  const present = member.nullable
152
141
  ? optionalParamValue(member.type, `value.${memberName}`)
153
142
  : paramValue(member.type, `value.${memberName}`);
@@ -173,18 +162,18 @@ function emitSyqlSwiftTypes(query: AnalyzedQuery): string[] {
173
162
  lines.push(`public struct ${name}: Sendable {`);
174
163
  for (const member of input.members) {
175
164
  lines.push(
176
- ` public let ${camelCase(member.langName)}: ${syqlSwiftType(member.type, member.nullable)}`,
165
+ ` public let ${snakeToCamel(member.langName)}: ${syqlSwiftType(member.type, member.nullable)}`,
177
166
  );
178
167
  }
179
168
  const args = input.members
180
169
  .map(
181
170
  (member) =>
182
- `${camelCase(member.langName)}: ${syqlSwiftType(member.type, member.nullable)}`,
171
+ `${snakeToCamel(member.langName)}: ${syqlSwiftType(member.type, member.nullable)}`,
183
172
  )
184
173
  .join(', ');
185
174
  lines.push(` public init(${args}) {`);
186
175
  for (const member of input.members) {
187
- const name = camelCase(member.langName);
176
+ const name = snakeToCamel(member.langName);
188
177
  lines.push(` self.${name} = ${name}`);
189
178
  }
190
179
  lines.push(' }', '}', '');
@@ -192,7 +181,7 @@ function emitSyqlSwiftTypes(query: AnalyzedQuery): string[] {
192
181
  const name = `${typeName(query.name)}${typeName(input.langName)}`;
193
182
  lines.push(`public enum ${name}: Int, Sendable {`);
194
183
  input.profiles.forEach((profile, index) => {
195
- lines.push(` case ${camelCase(profile.langName)} = ${index}`);
184
+ lines.push(` case ${snakeToCamel(profile.langName)} = ${index}`);
196
185
  });
197
186
  lines.push('}', '');
198
187
  }
@@ -213,7 +202,7 @@ function emitSyqlSwiftRunner(query: AnalyzedQuery): string[] {
213
202
  );
214
203
  const args = ['client: SyncularClient'];
215
204
  for (const input of metadata.inputs) {
216
- const name = camelCase(input.langName);
205
+ const name = snakeToCamel(input.langName);
217
206
  if (input.kind === 'value') {
218
207
  const type = syqlSwiftType(input.type, input.nullable);
219
208
  if (input.required) args.push(`${name}: ${type}`);
@@ -230,7 +219,7 @@ function emitSyqlSwiftRunner(query: AnalyzedQuery): string[] {
230
219
  input.profiles.find((profile) => profile.name === input.defaultProfile)
231
220
  ?.langName ?? input.defaultProfile;
232
221
  args.push(
233
- `${name}: ${typeName(query.name)}${typeName(input.langName)} = .${camelCase(defaultCase)}`,
222
+ `${name}: ${typeName(query.name)}${typeName(input.langName)} = .${snakeToCamel(defaultCase)}`,
234
223
  );
235
224
  } else {
236
225
  args.push(`${name}: Int? = nil`);
@@ -241,7 +230,7 @@ function emitSyqlSwiftRunner(query: AnalyzedQuery): string[] {
241
230
  );
242
231
  const page = metadata.inputs.find((input) => input.kind === 'limit');
243
232
  if (page?.kind === 'limit') {
244
- const name = camelCase(page.langName);
233
+ const name = snakeToCamel(page.langName);
245
234
  lines.push(
246
235
  ` let effective${typeName(name)} = ${name} ?? ${page.defaultSize}`,
247
236
  ` guard effective${typeName(name)} >= 1 && effective${typeName(name)} <= ${page.maxSize} else {`,
@@ -260,7 +249,7 @@ function emitSyqlSwiftRunner(query: AnalyzedQuery): string[] {
260
249
  const sort = metadata.inputs.find((input) => input.kind === 'sort');
261
250
  const profileCount = sort?.kind === 'sort' ? sort.profiles.length : 1;
262
251
  const sortIndex =
263
- sort?.kind === 'sort' ? `${camelCase(sort.langName)}.rawValue` : '0';
252
+ sort?.kind === 'sort' ? `${snakeToCamel(sort.langName)}.rawValue` : '0';
264
253
  const index =
265
254
  metadata.plan.backend === 'variants'
266
255
  ? `activationMask * ${profileCount} + ${sortIndex}`
@@ -298,13 +287,13 @@ function emitRowStruct(query: AnalyzedQuery): string[] {
298
287
  for (const column of query.columns) {
299
288
  const opt = column.nullable ? '?' : '';
300
289
  lines.push(
301
- ` public let ${camelCase(column.langName)}: ${SWIFT_TYPE[column.type]}${opt}`,
290
+ ` public let ${snakeToCamel(column.langName)}: ${SWIFT_TYPE[column.type]}${opt}`,
302
291
  );
303
292
  }
304
293
  lines.push('');
305
294
  lines.push(' public init?(row: [String: JSONValue]) {');
306
295
  for (const column of query.columns) {
307
- const name = camelCase(column.langName);
296
+ const name = snakeToCamel(column.langName);
308
297
  const accessor = rowAccessor(column);
309
298
  if (column.nullable) {
310
299
  lines.push(` self.${name} = ${accessor}`);
@@ -332,7 +321,7 @@ function emitRunner(query: AnalyzedQuery): string[] {
332
321
  lines.push(` /// Run the ${query.name} named query (SELECT-only).`);
333
322
  const args: string[] = [];
334
323
  for (const p of query.params) {
335
- const name = camelCase(p.langName);
324
+ const name = snakeToCamel(p.langName);
336
325
  args.push(`${name}: ${SWIFT_TYPE[p.type]}`);
337
326
  }
338
327
  const signature =
@@ -346,7 +335,7 @@ function emitRunner(query: AnalyzedQuery): string[] {
346
335
  if (query.params.length > 0) {
347
336
  const binds = query.params
348
337
  .map((p) => {
349
- const name = camelCase(p.langName);
338
+ const name = snakeToCamel(p.langName);
350
339
  return paramValue(p.type, name);
351
340
  })
352
341
  .join(', ');
@@ -392,6 +381,11 @@ export function emitQueriesSwiftModule(
392
381
  'public enum SyncularQueryPresence<Value: Sendable>: Sendable {',
393
382
  ' case absent',
394
383
  ' case present(Value)',
384
+ '',
385
+ ' public var isPresent: Bool {',
386
+ ' if case .present = self { return true }',
387
+ ' return false',
388
+ ' }',
395
389
  '}',
396
390
  '',
397
391
  'public struct SyncularQueryInputError: Error, Sendable {',
@@ -18,11 +18,11 @@
18
18
  * `--check` gates freshness byte-exactly, like every other emitter.
19
19
  */
20
20
  import type { IrColumnType } from './ir';
21
- import type {
22
- AnalyzedQuery,
23
- QueryParam,
24
- QuerySyqlPlanBind,
25
- QuerySyqlPublicInput,
21
+ import {
22
+ type AnalyzedQuery,
23
+ type QueryParam,
24
+ type QuerySyqlPlanBind,
25
+ syqlInput,
26
26
  } from './query';
27
27
 
28
28
  const TS_TYPE: Readonly<Record<IrColumnType, string>> = {
@@ -98,12 +98,6 @@ function reactiveParam(query: AnalyzedQuery, name: string): string {
98
98
  return `String(params.${propertyKey(param.langName)})`;
99
99
  }
100
100
 
101
- function syqlInput(query: AnalyzedQuery, name: string): QuerySyqlPublicInput {
102
- const input = query.syql?.inputs.find((candidate) => candidate.name === name);
103
- if (input === undefined) throw new Error(`unknown SYQL input ${name}`);
104
- return input;
105
- }
106
-
107
101
  function syqlTsValueType(type: IrColumnType, nullable: boolean): string {
108
102
  return `${SYQL_PARAM_TS_TYPE[type]}${nullable ? ' | null' : ''}`;
109
103
  }
package/src/emit-swift.ts CHANGED
@@ -2,8 +2,8 @@
2
2
  * Swift emitter: neutral IR → one standalone `.swift` file exporting
3
3
  *
4
4
  * - `enum <EnumName> { static let schema: JSONValue }` — the ServerSchema
5
- * object, built from the IR with byte-stable ordering (fed straight into
6
- * `SyncularClient(schema:)`),
5
+ * object: the exact `serializeSchema` JSON the TS module embeds, parsed
6
+ * from a string literal (fed straight into `SyncularClient(schema:)`),
7
7
  * - one `struct` per table with typed properties (per the six §2.4 column
8
8
  * types, plus blob_ref/crdt in their honest Swift shapes) and a
9
9
  * `init?(row:)` from a `[String: JSONValue]` (the shape `query`/`readRows`
@@ -14,8 +14,15 @@
14
14
  * IR hash so `--check` verifies freshness byte-exactly, exactly like the TS
15
15
  * emitter.
16
16
  */
17
- import type { IrColumnType, IrDocument, IrSubscription, IrTable } from './ir';
18
- import { snakeToCamel } from './naming';
17
+ import {
18
+ appColumnType,
19
+ type IrColumnType,
20
+ type IrDocument,
21
+ type IrSubscription,
22
+ type IrTable,
23
+ serializeSchema,
24
+ } from './ir';
25
+ import { pascalCase, snakeToCamel, stringLiteral } from './naming';
19
26
 
20
27
  /**
21
28
  * §2.4 column type → honest Swift type. `json`/`blob_ref` are the raw
@@ -33,93 +40,9 @@ const SWIFT_TYPE: Readonly<Record<IrColumnType, string>> = {
33
40
  crdt: '[UInt8]',
34
41
  };
35
42
 
36
- function appColumnType(column: IrTable['columns'][number]): IrColumnType {
37
- return column.encrypted === true && column.declaredType !== undefined
38
- ? column.declaredType
39
- : column.type;
40
- }
41
-
42
- /** §5.11: app-side Swift type — declaredType for an encrypted column. */
43
- function appSwiftType(column: IrTable['columns'][number]): string {
44
- return SWIFT_TYPE[appColumnType(column)];
45
- }
46
-
47
- function pascalCase(name: string): string {
48
- return name
49
- .split(/[_-]+/)
50
- .filter((part) => part.length > 0)
51
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
52
- .join('');
53
- }
54
-
55
- /** Language-facing field name — the pinned §12 naming map. */
56
- function camelCase(name: string): string {
57
- return snakeToCamel(name);
58
- }
59
-
60
- function quote(value: string): string {
61
- return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
62
- }
63
-
64
- /** Emit a `JSONValue` literal for the schema object (built from the IR). */
65
- function emitSchemaValue(ir: IrDocument, indent: string): string[] {
66
- const lines: string[] = [];
67
- const i = indent;
68
- lines.push(`${i}.object([`);
69
- lines.push(`${i} "version": .number(${ir.schemaVersion}),`);
70
- lines.push(`${i} "tables": .array([`);
71
- for (const table of ir.tables) {
72
- lines.push(`${i} .object([`);
73
- lines.push(`${i} "name": .string(${quote(table.name)}),`);
74
- lines.push(`${i} "primaryKey": .string(${quote(table.primaryKey)}),`);
75
- lines.push(`${i} "columns": .array([`);
76
- for (const column of table.columns) {
77
- const parts = [
78
- `"name": .string(${quote(column.name)})`,
79
- `"type": .string(${quote(column.type)})`,
80
- `"nullable": .bool(${column.nullable})`,
81
- ];
82
- if (column.crdtType !== undefined) {
83
- parts.push(`"crdtType": .string(${quote(column.crdtType)})`);
84
- }
85
- if (column.encrypted === true) {
86
- parts.push('"encrypted": .bool(true)');
87
- parts.push(
88
- `"declaredType": .string(${quote(column.declaredType ?? column.type)})`,
89
- );
90
- }
91
- lines.push(`${i} .object([${parts.join(', ')}]),`);
92
- }
93
- lines.push(`${i} ]),`);
94
- lines.push(`${i} "scopes": .array([`);
95
- for (const scope of table.scopes) {
96
- lines.push(
97
- `${i} .object(["pattern": .string(${quote(scope.pattern)}), "column": .string(${quote(scope.column)})]),`,
98
- );
99
- }
100
- lines.push(`${i} ]),`);
101
- if (table.ftsIndexes.length > 0) {
102
- lines.push(`${i} "ftsIndexes": .array([`);
103
- for (const index of table.ftsIndexes) {
104
- const columns = index.columns
105
- .map((column) => `.string(${quote(column)})`)
106
- .join(', ');
107
- lines.push(
108
- `${i} .object(["name": .string(${quote(index.name)}), "columns": .array([${columns}]), "tokenize": .string(${quote(index.tokenize)})]),`,
109
- );
110
- }
111
- lines.push(`${i} ]),`);
112
- }
113
- lines.push(`${i} ]),`);
114
- }
115
- lines.push(`${i} ]),`);
116
- lines.push(`${i}])`);
117
- return lines;
118
- }
119
-
120
43
  /** The accessor that lifts a §2.4 value out of a `[String: JSONValue]` row. */
121
44
  function rowAccessor(column: IrTable['columns'][number]): string {
122
- const key = `row[${quote(column.name)}]`;
45
+ const key = `row[${stringLiteral(column.name, 'swift')}]`;
123
46
  switch (appColumnType(column)) {
124
47
  case 'string':
125
48
  case 'json':
@@ -147,22 +70,22 @@ function emitStruct(table: IrTable): string[] {
147
70
  lines.push(`/// One ${table.name} row (§2.4 column order).`);
148
71
  lines.push(`public struct ${type}: Sendable, Equatable {`);
149
72
  for (const column of table.columns) {
150
- const swift = appSwiftType(column);
73
+ const swift = SWIFT_TYPE[appColumnType(column)];
151
74
  const opt = column.nullable ? '?' : '';
152
- lines.push(` public let ${camelCase(column.name)}: ${swift}${opt}`);
75
+ lines.push(` public let ${snakeToCamel(column.name)}: ${swift}${opt}`);
153
76
  }
154
77
  lines.push('');
155
78
  // Memberwise init (public, so app code can build rows too).
156
79
  const params = table.columns
157
80
  .map((c) => {
158
- const swift = appSwiftType(c);
81
+ const swift = SWIFT_TYPE[appColumnType(c)];
159
82
  const opt = c.nullable ? '? = nil' : '';
160
- return `${camelCase(c.name)}: ${swift}${opt}`;
83
+ return `${snakeToCamel(c.name)}: ${swift}${opt}`;
161
84
  })
162
85
  .join(', ');
163
86
  lines.push(` public init(${params}) {`);
164
87
  for (const column of table.columns) {
165
- const name = camelCase(column.name);
88
+ const name = snakeToCamel(column.name);
166
89
  lines.push(` self.${name} = ${name}`);
167
90
  }
168
91
  lines.push(' }');
@@ -175,7 +98,7 @@ function emitStruct(table: IrTable): string[] {
175
98
  );
176
99
  lines.push(' public init?(row: [String: JSONValue]) {');
177
100
  for (const column of table.columns) {
178
- const name = camelCase(column.name);
101
+ const name = snakeToCamel(column.name);
179
102
  const accessor = rowAccessor(column);
180
103
  if (column.nullable) {
181
104
  lines.push(` self.${name} = ${accessor}`);
@@ -200,12 +123,16 @@ function emitSubscription(sub: IrSubscription): string[] {
200
123
  }
201
124
  const lines: string[] = [];
202
125
  lines.push(
203
- ` /// Requested-scope template for the ${quote(sub.name)} subscription.`,
126
+ ` /// Requested-scope template for the ${stringLiteral(sub.name, 'swift')} subscription.`,
204
127
  );
205
128
  lines.push(` public enum ${pascalCase(sub.name)} {`);
206
- lines.push(` public static let name = ${quote(sub.name)}`);
207
- lines.push(` public static let table = ${quote(sub.table)}`);
208
- const args = params.map((p) => `${camelCase(p)}: String`).join(', ');
129
+ lines.push(
130
+ ` public static let name = ${stringLiteral(sub.name, 'swift')}`,
131
+ );
132
+ lines.push(
133
+ ` public static let table = ${stringLiteral(sub.table, 'swift')}`,
134
+ );
135
+ const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
209
136
  lines.push(
210
137
  ` public static func scopes(${args}) -> [String: [String]] {`,
211
138
  );
@@ -213,10 +140,14 @@ function emitSubscription(sub: IrSubscription): string[] {
213
140
  for (const scope of sub.scopes) {
214
141
  const values = scope.values
215
142
  .map((value) =>
216
- value.kind === 'literal' ? quote(value.value) : camelCase(value.name),
143
+ value.kind === 'literal'
144
+ ? stringLiteral(value.value, 'swift')
145
+ : snakeToCamel(value.name),
217
146
  )
218
147
  .join(', ');
219
- lines.push(` ${quote(scope.variable)}: [${values}],`);
148
+ lines.push(
149
+ ` ${stringLiteral(scope.variable, 'swift')}: [${values}],`,
150
+ );
220
151
  }
221
152
  lines.push(' ]');
222
153
  lines.push(' }');
@@ -250,10 +181,17 @@ export function emitSwiftModule(
250
181
  schemaLines.push(
251
182
  ` /// ServerSchema-compatible schema — pass to \`SyncularClient(schema:)\`.`,
252
183
  );
253
- schemaLines.push(' public static let schema: JSONValue =');
254
- for (const line of emitSchemaValue(ir, ' ')) {
255
- schemaLines.push(line);
184
+ // A multi-line literal strips the closing delimiter's indentation from
185
+ // every line, so the parsed string is the serializeSchema bytes. JSON
186
+ // escapes every quote inside a string, so it never holds the closing
187
+ // delimiter; doubling backslashes also disarms `\(` interpolation.
188
+ schemaLines.push(
189
+ ' public static let schema: JSONValue = try! JSONValue(decoding: """',
190
+ );
191
+ for (const line of serializeSchema(ir).split('\n')) {
192
+ schemaLines.push(` ${line.replaceAll('\\', '\\\\')}`);
256
193
  }
194
+ schemaLines.push(' """)');
257
195
  schemaLines.push('');
258
196
  // Subscriptions namespace nested in the schema enum.
259
197
  schemaLines.push(' /// Typed requested-scope builders per subscription.');
package/src/emit.ts CHANGED
@@ -12,8 +12,20 @@
12
12
  * The header carries the IR hash so `--check` verifies freshness
13
13
  * byte-exactly.
14
14
  */
15
- import type { IrColumnType, IrDocument, IrSubscription, IrTable } from './ir';
16
- import { type NamingMode, snakeToCamel } from './naming';
15
+ import {
16
+ appColumnType,
17
+ type IrColumnType,
18
+ type IrDocument,
19
+ type IrSubscription,
20
+ type IrTable,
21
+ serializeSchema,
22
+ } from './ir';
23
+ import {
24
+ type NamingMode,
25
+ pascalCase,
26
+ snakeToCamel,
27
+ stringLiteral,
28
+ } from './naming';
17
29
 
18
30
  const TS_TYPE: Readonly<Record<IrColumnType, string>> = {
19
31
  string: 'string',
@@ -30,110 +42,10 @@ const TS_TYPE: Readonly<Record<IrColumnType, string>> = {
30
42
  crdt: 'Uint8Array',
31
43
  };
32
44
 
33
- /**
34
- * §5.11: the app-side TS type of a column. An encrypted column's wire type is
35
- * `bytes`, but the app sees its declared type (the local mirror is plaintext).
36
- */
37
- function appTsType(column: IrTable['columns'][number]): string {
38
- const type =
39
- column.encrypted === true && column.declaredType !== undefined
40
- ? column.declaredType
41
- : column.type;
42
- return TS_TYPE[type];
43
- }
44
-
45
- function pascalCase(name: string): string {
46
- return name
47
- .split(/[_-]+/)
48
- .filter((part) => part.length > 0)
49
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
50
- .join('');
51
- }
52
-
53
- function quote(value: string): string {
54
- return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
55
- }
56
-
57
45
  const IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
58
46
 
59
47
  function propertyKey(name: string): string {
60
- return IDENTIFIER_RE.test(name) ? name : quote(name);
61
- }
62
-
63
- function emitSchema(ir: IrDocument): string {
64
- const lines: string[] = [];
65
- lines.push('/** ServerSchema-compatible schema object (SPEC §2.4, §3.1). */');
66
- lines.push('export const schema = {');
67
- lines.push(` version: ${ir.schemaVersion},`);
68
- lines.push(' tables: [');
69
- for (const table of ir.tables) {
70
- lines.push(' {');
71
- lines.push(` name: ${quote(table.name)},`);
72
- lines.push(' columns: [');
73
- for (const column of table.columns) {
74
- // §5.10.1: emit crdtType on crdt columns so a generated server schema
75
- // can select the merger; omitted (and thus unchanged) for others.
76
- const crdtType =
77
- column.crdtType !== undefined
78
- ? `, crdtType: ${quote(column.crdtType)}`
79
- : '';
80
- // §5.11: emit encrypted/declaredType on encrypted columns so the client
81
- // codec encrypts/decrypts them; omitted for others.
82
- const encrypted =
83
- column.encrypted === true
84
- ? `, encrypted: true, declaredType: ${quote(column.declaredType ?? column.type)}`
85
- : '';
86
- lines.push(
87
- ` { name: ${quote(column.name)}, type: ${quote(column.type)}, nullable: ${column.nullable}${crdtType}${encrypted} },`,
88
- );
89
- }
90
- lines.push(' ],');
91
- lines.push(` primaryKey: ${quote(table.primaryKey)},`);
92
- lines.push(' scopes: [');
93
- for (const scope of table.scopes) {
94
- lines.push(
95
- ` { pattern: ${quote(scope.pattern)}, column: ${quote(scope.column)} },`,
96
- );
97
- }
98
- lines.push(' ],');
99
- // §6.11 declared references — emitted only when the table declares any,
100
- // so reference-free tables keep their exact pre-reference generated bytes.
101
- if (table.references.length > 0) {
102
- lines.push(' references: [');
103
- for (const reference of table.references) {
104
- lines.push(
105
- ` { column: ${quote(reference.column)}, parentTable: ${quote(reference.parentTable)}, onDelete: ${quote(reference.onDelete)} },`,
106
- );
107
- }
108
- lines.push(' ],');
109
- }
110
- // Local secondary indexes — emitted only when the table declares any, so
111
- // index-free tables keep their exact pre-index generated bytes.
112
- if (table.indexes.length > 0) {
113
- lines.push(' indexes: [');
114
- for (const index of table.indexes) {
115
- const cols = index.columns.map((c) => quote(c)).join(', ');
116
- lines.push(
117
- ` { name: ${quote(index.name)}, columns: [${cols}], unique: ${index.unique} },`,
118
- );
119
- }
120
- lines.push(' ],');
121
- }
122
- if (table.ftsIndexes.length > 0) {
123
- lines.push(' ftsIndexes: [');
124
- for (const index of table.ftsIndexes) {
125
- const cols = index.columns.map((column) => quote(column)).join(', ');
126
- lines.push(
127
- ` { name: ${quote(index.name)}, columns: [${cols}], tokenize: ${quote(index.tokenize)} },`,
128
- );
129
- }
130
- lines.push(' ],');
131
- }
132
- lines.push(' },');
133
- }
134
- lines.push(' ],');
135
- lines.push('} as const;');
136
- return lines.join('\n');
48
+ return IDENTIFIER_RE.test(name) ? name : stringLiteral(name, 'ts');
137
49
  }
138
50
 
139
51
  function emitRowInterfaces(table: IrTable, naming: NamingMode): string {
@@ -147,7 +59,7 @@ function emitRowInterfaces(table: IrTable, naming: NamingMode): string {
147
59
  lines.push(`/** One ${table.name} row (§2.4 column order). */`);
148
60
  lines.push(`export interface ${type}Row {`);
149
61
  for (const column of table.columns) {
150
- const ts = appTsType(column);
62
+ const ts = TS_TYPE[appColumnType(column)];
151
63
  lines.push(
152
64
  ` ${key(column.name)}: ${ts}${column.nullable ? ' | null' : ''};`,
153
65
  );
@@ -157,7 +69,7 @@ function emitRowInterfaces(table: IrTable, naming: NamingMode): string {
157
69
  lines.push(`/** Insert shape: nullable columns may be omitted. */`);
158
70
  lines.push(`export interface ${type}Insert {`);
159
71
  for (const column of table.columns) {
160
- const ts = appTsType(column);
72
+ const ts = TS_TYPE[appColumnType(column)];
161
73
  lines.push(
162
74
  column.nullable
163
75
  ? ` ${key(column.name)}?: ${ts} | null;`
@@ -171,7 +83,7 @@ function emitRowInterfaces(table: IrTable, naming: NamingMode): string {
171
83
  );
172
84
  lines.push(`export interface ${type}Update {`);
173
85
  for (const column of table.columns) {
174
- const ts = appTsType(column);
86
+ const ts = TS_TYPE[appColumnType(column)];
175
87
  if (column.name === table.primaryKey) {
176
88
  lines.push(` ${key(column.name)}: ${ts};`);
177
89
  } else {
@@ -195,11 +107,11 @@ function emitTableDescriptor(table: IrTable, naming: NamingMode): string {
195
107
  naming === 'camel' ? snakeToCamel(table.primaryKey) : table.primaryKey;
196
108
  const constant = `${naming === 'camel' ? snakeToCamel(table.name) : table.name}Table`;
197
109
  return [
198
- `/** Typed mutation/resource descriptor for ${quote(table.name)}. */`,
199
- `export const ${constant}: SyncTable<${type}Row, ${type}Insert, ${type}Update, ${appTsType(primary)}> = {`,
200
- ` name: ${quote(table.name)},`,
201
- ` primaryKey: ${quote(field)},`,
202
- ` physicalPrimaryKey: ${quote(table.primaryKey)},`,
110
+ `/** Typed mutation/resource descriptor for ${stringLiteral(table.name, 'ts')}. */`,
111
+ `export const ${constant}: SyncTable<${type}Row, ${type}Insert, ${type}Update, ${TS_TYPE[appColumnType(primary)]}> = {`,
112
+ ` name: ${stringLiteral(table.name, 'ts')},`,
113
+ ` primaryKey: ${stringLiteral(field, 'ts')},`,
114
+ ` physicalPrimaryKey: ${stringLiteral(table.primaryKey, 'ts')},`,
203
115
  '};',
204
116
  ].join('\n');
205
117
  }
@@ -224,18 +136,18 @@ function emitSubscription(sub: IrSubscription): string {
224
136
  lines.push('');
225
137
  }
226
138
  lines.push(
227
- `/** Requested-scope template for the ${quote(sub.name)} subscription. */`,
139
+ `/** Requested-scope template for the ${stringLiteral(sub.name, 'ts')} subscription. */`,
228
140
  );
229
141
  lines.push(`export const ${sub.name}Subscription = {`);
230
- lines.push(` name: ${quote(sub.name)},`);
231
- lines.push(` table: ${quote(sub.table)},`);
142
+ lines.push(` name: ${stringLiteral(sub.name, 'ts')},`);
143
+ lines.push(` table: ${stringLiteral(sub.table, 'ts')},`);
232
144
  const args = params.length > 0 ? `params: ${paramsType}` : '';
233
145
  lines.push(` scopes: (${args}): Record<string, string[]> => ({`);
234
146
  for (const scope of sub.scopes) {
235
147
  const values = scope.values
236
148
  .map((value) =>
237
149
  value.kind === 'literal'
238
- ? quote(value.value)
150
+ ? stringLiteral(value.value, 'ts')
239
151
  : `params.${propertyKey(value.name)}`,
240
152
  )
241
153
  .join(', ');
@@ -276,7 +188,12 @@ export function emitModule(
276
188
  '}',
277
189
  ].join('\n'),
278
190
  );
279
- parts.push(emitSchema(ir));
191
+ parts.push(
192
+ [
193
+ '/** ServerSchema-compatible schema object (SPEC §2.4, §3.1). */',
194
+ `export const schema = ${serializeSchema(ir)} as const;`,
195
+ ].join('\n'),
196
+ );
280
197
  for (const table of ir.tables) {
281
198
  parts.push(emitRowInterfaces(table, naming));
282
199
  parts.push(emitTableDescriptor(table, naming));
package/src/errors.ts CHANGED
@@ -1,11 +1,22 @@
1
- /** Fail-loud codegen error: every message names the offending construct. */
1
+ /** Fail-loud codegen error: every message names the offending construct. A
2
+ * coded error carries a static message, its stable `code`, and the dynamic
3
+ * values (table, column, …) in `details`. */
2
4
  export class TypegenError extends Error {
3
5
  /** Input the error came from (a migration file, the manifest, …). */
4
6
  readonly source: string;
7
+ readonly code?: string;
8
+ readonly details?: Readonly<Record<string, unknown>>;
5
9
 
6
- constructor(source: string, message: string) {
10
+ constructor(
11
+ source: string,
12
+ message: string,
13
+ code?: string,
14
+ details?: Readonly<Record<string, unknown>>,
15
+ ) {
7
16
  super(`${source}: ${message}`);
8
17
  this.name = 'TypegenError';
9
18
  this.source = source;
19
+ if (code !== undefined) this.code = code;
20
+ if (details !== undefined) this.details = details;
10
21
  }
11
22
  }