@innovatorved/code-lab 0.7.0 → 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 (159) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +6 -6
  4. package/dist/code-lab-sql.esm.js +19 -19
  5. package/dist/code-lab-sql.umd.js +20 -20
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +1183 -1909
  9. package/dist/code-lab.js +1182 -1906
  10. package/dist/extensions/cpp.esm.js +132 -8760
  11. package/dist/extensions/cpp.js +124 -8770
  12. package/dist/extensions/guided-lab.esm.js +33 -6836
  13. package/dist/extensions/guided-lab.js +33 -6854
  14. package/dist/extensions/javascript.esm.js +1 -36
  15. package/dist/extensions/javascript.js +1 -58
  16. package/dist/extensions/python.esm.js +113 -8122
  17. package/dist/extensions/python.js +113 -8140
  18. package/dist/extensions/typescript.esm.js +1 -55
  19. package/dist/extensions/typescript.js +1 -77
  20. package/dist/index.d.ts +1 -1
  21. package/dist/logger.d.ts +4 -20
  22. package/dist/modular-kernel.d.ts +0 -5
  23. package/dist/packages/core/src/errors.d.ts +5 -1
  24. package/dist/packages/fs/src/backends.d.ts +0 -27
  25. package/dist/packages/fs/src/index.d.ts +1 -1
  26. package/dist/packages/ui/src/html.d.ts +1 -0
  27. package/dist/packages/ui/src/index.d.ts +1 -0
  28. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -11
  29. package/dist/packages/ui/src/observability.d.ts +1 -1
  30. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  31. package/dist/preview-sw.js +1 -1
  32. package/dist/runtime.d.ts +3 -0
  33. package/dist/runtime.esm.js +78 -78
  34. package/dist/runtime.js +78 -78
  35. package/dist/schemas.d.ts +10 -1
  36. package/dist/schemas.esm.js +33 -6815
  37. package/dist/schemas.js +33 -6831
  38. package/dist/shell.esm.js +277 -285
  39. package/dist/shell.js +277 -285
  40. package/dist/terminal.esm.js +9 -7
  41. package/dist/terminal.js +7 -7
  42. package/dist/workbench/command-palette.d.ts +0 -4
  43. package/dist/workbench/editor.d.ts +0 -4
  44. package/dist/workbench/index.d.ts +0 -22
  45. package/dist/workbench/intellisense.d.ts +1 -8
  46. package/dist/workbench/xterm-adapter.d.ts +0 -1
  47. package/package.json +4 -13
  48. package/dist/code-lab.umd.js +0 -6117
  49. package/dist/packages/editor/src/index.d.ts +0 -118
  50. package/dist/packages/preview/src/index.d.ts +0 -34
  51. package/dist/packages/runtime/src/index.d.ts +0 -47
  52. package/dist/packages/terminal/src/index.d.ts +0 -54
  53. package/dist/workbench/drawer.d.ts +0 -18
  54. package/dist/workbench/file-tree.d.ts +0 -11
  55. package/dist/workbench/guided-pane.d.ts +0 -11
  56. package/dist/workbench/styles.d.ts +0 -4
  57. package/dist/workbench/toolbar.d.ts +0 -17
  58. package/packages/commands/README.md +0 -7
  59. package/packages/commands/package.json +0 -16
  60. package/packages/commands/src/index.ts +0 -467
  61. package/packages/commands/tsconfig.json +0 -22
  62. package/packages/core/README.md +0 -12
  63. package/packages/core/package.json +0 -13
  64. package/packages/core/src/di.ts +0 -147
  65. package/packages/core/src/disposable.ts +0 -112
  66. package/packages/core/src/errors.ts +0 -205
  67. package/packages/core/src/events.ts +0 -157
  68. package/packages/core/src/index.ts +0 -49
  69. package/packages/core/src/path.ts +0 -118
  70. package/packages/core/src/registry.ts +0 -61
  71. package/packages/core/tsconfig.json +0 -19
  72. package/packages/editor/README.md +0 -9
  73. package/packages/editor/package.json +0 -18
  74. package/packages/editor/src/index.ts +0 -344
  75. package/packages/editor/tsconfig.json +0 -24
  76. package/packages/fs/README.md +0 -7
  77. package/packages/fs/package.json +0 -16
  78. package/packages/fs/src/backends.ts +0 -301
  79. package/packages/fs/src/index.ts +0 -18
  80. package/packages/fs/src/types.ts +0 -44
  81. package/packages/fs/src/vfs-service.ts +0 -257
  82. package/packages/fs/tsconfig.json +0 -22
  83. package/packages/preview/README.md +0 -3
  84. package/packages/preview/package.json +0 -16
  85. package/packages/preview/src/index.ts +0 -125
  86. package/packages/preview/tsconfig.json +0 -22
  87. package/packages/runtime/README.md +0 -3
  88. package/packages/runtime/package.json +0 -17
  89. package/packages/runtime/src/index.ts +0 -134
  90. package/packages/runtime/tsconfig.json +0 -23
  91. package/packages/settings/README.md +0 -7
  92. package/packages/settings/package.json +0 -16
  93. package/packages/settings/src/builtin-schemas.ts +0 -262
  94. package/packages/settings/src/configuration-service.ts +0 -609
  95. package/packages/settings/src/index.ts +0 -38
  96. package/packages/settings/src/jsonc.ts +0 -189
  97. package/packages/settings/src/schema.ts +0 -164
  98. package/packages/settings/tsconfig.json +0 -22
  99. package/packages/sql/README.md +0 -12
  100. package/packages/sql/package.json +0 -13
  101. package/packages/sql/src/completions.ts +0 -359
  102. package/packages/sql/src/diagnostics.ts +0 -200
  103. package/packages/sql/src/formatter.ts +0 -271
  104. package/packages/sql/src/index.ts +0 -54
  105. package/packages/sql/src/sql-editor.ts +0 -802
  106. package/packages/sql/src/styles.ts +0 -524
  107. package/packages/sql/src/tokenizer.ts +0 -457
  108. package/packages/sql/src/types.ts +0 -148
  109. package/packages/sql/tsconfig.json +0 -19
  110. package/packages/terminal/README.md +0 -3
  111. package/packages/terminal/package.json +0 -16
  112. package/packages/terminal/src/index.ts +0 -183
  113. package/packages/terminal/tsconfig.json +0 -22
  114. package/packages/ui/README.md +0 -8
  115. package/packages/ui/package.json +0 -18
  116. package/packages/ui/src/index.ts +0 -40
  117. package/packages/ui/src/observability.ts +0 -173
  118. package/packages/ui/src/plugin-registry.ts +0 -289
  119. package/packages/ui/src/settings-dialog.ts +0 -939
  120. package/packages/ui/src/themes.ts +0 -333
  121. package/packages/ui/tsconfig.json +0 -24
  122. package/src/code-lab.css +0 -8584
  123. package/src/csp.ts +0 -590
  124. package/src/diagnostics.ts +0 -287
  125. package/src/extensions/cpp.ts +0 -2389
  126. package/src/extensions/guided-lab.ts +0 -64
  127. package/src/extensions/javascript.ts +0 -54
  128. package/src/extensions/python.ts +0 -1737
  129. package/src/extensions/typescript.ts +0 -85
  130. package/src/extensions/umbrella.ts +0 -5
  131. package/src/html.ts +0 -88
  132. package/src/index.ts +0 -129
  133. package/src/logger.ts +0 -139
  134. package/src/modular-kernel.ts +0 -11
  135. package/src/preview-sw.js +0 -296
  136. package/src/runtime/test-harness.ts +0 -57
  137. package/src/runtime.ts +0 -10480
  138. package/src/sample.html +0 -304
  139. package/src/schemas.ts +0 -366
  140. package/src/scm.ts +0 -2453
  141. package/src/search.ts +0 -433
  142. package/src/shell.ts +0 -10987
  143. package/src/storage.ts +0 -773
  144. package/src/terminal.ts +0 -1400
  145. package/src/workbench/command-palette.ts +0 -381
  146. package/src/workbench/diff-editor.ts +0 -470
  147. package/src/workbench/drawer.ts +0 -157
  148. package/src/workbench/editor.ts +0 -49
  149. package/src/workbench/file-tree.ts +0 -51
  150. package/src/workbench/guided-pane.ts +0 -43
  151. package/src/workbench/icons.ts +0 -255
  152. package/src/workbench/index.ts +0 -44
  153. package/src/workbench/intellisense.ts +0 -1871
  154. package/src/workbench/share.ts +0 -128
  155. package/src/workbench/styles.ts +0 -211
  156. package/src/workbench/toolbar.ts +0 -182
  157. package/src/workbench/xterm-adapter.ts +0 -1571
  158. package/src/workbench.ts +0 -22132
  159. package/src/zip.ts +0 -348
package/src/terminal.ts DELETED
@@ -1,1400 +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' || (isCtrl && (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.isCommandRunning()) {
1145
- await new Promise((r) => setTimeout(r, 10));
1146
- }
1147
- } else if (seg.length > 0) {
1148
- this.buffer = seg;
1149
- this.cursor = seg.length;
1150
- this.updateActiveLine();
1151
- }
1152
- }
1153
- }
1154
-
1155
- autoComplete() {
1156
- if (!this.getCompletions) return;
1157
- const res = this.getCompletions(this.buffer, this.cursor);
1158
- if (!res || !Array.isArray(res.matches) || res.matches.length === 0) return;
1159
-
1160
- const matches = res.matches;
1161
- if (matches.length === 1) {
1162
- const match = matches[0];
1163
- const isDir = match.endsWith('/');
1164
- const appendChar = isDir ? '' : ' ';
1165
- const before = this.buffer.slice(0, res.tokenStart);
1166
- const after = this.buffer.slice(this.cursor);
1167
- this.buffer = before + match + appendChar + after;
1168
- this.cursor = before.length + match.length + appendChar.length;
1169
- this.updateActiveLine();
1170
- } else {
1171
- // Find longest common prefix
1172
- let lcp = matches[0];
1173
- for (let i = 1; i < matches.length; i++) {
1174
- let j = 0;
1175
- while (j < lcp.length && j < matches[i].length && lcp[j] === matches[i][j]) {
1176
- j++;
1177
- }
1178
- lcp = lcp.slice(0, j);
1179
- }
1180
-
1181
- if (lcp.length > res.token.length) {
1182
- const before = this.buffer.slice(0, res.tokenStart);
1183
- const after = this.buffer.slice(this.cursor);
1184
- this.buffer = before + lcp + after;
1185
- this.cursor = before.length + lcp.length;
1186
- }
1187
-
1188
- // Print candidate matches
1189
- this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
1190
- this._pushLog({ type: 'stdout', text: matches.join(' ') });
1191
- this.render();
1192
- }
1193
- }
1194
-
1195
- submitLine() {
1196
- if (this._readLineQueue && this._readLineQueue.length > 0) {
1197
- const line = this.buffer;
1198
- this.buffer = '';
1199
- this.cursor = 0;
1200
- this.historyIdx = -1;
1201
- this.searchMode = false;
1202
- this.searchQuery = '';
1203
- this.searchMatchIdx = -1;
1204
-
1205
- const entry = this._readLineQueue.shift();
1206
- if (entry && typeof entry.cleanup === 'function') {
1207
- entry.cleanup();
1208
- }
1209
- if (typeof entry === 'function') {
1210
- this.updateActiveLine();
1211
- entry(line);
1212
- } else if (entry && typeof entry.resolve === 'function') {
1213
- this.promptOverride = entry.prevPrompt;
1214
- this._activateNextReadLine();
1215
- this.updateActiveLine();
1216
- entry.resolve(line);
1217
- }
1218
- return;
1219
- }
1220
-
1221
- if (this.isBusy) {
1222
- return;
1223
- }
1224
-
1225
- const line = this.buffer;
1226
- const promptSnap = this.getPrompt();
1227
- this.buffer = '';
1228
- this.cursor = 0;
1229
- this.historyIdx = -1;
1230
- this.searchMode = false;
1231
- this.searchQuery = '';
1232
- this.searchMatchIdx = -1;
1233
-
1234
- const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
1235
- this._activeLineCommitted = true;
1236
- this._cursorCol = 0;
1237
- this._targetLineIdx = -1;
1238
- this._needsRewrite = false;
1239
- this._appendDomLine(echoed);
1240
- this._activeLineEl = null;
1241
-
1242
- if (line.trim()) {
1243
- if (this.history[this.history.length - 1] !== line.trim()) {
1244
- this.history.push(line.trim());
1245
- const maxHist = typeof this.maxHistory === 'number' && this.maxHistory > 0 ? this.maxHistory : 1000;
1246
- if (this.history.length > maxHist) {
1247
- this.history.splice(0, this.history.length - maxHist);
1248
- }
1249
- }
1250
- }
1251
-
1252
- if (!this.onCommand) {
1253
- this.updateActiveLine();
1254
- return;
1255
- }
1256
-
1257
- this.isBusy = true;
1258
- this.updateActiveLine();
1259
-
1260
- let cmdResult;
1261
- try {
1262
- cmdResult = this.onCommand(line);
1263
- } catch (err) {
1264
- this.isBusy = false;
1265
- this.updateActiveLine();
1266
- throw err;
1267
- }
1268
-
1269
- if (cmdResult && typeof cmdResult.then === 'function') {
1270
- Promise.resolve(cmdResult)
1271
- .catch((err) => {
1272
- _terminalLogger.debug('Terminal onCommand promise rejected.', err);
1273
- })
1274
- .finally(() => {
1275
- this.isBusy = false;
1276
- this.updateActiveLine();
1277
- });
1278
- } else {
1279
- this.isBusy = false;
1280
- this.updateActiveLine();
1281
- }
1282
- }
1283
-
1284
- updateActiveLine() {
1285
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1286
- const input = this.container.querySelector('#cl-repl-input');
1287
- if (input && input.value !== this.buffer) {
1288
- input.value = this.buffer;
1289
- }
1290
- const lineEl = this.container.querySelector('#cl-pty-active-line');
1291
- if (!lineEl) return;
1292
-
1293
- if (this.isCommandRunning()) {
1294
- if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
1295
- if (lineEl.style) lineEl.style.display = 'none';
1296
- 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>`;
1297
- return;
1298
- }
1299
-
1300
- if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
1301
- if (lineEl.style) lineEl.style.display = '';
1302
-
1303
- const prompt = this.searchMode
1304
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1305
- : this.getPrompt();
1306
- const before = this.buffer.slice(0, this.cursor);
1307
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1308
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1309
-
1310
- 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>`;
1311
- }
1312
-
1313
- render() {
1314
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1315
- const prevInput = this.container.querySelector('#cl-repl-input');
1316
- const hadFocus = Boolean(
1317
- prevInput &&
1318
- typeof document !== 'undefined' &&
1319
- document.activeElement === prevInput
1320
- );
1321
-
1322
- const logsHtml = this.logs
1323
- .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
1324
- .join('');
1325
-
1326
- const busy = this.isCommandRunning();
1327
- const prompt = busy
1328
- ? ''
1329
- : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
1330
- const before = busy ? '' : this.buffer.slice(0, this.cursor);
1331
- const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
1332
- const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
1333
- const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
1334
- const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
1335
-
1336
- this.container.innerHTML = `
1337
- <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1338
- <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1339
- <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
1340
- <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>
1341
- </div>
1342
- <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1343
- <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
1344
- </form>
1345
- </div>
1346
- `;
1347
-
1348
- this._scrollToBottom();
1349
-
1350
- this._bindEvents();
1351
-
1352
- if (hadFocus) {
1353
- const nextInput = this.container.querySelector('#cl-repl-input');
1354
- if (nextInput && typeof nextInput.focus === 'function') {
1355
- try {
1356
- nextInput.focus();
1357
- if (typeof nextInput.setSelectionRange === 'function') {
1358
- nextInput.setSelectionRange(this.cursor, this.cursor);
1359
- }
1360
- } catch (err) {
1361
- _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
1362
- }
1363
- }
1364
- }
1365
- }
1366
- }
1367
-
1368
- function createTerminal(container, options = {}) {
1369
- return new PTYTerminalEngine(container, options);
1370
- }
1371
-
1372
- const createPTYTerminalEngine = createTerminal;
1373
-
1374
- return {
1375
- PTYTerminalEngine,
1376
- createPTYTerminalEngine,
1377
- createTerminal,
1378
- ansiToHtml,
1379
- parseAnsiToHtml,
1380
- escapeHtml,
1381
- ANSI_CODE_MAP,
1382
- resolveAnsiControlCodes
1383
- };
1384
- });
1385
-
1386
- // ── TypeScript module surface (stripped from browser bundles) ──────────────
1387
- const _hostTerminal: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabTerminal : undefined)
1388
- || (typeof module !== 'undefined' && module.exports ? module.exports : {});
1389
-
1390
- export const ANSI_CODE_MAP: Record<number, string> = _hostTerminal.ANSI_CODE_MAP;
1391
- export const ansi256ToColor: (n: number | string) => string | null = _hostTerminal.ansi256ToColor;
1392
- export const escapeHtml: (str: any) => string = _hostTerminal.escapeHtml;
1393
- export const resolveAnsiControlCodes: (raw: any) => string = _hostTerminal.resolveAnsiControlCodes;
1394
- export const ansiToHtml: (str: any) => string = _hostTerminal.ansiToHtml;
1395
- export const parseAnsiToHtml: (str: any) => string = _hostTerminal.parseAnsiToHtml;
1396
- export const PTYTerminalEngine: any = _hostTerminal.PTYTerminalEngine;
1397
- export const createTerminal: (container?: any, options?: any) => any = _hostTerminal.createTerminal;
1398
- export const createPTYTerminalEngine: (container?: any, options?: any) => any = _hostTerminal.createPTYTerminalEngine;
1399
-
1400
- export default _hostTerminal;