@syncular/typegen 0.58.0 → 0.60.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 (78) hide show
  1. package/README.md +96 -43
  2. package/dist/cli.js +8 -3
  3. package/dist/emit-dart.d.ts +4 -3
  4. package/dist/emit-dart.js +40 -100
  5. package/dist/emit-kotlin.d.ts +4 -4
  6. package/dist/emit-kotlin.js +41 -99
  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 +18 -19
  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 +18 -27
  17. package/dist/emit-swift.d.ts +4 -4
  18. package/dist/emit-swift.js +43 -102
  19. package/dist/emit.d.ts +3 -3
  20. package/dist/emit.js +37 -113
  21. package/dist/errors.d.ts +6 -2
  22. package/dist/errors.js +10 -2
  23. package/dist/fmt.js +11 -2
  24. package/dist/generate.d.ts +4 -3
  25. package/dist/generate.js +61 -73
  26. package/dist/init.js +5 -6
  27. package/dist/ir.d.ts +14 -2
  28. package/dist/ir.js +67 -49
  29. package/dist/lower.d.ts +0 -7
  30. package/dist/lower.js +0 -62
  31. package/dist/lsp.js +6 -1
  32. package/dist/manifest.d.ts +1 -2
  33. package/dist/manifest.js +13 -12
  34. package/dist/migration-lock.d.ts +32 -23
  35. package/dist/migration-lock.js +115 -92
  36. package/dist/naming.d.ts +25 -0
  37. package/dist/naming.js +92 -0
  38. package/dist/query.d.ts +94 -14
  39. package/dist/query.js +642 -461
  40. package/dist/sql.js +18 -3
  41. package/dist/syql-ast.d.ts +2 -0
  42. package/dist/syql-ast.js +7 -1
  43. package/dist/syql-browser.js +7 -6
  44. package/dist/syql-diagnostics.d.ts +1 -0
  45. package/dist/syql-diagnostics.js +1 -0
  46. package/dist/syql-lowering.js +11 -1
  47. package/dist/syql-parser.d.ts +4 -1
  48. package/dist/syql-parser.js +42 -5
  49. package/dist/syql-validator.js +13 -220
  50. package/package.json +3 -3
  51. package/src/cli.ts +9 -3
  52. package/src/emit-dart.ts +44 -116
  53. package/src/emit-kotlin.ts +41 -118
  54. package/src/emit-queries-dart.ts +23 -32
  55. package/src/emit-queries-kotlin.ts +20 -30
  56. package/src/emit-queries-rust.ts +29 -31
  57. package/src/emit-queries-swift.ts +26 -32
  58. package/src/emit-queries.ts +26 -47
  59. package/src/emit-swift.ts +49 -120
  60. package/src/emit.ts +45 -135
  61. package/src/errors.ts +13 -2
  62. package/src/fmt.ts +10 -2
  63. package/src/generate.ts +113 -107
  64. package/src/init.ts +8 -6
  65. package/src/ir.ts +91 -54
  66. package/src/lower.ts +0 -53
  67. package/src/lsp.ts +11 -4
  68. package/src/manifest.ts +22 -18
  69. package/src/migration-lock.ts +192 -137
  70. package/src/naming.ts +154 -0
  71. package/src/query.ts +864 -502
  72. package/src/sql.ts +30 -3
  73. package/src/syql-ast.ts +9 -0
  74. package/src/syql-browser.ts +8 -7
  75. package/src/syql-diagnostics.ts +2 -0
  76. package/src/syql-lowering.ts +16 -1
  77. package/src/syql-parser.ts +73 -8
  78. package/src/syql-validator.ts +21 -279
package/src/emit-swift.ts CHANGED
@@ -2,20 +2,27 @@
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`
10
10
  * return),
11
- * - a `subscriptions` namespace of typed requested-scope builders.
11
+ * - a `subscriptions` namespace of typed unit-template builders (SPEC §4.1).
12
12
  *
13
13
  * The file imports only `Syncular` (for `JSONValue`). The header carries the
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}`);
@@ -190,33 +113,30 @@ function emitStruct(table: IrTable): string[] {
190
113
  }
191
114
 
192
115
  function emitSubscription(sub: IrSubscription): string[] {
193
- const params: string[] = [];
194
- for (const scope of sub.scopes) {
195
- for (const value of scope.values) {
196
- if (value.kind === 'parameter' && !params.includes(value.name)) {
197
- params.push(value.name);
198
- }
199
- }
200
- }
116
+ const params = [
117
+ ...new Set(
118
+ sub.scopes.flatMap(({ value }) =>
119
+ value.kind === 'parameter' ? [value.name] : [],
120
+ ),
121
+ ),
122
+ ];
201
123
  const lines: string[] = [];
202
124
  lines.push(
203
- ` /// Requested-scope template for the ${quote(sub.name)} subscription.`,
125
+ ` /// Unit template for the ${stringLiteral(sub.name, 'swift')} subscription (SPEC §4.1).`,
204
126
  );
205
127
  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(', ');
209
128
  lines.push(
210
- ` public static func scopes(${args}) -> [String: [String]] {`,
129
+ ` public static let name = ${stringLiteral(sub.name, 'swift')}`,
130
+ );
131
+ const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
132
+ lines.push(
133
+ ` public static func scopes(${args}) -> [String: String] {`,
211
134
  );
212
135
  lines.push(' [');
213
- for (const scope of sub.scopes) {
214
- const values = scope.values
215
- .map((value) =>
216
- value.kind === 'literal' ? quote(value.value) : camelCase(value.name),
217
- )
218
- .join(', ');
219
- lines.push(` ${quote(scope.variable)}: [${values}],`);
136
+ for (const { variable, value } of sub.scopes) {
137
+ lines.push(
138
+ ` ${stringLiteral(variable, 'swift')}: ${value.kind === 'literal' ? stringLiteral(value.value, 'swift') : snakeToCamel(value.name)},`,
139
+ );
220
140
  }
221
141
  lines.push(' ]');
222
142
  lines.push(' }');
@@ -250,13 +170,22 @@ export function emitSwiftModule(
250
170
  schemaLines.push(
251
171
  ` /// ServerSchema-compatible schema — pass to \`SyncularClient(schema:)\`.`,
252
172
  );
253
- schemaLines.push(' public static let schema: JSONValue =');
254
- for (const line of emitSchemaValue(ir, ' ')) {
255
- schemaLines.push(line);
173
+ // A multi-line literal strips the closing delimiter's indentation from
174
+ // every line, so the parsed string is the serializeSchema bytes. JSON
175
+ // escapes every quote inside a string, so it never holds the closing
176
+ // delimiter; doubling backslashes also disarms `\(` interpolation.
177
+ schemaLines.push(
178
+ ' public static let schema: JSONValue = try! JSONValue(decoding: """',
179
+ );
180
+ for (const line of serializeSchema(ir).split('\n')) {
181
+ schemaLines.push(` ${line.replaceAll('\\', '\\\\')}`);
256
182
  }
183
+ schemaLines.push(' """)');
257
184
  schemaLines.push('');
258
185
  // Subscriptions namespace nested in the schema enum.
259
- schemaLines.push(' /// Typed requested-scope builders per subscription.');
186
+ schemaLines.push(
187
+ ' /// Typed unit-template builders per subscription (SPEC §4.1).',
188
+ );
260
189
  schemaLines.push(' public enum subscriptions {');
261
190
  if (ir.subscriptions.length === 0) {
262
191
  schemaLines.push(' // (no subscriptions declared)');
package/src/emit.ts CHANGED
@@ -6,14 +6,26 @@
6
6
  * - a `<Table>Row` interface per table,
7
7
  * - `<Table>Insert` / `<Table>Update` mutation-input shapes honoring
8
8
  * nullability,
9
- * - a `<name>Subscription` helper constant per manifest subscription with
10
- * a typed requested-scopes builder.
9
+ * - a `<name>Subscription` helper constant per manifest unit template with
10
+ * a typed builder of its unit scope map (SPEC §4.1).
11
11
  *
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,24 +107,23 @@ 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
  }
206
118
 
207
119
  function emitSubscription(sub: IrSubscription): string {
208
- const params: string[] = [];
209
- for (const scope of sub.scopes) {
210
- for (const value of scope.values) {
211
- if (value.kind === 'parameter' && !params.includes(value.name)) {
212
- params.push(value.name);
213
- }
214
- }
215
- }
120
+ const params = [
121
+ ...new Set(
122
+ sub.scopes.flatMap(({ value }) =>
123
+ value.kind === 'parameter' ? [value.name] : [],
124
+ ),
125
+ ),
126
+ ];
216
127
  const lines: string[] = [];
217
128
  const paramsType = `${pascalCase(sub.name)}Params`;
218
129
  if (params.length > 0) {
@@ -224,22 +135,16 @@ function emitSubscription(sub: IrSubscription): string {
224
135
  lines.push('');
225
136
  }
226
137
  lines.push(
227
- `/** Requested-scope template for the ${quote(sub.name)} subscription. */`,
138
+ `/** Unit template for the ${stringLiteral(sub.name, 'ts')} subscription (SPEC §4.1). */`,
228
139
  );
229
140
  lines.push(`export const ${sub.name}Subscription = {`);
230
- lines.push(` name: ${quote(sub.name)},`);
231
- lines.push(` table: ${quote(sub.table)},`);
141
+ lines.push(` name: ${stringLiteral(sub.name, 'ts')},`);
232
142
  const args = params.length > 0 ? `params: ${paramsType}` : '';
233
- lines.push(` scopes: (${args}): Record<string, string[]> => ({`);
234
- for (const scope of sub.scopes) {
235
- const values = scope.values
236
- .map((value) =>
237
- value.kind === 'literal'
238
- ? quote(value.value)
239
- : `params.${propertyKey(value.name)}`,
240
- )
241
- .join(', ');
242
- lines.push(` ${propertyKey(scope.variable)}: [${values}],`);
143
+ lines.push(` scopes: (${args}): Record<string, string> => ({`);
144
+ for (const { variable, value } of sub.scopes) {
145
+ lines.push(
146
+ ` ${propertyKey(variable)}: ${value.kind === 'literal' ? stringLiteral(value.value, 'ts') : `params.${propertyKey(value.name)}`},`,
147
+ );
243
148
  }
244
149
  lines.push(' }),');
245
150
  lines.push('} as const;');
@@ -276,7 +181,12 @@ export function emitModule(
276
181
  '}',
277
182
  ].join('\n'),
278
183
  );
279
- parts.push(emitSchema(ir));
184
+ parts.push(
185
+ [
186
+ '/** ServerSchema-compatible schema object (SPEC §2.4, §3.1). */',
187
+ `export const schema = ${serializeSchema(ir)} as const;`,
188
+ ].join('\n'),
189
+ );
280
190
  for (const table of ir.tables) {
281
191
  parts.push(emitRowInterfaces(table, naming));
282
192
  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
  }
package/src/fmt.ts CHANGED
@@ -267,6 +267,7 @@ function formatTokens(parsed: SyqlSyntaxFile): string {
267
267
  let importList = false;
268
268
  let justClosedImportList = false;
269
269
  let seenTopLevel = false;
270
+ let acknowledging = false;
270
271
  let pendingBetween = 0;
271
272
  let inlineParameterRecord = false;
272
273
  let justClosedInlineParameterRecord = false;
@@ -284,10 +285,17 @@ function formatTokens(parsed: SyqlSyntaxFile): string {
284
285
  (lower === 'import' ||
285
286
  lower === 'predicate' ||
286
287
  lower === 'query' ||
287
- lower === 'sync') &&
288
+ lower === 'sync' ||
289
+ (lower === 'allow' &&
290
+ (previous === undefined ||
291
+ previous.kind === 'string' ||
292
+ previous.text === '}'))) &&
288
293
  !(lower === 'query' && previous?.text === 'sync');
289
294
  if (topLevelDeclaration) {
290
- if (seenTopLevel) writer.blankline();
295
+ // Acknowledgements sit on their own lines directly above their query.
296
+ if (acknowledging) writer.newline();
297
+ else if (seenTopLevel) writer.blankline();
298
+ acknowledging = lower === 'allow';
291
299
  seenTopLevel = true;
292
300
  previous = undefined;
293
301
  awaitsDeclarationParameters = lower === 'predicate' || lower === 'query';