@innovatorved/code-lab 0.5.0 → 0.6.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 (67) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +3 -3
  4. package/dist/code-lab-sql.esm.js +1 -1
  5. package/dist/code-lab-sql.umd.js +2 -2
  6. package/dist/code-lab.css +32 -7273
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +4669 -74678
  9. package/dist/code-lab.js +4655 -74665
  10. package/dist/code-lab.umd.js +4655 -74665
  11. package/dist/extensions/cpp.d.ts +2 -2
  12. package/dist/extensions/cpp.esm.js +1788 -14707
  13. package/dist/extensions/cpp.js +1788 -14707
  14. package/dist/extensions/guided-lab.esm.js +2938 -16127
  15. package/dist/extensions/guided-lab.js +2938 -16127
  16. package/dist/extensions/python.d.ts +2 -2
  17. package/dist/extensions/python.esm.js +1769 -14701
  18. package/dist/extensions/python.js +1769 -14701
  19. package/dist/index.d.ts +1 -1
  20. package/dist/preview-sw.js +4 -188
  21. package/dist/runtime.esm.js +109 -10284
  22. package/dist/runtime.js +107 -10284
  23. package/dist/schemas.d.ts +2 -2
  24. package/dist/schemas.esm.js +2938 -16127
  25. package/dist/schemas.js +2941 -16130
  26. package/dist/scm.d.ts +221 -20
  27. package/dist/shell.esm.js +811 -10002
  28. package/dist/shell.js +811 -10002
  29. package/dist/storage.d.ts +9 -0
  30. package/dist/terminal.esm.js +20 -1347
  31. package/dist/terminal.js +20 -1347
  32. package/dist/workbench/command-palette.d.ts +16 -1
  33. package/dist/workbench/diff-editor.d.ts +27 -1
  34. package/dist/workbench/icons.d.ts +6 -2
  35. package/dist/workbench/index.d.ts +32 -0
  36. package/dist/workbench/intellisense.d.ts +194 -0
  37. package/dist/workbench/xterm-adapter.d.ts +122 -0
  38. package/package.json +7 -1
  39. package/packages/commands/package.json +1 -1
  40. package/packages/core/package.json +1 -1
  41. package/packages/editor/package.json +1 -1
  42. package/packages/fs/package.json +1 -1
  43. package/packages/preview/package.json +1 -1
  44. package/packages/runtime/package.json +1 -1
  45. package/packages/settings/package.json +1 -1
  46. package/packages/sql/package.json +1 -1
  47. package/packages/terminal/package.json +1 -1
  48. package/packages/ui/package.json +1 -1
  49. package/packages/ui/src/settings-dialog.ts +36 -24
  50. package/packages/ui/src/themes.ts +89 -23
  51. package/src/code-lab.css +1345 -481
  52. package/src/extensions/cpp.ts +304 -38
  53. package/src/extensions/python.ts +342 -43
  54. package/src/index.ts +1 -1
  55. package/src/runtime.ts +272 -43
  56. package/src/schemas.ts +2 -2
  57. package/src/scm.ts +1467 -92
  58. package/src/shell.ts +1075 -93
  59. package/src/storage.ts +66 -3
  60. package/src/terminal.ts +148 -12
  61. package/src/workbench/command-palette.ts +289 -48
  62. package/src/workbench/diff-editor.ts +240 -78
  63. package/src/workbench/icons.ts +250 -53
  64. package/src/workbench/index.ts +7 -1
  65. package/src/workbench/intellisense.ts +1859 -0
  66. package/src/workbench/xterm-adapter.ts +1566 -0
  67. package/src/workbench.ts +1605 -236
@@ -0,0 +1,1859 @@
1
+ /**
2
+ * @innovatorved/code-lab — Browser-Native Language Intelligence (100% Client-Side)
3
+ *
4
+ * Provides VS Code Dark/Light/HC Modern Monaco themes, normalized `file:///workspace/...`
5
+ * eager multi-file TS/JS model synchronization, live `tsconfig.json` compiler sync,
6
+ * cross-file F12 / Cmd+Click Go-to-Definition editor opener, Automatic Type Acquisition (ATA)
7
+ * with IndexedDB caching + Node.js ambient `.d.ts`, JSON schemas (`package.json`, `tsconfig.json`),
8
+ * HTML/JSX auto-closing tags + Emmet abbreviations, cross-file CSS custom property completions,
9
+ * SQL schema-aware completions, and universal document/workspace symbol extraction for Outline,
10
+ * Breadcrumbs, and Quick Open (`@` / `#`).
11
+ */
12
+
13
+ export type SymbolKindName =
14
+ | 'class'
15
+ | 'interface'
16
+ | 'type'
17
+ | 'enum'
18
+ | 'struct'
19
+ | 'function'
20
+ | 'method'
21
+ | 'property'
22
+ | 'variable'
23
+ | 'constant'
24
+ | 'heading'
25
+ | 'table';
26
+
27
+ export interface CodeLabSymbolItem {
28
+ name: string;
29
+ kind: SymbolKindName;
30
+ detail?: string;
31
+ file: string;
32
+ line: number;
33
+ endLine: number;
34
+ column: number;
35
+ containerName?: string;
36
+ }
37
+
38
+ export interface WorkspaceFilesGetter {
39
+ (): Record<string, string>;
40
+ }
41
+
42
+ export interface MonacoUriLike {
43
+ path?: string;
44
+ toString?: () => string;
45
+ }
46
+
47
+ export interface MonacoPositionLike {
48
+ lineNumber: number;
49
+ column: number;
50
+ }
51
+
52
+ export interface MonacoRangeLike {
53
+ startLineNumber: number;
54
+ startColumn: number;
55
+ endLineNumber: number;
56
+ endColumn: number;
57
+ }
58
+
59
+ export interface MonacoTextModelLike {
60
+ getLineContent: (lineNumber: number) => string;
61
+ getValue?: () => string;
62
+ getLanguageId?: () => string;
63
+ getWordUntilPosition: (pos: MonacoPositionLike) => { word: string; startColumn: number; endColumn: number };
64
+ getWordAtPosition: (pos: MonacoPositionLike) => { word: string; startColumn: number; endColumn: number } | null;
65
+ }
66
+
67
+ export interface MonacoChangeEventLike {
68
+ changes?: Array<{ text: string; range: MonacoRangeLike }>;
69
+ }
70
+
71
+ export interface MonacoEditorLike {
72
+ onDidChangeModelContent?: (cb: (event: MonacoChangeEventLike) => void) => { dispose: () => void } | undefined;
73
+ getModel?: () => MonacoTextModelLike | null;
74
+ executeEdits: (source: string, edits: Array<{ range: MonacoRangeLike; text: string; forceMoveMarkers?: boolean }>) => void;
75
+ setPosition: (pos: MonacoPositionLike) => void;
76
+ }
77
+
78
+ export interface MonacoTsDefaultsLike {
79
+ setCompilerOptions?: (opts: Record<string, unknown>) => void;
80
+ setEagerModelSync?: (value: boolean) => void;
81
+ setDiagnosticsOptions?: (opts: Record<string, unknown>) => void;
82
+ addExtraLib?: (content: string, filePath?: string) => { dispose?: () => void } | undefined;
83
+ }
84
+
85
+ export interface MonacoNamespaceLike {
86
+ Uri?: {
87
+ file?: (path: string) => MonacoUriLike;
88
+ parse?: (uri: string) => MonacoUriLike;
89
+ };
90
+ Range?: new (startLine: number, startCol: number, endLine: number, endCol: number) => MonacoRangeLike;
91
+ editor?: {
92
+ defineTheme?: (name: string, data: Record<string, unknown>) => void;
93
+ registerEditorOpener?: (opener: {
94
+ openCodeEditor: (
95
+ source: unknown,
96
+ resource: MonacoUriLike | string,
97
+ selectionOrPosition?: Partial<MonacoRangeLike & MonacoPositionLike>
98
+ ) => boolean;
99
+ }) => { dispose: () => void };
100
+ };
101
+ languages?: {
102
+ CompletionItemKind?: Record<string, number>;
103
+ CompletionItemInsertTextRule?: Record<string, number>;
104
+ registerCompletionItemProvider?: (
105
+ lang: string,
106
+ provider: {
107
+ triggerCharacters?: string[];
108
+ provideCompletionItems: (model: MonacoTextModelLike, position: MonacoPositionLike) => { suggestions: Array<Record<string, unknown>> };
109
+ }
110
+ ) => { dispose: () => void };
111
+ registerHoverProvider?: (
112
+ lang: string,
113
+ provider: {
114
+ provideHover: (model: MonacoTextModelLike, position: MonacoPositionLike) => Record<string, unknown> | null;
115
+ }
116
+ ) => { dispose: () => void };
117
+ typescript?: {
118
+ ScriptTarget?: Record<string, number>;
119
+ ModuleKind?: Record<string, number>;
120
+ ModuleResolutionKind?: Record<string, number>;
121
+ JsxEmit?: Record<string, number>;
122
+ typescriptDefaults?: MonacoTsDefaultsLike;
123
+ javascriptDefaults?: MonacoTsDefaultsLike;
124
+ };
125
+ json?: {
126
+ jsonDefaults?: {
127
+ setDiagnosticsOptions?: (opts: Record<string, unknown>) => void;
128
+ };
129
+ };
130
+ };
131
+ }
132
+
133
+ const VOID_HTML_TAGS = new Set([
134
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
135
+ 'link', 'meta', 'param', 'source', 'track', 'wbr'
136
+ ]);
137
+
138
+ const BUILTIN_NODE_MODULES = new Set([
139
+ 'assert', 'assert/strict', 'async_hooks', 'buffer', 'child_process', 'cluster',
140
+ 'console', 'constants', 'crypto', 'dgram', 'diagnostics_channel', 'dns', 'dns/promises',
141
+ 'domain', 'events', 'fs', 'fs/promises', 'http', 'http2', 'https', 'inspector',
142
+ 'module', 'net', 'os', 'path', 'path/posix', 'path/win32', 'perf_hooks', 'process',
143
+ 'punycode', 'querystring', 'readline', 'readline/promises', 'repl', 'sqlite',
144
+ 'stream', 'stream/consumers', 'stream/promises', 'stream/web', 'string_decoder',
145
+ 'sys', 'test', 'timers', 'timers/promises', 'tls', 'trace_events', 'tty', 'url',
146
+ 'util', 'util/types', 'v8', 'vm', 'wasi', 'worker_threads', 'zlib'
147
+ ]);
148
+
149
+ const NODE_AMBIENT_DTS = `
150
+ declare interface Buffer extends Uint8Array {
151
+ toString(encoding?: string, start?: number, end?: number): string;
152
+ write(str: string, offset?: number, length?: number, encoding?: string): number;
153
+ slice(start?: number, end?: number): Buffer;
154
+ equals(otherBuffer: Uint8Array): boolean;
155
+ }
156
+ declare var Buffer: {
157
+ from(data: string | ArrayLike<number> | ArrayBufferLike, encoding?: string): Buffer;
158
+ alloc(size: number, fill?: string | number): Buffer;
159
+ allocUnsafe(size: number): Buffer;
160
+ concat(list: ReadonlyArray<Uint8Array>, totalLength?: number): Buffer;
161
+ isBuffer(obj: unknown): obj is Buffer;
162
+ byteLength(string: string | Uint8Array, encoding?: string): number;
163
+ };
164
+ declare namespace NodeJS {
165
+ interface ProcessEnv { [key: string]: string | undefined; NODE_ENV?: string; HOME?: string; PATH?: string; }
166
+ interface ReadStream { on(event: string, listener: (...args: any[]) => void): this; resume(): this; pause(): this; setEncoding(enc: string): this; }
167
+ interface WriteStream { write(chunk: string | Uint8Array): boolean; columns?: number; rows?: number; isTTY?: boolean; }
168
+ interface Process {
169
+ env: ProcessEnv;
170
+ argv: string[];
171
+ cwd(): string;
172
+ chdir(directory: string): void;
173
+ exit(code?: number): never;
174
+ nextTick(callback: (...args: any[]) => void, ...args: any[]): void;
175
+ hrtime: { (time?: [number, number]): [number, number]; bigint(): bigint };
176
+ platform: string;
177
+ version: string;
178
+ versions: Record<string, string>;
179
+ pid: number;
180
+ stdout: WriteStream;
181
+ stderr: WriteStream;
182
+ stdin: ReadStream;
183
+ on(event: string, listener: (...args: any[]) => void): this;
184
+ }
185
+ }
186
+ declare var process: NodeJS.Process;
187
+
188
+ declare module 'fs' {
189
+ export interface Stats { isFile(): boolean; isDirectory(): boolean; size: number; mtimeMs: number; mtime: Date; }
190
+ export function readFileSync(path: string, encoding?: string | { encoding?: string }): any;
191
+ export function writeFileSync(path: string, data: string | Uint8Array, options?: any): void;
192
+ export function appendFileSync(path: string, data: string | Uint8Array): void;
193
+ export function existsSync(path: string): boolean;
194
+ export function mkdirSync(path: string, options?: { recursive?: boolean }): string | undefined;
195
+ export function readdirSync(path: string, options?: any): any[];
196
+ export function statSync(path: string): Stats;
197
+ export function lstatSync(path: string): Stats;
198
+ export function unlinkSync(path: string): void;
199
+ export function rmSync(path: string, options?: { recursive?: boolean; force?: boolean }): void;
200
+ export function renameSync(oldPath: string, newPath: string): void;
201
+ export function copyFileSync(src: string, dest: string): void;
202
+ export const promises: typeof import('fs/promises');
203
+ }
204
+ declare module 'node:fs' { export * from 'fs'; }
205
+
206
+ declare module 'fs/promises' {
207
+ import type { Stats } from 'fs';
208
+ export function readFile(path: string, encoding?: string | { encoding?: string }): Promise<any>;
209
+ export function writeFile(path: string, data: string | Uint8Array, options?: any): Promise<void>;
210
+ export function appendFile(path: string, data: string | Uint8Array): Promise<void>;
211
+ export function mkdir(path: string, options?: { recursive?: boolean }): Promise<string | undefined>;
212
+ export function readdir(path: string, options?: any): Promise<any[]>;
213
+ export function stat(path: string): Promise<Stats>;
214
+ export function unlink(path: string): Promise<void>;
215
+ export function rm(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>;
216
+ export function rename(oldPath: string, newPath: string): Promise<void>;
217
+ export function copyFile(src: string, dest: string): Promise<void>;
218
+ }
219
+ declare module 'node:fs/promises' { export * from 'fs/promises'; }
220
+
221
+ declare module 'path' {
222
+ export const sep: string;
223
+ export const delimiter: string;
224
+ export function join(...paths: string[]): string;
225
+ export function resolve(...paths: string[]): string;
226
+ export function dirname(p: string): string;
227
+ export function basename(p: string, ext?: string): string;
228
+ export function extname(p: string): string;
229
+ export function normalize(p: string): string;
230
+ export function relative(from: string, to: string): string;
231
+ export function isAbsolute(p: string): boolean;
232
+ export function parse(p: string): { root: string; dir: string; base: string; ext: string; name: string };
233
+ }
234
+ declare module 'node:path' { export * from 'path'; }
235
+
236
+ declare module 'os' {
237
+ export const EOL: string;
238
+ export function platform(): string;
239
+ export function arch(): string;
240
+ export function homedir(): string;
241
+ export function tmpdir(): string;
242
+ export function cpus(): Array<{ model: string; speed: number }>;
243
+ export function totalmem(): number;
244
+ export function freemem(): number;
245
+ }
246
+ declare module 'node:os' { export * from 'os'; }
247
+
248
+ declare module 'events' {
249
+ export class EventEmitter {
250
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
251
+ once(event: string | symbol, listener: (...args: any[]) => void): this;
252
+ off(event: string | symbol, listener: (...args: any[]) => void): this;
253
+ emit(event: string | symbol, ...args: any[]): boolean;
254
+ removeAllListeners(event?: string | symbol): this;
255
+ }
256
+ export default EventEmitter;
257
+ }
258
+ declare module 'node:events' { export * from 'events'; export { EventEmitter as default } from 'events'; }
259
+
260
+ declare module 'crypto' {
261
+ export function randomUUID(): string;
262
+ export function randomBytes(size: number): Buffer;
263
+ export function createHash(algorithm: string): { update(data: string | Uint8Array): any; digest(encoding?: string): any };
264
+ export function createHmac(algorithm: string, key: string | Uint8Array): { update(data: string | Uint8Array): any; digest(encoding?: string): any };
265
+ }
266
+ declare module 'node:crypto' { export * from 'crypto'; }
267
+
268
+ declare module 'http' {
269
+ export interface IncomingMessage { method?: string; url?: string; headers: Record<string, string | string[] | undefined>; on(event: string, cb: (...args: any[]) => void): this; }
270
+ export interface ServerResponse { statusCode: number; setHeader(name: string, value: string | number | string[]): this; writeHead(statusCode: number, headers?: Record<string, any>): this; write(chunk: any): boolean; end(data?: any): this; }
271
+ export interface Server { listen(port?: number, hostname?: string | (() => void), cb?: () => void): this; close(cb?: (err?: Error) => void): this; }
272
+ export function createServer(handler?: (req: IncomingMessage, res: ServerResponse) => void): Server;
273
+ }
274
+ declare module 'node:http' { export * from 'http'; }
275
+
276
+ declare module 'readline' {
277
+ export interface Interface {
278
+ question(query: string, callback: (answer: string) => void): void;
279
+ close(): void;
280
+ on(event: string, listener: (...args: any[]) => void): this;
281
+ }
282
+ export function createInterface(options: any): Interface;
283
+ }
284
+ declare module 'node:readline' { export * from 'readline'; }
285
+
286
+ declare module 'readline/promises' {
287
+ export interface Interface {
288
+ question(query: string, options?: { signal?: AbortSignal }): Promise<string>;
289
+ close(): void;
290
+ }
291
+ export function createInterface(options: any): Interface;
292
+ }
293
+ declare module 'node:readline/promises' { export * from 'readline/promises'; }
294
+
295
+ declare module 'assert' {
296
+ function assert(value: unknown, message?: string | Error): asserts value;
297
+ namespace assert {
298
+ export function ok(value: unknown, message?: string | Error): asserts value;
299
+ export function equal(actual: unknown, expected: unknown, message?: string | Error): void;
300
+ export function strictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
301
+ export function deepStrictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
302
+ export function throws(block: () => unknown, message?: RegExp | Function | string | Error): void;
303
+ export function rejects(block: (() => Promise<unknown>) | Promise<unknown>, message?: RegExp | Function | string | Error): Promise<void>;
304
+ }
305
+ export = assert;
306
+ }
307
+ declare module 'node:assert' { import assert = require('assert'); export = assert; }
308
+
309
+ declare module 'node:test' {
310
+ export function test(name: string, fn: (t: any) => void | Promise<void>): Promise<void>;
311
+ export function describe(name: string, fn: () => void | Promise<void>): Promise<void>;
312
+ export function it(name: string, fn: (t: any) => void | Promise<void>): Promise<void>;
313
+ export function before(fn: () => void | Promise<void>): void;
314
+ export function after(fn: () => void | Promise<void>): void;
315
+ export function beforeEach(fn: () => void | Promise<void>): void;
316
+ export function afterEach(fn: () => void | Promise<void>): void;
317
+ export default test;
318
+ }
319
+
320
+ declare module 'node:sqlite' {
321
+ export class StatementSync {
322
+ all(...params: any[]): Record<string, any>[];
323
+ get(...params: any[]): Record<string, any> | undefined;
324
+ run(...params: any[]): { changes: number; lastInsertRowid: number };
325
+ }
326
+ export class DatabaseSync {
327
+ constructor(location?: string);
328
+ exec(sql: string): void;
329
+ prepare(sql: string): StatementSync;
330
+ close(): void;
331
+ }
332
+ }
333
+ `;
334
+
335
+ const PACKAGE_JSON_SCHEMA = {
336
+ uri: 'https://codelab.local/schemas/package.json',
337
+ fileMatch: ['package.json', '**/package.json'],
338
+ schema: {
339
+ type: 'object',
340
+ properties: {
341
+ name: { type: 'string', description: 'The name of the package.' },
342
+ version: { type: 'string', description: 'Semantic version (semver) of the package.' },
343
+ description: { type: 'string', description: 'Brief package summary.' },
344
+ type: { type: 'string', enum: ['module', 'commonjs'], description: 'Module format for .js files.' },
345
+ main: { type: 'string', description: 'Primary CommonJS entrypoint.' },
346
+ module: { type: 'string', description: 'Primary ESM entrypoint.' },
347
+ types: { type: 'string', description: 'TypeScript declaration entrypoint (.d.ts).' },
348
+ private: { type: 'boolean', description: 'Prevent accidental npm publish when true.' },
349
+ license: { type: 'string', description: 'SPDX license identifier (e.g. MIT, Apache-2.0).' },
350
+ scripts: {
351
+ type: 'object',
352
+ description: 'Executable lifecycle and project scripts run via npm run <script>.',
353
+ additionalProperties: { type: 'string' }
354
+ },
355
+ dependencies: {
356
+ type: 'object',
357
+ description: 'Runtime npm package dependencies.',
358
+ additionalProperties: { type: 'string' }
359
+ },
360
+ devDependencies: {
361
+ type: 'object',
362
+ description: 'Development and build-time npm dependencies.',
363
+ additionalProperties: { type: 'string' }
364
+ }
365
+ }
366
+ }
367
+ };
368
+
369
+ const TSCONFIG_JSON_SCHEMA = {
370
+ uri: 'https://codelab.local/schemas/tsconfig.json',
371
+ fileMatch: ['tsconfig.json', '**/tsconfig.json', 'jsconfig.json', '**/jsconfig.json'],
372
+ schema: {
373
+ type: 'object',
374
+ properties: {
375
+ compilerOptions: {
376
+ type: 'object',
377
+ properties: {
378
+ target: {
379
+ type: 'string',
380
+ enum: ['ES5', 'ES6', 'ES2015', 'ES2018', 'ES2020', 'ES2021', 'ES2022', 'ES2023', 'ESNext'],
381
+ description: 'Set the JavaScript language version for emitted JavaScript.'
382
+ },
383
+ module: {
384
+ type: 'string',
385
+ enum: ['CommonJS', 'ES6', 'ES2015', 'ES2020', 'ES2022', 'ESNext', 'Node16', 'NodeNext', 'Bundler'],
386
+ description: 'Specify what module code is generated.'
387
+ },
388
+ moduleResolution: {
389
+ type: 'string',
390
+ enum: ['classic', 'node', 'node10', 'node16', 'nodenext', 'bundler'],
391
+ description: 'Specify how TypeScript looks up a file from a given module specifier.'
392
+ },
393
+ jsx: {
394
+ type: 'string',
395
+ enum: ['preserve', 'react', 'react-jsx', 'react-jsxdev', 'react-native'],
396
+ description: 'Specify what JSX code is generated.'
397
+ },
398
+ strict: { type: 'boolean', description: 'Enable all strict type-checking options.' },
399
+ noImplicitAny: { type: 'boolean', description: 'Enable error reporting for expressions with an implied any type.' },
400
+ strictNullChecks: { type: 'boolean', description: 'Take null and undefined into account during type checking.' },
401
+ allowJs: { type: 'boolean', description: 'Allow JavaScript files to be a part of your program.' },
402
+ checkJs: { type: 'boolean', description: 'Enable error reporting in type-checked JavaScript files.' },
403
+ noEmit: { type: 'boolean', description: 'Disable emitting files from a compilation.' },
404
+ esModuleInterop: { type: 'boolean', description: 'Emit additional JavaScript to ease importing CommonJS modules.' },
405
+ resolveJsonModule: { type: 'boolean', description: 'Enable importing .json files.' },
406
+ skipLibCheck: { type: 'boolean', description: 'Skip type checking all .d.ts files.' },
407
+ baseUrl: { type: 'string', description: 'Base directory to resolve non-relative module names.' },
408
+ outDir: { type: 'string', description: 'Specify an output folder for all emitted files.' },
409
+ rootDir: { type: 'string', description: 'Specify the root folder within your source files.' },
410
+ lib: { type: 'array', items: { type: 'string' }, description: 'Bundled library declaration files.' }
411
+ }
412
+ },
413
+ include: { type: 'array', items: { type: 'string' } },
414
+ exclude: { type: 'array', items: { type: 'string' } }
415
+ }
416
+ }
417
+ };
418
+
419
+ const registeredMonacoInstances = new WeakSet<object>();
420
+
421
+ /**
422
+ * Registers VS Code Dark Modern, Light Modern, and Dark High Contrast themes on Monaco.
423
+ */
424
+ export function registerCodeLabMonacoThemes(monaco: MonacoNamespaceLike | null | undefined): boolean {
425
+ if (!monaco || !monaco.editor || typeof monaco.editor.defineTheme !== 'function') {
426
+ return false;
427
+ }
428
+ try {
429
+ monaco.editor.defineTheme('codelab-dark-modern', {
430
+ base: 'vs-dark',
431
+ inherit: true,
432
+ rules: [
433
+ { token: 'comment', foreground: '6A9955', fontStyle: 'italic' },
434
+ { token: 'keyword', foreground: '569CD6' },
435
+ { token: 'keyword.control', foreground: 'C586C0' },
436
+ { token: 'keyword.operator', foreground: 'D4D4D4' },
437
+ { token: 'storage', foreground: '569CD6' },
438
+ { token: 'type', foreground: '4EC9B0' },
439
+ { token: 'type.identifier', foreground: '4EC9B0' },
440
+ { token: 'class', foreground: '4EC9B0' },
441
+ { token: 'interface', foreground: '4EC9B0' },
442
+ { token: 'function', foreground: 'DCDCAA' },
443
+ { token: 'identifier.function', foreground: 'DCDCAA' },
444
+ { token: 'variable', foreground: '9CDCFE' },
445
+ { token: 'variable.predefined', foreground: '4FC1FF' },
446
+ { token: 'constant', foreground: '4FC1FF' },
447
+ { token: 'string', foreground: 'CE9178' },
448
+ { token: 'string.key.json', foreground: '9CDCFE' },
449
+ { token: 'string.value.json', foreground: 'CE9178' },
450
+ { token: 'number', foreground: 'B5CEA8' },
451
+ { token: 'regexp', foreground: 'D16969' },
452
+ { token: 'tag', foreground: '569CD6' },
453
+ { token: 'attribute.name', foreground: '9CDCFE' },
454
+ { token: 'attribute.value', foreground: 'CE9178' },
455
+ { token: 'delimiter', foreground: 'D4D4D4' }
456
+ ],
457
+ colors: {
458
+ 'editor.background': '#1f1f1f',
459
+ 'editor.foreground': '#cccccc',
460
+ 'editorLineNumber.foreground': '#6e7681',
461
+ 'editorLineNumber.activeForeground': '#cccccc',
462
+ 'editorCursor.foreground': '#aeafad',
463
+ 'editor.selectionBackground': '#264f78',
464
+ 'editor.inactiveSelectionBackground': '#3a3d41',
465
+ 'editor.lineHighlightBackground': '#2a2d2e66',
466
+ 'editor.lineHighlightBorder': '#00000000',
467
+ 'editorGutter.background': '#1f1f1f',
468
+ 'editorGutter.modifiedBackground': '#0078d4',
469
+ 'editorGutter.addedBackground': '#2ea043',
470
+ 'editorGutter.deletedBackground': '#f85149',
471
+ 'editorWidget.background': '#202020',
472
+ 'editorWidget.border': '#454545',
473
+ 'editorSuggestWidget.background': '#202020',
474
+ 'editorSuggestWidget.border': '#454545',
475
+ 'editorSuggestWidget.selectedBackground': '#04395e',
476
+ 'editorSuggestWidget.highlightForeground': '#4daafc',
477
+ 'editorHoverWidget.background': '#202020',
478
+ 'editorHoverWidget.border': '#454545',
479
+ 'editorIndentGuide.background1': '#40404066',
480
+ 'editorIndentGuide.activeBackground1': '#707070',
481
+ 'editorBracketMatch.background': '#0064001a',
482
+ 'editorBracketMatch.border': '#888888',
483
+ 'scrollbarSlider.background': '#79797933',
484
+ 'scrollbarSlider.hoverBackground': '#646464b3',
485
+ 'scrollbarSlider.activeBackground': '#bfbfbf66',
486
+ 'diffEditor.insertedTextBackground': '#2ea04326',
487
+ 'diffEditor.removedTextBackground': '#f8514926'
488
+ }
489
+ });
490
+
491
+ monaco.editor.defineTheme('codelab-light-modern', {
492
+ base: 'vs',
493
+ inherit: true,
494
+ rules: [
495
+ { token: 'comment', foreground: '008000', fontStyle: 'italic' },
496
+ { token: 'keyword', foreground: '0000FF' },
497
+ { token: 'keyword.control', foreground: 'AF00DB' },
498
+ { token: 'type', foreground: '267F99' },
499
+ { token: 'type.identifier', foreground: '267F99' },
500
+ { token: 'function', foreground: '795E26' },
501
+ { token: 'variable', foreground: '001080' },
502
+ { token: 'string', foreground: 'A31515' },
503
+ { token: 'string.key.json', foreground: '0451A5' },
504
+ { token: 'number', foreground: '098658' },
505
+ { token: 'tag', foreground: '800000' },
506
+ { token: 'attribute.name', foreground: 'E50000' }
507
+ ],
508
+ colors: {
509
+ 'editor.background': '#ffffff',
510
+ 'editor.foreground': '#3b3b3b',
511
+ 'editorLineNumber.foreground': '#6e7681',
512
+ 'editorLineNumber.activeForeground': '#0b216f',
513
+ 'editorCursor.foreground': '#000000',
514
+ 'editor.selectionBackground': '#add6ff',
515
+ 'editor.lineHighlightBackground': '#f3f3f3',
516
+ 'editor.lineHighlightBorder': '#00000000',
517
+ 'editorGutter.background': '#ffffff',
518
+ 'editorWidget.background': '#f8f8f8',
519
+ 'editorWidget.border': '#cecece',
520
+ 'editorSuggestWidget.background': '#f8f8f8',
521
+ 'editorSuggestWidget.border': '#cecece',
522
+ 'editorSuggestWidget.selectedBackground': '#e8e8e8',
523
+ 'editorHoverWidget.background': '#f8f8f8',
524
+ 'editorHoverWidget.border': '#cecece',
525
+ 'diffEditor.insertedTextBackground': '#2ea04324',
526
+ 'diffEditor.removedTextBackground': '#cf222e20'
527
+ }
528
+ });
529
+
530
+ monaco.editor.defineTheme('codelab-hc-black', {
531
+ base: 'hc-black',
532
+ inherit: true,
533
+ rules: [],
534
+ colors: {
535
+ 'editor.background': '#000000',
536
+ 'editor.foreground': '#ffffff',
537
+ 'editor.selectionBackground': '#264f78',
538
+ 'contrastBorder': '#6fc3df'
539
+ }
540
+ });
541
+ return true;
542
+ } catch {
543
+ return false;
544
+ }
545
+ }
546
+
547
+ export function getMonacoThemeName(resolvedTheme: string, monaco?: MonacoNamespaceLike | null): string {
548
+ const hasCustomThemes = monaco ? registerCodeLabMonacoThemes(monaco) : false;
549
+ if (resolvedTheme === 'light') {
550
+ return hasCustomThemes ? 'codelab-light-modern' : 'vs';
551
+ }
552
+ if (resolvedTheme === 'high-contrast') {
553
+ return hasCustomThemes ? 'codelab-hc-black' : 'hc-black';
554
+ }
555
+ return hasCustomThemes ? 'codelab-dark-modern' : 'vs-dark';
556
+ }
557
+
558
+ /**
559
+ * Maps a workspace filename to its exact Monaco language ID.
560
+ */
561
+ export function getMonacoLanguageForFile(filePath: string, fallbackLang = 'javascript'): string {
562
+ const raw = String(filePath || '').trim();
563
+ if (!raw || raw === '__welcome__') return 'markdown';
564
+ const base = raw.split('/').pop() || raw;
565
+ const lower = base.toLowerCase();
566
+
567
+ if (lower === 'dockerfile' || lower.startsWith('dockerfile.')) return 'dockerfile';
568
+ if (lower === 'makefile' || lower === 'gnumakefile') return 'makefile';
569
+ if (lower === '.gitignore' || lower === '.npmrc' || lower.startsWith('.env')) return 'ini';
570
+
571
+ const dotIdx = lower.lastIndexOf('.');
572
+ const ext = dotIdx >= 0 ? lower.slice(dotIdx) : '';
573
+
574
+ switch (ext) {
575
+ case '.ts':
576
+ case '.tsx':
577
+ case '.mts':
578
+ case '.cts':
579
+ return 'typescript';
580
+ case '.js':
581
+ case '.jsx':
582
+ case '.mjs':
583
+ case '.cjs':
584
+ return 'javascript';
585
+ case '.json':
586
+ case '.jsonc':
587
+ case '.prettierrc':
588
+ case '.eslintrc':
589
+ return 'json';
590
+ case '.css':
591
+ return 'css';
592
+ case '.scss':
593
+ return 'scss';
594
+ case '.less':
595
+ return 'less';
596
+ case '.html':
597
+ case '.htm':
598
+ return 'html';
599
+ case '.md':
600
+ case '.mdx':
601
+ case '.markdown':
602
+ return 'markdown';
603
+ case '.py':
604
+ case '.pyw':
605
+ return 'python';
606
+ case '.cpp':
607
+ case '.cc':
608
+ case '.cxx':
609
+ case '.c':
610
+ case '.h':
611
+ case '.hpp':
612
+ case '.hxx':
613
+ return 'cpp';
614
+ case '.sql':
615
+ return 'sql';
616
+ case '.sh':
617
+ case '.bash':
618
+ case '.zsh':
619
+ return 'shell';
620
+ case '.yml':
621
+ case '.yaml':
622
+ return 'yaml';
623
+ case '.xml':
624
+ case '.svg':
625
+ return 'xml';
626
+ case '.toml':
627
+ case '.ini':
628
+ case '.conf':
629
+ return 'ini';
630
+ case '.txt':
631
+ case '.log':
632
+ return 'plaintext';
633
+ default:
634
+ if (fallbackLang === 'ts') return 'typescript';
635
+ if (fallbackLang === 'py') return 'python';
636
+ if (fallbackLang === 'cpp') return 'cpp';
637
+ if (fallbackLang === 'sql') return 'sql';
638
+ return 'javascript';
639
+ }
640
+ }
641
+
642
+ /**
643
+ * Human-readable VS Code Status Bar language mode label.
644
+ */
645
+ export function getLanguageDisplayLabel(filePath: string, fallbackLang = 'js'): string {
646
+ const raw = String(filePath || '').trim();
647
+ if (!raw || raw === '__welcome__') return 'Welcome';
648
+ const lower = (raw.split('/').pop() || raw).toLowerCase();
649
+ if (lower.endsWith('.tsx')) return 'TypeScript JSX';
650
+ if (lower.endsWith('.jsx')) return 'JavaScript JSX';
651
+ if (lower.endsWith('.jsonc') || lower === 'tsconfig.json' || lower === 'jsconfig.json') return 'JSON with Comments';
652
+ const langId = getMonacoLanguageForFile(raw, fallbackLang);
653
+ const labels: Record<string, string> = {
654
+ typescript: 'TypeScript',
655
+ javascript: 'JavaScript',
656
+ json: 'JSON',
657
+ css: 'CSS',
658
+ scss: 'SCSS',
659
+ less: 'Less',
660
+ html: 'HTML',
661
+ markdown: 'Markdown',
662
+ python: 'Python',
663
+ cpp: 'C++',
664
+ sql: 'SQL',
665
+ shell: 'Shell Script',
666
+ yaml: 'YAML',
667
+ xml: 'XML',
668
+ ini: 'Properties',
669
+ dockerfile: 'Dockerfile',
670
+ makefile: 'Makefile',
671
+ plaintext: 'Plain Text'
672
+ };
673
+ return labels[langId] || 'Plain Text';
674
+ }
675
+
676
+ export function normalizeWorkspaceRelPath(filePath: string): string {
677
+ let clean = String(filePath || '').replace(/\\/g, '/').trim();
678
+ const wsMatch = clean.match(/^(?:file:\/\/)?\/workspace(?:-[^/]+)?\/(.*)$/);
679
+ if (wsMatch) {
680
+ clean = wsMatch[1];
681
+ } else if (clean.startsWith('file:///')) {
682
+ clean = clean.slice('file:///'.length);
683
+ }
684
+ return clean.replace(/^\/+/, '');
685
+ }
686
+
687
+ /**
688
+ * Builds a canonical `file:///workspace[-instance]/<relPath>` Monaco Uri so multi-file TS/JS imports resolve cleanly.
689
+ */
690
+ export function toWorkspaceModelUri(
691
+ monaco: MonacoNamespaceLike | null | undefined,
692
+ filePath: string,
693
+ workspacePrefix = '/workspace'
694
+ ): MonacoUriLike | undefined {
695
+ const clean = normalizeWorkspaceRelPath(filePath);
696
+ const normPrefix = ('/' + String(workspacePrefix || '/workspace').replace(/^\/+|\/+$/g, '')).replace(/\/+$/, '');
697
+ if (!monaco || !monaco.Uri) return undefined;
698
+ if (typeof monaco.Uri.file === 'function') {
699
+ return monaco.Uri.file(`${normPrefix}/${clean}`);
700
+ }
701
+ if (typeof monaco.Uri.parse === 'function') {
702
+ return monaco.Uri.parse(`file://${normPrefix}/${clean}`);
703
+ }
704
+ return undefined;
705
+ }
706
+
707
+ export function fromWorkspaceModelUri(
708
+ uri: MonacoUriLike | string | null | undefined,
709
+ workspacePrefix = '/workspace'
710
+ ): string | null {
711
+ if (!uri) return null;
712
+ const raw = typeof uri === 'string' ? uri : String(uri.path || uri.toString?.() || '');
713
+ if (raw.includes('/node_modules/')) return null;
714
+ const normPrefix = ('/' + String(workspacePrefix || '/workspace').replace(/^\/+|\/+$/g, '')).replace(/\/+$/, '');
715
+ if (raw.startsWith(`file://${normPrefix}/`)) {
716
+ return raw.slice(`file://${normPrefix}/`.length).replace(/^\/+/, '');
717
+ }
718
+ if (raw.startsWith(`${normPrefix}/`)) {
719
+ return raw.slice(`${normPrefix}/`.length).replace(/^\/+/, '');
720
+ }
721
+ const instMatch = raw.match(/^(?:file:\/\/)?\/workspace(?:-[^/]+)?\/(.+)$/);
722
+ if (instMatch) {
723
+ return instMatch[1].replace(/^\/+/, '');
724
+ }
725
+ if (raw.startsWith('file:///') && !raw.startsWith('file:///node_modules/')) {
726
+ return raw.slice('file:///'.length).replace(/^\/+/, '');
727
+ }
728
+ if (raw.startsWith('/') && !raw.startsWith('/node_modules/')) {
729
+ return raw.replace(/^\/+/, '');
730
+ }
731
+ return null;
732
+ }
733
+
734
+ /**
735
+ * Strips `//` and `/* ... * /` comments + trailing commas so `tsconfig.json` (JSONC) parses cleanly.
736
+ */
737
+ export function parseJsoncSafe(raw: string): Record<string, unknown> | null {
738
+ if (!raw || typeof raw !== 'string') return null;
739
+ let out = '';
740
+ let inStr = false;
741
+ let esc = false;
742
+ let i = 0;
743
+ while (i < raw.length) {
744
+ const ch = raw[i];
745
+ const next = raw[i + 1];
746
+ if (inStr) {
747
+ out += ch;
748
+ if (esc) esc = false;
749
+ else if (ch === '\\') esc = true;
750
+ else if (ch === '"') inStr = false;
751
+ i++;
752
+ continue;
753
+ }
754
+ if (ch === '"') {
755
+ inStr = true;
756
+ out += ch;
757
+ i++;
758
+ continue;
759
+ }
760
+ if (ch === '/' && next === '/') {
761
+ while (i < raw.length && raw[i] !== '\n') i++;
762
+ continue;
763
+ }
764
+ if (ch === '/' && next === '*') {
765
+ i += 2;
766
+ while (i < raw.length && !(raw[i] === '*' && raw[i + 1] === '/')) i++;
767
+ i += 2;
768
+ continue;
769
+ }
770
+ out += ch;
771
+ i++;
772
+ }
773
+ const withoutTrailingCommas = out.replace(/,\s*([}\]])/g, '$1');
774
+ try {
775
+ const parsed: unknown = JSON.parse(withoutTrailingCommas);
776
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
777
+ ? (parsed as Record<string, unknown>)
778
+ : null;
779
+ } catch {
780
+ return null;
781
+ }
782
+ }
783
+
784
+ /**
785
+ * Synchronizes `/workspace/tsconfig.json` or `jsconfig.json` compiler options into Monaco's TS/JS workers.
786
+ */
787
+ export function syncTsConfigToMonaco(
788
+ monaco: MonacoNamespaceLike | null | undefined,
789
+ files: Record<string, string>,
790
+ workspaceRootUri = 'file:///workspace'
791
+ ): void {
792
+ const tsLang = monaco?.languages?.typescript;
793
+ if (!tsLang) return;
794
+
795
+ const cleanRootUri = String(workspaceRootUri || 'file:///workspace').replace(/\/+$/, '');
796
+ const tsDefaults = tsLang.typescriptDefaults;
797
+ const jsDefaults = tsLang.javascriptDefaults;
798
+ const ST = tsLang.ScriptTarget || {};
799
+ const MK = tsLang.ModuleKind || {};
800
+ const MR = tsLang.ModuleResolutionKind || {};
801
+ const JSX = tsLang.JsxEmit || {};
802
+
803
+ const baseCompilerOptions: Record<string, unknown> = {
804
+ target: ST.ESNext ?? ST.ES2020 ?? 99,
805
+ module: MK.ESNext ?? 99,
806
+ moduleResolution: MR.NodeJs ?? 2,
807
+ jsx: JSX.ReactJSX ?? JSX.React ?? 4,
808
+ allowNonTsExtensions: true,
809
+ allowJs: true,
810
+ checkJs: false,
811
+ esModuleInterop: true,
812
+ allowSyntheticDefaultImports: true,
813
+ resolveJsonModule: true,
814
+ isolatedModules: false,
815
+ noEmit: true,
816
+ skipLibCheck: true,
817
+ baseUrl: cleanRootUri
818
+ };
819
+
820
+ const rawTsConfig = files['tsconfig.json'] ?? files['jsconfig.json'];
821
+ const parsed = rawTsConfig ? parseJsoncSafe(rawTsConfig) : null;
822
+ const userOpts =
823
+ parsed && parsed.compilerOptions && typeof parsed.compilerOptions === 'object' && !Array.isArray(parsed.compilerOptions)
824
+ ? (parsed.compilerOptions as Record<string, unknown>)
825
+ : null;
826
+
827
+ if (userOpts) {
828
+ if (typeof userOpts.strict === 'boolean') baseCompilerOptions.strict = userOpts.strict;
829
+ if (typeof userOpts.noImplicitAny === 'boolean') baseCompilerOptions.noImplicitAny = userOpts.noImplicitAny;
830
+ if (typeof userOpts.strictNullChecks === 'boolean') baseCompilerOptions.strictNullChecks = userOpts.strictNullChecks;
831
+ if (typeof userOpts.checkJs === 'boolean') baseCompilerOptions.checkJs = userOpts.checkJs;
832
+ if (typeof userOpts.allowJs === 'boolean') baseCompilerOptions.allowJs = userOpts.allowJs;
833
+ if (typeof userOpts.experimentalDecorators === 'boolean') {
834
+ baseCompilerOptions.experimentalDecorators = userOpts.experimentalDecorators;
835
+ }
836
+ if (typeof userOpts.jsx === 'string') {
837
+ const jsxLower = userOpts.jsx.toLowerCase();
838
+ if (jsxLower === 'preserve' && JSX.Preserve !== undefined) baseCompilerOptions.jsx = JSX.Preserve;
839
+ else if (jsxLower === 'react' && JSX.React !== undefined) baseCompilerOptions.jsx = JSX.React;
840
+ else if (JSX.ReactJSX !== undefined) baseCompilerOptions.jsx = JSX.ReactJSX;
841
+ }
842
+ if (userOpts.paths && typeof userOpts.paths === 'object') {
843
+ baseCompilerOptions.paths = userOpts.paths;
844
+ }
845
+ if (typeof userOpts.baseUrl === 'string') {
846
+ const cleanBase = userOpts.baseUrl.replace(/^\.\/?/, '').replace(/^\/+/, '');
847
+ baseCompilerOptions.baseUrl = cleanBase ? `${cleanRootUri}/${cleanBase}` : cleanRootUri;
848
+ }
849
+ }
850
+
851
+ try {
852
+ if (tsDefaults?.setCompilerOptions) tsDefaults.setCompilerOptions(baseCompilerOptions);
853
+ if (tsDefaults?.setEagerModelSync) tsDefaults.setEagerModelSync(true);
854
+ if (tsDefaults?.setDiagnosticsOptions) {
855
+ tsDefaults.setDiagnosticsOptions({
856
+ noSemanticValidation: false,
857
+ noSyntaxValidation: false,
858
+ noSuggestionDiagnostics: false
859
+ });
860
+ }
861
+ if (jsDefaults?.setCompilerOptions) {
862
+ jsDefaults.setCompilerOptions({
863
+ ...baseCompilerOptions,
864
+ allowJs: true,
865
+ checkJs: Boolean(userOpts?.checkJs)
866
+ });
867
+ }
868
+ if (jsDefaults?.setEagerModelSync) jsDefaults.setEagerModelSync(true);
869
+ if (jsDefaults?.setDiagnosticsOptions) {
870
+ jsDefaults.setDiagnosticsOptions({
871
+ noSemanticValidation: false,
872
+ noSyntaxValidation: false
873
+ });
874
+ }
875
+ } catch (_err) {
876
+ void _err;
877
+ }
878
+ }
879
+
880
+ /**
881
+ * IndexedDB-backed Automatic Type Acquisition (ATA) controller for bare npm imports in TS/JS.
882
+ */
883
+ const ATA_DB_NAME = 'codelab_ata_cache_v1';
884
+ const ATA_STORE_NAME = 'dts';
885
+
886
+ function readAtaCache(pkgName: string): Promise<string | null> {
887
+ if (typeof indexedDB === 'undefined') return Promise.resolve(null);
888
+ return new Promise((resolve) => {
889
+ try {
890
+ const req = indexedDB.open(ATA_DB_NAME, 1);
891
+ req.onupgradeneeded = () => {
892
+ const db = req.result;
893
+ if (!db.objectStoreNames.contains(ATA_STORE_NAME)) {
894
+ db.createObjectStore(ATA_STORE_NAME);
895
+ }
896
+ };
897
+ req.onerror = () => resolve(null);
898
+ req.onsuccess = () => {
899
+ try {
900
+ const db = req.result;
901
+ const tx = db.transaction(ATA_STORE_NAME, 'readonly');
902
+ const getReq = tx.objectStore(ATA_STORE_NAME).get(pkgName);
903
+ getReq.onsuccess = () => resolve(typeof getReq.result === 'string' ? getReq.result : null);
904
+ getReq.onerror = () => resolve(null);
905
+ } catch {
906
+ resolve(null);
907
+ }
908
+ };
909
+ } catch {
910
+ resolve(null);
911
+ }
912
+ });
913
+ }
914
+
915
+ function writeAtaCache(pkgName: string, dts: string): Promise<void> {
916
+ if (typeof indexedDB === 'undefined') return Promise.resolve();
917
+ return new Promise((resolve) => {
918
+ try {
919
+ const req = indexedDB.open(ATA_DB_NAME, 1);
920
+ req.onupgradeneeded = () => {
921
+ const db = req.result;
922
+ if (!db.objectStoreNames.contains(ATA_STORE_NAME)) {
923
+ db.createObjectStore(ATA_STORE_NAME);
924
+ }
925
+ };
926
+ req.onerror = () => resolve();
927
+ req.onsuccess = () => {
928
+ try {
929
+ const db = req.result;
930
+ const tx = db.transaction(ATA_STORE_NAME, 'readwrite');
931
+ tx.objectStore(ATA_STORE_NAME).put(dts, pkgName);
932
+ tx.oncomplete = () => resolve();
933
+ tx.onerror = () => resolve();
934
+ } catch {
935
+ resolve();
936
+ }
937
+ };
938
+ } catch {
939
+ resolve();
940
+ }
941
+ });
942
+ }
943
+
944
+ export function extractBarePackageSpecifiers(files: Record<string, string>): string[] {
945
+ const packages = new Set<string>();
946
+ const importRegex = /(?:import|export)\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\)|import\(\s*['"]([^'"]+)['"]\s*\)/g;
947
+
948
+ const normalizePkg = (spec: string): string | null => {
949
+ const trimmed = String(spec || '').trim();
950
+ if (!trimmed || trimmed.startsWith('.') || trimmed.startsWith('/') || trimmed.startsWith('http:') || trimmed.startsWith('https:') || trimmed.startsWith('node:')) {
951
+ return null;
952
+ }
953
+ if (trimmed.startsWith('@')) {
954
+ const parts = trimmed.split('/');
955
+ if (parts.length < 2) return null;
956
+ return `${parts[0]}/${parts[1]}`;
957
+ }
958
+ const root = trimmed.split('/')[0];
959
+ if (!root || BUILTIN_NODE_MODULES.has(root)) return null;
960
+ if (!/^[a-zA-Z0-9._-]+$/.test(root)) return null;
961
+ return root;
962
+ };
963
+
964
+ for (const [path, content] of Object.entries(files || {})) {
965
+ const lower = path.toLowerCase();
966
+ if (lower === 'package.json' || lower.endsWith('/package.json')) {
967
+ const pkg = parseJsoncSafe(content);
968
+ if (pkg) {
969
+ for (const section of [pkg.dependencies, pkg.devDependencies]) {
970
+ if (section && typeof section === 'object') {
971
+ for (const name of Object.keys(section)) {
972
+ const normalized = normalizePkg(name);
973
+ if (normalized) packages.add(normalized);
974
+ }
975
+ }
976
+ }
977
+ }
978
+ continue;
979
+ }
980
+ if (!/\.(?:[cm]?[jt]sx?)$/i.test(lower)) continue;
981
+ importRegex.lastIndex = 0;
982
+ let m: RegExpExecArray | null;
983
+ while ((m = importRegex.exec(String(content || ''))) !== null) {
984
+ const spec = m[1] || m[2] || m[3] || '';
985
+ const normalized = normalizePkg(spec);
986
+ if (normalized) packages.add(normalized);
987
+ }
988
+ }
989
+
990
+ return Array.from(packages);
991
+ }
992
+
993
+ async function fetchPackageDtsFromCdn(pkgName: string): Promise<string | null> {
994
+ if (typeof fetch !== 'function') return null;
995
+
996
+ const fetchWithTimeout = async (url: string, method: 'GET' | 'HEAD' = 'GET'): Promise<Response | null> => {
997
+ const ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
998
+ const timer = setTimeout(() => ctrl?.abort(), 4500);
999
+ try {
1000
+ const res = await fetch(url, { method, signal: ctrl?.signal });
1001
+ return res;
1002
+ } catch {
1003
+ return null;
1004
+ } finally {
1005
+ clearTimeout(timer);
1006
+ }
1007
+ };
1008
+
1009
+ // Strategy 1: esm.sh X-TypeScript-Types header
1010
+ const esmHead = await fetchWithTimeout(`https://esm.sh/${pkgName}`, 'GET');
1011
+ if (esmHead) {
1012
+ const typesUrl = esmHead.headers?.get?.('x-typescript-types') || esmHead.headers?.get?.('X-TypeScript-Types');
1013
+ if (typesUrl) {
1014
+ const resolvedUrl = typesUrl.startsWith('http') ? typesUrl : `https://esm.sh${typesUrl.startsWith('/') ? '' : '/'}${typesUrl}`;
1015
+ const dtsRes = await fetchWithTimeout(resolvedUrl, 'GET');
1016
+ if (dtsRes && dtsRes.ok) {
1017
+ const text = await dtsRes.text();
1018
+ if (text && text.length < 600_000) return text;
1019
+ }
1020
+ }
1021
+ }
1022
+
1023
+ // Strategy 2: jsDelivr package.json -> types / typings or @types/<pkg>
1024
+ const tryJsDelivr = async (targetPkg: string): Promise<string | null> => {
1025
+ const pkgJsonRes = await fetchWithTimeout(`https://cdn.jsdelivr.net/npm/${targetPkg}/package.json`, 'GET');
1026
+ if (!pkgJsonRes || !pkgJsonRes.ok) return null;
1027
+ const meta = await pkgJsonRes.json().catch(() => null);
1028
+ if (!meta || typeof meta !== 'object') return null;
1029
+ const typesRel = String(meta.types || meta.typings || 'index.d.ts').replace(/^\.\//, '').replace(/^\/+/, '');
1030
+ const dtsRes = await fetchWithTimeout(`https://cdn.jsdelivr.net/npm/${targetPkg}/${typesRel}`, 'GET');
1031
+ if (dtsRes && dtsRes.ok) {
1032
+ const text = await dtsRes.text();
1033
+ if (text && text.length < 600_000) return text;
1034
+ }
1035
+ return null;
1036
+ };
1037
+
1038
+ const direct = await tryJsDelivr(pkgName);
1039
+ if (direct) return direct;
1040
+
1041
+ const typesPkgName = pkgName.startsWith('@')
1042
+ ? `@types/${pkgName.slice(1).replace('/', '__')}`
1043
+ : `@types/${pkgName}`;
1044
+ return tryJsDelivr(typesPkgName);
1045
+ }
1046
+
1047
+ export class WorkspaceAtaController {
1048
+ private monaco: MonacoNamespaceLike | null | undefined;
1049
+ private acquired = new Set<string>();
1050
+ private inFlight = new Set<string>();
1051
+ private disposables: Array<{ dispose?: () => void }> = [];
1052
+ private debounceTimer: ReturnType<typeof setTimeout> | null = null;
1053
+
1054
+ constructor(monaco: MonacoNamespaceLike | null | undefined) {
1055
+ this.monaco = monaco;
1056
+ }
1057
+
1058
+ public scheduleScan(files: Record<string, string>, delayMs = 450): void {
1059
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
1060
+ this.debounceTimer = setTimeout(() => {
1061
+ this.debounceTimer = null;
1062
+ void this.scanNow(files);
1063
+ }, delayMs);
1064
+ }
1065
+
1066
+ public async scanNow(files: Record<string, string>): Promise<void> {
1067
+ const tsLang = this.monaco?.languages?.typescript;
1068
+ if (!tsLang?.typescriptDefaults?.addExtraLib) return;
1069
+
1070
+ // Also inspect installed VFS /workspace/node_modules/<pkg>/.d.ts first if present in workspace map
1071
+ const specs = extractBarePackageSpecifiers(files);
1072
+ for (const pkgName of specs) {
1073
+ if (this.acquired.has(pkgName) || this.inFlight.has(pkgName)) continue;
1074
+ this.inFlight.add(pkgName);
1075
+ void this.acquireOne(pkgName).finally(() => {
1076
+ this.inFlight.delete(pkgName);
1077
+ });
1078
+ }
1079
+ }
1080
+
1081
+ public registerLocalPackageTypes(pkgName: string, dtsContent: string): void {
1082
+ if (!pkgName || !dtsContent || this.acquired.has(pkgName)) return;
1083
+ this.injectExtraLib(pkgName, dtsContent);
1084
+ }
1085
+
1086
+ private injectExtraLib(pkgName: string, rawDts: string): void {
1087
+ const tsLang = this.monaco?.languages?.typescript;
1088
+ if (!tsLang?.typescriptDefaults?.addExtraLib) return;
1089
+ this.acquired.add(pkgName);
1090
+
1091
+ const hasDeclareModule = new RegExp(`declare\\s+module\\s+['"]${pkgName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`).test(rawDts);
1092
+ const wrapped = hasDeclareModule
1093
+ ? rawDts
1094
+ : `${rawDts}\n;declare module '${pkgName}' { export * from 'file:///node_modules/${pkgName}/index'; }\n`;
1095
+ const fileUri = `file:///node_modules/${pkgName}/index.d.ts`;
1096
+ try {
1097
+ const d1 = tsLang.typescriptDefaults.addExtraLib(rawDts, fileUri);
1098
+ if (d1) this.disposables.push(d1);
1099
+ if (tsLang.javascriptDefaults?.addExtraLib) {
1100
+ const d2 = tsLang.javascriptDefaults.addExtraLib(wrapped, fileUri);
1101
+ if (d2) this.disposables.push(d2);
1102
+ }
1103
+ } catch (_err) {
1104
+ void _err;
1105
+ }
1106
+ }
1107
+
1108
+ private async acquireOne(pkgName: string): Promise<void> {
1109
+ const cached = await readAtaCache(pkgName);
1110
+ if (cached) {
1111
+ this.injectExtraLib(pkgName, cached);
1112
+ return;
1113
+ }
1114
+ const fetched = await fetchPackageDtsFromCdn(pkgName);
1115
+ if (fetched) {
1116
+ await writeAtaCache(pkgName, fetched);
1117
+ this.injectExtraLib(pkgName, fetched);
1118
+ }
1119
+ }
1120
+
1121
+ public dispose(): void {
1122
+ if (this.debounceTimer) {
1123
+ clearTimeout(this.debounceTimer);
1124
+ this.debounceTimer = null;
1125
+ }
1126
+ for (const d of this.disposables) {
1127
+ try {
1128
+ d?.dispose?.();
1129
+ } catch (_err) {
1130
+ void _err;
1131
+ }
1132
+ }
1133
+ this.disposables = [];
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * Registers cross-file Go to Definition (`F12` / `Cmd+Click`) so Monaco switches tabs automatically.
1139
+ */
1140
+ export function registerCrossFileEditorOpener(
1141
+ monaco: MonacoNamespaceLike | null | undefined,
1142
+ onOpenWorkspaceFile: (relPath: string, lineNumber?: number, column?: number) => boolean | void,
1143
+ workspacePrefix = '/workspace'
1144
+ ): { dispose: () => void } {
1145
+ if (!monaco?.editor || typeof monaco.editor.registerEditorOpener !== 'function') {
1146
+ return { dispose: () => {} };
1147
+ }
1148
+ return monaco.editor.registerEditorOpener({
1149
+ openCodeEditor(
1150
+ _source: unknown,
1151
+ resource: MonacoUriLike | string,
1152
+ selectionOrPosition?: Partial<MonacoRangeLike & MonacoPositionLike>
1153
+ ): boolean {
1154
+ const targetRel = fromWorkspaceModelUri(resource, workspacePrefix);
1155
+ if (!targetRel) return false;
1156
+ const line = selectionOrPosition?.startLineNumber ?? selectionOrPosition?.lineNumber ?? 1;
1157
+ const col = selectionOrPosition?.startColumn ?? selectionOrPosition?.column ?? 1;
1158
+ const handled = onOpenWorkspaceFile(targetRel, line, col);
1159
+ return handled !== false;
1160
+ }
1161
+ });
1162
+ }
1163
+
1164
+ /**
1165
+ * Attaches HTML / JSX / TSX auto-closing tag insertion (`<div>` -> `<div>|</div>`) to a Monaco editor instance.
1166
+ */
1167
+ export function attachAutoCloseTagBehavior(
1168
+ monaco: MonacoNamespaceLike | null | undefined,
1169
+ editor: MonacoEditorLike | null | undefined
1170
+ ): { dispose: () => void } {
1171
+ if (!editor || typeof editor.onDidChangeModelContent !== 'function') {
1172
+ return { dispose: () => {} };
1173
+ }
1174
+ let isInserting = false;
1175
+ const sub = editor.onDidChangeModelContent((event: MonacoChangeEventLike) => {
1176
+ if (isInserting || !event || !Array.isArray(event.changes) || event.changes.length !== 1) return;
1177
+ const change = event.changes[0];
1178
+ if (change.text !== '>') return;
1179
+
1180
+ const model = editor.getModel?.();
1181
+ if (!model) return;
1182
+ const langId = typeof model.getLanguageId === 'function' ? model.getLanguageId() : '';
1183
+ if (langId !== 'html' && langId !== 'javascript' && langId !== 'typescript' && langId !== 'xml') return;
1184
+
1185
+ const lineNumber = change.range.startLineNumber;
1186
+ const afterCol = change.range.startColumn + 1;
1187
+ const linePrefix = String(model.getLineContent(lineNumber) || '').slice(0, afterCol - 1);
1188
+
1189
+ // Ignore self-closing `/>`, closing `</tag>`, comments `-->`, or comparison operators `a >`
1190
+ if (linePrefix.endsWith('/>') || linePrefix.endsWith('-->') || linePrefix.endsWith('=>')) return;
1191
+ const tagMatch = linePrefix.match(/<([A-Za-z][A-Za-z0-9._:-]*)(?:\s+[^<>]*?)?>$/);
1192
+ if (!tagMatch) return;
1193
+ const tagName = tagMatch[1];
1194
+ if (VOID_HTML_TAGS.has(tagName.toLowerCase())) return;
1195
+
1196
+ // Avoid duplicating if closing tag already immediately follows cursor
1197
+ const lineSuffix = String(model.getLineContent(lineNumber) || '').slice(afterCol - 1);
1198
+ if (lineSuffix.startsWith(`</${tagName}>`)) return;
1199
+
1200
+ isInserting = true;
1201
+ try {
1202
+ const range = monaco?.Range
1203
+ ? new monaco.Range(lineNumber, afterCol, lineNumber, afterCol)
1204
+ : { startLineNumber: lineNumber, startColumn: afterCol, endLineNumber: lineNumber, endColumn: afterCol };
1205
+ editor.executeEdits('codelab-auto-close-tag', [{ range, text: `</${tagName}>`, forceMoveMarkers: false }]);
1206
+ editor.setPosition({ lineNumber, column: afterCol });
1207
+ } catch (_err) {
1208
+ void _err;
1209
+ } finally {
1210
+ isInserting = false;
1211
+ }
1212
+ });
1213
+ return sub || { dispose: () => {} };
1214
+ }
1215
+
1216
+ function expandSimpleEmmet(abbr: string): string | null {
1217
+ const clean = abbr.trim();
1218
+ if (clean === '!' || clean === 'html:5') {
1219
+ return [
1220
+ '<!DOCTYPE html>',
1221
+ '<html lang="en">',
1222
+ '<head>',
1223
+ ' <meta charset="UTF-8" />',
1224
+ ' <meta name="viewport" content="width=device-width, initial-scale=1.0" />',
1225
+ ' <title>${1:Document}</title>',
1226
+ '</head>',
1227
+ '<body>',
1228
+ ' $0',
1229
+ '</body>',
1230
+ '</html>'
1231
+ ].join('\n');
1232
+ }
1233
+ // Support tag#id.class1.class2*count and parent>child*count
1234
+ const parts = clean.split('>');
1235
+ if (parts.length > 3) return null;
1236
+
1237
+ const parseSegment = (seg: string): { tag: string; id: string; classes: string[]; count: number } | null => {
1238
+ const m = seg.match(/^([a-zA-Z][a-zA-Z0-9-]*)?(?:#([a-zA-Z0-9_-]+))?((?:\.[a-zA-Z0-9_-]+)*)(?:\*(\d+))?$/);
1239
+ if (!m) return null;
1240
+ const tag = m[1] || (m[2] || m[3] ? 'div' : '');
1241
+ if (!tag) return null;
1242
+ const id = m[2] || '';
1243
+ const classes = m[3] ? m[3].slice(1).split('.').filter(Boolean) : [];
1244
+ const count = Math.min(12, Math.max(1, Number(m[4] || 1)));
1245
+ if (parts.length === 1 && !m[2] && classes.length === 0 && !m[4]) return null;
1246
+ return { tag, id, classes, count };
1247
+ };
1248
+
1249
+ const parsed = parts.map(parseSegment);
1250
+ if (parsed.some((p) => !p)) return null;
1251
+
1252
+ const renderNode = (idx: number, indent: string, tabStopRef: { n: number }): string => {
1253
+ const node = parsed[idx]!;
1254
+ const attrs = [
1255
+ node.id ? ` id="${node.id}"` : '',
1256
+ node.classes.length ? ` class="${node.classes.join(' ')}"` : ''
1257
+ ].join('');
1258
+ const lines: string[] = [];
1259
+ for (let i = 0; i < node.count; i++) {
1260
+ if (VOID_HTML_TAGS.has(node.tag.toLowerCase())) {
1261
+ lines.push(`${indent}<${node.tag}${attrs} />`);
1262
+ } else if (idx < parsed.length - 1) {
1263
+ lines.push(`${indent}<${node.tag}${attrs}>\n${renderNode(idx + 1, indent + ' ', tabStopRef)}\n${indent}</${node.tag}>`);
1264
+ } else {
1265
+ const stop = tabStopRef.n === 0 ? '$0' : `\${${tabStopRef.n}}`;
1266
+ tabStopRef.n++;
1267
+ lines.push(`${indent}<${node.tag}${attrs}>${stop}</${node.tag}>`);
1268
+ }
1269
+ }
1270
+ return lines.join('\n');
1271
+ };
1272
+
1273
+ return renderNode(0, '', { n: 1 });
1274
+ }
1275
+
1276
+ function collectCssVariables(files: Record<string, string>): Map<string, { value: string; file: string }> {
1277
+ const vars = new Map<string, { value: string; file: string }>();
1278
+ const re = /(--[a-zA-Z0-9_-]+)\s*:\s*([^;}\n]+)/g;
1279
+ for (const [file, content] of Object.entries(files || {})) {
1280
+ if (!/\.(?:css|scss|less|html)$/i.test(file)) continue;
1281
+ re.lastIndex = 0;
1282
+ let m: RegExpExecArray | null;
1283
+ while ((m = re.exec(String(content || ''))) !== null) {
1284
+ if (!vars.has(m[1])) {
1285
+ vars.set(m[1], { value: m[2].trim(), file });
1286
+ }
1287
+ }
1288
+ }
1289
+ return vars;
1290
+ }
1291
+
1292
+ function collectSqlSchemaTables(files: Record<string, string>, currentContent = ''): Array<{ table: string; columns: Array<{ name: string; type: string }> }> {
1293
+ const tables = new Map<string, Array<{ name: string; type: string }>>();
1294
+ const sources = [...Object.entries(files || {}).filter(([f]) => /\.sql$/i.test(f)).map(([, c]) => c), currentContent];
1295
+ const createTableRe = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s*\(([\s\S]*?)\)\s*;/gi;
1296
+
1297
+ for (const src of sources) {
1298
+ if (!src) continue;
1299
+ createTableRe.lastIndex = 0;
1300
+ let m: RegExpExecArray | null;
1301
+ while ((m = createTableRe.exec(src)) !== null) {
1302
+ const tableName = m[1];
1303
+ const body = m[2];
1304
+ const cols: Array<{ name: string; type: string }> = [];
1305
+ for (const rawLine of body.split(',')) {
1306
+ const trimmed = rawLine.trim();
1307
+ if (!trimmed || /^(?:PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT)\b/i.test(trimmed)) continue;
1308
+ const colMatch = trimmed.match(/^["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s+([A-Za-z0-9_()]+)/);
1309
+ if (colMatch) {
1310
+ cols.push({ name: colMatch[1], type: colMatch[2].toUpperCase() });
1311
+ }
1312
+ }
1313
+ tables.set(tableName, cols);
1314
+ }
1315
+ }
1316
+
1317
+ return Array.from(tables.entries()).map(([table, columns]) => ({ table, columns }));
1318
+ }
1319
+
1320
+ const SQL_KEYWORDS = [
1321
+ 'SELECT', 'FROM', 'WHERE', 'INSERT INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE FROM',
1322
+ 'CREATE TABLE', 'CREATE INDEX', 'DROP TABLE', 'ALTER TABLE', 'JOIN', 'LEFT JOIN',
1323
+ 'INNER JOIN', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT', 'OFFSET', 'DISTINCT',
1324
+ 'AS', 'ON', 'AND', 'OR', 'NOT', 'NULL', 'IS NULL', 'IS NOT NULL', 'PRIMARY KEY',
1325
+ 'FOREIGN KEY', 'REFERENCES', 'AUTOINCREMENT', 'DEFAULT', 'UNIQUE', 'BEGIN TRANSACTION', 'COMMIT'
1326
+ ];
1327
+
1328
+ const SQL_FUNCTIONS: Array<{ name: string; sig: string; doc: string }> = [
1329
+ { name: 'COUNT', sig: 'COUNT(expr) -> INTEGER', doc: 'Returns the number of rows matching the query.' },
1330
+ { name: 'SUM', sig: 'SUM(expr) -> NUMERIC', doc: 'Returns the sum of non-NULL values in a group.' },
1331
+ { name: 'AVG', sig: 'AVG(expr) -> REAL', doc: 'Returns the average value of non-NULL values.' },
1332
+ { name: 'MIN', sig: 'MIN(expr) -> ANY', doc: 'Returns the minimum non-NULL value.' },
1333
+ { name: 'MAX', sig: 'MAX(expr) -> ANY', doc: 'Returns the maximum non-NULL value.' },
1334
+ { name: 'COALESCE', sig: 'COALESCE(x, y, ...) -> ANY', doc: 'Returns the first non-NULL argument.' },
1335
+ { name: 'LOWER', sig: 'LOWER(str) -> TEXT', doc: 'Converts ASCII string characters to lowercase.' },
1336
+ { name: 'UPPER', sig: 'UPPER(str) -> TEXT', doc: 'Converts ASCII string characters to uppercase.' },
1337
+ { name: 'ROUND', sig: 'ROUND(num, digits?) -> REAL', doc: 'Rounds a floating-point value to the specified precision.' },
1338
+ { name: 'DATETIME', sig: "DATETIME('now', modifier...) -> TEXT", doc: 'Returns formatted ISO-8601 date and time.' }
1339
+ ];
1340
+
1341
+ /**
1342
+ * Configures Monaco language services once per `monaco` global instance:
1343
+ * - VS Code Modern themes
1344
+ * - Node.js ambient `.d.ts` + `tsconfig.json` compiler options
1345
+ * - JSON schemas (`package.json`, `tsconfig.json`, `jsconfig.json`)
1346
+ * - HTML Emmet completions, CSS cross-file variable completions/hovers, SQL schema completions/hovers
1347
+ */
1348
+ export function initializeMonacoIntelligence(
1349
+ monaco: MonacoNamespaceLike | null | undefined,
1350
+ getWorkspaceFiles: WorkspaceFilesGetter
1351
+ ): void {
1352
+ if (!monaco || typeof monaco !== 'object') return;
1353
+ registerCodeLabMonacoThemes(monaco);
1354
+ syncTsConfigToMonaco(monaco, getWorkspaceFiles() || {});
1355
+
1356
+ if (registeredMonacoInstances.has(monaco)) return;
1357
+ registeredMonacoInstances.add(monaco);
1358
+
1359
+ // 1. Node.js / Web ambient declarations
1360
+ try {
1361
+ const tsLang = monaco.languages?.typescript;
1362
+ if (tsLang?.typescriptDefaults?.addExtraLib) {
1363
+ tsLang.typescriptDefaults.addExtraLib(NODE_AMBIENT_DTS, 'file:///node_modules/@types/node/index.d.ts');
1364
+ }
1365
+ if (tsLang?.javascriptDefaults?.addExtraLib) {
1366
+ tsLang.javascriptDefaults.addExtraLib(NODE_AMBIENT_DTS, 'file:///node_modules/@types/node/index.d.ts');
1367
+ }
1368
+ } catch (_err) {
1369
+ void _err;
1370
+ }
1371
+
1372
+ // 2. JSON Schemas (`package.json`, `tsconfig.json`, `jsconfig.json`)
1373
+ try {
1374
+ const jsonDefaults = monaco.languages?.json?.jsonDefaults;
1375
+ if (jsonDefaults?.setDiagnosticsOptions) {
1376
+ jsonDefaults.setDiagnosticsOptions({
1377
+ validate: true,
1378
+ allowComments: true,
1379
+ trailingCommas: 'ignore',
1380
+ enableSchemaRequest: false,
1381
+ schemas: [PACKAGE_JSON_SCHEMA, TSCONFIG_JSON_SCHEMA]
1382
+ });
1383
+ }
1384
+ } catch (_err) {
1385
+ void _err;
1386
+ }
1387
+
1388
+ if (!monaco.languages?.registerCompletionItemProvider) return;
1389
+ const CIK = monaco.languages.CompletionItemKind || {};
1390
+ const CITR = monaco.languages.CompletionItemInsertTextRule || {};
1391
+
1392
+ // 3. HTML Emmet abbreviation expansion
1393
+ monaco.languages.registerCompletionItemProvider('html', {
1394
+ triggerCharacters: ['!', '.', '#', '*', '>'],
1395
+ provideCompletionItems(model: MonacoTextModelLike, position: MonacoPositionLike) {
1396
+ const linePrefix = String(model.getLineContent(position.lineNumber) || '').slice(0, position.column - 1);
1397
+ const abbrMatch = linePrefix.match(/(?:^|\s)(!|html:5|[a-zA-Z.#][a-zA-Z0-9.#*>-]*)$/);
1398
+ if (!abbrMatch) return { suggestions: [] };
1399
+ const abbr = abbrMatch[1];
1400
+ const expanded = expandSimpleEmmet(abbr);
1401
+ if (!expanded) return { suggestions: [] };
1402
+ const startCol = position.column - abbr.length;
1403
+ return {
1404
+ suggestions: [{
1405
+ label: `${abbr} (Emmet)`,
1406
+ kind: CIK.Snippet ?? 27,
1407
+ detail: 'Emmet Abbreviation',
1408
+ documentation: { value: '```html\n' + expanded.replace(/\$\{\d+:?([^}]*)\}|\$0/g, '$1') + '\n```' },
1409
+ insertText: expanded,
1410
+ insertTextRules: CITR.InsertAsSnippet ?? 4,
1411
+ range: {
1412
+ startLineNumber: position.lineNumber,
1413
+ startColumn: startCol,
1414
+ endLineNumber: position.lineNumber,
1415
+ endColumn: position.column
1416
+ }
1417
+ }]
1418
+ };
1419
+ }
1420
+ });
1421
+
1422
+ // 4. Cross-file CSS Custom Property (`--var`) completions & hover
1423
+ for (const cssLang of ['css', 'scss', 'less']) {
1424
+ monaco.languages.registerCompletionItemProvider(cssLang, {
1425
+ triggerCharacters: ['-'],
1426
+ provideCompletionItems(model: MonacoTextModelLike, position: MonacoPositionLike) {
1427
+ const linePrefix = String(model.getLineContent(position.lineNumber) || '').slice(0, position.column - 1);
1428
+ if (!/(?:var\(\s*|--)[a-zA-Z0-9_-]*$/.test(linePrefix)) return { suggestions: [] };
1429
+ const vars = collectCssVariables(getWorkspaceFiles() || {});
1430
+ const word = model.getWordUntilPosition(position);
1431
+ const startCol = Math.max(1, linePrefix.lastIndexOf('--') + 1 || word.startColumn);
1432
+ const range = {
1433
+ startLineNumber: position.lineNumber,
1434
+ startColumn: startCol,
1435
+ endLineNumber: position.lineNumber,
1436
+ endColumn: position.column
1437
+ };
1438
+ return {
1439
+ suggestions: Array.from(vars.entries()).map(([name, info]) => ({
1440
+ label: name,
1441
+ kind: CIK.Variable ?? 5,
1442
+ detail: `${info.value} (${info.file})`,
1443
+ insertText: name,
1444
+ range
1445
+ }))
1446
+ };
1447
+ }
1448
+ });
1449
+
1450
+ if (monaco.languages.registerHoverProvider) {
1451
+ monaco.languages.registerHoverProvider(cssLang, {
1452
+ provideHover(model: MonacoTextModelLike, position: MonacoPositionLike) {
1453
+ const line = String(model.getLineContent(position.lineNumber) || '');
1454
+ const re = /--[a-zA-Z0-9_-]+/g;
1455
+ let m: RegExpExecArray | null;
1456
+ while ((m = re.exec(line)) !== null) {
1457
+ const start = m.index + 1;
1458
+ const end = start + m[0].length;
1459
+ if (position.column >= start && position.column <= end) {
1460
+ const info = collectCssVariables(getWorkspaceFiles() || {}).get(m[0]);
1461
+ if (!info) return null;
1462
+ const hoverRange = monaco.Range
1463
+ ? new monaco.Range(position.lineNumber, start, position.lineNumber, end)
1464
+ : { startLineNumber: position.lineNumber, startColumn: start, endLineNumber: position.lineNumber, endColumn: end };
1465
+ return {
1466
+ range: hoverRange,
1467
+ contents: [
1468
+ { value: `\`\`\`css\n${m[0]}: ${info.value};\n\`\`\`` },
1469
+ { value: `Defined in \`${info.file}\`` }
1470
+ ]
1471
+ };
1472
+ }
1473
+ }
1474
+ return null;
1475
+ }
1476
+ });
1477
+ }
1478
+ }
1479
+
1480
+ // 5. SQL Schema-Aware Completion & Hover Provider
1481
+ monaco.languages.registerCompletionItemProvider('sql', {
1482
+ triggerCharacters: ['.', ' '],
1483
+ provideCompletionItems(model: MonacoTextModelLike, position: MonacoPositionLike) {
1484
+ const word = model.getWordUntilPosition(position);
1485
+ const range = {
1486
+ startLineNumber: position.lineNumber,
1487
+ startColumn: word.startColumn,
1488
+ endLineNumber: position.lineNumber,
1489
+ endColumn: word.endColumn
1490
+ };
1491
+ const tables = collectSqlSchemaTables(getWorkspaceFiles() || {}, model.getValue?.() || '');
1492
+ const linePrefix = String(model.getLineContent(position.lineNumber) || '').slice(0, position.column - 1);
1493
+ const dotMatch = linePrefix.match(/([A-Za-z_][A-Za-z0-9_]*)\.[A-Za-z0-9_]*$/);
1494
+
1495
+ if (dotMatch) {
1496
+ const tableObj = tables.find((t) => t.table.toLowerCase() === dotMatch[1].toLowerCase());
1497
+ if (tableObj) {
1498
+ return {
1499
+ suggestions: tableObj.columns.map((col) => ({
1500
+ label: col.name,
1501
+ kind: CIK.Field ?? 4,
1502
+ detail: `${tableObj.table}.${col.name} (${col.type})`,
1503
+ insertText: col.name,
1504
+ range
1505
+ }))
1506
+ };
1507
+ }
1508
+ }
1509
+
1510
+ const suggestions: Array<Record<string, unknown>> = [];
1511
+ for (const kw of SQL_KEYWORDS) {
1512
+ suggestions.push({
1513
+ label: kw,
1514
+ kind: CIK.Keyword ?? 17,
1515
+ detail: 'SQL Keyword',
1516
+ insertText: kw,
1517
+ range
1518
+ });
1519
+ }
1520
+ for (const fn of SQL_FUNCTIONS) {
1521
+ suggestions.push({
1522
+ label: fn.name,
1523
+ kind: CIK.Function ?? 1,
1524
+ detail: fn.sig,
1525
+ documentation: fn.doc,
1526
+ insertText: `${fn.name}($0)`,
1527
+ insertTextRules: CITR.InsertAsSnippet ?? 4,
1528
+ range
1529
+ });
1530
+ }
1531
+ for (const t of tables) {
1532
+ suggestions.push({
1533
+ label: t.table,
1534
+ kind: CIK.Struct ?? 6,
1535
+ detail: `Table (${t.columns.map((c) => c.name).join(', ')})`,
1536
+ insertText: t.table,
1537
+ range
1538
+ });
1539
+ for (const col of t.columns) {
1540
+ suggestions.push({
1541
+ label: col.name,
1542
+ kind: CIK.Field ?? 4,
1543
+ detail: `${t.table}.${col.name}: ${col.type}`,
1544
+ insertText: col.name,
1545
+ range
1546
+ });
1547
+ }
1548
+ }
1549
+ return { suggestions };
1550
+ }
1551
+ });
1552
+
1553
+ if (monaco.languages.registerHoverProvider) {
1554
+ monaco.languages.registerHoverProvider('sql', {
1555
+ provideHover(model: MonacoTextModelLike, position: MonacoPositionLike) {
1556
+ const word = model.getWordAtPosition(position);
1557
+ if (!word) return null;
1558
+ const upper = word.word.toUpperCase();
1559
+ const fn = SQL_FUNCTIONS.find((f) => f.name === upper);
1560
+ if (fn) {
1561
+ const fnRange = monaco.Range
1562
+ ? new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn)
1563
+ : { startLineNumber: position.lineNumber, startColumn: word.startColumn, endLineNumber: position.lineNumber, endColumn: word.endColumn };
1564
+ return {
1565
+ range: fnRange,
1566
+ contents: [{ value: `\`\`\`sql\n${fn.sig}\n\`\`\`` }, { value: fn.doc }]
1567
+ };
1568
+ }
1569
+ const tables = collectSqlSchemaTables(getWorkspaceFiles() || {}, model.getValue?.() || '');
1570
+ const table = tables.find((t) => t.table.toLowerCase() === word.word.toLowerCase());
1571
+ if (table) {
1572
+ const cols = table.columns.map((c) => ` ${c.name} ${c.type}`).join(',\n');
1573
+ const tblRange = monaco.Range
1574
+ ? new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn)
1575
+ : { startLineNumber: position.lineNumber, startColumn: word.startColumn, endLineNumber: position.lineNumber, endColumn: word.endColumn };
1576
+ return {
1577
+ range: tblRange,
1578
+ contents: [{ value: `\`\`\`sql\nTABLE ${table.table} (\n${cols}\n)\n\`\`\`` }]
1579
+ };
1580
+ }
1581
+ return null;
1582
+ }
1583
+ });
1584
+ }
1585
+ }
1586
+
1587
+ /**
1588
+ * Extracts structured symbols from any workspace file for Explorer OUTLINE,
1589
+ * cursor-aware Breadcrumbs, and Quick Open `@symbol` / `#workspaceSymbol`.
1590
+ */
1591
+ export function extractDocumentSymbols(filePath: string, content: string): CodeLabSymbolItem[] {
1592
+ const symbols: CodeLabSymbolItem[] = [];
1593
+ const text = String(content || '');
1594
+ if (!text) return symbols;
1595
+ const lines = text.split('\n');
1596
+ const lang = getMonacoLanguageForFile(filePath);
1597
+
1598
+ if (lang === 'markdown') {
1599
+ for (let i = 0; i < lines.length; i++) {
1600
+ const m = lines[i].match(/^(#{1,6})\s+(.+?)\s*$/);
1601
+ if (m) {
1602
+ symbols.push({
1603
+ name: m[2],
1604
+ kind: 'heading',
1605
+ detail: `H${m[1].length}`,
1606
+ file: filePath,
1607
+ line: i + 1,
1608
+ endLine: i + 1,
1609
+ column: 1
1610
+ });
1611
+ }
1612
+ }
1613
+ return symbols;
1614
+ }
1615
+
1616
+ if (lang === 'python') {
1617
+ let activeClass: { name: string; indent: number; idx: number } | null = null;
1618
+ for (let i = 0; i < lines.length; i++) {
1619
+ const line = lines[i];
1620
+ const indent = (line.match(/^(\s*)/)?.[1] || '').length;
1621
+ if (activeClass && line.trim() && !line.trim().startsWith('#') && indent <= activeClass.indent) {
1622
+ symbols[activeClass.idx].endLine = Math.max(symbols[activeClass.idx].line, i);
1623
+ activeClass = null;
1624
+ }
1625
+ const clsMatch = line.match(/^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)/);
1626
+ if (clsMatch) {
1627
+ const idx = symbols.push({
1628
+ name: clsMatch[1],
1629
+ kind: 'class',
1630
+ file: filePath,
1631
+ line: i + 1,
1632
+ endLine: lines.length,
1633
+ column: line.indexOf(clsMatch[1]) + 1
1634
+ }) - 1;
1635
+ activeClass = { name: clsMatch[1], indent, idx };
1636
+ continue;
1637
+ }
1638
+ const defMatch = line.match(/^\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/);
1639
+ if (defMatch) {
1640
+ symbols.push({
1641
+ name: defMatch[1],
1642
+ kind: activeClass && indent > activeClass.indent ? 'method' : 'function',
1643
+ detail: `(${defMatch[2].trim()})`,
1644
+ containerName: activeClass && indent > activeClass.indent ? activeClass.name : undefined,
1645
+ file: filePath,
1646
+ line: i + 1,
1647
+ endLine: i + 1,
1648
+ column: line.indexOf(defMatch[1]) + 1
1649
+ });
1650
+ }
1651
+ }
1652
+ return symbols;
1653
+ }
1654
+
1655
+ if (lang === 'cpp') {
1656
+ for (let i = 0; i < lines.length; i++) {
1657
+ const line = lines[i];
1658
+ const trimmed = line.trim();
1659
+ if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#')) continue;
1660
+ const typeMatch = line.match(/^\s*(class|struct|enum)\s+([A-Za-z_][A-Za-z0-9_]*)/);
1661
+ if (typeMatch) {
1662
+ symbols.push({
1663
+ name: typeMatch[2],
1664
+ kind: typeMatch[1] === 'struct' ? 'struct' : typeMatch[1] === 'enum' ? 'enum' : 'class',
1665
+ file: filePath,
1666
+ line: i + 1,
1667
+ endLine: i + 1,
1668
+ column: line.indexOf(typeMatch[2]) + 1
1669
+ });
1670
+ continue;
1671
+ }
1672
+ const fnMatch = line.match(/^\s*(?:template\s*<[^>]+>\s*)?(?:inline\s+|static\s+|virtual\s+|constexpr\s+)*[A-Za-z_][A-Za-z0-9_:<>,&\s*]*\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^;{}]*)\)\s*(?:const\s*)?(?:noexcept\s*)?\{?/);
1673
+ if (fnMatch && !/^(?:if|for|while|switch|catch|return)$/.test(fnMatch[1])) {
1674
+ symbols.push({
1675
+ name: fnMatch[1],
1676
+ kind: 'function',
1677
+ detail: `(${fnMatch[2].trim()})`,
1678
+ file: filePath,
1679
+ line: i + 1,
1680
+ endLine: i + 1,
1681
+ column: line.indexOf(fnMatch[1]) + 1
1682
+ });
1683
+ }
1684
+ }
1685
+ return symbols;
1686
+ }
1687
+
1688
+ if (lang === 'sql') {
1689
+ for (let i = 0; i < lines.length; i++) {
1690
+ const m = lines[i].match(/^\s*CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?(TABLE|VIEW|INDEX|TRIGGER)\s+(?:IF\s+NOT\s+EXISTS\s+)?["`[]?([A-Za-z_][A-Za-z0-9_]*)/i);
1691
+ if (m) {
1692
+ symbols.push({
1693
+ name: m[2],
1694
+ kind: 'table',
1695
+ detail: m[1].toUpperCase(),
1696
+ file: filePath,
1697
+ line: i + 1,
1698
+ endLine: i + 1,
1699
+ column: lines[i].indexOf(m[2]) + 1
1700
+ });
1701
+ }
1702
+ }
1703
+ return symbols;
1704
+ }
1705
+
1706
+ if (lang === 'css' || lang === 'scss' || lang === 'less') {
1707
+ for (let i = 0; i < lines.length; i++) {
1708
+ const m = lines[i].match(/^\s*([.#@][A-Za-z0-9_.:[\]="\s>-]+?)\s*\{/);
1709
+ if (m) {
1710
+ symbols.push({
1711
+ name: m[1].trim(),
1712
+ kind: 'property',
1713
+ file: filePath,
1714
+ line: i + 1,
1715
+ endLine: i + 1,
1716
+ column: 1
1717
+ });
1718
+ }
1719
+ }
1720
+ return symbols;
1721
+ }
1722
+
1723
+ if (lang === 'json') {
1724
+ for (let i = 0; i < lines.length; i++) {
1725
+ const m = lines[i].match(/^\s{1,4}"([^"]+)"\s*:/);
1726
+ if (m) {
1727
+ symbols.push({
1728
+ name: m[1],
1729
+ kind: 'property',
1730
+ file: filePath,
1731
+ line: i + 1,
1732
+ endLine: i + 1,
1733
+ column: lines[i].indexOf(m[1]) + 1
1734
+ });
1735
+ }
1736
+ }
1737
+ return symbols;
1738
+ }
1739
+
1740
+ // Default: TypeScript / JavaScript
1741
+ let activeContainer: { name: string; braceDepth: number; idx: number } | null = null;
1742
+ let braceDepth = 0;
1743
+ for (let i = 0; i < lines.length; i++) {
1744
+ const line = lines[i];
1745
+ const trimmed = line.trim();
1746
+ if (!trimmed.startsWith('//') && !trimmed.startsWith('*')) {
1747
+ const classMatch = line.match(/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(class|interface|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/);
1748
+ if (classMatch) {
1749
+ const kind = classMatch[1] as SymbolKindName;
1750
+ const idx = symbols.push({
1751
+ name: classMatch[2],
1752
+ kind,
1753
+ file: filePath,
1754
+ line: i + 1,
1755
+ endLine: i + 1,
1756
+ column: line.indexOf(classMatch[2]) + 1
1757
+ }) - 1;
1758
+ if (kind === 'class' || kind === 'interface' || kind === 'enum') {
1759
+ activeContainer = { name: classMatch[2], braceDepth, idx };
1760
+ }
1761
+ } else {
1762
+ const fnMatch = line.match(/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)/);
1763
+ if (fnMatch) {
1764
+ symbols.push({
1765
+ name: fnMatch[1],
1766
+ kind: 'function',
1767
+ detail: `(${fnMatch[2].trim()})`,
1768
+ file: filePath,
1769
+ line: i + 1,
1770
+ endLine: i + 1,
1771
+ column: line.indexOf(fnMatch[1]) + 1
1772
+ });
1773
+ } else {
1774
+ const arrowMatch = line.match(/^\s*(?:export\s+)?(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\(([^)]*)\)|([A-Za-z_$][A-Za-z0-9_$]*))\s*=>/);
1775
+ if (arrowMatch) {
1776
+ symbols.push({
1777
+ name: arrowMatch[2],
1778
+ kind: 'function',
1779
+ detail: `(${(arrowMatch[3] ?? arrowMatch[4] ?? '').trim()}) =>`,
1780
+ file: filePath,
1781
+ line: i + 1,
1782
+ endLine: i + 1,
1783
+ column: line.indexOf(arrowMatch[2]) + 1
1784
+ });
1785
+ } else if (activeContainer && braceDepth === activeContainer.braceDepth + 1) {
1786
+ const methodMatch = line.match(/^\s*(?:public\s+|private\s+|protected\s+|static\s+|readonly\s+|async\s+|get\s+|set\s+)*([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?::[^{;]+)?\{/);
1787
+ if (methodMatch && !/^(?:if|for|while|switch|catch)$/.test(methodMatch[1])) {
1788
+ symbols.push({
1789
+ name: methodMatch[1],
1790
+ kind: 'method',
1791
+ detail: `(${methodMatch[2].trim()})`,
1792
+ containerName: activeContainer.name,
1793
+ file: filePath,
1794
+ line: i + 1,
1795
+ endLine: i + 1,
1796
+ column: line.indexOf(methodMatch[1]) + 1
1797
+ });
1798
+ }
1799
+ } else if (braceDepth === 0) {
1800
+ const constMatch = line.match(/^\s*(?:export\s+)?(const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*([^=;]+))?\s*=/);
1801
+ if (constMatch) {
1802
+ symbols.push({
1803
+ name: constMatch[2],
1804
+ kind: constMatch[1] === 'const' ? 'constant' : 'variable',
1805
+ detail: constMatch[3]?.trim(),
1806
+ file: filePath,
1807
+ line: i + 1,
1808
+ endLine: i + 1,
1809
+ column: line.indexOf(constMatch[2]) + 1
1810
+ });
1811
+ }
1812
+ }
1813
+ }
1814
+ }
1815
+ }
1816
+
1817
+ for (let c = 0; c < line.length; c++) {
1818
+ if (line[c] === '{') braceDepth++;
1819
+ else if (line[c] === '}') {
1820
+ braceDepth = Math.max(0, braceDepth - 1);
1821
+ if (activeContainer && braceDepth <= activeContainer.braceDepth) {
1822
+ symbols[activeContainer.idx].endLine = i + 1;
1823
+ activeContainer = null;
1824
+ }
1825
+ }
1826
+ }
1827
+ }
1828
+
1829
+ for (let s = 0; s < symbols.length; s++) {
1830
+ if (symbols[s].endLine <= symbols[s].line) {
1831
+ const nextLine = symbols[s + 1] ? symbols[s + 1].line - 1 : lines.length;
1832
+ symbols[s].endLine = Math.max(symbols[s].line, nextLine);
1833
+ }
1834
+ }
1835
+
1836
+ return symbols;
1837
+ }
1838
+
1839
+ export function extractWorkspaceSymbols(files: Record<string, string>): CodeLabSymbolItem[] {
1840
+ const all: CodeLabSymbolItem[] = [];
1841
+ for (const [filePath, content] of Object.entries(files || {})) {
1842
+ if (!filePath || filePath === '__welcome__' || filePath.startsWith('.git/')) continue;
1843
+ const docSymbols = extractDocumentSymbols(filePath, content);
1844
+ for (const sym of docSymbols) all.push(sym);
1845
+ }
1846
+ return all;
1847
+ }
1848
+
1849
+ export function findEnclosingSymbolAtLine(symbols: CodeLabSymbolItem[], lineNumber: number): CodeLabSymbolItem | null {
1850
+ let best: CodeLabSymbolItem | null = null;
1851
+ for (const sym of symbols) {
1852
+ if (lineNumber >= sym.line && lineNumber <= sym.endLine) {
1853
+ if (!best || sym.line >= best.line) {
1854
+ best = sym;
1855
+ }
1856
+ }
1857
+ }
1858
+ return best;
1859
+ }