@syncular/typegen 0.58.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
package/dist/naming.js CHANGED
@@ -40,6 +40,31 @@ export function snakeToCamel(name) {
40
40
  .map((s) => s.charAt(0).toUpperCase() + s.slice(1));
41
41
  return lead + first + rest.join('') + trail;
42
42
  }
43
+ /** Generated type name of a table or subscription: `_`/`-` separated parts,
44
+ * each with its first character upper-cased (`project_tasks` →
45
+ * `ProjectTasks`). */
46
+ export function pascalCase(name) {
47
+ return name
48
+ .split(/[_-]+/)
49
+ .filter((part) => part.length > 0)
50
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
51
+ .join('');
52
+ }
53
+ /** `value` as a string literal of a schema emitter's language. Swift and
54
+ * Kotlin delimit with `"`, TS and Dart with `'`; Kotlin and Dart also escape
55
+ * the `$` that would start an interpolation. */
56
+ export function stringLiteral(value, target) {
57
+ const delimiter = target === 'swift' || target === 'kotlin' ? '"' : "'";
58
+ const interpolates = target === 'kotlin' || target === 'dart';
59
+ let body = '';
60
+ for (const char of value) {
61
+ body +=
62
+ char === '\\' || char === delimiter || (interpolates && char === '$')
63
+ ? `\\${char}`
64
+ : char;
65
+ }
66
+ return `${delimiter}${body}${delimiter}`;
67
+ }
43
68
  /** Reserved words that cannot be a generated field/property name on each
44
69
  * target. Deliberately the core keyword lists — mechanical and predictable
45
70
  * beats exhaustive; an escape hatch (`AS` alias / "preserve") always exists. */
@@ -362,3 +387,70 @@ export function buildNamingMap(sqlNames, mode, context, scope, targets) {
362
387
  langName: bySqlName.get(sqlName),
363
388
  }));
364
389
  }
390
+ /**
391
+ * The schema identifier rules for every configured target in both naming
392
+ * modes. Table names, and column names within a table, stay distinct under
393
+ * SQLite's case-insensitive comparison; generated type names
394
+ * (`pascalCase(table)`) stay distinct; each target's emitted column names
395
+ * stay distinct and clear of its reserved words. Swift, Kotlin, and Dart
396
+ * always emit camelCase fields; TS and Rust follow the naming mode.
397
+ */
398
+ export function validateSchemaIdentifiers(tables, mode, targets, context) {
399
+ const distinct = (names, key, code, message, details = {}) => {
400
+ const seen = new Map();
401
+ for (const name of names) {
402
+ const other = seen.get(key(name));
403
+ if (other !== undefined) {
404
+ throw new TypegenError(context, message, code, {
405
+ ...details,
406
+ names: [other, name],
407
+ });
408
+ }
409
+ seen.set(key(name), name);
410
+ }
411
+ };
412
+ const caseless = (name) => name.toLowerCase();
413
+ const tableNames = tables.map((table) => table.name);
414
+ distinct(tableNames, caseless, 'typegen.duplicate_identifier', 'two table names differ only in letter case; SQLite compares identifiers case-insensitively');
415
+ distinct(tableNames, pascalCase, 'typegen.identifier_collision', 'two tables map to one generated type name');
416
+ for (const table of tables) {
417
+ const columnNames = table.columns.map((column) => column.name);
418
+ distinct(columnNames, caseless, 'typegen.duplicate_identifier', 'two column names differ only in letter case; SQLite compares identifiers case-insensitively', { table: table.name });
419
+ for (const target of targets) {
420
+ const emit = (name) => {
421
+ const langName = mode === 'camel' || (target !== 'ts' && target !== 'rust')
422
+ ? snakeToCamel(name)
423
+ : name;
424
+ return target === 'rust' ? rustSnakeCase(langName) : langName;
425
+ };
426
+ distinct(columnNames, emit, 'typegen.identifier_collision', 'two columns map to one generated field name', { target, table: table.name });
427
+ for (const column of columnNames) {
428
+ const emitted = emit(column);
429
+ if (TARGET_KEYWORDS[target].has(emitted) ||
430
+ (target === 'dart' && emitted.startsWith('_'))) {
431
+ throw new TypegenError(context, 'a column maps to a generated field name that is a reserved word or library-private on an emitter target; rename the column', 'typegen.reserved_identifier', { target, table: table.name, column, emitted });
432
+ }
433
+ }
434
+ }
435
+ }
436
+ }
437
+ /**
438
+ * Refuse a query name, result column, or query input that some configured
439
+ * target cannot emit: TS uses the name as is, Rust its snake_case form, and
440
+ * Swift, Kotlin, and Dart its camelCase form. Each must be an identifier
441
+ * clear of the target's reserved words; Dart also refuses a leading `_`.
442
+ */
443
+ export function validateQueryIdentifier(name, targets, context, scope) {
444
+ for (const target of targets) {
445
+ const emitted = target === 'rust'
446
+ ? rustSnakeCase(name)
447
+ : target === 'ts'
448
+ ? name
449
+ : snakeToCamel(name);
450
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(emitted) ||
451
+ TARGET_KEYWORDS[target].has(emitted) ||
452
+ (target === 'dart' && emitted.startsWith('_'))) {
453
+ throw new TypegenError(context, 'a query name, result column, or query input is not a valid identifier on an emitter target; rename it or alias it in SQL (AS)', 'typegen.invalid_query_identifier', { target, scope, name, emitted });
454
+ }
455
+ }
456
+ }
package/dist/query.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type SyqlToken } from './syql-lexer.js';
1
2
  import type { IrColumnType, IrDocument } from './ir.js';
2
3
  import { type NamingMode, type NamingTarget } from './naming.js';
3
4
  /** A param type is one of the §2.4 types (the columns params compare to). */
@@ -20,7 +21,7 @@ export interface QueryColumn {
20
21
  readonly type: IrColumnType;
21
22
  readonly nullable: boolean;
22
23
  /** `exact` = resolved to an IR column (plain ref); `fallback` = a computed
23
- * expression typed by the documented honest fallback. */
24
+ * expression typed by its `CAST` or `count()` (SYQL §14.1). */
24
25
  readonly fidelity: 'exact' | 'fallback';
25
26
  /** Proven physical origin for reactive row identity and diagnostics. */
26
27
  readonly origin?: {
@@ -188,6 +189,8 @@ export interface AnalyzedQuery {
188
189
  * present, emitters use this instead of treating `params` as the API. */
189
190
  readonly syql?: QuerySyqlMetadata;
190
191
  }
192
+ /** The public SYQL input an emitter binds by name. */
193
+ export declare function syqlInput(query: AnalyzedQuery, name: string): QuerySyqlPublicInput;
191
194
  /**
192
195
  * Path-relative default name. `billing/invoices/list.sql` → `billingInvoicesList`;
193
196
  * a flat `list-todos.sql` → `listTodos` (unchanged). Every folder segment AND
@@ -206,19 +209,19 @@ export interface SplitStatement {
206
209
  /** 1-based line number of the statement's first character in the file. */
207
210
  readonly startLine: number;
208
211
  }
209
- /** Split file content into statements on top-level `;` (string/comment-aware).
210
- * Blank/comment-only tails are dropped; each statement keeps its own leading
211
- * comment block (everything between the previous `;` and this SQL). */
212
- export declare function splitStatements(content: string): SplitStatement[];
212
+ /** Split file content into statements on top-level `;` tokens. A statement
213
+ * keeps its leading comment block; comment-only parts are dropped. The
214
+ * SELECT-only subset has no BEGIN/END blocks, so every `;` token ends one
215
+ * statement and a trailing `;` is optional. */
216
+ export declare function splitStatements(content: string, file?: string): SplitStatement[];
213
217
  /** The `-- name:` override in a statement's leading comment block, or null. */
214
218
  export declare function parseStatementName(statementText: string, location: string): string | null;
215
- /** Strip `--` and block comments so identifier scans don't hit commented SQL,
216
- * and string literals so `':x'` inside a string isn't read as a param. */
219
+ /** Blank comments and string/blob literals with spaces (newlines kept), so
220
+ * offset-preserving text scans never read inside them. */
217
221
  export declare function stripCommentsAndStrings(sql: string): string;
218
- /** Rewrite `:name` → positional placeholders AND strip comments + collapse
219
- * whitespace, producing a clean single-line SQL string suitable for
220
- * embedding in a generated string literal. String literals are preserved
221
- * verbatim (their inner whitespace is not collapsed).
222
+ /** The emitted single-line statement: `:name` binds become positional, every
223
+ * whitespace/comment run between tokens becomes one space, and every other
224
+ * token (string literals, quoted identifiers) keeps its exact text.
222
225
  *
223
226
  * When every param occurs exactly once, plain `?` is emitted. When ANY
224
227
  * param repeats (the §7 neutralization guards mention a param in the guard
@@ -236,6 +239,8 @@ export interface TableRef {
236
239
  /** True when an enclosing flat join chain can null-extend this relation. */
237
240
  readonly nullable: boolean;
238
241
  }
242
+ /** The name a plain or quoted identifier token spells. */
243
+ export declare function sqlIdentifier(token: SyqlToken | undefined): string | undefined;
239
244
  /** A common table expression read in a FROM/JOIN position. */
240
245
  export interface CteRef {
241
246
  /** Lowercased CTE name. */
@@ -268,6 +273,41 @@ export declare function scanTableRefs(sql: string, ir: IrDocument, lowered?: boo
268
273
  /** `lowered` scans emitted SQL, whose FTS mapping reads
269
274
  * ({@link lowerFtsSourceIds}) are internal and not relations of the query. */
270
275
  export declare function scanRelations(sql: string, ir: IrDocument, lowered?: boolean): SqlRelations;
276
+ /** A declared scope column of one table instance: the instance's SELECT scope
277
+ * ({@link SqlRelations.scopeAt}), lowercased alias, and lowercased column. */
278
+ export interface ScopeColumn {
279
+ readonly scope: string;
280
+ readonly alias: string;
281
+ readonly column: string;
282
+ }
283
+ export interface ScopeProofs {
284
+ /** `column = :bind`, `:bind = column`, `column IS :bind`, and
285
+ * `column IN (:a, :b)` conjuncts of a WHERE clause. */
286
+ readonly binds: readonly (ScopeColumn & {
287
+ readonly operator: 'equal' | 'in';
288
+ readonly params: readonly string[];
289
+ })[];
290
+ /** Qualified `a.x = b.y` conjuncts. A symmetric equality (a WHERE conjunct
291
+ * or an inner-join ON conjunct) proves each operand from the other; an
292
+ * outer-join ON conjunct proves only `target` from `source`. */
293
+ readonly equalities: readonly {
294
+ readonly target: ScopeColumn;
295
+ readonly source: ScopeColumn;
296
+ readonly symmetric: boolean;
297
+ }[];
298
+ }
299
+ /**
300
+ * The scope-proof rule shared by `.sql` and `.syql` queries (SYQL §13). A
301
+ * comparison proves a scope only when it is a whole top-level conjunct of
302
+ * the WHERE clause of the SELECT scope that reads the instance: the outer
303
+ * statement or a top-level CTE body. Parentheses around a whole conjunct are
304
+ * transparent. Nothing else is a proof: a WHERE clause with a top-level OR, a
305
+ * compound SELECT scope, a nested subquery, and any other conjunct shape (NOT,
306
+ * a comparison of the comparison, a function, CASE, COLLATE, IS after the
307
+ * bind, a literal in an IN list). Column equalities also come from the
308
+ * conjuncts of an ON clause without OR, NOT, or a subquery.
309
+ */
310
+ export declare function scopeProofs(sql: string, ir: IrDocument): ScopeProofs;
271
311
  export interface SelectItem {
272
312
  /** The raw expression text (before any `AS alias`). */
273
313
  readonly expr: string;
@@ -279,11 +319,11 @@ export interface SelectItem {
279
319
  export declare function splitSelectList(sql: string): SelectItem[] | null;
280
320
  export declare const PLAIN_REF_RE: RegExp;
281
321
  /**
282
- * Return every revision-1 column/LIKE type constraint for one bind. Unlike
283
- * `inferParamType` (the legacy first-match helper), SYQL uses the complete set
284
- * so conflicting checked uses cannot be silently accepted.
322
+ * Every column/LIKE/MATCH type constraint on one bind, in pattern order. A
323
+ * `.sql` query takes the first; SYQL rejects conflicting evidence.
285
324
  */
286
325
  export declare function inferParamTypeEvidence(paramName: string, sql: string, refs: readonly TableRef[], ir: IrDocument): readonly IrColumnType[];
326
+ export declare const AGGREGATE_FUNCTIONS: Set<string>;
287
327
  export interface QueryDb {
288
328
  /** Prepare + return the result columns / declared types / param count.
289
329
  * Throws (with SQLite's message) when the SQL is invalid against the DDL. */