@innovatorved/code-lab 0.3.1 → 0.4.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 (171) hide show
  1. package/ARCHITECTURE.md +8 -4
  2. package/CHANGELOG.md +45 -0
  3. package/README.md +70 -158
  4. package/dist/apps/web/src/index.d.ts +34 -0
  5. package/dist/code-lab-sql.css +482 -0
  6. package/dist/code-lab-sql.d.ts +179 -0
  7. package/dist/code-lab-sql.esm.js +542 -0
  8. package/dist/code-lab-sql.umd.js +531 -0
  9. package/dist/code-lab.css +298 -2
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +35284 -18253
  12. package/dist/code-lab.js +40434 -23431
  13. package/dist/code-lab.umd.js +65502 -0
  14. package/dist/diagnostics.d.ts +5 -0
  15. package/dist/extensions/cpp.esm.js +19532 -3772
  16. package/dist/extensions/cpp.js +19529 -3769
  17. package/dist/extensions/guided-lab.esm.js +19401 -3725
  18. package/dist/extensions/guided-lab.js +19400 -3724
  19. package/dist/extensions/python.d.ts +1 -0
  20. package/dist/extensions/python.esm.js +19666 -3843
  21. package/dist/extensions/python.js +19668 -3845
  22. package/dist/extensions/umbrella.d.ts +5 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/modular-kernel.d.ts +11 -0
  25. package/dist/packages/commands/src/index.d.ts +96 -0
  26. package/dist/packages/core/src/di.d.ts +36 -0
  27. package/dist/packages/core/src/disposable.d.ts +27 -0
  28. package/dist/packages/core/src/errors.d.ts +69 -0
  29. package/dist/packages/core/src/events.d.ts +38 -0
  30. package/dist/packages/core/src/index.d.ts +6 -0
  31. package/dist/packages/core/src/path.d.ts +14 -0
  32. package/dist/packages/core/src/registry.d.ts +23 -0
  33. package/dist/packages/editor/src/index.d.ts +118 -0
  34. package/dist/packages/fs/src/backends.d.ts +37 -0
  35. package/dist/packages/fs/src/index.d.ts +3 -0
  36. package/dist/packages/fs/src/types.d.ts +40 -0
  37. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  38. package/dist/packages/preview/src/index.d.ts +34 -0
  39. package/dist/packages/runtime/src/index.d.ts +47 -0
  40. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  41. package/dist/packages/settings/src/configuration-service.d.ts +100 -0
  42. package/dist/packages/settings/src/index.d.ts +4 -0
  43. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  44. package/dist/packages/settings/src/schema.d.ts +28 -0
  45. package/dist/packages/sql/src/completions.d.ts +8 -0
  46. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  47. package/dist/packages/sql/src/formatter.d.ts +2 -0
  48. package/dist/packages/sql/src/index.d.ts +7 -0
  49. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  50. package/dist/packages/sql/src/styles.d.ts +2 -0
  51. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  52. package/dist/packages/sql/src/types.d.ts +130 -0
  53. package/dist/packages/terminal/src/index.d.ts +54 -0
  54. package/dist/packages/ui/src/index.d.ts +4 -0
  55. package/dist/packages/ui/src/observability.d.ts +22 -0
  56. package/dist/packages/ui/src/plugin-registry.d.ts +89 -0
  57. package/dist/packages/ui/src/settings-dialog.d.ts +25 -0
  58. package/dist/packages/ui/src/themes.d.ts +35 -0
  59. package/dist/preview-sw.js +82 -24
  60. package/dist/runtime.d.ts +3 -3
  61. package/dist/runtime.esm.js +503 -73
  62. package/dist/runtime.js +501 -73
  63. package/dist/schemas.d.ts +234 -814
  64. package/dist/schemas.esm.js +19401 -3725
  65. package/dist/schemas.js +19404 -3728
  66. package/dist/scm.d.ts +13 -2
  67. package/dist/search.d.ts +5 -1
  68. package/dist/shell.d.ts +1 -1
  69. package/dist/shell.esm.js +435 -54
  70. package/dist/shell.js +435 -54
  71. package/dist/terminal.esm.js +242 -54
  72. package/dist/terminal.js +242 -54
  73. package/dist/workbench/diff-editor.d.ts +1 -0
  74. package/dist/workbench/index.d.ts +1 -1
  75. package/dist/workbench/styles.d.ts +1 -1
  76. package/dist/zip.d.ts +4 -3
  77. package/package.json +37 -8
  78. package/packages/commands/README.md +7 -0
  79. package/packages/commands/package.json +16 -0
  80. package/packages/commands/src/index.ts +467 -0
  81. package/packages/commands/tsconfig.json +22 -0
  82. package/packages/core/README.md +12 -0
  83. package/packages/core/package.json +13 -0
  84. package/packages/core/src/di.ts +147 -0
  85. package/packages/core/src/disposable.ts +112 -0
  86. package/packages/core/src/errors.ts +205 -0
  87. package/packages/core/src/events.ts +157 -0
  88. package/packages/core/src/index.ts +49 -0
  89. package/packages/core/src/path.ts +118 -0
  90. package/packages/core/src/registry.ts +61 -0
  91. package/packages/core/tsconfig.json +19 -0
  92. package/packages/editor/README.md +9 -0
  93. package/packages/editor/package.json +18 -0
  94. package/packages/editor/src/index.ts +344 -0
  95. package/packages/editor/tsconfig.json +24 -0
  96. package/packages/fs/README.md +7 -0
  97. package/packages/fs/package.json +16 -0
  98. package/packages/fs/src/backends.ts +301 -0
  99. package/packages/fs/src/index.ts +18 -0
  100. package/packages/fs/src/types.ts +44 -0
  101. package/packages/fs/src/vfs-service.ts +257 -0
  102. package/packages/fs/tsconfig.json +22 -0
  103. package/packages/preview/README.md +3 -0
  104. package/packages/preview/package.json +16 -0
  105. package/packages/preview/src/index.ts +125 -0
  106. package/packages/preview/tsconfig.json +22 -0
  107. package/packages/runtime/README.md +3 -0
  108. package/packages/runtime/package.json +17 -0
  109. package/packages/runtime/src/index.ts +134 -0
  110. package/packages/runtime/tsconfig.json +23 -0
  111. package/packages/settings/README.md +7 -0
  112. package/packages/settings/package.json +16 -0
  113. package/packages/settings/src/builtin-schemas.ts +235 -0
  114. package/packages/settings/src/configuration-service.ts +543 -0
  115. package/packages/settings/src/index.ts +37 -0
  116. package/packages/settings/src/jsonc.ts +189 -0
  117. package/packages/settings/src/schema.ts +164 -0
  118. package/packages/settings/tsconfig.json +22 -0
  119. package/packages/sql/README.md +12 -0
  120. package/packages/sql/package.json +13 -0
  121. package/packages/sql/src/completions.ts +359 -0
  122. package/packages/sql/src/diagnostics.ts +200 -0
  123. package/packages/sql/src/formatter.ts +271 -0
  124. package/packages/sql/src/index.ts +54 -0
  125. package/packages/sql/src/sql-editor.ts +802 -0
  126. package/packages/sql/src/styles.ts +501 -0
  127. package/packages/sql/src/tokenizer.ts +457 -0
  128. package/packages/sql/src/types.ts +148 -0
  129. package/packages/sql/tsconfig.json +19 -0
  130. package/packages/terminal/README.md +3 -0
  131. package/packages/terminal/package.json +16 -0
  132. package/packages/terminal/src/index.ts +183 -0
  133. package/packages/terminal/tsconfig.json +22 -0
  134. package/packages/ui/README.md +8 -0
  135. package/packages/ui/package.json +18 -0
  136. package/packages/ui/src/index.ts +36 -0
  137. package/packages/ui/src/observability.ts +175 -0
  138. package/packages/ui/src/plugin-registry.ts +274 -0
  139. package/packages/ui/src/settings-dialog.ts +293 -0
  140. package/packages/ui/src/themes.ts +174 -0
  141. package/packages/ui/tsconfig.json +24 -0
  142. package/src/code-lab.css +298 -2
  143. package/src/csp.ts +7 -10
  144. package/src/diagnostics.ts +42 -3
  145. package/src/extensions/cpp.ts +105 -24
  146. package/src/extensions/python.ts +260 -116
  147. package/src/extensions/umbrella.ts +5 -0
  148. package/src/index.ts +1 -1
  149. package/src/modular-kernel.ts +11 -0
  150. package/src/preview-sw.js +73 -12
  151. package/src/runtime.ts +501 -74
  152. package/src/schemas.ts +62 -62
  153. package/src/scm.ts +106 -19
  154. package/src/search.ts +71 -27
  155. package/src/shell.ts +433 -53
  156. package/src/terminal.ts +239 -52
  157. package/src/workbench/diff-editor.ts +106 -18
  158. package/src/workbench/drawer.ts +17 -4
  159. package/src/workbench/guided-pane.ts +12 -2
  160. package/src/workbench/icons.ts +5 -2
  161. package/src/workbench/share.ts +37 -8
  162. package/src/workbench/styles.ts +2 -1
  163. package/src/workbench/toolbar.ts +15 -4
  164. package/src/workbench.ts +2877 -284
  165. package/src/zip.ts +29 -7
  166. package/dist/runtime/index.d.ts +0 -4
  167. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  168. package/dist/shell/index.d.ts +0 -4
  169. package/src/runtime/index.ts +0 -5
  170. package/src/shell/coreutils/compilers-cli.ts +0 -103
  171. package/src/shell/index.ts +0 -5
@@ -0,0 +1,359 @@
1
+ import { getDialectKeywords, getSqlBuiltinFunctions, tokenizeSql, type SqlToken } from './tokenizer';
2
+ import type {
3
+ SqlColumnSchema,
4
+ SqlCompletionItem,
5
+ SqlDialect,
6
+ SqlSchema,
7
+ SqlTableSchema
8
+ } from './types';
9
+
10
+ const NON_ALIAS_KEYWORDS = new Set([
11
+ 'WHERE', 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS', 'NATURAL', 'LATERAL',
12
+ 'ON', 'USING', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'OFFSET', 'UNION', 'INTERSECT',
13
+ 'EXCEPT', 'SET', 'VALUES', 'RETURNING', 'WINDOW', 'FETCH', 'FOR'
14
+ ]);
15
+
16
+ const TABLE_CLAUSES = new Set(['FROM', 'JOIN', 'UPDATE', 'INTO', 'TABLE']);
17
+
18
+ function stripIdentifierQuotes(raw: string): string {
19
+ if (
20
+ (raw.startsWith('"') && raw.endsWith('"')) ||
21
+ (raw.startsWith('`') && raw.endsWith('`')) ||
22
+ (raw.startsWith('[') && raw.endsWith(']'))
23
+ ) {
24
+ return raw.slice(1, -1);
25
+ }
26
+ return raw;
27
+ }
28
+
29
+ export interface ParsedSqlContext {
30
+ readonly aliases: ReadonlyMap<string, string>;
31
+ readonly referencedTables: ReadonlySet<string>;
32
+ readonly cteNames: ReadonlySet<string>;
33
+ }
34
+
35
+ export function extractTableAliases(sql: string, dialect: SqlDialect = 'postgres'): ParsedSqlContext {
36
+ const tokens = tokenizeSql(sql, dialect).filter(
37
+ (t) => t.type !== 'whitespace' && t.type !== 'comment'
38
+ );
39
+ const aliases = new Map<string, string>();
40
+ const referencedTables = new Set<string>();
41
+ const cteNames = new Set<string>();
42
+
43
+ for (let i = 0; i < tokens.length; i++) {
44
+ const tok = tokens[i];
45
+ const upper = tok.value.toUpperCase();
46
+
47
+ // Detect `WITH [RECURSIVE] cte_name AS (` and `, cte2 AS (`
48
+ if (upper === 'WITH') {
49
+ let j = i + 1;
50
+ if (j < tokens.length && tokens[j].value.toUpperCase() === 'RECURSIVE') j++;
51
+ while (j < tokens.length) {
52
+ const nameTok = tokens[j];
53
+ const nextTok = tokens[j + 1];
54
+ if (
55
+ nameTok &&
56
+ (nameTok.type === 'identifier' || nameTok.type === 'quoted-ident') &&
57
+ nextTok &&
58
+ nextTok.value.toUpperCase() === 'AS'
59
+ ) {
60
+ cteNames.add(stripIdentifierQuotes(nameTok.value));
61
+ }
62
+ // Advance past parenthesized CTE body if we see `(`
63
+ let foundComma = false;
64
+ let depth = 0;
65
+ while (j < tokens.length) {
66
+ if (tokens[j].value === '(') depth++;
67
+ else if (tokens[j].value === ')') {
68
+ depth = Math.max(0, depth - 1);
69
+ if (depth === 0 && tokens[j + 1]?.value === ',') {
70
+ j += 2;
71
+ foundComma = true;
72
+ break;
73
+ } else if (depth === 0) {
74
+ break;
75
+ }
76
+ }
77
+ j++;
78
+ }
79
+ if (!foundComma) break;
80
+ }
81
+ }
82
+
83
+ if (TABLE_CLAUSES.has(upper)) {
84
+ let tableIdx = i + 1;
85
+ if (tableIdx < tokens.length && tokens[tableIdx].value.toUpperCase() === 'ONLY') {
86
+ tableIdx++;
87
+ }
88
+ const tableTok = tokens[tableIdx];
89
+ if (!tableTok || (tableTok.type !== 'identifier' && tableTok.type !== 'quoted-ident')) {
90
+ continue;
91
+ }
92
+ let tableName = stripIdentifierQuotes(tableTok.value);
93
+ let afterTableIdx = tableIdx + 1;
94
+ // Handle schema-qualified `public.orders`
95
+ if (
96
+ tokens[afterTableIdx]?.value === '.' &&
97
+ tokens[afterTableIdx + 1] &&
98
+ (tokens[afterTableIdx + 1].type === 'identifier' || tokens[afterTableIdx + 1].type === 'quoted-ident')
99
+ ) {
100
+ tableName = stripIdentifierQuotes(tokens[afterTableIdx + 1].value);
101
+ afterTableIdx += 2;
102
+ }
103
+ referencedTables.add(tableName);
104
+ aliases.set(tableName.toLowerCase(), tableName);
105
+
106
+ let aliasTok: SqlToken | undefined = tokens[afterTableIdx];
107
+ if (aliasTok && aliasTok.value.toUpperCase() === 'AS') {
108
+ aliasTok = tokens[afterTableIdx + 1];
109
+ }
110
+ if (
111
+ aliasTok &&
112
+ (aliasTok.type === 'identifier' || aliasTok.type === 'quoted-ident') &&
113
+ !NON_ALIAS_KEYWORDS.has(aliasTok.value.toUpperCase())
114
+ ) {
115
+ const aliasName = stripIdentifierQuotes(aliasTok.value);
116
+ aliases.set(aliasName.toLowerCase(), tableName);
117
+ }
118
+ }
119
+ }
120
+
121
+ return { aliases, referencedTables, cteNames };
122
+ }
123
+
124
+ function formatRowCount(rowCount: number | undefined): string | undefined {
125
+ if (rowCount === undefined || !Number.isFinite(rowCount)) return undefined;
126
+ return `${rowCount.toLocaleString('en-US')} rows`;
127
+ }
128
+
129
+ function columnSecondaryBadge(col: SqlColumnSchema): string | undefined {
130
+ const parts: string[] = [];
131
+ if (col.pk || col.primaryKey) parts.push('PK');
132
+ const fkTarget = col.fk ?? col.references;
133
+ if (fkTarget) parts.push(`FK→${fkTarget}`);
134
+ return parts.length > 0 ? parts.join(' · ') : undefined;
135
+ }
136
+
137
+ function findTableCaseInsensitive(
138
+ schema: SqlSchema | null | undefined,
139
+ name: string
140
+ ): SqlTableSchema | undefined {
141
+ if (!schema) return undefined;
142
+ const target = name.toLowerCase();
143
+ return schema.tables.find((t) => t.name.toLowerCase() === target);
144
+ }
145
+
146
+ export function completeSql(
147
+ sql: string,
148
+ cursorOffset: number,
149
+ schema?: SqlSchema | null,
150
+ dialectOverride?: SqlDialect,
151
+ maxItems = 40
152
+ ): SqlCompletionItem[] {
153
+ const dialect: SqlDialect = dialectOverride ?? schema?.dialect ?? 'postgres';
154
+ const safeCursor = Math.max(0, Math.min(cursorOffset, sql.length));
155
+ const beforeCursor = sql.slice(0, safeCursor);
156
+
157
+ // Do not trigger inside comments or string literals
158
+ const prefixTokens = tokenizeSql(beforeCursor, dialect);
159
+ const lastRaw = prefixTokens[prefixTokens.length - 1];
160
+ if (lastRaw && (lastRaw.type === 'comment' || lastRaw.type === 'string')) {
161
+ return [];
162
+ }
163
+
164
+ const parsedCtx = extractTableAliases(sql, dialect);
165
+
166
+ // 1. Check for `qualifier.partial` (e.g., `o.` or `orders.tot`)
167
+ const dotMatch = /([A-Za-z_][A-Za-z0-9_$]*|"[^"]+")\.([A-Za-z0-9_$]*)$/.exec(beforeCursor);
168
+ if (dotMatch) {
169
+ const rawQualifier = stripIdentifierQuotes(dotMatch[1]);
170
+ const partial = dotMatch[2];
171
+ const partialLower = partial.toLowerCase();
172
+ const replaceFrom = safeCursor - partial.length;
173
+ const resolvedTableName =
174
+ parsedCtx.aliases.get(rawQualifier.toLowerCase()) ?? rawQualifier;
175
+ const tableSchema = findTableCaseInsensitive(schema, resolvedTableName);
176
+ if (!tableSchema) return [];
177
+
178
+ const items: SqlCompletionItem[] = [];
179
+ for (const col of tableSchema.columns) {
180
+ if (!partial || col.name.toLowerCase().startsWith(partialLower)) {
181
+ items.push({
182
+ label: col.name,
183
+ insertText: col.name,
184
+ kind: 'column',
185
+ detail: col.type,
186
+ badge: tableSchema.name,
187
+ secondaryBadge: columnSecondaryBadge(col),
188
+ description: col.comment,
189
+ replaceFrom,
190
+ replaceTo: safeCursor
191
+ });
192
+ }
193
+ }
194
+ return items.slice(0, maxItems);
195
+ }
196
+
197
+ // Extract current word prefix before cursor
198
+ const wordMatch = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(beforeCursor);
199
+ const prefix = wordMatch ? wordMatch[1] : '';
200
+ const prefixLower = prefix.toLowerCase();
201
+ const replaceFrom = safeCursor - prefix.length;
202
+
203
+ // Determine active SQL clause before cursor
204
+ const nonWsTokens = prefixTokens.filter((t) => t.type !== 'whitespace' && t.type !== 'comment');
205
+ const searchEnd = prefix ? nonWsTokens.length - 2 : nonWsTokens.length - 1;
206
+ let activeClause = '';
207
+ const prevWord = searchEnd >= 0 ? nonWsTokens[searchEnd]?.value.toUpperCase() : '';
208
+ for (let i = searchEnd; i >= 0; i--) {
209
+ const u = nonWsTokens[i].value.toUpperCase();
210
+ if (
211
+ TABLE_CLAUSES.has(u) ||
212
+ u === 'SELECT' || u === 'WHERE' || u === 'ON' || u === 'HAVING' ||
213
+ u === 'GROUP' || u === 'ORDER' || u === 'SET' || u === 'RETURNING' || u === 'FILTER'
214
+ ) {
215
+ activeClause = u;
216
+ break;
217
+ }
218
+ if (nonWsTokens[i].value === ';') break;
219
+ }
220
+
221
+ const matchesPrefix = (candidate: string): boolean => {
222
+ if (!prefix) return true;
223
+ return candidate.toLowerCase().startsWith(prefixLower);
224
+ };
225
+
226
+ const results: SqlCompletionItem[] = [];
227
+ const seen = new Set<string>();
228
+ const pushUnique = (item: SqlCompletionItem): void => {
229
+ const key = `${item.kind}:${item.label.toLowerCase()}`;
230
+ if (seen.has(key)) return;
231
+ seen.add(key);
232
+ results.push(item);
233
+ };
234
+
235
+ // 2. Immediately after `FROM`, `JOIN`, `UPDATE`, `INTO`, `TABLE`: prioritize tables & CTEs
236
+ if (TABLE_CLAUSES.has(prevWord) || (TABLE_CLAUSES.has(activeClause) && prevWord === ',')) {
237
+ if (schema) {
238
+ for (const tbl of schema.tables) {
239
+ if (matchesPrefix(tbl.name)) {
240
+ pushUnique({
241
+ label: tbl.name,
242
+ insertText: tbl.name,
243
+ kind: 'table',
244
+ detail: 'table',
245
+ badge: formatRowCount(tbl.rowCount),
246
+ replaceFrom,
247
+ replaceTo: safeCursor
248
+ });
249
+ }
250
+ }
251
+ }
252
+ for (const cte of parsedCtx.cteNames) {
253
+ if (matchesPrefix(cte)) {
254
+ pushUnique({
255
+ label: cte,
256
+ insertText: cte,
257
+ kind: 'cte',
258
+ detail: 'CTE',
259
+ replaceFrom,
260
+ replaceTo: safeCursor
261
+ });
262
+ }
263
+ }
264
+ return results.slice(0, maxItems);
265
+ }
266
+
267
+ // If no prefix typed and not right after `FROM`/`JOIN`/`.`, don't spam popup unprompted
268
+ if (!prefix) {
269
+ return [];
270
+ }
271
+
272
+ // 3. Expression clauses (`SELECT`, `WHERE`, `ON`, `GROUP`, `HAVING`, `ORDER`, `SET`, `RETURNING`, `FILTER`):
273
+ // Suggest columns from referenced tables first, then other schema tables/columns, then functions, then keywords.
274
+ if (schema) {
275
+ const refLower = new Set(Array.from(parsedCtx.referencedTables, (t) => t.toLowerCase()));
276
+ const prioritizedTables = [
277
+ ...schema.tables.filter((t) => refLower.has(t.name.toLowerCase())),
278
+ ...schema.tables.filter((t) => !refLower.has(t.name.toLowerCase()))
279
+ ];
280
+
281
+ for (const tbl of prioritizedTables) {
282
+ for (const col of tbl.columns) {
283
+ if (matchesPrefix(col.name)) {
284
+ pushUnique({
285
+ label: col.name,
286
+ insertText: col.name,
287
+ kind: 'column',
288
+ detail: col.type,
289
+ badge: tbl.name,
290
+ secondaryBadge: columnSecondaryBadge(col),
291
+ description: col.comment,
292
+ replaceFrom,
293
+ replaceTo: safeCursor
294
+ });
295
+ }
296
+ }
297
+ }
298
+
299
+ for (const tbl of schema.tables) {
300
+ if (matchesPrefix(tbl.name)) {
301
+ pushUnique({
302
+ label: tbl.name,
303
+ insertText: tbl.name,
304
+ kind: 'table',
305
+ detail: 'table',
306
+ badge: formatRowCount(tbl.rowCount),
307
+ replaceFrom,
308
+ replaceTo: safeCursor
309
+ });
310
+ }
311
+ }
312
+
313
+ if (schema.functions) {
314
+ for (const fn of schema.functions) {
315
+ if (matchesPrefix(fn.name)) {
316
+ pushUnique({
317
+ label: fn.name,
318
+ insertText: `${fn.name}(`,
319
+ kind: 'function',
320
+ detail: fn.signature,
321
+ description: fn.description,
322
+ replaceFrom,
323
+ replaceTo: safeCursor
324
+ });
325
+ }
326
+ }
327
+ }
328
+ }
329
+
330
+ // 4. Built-in SQL functions
331
+ for (const fnName of getSqlBuiltinFunctions()) {
332
+ if (matchesPrefix(fnName)) {
333
+ pushUnique({
334
+ label: fnName,
335
+ insertText: `${fnName}(`,
336
+ kind: 'function',
337
+ detail: 'SQL function',
338
+ replaceFrom,
339
+ replaceTo: safeCursor
340
+ });
341
+ }
342
+ }
343
+
344
+ // 5. Dialect keywords
345
+ for (const kw of getDialectKeywords(dialect)) {
346
+ if (matchesPrefix(kw)) {
347
+ pushUnique({
348
+ label: kw,
349
+ insertText: kw,
350
+ kind: 'keyword',
351
+ detail: dialect === 'postgres' ? 'PostgreSQL' : 'SQLite',
352
+ replaceFrom,
353
+ replaceTo: safeCursor
354
+ });
355
+ }
356
+ }
357
+
358
+ return results.slice(0, maxItems);
359
+ }
@@ -0,0 +1,200 @@
1
+ import { tokenizeSql } from './tokenizer';
2
+ import type { SqlDiagnostic, SqlDialect } from './types';
3
+
4
+ function offsetToLineColumn(sql: string, offset: number): { line: number; column: number } {
5
+ let line = 1;
6
+ let column = 1;
7
+ const clamped = Math.max(0, Math.min(offset, sql.length));
8
+ for (let i = 0; i < clamped; i++) {
9
+ if (sql[i] === '\n') {
10
+ line++;
11
+ column = 1;
12
+ } else {
13
+ column++;
14
+ }
15
+ }
16
+ return { line, column };
17
+ }
18
+
19
+ function lineColumnToOffset(sql: string, line: number, column = 1): number {
20
+ let curLine = 1;
21
+ let idx = 0;
22
+ while (idx < sql.length && curLine < line) {
23
+ if (sql[idx] === '\n') curLine++;
24
+ idx++;
25
+ }
26
+ return Math.min(sql.length, idx + Math.max(0, column - 1));
27
+ }
28
+
29
+ function expandTokenSpanAtOffset(
30
+ sql: string,
31
+ offset: number,
32
+ dialect: SqlDialect
33
+ ): { fromOffset: number; toOffset: number } {
34
+ const clamped = Math.max(0, Math.min(offset, Math.max(0, sql.length - 1)));
35
+ const tokens = tokenizeSql(sql, dialect);
36
+ for (const tok of tokens) {
37
+ if (tok.type !== 'whitespace' && clamped >= tok.start && clamped < tok.end) {
38
+ return { fromOffset: tok.start, toOffset: tok.end };
39
+ }
40
+ }
41
+ const lineEnd = sql.indexOf('\n', clamped);
42
+ const end = lineEnd === -1 ? Math.min(sql.length, clamped + 1) : Math.max(clamped + 1, lineEnd);
43
+ return { fromOffset: clamped, toOffset: end };
44
+ }
45
+
46
+ export function parseSqlEngineError(
47
+ error: unknown,
48
+ sql: string,
49
+ dialect: SqlDialect = 'postgres'
50
+ ): SqlDiagnostic {
51
+ const errObj = typeof error === 'object' && error !== null ? (error as Record<string, unknown>) : null;
52
+ const rawMessage =
53
+ errObj && typeof errObj.message === 'string'
54
+ ? errObj.message
55
+ : typeof error === 'string'
56
+ ? error
57
+ : String(error ?? 'SQL query failed');
58
+
59
+ // Extract HINT line if embedded or provided on PGlite / Postgres Error object
60
+ let hint: string | undefined =
61
+ errObj && typeof errObj.hint === 'string' && errObj.hint.trim() ? errObj.hint.trim() : undefined;
62
+ const hintMatch = /\bHINT:\s*([^\n]+)/i.exec(rawMessage);
63
+ if (!hint && hintMatch) {
64
+ hint = hintMatch[1].trim();
65
+ }
66
+
67
+ const cleanMsg = rawMessage
68
+ .split('\n')
69
+ .filter((l) => !/^\s*(LINE\s+\d+:|HINT:|\^)/i.test(l))
70
+ .join(' ')
71
+ .replace(/^ERROR:\s*/i, '')
72
+ .trim() || rawMessage.trim();
73
+
74
+ // 1. PostgreSQL / PGlite explicit 1-based character `position`
75
+ const rawPos =
76
+ errObj && (typeof errObj.position === 'number' || typeof errObj.position === 'string')
77
+ ? Number(errObj.position)
78
+ : (() => {
79
+ const m = /\bat character\s+(\d+)/i.exec(rawMessage);
80
+ return m ? Number(m[1]) : NaN;
81
+ })();
82
+
83
+ if (Number.isFinite(rawPos) && rawPos >= 1) {
84
+ const zeroBased = Math.min(Math.max(0, rawPos - 1), Math.max(0, sql.length - 1));
85
+ const span = expandTokenSpanAtOffset(sql, zeroBased, dialect);
86
+ const lc = offsetToLineColumn(sql, span.fromOffset);
87
+ return {
88
+ severity: 'error',
89
+ message: cleanMsg,
90
+ ...(hint ? { hint } : {}),
91
+ line: lc.line,
92
+ column: lc.column,
93
+ fromOffset: span.fromOffset,
94
+ toOffset: span.toOffset
95
+ };
96
+ }
97
+
98
+ // 2. PostgreSQL `LINE N:` + optional `^` caret line
99
+ const lineMatch = /\bLINE\s+(\d+):/i.exec(rawMessage);
100
+ if (lineMatch) {
101
+ const lineNum = Math.max(1, Number(lineMatch[1]));
102
+ let colNum = 1;
103
+ const msgLines = rawMessage.split('\n');
104
+ const lineHeaderIdx = msgLines.findIndex((l) => /\bLINE\s+\d+:/i.test(l));
105
+ if (lineHeaderIdx !== -1 && lineHeaderIdx + 1 < msgLines.length) {
106
+ const prefixMatch = /^(\s*LINE\s+\d+:\s*)/i.exec(msgLines[lineHeaderIdx]);
107
+ const caretMatch = /^(\s*)\^/.exec(msgLines[lineHeaderIdx + 1]);
108
+ if (prefixMatch && caretMatch) {
109
+ colNum = Math.max(1, caretMatch[1].length - prefixMatch[1].length + 1);
110
+ }
111
+ }
112
+ const offset = lineColumnToOffset(sql, lineNum, colNum);
113
+ const span = expandTokenSpanAtOffset(sql, offset, dialect);
114
+ return {
115
+ severity: 'error',
116
+ message: cleanMsg,
117
+ ...(hint ? { hint } : {}),
118
+ line: lineNum,
119
+ column: colNum,
120
+ fromOffset: span.fromOffset,
121
+ toOffset: span.toOffset
122
+ };
123
+ }
124
+
125
+ // 3. SQLite `near "TOKEN"` / `no such column: X` / `no such table: Y` / `ambiguous column name: Z`
126
+ const tokenPatterns: Array<{ re: RegExp; defaultHint?: (tok: string) => string }> = [
127
+ {
128
+ re: /\bnear\s+"([^"]+)"/i,
129
+ defaultHint: (tok) => `Check SQL syntax right before or around "${tok}".`
130
+ },
131
+ {
132
+ re: /\bno such column:\s*([A-Za-z0-9_."`[\]]+)/i,
133
+ defaultHint: (tok) => `Column "${tok}" does not exist on the referenced tables. Check spelling or table aliases.`
134
+ },
135
+ {
136
+ re: /\bcolumn\s+"([^"]+)"\s+does not exist/i,
137
+ defaultHint: (tok) => `Verify that column "${tok}" exists in the target table schema.`
138
+ },
139
+ {
140
+ re: /\bno such table:\s*([A-Za-z0-9_."`[\]]+)/i,
141
+ defaultHint: (tok) => `Table "${tok}" was not found in the active database schema.`
142
+ },
143
+ {
144
+ re: /\brelation\s+"([^"]+)"\s+does not exist/i,
145
+ defaultHint: (tok) => `Relation "${tok}" was not found in the database.`
146
+ },
147
+ {
148
+ re: /\bambiguous column name:\s*([A-Za-z0-9_."`[\]]+)/i,
149
+ defaultHint: (tok) => `Qualify "${tok}" with a table name or alias (e.g. t.${tok}).`
150
+ }
151
+ ];
152
+
153
+ for (const pat of tokenPatterns) {
154
+ const m = pat.re.exec(rawMessage);
155
+ if (m && m[1]) {
156
+ const needle = m[1];
157
+ const tokens = tokenizeSql(sql, dialect);
158
+ const matchedTok =
159
+ tokens.find((t) => t.value === needle) ??
160
+ tokens.find((t) => t.value.toLowerCase() === needle.toLowerCase());
161
+ if (matchedTok) {
162
+ const lc = offsetToLineColumn(sql, matchedTok.start);
163
+ const derivedHint = hint ?? (pat.defaultHint ? pat.defaultHint(needle) : undefined);
164
+ return {
165
+ severity: 'error',
166
+ message: cleanMsg,
167
+ ...(derivedHint ? { hint: derivedHint } : {}),
168
+ line: lc.line,
169
+ column: lc.column,
170
+ fromOffset: matchedTok.start,
171
+ toOffset: matchedTok.end
172
+ };
173
+ }
174
+ const rawIdx = sql.toLowerCase().indexOf(needle.toLowerCase());
175
+ if (rawIdx !== -1) {
176
+ const lc = offsetToLineColumn(sql, rawIdx);
177
+ const derivedHint = hint ?? (pat.defaultHint ? pat.defaultHint(needle) : undefined);
178
+ return {
179
+ severity: 'error',
180
+ message: cleanMsg,
181
+ ...(derivedHint ? { hint: derivedHint } : {}),
182
+ line: lc.line,
183
+ column: lc.column,
184
+ fromOffset: rawIdx,
185
+ toOffset: rawIdx + needle.length
186
+ };
187
+ }
188
+ }
189
+ }
190
+
191
+ return {
192
+ severity: 'error',
193
+ message: cleanMsg,
194
+ ...(hint ? { hint } : {}),
195
+ line: 1,
196
+ column: 1,
197
+ fromOffset: 0,
198
+ toOffset: Math.min(sql.length, Math.max(1, sql.indexOf('\n') === -1 ? sql.length : sql.indexOf('\n')))
199
+ };
200
+ }