@native-sdk/cli 0.8.4 → 0.9.1

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 (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -0,0 +1,806 @@
1
+ // SQLite schema/query analysis and deterministic generated surfaces.
2
+ // The real SQLite parser is the authority: migrations run against an
3
+ // in-memory DatabaseSync and every declared statement is prepared there.
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import crypto from "node:crypto";
8
+ import { constants as sqliteConstants, DatabaseSync, type StatementSync } from "node:sqlite";
9
+ import { inspectRelationalSql, relationalRuntimePolicy, relationalTableReferences, setRelationalAuthorizer } from "./sqlite_runtime_policy.ts";
10
+
11
+ export interface SqliteDiagnostic {
12
+ readonly rule: `NS14${number}`;
13
+ readonly message: string;
14
+ readonly file: string;
15
+ readonly line: number;
16
+ readonly column: number;
17
+ readonly fix?: string;
18
+ readonly why?: string;
19
+ readonly warning?: boolean;
20
+ }
21
+
22
+ export interface MigrationSource {
23
+ readonly version: number;
24
+ readonly name: string;
25
+ readonly file: string;
26
+ readonly sql: string;
27
+ readonly hash: string;
28
+ }
29
+
30
+ export type SqlType = "INTEGER" | "REAL" | "TEXT" | "BLOB" | "ANY";
31
+
32
+ export interface QueryField {
33
+ readonly name: string;
34
+ readonly sqlType: SqlType;
35
+ readonly nullable: boolean;
36
+ }
37
+
38
+ export interface DeclaredQuery {
39
+ readonly name: string;
40
+ readonly kind: "query" | "exec";
41
+ readonly live: boolean;
42
+ readonly file: string;
43
+ readonly line: number;
44
+ readonly sql: string;
45
+ readonly params: readonly QueryField[];
46
+ readonly columns: readonly QueryField[];
47
+ readonly tables: readonly string[];
48
+ }
49
+
50
+ export interface SqliteAnalysis {
51
+ readonly migrations: readonly MigrationSource[];
52
+ readonly queries: readonly DeclaredQuery[];
53
+ readonly diagnostics: readonly SqliteDiagnostic[];
54
+ readonly warnings: readonly SqliteDiagnostic[];
55
+ readonly schemaHash: string;
56
+ }
57
+
58
+ const migrationPattern = /^(\d{4})_([a-z0-9][a-z0-9_-]*)\.sql$/;
59
+ const queryHeader = /^\s*--\s*name:\s*([A-Za-z][A-Za-z0-9]*)(?:\s+(:exec))?(?:\s+(:live))?\s*$/;
60
+ const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
61
+
62
+ function diag(rule: `NS14${number}`, file: string, line: number, message: string, fix?: string, why?: string, warning = false): SqliteDiagnostic {
63
+ return { rule, file, line, column: 1, message, ...(fix ? { fix } : {}), ...(why ? { why } : {}), ...(warning ? { warning: true } : {}) };
64
+ }
65
+
66
+ function sqliteMessage(error: unknown): string {
67
+ return error instanceof Error ? error.message.replace(/^SQLITE_ERROR:\s*/, "") : String(error);
68
+ }
69
+
70
+ function scanParameters(sql: string): { names: string[]; unsupported: boolean } {
71
+ const names: string[] = [];
72
+ let unsupported = false;
73
+ let at = 0;
74
+ while (at < sql.length) {
75
+ const char = sql[at]!;
76
+ if (char === "'" || char === '"' || char === "`") {
77
+ const quote = char;
78
+ at += 1;
79
+ while (at < sql.length) {
80
+ if (sql[at] !== quote) { at += 1; continue; }
81
+ if (sql[at + 1] === quote) { at += 2; continue; }
82
+ at += 1;
83
+ break;
84
+ }
85
+ continue;
86
+ }
87
+ if (char === "[") {
88
+ const end = sql.indexOf("]", at + 1);
89
+ at = end < 0 ? sql.length : end + 1;
90
+ continue;
91
+ }
92
+ if (char === "-" && sql[at + 1] === "-") {
93
+ const end = sql.indexOf("\n", at + 2);
94
+ at = end < 0 ? sql.length : end + 1;
95
+ continue;
96
+ }
97
+ if (char === "/" && sql[at + 1] === "*") {
98
+ const end = sql.indexOf("*/", at + 2);
99
+ at = end < 0 ? sql.length : end + 2;
100
+ continue;
101
+ }
102
+ if (char === ":" && /[A-Za-z_]/.test(sql[at + 1] ?? "")) {
103
+ let end = at + 2;
104
+ while (/[A-Za-z0-9_]/.test(sql[end] ?? "")) end += 1;
105
+ const name = sql.slice(at + 1, end);
106
+ if (!names.includes(name)) names.push(name);
107
+ at = end;
108
+ continue;
109
+ }
110
+ if (char === "?" || ((char === "$" || char === "@") && /[A-Za-z_]/.test(sql[at + 1] ?? ""))) {
111
+ unsupported = true;
112
+ }
113
+ at += 1;
114
+ }
115
+ return { names, unsupported };
116
+ }
117
+
118
+ function tailHasStatement(sql: string, sourceSQL: string): boolean {
119
+ const tail = sql.slice(sourceSQL.length);
120
+ let at = 0;
121
+ while (at < tail.length) {
122
+ const char = tail[at]!;
123
+ if (/\s/.test(char) || char === ";") { at += 1; continue; }
124
+ if (char === "-" && tail[at + 1] === "-") {
125
+ const end = tail.indexOf("\n", at + 2);
126
+ if (end < 0) return false;
127
+ at = end + 1;
128
+ continue;
129
+ }
130
+ if (char === "/" && tail[at + 1] === "*") {
131
+ const end = tail.indexOf("*/", at + 2);
132
+ if (end < 0) return false;
133
+ at = end + 2;
134
+ continue;
135
+ }
136
+ return true;
137
+ }
138
+ return false;
139
+ }
140
+
141
+ function execMigrationSql(db: DatabaseSync, sql: string): void {
142
+ let tail = sql;
143
+ while (tailHasStatement(tail, "")) {
144
+ const statement = db.prepare(tail);
145
+ const inspection = inspectRelationalSql(statement.sourceSQL, true);
146
+ if (inspection.error !== null) throw new Error(inspection.error);
147
+ statement.run();
148
+ tail = tail.slice(statement.sourceSQL.length);
149
+ }
150
+ }
151
+
152
+ function sha256(parts: readonly string[]): string {
153
+ const hash = crypto.createHash("sha256");
154
+ for (const part of parts) hash.update(part).update("\0");
155
+ return hash.digest("hex");
156
+ }
157
+
158
+ export function analyzeSqlite(srcDir: string): SqliteAnalysis {
159
+ const diagnostics: SqliteDiagnostic[] = [];
160
+ const warnings: SqliteDiagnostic[] = [];
161
+ const schemaDir = path.join(srcDir, "schema");
162
+ const migrations: MigrationSource[] = [];
163
+ if (fs.existsSync(schemaDir)) {
164
+ for (const name of fs.readdirSync(schemaDir).sort()) {
165
+ const file = path.join(schemaDir, name);
166
+ if (!fs.statSync(file).isFile()) continue;
167
+ const match = migrationPattern.exec(name);
168
+ if (!match) {
169
+ if (name.endsWith(".sql")) diagnostics.push(diag("NS1401", file, 1, `Migration \`${name}\` is not named NNNN_description.sql.`, "Rename it to a four-digit, monotonically numbered migration such as 0001_init.sql.", "Migration filenames are the durable schema version; their order must be unambiguous."));
170
+ continue;
171
+ }
172
+ const version = Number(match[1]);
173
+ const sql = fs.readFileSync(file, "utf8").replaceAll("\r\n", "\n");
174
+ migrations.push({ version, name: match[2], file, sql, hash: sha256([sql]) });
175
+ }
176
+ }
177
+ migrations.sort((a, b) => a.version - b.version);
178
+ for (let i = 0; i < migrations.length; i++) {
179
+ const expected = i + 1;
180
+ if (migrations[i]!.version !== expected) diagnostics.push(diag("NS1402", migrations[i]!.file, 1, `Migration version ${migrations[i]!.version} appears where ${expected} is required.`, `Number migrations contiguously; the next filename is ${String(expected).padStart(4, "0")}_name.sql.`, "The runtime advances PRAGMA user_version one append-only step at a time and never guesses across gaps."));
181
+ if (!tailHasStatement(migrations[i]!.sql, "")) diagnostics.push(diag("NS1403", migrations[i]!.file, 1, "A migration is empty.", "Add the schema change, or remove the unshipped migration and create it again.", "Every published version is monotonic and may never be reused."));
182
+ if (migrations[i]!.sql.includes("\0")) diagnostics.push(diag("NS1403", migrations[i]!.file, 1, "A migration contains a NUL byte.", "Remove the NUL byte and keep the migration as ordinary UTF-8 SQL.", "Both SQLite's C API and the generated runtime module require an unambiguous SQL boundary."));
183
+ if (Buffer.byteLength(migrations[i]!.sql) > 1024 * 1024) diagnostics.push(diag("NS1403", migrations[i]!.file, 1, "A migration exceeds the 1 MiB runtime bound.", "Split the schema change across consecutive migrations.", "Migration input has its own explicit bound so startup memory is predictable."));
184
+ }
185
+
186
+ const db = new DatabaseSync(":memory:");
187
+ db.exec("PRAGMA foreign_keys=ON;");
188
+ if (diagnostics.length === 0) {
189
+ db.exec("BEGIN IMMEDIATE;");
190
+ let migrationAuthorizerInstalled = false;
191
+ let activeMigration: MigrationSource | undefined;
192
+ try {
193
+ migrationAuthorizerInstalled = setRelationalAuthorizer(db, (action, first, second) => {
194
+ if (action === sqliteConstants.SQLITE_TRANSACTION || action === sqliteConstants.SQLITE_SAVEPOINT) {
195
+ return sqliteConstants.SQLITE_DENY;
196
+ }
197
+ return relationalRuntimePolicy(action, first, second);
198
+ });
199
+ for (const migration of migrations) {
200
+ activeMigration = migration;
201
+ try {
202
+ execMigrationSql(db, migration.sql);
203
+ } catch (error) {
204
+ diagnostics.push(diag("NS1404", migration.file, 1, `SQLite rejected migration ${String(migration.version).padStart(4, "0")}: ${sqliteMessage(error)}.`, "Fix the SQL at this migration; native check applies the real SQLite dialect in memory.", "Shipping a migration that fails would prevent the app database from opening."));
205
+ break;
206
+ }
207
+ }
208
+ if (migrationAuthorizerInstalled) setRelationalAuthorizer(db, null);
209
+ migrationAuthorizerInstalled = false;
210
+ if (diagnostics.length === 0) {
211
+ db.exec(`PRAGMA user_version=${migrations.at(-1)?.version ?? 0};`);
212
+ db.exec("COMMIT;");
213
+ }
214
+ else db.exec("ROLLBACK;");
215
+ } catch (error) {
216
+ if (migrationAuthorizerInstalled) {
217
+ try { setRelationalAuthorizer(db, null); } catch {}
218
+ }
219
+ try { db.exec("ROLLBACK;"); } catch {}
220
+ if (diagnostics.length === 0) {
221
+ const migration = activeMigration ?? migrations.at(-1);
222
+ diagnostics.push(diag(
223
+ "NS1404",
224
+ migration?.file ?? schemaDir,
225
+ 1,
226
+ `SQLite could not commit the migration chain: ${sqliteMessage(error)}.`,
227
+ "Remove transaction-control SQL from migrations and fix the reported SQLite error.",
228
+ "The runtime owns the one transaction that applies the complete pending migration chain.",
229
+ ));
230
+ }
231
+ }
232
+ }
233
+
234
+ if (diagnostics.length === 0) {
235
+ const tableRows = db.prepare("PRAGMA table_list;").all() as Array<Record<string, unknown>>;
236
+ for (const row of tableRows) {
237
+ const name = String(row.name ?? "");
238
+ const schema = String(row.schema ?? "");
239
+ const kind = String(row.type ?? "");
240
+ if (schema !== "main" || name.startsWith("sqlite_") || kind !== "table") continue;
241
+ if (Number(row.strict ?? 0) !== 1) diagnostics.push(diag("NS1405", migrations.at(-1)?.file ?? schemaDir, 1, `Table \`${name}\` is not STRICT.`, `Declare it with \`CREATE TABLE ${name}(...) STRICT\` in its introducing migration.`, "Generated parameter and result types are honest only when SQLite enforces the declared storage classes."));
242
+ }
243
+ }
244
+
245
+ const queriesFile = path.join(srcDir, "queries.sql");
246
+ const queries: DeclaredQuery[] = [];
247
+ if (fs.existsSync(queriesFile) && diagnostics.length === 0) {
248
+ let statementWrites = false;
249
+ let statementControlsTransaction = false;
250
+ const queryAuthorizerInstalled = setRelationalAuthorizer(db, (action, first, second) => {
251
+ if (action === sqliteConstants.SQLITE_INSERT || action === sqliteConstants.SQLITE_UPDATE || action === sqliteConstants.SQLITE_DELETE) statementWrites = true;
252
+ if (action === sqliteConstants.SQLITE_TRANSACTION || action === sqliteConstants.SQLITE_SAVEPOINT) statementControlsTransaction = true;
253
+ return relationalRuntimePolicy(action, first, second);
254
+ });
255
+ const source = fs.readFileSync(queriesFile, "utf8").replaceAll("\r\n", "\n");
256
+ const lines = source.split("\n");
257
+ const headers: Array<{ name: string; exec: boolean; live: boolean; line: number; headerStart: number; start: number }> = [];
258
+ let offset = 0;
259
+ for (let i = 0; i < lines.length; i++) {
260
+ const match = queryHeader.exec(lines[i]!);
261
+ if (match) headers.push({ name: match[1]!, exec: match[2] === ":exec", live: match[3] === ":live", line: i + 1, headerStart: offset, start: offset + lines[i]!.length + 1 });
262
+ offset += lines[i]!.length + 1;
263
+ }
264
+ if (source.trim().length > 0 && headers.length === 0) diagnostics.push(diag("NS1410", queriesFile, 1, "queries.sql contains no named query blocks.", "Start each statement with `-- name: queryName`, optionally followed by `:exec` or `:live`.", "Stable names are the generated API and the live-query replay identity."));
265
+ if (headers.length > 0 && tailHasStatement(source.slice(0, headers[0]!.headerStart), "")) diagnostics.push(diag("NS1410", queriesFile, 1, "queries.sql contains SQL before its first named query block.", "Put a `-- name: queryName` header immediately before every statement.", "Unnamed SQL has no generated constructor and would otherwise escape build-time validation."));
266
+ const names = new Set<string>();
267
+ const generatedNames = new Map<string, string>();
268
+ const reservesTransactionBuilder = headers.some((header) => header.exec);
269
+ for (let i = 0; i < headers.length; i++) {
270
+ const header = headers[i]!;
271
+ const end = i + 1 < headers.length ? headers[i + 1]!.headerStart : source.length;
272
+ const sql = source.slice(header.start, end).trim();
273
+ if (names.has(header.name)) {
274
+ diagnostics.push(diag("NS1411", queriesFile, header.line, `Declared query name \`${header.name}\` is duplicated.`, "Give every block a unique camelCase name.", "Generated members and journal identities must be one-to-one."));
275
+ continue;
276
+ }
277
+ names.add(header.name);
278
+ const generatedName = `q${pascal(header.name)}`;
279
+ const priorName = generatedNames.get(generatedName);
280
+ if (priorName !== undefined || (reservesTransactionBuilder && generatedName === "qTx")) {
281
+ const conflict = priorName === undefined ? "the generated transaction builder" : `declared query \`${priorName}\``;
282
+ diagnostics.push(diag("NS1411", queriesFile, header.line, `Declared query \`${header.name}\` generates \`${generatedName}\`, which collides with ${conflict}.`, "Rename the query so its generated q<Name> member is unique after the first letter is capitalized.", "Generated constructors, row types, decoders, and replay identities must stay one-to-one."));
283
+ continue;
284
+ }
285
+ generatedNames.set(generatedName, header.name);
286
+ if (sql.length === 0) {
287
+ diagnostics.push(diag("NS1412", queriesFile, header.line, `Declared query \`${header.name}\` has no SQL.`, "Put exactly one SQLite statement below its name header."));
288
+ continue;
289
+ }
290
+ if (header.live && header.exec) {
291
+ diagnostics.push(diag("NS1413", queriesFile, header.line, `Declared query \`${header.name}\` cannot be both :exec and :live.`, "Remove :live; subscriptions are read queries."));
292
+ continue;
293
+ }
294
+ try {
295
+ statementWrites = false;
296
+ statementControlsTransaction = false;
297
+ const inspection = inspectRelationalSql(sql, true);
298
+ if (inspection.error !== null) throw new Error(inspection.error);
299
+ const statement = db.prepare(sql);
300
+ const writes = queryAuthorizerInstalled ? statementWrites : inspection.writes;
301
+ const controlsTransaction = statementControlsTransaction;
302
+ if (tailHasStatement(sql, statement.sourceSQL)) throw new Error("declared query contains more than one statement");
303
+ const columns = statement.columns();
304
+ if (controlsTransaction) throw new Error("transaction control is engine-owned and cannot be declared");
305
+ if (header.exec && !writes) throw new Error(":exec statement is read-only");
306
+ if (!header.exec && writes) throw new Error("writable statement must be declared with :exec and cannot return rows");
307
+ if (header.exec && columns.length > 0) throw new Error(":exec statement returns rows");
308
+ if (!header.exec && columns.length === 0) throw new Error("query returns no columns; declare writes with :exec");
309
+ const columnNames = new Set<string>();
310
+ for (const column of columns) {
311
+ if (columnNames.has(column.name)) throw new Error(`result column \`${column.name}\` is duplicated; give every selected column a unique AS alias`);
312
+ columnNames.add(column.name);
313
+ }
314
+ const parameterScan = scanParameters(sql);
315
+ if (parameterScan.unsupported) throw new Error("declared queries use :named parameters, not positional, $named, or @named placeholders");
316
+ const params = inferParams(db, sql, parameterScan.names);
317
+ const explain = db.prepare(`EXPLAIN ${sql}`);
318
+ if (params.length === 0) explain.all();
319
+ else explain.all(dummyBindings(params.map((param) => param.name)));
320
+ const result = columns.map((column, index) => inferColumn(db, column, sql, index, columns.length));
321
+ const tables = dependencyTables(db, sql, params.map((p) => p.name));
322
+ if (header.live && tables.length === 0) diagnostics.push(diag("NS1421", queriesFile, header.line, `Live query \`${header.name}\` has no table dependency and cannot refresh.`, "Remove :live for a one-shot query, or select from a schema table.", "A live subscription must have at least one generated table dependency so committed writes can invalidate it."));
323
+ for (const field of [...params, ...result]) {
324
+ if (field.sqlType === "INTEGER" && /(^id$|_id$|Id$)/.test(field.name)) {
325
+ warnings.push(diag("NS1422", queriesFile, header.line, `INTEGER identifier \`${field.name}\` in \`${header.name}\` maps to an exact TypeScript number.`, "Keep identifier values within -(2^53-1)..(2^53-1); generated page decoders reject wider i64 values instead of rounding them.", "Choosing number keeps the app-core API uniform; an explicit bigint tier can be added later without silently changing existing generated contracts.", true));
326
+ }
327
+ }
328
+ queries.push({ name: header.name, kind: header.exec ? "exec" : "query", live: header.live, file: queriesFile, line: header.line, sql, params, columns: result, tables });
329
+ } catch (error) {
330
+ diagnostics.push(diag("NS1414", queriesFile, header.line + 1, `SQLite rejected declared query \`${header.name}\`: ${sqliteMessage(error)}.`, "Fix the table, column, parameter, or statement shape named by SQLite.", "Declared queries are prepared against the schema produced by the complete migration chain."));
331
+ }
332
+ }
333
+ }
334
+ db.close();
335
+ return { migrations, queries, diagnostics, warnings, schemaHash: sha256(migrations.flatMap((m) => [String(m.version), m.name, m.hash])) };
336
+ }
337
+
338
+ function normalizeType(type: string | null): SqlType {
339
+ const upper = (type ?? "").toUpperCase();
340
+ if (upper.includes("INT")) return "INTEGER";
341
+ if (upper.includes("REAL") || upper.includes("FLOA") || upper.includes("DOUB")) return "REAL";
342
+ if (upper.includes("TEXT") || upper.includes("CHAR") || upper.includes("CLOB")) return "TEXT";
343
+ if (upper.includes("BLOB")) return "BLOB";
344
+ return "ANY";
345
+ }
346
+
347
+ function tableInfo(db: DatabaseSync, table: string): Array<Record<string, unknown>> {
348
+ const quoted = table.replaceAll("'", "''");
349
+ return db.prepare(`PRAGMA table_xinfo('${quoted}');`).all() as Array<Record<string, unknown>>;
350
+ }
351
+
352
+ function inferColumn(db: DatabaseSync, column: ReturnType<StatementSync["columns"]>[number], sql: string, index: number, columnCount: number): QueryField {
353
+ let sqlType = normalizeType(column.type);
354
+ let nullable = true;
355
+ if (column.table && column.column) {
356
+ const row = tableInfo(db, column.table).find((entry) => String(entry.name) === column.column);
357
+ if (row) nullable = Number(row.notnull ?? 0) !== 1 && Number(row.pk ?? 0) === 0;
358
+ }
359
+ if (isDirectCountColumn(sql, index, columnCount)) {
360
+ nullable = false;
361
+ sqlType = "INTEGER";
362
+ }
363
+ // Statement.columns() reports the origin and declared type of the first
364
+ // SELECT arm only. Later compound arms may legally contribute NULL or any
365
+ // other SQLite storage class, so that metadata cannot narrow the row wire.
366
+ if (hasTopLevelCompoundSelect(sql)) {
367
+ nullable = true;
368
+ sqlType = "ANY";
369
+ }
370
+ // SQLite's column-origin metadata names the underlying NOT NULL column,
371
+ // but an outer join may synthesize NULL for it. Conservatively widen all
372
+ // result columns in an outer-join statement; generated decoding must never
373
+ // reject a legal row merely to claim a narrower type.
374
+ if (/\b(?:left|right|full)(?:\s+outer)?\s+join\b/i.test(sql)) nullable = true;
375
+ // SQLite retains the origin metadata of a NOT NULL table column through a
376
+ // scalar subquery, but an empty scalar subquery produces NULL. The origin
377
+ // still determines the storage class; only its nullability must widen.
378
+ const expressions = topLevelSelectExpressions(sql);
379
+ if (expressions.length === columnCount && containsSubquery(expressions[index] ?? "")) nullable = true;
380
+ return { name: column.name, sqlType, nullable };
381
+ }
382
+
383
+ function containsSubquery(expression: string): boolean {
384
+ let quote = "";
385
+ for (let at = 0; at < expression.length; at++) {
386
+ const char = expression[at]!;
387
+ if (quote) {
388
+ if (char === quote && expression[at + 1] === quote) { at += 1; continue; }
389
+ if (char === quote) quote = "";
390
+ continue;
391
+ }
392
+ if (char === "'" || char === "\"" || char === "`") { quote = char; continue; }
393
+ if (char === "[") {
394
+ const end = expression.indexOf("]", at + 1);
395
+ at = end < 0 ? expression.length : end;
396
+ continue;
397
+ }
398
+ if (char !== "(") continue;
399
+ let next = at + 1;
400
+ while (next < expression.length) {
401
+ if (/\s/.test(expression[next]!)) { next += 1; continue; }
402
+ if (expression[next] === "-" && expression[next + 1] === "-") {
403
+ const end = expression.indexOf("\n", next + 2);
404
+ next = end < 0 ? expression.length : end + 1;
405
+ continue;
406
+ }
407
+ if (expression[next] === "/" && expression[next + 1] === "*") {
408
+ const end = expression.indexOf("*/", next + 2);
409
+ next = end < 0 ? expression.length : end + 2;
410
+ continue;
411
+ }
412
+ break;
413
+ }
414
+ if (/^(?:select|with)\b/i.test(expression.slice(next))) return true;
415
+ }
416
+ return false;
417
+ }
418
+
419
+ function hasTopLevelCompoundSelect(sql: string): boolean {
420
+ let depth = 0;
421
+ let quote = "";
422
+ for (let at = 0; at < sql.length; at++) {
423
+ const char = sql[at]!;
424
+ if (quote) {
425
+ if (char === quote && sql[at + 1] === quote) { at += 1; continue; }
426
+ if (char === quote) quote = "";
427
+ continue;
428
+ }
429
+ if (char === "'" || char === '"' || char === "`") { quote = char; continue; }
430
+ if (char === "[") {
431
+ const end = sql.indexOf("]", at + 1);
432
+ at = end < 0 ? sql.length : end;
433
+ continue;
434
+ }
435
+ if (char === "-" && sql[at + 1] === "-") {
436
+ const end = sql.indexOf("\n", at + 2);
437
+ at = end < 0 ? sql.length : end;
438
+ continue;
439
+ }
440
+ if (char === "/" && sql[at + 1] === "*") {
441
+ const end = sql.indexOf("*/", at + 2);
442
+ at = end < 0 ? sql.length : end + 1;
443
+ continue;
444
+ }
445
+ if (char === "(") { depth += 1; continue; }
446
+ if (char === ")") { depth -= 1; continue; }
447
+ if (depth !== 0 || /[A-Za-z0-9_]/.test(sql[at - 1] ?? "")) continue;
448
+ if (/^(?:union|intersect|except)\b/i.test(sql.slice(at))) return true;
449
+ }
450
+ return false;
451
+ }
452
+
453
+ function isDirectCountColumn(sql: string, index: number, columnCount: number): boolean {
454
+ const expressions = topLevelSelectExpressions(sql);
455
+ if (expressions.length !== columnCount) return false;
456
+ const expression = expressions[index]?.trim().replace(/^distinct\s+/i, "") ?? "";
457
+ const count = /^count\s*\(/i.exec(expression);
458
+ if (!count) return false;
459
+ let depth = 0;
460
+ let quote = "";
461
+ for (let at = expression.indexOf("(", count.index); at < expression.length; at++) {
462
+ const char = expression[at]!;
463
+ if (quote) {
464
+ if (char === quote && expression[at + 1] === quote) { at += 1; continue; }
465
+ if (char === quote) quote = "";
466
+ continue;
467
+ }
468
+ if (char === "'" || char === '"' || char === "`") { quote = char; continue; }
469
+ if (char === "(") depth += 1;
470
+ else if (char === ")" && --depth === 0) {
471
+ const suffix = expression.slice(at + 1).trim();
472
+ return suffix.length === 0 || /^(?:as\s+)?(?:[A-Za-z_][A-Za-z0-9_]*|"(?:[^"]|"")+"|`(?:[^`]|``)+`|\[(?:[^\]]|\]\])+\])$/i.test(suffix);
473
+ }
474
+ }
475
+ return false;
476
+ }
477
+
478
+ function topLevelSelectExpressions(sql: string): string[] {
479
+ let depth = 0;
480
+ let quote = "";
481
+ let selectEnd = -1;
482
+ let expressionStart = -1;
483
+ const expressions: string[] = [];
484
+ for (let at = 0; at < sql.length; at++) {
485
+ const char = sql[at]!;
486
+ if (quote) {
487
+ if (char === quote && sql[at + 1] === quote) { at += 1; continue; }
488
+ if (char === quote) quote = "";
489
+ continue;
490
+ }
491
+ if (char === "'" || char === '"' || char === "`") { quote = char; continue; }
492
+ if (char === "[") {
493
+ const end = sql.indexOf("]", at + 1);
494
+ at = end < 0 ? sql.length : end;
495
+ continue;
496
+ }
497
+ if (char === "-" && sql[at + 1] === "-") {
498
+ const end = sql.indexOf("\n", at + 2);
499
+ at = end < 0 ? sql.length : end;
500
+ continue;
501
+ }
502
+ if (char === "/" && sql[at + 1] === "*") {
503
+ const end = sql.indexOf("*/", at + 2);
504
+ at = end < 0 ? sql.length : end + 1;
505
+ continue;
506
+ }
507
+ if (char === "(") { depth += 1; continue; }
508
+ if (char === ")") { depth -= 1; continue; }
509
+ if (depth !== 0) continue;
510
+ const wordBoundary = !/[A-Za-z0-9_]/.test(sql[at - 1] ?? "");
511
+ if (selectEnd < 0 && wordBoundary && /^select\b/i.test(sql.slice(at))) {
512
+ selectEnd = at + 6;
513
+ expressionStart = selectEnd;
514
+ at += 5;
515
+ continue;
516
+ }
517
+ if (selectEnd < 0) continue;
518
+ if (char === ",") {
519
+ expressions.push(sql.slice(expressionStart, at));
520
+ expressionStart = at + 1;
521
+ continue;
522
+ }
523
+ if (wordBoundary && /^(?:from|union|intersect|except)\b/i.test(sql.slice(at))) {
524
+ expressions.push(sql.slice(expressionStart, at));
525
+ return expressions;
526
+ }
527
+ }
528
+ if (expressionStart >= 0) expressions.push(sql.slice(expressionStart));
529
+ return expressions;
530
+ }
531
+
532
+ function inferParams(db: DatabaseSync, sql: string, names: readonly string[]): QueryField[] {
533
+ const tables = new Map<string, Array<Record<string, unknown>>>();
534
+ const mainTables = canonicalMainTables(db);
535
+ for (const reference of relationalTableReferences(sql)) {
536
+ if (reference.schema !== null && reference.schema !== "main") continue;
537
+ const table = mainTables.get(reference.table);
538
+ if (table !== undefined) tables.set(table, tableInfo(db, table));
539
+ }
540
+ const allColumns = [...tables.values()].flat();
541
+ return names.map((name) => {
542
+ let type: SqlType = "ANY";
543
+ let nullable = true;
544
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
545
+ const around = new RegExp(`(?:(?:[A-Za-z_][A-Za-z0-9_]*\\.)?([A-Za-z_][A-Za-z0-9_]*)\\s*(?:=|<>|!=|<=|>=|<|>|MATCH|LIKE|GLOB|IS)\\s*:${escaped}|:${escaped}\\s*(?:=|<>|!=|<=|>=|<|>|MATCH|LIKE|GLOB|IS)\\s*(?:[A-Za-z_][A-Za-z0-9_]*\\.)?([A-Za-z_][A-Za-z0-9_]*))`, "i").exec(sql);
546
+ let columnName = around?.[1] ?? around?.[2];
547
+ if (!columnName) {
548
+ const insert = /\binsert\s+into\s+(?:main\.)?["`\[]?([A-Za-z_][A-Za-z0-9_]*)[^\(]*\(([^)]*)\)\s*values\s*\(([^)]*)\)/i.exec(sql);
549
+ if (insert) {
550
+ const columns = insert[2]!.split(",").map((value) => value.trim().replace(/^["`\[]|["`\]]$/g, ""));
551
+ const values = insert[3]!.split(",").map((value) => value.trim());
552
+ const valueIndex = values.findIndex((value) => value === `:${name}`);
553
+ if (valueIndex >= 0) columnName = columns[valueIndex];
554
+ }
555
+ }
556
+ if (columnName) {
557
+ const matches = allColumns.filter((entry) => String(entry.name) === columnName);
558
+ const inferredTypes = new Set(matches.map((entry) => normalizeType(String(entry.type ?? ""))));
559
+ if (matches.length > 0 && inferredTypes.size === 1) {
560
+ type = inferredTypes.values().next().value ?? "ANY";
561
+ nullable = matches.some((row) => Number(row.notnull ?? 0) !== 1 && Number(row.pk ?? 0) === 0);
562
+ }
563
+ }
564
+ return { name, sqlType: type, nullable };
565
+ });
566
+ }
567
+
568
+ function dummyBindings(names: readonly string[]): Record<string, null> {
569
+ return Object.fromEntries(names.map((name) => [name, null]));
570
+ }
571
+
572
+ function dependencyTables(db: DatabaseSync, sql: string, params: readonly string[]): string[] {
573
+ const found = new Set<string>();
574
+ for (const reference of relationalTableReferences(sql)) {
575
+ if (reference.schema === null || reference.schema === "main") found.add(reference.table);
576
+ }
577
+ try {
578
+ const rows = db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all(dummyBindings(params)) as Array<Record<string, unknown>>;
579
+ for (const row of rows) {
580
+ const detail = String(row.detail ?? "");
581
+ for (const match of detail.matchAll(/\b(?:SCAN|SEARCH)\s+(?:TABLE\s+)?([A-Za-z_][A-Za-z0-9_]*)/gi)) found.add(match[1]!);
582
+ }
583
+ } catch {}
584
+ const tableRows = (db.prepare("PRAGMA table_list;").all() as Array<Record<string, unknown>>)
585
+ .filter((row) => String(row.schema) === "main");
586
+ const realTables = new Map(tableRows.map((row) => [String(row.name).toLowerCase(), String(row.name)]));
587
+ const dependencies = new Set(
588
+ [...found]
589
+ .map((name) => realTables.get(name.toLowerCase()))
590
+ .filter((name): name is string => name !== undefined && !name.toLowerCase().startsWith("sqlite_")),
591
+ );
592
+ // sqlite3_update_hook names FTS shadow tables, not the virtual table the
593
+ // SELECT spells. Carry those generated dependencies too so FTS live
594
+ // queries invalidate on every committed index mutation.
595
+ for (const name of [...dependencies]) {
596
+ const virtual = tableRows.find((row) => String(row.name) === name && String(row.type) === "virtual");
597
+ if (!virtual) continue;
598
+ for (const row of tableRows) {
599
+ const shadow = String(row.name);
600
+ if (String(row.type) === "shadow" && shadow.startsWith(`${name}_`)) dependencies.add(shadow);
601
+ }
602
+ }
603
+ return [...dependencies].sort();
604
+ }
605
+
606
+ function canonicalMainTables(db: DatabaseSync): Map<string, string> {
607
+ const rows = db.prepare("PRAGMA table_list;").all() as Array<Record<string, unknown>>;
608
+ return new Map(
609
+ rows
610
+ .filter((row) => String(row.schema) === "main")
611
+ .map((row) => [String(row.name).toLowerCase(), String(row.name)]),
612
+ );
613
+ }
614
+
615
+ function tsType(field: QueryField, parameter = false): string {
616
+ // Dynamic core text is UTF-8 bytes. Generated TEXT parameters wrap those
617
+ // bytes with dbText() at the wire edge; decoded TEXT rows stay bytes so a
618
+ // subscribed row can live honestly in Model.
619
+ const base = field.sqlType === "INTEGER" || field.sqlType === "REAL" ? "number" : field.sqlType === "TEXT" || field.sqlType === "BLOB" ? "Uint8Array" : parameter ? "DbValue" : "DbDecodedValue";
620
+ return field.nullable ? `${base} | null` : base;
621
+ }
622
+
623
+ function paramExpr(field: QueryField): string {
624
+ const access = `params.${field.name}`;
625
+ if (field.sqlType !== "TEXT") return access;
626
+ return field.nullable ? `${access} === null ? null : dbText(${access})` : `dbText(${access})`;
627
+ }
628
+
629
+ function pascal(name: string): string {
630
+ return name[0]!.toUpperCase() + name.slice(1);
631
+ }
632
+
633
+ function js(value: string): string {
634
+ return JSON.stringify(value);
635
+ }
636
+
637
+ export function generatedFragments(analysis: SqliteAnalysis): { types: string; cmds: string; subs: string } {
638
+ const typeLines: string[] = [];
639
+ const cmdLines: string[] = [];
640
+ const subLines: string[] = [];
641
+ const rowQueries = analysis.queries.filter((query) => query.kind === "query");
642
+ if (rowQueries.length > 0) {
643
+ typeLines.push(`export type DbDecodedValue = null | number | Uint8Array;`);
644
+ typeLines.push(`function nsgDbPageNeed(bytes: Uint8Array, at: number, count: number): void { if (at < 0 || count < 0 || at + count > bytes.length) throw new Error("a relational page ended mid-value"); }`);
645
+ typeLines.push(`function nsgDbPageU32(bytes: Uint8Array, at: number): number { nsgDbPageNeed(bytes, at, 4); return bytes[at]! + bytes[at + 1]! * 256 + bytes[at + 2]! * 65536 + bytes[at + 3]! * 16777216; }`);
646
+ typeLines.push(`function nsgDbPageI64(bytes: Uint8Array, at: number): number { nsgDbPageNeed(bytes, at, 8); const lo = nsgDbPageU32(bytes, at); const hiUnsigned = nsgDbPageU32(bytes, at + 4); const hi = hiUnsigned >= 2147483648 ? hiUnsigned - 4294967296 : hiUnsigned; const value = hi * 4294967296 + lo; if (!Number.isSafeInteger(value)) throw new Error("a SQLite INTEGER exceeds TypeScript's exact number range"); return Math.trunc(value); }`);
647
+ typeLines.push(`function nsgDbPageF64(bytes: Uint8Array, at: number): number { nsgDbPageNeed(bytes, at, 8); const value = new DataView(bytes.buffer, bytes.byteOffset + at, 8).getFloat64(0, true); if (!Number.isFinite(value)) throw new Error("a relational page carries a non-finite REAL"); return value; }`);
648
+ }
649
+ for (const query of analysis.queries) {
650
+ const stem = pascal(query.name);
651
+ typeLines.push(`export interface ${stem}Params {`);
652
+ for (const param of query.params) typeLines.push(` readonly ${param.name}: ${tsType(param, true)};`);
653
+ typeLines.push("}");
654
+ if (query.kind === "query") {
655
+ typeLines.push(`export interface ${stem}Row {`);
656
+ for (const column of query.columns) typeLines.push(` readonly ${ident.test(column.name) ? column.name : js(column.name)}: ${tsType(column)};`);
657
+ typeLines.push("}");
658
+ typeLines.push(generatePageDecoder(query, stem));
659
+ }
660
+ }
661
+ const execNames = analysis.queries.filter((q) => q.kind === "exec");
662
+ for (const query of analysis.queries) {
663
+ const stem = pascal(query.name);
664
+ const values = query.params.map(paramExpr).join(", ");
665
+ if (query.kind === "query") {
666
+ cmdLines.push(`q${stem}<M extends Msgish>(params: ${stem}Params, route: TypedRowsRoute<${stem}Row, M>): Cmd<M> { return Cmd.db.query(${js(query.sql)}, [${values}], route); },`);
667
+ } else {
668
+ cmdLines.push(`q${stem}(params: ${stem}Params): TypedDbStatement { return { sql: ${js(query.sql)}, params: [${values}], __typedDbStatement: true }; },`);
669
+ }
670
+ }
671
+ if (execNames.length > 0) cmdLines.push("qTx<M extends Msgish>(statements: ReadonlyArray<TypedDbStatement>, route: WriteRoute<M>): Cmd<M> { const raw: DbStatement[] = []; for (const statement of statements) raw.push([statement.sql, statement.params]); return Cmd.db.exec(raw, route); },");
672
+ const live = analysis.queries.filter((q) => q.live);
673
+ for (const query of live) {
674
+ const stem = pascal(query.name);
675
+ const values = query.params.map(paramExpr).join(", ");
676
+ subLines.push(`q${stem}<M extends Msgish>(key: string, params: ${stem}Params, route: TypedRowsRoute<${stem}Row, M>): Sub<M> { return { op: "db_live", key, pageKind: route.page, doneKind: route.done, errKind: route.err, sql: ${js(query.sql)}, params: [${values}], tables: [${query.tables.map(js).join(", ")}] }; },`);
677
+ }
678
+ return { types: typeLines.join("\n"), cmds: cmdLines.join("\n"), subs: subLines.join("\n") };
679
+ }
680
+
681
+ function generatePageDecoder(query: DeclaredQuery, stem: string): string {
682
+ const out: string[] = [`export function decode${stem}Page(bytes: Uint8Array): ReadonlyArray<${stem}Row> {`, " let at = 0;", " const columnCount = nsgDbPageU32(bytes, at); at += 4;", " const rowCount = nsgDbPageU32(bytes, at); at += 4;", ` if (columnCount !== ${query.columns.length} || rowCount > 256) throw new Error("a relational page does not match declared query ${query.name}");`];
683
+ for (const column of query.columns) {
684
+ const nameBytes = [...Buffer.from(column.name, "utf8")];
685
+ out.push(` { const length = nsgDbPageU32(bytes, at); at += 4; if (length !== ${nameBytes.length}) throw new Error("a relational page column does not match declared query ${query.name}"); nsgDbPageNeed(bytes, at, length);`);
686
+ nameBytes.forEach((byte, index) => out.push(` if (bytes[at + ${index}] !== ${byte}) throw new Error("a relational page column does not match declared query ${query.name}");`));
687
+ out.push(" at += length; }");
688
+ }
689
+ out.push(` const rows: ${stem}Row[] = [];`, " for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {");
690
+ query.columns.forEach((column, index) => {
691
+ const local = `field${index}`;
692
+ const tag = `tag${index}`;
693
+ out.push(` let ${local}: ${tsType(column)};`, " nsgDbPageNeed(bytes, at, 1);", ` const ${tag} = bytes[at]!; at += 1;`);
694
+ const nullArm = column.nullable ? `${local} = null;` : `throw new Error("a non-null declared column arrived as NULL");`;
695
+ const numberArms = column.sqlType === "REAL"
696
+ ? `else if (tag === 1) { ${local} = nsgDbPageI64(bytes, at); at += 8; } else if (tag === 2) { ${local} = nsgDbPageF64(bytes, at); at += 8; }`
697
+ : `else if (tag === 1) { const integer = nsgDbPageI64(bytes, at); if (!(integer >= -9007199254740991 && integer <= 9007199254740991)) throw new Error("a SQLite INTEGER exceeds TypeScript's exact number range"); ${local} = Math.trunc(integer); at += 8; }`;
698
+ if (column.sqlType === "INTEGER" || column.sqlType === "REAL") {
699
+ out.push(` if (${tag} === 0) { ${nullArm} } ${numberArms.replaceAll("tag", tag)} else throw new Error("a relational value does not match its declared numeric type");`);
700
+ } else if (column.sqlType === "TEXT" || column.sqlType === "BLOB") {
701
+ const expected = column.sqlType === "TEXT" ? 3 : 4;
702
+ out.push(` if (${tag} === 0) { ${nullArm} } else if (${tag} === ${expected}) { const length = nsgDbPageU32(bytes, at); at += 4; nsgDbPageNeed(bytes, at, length); ${local} = bytes.slice(at, at + length); at += length; } else throw new Error("a relational value does not match its declared byte type");`);
703
+ } else {
704
+ out.push(` if (${tag} === 0) { ${local} = null; } else if (${tag} === 1) { ${local} = nsgDbPageI64(bytes, at); at += 8; } else if (${tag} === 2) { ${local} = nsgDbPageF64(bytes, at); at += 8; } else if (${tag} === 3 || ${tag} === 4) { const length = nsgDbPageU32(bytes, at); at += 4; nsgDbPageNeed(bytes, at, length); ${local} = bytes.slice(at, at + length); at += length; } else throw new Error("a relational value carries an unknown tag");`);
705
+ }
706
+ });
707
+ out.push(` rows.push({ ${query.columns.map((column, index) => `${ident.test(column.name) ? column.name : js(column.name)}: field${index}`).join(", ")} });`, " }", " if (at !== bytes.length) throw new Error(\"a relational page carries trailing bytes\");", " return rows;", "}");
708
+ return out.join("\n");
709
+ }
710
+
711
+ export function generateCoreSurface(base: string, analysis: SqliteAnalysis): string {
712
+ const fragments = generatedFragments(analysis);
713
+ return base
714
+ .replace("// @native-sqlite-generated-types", fragments.types)
715
+ .replace("// @native-sqlite-generated-cmds", fragments.cmds)
716
+ .replace("// @native-sqlite-generated-subs", fragments.subs);
717
+ }
718
+
719
+ function zigMultiline(sql: string): string {
720
+ return sql.split("\n").map((line) => ` \\\\${line}`).join("\n");
721
+ }
722
+
723
+ export function generateMigrationsZig(analysis: SqliteAnalysis): string {
724
+ const out = ["// Generated by native SQLite schema analysis; do not edit.", "const relational = @import(\"native_sdk\").relational_store;", ""];
725
+ for (const migration of analysis.migrations) {
726
+ out.push(`const migration_${migration.version}: []const u8 =`, zigMultiline(migration.sql), ";", "");
727
+ }
728
+ out.push("pub const migrations = [_]relational.Migration{");
729
+ for (const migration of analysis.migrations) out.push(` .{ .version = ${migration.version}, .name = ${js(migration.name)}, .sql = migration_${migration.version} },`);
730
+ out.push("};", "");
731
+ return out.join("\n");
732
+ }
733
+
734
+ export function formatSqliteDiagnostic(d: SqliteDiagnostic): string {
735
+ let out = `${d.file}:${d.line}:${d.column} ${d.warning ? "warning[" : ""}${d.rule}${d.warning ? "]" : ""} ${d.message}`;
736
+ if (d.fix) out += `\n fix: ${d.fix}`;
737
+ if (d.why) out += `\n why: ${d.why}`;
738
+ return out;
739
+ }
740
+
741
+ export interface MigrationState { readonly version: number; readonly hashes: readonly string[]; readonly schema_hash: string }
742
+
743
+ function validMigrationState(value: unknown): value is MigrationState {
744
+ if (value === null || typeof value !== "object") return false;
745
+ const state = value as Partial<MigrationState>;
746
+ return Number.isSafeInteger(state.version)
747
+ && (state.version ?? -1) >= 0
748
+ && Array.isArray(state.hashes)
749
+ && state.hashes.length === state.version
750
+ && state.hashes.every((hash) => typeof hash === "string" && hash.length > 0)
751
+ && typeof state.schema_hash === "string"
752
+ && state.schema_hash.length > 0;
753
+ }
754
+
755
+ function damagedMigrationState(stateFile: string): SqliteDiagnostic {
756
+ return diag(
757
+ "NS1408",
758
+ stateFile,
759
+ 1,
760
+ "The migration lock is unreadable or malformed.",
761
+ "Restore src/schema/migrations.lock.json from version control; do not regenerate it over an unknown history.",
762
+ "The lock is the append-only authority for migrations already applied to installed databases, so damaged state must never be silently re-baselined.",
763
+ );
764
+ }
765
+
766
+ export function checkMigrationState(analysis: SqliteAnalysis, stateFile: string): SqliteDiagnostic[] {
767
+ // Never bless a chain that the real-SQLite/schema pass rejected. The CLI
768
+ // still prints those primary diagnostics; the append-only lock remains at
769
+ // the last valid chain so fixing the SQL cannot accidentally establish a
770
+ // broken history as the new baseline.
771
+ if (analysis.diagnostics.length > 0) return [];
772
+ let prior: MigrationState | null = null;
773
+ let stateSource: string | null = null;
774
+ try {
775
+ stateSource = fs.readFileSync(stateFile, "utf8");
776
+ } catch (error) {
777
+ if (!(error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT")) {
778
+ return [damagedMigrationState(stateFile)];
779
+ }
780
+ }
781
+ if (stateSource !== null) {
782
+ let parsed: unknown;
783
+ try {
784
+ parsed = JSON.parse(stateSource);
785
+ } catch {
786
+ return [damagedMigrationState(stateFile)];
787
+ }
788
+ if (!validMigrationState(parsed)) return [damagedMigrationState(stateFile)];
789
+ prior = parsed;
790
+ }
791
+ const errors: SqliteDiagnostic[] = [];
792
+ if (prior) {
793
+ for (let i = 0; i < prior.hashes.length; i++) {
794
+ if (analysis.migrations[i]?.hash !== prior.hashes[i]) errors.push(diag("NS1406", analysis.migrations[i]?.file ?? path.join(path.dirname(stateFile), "schema"), 1, `Published migration ${String(i + 1).padStart(4, "0")} changed after it was accepted.`, "Restore the migration and add a new numbered migration for the change.", "Installed databases may already have applied every prior version; migration history is append-only."));
795
+ }
796
+ if (analysis.migrations.length < prior.version) errors.push(diag("NS1407", path.dirname(stateFile), 1, `The migration chain moved backward from ${prior.version} to ${analysis.migrations.length}.`, "Restore the removed migrations; version numbers are never reused."));
797
+ }
798
+ if (errors.length === 0) {
799
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
800
+ const next: MigrationState = { version: analysis.migrations.length, hashes: analysis.migrations.map((m) => m.hash), schema_hash: analysis.schemaHash };
801
+ const temp = `${stateFile}.${process.pid}.tmp`;
802
+ fs.writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`);
803
+ fs.renameSync(temp, stateFile);
804
+ }
805
+ return errors;
806
+ }