@x-otto/tui-screen 0.0.0-stage → 0.4.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ {
2
+ "version": 1,
3
+ "revision": "e448f39f717510ddf03a678c46426906"
4
+ }
@@ -0,0 +1,115 @@
1
+ //#region src/cursor.d.ts
2
+ declare function charDisplayWidth(char: string): number;
3
+ declare function stringWidth(input: string): number;
4
+ //#endregion
5
+ //#region src/screen-buffer.d.ts
6
+ interface Cell {
7
+ ch: string;
8
+ style: string;
9
+ width: 0 | 1 | 2;
10
+ link?: string;
11
+ }
12
+ //#endregion
13
+ //#region src/screen-buffer-store.d.ts
14
+ interface Damage {
15
+ top: number;
16
+ bottom: number;
17
+ }
18
+ declare const CURSOR_BURST_FLOOR_MS = 200;
19
+ declare const CURSOR_BURST_PERIOD_MULTIPLE = 2.5;
20
+ declare function computeBurstQuietMs(minAnimationPeriodMs: number | undefined): number;
21
+ interface ScreenBufferOptions {
22
+ frameTop?: number;
23
+ parseEveryLine?: boolean;
24
+ minAnimationPeriod?: () => number | undefined;
25
+ }
26
+ type SelectionQuery = (row: number, col: number) => boolean;
27
+ declare class ScreenBuffer {
28
+ private readonly minAnimationPeriod;
29
+ private readonly frameTop;
30
+ private readonly parseEveryLine;
31
+ private needsAnchor;
32
+ private rows;
33
+ private rawLines;
34
+ private parsedLineCount;
35
+ private damageTop;
36
+ private damageBottom;
37
+ private maxLineWidth;
38
+ private selectionQuery;
39
+ private screenRows;
40
+ private prevLineCount;
41
+ private prevCursor;
42
+ private cursorShown;
43
+ private lastRedrawAt;
44
+ constructor(options?: ScreenBufferOptions);
45
+ setSelectionQuery(query: SelectionQuery | undefined): void;
46
+ setScreenRows(rows: number): void;
47
+ buildSelectionRepaint(rows: readonly number[]): string;
48
+ resync(): void;
49
+ repaintSequence(cursor?: {
50
+ x: number;
51
+ y: number;
52
+ }, now?: number): string;
53
+ private burstQuietMs;
54
+ get height(): number;
55
+ lineAt(row: number): readonly Cell[] | undefined;
56
+ takeDamage(): Damage | null;
57
+ private markDirty;
58
+ markAllDirty(): void;
59
+ invalidate(): void;
60
+ setMaxLineWidth(columns: number): void;
61
+ private clampToMaxWidth;
62
+ ingest(frame: string): void;
63
+ parsedLines(): number;
64
+ bookkeeping(): {
65
+ prevLineCount: number;
66
+ prevCursor: {
67
+ x: number;
68
+ y: number;
69
+ } | undefined;
70
+ cursorShown: boolean;
71
+ };
72
+ buildCursorOnlySequence(cursor?: {
73
+ x: number;
74
+ y: number;
75
+ }, now?: number): string;
76
+ flushSequence(damage: Damage, cursor?: {
77
+ x: number;
78
+ y: number;
79
+ }, now?: number): string;
80
+ renderLine(row: number): string;
81
+ }
82
+ //#endregion
83
+ //#region src/alt-screen.d.ts
84
+ declare const ENTER_ALT_SCREEN = "\u001B[?1049h";
85
+ declare const EXIT_ALT_SCREEN = "\u001B[?1049l";
86
+ interface AltScreenController {
87
+ readonly active: boolean;
88
+ enter(): void;
89
+ exit(): void;
90
+ }
91
+ declare function createAltScreenController(stream: NodeJS.WriteStream): AltScreenController;
92
+ declare function eraseLastFrame(lineCount: number): string;
93
+ //#endregion
94
+ //#region src/restore-guard.d.ts
95
+ interface ProcessRestoreTarget {
96
+ pid: number;
97
+ once(event: 'exit', listener: () => void): unknown;
98
+ on(event: string, listener: (...args: unknown[]) => void): unknown;
99
+ off(event: string, listener: (...args: unknown[]) => void): unknown;
100
+ kill(pid: number, signal: NodeJS.Signals): boolean;
101
+ }
102
+ interface RestoreGuardHooks {
103
+ restore(): void;
104
+ resume?(): void;
105
+ onFatal?(phase: 'uncaughtException' | 'unhandledRejection', error: unknown): void;
106
+ onRejection?(reason: unknown): void;
107
+ }
108
+ interface RestoreGuard {
109
+ readonly active: boolean;
110
+ dispose(): void;
111
+ }
112
+ declare function isTerminalGone(error: unknown): boolean;
113
+ declare function installRestoreGuard(hooks: RestoreGuardHooks, target?: ProcessRestoreTarget): RestoreGuard;
114
+ //#endregion
115
+ export { type AltScreenController, CURSOR_BURST_FLOOR_MS, CURSOR_BURST_PERIOD_MULTIPLE, type Cell, type Damage, ENTER_ALT_SCREEN, EXIT_ALT_SCREEN, type ProcessRestoreTarget, type RestoreGuard, type RestoreGuardHooks, ScreenBuffer, type ScreenBufferOptions, type SelectionQuery, charDisplayWidth, computeBurstQuietMs, createAltScreenController, eraseLastFrame, installRestoreGuard, isTerminalGone, stringWidth };
package/dist/index.js ADDED
@@ -0,0 +1,568 @@
1
+ import stringWidthOf from "string-width";
2
+
3
+ //#region src/cursor.ts
4
+ function charDisplayWidth(char) {
5
+ return stringWidthOf(char);
6
+ }
7
+ function stringWidth(input) {
8
+ return stringWidthOf(input);
9
+ }
10
+
11
+ //#endregion
12
+ //#region src/screen-buffer.ts
13
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
14
+ const TAB_STOP = 8;
15
+ const ESC_CHAR = String.fromCharCode(27);
16
+ const SGR_RE = new RegExp(ESC_CHAR + "\\[[0-9;]*m", "y");
17
+ const OSC_RE = new RegExp(ESC_CHAR + "\\][^\x07\x1B]*(?:\x07|\x1B\\\\)", "y");
18
+ const OSC8_RE = new RegExp("^" + ESC_CHAR + "\\]8;[^;]*;([^\x07\x1B]*)(?:\x07|\x1B\\\\)$");
19
+ const ESC_SEQ_RE = new RegExp(ESC_CHAR + "\\[[\\d;?]*[ -/]*[@-~]|\x1B[P_^X][^\x07\x1B]*(?:\x07|\x1B\\\\)|\x1B[@-Z\\\\^_0-9=><]", "y");
20
+ const OSC8_CLOSE = "\x1B]8;;\x1B\\";
21
+ const PRINTABLE_ASCII = /^[\x20-\x7e]*$/;
22
+ function parseLine(line) {
23
+ const cells = [];
24
+ let style = "";
25
+ let link;
26
+ let i = 0;
27
+ let gridCol = 0;
28
+ const pushText = (text) => {
29
+ if (PRINTABLE_ASCII.test(text)) {
30
+ for (let index = 0; index < text.length; index += 1) cells.push({
31
+ ch: text[index],
32
+ style,
33
+ width: 1,
34
+ link
35
+ });
36
+ gridCol += text.length;
37
+ return;
38
+ }
39
+ for (const { segment } of segmenter.segment(text)) {
40
+ if (segment === " ") {
41
+ const tabWidth = TAB_STOP - gridCol % TAB_STOP;
42
+ for (let k = 0; k < tabWidth; k += 1) cells.push({
43
+ ch: " ",
44
+ style,
45
+ width: 1,
46
+ link
47
+ });
48
+ gridCol += tabWidth;
49
+ continue;
50
+ }
51
+ if (isControlSegment(segment)) continue;
52
+ const w = stringWidth(segment);
53
+ if (w === 0) {
54
+ const previous = cells[cells.length - 1];
55
+ if (previous !== void 0 && previous.width > 0) previous.ch += segment;
56
+ else cells.push({
57
+ ch: segment,
58
+ style,
59
+ width: 0,
60
+ link
61
+ });
62
+ continue;
63
+ }
64
+ if (w === 2) {
65
+ cells.push({
66
+ ch: segment,
67
+ style,
68
+ width: 2,
69
+ link
70
+ });
71
+ cells.push({
72
+ ch: "",
73
+ style,
74
+ width: 0,
75
+ link
76
+ });
77
+ gridCol += 2;
78
+ } else {
79
+ cells.push({
80
+ ch: segment,
81
+ style,
82
+ width: 1,
83
+ link
84
+ });
85
+ gridCol += 1;
86
+ }
87
+ }
88
+ };
89
+ while (i < line.length) {
90
+ if (line.charCodeAt(i) === 27) {
91
+ SGR_RE.lastIndex = i;
92
+ const sgr = SGR_RE.exec(line);
93
+ if (sgr) {
94
+ const seq = sgr[0];
95
+ style = /\x1b\[0?m/.test(seq) ? "" : style + seq;
96
+ i = SGR_RE.lastIndex;
97
+ continue;
98
+ }
99
+ OSC_RE.lastIndex = i;
100
+ const osc = OSC_RE.exec(line);
101
+ if (osc) {
102
+ const hit = OSC8_RE.exec(osc[0]);
103
+ if (hit) link = hit[1] !== void 0 && hit[1] !== "" ? osc[0] : void 0;
104
+ i = OSC_RE.lastIndex;
105
+ continue;
106
+ }
107
+ ESC_SEQ_RE.lastIndex = i;
108
+ if (ESC_SEQ_RE.exec(line)) {
109
+ i = ESC_SEQ_RE.lastIndex;
110
+ continue;
111
+ }
112
+ break;
113
+ }
114
+ let end = line.indexOf(ESC_CHAR, i);
115
+ if (end < 0) end = line.length;
116
+ pushText(line.slice(i, end));
117
+ i = end;
118
+ }
119
+ return cells;
120
+ }
121
+ function isControlSegment(segment) {
122
+ for (const char of segment) {
123
+ const code = char.codePointAt(0) ?? 0;
124
+ if (code < 32 || code === 127) return true;
125
+ }
126
+ return false;
127
+ }
128
+ function renderCells(cells) {
129
+ let out = "";
130
+ let style = "";
131
+ let link;
132
+ for (const cell of cells) {
133
+ if (cell.width === 0) continue;
134
+ if (cell.link !== link) {
135
+ if (link !== void 0) out += OSC8_CLOSE;
136
+ if (cell.link !== void 0) out += cell.link;
137
+ link = cell.link;
138
+ }
139
+ if (cell.style !== style) {
140
+ out += "\x1B[0m";
141
+ out += cell.style;
142
+ style = cell.style;
143
+ }
144
+ out += cell.ch;
145
+ }
146
+ if (link !== void 0) out += OSC8_CLOSE;
147
+ if (style !== "") out += "\x1B[0m";
148
+ return out;
149
+ }
150
+ const SELECT_ON = "\x1B[7m";
151
+ function highlightCells(cells, startCol, endCol) {
152
+ let col = 0;
153
+ return cells.map((cell) => {
154
+ const next = col + cell.width;
155
+ const inRange = cell.width > 0 && next > startCol && col < endCol;
156
+ col = next;
157
+ return inRange ? {
158
+ ...cell,
159
+ style: cell.style + SELECT_ON
160
+ } : cell;
161
+ });
162
+ }
163
+
164
+ //#endregion
165
+ //#region src/screen-buffer-store.ts
166
+ const CURSOR_BURST_FLOOR_MS = 200;
167
+ const CURSOR_BURST_PERIOD_MULTIPLE = 2.5;
168
+ function computeBurstQuietMs(minAnimationPeriodMs) {
169
+ if (minAnimationPeriodMs === void 0 || !Number.isFinite(minAnimationPeriodMs)) return 200;
170
+ return Math.max(200, Math.ceil(minAnimationPeriodMs * CURSOR_BURST_PERIOD_MULTIPLE));
171
+ }
172
+ var ScreenBuffer = class {
173
+ minAnimationPeriod;
174
+ frameTop;
175
+ parseEveryLine;
176
+ needsAnchor = true;
177
+ rows = [];
178
+ rawLines = [];
179
+ parsedLineCount = 0;
180
+ damageTop = null;
181
+ damageBottom = null;
182
+ maxLineWidth = 0;
183
+ selectionQuery;
184
+ screenRows = 0;
185
+ prevLineCount = 0;
186
+ prevCursor;
187
+ cursorShown = false;
188
+ lastRedrawAt = 0;
189
+ constructor(options = {}) {
190
+ this.minAnimationPeriod = options.minAnimationPeriod ?? (() => void 0);
191
+ this.frameTop = Math.max(0, options.frameTop ?? 0);
192
+ this.parseEveryLine = options.parseEveryLine === true;
193
+ }
194
+ setSelectionQuery(query) {
195
+ this.selectionQuery = query;
196
+ }
197
+ setScreenRows(rows) {
198
+ this.screenRows = Number.isFinite(rows) && rows > 0 ? Math.floor(rows) : 0;
199
+ }
200
+ buildSelectionRepaint(rows) {
201
+ if (rows.length === 0) return "";
202
+ const ESC = "\x1B[";
203
+ const total = Math.max(this.rows.length, 1);
204
+ const baseline = this.prevCursor?.y ?? Math.max(0, this.prevLineCount - 1);
205
+ let out = `${ESC}?25l`;
206
+ for (const row of rows) {
207
+ if (row < 0 || row >= total) continue;
208
+ const delta = row - baseline;
209
+ if (delta < 0) out += `${ESC}${-delta}A`;
210
+ else if (delta > 0) out += `${ESC}${delta}B`;
211
+ out += `\r${ESC}2K${this.renderLine(row)}`;
212
+ if (delta < 0) out += `${ESC}${-delta}B`;
213
+ else if (delta > 0) out += `${ESC}${delta}A`;
214
+ }
215
+ out += "\r";
216
+ if (this.prevCursor !== void 0 && this.prevCursor.x > 0) out += `${ESC}${this.prevCursor.x + 1}G`;
217
+ if (this.cursorShown) out += `${ESC}?25h`;
218
+ return out;
219
+ }
220
+ resync() {
221
+ this.needsAnchor = true;
222
+ for (let row = 0; row < this.rows.length; row += 1) this.markDirty(row);
223
+ }
224
+ repaintSequence(cursor, now = Date.now()) {
225
+ if (this.rows.length === 0) return "";
226
+ this.resync();
227
+ const damage = this.takeDamage();
228
+ return damage ? this.flushSequence(damage, cursor, now) : "";
229
+ }
230
+ burstQuietMs() {
231
+ return computeBurstQuietMs(this.minAnimationPeriod());
232
+ }
233
+ get height() {
234
+ return this.rows.length;
235
+ }
236
+ lineAt(row) {
237
+ return this.rows[row];
238
+ }
239
+ takeDamage() {
240
+ if (this.damageTop === null || this.damageBottom === null) return null;
241
+ const damage = {
242
+ top: this.damageTop,
243
+ bottom: this.damageBottom
244
+ };
245
+ this.damageTop = null;
246
+ this.damageBottom = null;
247
+ return damage;
248
+ }
249
+ markDirty(row) {
250
+ if (this.damageTop === null || row < this.damageTop) this.damageTop = row;
251
+ if (this.damageBottom === null || row > this.damageBottom) this.damageBottom = row;
252
+ }
253
+ markAllDirty() {
254
+ for (let row = 0; row < this.rows.length; row += 1) this.markDirty(row);
255
+ }
256
+ invalidate() {
257
+ this.resync();
258
+ }
259
+ setMaxLineWidth(columns) {
260
+ const next = Math.max(0, Math.floor(columns));
261
+ if (next === this.maxLineWidth) return;
262
+ this.maxLineWidth = next;
263
+ this.rawLines = [];
264
+ for (let row = 0; row < this.rows.length; row += 1) {
265
+ const cells = this.rows[row];
266
+ if (cells) this.rows[row] = this.clampToMaxWidth(cells);
267
+ }
268
+ this.markAllDirty();
269
+ }
270
+ clampToMaxWidth(cells) {
271
+ const cap = this.maxLineWidth;
272
+ if (cap <= 0) return cells;
273
+ let width = 0;
274
+ for (let i = 0; i < cells.length; i += 1) {
275
+ const w = cells[i]?.width ?? 0;
276
+ if (width + w > cap) return cells.slice(0, i);
277
+ width += w;
278
+ }
279
+ return cells;
280
+ }
281
+ ingest(frame) {
282
+ const rawLines = frame.split("\n");
283
+ const lines = frame.endsWith("\n") ? rawLines.slice(0, -1) : rawLines;
284
+ if (lines.length < this.rows.length) {
285
+ const eraseUntil = this.screenRows > 0 ? Math.min(this.rows.length, this.screenRows) : this.rows.length;
286
+ for (let row = lines.length; row < eraseUntil; row += 1) this.markDirty(row);
287
+ this.rows.length = lines.length;
288
+ }
289
+ if (this.rawLines.length > lines.length) this.rawLines.length = lines.length;
290
+ for (let row = 0; row < lines.length; row += 1) {
291
+ const line = lines[row] ?? "";
292
+ const prev = this.rows[row];
293
+ if (!this.parseEveryLine && prev !== void 0 && this.rawLines[row] === line) continue;
294
+ this.rawLines[row] = line;
295
+ this.parsedLineCount += 1;
296
+ const parsed = this.clampToMaxWidth(parseLine(line));
297
+ if (prev !== void 0 && cellsEqual(prev, parsed)) continue;
298
+ this.rows[row] = parsed;
299
+ this.markDirty(row);
300
+ }
301
+ }
302
+ parsedLines() {
303
+ return this.parsedLineCount;
304
+ }
305
+ bookkeeping() {
306
+ return {
307
+ prevLineCount: this.prevLineCount,
308
+ prevCursor: this.prevCursor,
309
+ cursorShown: this.cursorShown
310
+ };
311
+ }
312
+ buildCursorOnlySequence(cursor, now = Date.now()) {
313
+ const samePos = cursor === void 0 && this.prevCursor === void 0 || cursor !== void 0 && this.prevCursor !== void 0 && cursor.x === this.prevCursor.x && cursor.y === this.prevCursor.y;
314
+ const needsSettle = cursor !== void 0 && !this.cursorShown && now - this.lastRedrawAt >= this.burstQuietMs();
315
+ if (samePos && !needsSettle) return "";
316
+ return this.flushSequence({
317
+ top: 0,
318
+ bottom: -1
319
+ }, cursor, now);
320
+ }
321
+ flushSequence(damage, cursor, now = Date.now()) {
322
+ const ESC = "\x1B[";
323
+ const total = Math.max(this.rows.length, 1);
324
+ const span = Math.max(total, this.prevLineCount);
325
+ const visibleSpan = this.screenRows > 0 ? Math.min(span, this.screenRows) : span;
326
+ const workLast = Math.max(0, visibleSpan - 1);
327
+ const lastRow = total - 1;
328
+ let out = "";
329
+ if (this.needsAnchor) {
330
+ this.needsAnchor = false;
331
+ out += `${ESC}${this.frameTop + 1};1H`;
332
+ this.prevCursor = void 0;
333
+ this.prevLineCount = 0;
334
+ }
335
+ if (this.prevCursor) {
336
+ out += `${ESC}?25l`;
337
+ const down = Math.max(0, this.prevLineCount - 1) - this.prevCursor.y;
338
+ if (down > 0) out += `${ESC}${down}B`;
339
+ out += "\r";
340
+ } else out += `${ESC}?25l`;
341
+ if (damage.bottom >= damage.top) {
342
+ const up = Math.max(0, this.prevLineCount - 1) - damage.top;
343
+ if (up > 0) out += `${ESC}${up}A`;
344
+ else if (up < 0) out += `${ESC}${-up}B`;
345
+ out += "\r";
346
+ const bottom = Math.min(damage.bottom, workLast);
347
+ for (let row = damage.top; row <= bottom; row += 1) {
348
+ out += `${ESC}2K`;
349
+ if (row < this.rows.length) out += this.renderLine(row);
350
+ if (row < bottom) out += "\n\r";
351
+ }
352
+ const delta = lastRow - bottom;
353
+ if (delta > 0) out += `${ESC}${delta}B`;
354
+ else if (delta < 0) out += `${ESC}${-delta}A`;
355
+ out += "\r";
356
+ }
357
+ const inBurst = damage.bottom >= damage.top && now - this.lastRedrawAt < this.burstQuietMs();
358
+ if (damage.bottom >= damage.top) this.lastRedrawAt = now;
359
+ const cursorUnchanged = cursor !== void 0 && this.prevCursor !== void 0 && cursor.x === this.prevCursor.x && cursor.y === this.prevCursor.y;
360
+ const damageHitsCursorRow = damage.bottom >= damage.top && cursor !== void 0 && cursor.y >= damage.top && cursor.y <= damage.bottom;
361
+ if (cursorUnchanged && !damageHitsCursorRow && damage.bottom >= damage.top) {
362
+ let seq = "\x1B7";
363
+ const up = cursor.y - damage.top;
364
+ if (up > 0) seq += `${ESC}${up}A`;
365
+ else if (up < 0) seq += `${ESC}${-up}B`;
366
+ seq += "\r";
367
+ const bottom = Math.min(damage.bottom, span - 1);
368
+ for (let row = damage.top; row <= bottom; row += 1) {
369
+ seq += `${ESC}2K`;
370
+ if (row < this.rows.length) seq += this.renderLine(row);
371
+ if (row < bottom) seq += "\n\r";
372
+ }
373
+ seq += "\x1B8";
374
+ this.prevLineCount = total;
375
+ if (!this.cursorShown) {
376
+ seq += `${ESC}?25h`;
377
+ this.cursorShown = true;
378
+ }
379
+ return seq;
380
+ }
381
+ if (cursor) {
382
+ const cUp = lastRow - Math.max(0, Math.min(cursor.y, lastRow));
383
+ if (cUp > 0) out += `${ESC}${cUp}A`;
384
+ if (cursor.x > 0) out += `${ESC}${cursor.x + 1}G`;
385
+ else out += "\r";
386
+ if (!inBurst) out += `${ESC}?25h`;
387
+ }
388
+ this.prevLineCount = total;
389
+ this.prevCursor = cursor ? { ...cursor } : void 0;
390
+ this.cursorShown = cursor !== void 0 && !inBurst;
391
+ return out;
392
+ }
393
+ renderLine(row) {
394
+ const cells = this.rows[row];
395
+ if (!cells) return "";
396
+ const query = this.selectionQuery;
397
+ if (query === void 0) return renderCells(cells);
398
+ let start = -1;
399
+ let end = -1;
400
+ let col = 0;
401
+ for (const cell of cells) {
402
+ if (cell.width > 0 && query(row, col)) {
403
+ if (start < 0) start = col;
404
+ end = col + cell.width;
405
+ }
406
+ col += cell.width;
407
+ }
408
+ if (start < 0) return renderCells(cells);
409
+ return renderCells(highlightCells(cells, start, end));
410
+ }
411
+ };
412
+ function cellsEqual(a, b) {
413
+ if (a.length !== b.length) return false;
414
+ for (let i = 0; i < a.length; i += 1) {
415
+ const x = a[i];
416
+ const y = b[i];
417
+ if (x?.ch !== y?.ch || x?.style !== y?.style || x?.width !== y?.width || x?.link !== y?.link) return false;
418
+ }
419
+ return true;
420
+ }
421
+
422
+ //#endregion
423
+ //#region src/alt-screen.ts
424
+ const ESC = "\x1B";
425
+ const ENTER_ALT_SCREEN = `${ESC}[?1049h`;
426
+ const EXIT_ALT_SCREEN = `${ESC}[?1049l`;
427
+ const CURSOR_HOME = `${ESC}[H`;
428
+ function createAltScreenController(stream) {
429
+ let entered = false;
430
+ const write = (sequence) => {
431
+ if (!stream.isTTY) return;
432
+ try {
433
+ stream.write(sequence);
434
+ } catch {}
435
+ };
436
+ return {
437
+ enter() {
438
+ if (entered) return;
439
+ entered = true;
440
+ write(ENTER_ALT_SCREEN + CURSOR_HOME);
441
+ },
442
+ exit() {
443
+ if (!entered) return;
444
+ entered = false;
445
+ write(EXIT_ALT_SCREEN);
446
+ },
447
+ get active() {
448
+ return entered;
449
+ }
450
+ };
451
+ }
452
+ function eraseLastFrame(lineCount) {
453
+ if (lineCount <= 0) return `${ESC}[2K\r`;
454
+ let sequence = `${ESC}[2K\r`;
455
+ for (let i = 0; i < lineCount; i += 1) sequence += `${ESC}[1A${ESC}[2K`;
456
+ return sequence;
457
+ }
458
+
459
+ //#endregion
460
+ //#region src/restore-guard.ts
461
+ const SIGTSTP = "SIGTSTP";
462
+ const RESTORE_SIGNAL = "SIGTERM";
463
+ const TERMINAL_GONE_CODES = new Set([
464
+ "EIO",
465
+ "EPIPE",
466
+ "ENOTTY",
467
+ "EBADF"
468
+ ]);
469
+ function isTerminalGone(error) {
470
+ if (typeof error !== "object" || error === null) return false;
471
+ const code = error.code;
472
+ return typeof code === "string" && TERMINAL_GONE_CODES.has(code);
473
+ }
474
+ function installRestoreGuard(hooks, target = process) {
475
+ let disposed = false;
476
+ let restoring = false;
477
+ let suspendAttached = false;
478
+ const runRestore = () => {
479
+ if (restoring) return;
480
+ restoring = true;
481
+ try {
482
+ hooks.restore();
483
+ } catch {} finally {
484
+ restoring = false;
485
+ }
486
+ };
487
+ const onExit = () => runRestore();
488
+ const notifyFatal = (phase, error) => {
489
+ if (hooks.onFatal === void 0) return;
490
+ try {
491
+ hooks.onFatal(phase, error);
492
+ } catch {}
493
+ };
494
+ const onUncaught = (error) => {
495
+ target.off("uncaughtException", onUncaught);
496
+ runRestore();
497
+ notifyFatal("uncaughtException", error);
498
+ if (isTerminalGone(error)) {
499
+ target.kill(target.pid, RESTORE_SIGNAL);
500
+ return;
501
+ }
502
+ throw error;
503
+ };
504
+ const onRejection = (reason) => {
505
+ if (hooks.onRejection !== void 0) try {
506
+ hooks.onRejection(reason);
507
+ return;
508
+ } catch {}
509
+ target.off("unhandledRejection", onRejection);
510
+ runRestore();
511
+ notifyFatal("unhandledRejection", reason);
512
+ if (isTerminalGone(reason)) {
513
+ target.kill(target.pid, RESTORE_SIGNAL);
514
+ return;
515
+ }
516
+ throw reason;
517
+ };
518
+ const onResume = () => {
519
+ if (disposed) return;
520
+ attachSuspend();
521
+ try {
522
+ hooks.resume?.();
523
+ } catch {}
524
+ };
525
+ const onSuspend = () => {
526
+ detachSuspend();
527
+ runRestore();
528
+ target.kill(target.pid, SIGTSTP);
529
+ };
530
+ const attachSuspend = () => {
531
+ if (disposed || suspendAttached) return;
532
+ suspendAttached = true;
533
+ target.on("SIGTSTP", onSuspend);
534
+ };
535
+ const detachSuspend = () => {
536
+ if (!suspendAttached) return;
537
+ suspendAttached = false;
538
+ target.off("SIGTSTP", onSuspend);
539
+ };
540
+ const attach = () => {
541
+ target.once("exit", onExit);
542
+ target.on("uncaughtException", onUncaught);
543
+ target.on("unhandledRejection", onRejection);
544
+ target.on("SIGCONT", onResume);
545
+ attachSuspend();
546
+ };
547
+ const detach = () => {
548
+ target.off("exit", onExit);
549
+ target.off("uncaughtException", onUncaught);
550
+ target.off("unhandledRejection", onRejection);
551
+ target.off("SIGCONT", onResume);
552
+ detachSuspend();
553
+ };
554
+ attach();
555
+ return {
556
+ get active() {
557
+ return !disposed;
558
+ },
559
+ dispose() {
560
+ if (disposed) return;
561
+ disposed = true;
562
+ detach();
563
+ }
564
+ };
565
+ }
566
+
567
+ //#endregion
568
+ export { CURSOR_BURST_FLOOR_MS, CURSOR_BURST_PERIOD_MULTIPLE, ENTER_ALT_SCREEN, EXIT_ALT_SCREEN, ScreenBuffer, charDisplayWidth, computeBurstQuietMs, createAltScreenController, eraseLastFrame, installRestoreGuard, isTerminalGone, stringWidth };
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@x-otto/tui-screen",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0-beta.0",
4
+ "description": "终端屏幕缓冲与备用屏:格子缓冲 + 增量写出 + alt-screen",
5
+ "files": [
6
+ "dist"
7
+ ],
8
+ "type": "module",
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ }
16
+ },
17
+ "dependencies": {
18
+ "string-width": "8.2.2"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "tag": "beta"
23
+ }
24
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.