@innovatorved/code-lab 0.7.1 → 0.7.2

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 (71) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +5 -5
  4. package/dist/code-lab-sql.esm.js +2 -2
  5. package/dist/code-lab-sql.umd.js +3 -3
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +918 -884
  9. package/dist/code-lab.js +917 -881
  10. package/dist/extensions/cpp.esm.js +33 -33
  11. package/dist/extensions/cpp.js +33 -33
  12. package/dist/extensions/python.esm.js +79 -49
  13. package/dist/extensions/python.js +79 -49
  14. package/dist/index.d.ts +1 -1
  15. package/dist/logger.d.ts +4 -20
  16. package/dist/modular-kernel.d.ts +0 -1
  17. package/dist/packages/core/src/errors.d.ts +5 -1
  18. package/dist/packages/fs/src/backends.d.ts +0 -27
  19. package/dist/packages/fs/src/index.d.ts +1 -1
  20. package/dist/packages/ui/src/html.d.ts +1 -0
  21. package/dist/packages/ui/src/index.d.ts +1 -0
  22. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -2
  23. package/dist/packages/ui/src/observability.d.ts +1 -1
  24. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  25. package/dist/preview-sw.js +1 -1
  26. package/dist/runtime.d.ts +3 -0
  27. package/dist/runtime.esm.js +2 -2
  28. package/dist/runtime.js +2 -2
  29. package/dist/schemas.d.ts +1 -1
  30. package/dist/shell.esm.js +277 -285
  31. package/dist/shell.js +277 -285
  32. package/dist/terminal.esm.js +2 -2
  33. package/dist/terminal.js +2 -2
  34. package/dist/workbench/editor.d.ts +0 -4
  35. package/dist/workbench/index.d.ts +0 -2
  36. package/dist/workbench/intellisense.d.ts +0 -1
  37. package/dist/workbench/xterm-adapter.d.ts +0 -1
  38. package/package.json +2 -4
  39. package/src/code-lab.css +0 -8086
  40. package/src/csp.ts +0 -590
  41. package/src/diagnostics.ts +0 -287
  42. package/src/extensions/cpp.ts +0 -2371
  43. package/src/extensions/guided-lab.ts +0 -68
  44. package/src/extensions/javascript.ts +0 -54
  45. package/src/extensions/python.ts +0 -1743
  46. package/src/extensions/typescript.ts +0 -85
  47. package/src/extensions/umbrella.ts +0 -5
  48. package/src/html.ts +0 -88
  49. package/src/index.ts +0 -129
  50. package/src/logger.ts +0 -139
  51. package/src/modular-kernel.ts +0 -7
  52. package/src/preview-sw.js +0 -296
  53. package/src/runtime/test-harness.ts +0 -57
  54. package/src/runtime.ts +0 -10565
  55. package/src/sample.html +0 -304
  56. package/src/schemas.ts +0 -366
  57. package/src/scm.ts +0 -2453
  58. package/src/search.ts +0 -433
  59. package/src/shell.ts +0 -10990
  60. package/src/storage.ts +0 -773
  61. package/src/terminal.ts +0 -1402
  62. package/src/workbench/command-palette.ts +0 -101
  63. package/src/workbench/diff-editor.ts +0 -472
  64. package/src/workbench/editor.ts +0 -49
  65. package/src/workbench/icons.ts +0 -255
  66. package/src/workbench/index.ts +0 -29
  67. package/src/workbench/intellisense.ts +0 -1884
  68. package/src/workbench/share.ts +0 -128
  69. package/src/workbench/xterm-adapter.ts +0 -1571
  70. package/src/workbench.ts +0 -21825
  71. package/src/zip.ts +0 -348
package/src/terminal.ts DELETED
@@ -1,1402 +0,0 @@
1
- // @ts-nocheck
2
- /**
3
- * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
4
- *
5
- * High-fidelity, self-contained terminal emulator engine providing:
6
- * - Inline prompt with cwd awareness (codelab:${cwd}$ )
7
- * - Interactive REPL sub-mode (> ) with .exit and Ctrl+D/Ctrl+C
8
- * - Character-by-character editing with cursor navigation:
9
- * ArrowLeft, ArrowRight, Home, End, Ctrl+A, Ctrl+E, Ctrl+U, Ctrl+K, Backspace, Delete
10
- * - Tab auto-completion for built-in commands and VFS filesystem paths
11
- * - History navigation (ArrowUp, ArrowDown)
12
- * - ANSI 16/256 SGR escape sequence translation to styled Geist HTML spans
13
- * - Headless DOM safety (defensive guards for Node.js test environments)
14
- *
15
- * (C) 2026 InnovatorVed / CodeLab. MIT License.
16
- */
17
-
18
- (function (root, factory) {
19
- const exports = factory();
20
- if (root) {
21
- root.CodeLabTerminal = exports;
22
- root.PTYTerminalEngine = exports.PTYTerminalEngine;
23
- root.createPTYTerminalEngine = exports.createPTYTerminalEngine;
24
- root.createTerminal = exports.createTerminal;
25
- root.ansiToHtml = exports.ansiToHtml;
26
- root.parseAnsiToHtml = exports.parseAnsiToHtml;
27
- }
28
- if (typeof module !== 'undefined' && module.exports) {
29
- module.exports = exports;
30
- } else if (typeof define === 'function' && define.amd) {
31
- define([], function () { return exports; });
32
- }
33
- })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
34
- 'use strict';
35
-
36
- const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
37
- const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
38
- ? _termRoot.CodeLabLogger.createLogger()
39
- : {
40
- debug() {},
41
- info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
42
- warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
43
- error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
44
- };
45
-
46
- const ANSI_CODE_MAP = {
47
- 1: 'cl-ansi-bold',
48
- 2: 'cl-ansi-dim',
49
- 3: 'cl-ansi-italic',
50
- 4: 'cl-ansi-underline',
51
- 7: 'cl-ansi-inverse',
52
- 9: 'cl-ansi-strike',
53
- 30: 'cl-ansi-black',
54
- 31: 'cl-ansi-red',
55
- 32: 'cl-ansi-green',
56
- 33: 'cl-ansi-yellow',
57
- 34: 'cl-ansi-blue',
58
- 35: 'cl-ansi-magenta',
59
- 36: 'cl-ansi-cyan',
60
- 37: 'cl-ansi-white',
61
- 90: 'cl-ansi-gray',
62
- 91: 'cl-ansi-bright-red',
63
- 92: 'cl-ansi-bright-green',
64
- 93: 'cl-ansi-bright-yellow',
65
- 94: 'cl-ansi-bright-blue',
66
- 95: 'cl-ansi-bright-magenta',
67
- 96: 'cl-ansi-bright-cyan',
68
- 97: 'cl-ansi-bright-white',
69
- 40: 'cl-ansi-bg-black',
70
- 41: 'cl-ansi-bg-red',
71
- 42: 'cl-ansi-bg-green',
72
- 43: 'cl-ansi-bg-yellow',
73
- 44: 'cl-ansi-bg-blue',
74
- 45: 'cl-ansi-bg-magenta',
75
- 46: 'cl-ansi-bg-cyan',
76
- 47: 'cl-ansi-bg-white',
77
- 100: 'cl-ansi-bg-bright-black',
78
- 101: 'cl-ansi-bg-bright-red',
79
- 102: 'cl-ansi-bg-bright-green',
80
- 103: 'cl-ansi-bg-bright-yellow',
81
- 104: 'cl-ansi-bg-bright-blue',
82
- 105: 'cl-ansi-bg-bright-magenta',
83
- 106: 'cl-ansi-bg-bright-cyan',
84
- 107: 'cl-ansi-bg-bright-white'
85
- };
86
-
87
- const ANSI_256_PALETTE = [
88
- '#000000', '#cd3131', '#0dbc79', '#e5e510', '#2472c8', '#bc3fbc', '#11a8cd', '#e5e5e5',
89
- '#666666', '#f14c4c', '#23d18b', '#f5f543', '#3b8eea', '#d670d6', '#29b8db', '#ffffff'
90
- ];
91
-
92
- function ansi256ToColor(n) {
93
- const idx = Number(n);
94
- if (!Number.isFinite(idx) || idx < 0 || idx > 255) return null;
95
- if (idx < 16) return ANSI_256_PALETTE[idx];
96
- if (idx < 232) {
97
- const c = idx - 16;
98
- const r = Math.floor(c / 36);
99
- const g = Math.floor((c % 36) / 6);
100
- const b = c % 6;
101
- const toChannel = v => (v === 0 ? 0 : 55 + v * 40);
102
- return `rgb(${toChannel(r)}, ${toChannel(g)}, ${toChannel(b)})`;
103
- }
104
- const gray = 8 + (idx - 232) * 10;
105
- return `rgb(${gray}, ${gray}, ${gray})`;
106
- }
107
-
108
- function escapeHtml(str) {
109
- if (str == null) return '';
110
- return String(str)
111
- .replace(/&/g, '&amp;')
112
- .replace(/</g, '&lt;')
113
- .replace(/>/g, '&gt;')
114
- .replace(/"/g, '&quot;')
115
- .replace(/'/g, '&#39;');
116
- }
117
-
118
- function resolveAnsiControlCodes(raw) {
119
- if (!raw) return '';
120
- const s = String(raw);
121
- if (!s.includes('\x1b') && !s.includes('\r')) return s;
122
-
123
- let text = s;
124
- // Strip OSC sequences (e.g. window title \x1b]0;...\x07) while preserving OSC-8 link visible labels
125
- text = text.replace(/\x1b\]8;[^;]*;[^\x07\x1b]*(?:\x07|\x1b\\)([\s\S]*?)\x1b\]8;;(?:\x07|\x1b\\)/g, '$1');
126
- text = text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '');
127
-
128
- const clearIdx2 = text.lastIndexOf('\x1b[2J');
129
- const clearIdx3 = text.lastIndexOf('\x1b[3J');
130
- const clearRis = text.lastIndexOf('\x1bc');
131
- const lastClear = Math.max(clearIdx2, clearIdx3, clearRis);
132
- if (lastClear !== -1) {
133
- const skipLen = lastClear === clearRis ? 2 : 4;
134
- text = text.slice(lastClear + skipLen);
135
- text = text.replace(/^(?:\x1b\[[23]J|\x1b\[(?:\d+;\d+)?H)+/, '');
136
- }
137
-
138
- text = text.replace(/\r\n/g, '\n');
139
- const rawLines = text.split('\n');
140
- const resolvedLines = [];
141
-
142
- for (let l = 0; l < rawLines.length; l++) {
143
- let line = rawLines[l];
144
-
145
- while (/\x1b\[(?:1)?A/.test(line)) {
146
- const upMatch = /\x1b\[(?:1)?A/.exec(line);
147
- const beforeUp = line.slice(0, upMatch.index);
148
- let afterUp = line.slice(upMatch.index + upMatch[0].length);
149
- if (resolvedLines.length > 0) {
150
- if (afterUp.includes('\x1b[2K')) {
151
- afterUp = afterUp.slice(afterUp.lastIndexOf('\x1b[2K') + 4);
152
- resolvedLines[resolvedLines.length - 1] = afterUp;
153
- } else if (afterUp.includes('\r')) {
154
- const parts = afterUp.split('\r');
155
- resolvedLines[resolvedLines.length - 1] = parts[parts.length - 1];
156
- } else {
157
- resolvedLines[resolvedLines.length - 1] = afterUp;
158
- }
159
- line = beforeUp;
160
- } else {
161
- line = beforeUp + afterUp;
162
- }
163
- }
164
-
165
- if (line.includes('\x1b[2K')) {
166
- const idx = line.lastIndexOf('\x1b[2K');
167
- line = line.slice(idx + 4);
168
- }
169
-
170
- if (line.includes('\r')) {
171
- const parts = line.split('\r');
172
- line = parts[parts.length - 1];
173
- }
174
-
175
- line = line.replace(/\x1b\[[0]?K/g, '');
176
- line = line.replace(/\x1b\[(?:1)?G/g, '');
177
- resolvedLines.push(line);
178
- }
179
-
180
- return resolvedLines.join('\n');
181
- }
182
-
183
- function ansiToHtml(str) {
184
- if (!str) return '';
185
- const resolved = resolveAnsiControlCodes(String(str));
186
- if (!resolved.includes('\x1b[')) {
187
- return escapeHtml(resolved);
188
- }
189
-
190
- // Strip non-color cursor control sequences without stripping lowercase 'm' SGR codes
191
- const cleaned = resolved.replace(/\x1b\[[0-9;?]*(?!m)[A-Za-z]/g, '');
192
-
193
- const tokenRegex = /\x1b\[([0-9;]*)m/g;
194
- let result = '';
195
- let lastIdx = 0;
196
- let match;
197
-
198
- const state = {
199
- bold: false,
200
- dim: false,
201
- italic: false,
202
- underline: false,
203
- inverse: false,
204
- strike: false,
205
- fgClass: null,
206
- bgClass: null,
207
- fgColor: null,
208
- bgColor: null
209
- };
210
-
211
- const resetState = () => {
212
- state.bold = false;
213
- state.dim = false;
214
- state.italic = false;
215
- state.underline = false;
216
- state.inverse = false;
217
- state.strike = false;
218
- state.fgClass = null;
219
- state.bgClass = null;
220
- state.fgColor = null;
221
- state.bgColor = null;
222
- };
223
-
224
- const renderChunk = (rawText) => {
225
- if (!rawText) return '';
226
- const escaped = escapeHtml(rawText);
227
- const classes = [];
228
- if (state.bold) classes.push('cl-ansi-bold');
229
- if (state.dim) classes.push('cl-ansi-dim');
230
- if (state.italic) classes.push('cl-ansi-italic');
231
- if (state.underline) classes.push('cl-ansi-underline');
232
- if (state.inverse) classes.push('cl-ansi-inverse');
233
- if (state.strike) classes.push('cl-ansi-strike');
234
- if (state.fgClass) classes.push(state.fgClass);
235
- if (state.bgClass) classes.push(state.bgClass);
236
-
237
- const styles = [];
238
- if (state.fgColor) styles.push(`color:${state.fgColor}`);
239
- if (state.bgColor) styles.push(`background-color:${state.bgColor}`);
240
- if (state.inverse && !state.fgClass && !state.bgClass) {
241
- styles.push('filter:invert(1)');
242
- }
243
- if (state.strike) {
244
- styles.push('text-decoration:line-through');
245
- }
246
-
247
- if (classes.length === 0 && styles.length === 0) {
248
- return escaped;
249
- }
250
- const classAttr = classes.length > 0 ? ` class="${classes.join(' ')}"` : '';
251
- const styleAttr = styles.length > 0 ? ` style="${styles.join(';')}"` : '';
252
- return `<span${classAttr}${styleAttr}>${escaped}</span>`;
253
- };
254
-
255
- while ((match = tokenRegex.exec(cleaned)) !== null) {
256
- const rawText = cleaned.slice(lastIdx, match.index);
257
- if (rawText) result += renderChunk(rawText);
258
- lastIdx = tokenRegex.lastIndex;
259
-
260
- const codes = match[1] ? match[1].split(';').map(Number) : [0];
261
- for (let i = 0; i < codes.length; i++) {
262
- const code = codes[i];
263
- if (code === 0 || Number.isNaN(code)) {
264
- resetState();
265
- } else if (code === 1) {
266
- state.bold = true;
267
- } else if (code === 2) {
268
- state.dim = true;
269
- } else if (code === 3) {
270
- state.italic = true;
271
- } else if (code === 4) {
272
- state.underline = true;
273
- } else if (code === 7) {
274
- state.inverse = true;
275
- } else if (code === 9) {
276
- state.strike = true;
277
- } else if (code === 22) {
278
- state.bold = false;
279
- state.dim = false;
280
- } else if (code === 23) {
281
- state.italic = false;
282
- } else if (code === 24) {
283
- state.underline = false;
284
- } else if (code === 27) {
285
- state.inverse = false;
286
- } else if (code === 29) {
287
- state.strike = false;
288
- } else if (code === 39) {
289
- state.fgClass = null;
290
- state.fgColor = null;
291
- } else if (code === 49) {
292
- state.bgClass = null;
293
- state.bgColor = null;
294
- } else if ((code === 38 || code === 48) && codes[i + 1] === 5 && i + 2 < codes.length) {
295
- const color = ansi256ToColor(codes[i + 2]);
296
- if (color) {
297
- if (code === 38) {
298
- state.fgClass = null;
299
- state.fgColor = color;
300
- } else {
301
- state.bgClass = null;
302
- state.bgColor = color;
303
- }
304
- }
305
- i += 2;
306
- } else if ((code === 38 || code === 48) && codes[i + 1] === 2 && i + 4 < codes.length) {
307
- const r = Math.max(0, Math.min(255, Number(codes[i + 2]) || 0));
308
- const g = Math.max(0, Math.min(255, Number(codes[i + 3]) || 0));
309
- const b = Math.max(0, Math.min(255, Number(codes[i + 4]) || 0));
310
- const color = `rgb(${r}, ${g}, ${b})`;
311
- if (code === 38) {
312
- state.fgClass = null;
313
- state.fgColor = color;
314
- } else {
315
- state.bgClass = null;
316
- state.bgColor = color;
317
- }
318
- i += 4;
319
- } else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
320
- state.fgClass = ANSI_CODE_MAP[code] || null;
321
- state.fgColor = null;
322
- } else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
323
- state.bgClass = ANSI_CODE_MAP[code] || null;
324
- state.bgColor = null;
325
- }
326
- }
327
- }
328
-
329
- const remaining = cleaned.slice(lastIdx);
330
- if (remaining) result += renderChunk(remaining);
331
- return result;
332
- }
333
-
334
- const parseAnsiToHtml = ansiToHtml;
335
-
336
- const MAX_SCROLLBACK = 2000;
337
- const VALID_LOG_TYPES = new Set(['stdout', 'stderr', 'system', 'info', 'warn', 'error', 'success']);
338
-
339
- function sanitizeLogType(type) {
340
- const t = String(type || 'stdout').trim();
341
- return VALID_LOG_TYPES.has(t) ? t : 'stdout';
342
- }
343
-
344
- class PTYTerminalEngine {
345
- constructor(container, options = {}) {
346
- if (
347
- container &&
348
- typeof container === 'object' &&
349
- typeof container.querySelector !== 'function' &&
350
- typeof container.appendChild !== 'function' &&
351
- arguments.length === 1
352
- ) {
353
- options = container;
354
- container = options.container || null;
355
- }
356
- this.container = container || null;
357
- this.options = options || {};
358
- this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
359
- ? this.options.maxScrollback
360
- : MAX_SCROLLBACK;
361
- this.maxHistory = typeof this.options.maxHistory === 'number' && this.options.maxHistory > 0
362
- ? this.options.maxHistory
363
- : 1000;
364
- this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
365
- this.cwd = this.options.cwd || '/workspace';
366
- this.replMode = Boolean(this.options.replMode);
367
- this.promptOverride = this.options.prompt || null;
368
- this.history = Array.isArray(this.options.history) ? this.options.history : [];
369
- this.historyIdx = -1;
370
- this.savedBuffer = '';
371
- this.buffer = '';
372
- this.cursor = 0;
373
- this.searchMode = false;
374
- this.searchQuery = '';
375
- this.searchMatchIdx = -1;
376
- this._readLineQueue = [];
377
- this.isBusy = false;
378
- this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
379
- this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
380
- this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
381
- this.onInterrupt = typeof this.options.onInterrupt === 'function' ? this.options.onInterrupt : null;
382
-
383
- // Stream & active line buffering state
384
- this._activeLineCommitted = true;
385
- this._cursorCol = 0;
386
- this._pendingEscape = '';
387
- this._targetLineIdx = -1;
388
- this._needsRewrite = false;
389
- this._activeLineEl = null;
390
-
391
- this._mounted = false;
392
- this._listeners = [];
393
-
394
- if (this.container) {
395
- this.mount(this.container);
396
- }
397
- }
398
-
399
- getPrompt() {
400
- if (this.promptOverride) return this.promptOverride;
401
- if (this.replMode) return '> ';
402
- const cwd = this.cwd || '/workspace';
403
- return `codelab:${cwd}$ `;
404
- }
405
-
406
- setPrompt(p) {
407
- this.promptOverride = p;
408
- this.updateActiveLine();
409
- }
410
-
411
- setCwd(cwd) {
412
- this.cwd = cwd;
413
- this.updateActiveLine();
414
- }
415
-
416
- setReplMode(enabled) {
417
- this.replMode = Boolean(enabled);
418
- this.updateActiveLine();
419
- }
420
-
421
- writeStreamChunk(data, type = 'stdout') {
422
- let str = String(data != null ? data : '');
423
- if (!str) return;
424
-
425
- if (this._pendingEscape) {
426
- str = this._pendingEscape + str;
427
- this._pendingEscape = '';
428
- }
429
-
430
- let modified = false;
431
- let i = 0;
432
-
433
- while (i < str.length) {
434
- if (str[i] === '\x1b') {
435
- const rest = str.slice(i);
436
- if (rest === '\x1b' || /^\x1b\[[0-9;?]*$/.test(rest) || /^\x1b\][^\x07]*(?:\x1b)?$/.test(rest)) {
437
- this._pendingEscape = rest;
438
- break;
439
- }
440
- if (rest.startsWith('\x1bc')) {
441
- i += 2;
442
- this.clear();
443
- modified = false;
444
- continue;
445
- }
446
- const oscMatch = /^\x1b\]([^\x07\x1b]*)(?:\x07|\x1b\\)/.exec(rest);
447
- if (oscMatch) {
448
- i += oscMatch[0].length;
449
- continue;
450
- }
451
-
452
- const csiMatch = /^\x1b\[([0-9;?]*)([A-Za-z])/.exec(rest);
453
- if (csiMatch) {
454
- const params = csiMatch[1];
455
- const cmd = csiMatch[2];
456
- const seq = csiMatch[0];
457
- i += seq.length;
458
-
459
- if (cmd === 'K') {
460
- const cur = this._getActiveLine(type);
461
- if (params === '2') {
462
- cur.text = '';
463
- this._cursorCol = 0;
464
- this._needsRewrite = false;
465
- } else {
466
- cur.text = cur.text.slice(0, this._cursorCol);
467
- this._needsRewrite = false;
468
- }
469
- modified = true;
470
- } else if (cmd === 'A') {
471
- const count = parseInt(params, 10) || 1;
472
- if (this.logs.length > 0) {
473
- const baseIdx = this._activeLineCommitted ? this.logs.length : this.logs.length - 1;
474
- this._targetLineIdx = Math.max(0, baseIdx - count);
475
- this._activeLineCommitted = false;
476
- this._cursorCol = 0;
477
- this._needsRewrite = false;
478
- const targetLine = this.logs[this._targetLineIdx];
479
- if (targetLine) targetLine.text = '';
480
- this._activeLineEl = null;
481
- }
482
- } else if (cmd === 'G' || cmd === 'H' || cmd === 'f') {
483
- this._cursorCol = 0;
484
- if (cmd === 'G') this._needsRewrite = true;
485
- } else if (cmd === 'J' && (params === '2' || params === '3')) {
486
- this.clear();
487
- modified = false;
488
- } else if (cmd === 'm') {
489
- const cur = this._getActiveLine(type);
490
- cur.text += seq;
491
- modified = true;
492
- }
493
- continue;
494
- }
495
- }
496
-
497
- const ch = str[i];
498
- if (ch === '\r') {
499
- this._cursorCol = 0;
500
- this._needsRewrite = true;
501
- i++;
502
- } else if (ch === '\n') {
503
- const cur = this._getActiveLine(type);
504
- cur.text += '\n';
505
- this._activeLineCommitted = true;
506
- this._cursorCol = 0;
507
- this._targetLineIdx = -1;
508
- this._needsRewrite = false;
509
- this._activeLineEl = null;
510
- modified = true;
511
- i++;
512
- } else {
513
- const cur = this._getActiveLine(type);
514
- if (this._needsRewrite && this._cursorCol === 0 && cur.text.length > 0 && !cur.text.endsWith('\n')) {
515
- cur.text = ch;
516
- this._needsRewrite = false;
517
- } else {
518
- cur.text += ch;
519
- }
520
- this._cursorCol++;
521
- modified = true;
522
- i++;
523
- }
524
- }
525
-
526
- if (modified) {
527
- this._updateActiveDomLine();
528
- }
529
- this._scrollToBottom();
530
- }
531
-
532
- write(data, type = 'stdout') {
533
- this.writeStreamChunk(data, type);
534
- }
535
-
536
- writeln(data, type = 'stdout') {
537
- this.writeStreamChunk(String(data) + '\n', type);
538
- }
539
-
540
- isCommandRunning() {
541
- return Boolean(this.isBusy && (!this._readLineQueue || this._readLineQueue.length === 0));
542
- }
543
-
544
- _pushLog(entry) {
545
- const normalized = {
546
- type: sanitizeLogType(entry && entry.type),
547
- text: String(entry && entry.text != null ? entry.text : '')
548
- };
549
- this.logs.push(normalized);
550
- if (this.logs.length > this.maxScrollback) {
551
- const excess = this.logs.length - this.maxScrollback;
552
- this.logs.splice(0, excess);
553
- if (this._targetLineIdx >= 0) {
554
- this._targetLineIdx = Math.max(0, this._targetLineIdx - excess);
555
- }
556
- if (this.container && typeof this.container.querySelector === 'function') {
557
- const logEl = this.container.querySelector('#cl-terminal-log');
558
- if (logEl && logEl.children && logEl.children.length > this.maxScrollback) {
559
- while (logEl.children.length > this.maxScrollback && typeof logEl.removeChild === 'function' && logEl.firstChild) {
560
- logEl.removeChild(logEl.firstChild);
561
- }
562
- }
563
- }
564
- }
565
- return normalized;
566
- }
567
-
568
- _getActiveLine(type) {
569
- if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
570
- return this.logs[this._targetLineIdx];
571
- }
572
- if (this._activeLineCommitted || this.logs.length === 0) {
573
- const newLine = this._pushLog({ text: '', type });
574
- this._activeLineCommitted = false;
575
- this._cursorCol = 0;
576
- this._targetLineIdx = this.logs.length - 1;
577
- this._needsRewrite = false;
578
- this._appendDomLine(newLine);
579
- return newLine;
580
- }
581
- this._targetLineIdx = this.logs.length - 1;
582
- return this.logs[this.logs.length - 1];
583
- }
584
-
585
- _appendDomLine(line) {
586
- if (!this.container || typeof document === 'undefined') return;
587
- const logEl = this.container.querySelector('#cl-terminal-log');
588
- if (!logEl) return;
589
- const lineEl = document.createElement('div');
590
- lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
591
- lineEl.innerHTML = ansiToHtml(line.text);
592
- logEl.appendChild(lineEl);
593
- this._activeLineEl = lineEl;
594
- }
595
-
596
- _updateActiveDomLine() {
597
- if (!this.container || typeof document === 'undefined') return;
598
- const line = this._getActiveLineSync();
599
- if (!line) return;
600
- let lineEl = this._activeLineEl;
601
- if (!lineEl || !lineEl.parentNode) {
602
- const logEl = this.container.querySelector('#cl-terminal-log');
603
- if (logEl) {
604
- if (this._targetLineIdx >= 0 && this._targetLineIdx < logEl.children.length) {
605
- lineEl = logEl.children[this._targetLineIdx];
606
- } else {
607
- lineEl = logEl.children[logEl.children.length - 1];
608
- }
609
- this._activeLineEl = lineEl;
610
- }
611
- }
612
- if (lineEl) {
613
- lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
614
- lineEl.innerHTML = ansiToHtml(line.text);
615
- }
616
- }
617
-
618
- _getActiveLineSync() {
619
- if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
620
- return this.logs[this._targetLineIdx];
621
- }
622
- return this.logs[this.logs.length - 1] || null;
623
- }
624
-
625
- _scrollToBottom() {
626
- if (!this.container) return;
627
- const surface = this.container.querySelector('#cl-terminal-surface') || this.container;
628
- if (surface && typeof surface.scrollTop === 'number' && typeof surface.scrollHeight === 'number') {
629
- surface.scrollTop = surface.scrollHeight;
630
- }
631
- }
632
-
633
- clear() {
634
- this.logs.length = 0;
635
- this._activeLineCommitted = true;
636
- this._cursorCol = 0;
637
- this._targetLineIdx = -1;
638
- this._needsRewrite = false;
639
- this._activeLineEl = null;
640
- if (this.container && typeof this.container.querySelector === 'function') {
641
- const logEl = this.container.querySelector('#cl-terminal-log');
642
- if (logEl) {
643
- logEl.innerHTML = '';
644
- }
645
- }
646
- }
647
-
648
- getHistory() {
649
- return [...this.history];
650
- }
651
-
652
- _activateNextReadLine() {
653
- if (!this._readLineQueue || this._readLineQueue.length === 0) return;
654
- const head = this._readLineQueue[0];
655
- if (head && typeof head === 'object' && !head._activated) {
656
- head._activated = true;
657
- head.prevPrompt = this.promptOverride;
658
- if (head.promptText) {
659
- this.promptOverride = head.promptText;
660
- }
661
- }
662
- }
663
-
664
- _drainReadLineQueue(result = null) {
665
- if (!Array.isArray(this._readLineQueue) || this._readLineQueue.length === 0) return;
666
- const queued = this._readLineQueue.splice(0, this._readLineQueue.length);
667
- let restoredPrompt = undefined;
668
- for (const entry of queued) {
669
- if (entry && typeof entry === 'object' && entry._activated && restoredPrompt === undefined) {
670
- restoredPrompt = entry.prevPrompt;
671
- }
672
- if (entry && typeof entry.cleanup === 'function') {
673
- entry.cleanup();
674
- }
675
- }
676
- if (restoredPrompt !== undefined) {
677
- this.promptOverride = restoredPrompt;
678
- }
679
- for (const entry of queued) {
680
- if (typeof entry === 'function') {
681
- try { entry(result); } catch (err) { _terminalLogger.debug('readLine callback threw during drain.', err); }
682
- } else if (entry && typeof entry.resolve === 'function') {
683
- try { entry.resolve(result); } catch (err) { _terminalLogger.debug('readLine resolve threw during drain.', err); }
684
- }
685
- }
686
- }
687
-
688
- readLine(promptText = '', options = {}) {
689
- if (options && options.signal && options.signal.aborted) {
690
- return Promise.resolve(null);
691
- }
692
- return new Promise((resolve) => {
693
- const item = {
694
- promptText: String(promptText || ''),
695
- prevPrompt: null,
696
- _activated: false,
697
- cleanup: null,
698
- resolve
699
- };
700
- if (options && options.signal && typeof options.signal.addEventListener === 'function') {
701
- const onAbort = () => {
702
- const idx = this._readLineQueue.indexOf(item);
703
- if (idx !== -1) {
704
- this._readLineQueue.splice(idx, 1);
705
- if (item._activated) {
706
- this.promptOverride = item.prevPrompt;
707
- this._activateNextReadLine();
708
- }
709
- this.updateActiveLine();
710
- resolve(null);
711
- }
712
- };
713
- options.signal.addEventListener('abort', onAbort, { once: true });
714
- item.cleanup = () => {
715
- try { options.signal.removeEventListener('abort', onAbort); } catch (err) { _terminalLogger.debug('readLine abort listener cleanup failed.', err); }
716
- };
717
- }
718
- this._readLineQueue.push(item);
719
- this._activateNextReadLine();
720
- this.updateActiveLine();
721
- });
722
- }
723
-
724
- focus() {
725
- if (!this.container || typeof this.container.querySelector !== 'function') return;
726
- const input = this.container.querySelector('#cl-repl-input');
727
- if (input && typeof input.focus === 'function') {
728
- try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
729
- }
730
- }
731
-
732
- mount(container) {
733
- if (typeof container === 'string' && typeof document !== 'undefined') {
734
- container = document.querySelector(container);
735
- }
736
- this.container = container || null;
737
- if (!this.container || typeof this.container.querySelector !== 'function') {
738
- this._mounted = false;
739
- return;
740
- }
741
- this._mounted = true;
742
- this.render();
743
- }
744
-
745
- _cleanupListeners() {
746
- if (!Array.isArray(this._listeners)) {
747
- this._listeners = [];
748
- return;
749
- }
750
- for (const entry of this._listeners) {
751
- if (typeof entry === 'function') {
752
- try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
753
- } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
754
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
755
- }
756
- }
757
- this._listeners = [];
758
- }
759
-
760
- destroy() {
761
- this._drainReadLineQueue(null);
762
- this._cleanupListeners();
763
- this._mounted = false;
764
- }
765
-
766
- _addListener(target, type, handler) {
767
- if (target && typeof target.addEventListener === 'function') {
768
- target.addEventListener(type, handler);
769
- this._listeners.push({ target, type, handler });
770
- }
771
- }
772
-
773
- _bindEvents() {
774
- this._cleanupListeners();
775
- if (!this.container || typeof this.container.querySelector !== 'function') return;
776
- const termSurface = this.container.querySelector('#cl-terminal-surface') || this.container;
777
- const input = this.container.querySelector('#cl-repl-input');
778
- const form = this.container.querySelector('#cl-repl-form');
779
-
780
- if (termSurface) {
781
- this._addListener(termSurface, 'click', (e) => {
782
- if (e && e.target === input) return;
783
- const hasSelection = typeof window !== 'undefined' && window.getSelection && String(window.getSelection());
784
- if (!hasSelection) this.focus();
785
- });
786
- }
787
-
788
- if (input) {
789
- this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
790
- this._addListener(input, 'paste', (e) => {
791
- const clip = e && e.clipboardData && typeof e.clipboardData.getData === 'function'
792
- ? e.clipboardData.getData('text/plain')
793
- : '';
794
- if (!clip) return;
795
- if (e.preventDefault) e.preventDefault();
796
- this.pasteText(clip);
797
- });
798
- this._addListener(input, 'input', () => {
799
- if (this.isCommandRunning()) {
800
- input.value = '';
801
- return;
802
- }
803
- if (input.value !== this.buffer) {
804
- this.buffer = input.value;
805
- this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
806
- this.updateActiveLine();
807
- }
808
- });
809
- }
810
-
811
- if (form) {
812
- this._addListener(form, 'submit', (e) => {
813
- if (e && typeof e.preventDefault === 'function') e.preventDefault();
814
- this.submitLine();
815
- });
816
- }
817
- }
818
-
819
- _findReverseSearchMatch(query, startIdx) {
820
- if (!query || !this.history.length) return -1;
821
- const from = typeof startIdx === 'number' ? Math.min(startIdx, this.history.length - 1) : this.history.length - 1;
822
- for (let i = from; i >= 0; i--) {
823
- if (this.history[i] && this.history[i].includes(query)) {
824
- return i;
825
- }
826
- }
827
- return -1;
828
- }
829
-
830
- handleKeyDown(e) {
831
- if (!e) return;
832
- if (this.onKey) {
833
- try {
834
- const res = this.onKey(e);
835
- if (res === false) return;
836
- } catch (err) {
837
- _terminalLogger.warn('Terminal onKey callback threw.', err);
838
- }
839
- }
840
-
841
- const key = e.key;
842
- const isCtrlOnly = Boolean(e.ctrlKey && !e.metaKey);
843
- const isMetaOnly = Boolean(e.metaKey && !e.ctrlKey);
844
- const isCtrl = Boolean(e.ctrlKey || e.metaKey);
845
-
846
- // macOS Cmd+K or Ctrl+L clears terminal
847
- if ((isCtrl && (key === 'l' || key === 'L')) || (isMetaOnly && (key === 'k' || key === 'K'))) {
848
- if (e.preventDefault) e.preventDefault();
849
- this.clear();
850
- return;
851
- }
852
-
853
- // Allow native clipboard copy on Cmd+C (macOS) or Ctrl+Shift+C, or Ctrl+C when idle with text selected
854
- if (isMetaOnly && (key === 'c' || key === 'C')) {
855
- return;
856
- }
857
- if (isMetaOnly && (key === 'v' || key === 'V')) {
858
- return;
859
- }
860
- if (isCtrlOnly && (key === 'c' || key === 'C')) {
861
- if (e.shiftKey) return;
862
- const hasSelection =
863
- !this.isBusy &&
864
- typeof window !== 'undefined' &&
865
- typeof window.getSelection === 'function' &&
866
- String(window.getSelection()).length > 0;
867
- if (hasSelection) return;
868
- if (e.preventDefault) e.preventDefault();
869
- const wasBusy = this.isBusy || (this._readLineQueue && this._readLineQueue.length > 0);
870
- this.isBusy = false;
871
- const sigLog = this._pushLog({ type: 'system', text: wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C` });
872
- this._appendDomLine(sigLog);
873
- this._activeLineCommitted = true;
874
- this._activeLineEl = null;
875
- this.buffer = '';
876
- this.cursor = 0;
877
- this.historyIdx = -1;
878
- this._drainReadLineQueue(null);
879
- if (this.replMode) {
880
- this.replMode = false;
881
- }
882
- if (this.onInterrupt) {
883
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
884
- }
885
- this.updateActiveLine();
886
- this._scrollToBottom();
887
- return;
888
- }
889
-
890
- if (this.isCommandRunning()) {
891
- if (e.preventDefault) e.preventDefault();
892
- return;
893
- }
894
-
895
- if (isCtrl && (key === 'r' || key === 'R')) {
896
- if (e.preventDefault) e.preventDefault();
897
- if (!this.searchMode) {
898
- this.searchMode = true;
899
- this.searchQuery = '';
900
- this.searchMatchIdx = -1;
901
- } else if (this.searchQuery) {
902
- const nextStart = this.searchMatchIdx > 0 ? this.searchMatchIdx - 1 : this.history.length - 1;
903
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, nextStart);
904
- if (matchIdx !== -1) {
905
- this.searchMatchIdx = matchIdx;
906
- this.buffer = this.history[matchIdx];
907
- this.cursor = this.buffer.length;
908
- }
909
- }
910
- this.updateActiveLine();
911
- return;
912
- }
913
-
914
- if (this.searchMode) {
915
- if (key === 'Escape' || (isCtrl && (key === 'g' || key === 'G'))) {
916
- if (e.preventDefault) e.preventDefault();
917
- this.searchMode = false;
918
- this.searchQuery = '';
919
- this.searchMatchIdx = -1;
920
- this.updateActiveLine();
921
- return;
922
- }
923
- if (key === 'Backspace') {
924
- if (e.preventDefault) e.preventDefault();
925
- this.searchQuery = this.searchQuery.slice(0, -1);
926
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
927
- this.searchMatchIdx = matchIdx;
928
- if (matchIdx !== -1) {
929
- this.buffer = this.history[matchIdx];
930
- this.cursor = this.buffer.length;
931
- }
932
- this.updateActiveLine();
933
- return;
934
- }
935
- if (key === 'Enter') {
936
- if (e.preventDefault) e.preventDefault();
937
- this.searchMode = false;
938
- this.searchQuery = '';
939
- this.searchMatchIdx = -1;
940
- this.submitLine();
941
- return;
942
- }
943
- if (key && key.length === 1 && !isCtrl && !e.altKey) {
944
- if (e.preventDefault) e.preventDefault();
945
- this.searchQuery += key;
946
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
947
- this.searchMatchIdx = matchIdx;
948
- if (matchIdx !== -1) {
949
- this.buffer = this.history[matchIdx];
950
- this.cursor = this.buffer.length;
951
- }
952
- this.updateActiveLine();
953
- return;
954
- }
955
- this.searchMode = false;
956
- this.searchQuery = '';
957
- this.searchMatchIdx = -1;
958
- }
959
-
960
- // Word navigation: Alt+B / Alt+ArrowLeft / Ctrl+ArrowLeft & Alt+F / Alt+ArrowRight / Ctrl+ArrowRight
961
- if ((e.altKey && (key === 'b' || key === 'B' || key === 'ArrowLeft')) || (isCtrlOnly && key === 'ArrowLeft')) {
962
- if (e.preventDefault) e.preventDefault();
963
- let pos = this.cursor;
964
- while (pos > 0 && /\s/.test(this.buffer[pos - 1])) pos--;
965
- while (pos > 0 && !/\s/.test(this.buffer[pos - 1])) pos--;
966
- this.cursor = pos;
967
- this.updateActiveLine();
968
- return;
969
- }
970
-
971
- if ((e.altKey && (key === 'f' || key === 'F' || key === 'ArrowRight')) || (isCtrlOnly && key === 'ArrowRight')) {
972
- if (e.preventDefault) e.preventDefault();
973
- let pos = this.cursor;
974
- while (pos < this.buffer.length && /\s/.test(this.buffer[pos])) pos++;
975
- while (pos < this.buffer.length && !/\s/.test(this.buffer[pos])) pos++;
976
- this.cursor = pos;
977
- this.updateActiveLine();
978
- return;
979
- }
980
-
981
- // Word delete backward: Ctrl+W or Alt+Backspace
982
- if ((isCtrlOnly && (key === 'w' || key === 'W')) || (e.altKey && key === 'Backspace')) {
983
- if (e.preventDefault) e.preventDefault();
984
- let pos = this.cursor;
985
- while (pos > 0 && /\s/.test(this.buffer[pos - 1])) pos--;
986
- while (pos > 0 && !/\s/.test(this.buffer[pos - 1])) pos--;
987
- this.buffer = this.buffer.slice(0, pos) + this.buffer.slice(this.cursor);
988
- this.cursor = pos;
989
- this.updateActiveLine();
990
- return;
991
- }
992
-
993
- if (key === 'ArrowLeft') {
994
- if (e.preventDefault) e.preventDefault();
995
- if (this.cursor > 0) {
996
- this.cursor--;
997
- this.updateActiveLine();
998
- }
999
- return;
1000
- }
1001
-
1002
- if (key === 'ArrowRight') {
1003
- if (e.preventDefault) e.preventDefault();
1004
- if (this.cursor < this.buffer.length) {
1005
- this.cursor++;
1006
- this.updateActiveLine();
1007
- }
1008
- return;
1009
- }
1010
-
1011
- if (key === 'Home' || (e.ctrlKey && !e.metaKey && (key === 'a' || key === 'A'))) {
1012
- if (e.preventDefault) e.preventDefault();
1013
- this.cursor = 0;
1014
- this.updateActiveLine();
1015
- return;
1016
- }
1017
-
1018
- if (key === 'End' || (isCtrl && (key === 'e' || key === 'E'))) {
1019
- if (e.preventDefault) e.preventDefault();
1020
- this.cursor = this.buffer.length;
1021
- this.updateActiveLine();
1022
- return;
1023
- }
1024
-
1025
- if (isCtrl && (key === 'u' || key === 'U')) {
1026
- if (e.preventDefault) e.preventDefault();
1027
- this.buffer = this.buffer.slice(this.cursor);
1028
- this.cursor = 0;
1029
- this.updateActiveLine();
1030
- return;
1031
- }
1032
-
1033
- if (isCtrl && (key === 'k' || key === 'K')) {
1034
- if (e.preventDefault) e.preventDefault();
1035
- this.buffer = this.buffer.slice(0, this.cursor);
1036
- this.updateActiveLine();
1037
- return;
1038
- }
1039
-
1040
- if (key === 'Backspace') {
1041
- if (e.preventDefault) e.preventDefault();
1042
- if (this.cursor > 0) {
1043
- this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
1044
- this.cursor--;
1045
- this.updateActiveLine();
1046
- }
1047
- return;
1048
- }
1049
-
1050
- if (key === 'Delete') {
1051
- if (e.preventDefault) e.preventDefault();
1052
- if (this.cursor < this.buffer.length) {
1053
- this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
1054
- this.updateActiveLine();
1055
- }
1056
- return;
1057
- }
1058
-
1059
- if (isCtrl && (key === 'd' || key === 'D')) {
1060
- if (this.buffer === '') {
1061
- if (e.preventDefault) e.preventDefault();
1062
- if (this._readLineQueue && this._readLineQueue.length > 0) {
1063
- this._drainReadLineQueue(null);
1064
- this.updateActiveLine();
1065
- return;
1066
- }
1067
- if (this.replMode) {
1068
- this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
1069
- this.replMode = false;
1070
- this.render();
1071
- return;
1072
- }
1073
- }
1074
- }
1075
-
1076
- if (key === 'ArrowUp') {
1077
- if (e.preventDefault) e.preventDefault();
1078
- if (!this.history.length) return;
1079
- if (this.historyIdx === -1) {
1080
- this.savedBuffer = this.buffer;
1081
- this.historyIdx = this.history.length - 1;
1082
- } else if (this.historyIdx > 0) {
1083
- this.historyIdx--;
1084
- }
1085
- this.buffer = this.history[this.historyIdx] || '';
1086
- this.cursor = this.buffer.length;
1087
- this.updateActiveLine();
1088
- return;
1089
- }
1090
-
1091
- if (key === 'ArrowDown') {
1092
- if (e.preventDefault) e.preventDefault();
1093
- if (this.historyIdx !== -1) {
1094
- if (this.historyIdx < this.history.length - 1) {
1095
- this.historyIdx++;
1096
- this.buffer = this.history[this.historyIdx] || '';
1097
- } else {
1098
- this.historyIdx = -1;
1099
- this.buffer = this.savedBuffer || '';
1100
- }
1101
- this.cursor = this.buffer.length;
1102
- this.updateActiveLine();
1103
- }
1104
- return;
1105
- }
1106
-
1107
- if (key === 'Tab') {
1108
- if (e.preventDefault) e.preventDefault();
1109
- this.autoComplete();
1110
- return;
1111
- }
1112
-
1113
- if (key === 'Enter') {
1114
- if (e.preventDefault) e.preventDefault();
1115
- this.submitLine();
1116
- return;
1117
- }
1118
-
1119
- // Printable character
1120
- if (key && key.length === 1 && !isCtrl && !e.altKey) {
1121
- if (e.preventDefault) e.preventDefault();
1122
- this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
1123
- this.cursor++;
1124
- this.updateActiveLine();
1125
- }
1126
- }
1127
-
1128
- async pasteText(rawText) {
1129
- if (!rawText || this.isCommandRunning()) return;
1130
- const normalized = String(rawText).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
1131
- if (!normalized.includes('\n')) {
1132
- this.buffer = this.buffer.slice(0, this.cursor) + normalized + this.buffer.slice(this.cursor);
1133
- this.cursor += normalized.length;
1134
- this.updateActiveLine();
1135
- return;
1136
- }
1137
- const parts = normalized.split('\n');
1138
- for (let i = 0; i < parts.length; i++) {
1139
- const seg = parts[i];
1140
- if (i < parts.length - 1) {
1141
- this.buffer = this.buffer.slice(0, this.cursor) + seg + this.buffer.slice(this.cursor);
1142
- this.cursor = this.buffer.length;
1143
- this.submitLine();
1144
- while (this._mounted && this.isCommandRunning()) {
1145
- await new Promise((r) => setTimeout(r, 10));
1146
- }
1147
- if (!this._mounted) return;
1148
- } else if (seg.length > 0) {
1149
- this.buffer = seg;
1150
- this.cursor = seg.length;
1151
- this.updateActiveLine();
1152
- }
1153
- }
1154
- }
1155
-
1156
- autoComplete() {
1157
- if (!this.getCompletions) return;
1158
- const res = this.getCompletions(this.buffer, this.cursor);
1159
- if (!res || !Array.isArray(res.matches) || res.matches.length === 0) return;
1160
-
1161
- const matches = res.matches;
1162
- if (matches.length === 1) {
1163
- const match = matches[0];
1164
- const isDir = match.endsWith('/');
1165
- const appendChar = isDir ? '' : ' ';
1166
- const before = this.buffer.slice(0, res.tokenStart);
1167
- const after = this.buffer.slice(this.cursor);
1168
- this.buffer = before + match + appendChar + after;
1169
- this.cursor = before.length + match.length + appendChar.length;
1170
- this.updateActiveLine();
1171
- } else {
1172
- // Find longest common prefix
1173
- let lcp = matches[0];
1174
- for (let i = 1; i < matches.length; i++) {
1175
- let j = 0;
1176
- while (j < lcp.length && j < matches[i].length && lcp[j] === matches[i][j]) {
1177
- j++;
1178
- }
1179
- lcp = lcp.slice(0, j);
1180
- }
1181
-
1182
- if (lcp.length > res.token.length) {
1183
- const before = this.buffer.slice(0, res.tokenStart);
1184
- const after = this.buffer.slice(this.cursor);
1185
- this.buffer = before + lcp + after;
1186
- this.cursor = before.length + lcp.length;
1187
- }
1188
-
1189
- // Print candidate matches
1190
- this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
1191
- this._pushLog({ type: 'stdout', text: matches.join(' ') });
1192
- this.render();
1193
- }
1194
- }
1195
-
1196
- submitLine() {
1197
- if (this._readLineQueue && this._readLineQueue.length > 0) {
1198
- const line = this.buffer;
1199
- this.buffer = '';
1200
- this.cursor = 0;
1201
- this.historyIdx = -1;
1202
- this.searchMode = false;
1203
- this.searchQuery = '';
1204
- this.searchMatchIdx = -1;
1205
-
1206
- const entry = this._readLineQueue.shift();
1207
- if (entry && typeof entry.cleanup === 'function') {
1208
- entry.cleanup();
1209
- }
1210
- if (typeof entry === 'function') {
1211
- this.updateActiveLine();
1212
- entry(line);
1213
- } else if (entry && typeof entry.resolve === 'function') {
1214
- this.promptOverride = entry.prevPrompt;
1215
- this._activateNextReadLine();
1216
- this.updateActiveLine();
1217
- entry.resolve(line);
1218
- }
1219
- return;
1220
- }
1221
-
1222
- if (this.isBusy) {
1223
- return;
1224
- }
1225
-
1226
- const line = this.buffer;
1227
- const promptSnap = this.getPrompt();
1228
- this.buffer = '';
1229
- this.cursor = 0;
1230
- this.historyIdx = -1;
1231
- this.searchMode = false;
1232
- this.searchQuery = '';
1233
- this.searchMatchIdx = -1;
1234
-
1235
- const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
1236
- this._activeLineCommitted = true;
1237
- this._cursorCol = 0;
1238
- this._targetLineIdx = -1;
1239
- this._needsRewrite = false;
1240
- this._appendDomLine(echoed);
1241
- this._activeLineEl = null;
1242
-
1243
- if (line.trim()) {
1244
- if (this.history[this.history.length - 1] !== line.trim()) {
1245
- this.history.push(line.trim());
1246
- const maxHist = typeof this.maxHistory === 'number' && this.maxHistory > 0 ? this.maxHistory : 1000;
1247
- if (this.history.length > maxHist) {
1248
- this.history.splice(0, this.history.length - maxHist);
1249
- }
1250
- }
1251
- }
1252
-
1253
- if (!this.onCommand) {
1254
- this.updateActiveLine();
1255
- return;
1256
- }
1257
-
1258
- this.isBusy = true;
1259
- this.updateActiveLine();
1260
-
1261
- let cmdResult;
1262
- try {
1263
- cmdResult = this.onCommand(line);
1264
- } catch (err) {
1265
- this.isBusy = false;
1266
- this.updateActiveLine();
1267
- throw err;
1268
- }
1269
-
1270
- if (cmdResult && typeof cmdResult.then === 'function') {
1271
- Promise.resolve(cmdResult)
1272
- .catch((err) => {
1273
- _terminalLogger.debug('Terminal onCommand promise rejected.', err);
1274
- })
1275
- .finally(() => {
1276
- this.isBusy = false;
1277
- this.updateActiveLine();
1278
- });
1279
- } else {
1280
- this.isBusy = false;
1281
- this.updateActiveLine();
1282
- }
1283
- }
1284
-
1285
- updateActiveLine() {
1286
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1287
- const input = this.container.querySelector('#cl-repl-input');
1288
- if (input && input.value !== this.buffer) {
1289
- input.value = this.buffer;
1290
- }
1291
- const lineEl = this.container.querySelector('#cl-pty-active-line');
1292
- if (!lineEl) return;
1293
-
1294
- if (this.isCommandRunning()) {
1295
- if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
1296
- if (lineEl.style) lineEl.style.display = 'none';
1297
- lineEl.innerHTML = `<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>`;
1298
- return;
1299
- }
1300
-
1301
- if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
1302
- if (lineEl.style) lineEl.style.display = '';
1303
-
1304
- const prompt = this.searchMode
1305
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1306
- : this.getPrompt();
1307
- const before = this.buffer.slice(0, this.cursor);
1308
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1309
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1310
-
1311
- lineEl.innerHTML = `<span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="codelab-pty__cursor blink">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>`;
1312
- }
1313
-
1314
- render() {
1315
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1316
- const prevInput = this.container.querySelector('#cl-repl-input');
1317
- const hadFocus = Boolean(
1318
- prevInput &&
1319
- typeof document !== 'undefined' &&
1320
- document.activeElement === prevInput
1321
- );
1322
-
1323
- const logsHtml = this.logs
1324
- .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
1325
- .join('');
1326
-
1327
- const busy = this.isCommandRunning();
1328
- const prompt = busy
1329
- ? ''
1330
- : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
1331
- const before = busy ? '' : this.buffer.slice(0, this.cursor);
1332
- const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
1333
- const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
1334
- const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
1335
- const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
1336
-
1337
- this.container.innerHTML = `
1338
- <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1339
- <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1340
- <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
1341
- <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="${cursorClass}">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
1342
- </div>
1343
- <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1344
- <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
1345
- </form>
1346
- </div>
1347
- `;
1348
-
1349
- this._scrollToBottom();
1350
-
1351
- this._bindEvents();
1352
-
1353
- if (hadFocus) {
1354
- const nextInput = this.container.querySelector('#cl-repl-input');
1355
- if (nextInput && typeof nextInput.focus === 'function') {
1356
- try {
1357
- nextInput.focus();
1358
- if (typeof nextInput.setSelectionRange === 'function') {
1359
- nextInput.setSelectionRange(this.cursor, this.cursor);
1360
- }
1361
- } catch (err) {
1362
- _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
1363
- }
1364
- }
1365
- }
1366
- }
1367
- }
1368
-
1369
- function createTerminal(container, options = {}) {
1370
- return new PTYTerminalEngine(container, options);
1371
- }
1372
-
1373
- const createPTYTerminalEngine = createTerminal;
1374
-
1375
- return {
1376
- PTYTerminalEngine,
1377
- createPTYTerminalEngine,
1378
- createTerminal,
1379
- ansiToHtml,
1380
- parseAnsiToHtml,
1381
- escapeHtml,
1382
- ANSI_CODE_MAP,
1383
- ansi256ToColor,
1384
- resolveAnsiControlCodes
1385
- };
1386
- });
1387
-
1388
- // ── TypeScript module surface (stripped from browser bundles) ──────────────
1389
- const _hostTerminal: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabTerminal : undefined)
1390
- || (typeof module !== 'undefined' && module.exports ? module.exports : {});
1391
-
1392
- export const ANSI_CODE_MAP: Record<number, string> = _hostTerminal.ANSI_CODE_MAP;
1393
- export const ansi256ToColor: (n: number | string) => string | null = _hostTerminal.ansi256ToColor;
1394
- export const escapeHtml: (str: any) => string = _hostTerminal.escapeHtml;
1395
- export const resolveAnsiControlCodes: (raw: any) => string = _hostTerminal.resolveAnsiControlCodes;
1396
- export const ansiToHtml: (str: any) => string = _hostTerminal.ansiToHtml;
1397
- export const parseAnsiToHtml: (str: any) => string = _hostTerminal.parseAnsiToHtml;
1398
- export const PTYTerminalEngine: any = _hostTerminal.PTYTerminalEngine;
1399
- export const createTerminal: (container?: any, options?: any) => any = _hostTerminal.createTerminal;
1400
- export const createPTYTerminalEngine: (container?: any, options?: any) => any = _hostTerminal.createPTYTerminalEngine;
1401
-
1402
- export default _hostTerminal;