@innovatorved/code-lab 0.6.1 → 0.7.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 (131) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +35 -0
  3. package/README.md +38 -1
  4. package/dist/apps/web/src/index.d.ts +0 -9
  5. package/dist/code-lab-sql.esm.js +19 -19
  6. package/dist/code-lab-sql.umd.js +20 -20
  7. package/dist/code-lab.css +1 -1
  8. package/dist/code-lab.d.ts +19 -1
  9. package/dist/code-lab.esm.js +933 -1685
  10. package/dist/code-lab.js +932 -1684
  11. package/dist/extensions/cpp.esm.js +132 -8751
  12. package/dist/extensions/cpp.js +124 -8761
  13. package/dist/extensions/guided-lab.esm.js +33 -6827
  14. package/dist/extensions/guided-lab.js +33 -6845
  15. package/dist/extensions/javascript.esm.js +1 -36
  16. package/dist/extensions/javascript.js +1 -58
  17. package/dist/extensions/python.esm.js +79 -8109
  18. package/dist/extensions/python.js +79 -8127
  19. package/dist/extensions/typescript.esm.js +1 -55
  20. package/dist/extensions/typescript.js +1 -77
  21. package/dist/index.d.ts +1 -1
  22. package/dist/modular-kernel.d.ts +0 -4
  23. package/dist/preview-sw.js +1 -1
  24. package/dist/runtime.esm.js +79 -79
  25. package/dist/runtime.js +79 -79
  26. package/dist/schemas.d.ts +22 -1
  27. package/dist/schemas.esm.js +33 -6806
  28. package/dist/schemas.js +33 -6822
  29. package/dist/shell.esm.js +248 -242
  30. package/dist/shell.js +248 -242
  31. package/dist/terminal.esm.js +8 -6
  32. package/dist/terminal.js +6 -6
  33. package/dist/workbench/command-palette.d.ts +0 -4
  34. package/dist/workbench/index.d.ts +0 -20
  35. package/dist/workbench/intellisense.d.ts +1 -7
  36. package/package.json +3 -10
  37. package/src/code-lab.css +11 -503
  38. package/src/extensions/cpp.ts +11 -29
  39. package/src/extensions/guided-lab.ts +6 -2
  40. package/src/extensions/python.ts +9 -3
  41. package/src/index.ts +1 -1
  42. package/src/modular-kernel.ts +0 -4
  43. package/src/runtime.ts +153 -42
  44. package/src/schemas.ts +12 -3
  45. package/src/shell.ts +109 -16
  46. package/src/terminal.ts +4 -2
  47. package/src/workbench/command-palette.ts +22 -302
  48. package/src/workbench/diff-editor.ts +2 -0
  49. package/src/workbench/icons.ts +1 -1
  50. package/src/workbench/index.ts +0 -15
  51. package/src/workbench/intellisense.ts +17 -4
  52. package/src/workbench.ts +432 -456
  53. package/dist/code-lab.umd.js +0 -6109
  54. package/dist/packages/editor/src/index.d.ts +0 -118
  55. package/dist/packages/preview/src/index.d.ts +0 -34
  56. package/dist/packages/runtime/src/index.d.ts +0 -47
  57. package/dist/packages/terminal/src/index.d.ts +0 -54
  58. package/dist/workbench/drawer.d.ts +0 -18
  59. package/dist/workbench/file-tree.d.ts +0 -11
  60. package/dist/workbench/guided-pane.d.ts +0 -11
  61. package/dist/workbench/styles.d.ts +0 -4
  62. package/dist/workbench/toolbar.d.ts +0 -17
  63. package/packages/commands/README.md +0 -7
  64. package/packages/commands/package.json +0 -16
  65. package/packages/commands/src/index.ts +0 -467
  66. package/packages/commands/tsconfig.json +0 -22
  67. package/packages/core/README.md +0 -12
  68. package/packages/core/package.json +0 -13
  69. package/packages/core/src/di.ts +0 -147
  70. package/packages/core/src/disposable.ts +0 -112
  71. package/packages/core/src/errors.ts +0 -205
  72. package/packages/core/src/events.ts +0 -157
  73. package/packages/core/src/index.ts +0 -49
  74. package/packages/core/src/path.ts +0 -118
  75. package/packages/core/src/registry.ts +0 -61
  76. package/packages/core/tsconfig.json +0 -19
  77. package/packages/editor/README.md +0 -9
  78. package/packages/editor/package.json +0 -18
  79. package/packages/editor/src/index.ts +0 -344
  80. package/packages/editor/tsconfig.json +0 -24
  81. package/packages/fs/README.md +0 -7
  82. package/packages/fs/package.json +0 -16
  83. package/packages/fs/src/backends.ts +0 -301
  84. package/packages/fs/src/index.ts +0 -18
  85. package/packages/fs/src/types.ts +0 -44
  86. package/packages/fs/src/vfs-service.ts +0 -257
  87. package/packages/fs/tsconfig.json +0 -22
  88. package/packages/preview/README.md +0 -3
  89. package/packages/preview/package.json +0 -16
  90. package/packages/preview/src/index.ts +0 -125
  91. package/packages/preview/tsconfig.json +0 -22
  92. package/packages/runtime/README.md +0 -3
  93. package/packages/runtime/package.json +0 -17
  94. package/packages/runtime/src/index.ts +0 -134
  95. package/packages/runtime/tsconfig.json +0 -23
  96. package/packages/settings/README.md +0 -7
  97. package/packages/settings/package.json +0 -16
  98. package/packages/settings/src/builtin-schemas.ts +0 -246
  99. package/packages/settings/src/configuration-service.ts +0 -609
  100. package/packages/settings/src/index.ts +0 -38
  101. package/packages/settings/src/jsonc.ts +0 -189
  102. package/packages/settings/src/schema.ts +0 -164
  103. package/packages/settings/tsconfig.json +0 -22
  104. package/packages/sql/README.md +0 -12
  105. package/packages/sql/package.json +0 -13
  106. package/packages/sql/src/completions.ts +0 -359
  107. package/packages/sql/src/diagnostics.ts +0 -200
  108. package/packages/sql/src/formatter.ts +0 -271
  109. package/packages/sql/src/index.ts +0 -54
  110. package/packages/sql/src/sql-editor.ts +0 -802
  111. package/packages/sql/src/styles.ts +0 -524
  112. package/packages/sql/src/tokenizer.ts +0 -457
  113. package/packages/sql/src/types.ts +0 -148
  114. package/packages/sql/tsconfig.json +0 -19
  115. package/packages/terminal/README.md +0 -3
  116. package/packages/terminal/package.json +0 -16
  117. package/packages/terminal/src/index.ts +0 -183
  118. package/packages/terminal/tsconfig.json +0 -22
  119. package/packages/ui/README.md +0 -8
  120. package/packages/ui/package.json +0 -18
  121. package/packages/ui/src/index.ts +0 -40
  122. package/packages/ui/src/observability.ts +0 -173
  123. package/packages/ui/src/plugin-registry.ts +0 -289
  124. package/packages/ui/src/settings-dialog.ts +0 -911
  125. package/packages/ui/src/themes.ts +0 -333
  126. package/packages/ui/tsconfig.json +0 -24
  127. package/src/workbench/drawer.ts +0 -157
  128. package/src/workbench/file-tree.ts +0 -51
  129. package/src/workbench/guided-pane.ts +0 -43
  130. package/src/workbench/styles.ts +0 -211
  131. package/src/workbench/toolbar.ts +0 -182
@@ -1,359 +0,0 @@
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
- }
@@ -1,200 +0,0 @@
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
- }