@innovatorved/code-lab 0.1.6 → 0.1.7

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.
package/src/terminal.ts CHANGED
@@ -1,5 +1,6 @@
1
+ // @ts-nocheck
1
2
  /**
2
- * @innovatorved/code-lab - Pure-JS/TS PTY Terminal Emulator Component
3
+ * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
3
4
  *
4
5
  * High-fidelity, self-contained terminal emulator engine providing:
5
6
  * - Inline prompt with cwd awareness (codelab:${cwd}$ )
@@ -14,261 +15,259 @@
14
15
  * (C) 2026 InnovatorVed / CodeLab. MIT License.
15
16
  */
16
17
 
17
- export interface TerminalLogItem {
18
- text: string;
19
- type?: string;
20
- }
21
-
22
- export interface CompletionResult {
23
- matches: string[];
24
- token: string;
25
- tokenStart: number;
26
- }
27
-
28
- export interface TerminalOptions {
29
- container?: any;
30
- logs?: TerminalLogItem[];
31
- cwd?: string;
32
- replMode?: boolean;
33
- prompt?: string | null;
34
- history?: string[];
35
- onCommand?: ((command: string) => void) | null;
36
- getCompletions?: ((buffer: string, cursor: number) => CompletionResult | null) | null;
37
- onKey?: ((event: any) => boolean | void) | null;
38
- onInterrupt?: (() => void) | null;
39
- }
40
-
41
- export const ANSI_CODE_MAP: Record<number, string> = {
42
- 1: 'cl-ansi-bold',
43
- 2: 'cl-ansi-dim',
44
- 3: 'cl-ansi-italic',
45
- 4: 'cl-ansi-underline',
46
- 30: 'cl-ansi-black',
47
- 31: 'cl-ansi-red',
48
- 32: 'cl-ansi-green',
49
- 33: 'cl-ansi-yellow',
50
- 34: 'cl-ansi-blue',
51
- 35: 'cl-ansi-magenta',
52
- 36: 'cl-ansi-cyan',
53
- 37: 'cl-ansi-white',
54
- 90: 'cl-ansi-gray',
55
- 91: 'cl-ansi-bright-red',
56
- 92: 'cl-ansi-bright-green',
57
- 93: 'cl-ansi-bright-yellow',
58
- 94: 'cl-ansi-bright-blue',
59
- 95: 'cl-ansi-bright-magenta',
60
- 96: 'cl-ansi-bright-cyan',
61
- 97: 'cl-ansi-bright-white',
62
- 40: 'cl-ansi-bg-black',
63
- 41: 'cl-ansi-bg-red',
64
- 42: 'cl-ansi-bg-green',
65
- 43: 'cl-ansi-bg-yellow',
66
- 44: 'cl-ansi-bg-blue',
67
- 45: 'cl-ansi-bg-magenta',
68
- 46: 'cl-ansi-bg-cyan',
69
- 47: 'cl-ansi-bg-white',
70
- 100: 'cl-ansi-bg-bright-black',
71
- 101: 'cl-ansi-bg-bright-red',
72
- 102: 'cl-ansi-bg-bright-green',
73
- 103: 'cl-ansi-bg-bright-yellow',
74
- 104: 'cl-ansi-bg-bright-blue',
75
- 105: 'cl-ansi-bg-bright-magenta',
76
- 106: 'cl-ansi-bg-bright-cyan',
77
- 107: 'cl-ansi-bg-bright-white'
78
- };
79
-
80
- export const ANSI_256_PALETTE: string[] = [
81
- '#000000', '#cd3131', '#0dbc79', '#e5e510', '#2472c8', '#bc3fbc', '#11a8cd', '#e5e5e5',
82
- '#666666', '#f14c4c', '#23d18b', '#f5f543', '#3b8eea', '#d670d6', '#29b8db', '#ffffff'
83
- ];
84
-
85
- export function ansi256ToColor(n: number | string): string | null {
86
- const idx = Number(n);
87
- if (!Number.isFinite(idx) || idx < 0 || idx > 255) return null;
88
- if (idx < 16) return ANSI_256_PALETTE[idx];
89
- if (idx < 232) {
90
- const c = idx - 16;
91
- const r = Math.floor(c / 36);
92
- const g = Math.floor((c % 36) / 6);
93
- const b = c % 6;
94
- const toChannel = (v: number) => (v === 0 ? 0 : 55 + v * 40);
95
- return `rgb(${toChannel(r)}, ${toChannel(g)}, ${toChannel(b)})`;
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;
96
27
  }
97
- const gray = 8 + (idx - 232) * 10;
98
- return `rgb(${gray}, ${gray}, ${gray})`;
99
- }
100
-
101
- export function escapeHtml(str: any): string {
102
- if (str == null) return '';
103
- return String(str)
104
- .replace(/&/g, '&amp;')
105
- .replace(/</g, '&lt;')
106
- .replace(/>/g, '&gt;')
107
- .replace(/"/g, '&quot;')
108
- .replace(/'/g, '&#39;');
109
- }
110
-
111
- export function resolveAnsiControlCodes(raw: any): string {
112
- if (!raw) return '';
113
- const s = String(raw);
114
- if (!s.includes('\x1b') && !s.includes('\r')) return s;
115
-
116
- let text = s;
117
- const lastClearScreen = text.lastIndexOf('\x1b[2J');
118
- if (lastClearScreen !== -1) {
119
- text = text.slice(lastClearScreen + 4);
120
- text = text.replace(/^\x1b\[(?:1;1)?H/, '');
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 ANSI_CODE_MAP = {
37
+ 1: 'cl-ansi-bold',
38
+ 2: 'cl-ansi-dim',
39
+ 3: 'cl-ansi-italic',
40
+ 4: 'cl-ansi-underline',
41
+ 30: 'cl-ansi-black',
42
+ 31: 'cl-ansi-red',
43
+ 32: 'cl-ansi-green',
44
+ 33: 'cl-ansi-yellow',
45
+ 34: 'cl-ansi-blue',
46
+ 35: 'cl-ansi-magenta',
47
+ 36: 'cl-ansi-cyan',
48
+ 37: 'cl-ansi-white',
49
+ 90: 'cl-ansi-gray',
50
+ 91: 'cl-ansi-bright-red',
51
+ 92: 'cl-ansi-bright-green',
52
+ 93: 'cl-ansi-bright-yellow',
53
+ 94: 'cl-ansi-bright-blue',
54
+ 95: 'cl-ansi-bright-magenta',
55
+ 96: 'cl-ansi-bright-cyan',
56
+ 97: 'cl-ansi-bright-white',
57
+ 40: 'cl-ansi-bg-black',
58
+ 41: 'cl-ansi-bg-red',
59
+ 42: 'cl-ansi-bg-green',
60
+ 43: 'cl-ansi-bg-yellow',
61
+ 44: 'cl-ansi-bg-blue',
62
+ 45: 'cl-ansi-bg-magenta',
63
+ 46: 'cl-ansi-bg-cyan',
64
+ 47: 'cl-ansi-bg-white',
65
+ 100: 'cl-ansi-bg-bright-black',
66
+ 101: 'cl-ansi-bg-bright-red',
67
+ 102: 'cl-ansi-bg-bright-green',
68
+ 103: 'cl-ansi-bg-bright-yellow',
69
+ 104: 'cl-ansi-bg-bright-blue',
70
+ 105: 'cl-ansi-bg-bright-magenta',
71
+ 106: 'cl-ansi-bg-bright-cyan',
72
+ 107: 'cl-ansi-bg-bright-white'
73
+ };
74
+
75
+ const ANSI_256_PALETTE = [
76
+ '#000000', '#cd3131', '#0dbc79', '#e5e510', '#2472c8', '#bc3fbc', '#11a8cd', '#e5e5e5',
77
+ '#666666', '#f14c4c', '#23d18b', '#f5f543', '#3b8eea', '#d670d6', '#29b8db', '#ffffff'
78
+ ];
79
+
80
+ function ansi256ToColor(n) {
81
+ const idx = Number(n);
82
+ if (!Number.isFinite(idx) || idx < 0 || idx > 255) return null;
83
+ if (idx < 16) return ANSI_256_PALETTE[idx];
84
+ if (idx < 232) {
85
+ const c = idx - 16;
86
+ const r = Math.floor(c / 36);
87
+ const g = Math.floor((c % 36) / 6);
88
+ const b = c % 6;
89
+ const toChannel = v => (v === 0 ? 0 : 55 + v * 40);
90
+ return `rgb(${toChannel(r)}, ${toChannel(g)}, ${toChannel(b)})`;
91
+ }
92
+ const gray = 8 + (idx - 232) * 10;
93
+ return `rgb(${gray}, ${gray}, ${gray})`;
94
+ }
95
+
96
+ function escapeHtml(str) {
97
+ if (str == null) return '';
98
+ return String(str)
99
+ .replace(/&/g, '&amp;')
100
+ .replace(/</g, '&lt;')
101
+ .replace(/>/g, '&gt;')
102
+ .replace(/"/g, '&quot;')
103
+ .replace(/'/g, '&#39;');
121
104
  }
122
105
 
123
- text = text.replace(/\r\n/g, '\n');
124
- const rawLines = text.split('\n');
125
- const resolvedLines: string[] = [];
126
-
127
- for (let l = 0; l < rawLines.length; l++) {
128
- let line = rawLines[l];
129
-
130
- while (/\x1b\[(?:1)?A/.test(line)) {
131
- const upMatch = /\x1b\[(?:1)?A/.exec(line);
132
- if (!upMatch) break;
133
- const beforeUp = line.slice(0, upMatch.index);
134
- let afterUp = line.slice(upMatch.index + upMatch[0].length);
135
- if (resolvedLines.length > 0) {
136
- if (afterUp.includes('\x1b[2K')) {
137
- afterUp = afterUp.slice(afterUp.lastIndexOf('\x1b[2K') + 4);
138
- resolvedLines[resolvedLines.length - 1] = afterUp;
139
- } else if (afterUp.includes('\r')) {
140
- const parts = afterUp.split('\r');
141
- resolvedLines[resolvedLines.length - 1] = parts[parts.length - 1];
106
+ function resolveAnsiControlCodes(raw) {
107
+ if (!raw) return '';
108
+ const s = String(raw);
109
+ if (!s.includes('\x1b') && !s.includes('\r')) return s;
110
+
111
+ let text = s;
112
+ const lastClearScreen = text.lastIndexOf('\x1b[2J');
113
+ if (lastClearScreen !== -1) {
114
+ text = text.slice(lastClearScreen + 4);
115
+ text = text.replace(/^\x1b\[(?:1;1)?H/, '');
116
+ }
117
+
118
+ text = text.replace(/\r\n/g, '\n');
119
+ const rawLines = text.split('\n');
120
+ const resolvedLines = [];
121
+
122
+ for (let l = 0; l < rawLines.length; l++) {
123
+ let line = rawLines[l];
124
+
125
+ while (/\x1b\[(?:1)?A/.test(line)) {
126
+ const upMatch = /\x1b\[(?:1)?A/.exec(line);
127
+ const beforeUp = line.slice(0, upMatch.index);
128
+ let afterUp = line.slice(upMatch.index + upMatch[0].length);
129
+ if (resolvedLines.length > 0) {
130
+ if (afterUp.includes('\x1b[2K')) {
131
+ afterUp = afterUp.slice(afterUp.lastIndexOf('\x1b[2K') + 4);
132
+ resolvedLines[resolvedLines.length - 1] = afterUp;
133
+ } else if (afterUp.includes('\r')) {
134
+ const parts = afterUp.split('\r');
135
+ resolvedLines[resolvedLines.length - 1] = parts[parts.length - 1];
136
+ } else {
137
+ resolvedLines[resolvedLines.length - 1] = afterUp;
138
+ }
139
+ line = beforeUp;
142
140
  } else {
143
- resolvedLines[resolvedLines.length - 1] = afterUp;
141
+ line = beforeUp + afterUp;
144
142
  }
145
- line = beforeUp;
146
- } else {
147
- line = beforeUp + afterUp;
148
143
  }
149
- }
150
144
 
151
- if (line.includes('\x1b[2K')) {
152
- const idx = line.lastIndexOf('\x1b[2K');
153
- line = line.slice(idx + 4);
154
- }
145
+ if (line.includes('\x1b[2K')) {
146
+ const idx = line.lastIndexOf('\x1b[2K');
147
+ line = line.slice(idx + 4);
148
+ }
149
+
150
+ if (line.includes('\r')) {
151
+ const parts = line.split('\r');
152
+ line = parts[parts.length - 1];
153
+ }
155
154
 
156
- if (line.includes('\r')) {
157
- const parts = line.split('\r');
158
- line = parts[parts.length - 1];
155
+ line = line.replace(/\x1b\[[0]?K/g, '');
156
+ line = line.replace(/\x1b\[(?:1)?G/g, '');
157
+ resolvedLines.push(line);
159
158
  }
160
159
 
161
- line = line.replace(/\x1b\[[0]?K/g, '');
162
- line = line.replace(/\x1b\[(?:1)?G/g, '');
163
- resolvedLines.push(line);
160
+ return resolvedLines.join('\n');
164
161
  }
165
162
 
166
- return resolvedLines.join('\n');
167
- }
168
-
169
- export function ansiToHtml(str: any): string {
170
- if (!str) return '';
171
- const resolved = resolveAnsiControlCodes(String(str));
172
- if (!resolved.includes('\x1b[')) {
173
- return escapeHtml(resolved);
174
- }
163
+ function ansiToHtml(str) {
164
+ if (!str) return '';
165
+ const resolved = resolveAnsiControlCodes(String(str));
166
+ if (!resolved.includes('\x1b[')) {
167
+ return escapeHtml(resolved);
168
+ }
175
169
 
176
- // Strip non-color cursor control sequences without stripping lowercase 'm' SGR codes
177
- const cleaned = resolved.replace(/\x1b\[[0-9;?]*(?!m)[A-Za-z]/g, '');
178
-
179
- const tokenRegex = /\x1b\[([0-9;]*)m/g;
180
- let result = '';
181
- let lastIdx = 0;
182
- let match: RegExpExecArray | null;
183
-
184
- const state: {
185
- bold: boolean;
186
- dim: boolean;
187
- italic: boolean;
188
- underline: boolean;
189
- fgClass: string | null;
190
- bgClass: string | null;
191
- fgColor: string | null;
192
- bgColor: string | null;
193
- } = {
194
- bold: false,
195
- dim: false,
196
- italic: false,
197
- underline: false,
198
- fgClass: null,
199
- bgClass: null,
200
- fgColor: null,
201
- bgColor: null
202
- };
170
+ // Strip non-color cursor control sequences without stripping lowercase 'm' SGR codes
171
+ const cleaned = resolved.replace(/\x1b\[[0-9;?]*(?!m)[A-Za-z]/g, '');
172
+
173
+ const tokenRegex = /\x1b\[([0-9;]*)m/g;
174
+ let result = '';
175
+ let lastIdx = 0;
176
+ let match;
177
+
178
+ const state = {
179
+ bold: false,
180
+ dim: false,
181
+ italic: false,
182
+ underline: false,
183
+ fgClass: null,
184
+ bgClass: null,
185
+ fgColor: null,
186
+ bgColor: null
187
+ };
203
188
 
204
- const resetState = () => {
205
- state.bold = false;
206
- state.dim = false;
207
- state.italic = false;
208
- state.underline = false;
209
- state.fgClass = null;
210
- state.bgClass = null;
211
- state.fgColor = null;
212
- state.bgColor = null;
213
- };
189
+ const resetState = () => {
190
+ state.bold = false;
191
+ state.dim = false;
192
+ state.italic = false;
193
+ state.underline = false;
194
+ state.fgClass = null;
195
+ state.bgClass = null;
196
+ state.fgColor = null;
197
+ state.bgColor = null;
198
+ };
214
199
 
215
- const renderChunk = (rawText: string) => {
216
- if (!rawText) return '';
217
- const escaped = escapeHtml(rawText);
218
- const classes: string[] = [];
219
- if (state.bold) classes.push('cl-ansi-bold');
220
- if (state.dim) classes.push('cl-ansi-dim');
221
- if (state.italic) classes.push('cl-ansi-italic');
222
- if (state.underline) classes.push('cl-ansi-underline');
223
- if (state.fgClass) classes.push(state.fgClass);
224
- if (state.bgClass) classes.push(state.bgClass);
225
-
226
- const styles: string[] = [];
227
- if (state.fgColor) styles.push(`color:${state.fgColor}`);
228
- if (state.bgColor) styles.push(`background-color:${state.bgColor}`);
229
-
230
- if (classes.length === 0 && styles.length === 0) {
231
- return escaped;
232
- }
233
- const classAttr = classes.length > 0 ? ` class="${classes.join(' ')}"` : '';
234
- const styleAttr = styles.length > 0 ? ` style="${styles.join(';')}"` : '';
235
- return `<span${classAttr}${styleAttr}>${escaped}</span>`;
236
- };
200
+ const renderChunk = (rawText) => {
201
+ if (!rawText) return '';
202
+ const escaped = escapeHtml(rawText);
203
+ const classes = [];
204
+ if (state.bold) classes.push('cl-ansi-bold');
205
+ if (state.dim) classes.push('cl-ansi-dim');
206
+ if (state.italic) classes.push('cl-ansi-italic');
207
+ if (state.underline) classes.push('cl-ansi-underline');
208
+ if (state.fgClass) classes.push(state.fgClass);
209
+ if (state.bgClass) classes.push(state.bgClass);
210
+
211
+ const styles = [];
212
+ if (state.fgColor) styles.push(`color:${state.fgColor}`);
213
+ if (state.bgColor) styles.push(`background-color:${state.bgColor}`);
214
+
215
+ if (classes.length === 0 && styles.length === 0) {
216
+ return escaped;
217
+ }
218
+ const classAttr = classes.length > 0 ? ` class="${classes.join(' ')}"` : '';
219
+ const styleAttr = styles.length > 0 ? ` style="${styles.join(';')}"` : '';
220
+ return `<span${classAttr}${styleAttr}>${escaped}</span>`;
221
+ };
237
222
 
238
- while ((match = tokenRegex.exec(cleaned)) !== null) {
239
- const rawText = cleaned.slice(lastIdx, match.index);
240
- if (rawText) result += renderChunk(rawText);
241
- lastIdx = tokenRegex.lastIndex;
242
-
243
- const codes = match[1] ? match[1].split(';').map(Number) : [0];
244
- for (let i = 0; i < codes.length; i++) {
245
- const code = codes[i];
246
- if (code === 0 || Number.isNaN(code)) {
247
- resetState();
248
- } else if (code === 1) {
249
- state.bold = true;
250
- } else if (code === 2) {
251
- state.dim = true;
252
- } else if (code === 3) {
253
- state.italic = true;
254
- } else if (code === 4) {
255
- state.underline = true;
256
- } else if (code === 22) {
257
- state.bold = false;
258
- state.dim = false;
259
- } else if (code === 23) {
260
- state.italic = false;
261
- } else if (code === 24) {
262
- state.underline = false;
263
- } else if (code === 39) {
264
- state.fgClass = null;
265
- state.fgColor = null;
266
- } else if (code === 49) {
267
- state.bgClass = null;
268
- state.bgColor = null;
269
- } else if ((code === 38 || code === 48) && codes[i + 1] === 5 && i + 2 < codes.length) {
270
- const color = ansi256ToColor(codes[i + 2]);
271
- if (color) {
223
+ while ((match = tokenRegex.exec(cleaned)) !== null) {
224
+ const rawText = cleaned.slice(lastIdx, match.index);
225
+ if (rawText) result += renderChunk(rawText);
226
+ lastIdx = tokenRegex.lastIndex;
227
+
228
+ const codes = match[1] ? match[1].split(';').map(Number) : [0];
229
+ for (let i = 0; i < codes.length; i++) {
230
+ const code = codes[i];
231
+ if (code === 0 || Number.isNaN(code)) {
232
+ resetState();
233
+ } else if (code === 1) {
234
+ state.bold = true;
235
+ } else if (code === 2) {
236
+ state.dim = true;
237
+ } else if (code === 3) {
238
+ state.italic = true;
239
+ } else if (code === 4) {
240
+ state.underline = true;
241
+ } else if (code === 22) {
242
+ state.bold = false;
243
+ state.dim = false;
244
+ } else if (code === 23) {
245
+ state.italic = false;
246
+ } else if (code === 24) {
247
+ state.underline = false;
248
+ } else if (code === 39) {
249
+ state.fgClass = null;
250
+ state.fgColor = null;
251
+ } else if (code === 49) {
252
+ state.bgClass = null;
253
+ state.bgColor = null;
254
+ } else if ((code === 38 || code === 48) && codes[i + 1] === 5 && i + 2 < codes.length) {
255
+ const color = ansi256ToColor(codes[i + 2]);
256
+ if (color) {
257
+ if (code === 38) {
258
+ state.fgClass = null;
259
+ state.fgColor = color;
260
+ } else {
261
+ state.bgClass = null;
262
+ state.bgColor = color;
263
+ }
264
+ }
265
+ i += 2;
266
+ } else if ((code === 38 || code === 48) && codes[i + 1] === 2 && i + 4 < codes.length) {
267
+ const r = Math.max(0, Math.min(255, Number(codes[i + 2]) || 0));
268
+ const g = Math.max(0, Math.min(255, Number(codes[i + 3]) || 0));
269
+ const b = Math.max(0, Math.min(255, Number(codes[i + 4]) || 0));
270
+ const color = `rgb(${r}, ${g}, ${b})`;
272
271
  if (code === 38) {
273
272
  state.fgClass = null;
274
273
  state.fgColor = color;
@@ -276,822 +275,789 @@ export function ansiToHtml(str: any): string {
276
275
  state.bgClass = null;
277
276
  state.bgColor = color;
278
277
  }
278
+ i += 4;
279
+ } else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
280
+ state.fgClass = ANSI_CODE_MAP[code] || null;
281
+ state.fgColor = null;
282
+ } else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
283
+ state.bgClass = ANSI_CODE_MAP[code] || null;
284
+ state.bgColor = null;
279
285
  }
280
- i += 2;
281
- } else if ((code === 38 || code === 48) && codes[i + 1] === 2 && i + 4 < codes.length) {
282
- const r = Math.max(0, Math.min(255, Number(codes[i + 2]) || 0));
283
- const g = Math.max(0, Math.min(255, Number(codes[i + 3]) || 0));
284
- const b = Math.max(0, Math.min(255, Number(codes[i + 4]) || 0));
285
- const color = `rgb(${r}, ${g}, ${b})`;
286
- if (code === 38) {
287
- state.fgClass = null;
288
- state.fgColor = color;
289
- } else {
290
- state.bgClass = null;
291
- state.bgColor = color;
292
- }
293
- i += 4;
294
- } else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
295
- state.fgClass = ANSI_CODE_MAP[code] || null;
296
- state.fgColor = null;
297
- } else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
298
- state.bgClass = ANSI_CODE_MAP[code] || null;
299
- state.bgColor = null;
300
286
  }
301
287
  }
302
- }
303
288
 
304
- const remaining = cleaned.slice(lastIdx);
305
- if (remaining) result += renderChunk(remaining);
306
- return result;
307
- }
308
-
309
- export const parseAnsiToHtml = ansiToHtml;
310
-
311
- export class PTYTerminalEngine {
312
- container: any;
313
- options: TerminalOptions;
314
- logs: TerminalLogItem[];
315
- cwd: string;
316
- replMode: boolean;
317
- promptOverride: string | null;
318
- history: string[];
319
- historyIdx: number;
320
- savedBuffer: string;
321
- buffer: string;
322
- cursor: number;
323
- searchMode: boolean;
324
- searchQuery: string;
325
- searchMatchIdx: number;
326
- _readLineQueue: Array<(line: string) => void>;
327
- onCommand: ((command: string) => void) | null;
328
- getCompletions: ((buffer: string, cursor: number) => CompletionResult | null) | null;
329
- onKey: ((event: any) => boolean | void) | null;
330
- onInterrupt: (() => void) | null;
331
-
332
- // Stream & active line buffering state
333
- _activeLineCommitted: boolean;
334
- _cursorCol: number;
335
- _pendingEscape: string;
336
- _targetLineIdx: number;
337
- _needsRewrite: boolean;
338
- _activeLineEl: any;
339
-
340
- _mounted: boolean;
341
- _listeners: Array<any>;
342
-
343
- constructor(container?: any, options: TerminalOptions = {}) {
344
- if (
345
- container &&
346
- typeof container === 'object' &&
347
- typeof container.querySelector !== 'function' &&
348
- typeof container.appendChild !== 'function' &&
349
- arguments.length === 1
350
- ) {
351
- options = container;
352
- container = options.container || null;
353
- }
354
- this.container = container || null;
355
- this.options = options || {};
356
- this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
357
- this.cwd = this.options.cwd || '/workspace';
358
- this.replMode = Boolean(this.options.replMode);
359
- this.promptOverride = this.options.prompt || null;
360
- this.history = Array.isArray(this.options.history) ? this.options.history : [];
361
- this.historyIdx = -1;
362
- this.savedBuffer = '';
363
- this.buffer = '';
364
- this.cursor = 0;
365
- this.searchMode = false;
366
- this.searchQuery = '';
367
- this.searchMatchIdx = -1;
368
- this._readLineQueue = [];
369
- this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
370
- this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
371
- this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
372
- this.onInterrupt = typeof this.options.onInterrupt === 'function' ? this.options.onInterrupt : null;
373
-
374
- this._activeLineCommitted = true;
375
- this._cursorCol = 0;
376
- this._pendingEscape = '';
377
- this._targetLineIdx = -1;
378
- this._needsRewrite = false;
379
- this._activeLineEl = null;
380
-
381
- this._mounted = false;
382
- this._listeners = [];
383
-
384
- if (this.container) {
385
- this.mount(this.container);
386
- }
289
+ const remaining = cleaned.slice(lastIdx);
290
+ if (remaining) result += renderChunk(remaining);
291
+ return result;
387
292
  }
388
293
 
389
- getPrompt(): string {
390
- if (this.promptOverride) return this.promptOverride;
391
- if (this.replMode) return '> ';
392
- const cwd = this.cwd || '/workspace';
393
- return `codelab:${cwd}$ `;
394
- }
294
+ const parseAnsiToHtml = ansiToHtml;
295
+
296
+ class PTYTerminalEngine {
297
+ constructor(container, options = {}) {
298
+ if (
299
+ container &&
300
+ typeof container === 'object' &&
301
+ typeof container.querySelector !== 'function' &&
302
+ typeof container.appendChild !== 'function' &&
303
+ arguments.length === 1
304
+ ) {
305
+ options = container;
306
+ container = options.container || null;
307
+ }
308
+ this.container = container || null;
309
+ this.options = options || {};
310
+ this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
311
+ this.cwd = this.options.cwd || '/workspace';
312
+ this.replMode = Boolean(this.options.replMode);
313
+ this.promptOverride = this.options.prompt || null;
314
+ this.history = Array.isArray(this.options.history) ? this.options.history : [];
315
+ this.historyIdx = -1;
316
+ this.savedBuffer = '';
317
+ this.buffer = '';
318
+ this.cursor = 0;
319
+ this.searchMode = false;
320
+ this.searchQuery = '';
321
+ this.searchMatchIdx = -1;
322
+ this._readLineQueue = [];
323
+ this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
324
+ this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
325
+ this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
326
+ this.onInterrupt = typeof this.options.onInterrupt === 'function' ? this.options.onInterrupt : null;
327
+
328
+ // Stream & active line buffering state
329
+ this._activeLineCommitted = true;
330
+ this._cursorCol = 0;
331
+ this._pendingEscape = '';
332
+ this._targetLineIdx = -1;
333
+ this._needsRewrite = false;
334
+ this._activeLineEl = null;
395
335
 
396
- setPrompt(p: string | null): void {
397
- this.promptOverride = p;
398
- this.updateActiveLine();
399
- }
336
+ this._mounted = false;
337
+ this._listeners = [];
400
338
 
401
- setCwd(cwd: string): void {
402
- this.cwd = cwd;
403
- this.updateActiveLine();
404
- }
339
+ if (this.container) {
340
+ this.mount(this.container);
341
+ }
342
+ }
405
343
 
406
- setReplMode(enabled: boolean): void {
407
- this.replMode = Boolean(enabled);
408
- this.updateActiveLine();
409
- }
344
+ getPrompt() {
345
+ if (this.promptOverride) return this.promptOverride;
346
+ if (this.replMode) return '> ';
347
+ const cwd = this.cwd || '/workspace';
348
+ return `codelab:${cwd}$ `;
349
+ }
410
350
 
411
- writeStreamChunk(data: any, type: string = 'stdout'): void {
412
- let str = String(data != null ? data : '');
413
- if (!str) return;
351
+ setPrompt(p) {
352
+ this.promptOverride = p;
353
+ this.updateActiveLine();
354
+ }
414
355
 
415
- if (this._pendingEscape) {
416
- str = this._pendingEscape + str;
417
- this._pendingEscape = '';
356
+ setCwd(cwd) {
357
+ this.cwd = cwd;
358
+ this.updateActiveLine();
359
+ }
360
+
361
+ setReplMode(enabled) {
362
+ this.replMode = Boolean(enabled);
363
+ this.updateActiveLine();
418
364
  }
419
365
 
420
- let modified = false;
421
- let i = 0;
366
+ writeStreamChunk(data, type = 'stdout') {
367
+ let str = String(data != null ? data : '');
368
+ if (!str) return;
422
369
 
423
- while (i < str.length) {
424
- if (str[i] === '\x1b') {
425
- const rest = str.slice(i);
426
- if (/^\x1b(?:\[[0-9;?]*)?$/.test(rest)) {
427
- this._pendingEscape = rest;
428
- break;
429
- }
370
+ if (this._pendingEscape) {
371
+ str = this._pendingEscape + str;
372
+ this._pendingEscape = '';
373
+ }
430
374
 
431
- const csiMatch = /^\x1b\[([0-9;?]*)([A-Za-z])/.exec(rest);
432
- if (csiMatch) {
433
- const params = csiMatch[1];
434
- const cmd = csiMatch[2];
435
- const seq = csiMatch[0];
436
- i += seq.length;
437
-
438
- if (cmd === 'K') {
439
- const cur = this._getActiveLine(type);
440
- if (params === '2') {
441
- cur.text = '';
442
- this._cursorCol = 0;
443
- this._needsRewrite = false;
444
- } else {
445
- cur.text = cur.text.slice(0, this._cursorCol);
446
- this._needsRewrite = false;
447
- }
448
- modified = true;
449
- } else if (cmd === 'A') {
450
- const count = parseInt(params, 10) || 1;
451
- if (this.logs.length > 0) {
452
- const baseIdx = this._activeLineCommitted ? this.logs.length : this.logs.length - 1;
453
- this._targetLineIdx = Math.max(0, baseIdx - count);
454
- this._activeLineCommitted = false;
375
+ let modified = false;
376
+ let i = 0;
377
+
378
+ while (i < str.length) {
379
+ if (str[i] === '\x1b') {
380
+ const rest = str.slice(i);
381
+ if (/^\x1b(?:\[[0-9;?]*)?$/.test(rest)) {
382
+ this._pendingEscape = rest;
383
+ break;
384
+ }
385
+
386
+ const csiMatch = /^\x1b\[([0-9;?]*)([A-Za-z])/.exec(rest);
387
+ if (csiMatch) {
388
+ const params = csiMatch[1];
389
+ const cmd = csiMatch[2];
390
+ const seq = csiMatch[0];
391
+ i += seq.length;
392
+
393
+ if (cmd === 'K') {
394
+ const cur = this._getActiveLine(type);
395
+ if (params === '2') {
396
+ cur.text = '';
397
+ this._cursorCol = 0;
398
+ this._needsRewrite = false;
399
+ } else {
400
+ cur.text = cur.text.slice(0, this._cursorCol);
401
+ this._needsRewrite = false;
402
+ }
403
+ modified = true;
404
+ } else if (cmd === 'A') {
405
+ const count = parseInt(params, 10) || 1;
406
+ if (this.logs.length > 0) {
407
+ const baseIdx = this._activeLineCommitted ? this.logs.length : this.logs.length - 1;
408
+ this._targetLineIdx = Math.max(0, baseIdx - count);
409
+ this._activeLineCommitted = false;
410
+ this._cursorCol = 0;
411
+ this._needsRewrite = false;
412
+ const targetLine = this.logs[this._targetLineIdx];
413
+ if (targetLine) targetLine.text = '';
414
+ this._activeLineEl = null;
415
+ }
416
+ } else if (cmd === 'G') {
455
417
  this._cursorCol = 0;
456
- this._needsRewrite = false;
457
- const targetLine = this.logs[this._targetLineIdx];
458
- if (targetLine) targetLine.text = '';
459
- this._activeLineEl = null;
418
+ this._needsRewrite = true;
419
+ } else if (cmd === 'J' && params === '2') {
420
+ this.clear();
421
+ } else if (cmd === 'm') {
422
+ const cur = this._getActiveLine(type);
423
+ cur.text += seq;
424
+ modified = true;
460
425
  }
461
- } else if (cmd === 'G') {
462
- this._cursorCol = 0;
463
- this._needsRewrite = true;
464
- } else if (cmd === 'J' && params === '2') {
465
- this.clear();
466
- } else if (cmd === 'm') {
467
- const cur = this._getActiveLine(type);
468
- cur.text += seq;
469
- modified = true;
426
+ continue;
470
427
  }
471
- continue;
472
428
  }
473
- }
474
429
 
475
- const ch = str[i];
476
- if (ch === '\r') {
477
- this._cursorCol = 0;
478
- this._needsRewrite = true;
479
- i++;
480
- } else if (ch === '\n') {
481
- const cur = this._getActiveLine(type);
482
- cur.text += '\n';
483
- this._activeLineCommitted = true;
484
- this._cursorCol = 0;
485
- this._targetLineIdx = -1;
486
- this._needsRewrite = false;
487
- this._activeLineEl = null;
488
- modified = true;
489
- i++;
490
- } else {
491
- const cur = this._getActiveLine(type);
492
- if (this._needsRewrite && this._cursorCol === 0 && cur.text.length > 0 && !cur.text.endsWith('\n')) {
493
- cur.text = ch;
430
+ const ch = str[i];
431
+ if (ch === '\r') {
432
+ this._cursorCol = 0;
433
+ this._needsRewrite = true;
434
+ i++;
435
+ } else if (ch === '\n') {
436
+ const cur = this._getActiveLine(type);
437
+ cur.text += '\n';
438
+ this._activeLineCommitted = true;
439
+ this._cursorCol = 0;
440
+ this._targetLineIdx = -1;
494
441
  this._needsRewrite = false;
442
+ this._activeLineEl = null;
443
+ modified = true;
444
+ i++;
495
445
  } else {
496
- cur.text += ch;
446
+ const cur = this._getActiveLine(type);
447
+ if (this._needsRewrite && this._cursorCol === 0 && cur.text.length > 0 && !cur.text.endsWith('\n')) {
448
+ cur.text = ch;
449
+ this._needsRewrite = false;
450
+ } else {
451
+ cur.text += ch;
452
+ }
453
+ this._cursorCol++;
454
+ modified = true;
455
+ i++;
497
456
  }
498
- this._cursorCol++;
499
- modified = true;
500
- i++;
501
457
  }
502
- }
503
458
 
504
- if (modified) {
505
- this._updateActiveDomLine();
459
+ if (modified) {
460
+ this._updateActiveDomLine();
461
+ }
462
+ this._scrollToBottom();
506
463
  }
507
- this._scrollToBottom();
508
- }
509
-
510
- write(data: any, type: string = 'stdout'): void {
511
- this.writeStreamChunk(data, type);
512
- }
513
464
 
514
- writeln(data: any, type: string = 'stdout'): void {
515
- this.writeStreamChunk(String(data) + '\n', type);
516
- }
465
+ write(data, type = 'stdout') {
466
+ this.writeStreamChunk(data, type);
467
+ }
517
468
 
518
- _getActiveLine(type: string): TerminalLogItem {
519
- if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
520
- return this.logs[this._targetLineIdx];
469
+ writeln(data, type = 'stdout') {
470
+ this.writeStreamChunk(String(data) + '\n', type);
521
471
  }
522
- if (this._activeLineCommitted || this.logs.length === 0) {
523
- const newLine: TerminalLogItem = { text: '', type };
524
- this.logs.push(newLine);
525
- this._activeLineCommitted = false;
526
- this._cursorCol = 0;
472
+
473
+ _getActiveLine(type) {
474
+ if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
475
+ return this.logs[this._targetLineIdx];
476
+ }
477
+ if (this._activeLineCommitted || this.logs.length === 0) {
478
+ const newLine = { text: '', type };
479
+ this.logs.push(newLine);
480
+ this._activeLineCommitted = false;
481
+ this._cursorCol = 0;
482
+ this._targetLineIdx = this.logs.length - 1;
483
+ this._needsRewrite = false;
484
+ this._appendDomLine(newLine);
485
+ return newLine;
486
+ }
527
487
  this._targetLineIdx = this.logs.length - 1;
528
- this._needsRewrite = false;
529
- this._appendDomLine(newLine);
530
- return newLine;
488
+ return this.logs[this.logs.length - 1];
531
489
  }
532
- this._targetLineIdx = this.logs.length - 1;
533
- return this.logs[this.logs.length - 1];
534
- }
535
490
 
536
- _appendDomLine(line: TerminalLogItem): void {
537
- if (!this.container || typeof document === 'undefined') return;
538
- const logEl = this.container.querySelector('#cl-terminal-log');
539
- if (!logEl) return;
540
- const lineEl = document.createElement('div');
541
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
542
- lineEl.innerHTML = ansiToHtml(line.text);
543
- logEl.appendChild(lineEl);
544
- this._activeLineEl = lineEl;
545
- }
546
-
547
- _updateActiveDomLine(): void {
548
- if (!this.container || typeof document === 'undefined') return;
549
- const line = this._getActiveLineSync();
550
- if (!line) return;
551
- let lineEl = this._activeLineEl;
552
- if (!lineEl || !lineEl.parentNode) {
491
+ _appendDomLine(line) {
492
+ if (!this.container || typeof document === 'undefined') return;
553
493
  const logEl = this.container.querySelector('#cl-terminal-log');
554
- if (logEl) {
555
- if (this._targetLineIdx >= 0 && this._targetLineIdx < logEl.children.length) {
556
- lineEl = logEl.children[this._targetLineIdx];
557
- } else {
558
- lineEl = logEl.children[logEl.children.length - 1];
559
- }
560
- this._activeLineEl = lineEl;
561
- }
562
- }
563
- if (lineEl) {
494
+ if (!logEl) return;
495
+ const lineEl = document.createElement('div');
564
496
  lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
565
497
  lineEl.innerHTML = ansiToHtml(line.text);
498
+ logEl.appendChild(lineEl);
499
+ this._activeLineEl = lineEl;
566
500
  }
567
- }
568
501
 
569
- _getActiveLineSync(): TerminalLogItem | null {
570
- if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
571
- return this.logs[this._targetLineIdx];
572
- }
573
- return this.logs[this.logs.length - 1] || null;
574
- }
575
-
576
- _scrollToBottom(): void {
577
- if (!this.container) return;
578
- const surface = this.container.querySelector('#cl-terminal-surface') || this.container;
579
- if (surface && typeof surface.scrollTop === 'number' && typeof surface.scrollHeight === 'number') {
580
- surface.scrollTop = surface.scrollHeight;
502
+ _updateActiveDomLine() {
503
+ if (!this.container || typeof document === 'undefined') return;
504
+ const line = this._getActiveLineSync();
505
+ if (!line) return;
506
+ let lineEl = this._activeLineEl;
507
+ if (!lineEl || !lineEl.parentNode) {
508
+ const logEl = this.container.querySelector('#cl-terminal-log');
509
+ if (logEl) {
510
+ if (this._targetLineIdx >= 0 && this._targetLineIdx < logEl.children.length) {
511
+ lineEl = logEl.children[this._targetLineIdx];
512
+ } else {
513
+ lineEl = logEl.children[logEl.children.length - 1];
514
+ }
515
+ this._activeLineEl = lineEl;
516
+ }
517
+ }
518
+ if (lineEl) {
519
+ lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
520
+ lineEl.innerHTML = ansiToHtml(line.text);
521
+ }
581
522
  }
582
- }
583
523
 
584
- clear(): void {
585
- this.logs.length = 0;
586
- this._activeLineCommitted = true;
587
- this._cursorCol = 0;
588
- this._targetLineIdx = -1;
589
- this._needsRewrite = false;
590
- this._activeLineEl = null;
591
- if (this.container && typeof this.container.querySelector === 'function') {
592
- const logEl = this.container.querySelector('#cl-terminal-log');
593
- if (logEl) {
594
- logEl.innerHTML = '';
524
+ _getActiveLineSync() {
525
+ if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
526
+ return this.logs[this._targetLineIdx];
595
527
  }
528
+ return this.logs[this.logs.length - 1] || null;
596
529
  }
597
- }
598
-
599
- getHistory(): string[] {
600
- return [...this.history];
601
- }
602
530
 
603
- readLine(promptText: string = ''): Promise<string> {
604
- const prevPrompt = this.promptOverride;
605
- if (promptText) {
606
- this.setPrompt(promptText);
531
+ _scrollToBottom() {
532
+ if (!this.container) return;
533
+ const surface = this.container.querySelector('#cl-terminal-surface') || this.container;
534
+ if (surface && typeof surface.scrollTop === 'number' && typeof surface.scrollHeight === 'number') {
535
+ surface.scrollTop = surface.scrollHeight;
536
+ }
607
537
  }
608
- return new Promise((resolve) => {
609
- this._readLineQueue.push((line: string) => {
610
- this.promptOverride = prevPrompt;
611
- this.updateActiveLine();
612
- resolve(line);
613
- });
614
- });
615
- }
616
538
 
617
- focus(): void {
618
- if (!this.container || typeof this.container.querySelector !== 'function') return;
619
- const input = this.container.querySelector('#cl-repl-input');
620
- if (input && typeof input.focus === 'function') {
621
- try { input.focus(); } catch (_) {}
539
+ clear() {
540
+ this.logs.length = 0;
541
+ this._activeLineCommitted = true;
542
+ this._cursorCol = 0;
543
+ this._targetLineIdx = -1;
544
+ this._needsRewrite = false;
545
+ this._activeLineEl = null;
546
+ if (this.container && typeof this.container.querySelector === 'function') {
547
+ const logEl = this.container.querySelector('#cl-terminal-log');
548
+ if (logEl) {
549
+ logEl.innerHTML = '';
550
+ }
551
+ }
622
552
  }
623
- }
624
553
 
625
- mount(container: any): void {
626
- if (typeof container === 'string' && typeof document !== 'undefined') {
627
- container = document.querySelector(container);
554
+ getHistory() {
555
+ return [...this.history];
628
556
  }
629
- this.container = container || null;
630
- if (!this.container || typeof this.container.querySelector !== 'function') {
631
- this._mounted = false;
632
- return;
633
- }
634
- this._mounted = true;
635
- this.render();
636
- }
637
557
 
638
- _cleanupListeners(): void {
639
- if (!Array.isArray(this._listeners)) {
640
- this._listeners = [];
641
- return;
642
- }
643
- for (const entry of this._listeners) {
644
- if (typeof entry === 'function') {
645
- try { entry(); } catch (_) {}
646
- } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
647
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
558
+ readLine(promptText = '') {
559
+ const prevPrompt = this.promptOverride;
560
+ if (promptText) {
561
+ this.setPrompt(promptText);
648
562
  }
563
+ return new Promise((resolve) => {
564
+ this._readLineQueue.push((line) => {
565
+ this.promptOverride = prevPrompt;
566
+ this.updateActiveLine();
567
+ resolve(line);
568
+ });
569
+ });
649
570
  }
650
- this._listeners = [];
651
- }
652
571
 
653
- destroy(): void {
654
- this._cleanupListeners();
655
- this._mounted = false;
656
- }
657
-
658
- _addListener(target: any, type: string, handler: any): void {
659
- if (target && typeof target.addEventListener === 'function') {
660
- target.addEventListener(type, handler);
661
- this._listeners.push({ target, type, handler });
572
+ focus() {
573
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
574
+ const input = this.container.querySelector('#cl-repl-input');
575
+ if (input && typeof input.focus === 'function') {
576
+ try { input.focus(); } catch (_) {}
577
+ }
662
578
  }
663
- }
664
579
 
665
- _bindEvents(): void {
666
- this._cleanupListeners();
667
- if (!this.container || typeof this.container.querySelector !== 'function') return;
668
- const termSurface = this.container.querySelector('#cl-terminal-surface') || this.container;
669
- const input = this.container.querySelector('#cl-repl-input');
670
- const form = this.container.querySelector('#cl-repl-form');
671
-
672
- if (termSurface) {
673
- this._addListener(termSurface, 'click', (e: any) => {
674
- if (e && e.target === input) return;
675
- const hasSelection = typeof window !== 'undefined' && window.getSelection && String(window.getSelection());
676
- if (!hasSelection) this.focus();
677
- });
580
+ mount(container) {
581
+ if (typeof container === 'string' && typeof document !== 'undefined') {
582
+ container = document.querySelector(container);
583
+ }
584
+ this.container = container || null;
585
+ if (!this.container || typeof this.container.querySelector !== 'function') {
586
+ this._mounted = false;
587
+ return;
588
+ }
589
+ this._mounted = true;
590
+ this.render();
678
591
  }
679
592
 
680
- if (input) {
681
- this._addListener(input, 'keydown', (e: any) => this.handleKeyDown(e));
682
- this._addListener(input, 'input', () => {
683
- if (input.value !== this.buffer) {
684
- this.buffer = input.value;
685
- this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
686
- this.updateActiveLine();
593
+ _cleanupListeners() {
594
+ if (!Array.isArray(this._listeners)) {
595
+ this._listeners = [];
596
+ return;
597
+ }
598
+ for (const entry of this._listeners) {
599
+ if (typeof entry === 'function') {
600
+ try { entry(); } catch (_) {}
601
+ } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
602
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
687
603
  }
688
- });
604
+ }
605
+ this._listeners = [];
689
606
  }
690
607
 
691
- if (form) {
692
- this._addListener(form, 'submit', (e: any) => {
693
- if (e && typeof e.preventDefault === 'function') e.preventDefault();
694
- this.submitLine();
695
- });
608
+ destroy() {
609
+ this._cleanupListeners();
610
+ this._mounted = false;
696
611
  }
697
- }
698
612
 
699
- _findReverseSearchMatch(query: string, startIdx?: number): number {
700
- if (!query || !this.history.length) return -1;
701
- const from = typeof startIdx === 'number' ? Math.min(startIdx, this.history.length - 1) : this.history.length - 1;
702
- for (let i = from; i >= 0; i--) {
703
- if (this.history[i] && this.history[i].includes(query)) {
704
- return i;
613
+ _addListener(target, type, handler) {
614
+ if (target && typeof target.addEventListener === 'function') {
615
+ target.addEventListener(type, handler);
616
+ this._listeners.push({ target, type, handler });
705
617
  }
706
618
  }
707
- return -1;
708
- }
709
619
 
710
- handleKeyDown(e: any): void {
711
- if (!e) return;
712
- if (this.onKey) {
713
- try {
714
- const res = this.onKey(e);
715
- if (res === false) return;
716
- } catch (_) {}
717
- }
620
+ _bindEvents() {
621
+ this._cleanupListeners();
622
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
623
+ const termSurface = this.container.querySelector('#cl-terminal-surface') || this.container;
624
+ const input = this.container.querySelector('#cl-repl-input');
625
+ const form = this.container.querySelector('#cl-repl-form');
626
+
627
+ if (termSurface) {
628
+ this._addListener(termSurface, 'click', (e) => {
629
+ if (e && e.target === input) return;
630
+ const hasSelection = typeof window !== 'undefined' && window.getSelection && String(window.getSelection());
631
+ if (!hasSelection) this.focus();
632
+ });
633
+ }
718
634
 
719
- const key = e.key;
720
- const isCtrl = Boolean(e.ctrlKey || e.metaKey);
635
+ if (input) {
636
+ this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
637
+ this._addListener(input, 'input', () => {
638
+ if (input.value !== this.buffer) {
639
+ this.buffer = input.value;
640
+ this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
641
+ this.updateActiveLine();
642
+ }
643
+ });
644
+ }
721
645
 
722
- if (isCtrl && (key === 'r' || key === 'R')) {
723
- if (e.preventDefault) e.preventDefault();
724
- if (!this.searchMode) {
725
- this.searchMode = true;
726
- this.searchQuery = '';
727
- this.searchMatchIdx = -1;
728
- } else if (this.searchQuery) {
729
- const nextStart = this.searchMatchIdx > 0 ? this.searchMatchIdx - 1 : this.history.length - 1;
730
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, nextStart);
731
- if (matchIdx !== -1) {
732
- this.searchMatchIdx = matchIdx;
733
- this.buffer = this.history[matchIdx];
734
- this.cursor = this.buffer.length;
646
+ if (form) {
647
+ this._addListener(form, 'submit', (e) => {
648
+ if (e && typeof e.preventDefault === 'function') e.preventDefault();
649
+ this.submitLine();
650
+ });
651
+ }
652
+ }
653
+
654
+ _findReverseSearchMatch(query, startIdx) {
655
+ if (!query || !this.history.length) return -1;
656
+ const from = typeof startIdx === 'number' ? Math.min(startIdx, this.history.length - 1) : this.history.length - 1;
657
+ for (let i = from; i >= 0; i--) {
658
+ if (this.history[i] && this.history[i].includes(query)) {
659
+ return i;
735
660
  }
736
661
  }
737
- this.updateActiveLine();
738
- return;
662
+ return -1;
739
663
  }
740
664
 
741
- if (this.searchMode) {
742
- if (key === 'Escape' || (isCtrl && (key === 'g' || key === 'G'))) {
743
- if (e.preventDefault) e.preventDefault();
744
- this.searchMode = false;
745
- this.searchQuery = '';
746
- this.searchMatchIdx = -1;
747
- this.updateActiveLine();
748
- return;
665
+ handleKeyDown(e) {
666
+ if (!e) return;
667
+ if (this.onKey) {
668
+ try {
669
+ const res = this.onKey(e);
670
+ if (res === false) return;
671
+ } catch (_) {}
749
672
  }
750
- if (key === 'Backspace') {
673
+
674
+ const key = e.key;
675
+ const isCtrl = Boolean(e.ctrlKey || e.metaKey);
676
+
677
+ if (isCtrl && (key === 'r' || key === 'R')) {
751
678
  if (e.preventDefault) e.preventDefault();
752
- this.searchQuery = this.searchQuery.slice(0, -1);
753
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
754
- this.searchMatchIdx = matchIdx;
755
- if (matchIdx !== -1) {
756
- this.buffer = this.history[matchIdx];
757
- this.cursor = this.buffer.length;
679
+ if (!this.searchMode) {
680
+ this.searchMode = true;
681
+ this.searchQuery = '';
682
+ this.searchMatchIdx = -1;
683
+ } else if (this.searchQuery) {
684
+ const nextStart = this.searchMatchIdx > 0 ? this.searchMatchIdx - 1 : this.history.length - 1;
685
+ const matchIdx = this._findReverseSearchMatch(this.searchQuery, nextStart);
686
+ if (matchIdx !== -1) {
687
+ this.searchMatchIdx = matchIdx;
688
+ this.buffer = this.history[matchIdx];
689
+ this.cursor = this.buffer.length;
690
+ }
758
691
  }
759
692
  this.updateActiveLine();
760
693
  return;
761
694
  }
762
- if (key === 'Enter') {
763
- if (e.preventDefault) e.preventDefault();
695
+
696
+ if (this.searchMode) {
697
+ if (key === 'Escape' || (isCtrl && (key === 'g' || key === 'G'))) {
698
+ if (e.preventDefault) e.preventDefault();
699
+ this.searchMode = false;
700
+ this.searchQuery = '';
701
+ this.searchMatchIdx = -1;
702
+ this.updateActiveLine();
703
+ return;
704
+ }
705
+ if (key === 'Backspace') {
706
+ if (e.preventDefault) e.preventDefault();
707
+ this.searchQuery = this.searchQuery.slice(0, -1);
708
+ const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
709
+ this.searchMatchIdx = matchIdx;
710
+ if (matchIdx !== -1) {
711
+ this.buffer = this.history[matchIdx];
712
+ this.cursor = this.buffer.length;
713
+ }
714
+ this.updateActiveLine();
715
+ return;
716
+ }
717
+ if (key === 'Enter') {
718
+ if (e.preventDefault) e.preventDefault();
719
+ this.searchMode = false;
720
+ this.searchQuery = '';
721
+ this.searchMatchIdx = -1;
722
+ this.submitLine();
723
+ return;
724
+ }
725
+ if (key && key.length === 1 && !isCtrl && !e.altKey) {
726
+ if (e.preventDefault) e.preventDefault();
727
+ this.searchQuery += key;
728
+ const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
729
+ this.searchMatchIdx = matchIdx;
730
+ if (matchIdx !== -1) {
731
+ this.buffer = this.history[matchIdx];
732
+ this.cursor = this.buffer.length;
733
+ }
734
+ this.updateActiveLine();
735
+ return;
736
+ }
764
737
  this.searchMode = false;
765
738
  this.searchQuery = '';
766
739
  this.searchMatchIdx = -1;
767
- this.submitLine();
740
+ }
741
+
742
+ if (key === 'ArrowLeft') {
743
+ if (e.preventDefault) e.preventDefault();
744
+ if (this.cursor > 0) {
745
+ this.cursor--;
746
+ this.updateActiveLine();
747
+ }
768
748
  return;
769
749
  }
770
- if (key && key.length === 1 && !isCtrl && !e.altKey) {
750
+
751
+ if (key === 'ArrowRight') {
771
752
  if (e.preventDefault) e.preventDefault();
772
- this.searchQuery += key;
773
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
774
- this.searchMatchIdx = matchIdx;
775
- if (matchIdx !== -1) {
776
- this.buffer = this.history[matchIdx];
777
- this.cursor = this.buffer.length;
753
+ if (this.cursor < this.buffer.length) {
754
+ this.cursor++;
755
+ this.updateActiveLine();
778
756
  }
779
- this.updateActiveLine();
780
757
  return;
781
758
  }
782
- this.searchMode = false;
783
- this.searchQuery = '';
784
- this.searchMatchIdx = -1;
785
- }
786
759
 
787
- if (key === 'ArrowLeft') {
788
- if (e.preventDefault) e.preventDefault();
789
- if (this.cursor > 0) {
790
- this.cursor--;
760
+ if (key === 'Home' || (isCtrl && (key === 'a' || key === 'A'))) {
761
+ if (e.preventDefault) e.preventDefault();
762
+ this.cursor = 0;
791
763
  this.updateActiveLine();
764
+ return;
792
765
  }
793
- return;
794
- }
795
766
 
796
- if (key === 'ArrowRight') {
797
- if (e.preventDefault) e.preventDefault();
798
- if (this.cursor < this.buffer.length) {
799
- this.cursor++;
767
+ if (key === 'End' || (isCtrl && (key === 'e' || key === 'E'))) {
768
+ if (e.preventDefault) e.preventDefault();
769
+ this.cursor = this.buffer.length;
800
770
  this.updateActiveLine();
771
+ return;
801
772
  }
802
- return;
803
- }
804
773
 
805
- if (key === 'Home' || (isCtrl && (key === 'a' || key === 'A'))) {
806
- if (e.preventDefault) e.preventDefault();
807
- this.cursor = 0;
808
- this.updateActiveLine();
809
- return;
810
- }
811
-
812
- if (key === 'End' || (isCtrl && (key === 'e' || key === 'E'))) {
813
- if (e.preventDefault) e.preventDefault();
814
- this.cursor = this.buffer.length;
815
- this.updateActiveLine();
816
- return;
817
- }
818
-
819
- if (isCtrl && (key === 'u' || key === 'U')) {
820
- if (e.preventDefault) e.preventDefault();
821
- this.buffer = this.buffer.slice(this.cursor);
822
- this.cursor = 0;
823
- this.updateActiveLine();
824
- return;
825
- }
826
-
827
- if (isCtrl && (key === 'k' || key === 'K')) {
828
- if (e.preventDefault) e.preventDefault();
829
- this.buffer = this.buffer.slice(0, this.cursor);
830
- this.updateActiveLine();
831
- return;
832
- }
833
-
834
- if (key === 'Backspace') {
835
- if (e.preventDefault) e.preventDefault();
836
- if (this.cursor > 0) {
837
- this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
838
- this.cursor--;
774
+ if (isCtrl && (key === 'u' || key === 'U')) {
775
+ if (e.preventDefault) e.preventDefault();
776
+ this.buffer = this.buffer.slice(this.cursor);
777
+ this.cursor = 0;
839
778
  this.updateActiveLine();
779
+ return;
840
780
  }
841
- return;
842
- }
843
781
 
844
- if (key === 'Delete') {
845
- if (e.preventDefault) e.preventDefault();
846
- if (this.cursor < this.buffer.length) {
847
- this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
782
+ if (isCtrl && (key === 'k' || key === 'K')) {
783
+ if (e.preventDefault) e.preventDefault();
784
+ this.buffer = this.buffer.slice(0, this.cursor);
848
785
  this.updateActiveLine();
786
+ return;
849
787
  }
850
- return;
851
- }
852
788
 
853
- if (isCtrl && (key === 'l' || key === 'L')) {
854
- if (e.preventDefault) e.preventDefault();
855
- this.clear();
856
- return;
857
- }
789
+ if (key === 'Backspace') {
790
+ if (e.preventDefault) e.preventDefault();
791
+ if (this.cursor > 0) {
792
+ this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
793
+ this.cursor--;
794
+ this.updateActiveLine();
795
+ }
796
+ return;
797
+ }
858
798
 
859
- if (isCtrl && (key === 'c' || key === 'C')) {
860
- if (e.preventDefault) e.preventDefault();
861
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
862
- this.buffer = '';
863
- this.cursor = 0;
864
- this.historyIdx = -1;
865
- if (this.replMode) {
866
- this.replMode = false;
799
+ if (key === 'Delete') {
800
+ if (e.preventDefault) e.preventDefault();
801
+ if (this.cursor < this.buffer.length) {
802
+ this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
803
+ this.updateActiveLine();
804
+ }
805
+ return;
867
806
  }
868
- if (this.onInterrupt) {
869
- try { this.onInterrupt(); } catch (_) {}
807
+
808
+ if (isCtrl && (key === 'l' || key === 'L')) {
809
+ if (e.preventDefault) e.preventDefault();
810
+ this.clear();
811
+ return;
870
812
  }
871
- this.render();
872
- return;
873
- }
874
813
 
875
- if (isCtrl && (key === 'd' || key === 'D')) {
876
- if (this.buffer === '') {
814
+ if (isCtrl && (key === 'c' || key === 'C')) {
877
815
  if (e.preventDefault) e.preventDefault();
816
+ this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
817
+ this.buffer = '';
818
+ this.cursor = 0;
819
+ this.historyIdx = -1;
878
820
  if (this.replMode) {
879
- this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
880
821
  this.replMode = false;
881
- this.render();
882
- return;
883
822
  }
823
+ if (this.onInterrupt) {
824
+ try { this.onInterrupt(); } catch (_) {}
825
+ }
826
+ this.render();
827
+ return;
884
828
  }
885
- }
886
829
 
887
- if (key === 'ArrowUp') {
888
- if (e.preventDefault) e.preventDefault();
889
- if (!this.history.length) return;
890
- if (this.historyIdx === -1) {
891
- this.savedBuffer = this.buffer;
892
- this.historyIdx = this.history.length - 1;
893
- } else if (this.historyIdx > 0) {
894
- this.historyIdx--;
830
+ if (isCtrl && (key === 'd' || key === 'D')) {
831
+ if (this.buffer === '') {
832
+ if (e.preventDefault) e.preventDefault();
833
+ if (this.replMode) {
834
+ this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
835
+ this.replMode = false;
836
+ this.render();
837
+ return;
838
+ }
839
+ }
895
840
  }
896
- this.buffer = this.history[this.historyIdx] || '';
897
- this.cursor = this.buffer.length;
898
- this.updateActiveLine();
899
- return;
900
- }
901
841
 
902
- if (key === 'ArrowDown') {
903
- if (e.preventDefault) e.preventDefault();
904
- if (this.historyIdx !== -1) {
905
- if (this.historyIdx < this.history.length - 1) {
906
- this.historyIdx++;
907
- this.buffer = this.history[this.historyIdx] || '';
908
- } else {
909
- this.historyIdx = -1;
910
- this.buffer = this.savedBuffer || '';
842
+ if (key === 'ArrowUp') {
843
+ if (e.preventDefault) e.preventDefault();
844
+ if (!this.history.length) return;
845
+ if (this.historyIdx === -1) {
846
+ this.savedBuffer = this.buffer;
847
+ this.historyIdx = this.history.length - 1;
848
+ } else if (this.historyIdx > 0) {
849
+ this.historyIdx--;
911
850
  }
851
+ this.buffer = this.history[this.historyIdx] || '';
912
852
  this.cursor = this.buffer.length;
913
853
  this.updateActiveLine();
854
+ return;
914
855
  }
915
- return;
916
- }
917
856
 
918
- if (key === 'Tab') {
919
- if (e.preventDefault) e.preventDefault();
920
- this.autoComplete();
921
- return;
922
- }
857
+ if (key === 'ArrowDown') {
858
+ if (e.preventDefault) e.preventDefault();
859
+ if (this.historyIdx !== -1) {
860
+ if (this.historyIdx < this.history.length - 1) {
861
+ this.historyIdx++;
862
+ this.buffer = this.history[this.historyIdx] || '';
863
+ } else {
864
+ this.historyIdx = -1;
865
+ this.buffer = this.savedBuffer || '';
866
+ }
867
+ this.cursor = this.buffer.length;
868
+ this.updateActiveLine();
869
+ }
870
+ return;
871
+ }
923
872
 
924
- if (key === 'Enter') {
925
- if (e.preventDefault) e.preventDefault();
926
- this.submitLine();
927
- return;
928
- }
873
+ if (key === 'Tab') {
874
+ if (e.preventDefault) e.preventDefault();
875
+ this.autoComplete();
876
+ return;
877
+ }
929
878
 
930
- // Printable character
931
- if (key && key.length === 1 && !isCtrl && !e.altKey) {
932
- if (e.preventDefault) e.preventDefault();
933
- this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
934
- this.cursor++;
935
- this.updateActiveLine();
936
- }
937
- }
879
+ if (key === 'Enter') {
880
+ if (e.preventDefault) e.preventDefault();
881
+ this.submitLine();
882
+ return;
883
+ }
938
884
 
939
- autoComplete(): void {
940
- if (!this.getCompletions) return;
941
- const res = this.getCompletions(this.buffer, this.cursor);
942
- if (!res || !Array.isArray(res.matches) || res.matches.length === 0) return;
943
-
944
- const matches = res.matches;
945
- if (matches.length === 1) {
946
- const match = matches[0];
947
- const isDir = match.endsWith('/');
948
- const appendChar = isDir ? '' : ' ';
949
- const before = this.buffer.slice(0, res.tokenStart);
950
- const after = this.buffer.slice(this.cursor);
951
- this.buffer = before + match + appendChar + after;
952
- this.cursor = before.length + match.length + appendChar.length;
953
- this.updateActiveLine();
954
- } else {
955
- // Find longest common prefix
956
- let lcp = matches[0];
957
- for (let i = 1; i < matches.length; i++) {
958
- let j = 0;
959
- while (j < lcp.length && j < matches[i].length && lcp[j] === matches[i][j]) {
960
- j++;
961
- }
962
- lcp = lcp.slice(0, j);
885
+ // Printable character
886
+ if (key && key.length === 1 && !isCtrl && !e.altKey) {
887
+ if (e.preventDefault) e.preventDefault();
888
+ this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
889
+ this.cursor++;
890
+ this.updateActiveLine();
963
891
  }
892
+ }
893
+
894
+ autoComplete() {
895
+ if (!this.getCompletions) return;
896
+ const res = this.getCompletions(this.buffer, this.cursor);
897
+ if (!res || !Array.isArray(res.matches) || res.matches.length === 0) return;
964
898
 
965
- if (lcp.length > res.token.length) {
899
+ const matches = res.matches;
900
+ if (matches.length === 1) {
901
+ const match = matches[0];
902
+ const isDir = match.endsWith('/');
903
+ const appendChar = isDir ? '' : ' ';
966
904
  const before = this.buffer.slice(0, res.tokenStart);
967
905
  const after = this.buffer.slice(this.cursor);
968
- this.buffer = before + lcp + after;
969
- this.cursor = before.length + lcp.length;
970
- }
906
+ this.buffer = before + match + appendChar + after;
907
+ this.cursor = before.length + match.length + appendChar.length;
908
+ this.updateActiveLine();
909
+ } else {
910
+ // Find longest common prefix
911
+ let lcp = matches[0];
912
+ for (let i = 1; i < matches.length; i++) {
913
+ let j = 0;
914
+ while (j < lcp.length && j < matches[i].length && lcp[j] === matches[i][j]) {
915
+ j++;
916
+ }
917
+ lcp = lcp.slice(0, j);
918
+ }
971
919
 
972
- // Print candidate matches
973
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
974
- this.logs.push({ type: 'stdout', text: matches.join(' ') });
975
- this.render();
976
- }
977
- }
920
+ if (lcp.length > res.token.length) {
921
+ const before = this.buffer.slice(0, res.tokenStart);
922
+ const after = this.buffer.slice(this.cursor);
923
+ this.buffer = before + lcp + after;
924
+ this.cursor = before.length + lcp.length;
925
+ }
978
926
 
979
- submitLine(): void {
980
- const line = this.buffer;
981
- this.buffer = '';
982
- this.cursor = 0;
983
- this.historyIdx = -1;
984
- this.searchMode = false;
985
- this.searchQuery = '';
986
- this.searchMatchIdx = -1;
987
-
988
- if (line.trim()) {
989
- if (this.history[this.history.length - 1] !== line.trim()) {
990
- this.history.push(line.trim());
927
+ // Print candidate matches
928
+ this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
929
+ this.logs.push({ type: 'stdout', text: matches.join(' ') });
930
+ this.render();
991
931
  }
992
932
  }
993
933
 
994
- if (this._readLineQueue && this._readLineQueue.length > 0) {
995
- const resolver = this._readLineQueue.shift();
996
- this.updateActiveLine();
997
- if (resolver) resolver(line);
998
- return;
999
- }
934
+ submitLine() {
935
+ const line = this.buffer;
936
+ this.buffer = '';
937
+ this.cursor = 0;
938
+ this.historyIdx = -1;
939
+ this.searchMode = false;
940
+ this.searchQuery = '';
941
+ this.searchMatchIdx = -1;
1000
942
 
1001
- this.updateActiveLine();
1002
- if (this.onCommand) {
1003
- this.onCommand(line);
1004
- }
1005
- }
943
+ if (line.trim()) {
944
+ if (this.history[this.history.length - 1] !== line.trim()) {
945
+ this.history.push(line.trim());
946
+ }
947
+ }
948
+
949
+ if (this._readLineQueue && this._readLineQueue.length > 0) {
950
+ const resolver = this._readLineQueue.shift();
951
+ this.updateActiveLine();
952
+ resolver(line);
953
+ return;
954
+ }
1006
955
 
1007
- updateActiveLine(): void {
1008
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1009
- const input = this.container.querySelector('#cl-repl-input');
1010
- if (input && input.value !== this.buffer) {
1011
- input.value = this.buffer;
956
+ this.updateActiveLine();
957
+ if (this.onCommand) {
958
+ this.onCommand(line);
959
+ }
1012
960
  }
1013
- const lineEl = this.container.querySelector('#cl-pty-active-line');
1014
- if (!lineEl) return;
1015
961
 
1016
- const prompt = this.searchMode
1017
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1018
- : this.getPrompt();
1019
- const before = this.buffer.slice(0, this.cursor);
1020
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1021
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
962
+ updateActiveLine() {
963
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
964
+ const input = this.container.querySelector('#cl-repl-input');
965
+ if (input && input.value !== this.buffer) {
966
+ input.value = this.buffer;
967
+ }
968
+ const lineEl = this.container.querySelector('#cl-pty-active-line');
969
+ if (!lineEl) return;
1022
970
 
1023
- 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>`;
1024
- }
971
+ const prompt = this.searchMode
972
+ ? `(reverse-i-search)\`${this.searchQuery}\`: `
973
+ : this.getPrompt();
974
+ const before = this.buffer.slice(0, this.cursor);
975
+ const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
976
+ const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1025
977
 
1026
- render(): void {
1027
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1028
- const prevInput = this.container.querySelector('#cl-repl-input');
1029
- const hadFocus = Boolean(
1030
- prevInput &&
1031
- typeof document !== 'undefined' &&
1032
- document.activeElement === prevInput
1033
- );
1034
-
1035
- const logsHtml = this.logs
1036
- .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
1037
- .join('');
1038
-
1039
- const prompt = this.searchMode
1040
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1041
- : this.getPrompt();
1042
- const before = this.buffer.slice(0, this.cursor);
1043
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1044
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1045
-
1046
- this.container.innerHTML = `
1047
- <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1048
- <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1049
- <div class="codelab-pty__active-line" id="cl-pty-active-line">
1050
- <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>
978
+ 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>`;
979
+ }
980
+
981
+ render() {
982
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
983
+ const prevInput = this.container.querySelector('#cl-repl-input');
984
+ const hadFocus = Boolean(
985
+ prevInput &&
986
+ typeof document !== 'undefined' &&
987
+ document.activeElement === prevInput
988
+ );
989
+
990
+ const logsHtml = this.logs
991
+ .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
992
+ .join('');
993
+
994
+ const prompt = this.searchMode
995
+ ? `(reverse-i-search)\`${this.searchQuery}\`: `
996
+ : this.getPrompt();
997
+ const before = this.buffer.slice(0, this.cursor);
998
+ const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
999
+ const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1000
+
1001
+ this.container.innerHTML = `
1002
+ <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1003
+ <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1004
+ <div class="codelab-pty__active-line" id="cl-pty-active-line">
1005
+ <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>
1006
+ </div>
1007
+ <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1008
+ <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
1009
+ </form>
1051
1010
  </div>
1052
- <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1053
- <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
1054
- </form>
1055
- </div>
1056
- `;
1011
+ `;
1057
1012
 
1058
- this._scrollToBottom();
1013
+ this._scrollToBottom();
1059
1014
 
1060
- this._bindEvents();
1015
+ this._bindEvents();
1061
1016
 
1062
- if (hadFocus) {
1063
- const nextInput = this.container.querySelector('#cl-repl-input');
1064
- if (nextInput && typeof nextInput.focus === 'function') {
1065
- try {
1066
- nextInput.focus();
1067
- if (typeof nextInput.setSelectionRange === 'function') {
1068
- nextInput.setSelectionRange(this.cursor, this.cursor);
1069
- }
1070
- } catch (_) {}
1017
+ if (hadFocus) {
1018
+ const nextInput = this.container.querySelector('#cl-repl-input');
1019
+ if (nextInput && typeof nextInput.focus === 'function') {
1020
+ try {
1021
+ nextInput.focus();
1022
+ if (typeof nextInput.setSelectionRange === 'function') {
1023
+ nextInput.setSelectionRange(this.cursor, this.cursor);
1024
+ }
1025
+ } catch (_) {}
1026
+ }
1071
1027
  }
1072
1028
  }
1073
1029
  }
1074
- }
1075
-
1076
- export function createTerminal(container?: any, options: TerminalOptions = {}): PTYTerminalEngine {
1077
- return new PTYTerminalEngine(container, options);
1078
- }
1079
-
1080
- export const createPTYTerminalEngine = createTerminal;
1081
-
1082
- // Global browser attaching if in browser environment
1083
- if (typeof globalThis !== 'undefined') {
1084
- const g = globalThis as any;
1085
- if (!g.CodeLabTerminal) {
1086
- g.CodeLabTerminal = {
1087
- PTYTerminalEngine,
1088
- createPTYTerminalEngine,
1089
- createTerminal,
1090
- ansiToHtml,
1091
- parseAnsiToHtml,
1092
- escapeHtml,
1093
- ANSI_CODE_MAP,
1094
- resolveAnsiControlCodes
1095
- };
1030
+
1031
+ function createTerminal(container, options = {}) {
1032
+ return new PTYTerminalEngine(container, options);
1096
1033
  }
1097
- }
1034
+
1035
+ const createPTYTerminalEngine = createTerminal;
1036
+
1037
+ return {
1038
+ PTYTerminalEngine,
1039
+ createPTYTerminalEngine,
1040
+ createTerminal,
1041
+ ansiToHtml,
1042
+ parseAnsiToHtml,
1043
+ escapeHtml,
1044
+ ANSI_CODE_MAP,
1045
+ resolveAnsiControlCodes
1046
+ };
1047
+ });
1048
+
1049
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
1050
+ const _hostTerminal: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabTerminal : undefined)
1051
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
1052
+
1053
+ export const ANSI_CODE_MAP: Record<number, string> = _hostTerminal.ANSI_CODE_MAP;
1054
+ export const ansi256ToColor: (n: number | string) => string | null = _hostTerminal.ansi256ToColor;
1055
+ export const escapeHtml: (str: any) => string = _hostTerminal.escapeHtml;
1056
+ export const resolveAnsiControlCodes: (raw: any) => string = _hostTerminal.resolveAnsiControlCodes;
1057
+ export const ansiToHtml: (str: any) => string = _hostTerminal.ansiToHtml;
1058
+ export const parseAnsiToHtml: (str: any) => string = _hostTerminal.parseAnsiToHtml;
1059
+ export const PTYTerminalEngine: any = _hostTerminal.PTYTerminalEngine;
1060
+ export const createTerminal: (container?: any, options?: any) => any = _hostTerminal.createTerminal;
1061
+ export const createPTYTerminalEngine: (container?: any, options?: any) => any = _hostTerminal.createPTYTerminalEngine;
1062
+
1063
+ export default _hostTerminal;