omk-tui 1.3.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +28 -4
  2. package/dist/components/box.d.ts +5 -0
  3. package/dist/components/box.d.ts.map +1 -1
  4. package/dist/components/box.js +50 -15
  5. package/dist/components/box.js.map +1 -1
  6. package/dist/components/image.d.ts +2 -0
  7. package/dist/components/image.d.ts.map +1 -1
  8. package/dist/components/image.js +4 -0
  9. package/dist/components/image.js.map +1 -1
  10. package/dist/components/markdown.d.ts +4 -0
  11. package/dist/components/markdown.d.ts.map +1 -1
  12. package/dist/components/markdown.js +14 -0
  13. package/dist/components/markdown.js.map +1 -1
  14. package/dist/components/spacer.d.ts +2 -0
  15. package/dist/components/spacer.d.ts.map +1 -1
  16. package/dist/components/spacer.js +8 -0
  17. package/dist/components/spacer.js.map +1 -1
  18. package/dist/components/text.d.ts +4 -0
  19. package/dist/components/text.d.ts.map +1 -1
  20. package/dist/components/text.js +14 -0
  21. package/dist/components/text.js.map +1 -1
  22. package/dist/index.d.ts +3 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/line-reset-memo.d.ts +27 -0
  27. package/dist/line-reset-memo.d.ts.map +1 -0
  28. package/dist/line-reset-memo.js +101 -0
  29. package/dist/line-reset-memo.js.map +1 -0
  30. package/dist/render-generation.d.ts +24 -0
  31. package/dist/render-generation.d.ts.map +1 -0
  32. package/dist/render-generation.js +48 -0
  33. package/dist/render-generation.js.map +1 -0
  34. package/dist/terminal-output.d.ts +20 -1
  35. package/dist/terminal-output.d.ts.map +1 -1
  36. package/dist/terminal-output.js +62 -1
  37. package/dist/terminal-output.js.map +1 -1
  38. package/dist/terminal-resize-log.d.ts +39 -0
  39. package/dist/terminal-resize-log.d.ts.map +1 -0
  40. package/dist/terminal-resize-log.js +57 -0
  41. package/dist/terminal-resize-log.js.map +1 -0
  42. package/dist/terminal-resync.d.ts +74 -0
  43. package/dist/terminal-resync.d.ts.map +1 -0
  44. package/dist/terminal-resync.js +112 -0
  45. package/dist/terminal-resync.js.map +1 -0
  46. package/dist/terminal.d.ts.map +1 -1
  47. package/dist/terminal.js +1 -1
  48. package/dist/terminal.js.map +1 -1
  49. package/dist/tui.d.ts +29 -9
  50. package/dist/tui.d.ts.map +1 -1
  51. package/dist/tui.js +63 -85
  52. package/dist/tui.js.map +1 -1
  53. package/dist/undo-stack.d.ts +8 -2
  54. package/dist/undo-stack.d.ts.map +1 -1
  55. package/dist/undo-stack.js +12 -2
  56. package/dist/undo-stack.js.map +1 -1
  57. package/dist/utils.d.ts +2 -4
  58. package/dist/utils.d.ts.map +1 -1
  59. package/dist/utils.js +2 -128
  60. package/dist/utils.js.map +1 -1
  61. package/dist/visible-width.d.ts +14 -0
  62. package/dist/visible-width.d.ts.map +1 -0
  63. package/dist/visible-width.js +163 -0
  64. package/dist/visible-width.js.map +1 -0
  65. package/dist/windowed-container.d.ts +63 -0
  66. package/dist/windowed-container.d.ts.map +1 -0
  67. package/dist/windowed-container.js +259 -0
  68. package/dist/windowed-container.js.map +1 -0
  69. package/package.json +1 -1
@@ -0,0 +1,101 @@
1
+ import { isImageLine } from "./terminal-image.js";
2
+ import { normalizeTerminalOutput } from "./utils.js";
3
+ /** Reset SGR and close any open OSC 8 hyperlink at segment boundaries. */
4
+ export const SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
5
+ const KITTY_SEQUENCE_PREFIX = "\x1b_G";
6
+ const NO_IDS = [];
7
+ export function extractKittyImageIds(line) {
8
+ const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
9
+ if (sequenceStart === -1)
10
+ return NO_IDS;
11
+ const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
12
+ const paramsEnd = line.indexOf(";", paramsStart);
13
+ if (paramsEnd === -1)
14
+ return NO_IDS;
15
+ const params = line.slice(paramsStart, paramsEnd);
16
+ for (const param of params.split(",")) {
17
+ const [key, value] = param.split("=", 2);
18
+ if (key !== "i" || value === undefined)
19
+ continue;
20
+ const id = Number(value);
21
+ if (Number.isInteger(id) && id > 0 && id <= 0xffffffff) {
22
+ return [id];
23
+ }
24
+ }
25
+ return NO_IDS;
26
+ }
27
+ /**
28
+ * Per-row memo for line resets (normalization + SEGMENT_RESET) and Kitty image IDs.
29
+ *
30
+ * A row reuses the previous frame's output when its raw text equals the previous
31
+ * raw row at the same index, or at the same distance from the end. The second
32
+ * candidate covers a block of rows inserted or removed above (an off-screen
33
+ * message growing by a line shifts every row below it), so one early change no
34
+ * longer re-normalizes the whole transcript. Output depends only on the raw
35
+ * text, so reuse on equal text is always exact. Unchanged component caches
36
+ * usually compare by reference, keeping the renderer's diff on the cheap path.
37
+ */
38
+ export class LineResetMemo {
39
+ raw = [];
40
+ out = [];
41
+ /** Per-row Kitty IDs, or null when no row of the frame carries any (the common case). */
42
+ ids = null;
43
+ /** Raw buffer from two frames ago, refilled instead of reallocated. */
44
+ spareRaw = [];
45
+ /** Kitty image IDs present in the most recent `apply` result. */
46
+ kittyImageIds = new Set();
47
+ /** Normalizes `lines` in place (image lines untouched) and returns it. */
48
+ apply(lines) {
49
+ const count = lines.length;
50
+ const raw = this.spareRaw;
51
+ raw.length = count;
52
+ const previousRaw = this.raw;
53
+ const previousOut = this.out;
54
+ const previousIds = this.ids;
55
+ const previousLength = previousRaw.length;
56
+ const shift = previousLength - count;
57
+ let ids = null;
58
+ for (let i = 0; i < count; i++) {
59
+ const line = lines[i];
60
+ raw[i] = line;
61
+ let from = -1;
62
+ if (i < previousLength && previousRaw[i] === line) {
63
+ from = i;
64
+ }
65
+ else if (shift !== 0) {
66
+ const aligned = i + shift;
67
+ if (aligned >= 0 && aligned < previousLength && previousRaw[aligned] === line)
68
+ from = aligned;
69
+ }
70
+ let rowIds;
71
+ if (from !== -1) {
72
+ lines[i] = previousOut[from];
73
+ if (previousIds === null)
74
+ continue;
75
+ rowIds = previousIds[from];
76
+ }
77
+ else {
78
+ const output = isImageLine(line) ? line : normalizeTerminalOutput(line) + SEGMENT_RESET;
79
+ lines[i] = output;
80
+ rowIds = extractKittyImageIds(output);
81
+ }
82
+ if (rowIds.length > 0) {
83
+ ids ??= new Array(count).fill(NO_IDS);
84
+ ids[i] = rowIds;
85
+ }
86
+ }
87
+ const kittyImageIds = new Set();
88
+ if (ids !== null) {
89
+ for (const rowIds of ids)
90
+ for (const id of rowIds)
91
+ kittyImageIds.add(id);
92
+ }
93
+ this.spareRaw = previousRaw;
94
+ this.raw = raw;
95
+ this.out = lines;
96
+ this.ids = ids;
97
+ this.kittyImageIds = kittyImageIds;
98
+ return lines;
99
+ }
100
+ }
101
+ //# sourceMappingURL=line-reset-memo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"line-reset-memo.js","sourceRoot":"","sources":["../src/line-reset-memo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAErD,0EAA0E;AAC1E,MAAM,CAAC,MAAM,aAAa,GAAG,qBAAqB,CAAC;AAEnD,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AACvC,MAAM,MAAM,GAAsB,EAAE,CAAC;AAErC,MAAM,UAAU,oBAAoB,CAAC,IAAY,EAAqB;IACrE,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC;IAC1D,IAAI,aAAa,KAAK,CAAC,CAAC;QAAE,OAAO,MAAM,CAAC;IAExC,MAAM,WAAW,GAAG,aAAa,GAAG,qBAAqB,CAAC,MAAM,CAAC;IACjE,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IACjD,IAAI,SAAS,KAAK,CAAC,CAAC;QAAE,OAAO,MAAM,CAAC;IAEpC,MAAM,MAAM,GAAG,IAAI,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CAAoB,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBACzD,GAAG,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;YACjB,CAAC;QACF,CAAC;QACD,MAAM,aAAa,GAAG,IAAI,GAAG,EAAU,CAAC;QACxC,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;YAClB,KAAK,MAAM,MAAM,IAAI,GAAG;gBAAE,KAAK,MAAM,EAAE,IAAI,MAAM;oBAAE,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC1E,CAAC;QACD,IAAI,CAAC,QAAQ,GAAG,WAAW,CAAC;QAC5B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC;QACjB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,OAAO,KAAK,CAAC;IAAA,CACb;CACD","sourcesContent":["import { isImageLine } from \"./terminal-image.ts\";\nimport { normalizeTerminalOutput } from \"./utils.ts\";\n\n/** Reset SGR and close any open OSC 8 hyperlink at segment boundaries. */\nexport const SEGMENT_RESET = \"\\x1b[0m\\x1b]8;;\\x07\";\n\nconst KITTY_SEQUENCE_PREFIX = \"\\x1b_G\";\nconst NO_IDS: readonly number[] = [];\n\nexport function extractKittyImageIds(line: string): readonly number[] {\n\tconst sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);\n\tif (sequenceStart === -1) return NO_IDS;\n\n\tconst paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;\n\tconst paramsEnd = line.indexOf(\";\", paramsStart);\n\tif (paramsEnd === -1) return NO_IDS;\n\n\tconst params = line.slice(paramsStart, paramsEnd);\n\tfor (const param of params.split(\",\")) {\n\t\tconst [key, value] = param.split(\"=\", 2);\n\t\tif (key !== \"i\" || value === undefined) continue;\n\t\tconst id = Number(value);\n\t\tif (Number.isInteger(id) && id > 0 && id <= 0xffffffff) {\n\t\t\treturn [id];\n\t\t}\n\t}\n\treturn NO_IDS;\n}\n\n/**\n * Per-row memo for line resets (normalization + SEGMENT_RESET) and Kitty image IDs.\n *\n * A row reuses the previous frame's output when its raw text equals the previous\n * raw row at the same index, or at the same distance from the end. The second\n * candidate covers a block of rows inserted or removed above (an off-screen\n * message growing by a line shifts every row below it), so one early change no\n * longer re-normalizes the whole transcript. Output depends only on the raw\n * text, so reuse on equal text is always exact. Unchanged component caches\n * usually compare by reference, keeping the renderer's diff on the cheap path.\n */\nexport class LineResetMemo {\n\tprivate raw: string[] = [];\n\tprivate out: string[] = [];\n\t/** Per-row Kitty IDs, or null when no row of the frame carries any (the common case). */\n\tprivate ids: (readonly number[])[] | null = null;\n\t/** Raw buffer from two frames ago, refilled instead of reallocated. */\n\tprivate spareRaw: string[] = [];\n\t/** Kitty image IDs present in the most recent `apply` result. */\n\tkittyImageIds = new Set<number>();\n\n\t/** Normalizes `lines` in place (image lines untouched) and returns it. */\n\tapply(lines: string[]): string[] {\n\t\tconst count = lines.length;\n\t\tconst raw = this.spareRaw;\n\t\traw.length = count;\n\t\tconst previousRaw = this.raw;\n\t\tconst previousOut = this.out;\n\t\tconst previousIds = this.ids;\n\t\tconst previousLength = previousRaw.length;\n\t\tconst shift = previousLength - count;\n\t\tlet ids: (readonly number[])[] | null = null;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst line = lines[i];\n\t\t\traw[i] = line;\n\t\t\tlet from = -1;\n\t\t\tif (i < previousLength && previousRaw[i] === line) {\n\t\t\t\tfrom = i;\n\t\t\t} else if (shift !== 0) {\n\t\t\t\tconst aligned = i + shift;\n\t\t\t\tif (aligned >= 0 && aligned < previousLength && previousRaw[aligned] === line) from = aligned;\n\t\t\t}\n\t\t\tlet rowIds: readonly number[];\n\t\t\tif (from !== -1) {\n\t\t\t\tlines[i] = previousOut[from];\n\t\t\t\tif (previousIds === null) continue;\n\t\t\t\trowIds = previousIds[from];\n\t\t\t} else {\n\t\t\t\tconst output = isImageLine(line) ? line : normalizeTerminalOutput(line) + SEGMENT_RESET;\n\t\t\t\tlines[i] = output;\n\t\t\t\trowIds = extractKittyImageIds(output);\n\t\t\t}\n\t\t\tif (rowIds.length > 0) {\n\t\t\t\tids ??= new Array<readonly number[]>(count).fill(NO_IDS);\n\t\t\t\tids[i] = rowIds;\n\t\t\t}\n\t\t}\n\t\tconst kittyImageIds = new Set<number>();\n\t\tif (ids !== null) {\n\t\t\tfor (const rowIds of ids) for (const id of rowIds) kittyImageIds.add(id);\n\t\t}\n\t\tthis.spareRaw = previousRaw;\n\t\tthis.raw = raw;\n\t\tthis.out = lines;\n\t\tthis.ids = ids;\n\t\tthis.kittyImageIds = kittyImageIds;\n\t\treturn lines;\n\t}\n}\n"]}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Structural stand-in for tui.ts `Component` (importing it, even as a type,
3
+ * would put this module in an import cycle with tui.ts).
4
+ */
5
+ interface Component {
6
+ render(width: number): string[];
7
+ }
8
+ export declare function nextRenderGeneration(): number;
9
+ /** Missing hook ⇒ settled (plain components keep freeze-eligible behavior). */
10
+ export declare function isRenderSettled(component: Component): boolean;
11
+ /** Missing hook ⇒ 0 (component is treated as immutable once rendered). */
12
+ export declare function renderGeneration(component: Component): number;
13
+ /** Max generation over `own` and every child (children without hooks count as 0). */
14
+ export declare function maxChildGeneration(own: number, children: readonly Component[]): number;
15
+ /**
16
+ * Drop render caches of a frozen (off-screen) component without changing its
17
+ * render generation. Opt-in only: a component releases exactly what its own
18
+ * `releaseRenderCache()` drops (Container and Box forward to their children).
19
+ * Components without the hook are left untouched; fields are never cleared by
20
+ * name, because a third-party field called `cache` may not be a render cache.
21
+ */
22
+ export declare function releaseRenderCache(component: Component): void;
23
+ export {};
24
+ //# sourceMappingURL=render-generation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-generation.d.ts","sourceRoot":"","sources":["../src/render-generation.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,UAAU,SAAS;IAClB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CAChC;AAcD,wBAAgB,oBAAoB,IAAI,MAAM,CAG7C;AAOD,iFAA+E;AAC/E,wBAAgB,eAAe,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAG7D;AAED,4EAA0E;AAC1E,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM,CAG7D;AAED,qFAAqF;AACrF,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,SAAS,EAAE,GAAG,MAAM,CAOtF;AAID;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI,CAG7D","sourcesContent":["/**\n * Structural stand-in for tui.ts `Component` (importing it, even as a type,\n * would put this module in an import cycle with tui.ts).\n */\ninterface Component {\n\trender(width: number): string[];\n}\n\n/**\n * Process-wide render generation counter.\n *\n * Mutable TUI primitives stamp `nextRenderGeneration()` on every visible\n * change, and containers report the max stamp of themselves and their\n * children. Because stamps only ever increase, any change anywhere in a\n * subtree strictly raises that subtree's generation — removing a child, then\n * adding another, can never land back on a previously observed value. Off-\n * screen windowing compares these numbers instead of object identity.\n */\nlet renderGenerationCounter = 0;\n\nexport function nextRenderGeneration(): number {\n\trenderGenerationCounter += 1;\n\treturn renderGenerationCounter;\n}\n\ntype LifecycleNode = Component & {\n\tisRenderSettled?: () => boolean;\n\tgetRenderGeneration?: () => number;\n};\n\n/** Missing hook ⇒ settled (plain components keep freeze-eligible behavior). */\nexport function isRenderSettled(component: Component): boolean {\n\tconst node = component as LifecycleNode;\n\treturn typeof node.isRenderSettled === \"function\" ? node.isRenderSettled() : true;\n}\n\n/** Missing hook ⇒ 0 (component is treated as immutable once rendered). */\nexport function renderGeneration(component: Component): number {\n\tconst node = component as LifecycleNode;\n\treturn typeof node.getRenderGeneration === \"function\" ? node.getRenderGeneration() : 0;\n}\n\n/** Max generation over `own` and every child (children without hooks count as 0). */\nexport function maxChildGeneration(own: number, children: readonly Component[]): number {\n\tlet max = own;\n\tfor (const child of children) {\n\t\tconst generation = renderGeneration(child);\n\t\tif (generation > max) max = generation;\n\t}\n\treturn max;\n}\n\ntype CacheNode = Component & { releaseRenderCache?: () => void };\n\n/**\n * Drop render caches of a frozen (off-screen) component without changing its\n * render generation. Opt-in only: a component releases exactly what its own\n * `releaseRenderCache()` drops (Container and Box forward to their children).\n * Components without the hook are left untouched; fields are never cleared by\n * name, because a third-party field called `cache` may not be a render cache.\n */\nexport function releaseRenderCache(component: Component): void {\n\tconst node = component as CacheNode;\n\tif (typeof node.releaseRenderCache === \"function\") node.releaseRenderCache();\n}\n"]}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Process-wide render generation counter.
3
+ *
4
+ * Mutable TUI primitives stamp `nextRenderGeneration()` on every visible
5
+ * change, and containers report the max stamp of themselves and their
6
+ * children. Because stamps only ever increase, any change anywhere in a
7
+ * subtree strictly raises that subtree's generation — removing a child, then
8
+ * adding another, can never land back on a previously observed value. Off-
9
+ * screen windowing compares these numbers instead of object identity.
10
+ */
11
+ let renderGenerationCounter = 0;
12
+ export function nextRenderGeneration() {
13
+ renderGenerationCounter += 1;
14
+ return renderGenerationCounter;
15
+ }
16
+ /** Missing hook ⇒ settled (plain components keep freeze-eligible behavior). */
17
+ export function isRenderSettled(component) {
18
+ const node = component;
19
+ return typeof node.isRenderSettled === "function" ? node.isRenderSettled() : true;
20
+ }
21
+ /** Missing hook ⇒ 0 (component is treated as immutable once rendered). */
22
+ export function renderGeneration(component) {
23
+ const node = component;
24
+ return typeof node.getRenderGeneration === "function" ? node.getRenderGeneration() : 0;
25
+ }
26
+ /** Max generation over `own` and every child (children without hooks count as 0). */
27
+ export function maxChildGeneration(own, children) {
28
+ let max = own;
29
+ for (const child of children) {
30
+ const generation = renderGeneration(child);
31
+ if (generation > max)
32
+ max = generation;
33
+ }
34
+ return max;
35
+ }
36
+ /**
37
+ * Drop render caches of a frozen (off-screen) component without changing its
38
+ * render generation. Opt-in only: a component releases exactly what its own
39
+ * `releaseRenderCache()` drops (Container and Box forward to their children).
40
+ * Components without the hook are left untouched; fields are never cleared by
41
+ * name, because a third-party field called `cache` may not be a render cache.
42
+ */
43
+ export function releaseRenderCache(component) {
44
+ const node = component;
45
+ if (typeof node.releaseRenderCache === "function")
46
+ node.releaseRenderCache();
47
+ }
48
+ //# sourceMappingURL=render-generation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-generation.js","sourceRoot":"","sources":["../src/render-generation.ts"],"names":[],"mappings":"AAQA;;;;;;;;;GASG;AACH,IAAI,uBAAuB,GAAG,CAAC,CAAC;AAEhC,MAAM,UAAU,oBAAoB,GAAW;IAC9C,uBAAuB,IAAI,CAAC,CAAC;IAC7B,OAAO,uBAAuB,CAAC;AAAA,CAC/B;AAOD,iFAA+E;AAC/E,MAAM,UAAU,eAAe,CAAC,SAAoB,EAAW;IAC9D,MAAM,IAAI,GAAG,SAA0B,CAAC;IACxC,OAAO,OAAO,IAAI,CAAC,eAAe,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAAA,CAClF;AAED,4EAA0E;AAC1E,MAAM,UAAU,gBAAgB,CAAC,SAAoB,EAAU;IAC9D,MAAM,IAAI,GAAG,SAA0B,CAAC;IACxC,OAAO,OAAO,IAAI,CAAC,mBAAmB,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAAA,CACvF;AAED,qFAAqF;AACrF,MAAM,UAAU,kBAAkB,CAAC,GAAW,EAAE,QAA8B,EAAU;IACvF,IAAI,GAAG,GAAG,GAAG,CAAC;IACd,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,gBAAgB,CAAC,KAAK,CAAC,CAAC;QAC3C,IAAI,UAAU,GAAG,GAAG;YAAE,GAAG,GAAG,UAAU,CAAC;IACxC,CAAC;IACD,OAAO,GAAG,CAAC;AAAA,CACX;AAID;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAoB,EAAQ;IAC9D,MAAM,IAAI,GAAG,SAAsB,CAAC;IACpC,IAAI,OAAO,IAAI,CAAC,kBAAkB,KAAK,UAAU;QAAE,IAAI,CAAC,kBAAkB,EAAE,CAAC;AAAA,CAC7E","sourcesContent":["/**\n * Structural stand-in for tui.ts `Component` (importing it, even as a type,\n * would put this module in an import cycle with tui.ts).\n */\ninterface Component {\n\trender(width: number): string[];\n}\n\n/**\n * Process-wide render generation counter.\n *\n * Mutable TUI primitives stamp `nextRenderGeneration()` on every visible\n * change, and containers report the max stamp of themselves and their\n * children. Because stamps only ever increase, any change anywhere in a\n * subtree strictly raises that subtree's generation — removing a child, then\n * adding another, can never land back on a previously observed value. Off-\n * screen windowing compares these numbers instead of object identity.\n */\nlet renderGenerationCounter = 0;\n\nexport function nextRenderGeneration(): number {\n\trenderGenerationCounter += 1;\n\treturn renderGenerationCounter;\n}\n\ntype LifecycleNode = Component & {\n\tisRenderSettled?: () => boolean;\n\tgetRenderGeneration?: () => number;\n};\n\n/** Missing hook ⇒ settled (plain components keep freeze-eligible behavior). */\nexport function isRenderSettled(component: Component): boolean {\n\tconst node = component as LifecycleNode;\n\treturn typeof node.isRenderSettled === \"function\" ? node.isRenderSettled() : true;\n}\n\n/** Missing hook ⇒ 0 (component is treated as immutable once rendered). */\nexport function renderGeneration(component: Component): number {\n\tconst node = component as LifecycleNode;\n\treturn typeof node.getRenderGeneration === \"function\" ? node.getRenderGeneration() : 0;\n}\n\n/** Max generation over `own` and every child (children without hooks count as 0). */\nexport function maxChildGeneration(own: number, children: readonly Component[]): number {\n\tlet max = own;\n\tfor (const child of children) {\n\t\tconst generation = renderGeneration(child);\n\t\tif (generation > max) max = generation;\n\t}\n\treturn max;\n}\n\ntype CacheNode = Component & { releaseRenderCache?: () => void };\n\n/**\n * Drop render caches of a frozen (off-screen) component without changing its\n * render generation. Opt-in only: a component releases exactly what its own\n * `releaseRenderCache()` drops (Container and Box forward to their children).\n * Components without the hook are left untouched; fields are never cleared by\n * name, because a third-party field called `cache` may not be a render cache.\n */\nexport function releaseRenderCache(component: Component): void {\n\tconst node = component as CacheNode;\n\tif (typeof node.releaseRenderCache === \"function\") node.releaseRenderCache();\n}\n"]}
@@ -10,6 +10,13 @@ export interface TerminalOutputStats {
10
10
  readonly writableLength: number;
11
11
  readonly backpressured: boolean;
12
12
  }
13
+ /**
14
+ * Raw terminal bytes written from outside the render path (completion BEL,
15
+ * OSC 52 clipboard). While a TUI is writing they go through its
16
+ * TerminalOutput, so output stats and the OMK_TUI_RESIZE_LOG byte offsets
17
+ * count them; otherwise straight to stdout. May throw like stream.write.
18
+ */
19
+ export declare function writeTerminalRaw(data: string): void;
13
20
  /** Metadata-only observation. No paint queue, retries, or interception of error handling. */
14
21
  export declare class TerminalOutput {
15
22
  private readonly stream;
@@ -18,7 +25,19 @@ export declare class TerminalOutput {
18
25
  private readonly counters;
19
26
  private readonly onDrain;
20
27
  private readonly onError;
21
- constructor(stream: Writable, log?: string);
28
+ private readonly resizeLog;
29
+ constructor(stream: Writable, log?: string, resizeLog?: string);
30
+ private readonly finalLine;
31
+ private owesFinal;
32
+ /**
33
+ * Wraps a resize handler so each resize first logs the bytes written so far
34
+ * (OMK_TUI_RESIZE_LOG, see terminal-resize-log.ts). Returns the handler
35
+ * itself when the log is off, so an unset variable costs nothing per event.
36
+ */
37
+ withResizeLog(onResize: () => void, size: () => {
38
+ cols: number;
39
+ rows: number;
40
+ }): () => void;
22
41
  write(data: string, log?: boolean): void;
23
42
  snapshot(): TerminalOutputStats;
24
43
  stop(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"terminal-output.d.ts","sourceRoot":"","sources":["../src/terminal-output.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,4EAA4E;IAC5E,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;CAChC;AAgBD,6FAA6F;AAC7F,qBAAa,cAAc;IAC1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAW;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAOvB;IACF,OAAO,CAAC,QAAQ,CAAC,OAAO,CAEtB;IACF,OAAO,CAAC,QAAQ,CAAC,OAAO,CAEtB;IAEF,YAAY,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAK,EAGrC;IAED,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,UAAQ,GAAG,IAAI,CAuBrC;IAED,QAAQ,IAAI,mBAAmB,CAM9B;IAED,IAAI,IAAI,IAAI,CAIX;CACD","sourcesContent":["import { errorMonitor } from \"node:events\";\nimport { appendFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Writable } from \"node:stream\";\n\nexport interface TerminalOutputStats {\n\treadonly writeCalls: number;\n\t/** Bytes offered to write, not a claim that the terminal displayed them. */\n\treadonly submittedBytes: number;\n\treadonly writeFalseCount: number;\n\treadonly drainCount: number;\n\treadonly errorCount: number;\n\treadonly peakWritableLength: number;\n\treadonly writableLength: number;\n\treadonly backpressured: boolean;\n}\n\nfunction writeLogPath(value: string): string {\n\tif (!value) return \"\";\n\ttry {\n\t\tif (statSync(value).isDirectory()) {\n\t\t\tconst now = new Date();\n\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\treturn join(value, `tui-${ts}-${process.pid}.log`);\n\t\t}\n\t} catch {\n\t\t// A non-existing path is a filename, matching the existing debug-log contract.\n\t}\n\treturn value;\n}\n\n/** Metadata-only observation. No paint queue, retries, or interception of error handling. */\nexport class TerminalOutput {\n\tprivate readonly stream: Writable;\n\tprivate readonly logPath: string;\n\tprivate observing = false;\n\tprivate readonly counters = {\n\t\twriteCalls: 0,\n\t\tsubmittedBytes: 0,\n\t\twriteFalseCount: 0,\n\t\tdrainCount: 0,\n\t\terrorCount: 0,\n\t\tpeakWritableLength: 0,\n\t};\n\tprivate readonly onDrain = () => {\n\t\tthis.counters.drainCount++;\n\t};\n\tprivate readonly onError = () => {\n\t\tthis.counters.errorCount++;\n\t};\n\n\tconstructor(stream: Writable, log = \"\") {\n\t\tthis.stream = stream;\n\t\tthis.logPath = writeLogPath(log);\n\t}\n\n\twrite(data: string, log = false): void {\n\t\tif (!this.observing) {\n\t\t\tthis.stream.on(\"drain\", this.onDrain);\n\t\t\tthis.stream.on(errorMonitor, this.onError);\n\t\t\tthis.observing = true;\n\t\t}\n\t\tthis.counters.writeCalls++;\n\t\tthis.counters.submittedBytes += Buffer.byteLength(data, \"utf8\");\n\t\ttry {\n\t\t\t// false still accepts the write. Never resend it.\n\t\t\tif (!this.stream.write(data)) this.counters.writeFalseCount++;\n\t\t} catch (error) {\n\t\t\tthis.counters.errorCount++;\n\t\t\tthrow error;\n\t\t}\n\t\tthis.counters.peakWritableLength = Math.max(this.counters.peakWritableLength, this.stream.writableLength);\n\t\tif (log && this.logPath) {\n\t\t\ttry {\n\t\t\t\tappendFileSync(this.logPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t/* Explicit raw debug logging remains best-effort. */\n\t\t\t}\n\t\t}\n\t}\n\n\tsnapshot(): TerminalOutputStats {\n\t\treturn {\n\t\t\t...this.counters,\n\t\t\twritableLength: this.stream.writableLength,\n\t\t\tbackpressured: this.stream.writableNeedDrain,\n\t\t};\n\t}\n\n\tstop(): void {\n\t\tthis.stream.off(\"drain\", this.onDrain);\n\t\tthis.stream.off(errorMonitor, this.onError);\n\t\tthis.observing = false;\n\t}\n}\n"]}
1
+ {"version":3,"file":"terminal-output.d.ts","sourceRoot":"","sources":["../src/terminal-output.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG5C,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,4EAA4E;IAC5E,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;CAChC;AAmBD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAGnD;AAUD,6FAA6F;AAC7F,qBAAa,cAAc;IAC1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAW;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAOvB;IACF,OAAO,CAAC,QAAQ,CAAC,OAAO,CAEtB;IACF,OAAO,CAAC,QAAQ,CAAC,OAAO,CAEtB;IAEF,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAgC;IAE1D,YAAY,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAK,EAAE,SAAS,SAAuC,EAKvF;IAED,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6D;IAEvF,OAAO,CAAC,SAAS;IASjB;;;;OAIG;IACH,aAAa,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,IAAI,EAAE,MAAM;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,IAAI,CAU1F;IAED,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,UAAQ,GAAG,IAAI,CAyBrC;IAED,QAAQ,IAAI,mBAAmB,CAM9B;IAED,IAAI,IAAI,IAAI,CAOX;CACD","sourcesContent":["import { errorMonitor } from \"node:events\";\nimport { appendFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport { TerminalResizeLog } from \"./terminal-resize-log.ts\";\n\nexport interface TerminalOutputStats {\n\treadonly writeCalls: number;\n\t/** Bytes offered to write, not a claim that the terminal displayed them. */\n\treadonly submittedBytes: number;\n\treadonly writeFalseCount: number;\n\treadonly drainCount: number;\n\treadonly errorCount: number;\n\treadonly peakWritableLength: number;\n\treadonly writableLength: number;\n\treadonly backpressured: boolean;\n}\n\nfunction writeLogPath(value: string): string {\n\tif (!value) return \"\";\n\ttry {\n\t\tif (statSync(value).isDirectory()) {\n\t\t\tconst now = new Date();\n\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\treturn join(value, `tui-${ts}-${process.pid}.log`);\n\t\t}\n\t} catch {\n\t\t// A non-existing path is a filename, matching the existing debug-log contract.\n\t}\n\treturn value;\n}\n\n/** The TerminalOutput of the running TUI: set on its first write, cleared by stop. */\nlet activeOutput: TerminalOutput | undefined;\n\n/**\n * Raw terminal bytes written from outside the render path (completion BEL,\n * OSC 52 clipboard). While a TUI is writing they go through its\n * TerminalOutput, so output stats and the OMK_TUI_RESIZE_LOG byte offsets\n * count them; otherwise straight to stdout. May throw like stream.write.\n */\nexport function writeTerminalRaw(data: string): void {\n\tif (activeOutput) activeOutput.write(data);\n\telse process.stdout.write(data);\n}\n\n/**\n * Final resize-log lines still owed at process exit, for exits that skip stop\n * (a dead tty's EIO goes straight to process.exit). One exit listener serves\n * every TerminalOutput; stop removes its own entry, the next write re-adds it.\n */\nconst finalOnExit = new Set<() => void>();\nlet exitHooked = false;\n\n/** Metadata-only observation. No paint queue, retries, or interception of error handling. */\nexport class TerminalOutput {\n\tprivate readonly stream: Writable;\n\tprivate readonly logPath: string;\n\tprivate observing = false;\n\tprivate readonly counters = {\n\t\twriteCalls: 0,\n\t\tsubmittedBytes: 0,\n\t\twriteFalseCount: 0,\n\t\tdrainCount: 0,\n\t\terrorCount: 0,\n\t\tpeakWritableLength: 0,\n\t};\n\tprivate readonly onDrain = () => {\n\t\tthis.counters.drainCount++;\n\t};\n\tprivate readonly onError = () => {\n\t\tthis.counters.errorCount++;\n\t};\n\n\tprivate readonly resizeLog: TerminalResizeLog | undefined;\n\n\tconstructor(stream: Writable, log = \"\", resizeLog = process.env.OMK_TUI_RESIZE_LOG || \"\") {\n\t\tthis.stream = stream;\n\t\tthis.logPath = writeLogPath(log);\n\t\tthis.resizeLog = resizeLog ? new TerminalResizeLog(resizeLog) : undefined;\n\t\tif (this.resizeLog) this.owesFinal();\n\t}\n\n\tprivate readonly finalLine = () => this.resizeLog?.final(this.counters.submittedBytes);\n\n\tprivate owesFinal(): void {\n\t\tfinalOnExit.add(this.finalLine);\n\t\tif (exitHooked) return;\n\t\texitHooked = true;\n\t\tprocess.once(\"exit\", () => {\n\t\t\tfor (const finalLine of finalOnExit) finalLine();\n\t\t});\n\t}\n\n\t/**\n\t * Wraps a resize handler so each resize first logs the bytes written so far\n\t * (OMK_TUI_RESIZE_LOG, see terminal-resize-log.ts). Returns the handler\n\t * itself when the log is off, so an unset variable costs nothing per event.\n\t */\n\twithResizeLog(onResize: () => void, size: () => { cols: number; rows: number }): () => void {\n\t\tconst log = this.resizeLog;\n\t\tif (!log) return onResize;\n\t\tlet prev = size();\n\t\treturn () => {\n\t\t\tconst next = size();\n\t\t\tlog.resize(this.counters.submittedBytes, next.cols, next.rows, prev.cols, prev.rows);\n\t\t\tprev = next;\n\t\t\tonResize();\n\t\t};\n\t}\n\n\twrite(data: string, log = false): void {\n\t\tif (!this.observing) {\n\t\t\tthis.stream.on(\"drain\", this.onDrain);\n\t\t\tthis.stream.on(errorMonitor, this.onError);\n\t\t\tthis.observing = true;\n\t\t\tactiveOutput = this;\n\t\t\tif (this.resizeLog) this.owesFinal();\n\t\t}\n\t\tthis.counters.writeCalls++;\n\t\tthis.counters.submittedBytes += Buffer.byteLength(data, \"utf8\");\n\t\ttry {\n\t\t\t// false still accepts the write. Never resend it.\n\t\t\tif (!this.stream.write(data)) this.counters.writeFalseCount++;\n\t\t} catch (error) {\n\t\t\tthis.counters.errorCount++;\n\t\t\tthrow error;\n\t\t}\n\t\tthis.counters.peakWritableLength = Math.max(this.counters.peakWritableLength, this.stream.writableLength);\n\t\tif (log && this.logPath) {\n\t\t\ttry {\n\t\t\t\tappendFileSync(this.logPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t/* Explicit raw debug logging remains best-effort. */\n\t\t\t}\n\t\t}\n\t}\n\n\tsnapshot(): TerminalOutputStats {\n\t\treturn {\n\t\t\t...this.counters,\n\t\t\twritableLength: this.stream.writableLength,\n\t\t\tbackpressured: this.stream.writableNeedDrain,\n\t\t};\n\t}\n\n\tstop(): void {\n\t\tthis.finalLine();\n\t\tfinalOnExit.delete(this.finalLine);\n\t\tthis.stream.off(\"drain\", this.onDrain);\n\t\tthis.stream.off(errorMonitor, this.onError);\n\t\tthis.observing = false;\n\t\tif (activeOutput === this) activeOutput = undefined;\n\t}\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { errorMonitor } from "node:events";
2
2
  import { appendFileSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { TerminalResizeLog } from "./terminal-resize-log.js";
4
5
  function writeLogPath(value) {
5
6
  if (!value)
6
7
  return "";
@@ -16,6 +17,27 @@ function writeLogPath(value) {
16
17
  }
17
18
  return value;
18
19
  }
20
+ /** The TerminalOutput of the running TUI: set on its first write, cleared by stop. */
21
+ let activeOutput;
22
+ /**
23
+ * Raw terminal bytes written from outside the render path (completion BEL,
24
+ * OSC 52 clipboard). While a TUI is writing they go through its
25
+ * TerminalOutput, so output stats and the OMK_TUI_RESIZE_LOG byte offsets
26
+ * count them; otherwise straight to stdout. May throw like stream.write.
27
+ */
28
+ export function writeTerminalRaw(data) {
29
+ if (activeOutput)
30
+ activeOutput.write(data);
31
+ else
32
+ process.stdout.write(data);
33
+ }
34
+ /**
35
+ * Final resize-log lines still owed at process exit, for exits that skip stop
36
+ * (a dead tty's EIO goes straight to process.exit). One exit listener serves
37
+ * every TerminalOutput; stop removes its own entry, the next write re-adds it.
38
+ */
39
+ const finalOnExit = new Set();
40
+ let exitHooked = false;
19
41
  /** Metadata-only observation. No paint queue, retries, or interception of error handling. */
20
42
  export class TerminalOutput {
21
43
  stream;
@@ -35,15 +57,50 @@ export class TerminalOutput {
35
57
  onError = () => {
36
58
  this.counters.errorCount++;
37
59
  };
38
- constructor(stream, log = "") {
60
+ resizeLog;
61
+ constructor(stream, log = "", resizeLog = process.env.OMK_TUI_RESIZE_LOG || "") {
39
62
  this.stream = stream;
40
63
  this.logPath = writeLogPath(log);
64
+ this.resizeLog = resizeLog ? new TerminalResizeLog(resizeLog) : undefined;
65
+ if (this.resizeLog)
66
+ this.owesFinal();
67
+ }
68
+ finalLine = () => this.resizeLog?.final(this.counters.submittedBytes);
69
+ owesFinal() {
70
+ finalOnExit.add(this.finalLine);
71
+ if (exitHooked)
72
+ return;
73
+ exitHooked = true;
74
+ process.once("exit", () => {
75
+ for (const finalLine of finalOnExit)
76
+ finalLine();
77
+ });
78
+ }
79
+ /**
80
+ * Wraps a resize handler so each resize first logs the bytes written so far
81
+ * (OMK_TUI_RESIZE_LOG, see terminal-resize-log.ts). Returns the handler
82
+ * itself when the log is off, so an unset variable costs nothing per event.
83
+ */
84
+ withResizeLog(onResize, size) {
85
+ const log = this.resizeLog;
86
+ if (!log)
87
+ return onResize;
88
+ let prev = size();
89
+ return () => {
90
+ const next = size();
91
+ log.resize(this.counters.submittedBytes, next.cols, next.rows, prev.cols, prev.rows);
92
+ prev = next;
93
+ onResize();
94
+ };
41
95
  }
42
96
  write(data, log = false) {
43
97
  if (!this.observing) {
44
98
  this.stream.on("drain", this.onDrain);
45
99
  this.stream.on(errorMonitor, this.onError);
46
100
  this.observing = true;
101
+ activeOutput = this;
102
+ if (this.resizeLog)
103
+ this.owesFinal();
47
104
  }
48
105
  this.counters.writeCalls++;
49
106
  this.counters.submittedBytes += Buffer.byteLength(data, "utf8");
@@ -74,9 +131,13 @@ export class TerminalOutput {
74
131
  };
75
132
  }
76
133
  stop() {
134
+ this.finalLine();
135
+ finalOnExit.delete(this.finalLine);
77
136
  this.stream.off("drain", this.onDrain);
78
137
  this.stream.off(errorMonitor, this.onError);
79
138
  this.observing = false;
139
+ if (activeOutput === this)
140
+ activeOutput = undefined;
80
141
  }
81
142
  }
82
143
  //# sourceMappingURL=terminal-output.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"terminal-output.js","sourceRoot":"","sources":["../src/terminal-output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE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AkB,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;QAC1G,IAAI,GAAG,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACzB,IAAI,CAAC;gBACJ,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;YAC1D,CAAC;YAAC,MAAM,CAAC;gBACR,qDAAqD;YACtD,CAAC;QACF,CAAC;IAAA,CACD;IAED,QAAQ,GAAwB;QAC/B,OAAO;YACN,GAAG,IAAI,CAAC,QAAQ;YAChB,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc;YAC1C,aAAa,EAAE,IAAI,CAAC,MAAM,CAAC,iBAAiB;SAC5C,CAAC;IAAA,CACF;IAED,IAAI,GAAS;QACZ,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACvC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5C,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IAAA,CACvB;CACD","sourcesContent":["import { errorMonitor } from \"node:events\";\nimport { appendFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Writable } from \"node:stream\";\n\nexport interface TerminalOutputStats {\n\treadonly writeCalls: number;\n\t/** Bytes offered to write, not a claim that the terminal displayed them. */\n\treadonly submittedBytes: number;\n\treadonly writeFalseCount: number;\n\treadonly drainCount: number;\n\treadonly errorCount: number;\n\treadonly peakWritableLength: number;\n\treadonly writableLength: number;\n\treadonly backpressured: boolean;\n}\n\nfunction writeLogPath(value: string): string {\n\tif (!value) return \"\";\n\ttry {\n\t\tif (statSync(value).isDirectory()) {\n\t\t\tconst now = new Date();\n\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\treturn join(value, `tui-${ts}-${process.pid}.log`);\n\t\t}\n\t} catch {\n\t\t// A non-existing path is a filename, matching the existing debug-log contract.\n\t}\n\treturn value;\n}\n\n/** Metadata-only observation. No paint queue, retries, or interception of error handling. */\nexport class TerminalOutput {\n\tprivate readonly stream: Writable;\n\tprivate readonly logPath: string;\n\tprivate observing = false;\n\tprivate readonly counters = {\n\t\twriteCalls: 0,\n\t\tsubmittedBytes: 0,\n\t\twriteFalseCount: 0,\n\t\tdrainCount: 0,\n\t\terrorCount: 0,\n\t\tpeakWritableLength: 0,\n\t};\n\tprivate readonly onDrain = () => {\n\t\tthis.counters.drainCount++;\n\t};\n\tprivate readonly onError = () => {\n\t\tthis.counters.errorCount++;\n\t};\n\n\tconstructor(stream: Writable, log = \"\") {\n\t\tthis.stream = stream;\n\t\tthis.logPath = writeLogPath(log);\n\t}\n\n\twrite(data: string, log = false): void {\n\t\tif (!this.observing) {\n\t\t\tthis.stream.on(\"drain\", this.onDrain);\n\t\t\tthis.stream.on(errorMonitor, this.onError);\n\t\t\tthis.observing = true;\n\t\t}\n\t\tthis.counters.writeCalls++;\n\t\tthis.counters.submittedBytes += Buffer.byteLength(data, \"utf8\");\n\t\ttry {\n\t\t\t// false still accepts the write. Never resend it.\n\t\t\tif (!this.stream.write(data)) this.counters.writeFalseCount++;\n\t\t} catch (error) {\n\t\t\tthis.counters.errorCount++;\n\t\t\tthrow error;\n\t\t}\n\t\tthis.counters.peakWritableLength = Math.max(this.counters.peakWritableLength, this.stream.writableLength);\n\t\tif (log && this.logPath) {\n\t\t\ttry {\n\t\t\t\tappendFileSync(this.logPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t/* Explicit raw debug logging remains best-effort. */\n\t\t\t}\n\t\t}\n\t}\n\n\tsnapshot(): TerminalOutputStats {\n\t\treturn {\n\t\t\t...this.counters,\n\t\t\twritableLength: this.stream.writableLength,\n\t\t\tbackpressured: this.stream.writableNeedDrain,\n\t\t};\n\t}\n\n\tstop(): void {\n\t\tthis.stream.off(\"drain\", this.onDrain);\n\t\tthis.stream.off(errorMonitor, this.onError);\n\t\tthis.observing = false;\n\t}\n}\n"]}
1
+ {"version":3,"file":"terminal-output.js","sourceRoot":"","sources":["../src/terminal-output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAc7D,SAAS,YAAY,CAAC,KAAa,EAAU;IAC5C,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,IAAI,CAAC;QACJ,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,EAAE,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,IAAI,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,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AI,CAAC,QAAQ;YAChB,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc;YAC1C,aAAa,EAAE,IAAI,CAAC,MAAM,CAAC,iBAAiB;SAC5C,CAAC;IAAA,CACF;IAED,IAAI,GAAS;QACZ,IAAI,CAAC,SAAS,EAAE,CAAC;QACjB,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACvC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5C,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,YAAY,KAAK,IAAI;YAAE,YAAY,GAAG,SAAS,CAAC;IAAA,CACpD;CACD","sourcesContent":["import { errorMonitor } from \"node:events\";\nimport { appendFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport { TerminalResizeLog } from \"./terminal-resize-log.ts\";\n\nexport interface TerminalOutputStats {\n\treadonly writeCalls: number;\n\t/** Bytes offered to write, not a claim that the terminal displayed them. */\n\treadonly submittedBytes: number;\n\treadonly writeFalseCount: number;\n\treadonly drainCount: number;\n\treadonly errorCount: number;\n\treadonly peakWritableLength: number;\n\treadonly writableLength: number;\n\treadonly backpressured: boolean;\n}\n\nfunction writeLogPath(value: string): string {\n\tif (!value) return \"\";\n\ttry {\n\t\tif (statSync(value).isDirectory()) {\n\t\t\tconst now = new Date();\n\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\treturn join(value, `tui-${ts}-${process.pid}.log`);\n\t\t}\n\t} catch {\n\t\t// A non-existing path is a filename, matching the existing debug-log contract.\n\t}\n\treturn value;\n}\n\n/** The TerminalOutput of the running TUI: set on its first write, cleared by stop. */\nlet activeOutput: TerminalOutput | undefined;\n\n/**\n * Raw terminal bytes written from outside the render path (completion BEL,\n * OSC 52 clipboard). While a TUI is writing they go through its\n * TerminalOutput, so output stats and the OMK_TUI_RESIZE_LOG byte offsets\n * count them; otherwise straight to stdout. May throw like stream.write.\n */\nexport function writeTerminalRaw(data: string): void {\n\tif (activeOutput) activeOutput.write(data);\n\telse process.stdout.write(data);\n}\n\n/**\n * Final resize-log lines still owed at process exit, for exits that skip stop\n * (a dead tty's EIO goes straight to process.exit). One exit listener serves\n * every TerminalOutput; stop removes its own entry, the next write re-adds it.\n */\nconst finalOnExit = new Set<() => void>();\nlet exitHooked = false;\n\n/** Metadata-only observation. No paint queue, retries, or interception of error handling. */\nexport class TerminalOutput {\n\tprivate readonly stream: Writable;\n\tprivate readonly logPath: string;\n\tprivate observing = false;\n\tprivate readonly counters = {\n\t\twriteCalls: 0,\n\t\tsubmittedBytes: 0,\n\t\twriteFalseCount: 0,\n\t\tdrainCount: 0,\n\t\terrorCount: 0,\n\t\tpeakWritableLength: 0,\n\t};\n\tprivate readonly onDrain = () => {\n\t\tthis.counters.drainCount++;\n\t};\n\tprivate readonly onError = () => {\n\t\tthis.counters.errorCount++;\n\t};\n\n\tprivate readonly resizeLog: TerminalResizeLog | undefined;\n\n\tconstructor(stream: Writable, log = \"\", resizeLog = process.env.OMK_TUI_RESIZE_LOG || \"\") {\n\t\tthis.stream = stream;\n\t\tthis.logPath = writeLogPath(log);\n\t\tthis.resizeLog = resizeLog ? new TerminalResizeLog(resizeLog) : undefined;\n\t\tif (this.resizeLog) this.owesFinal();\n\t}\n\n\tprivate readonly finalLine = () => this.resizeLog?.final(this.counters.submittedBytes);\n\n\tprivate owesFinal(): void {\n\t\tfinalOnExit.add(this.finalLine);\n\t\tif (exitHooked) return;\n\t\texitHooked = true;\n\t\tprocess.once(\"exit\", () => {\n\t\t\tfor (const finalLine of finalOnExit) finalLine();\n\t\t});\n\t}\n\n\t/**\n\t * Wraps a resize handler so each resize first logs the bytes written so far\n\t * (OMK_TUI_RESIZE_LOG, see terminal-resize-log.ts). Returns the handler\n\t * itself when the log is off, so an unset variable costs nothing per event.\n\t */\n\twithResizeLog(onResize: () => void, size: () => { cols: number; rows: number }): () => void {\n\t\tconst log = this.resizeLog;\n\t\tif (!log) return onResize;\n\t\tlet prev = size();\n\t\treturn () => {\n\t\t\tconst next = size();\n\t\t\tlog.resize(this.counters.submittedBytes, next.cols, next.rows, prev.cols, prev.rows);\n\t\t\tprev = next;\n\t\t\tonResize();\n\t\t};\n\t}\n\n\twrite(data: string, log = false): void {\n\t\tif (!this.observing) {\n\t\t\tthis.stream.on(\"drain\", this.onDrain);\n\t\t\tthis.stream.on(errorMonitor, this.onError);\n\t\t\tthis.observing = true;\n\t\t\tactiveOutput = this;\n\t\t\tif (this.resizeLog) this.owesFinal();\n\t\t}\n\t\tthis.counters.writeCalls++;\n\t\tthis.counters.submittedBytes += Buffer.byteLength(data, \"utf8\");\n\t\ttry {\n\t\t\t// false still accepts the write. Never resend it.\n\t\t\tif (!this.stream.write(data)) this.counters.writeFalseCount++;\n\t\t} catch (error) {\n\t\t\tthis.counters.errorCount++;\n\t\t\tthrow error;\n\t\t}\n\t\tthis.counters.peakWritableLength = Math.max(this.counters.peakWritableLength, this.stream.writableLength);\n\t\tif (log && this.logPath) {\n\t\t\ttry {\n\t\t\t\tappendFileSync(this.logPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t/* Explicit raw debug logging remains best-effort. */\n\t\t\t}\n\t\t}\n\t}\n\n\tsnapshot(): TerminalOutputStats {\n\t\treturn {\n\t\t\t...this.counters,\n\t\t\twritableLength: this.stream.writableLength,\n\t\t\tbackpressured: this.stream.writableNeedDrain,\n\t\t};\n\t}\n\n\tstop(): void {\n\t\tthis.finalLine();\n\t\tfinalOnExit.delete(this.finalLine);\n\t\tthis.stream.off(\"drain\", this.onDrain);\n\t\tthis.stream.off(errorMonitor, this.onError);\n\t\tthis.observing = false;\n\t\tif (activeOutput === this) activeOutput = undefined;\n\t}\n}\n"]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture
3
+ * of omk's terminal output can be replayed with resizes at exact byte offsets
4
+ * (tmux `pipe-pane` file sizes lag by several KB).
5
+ *
6
+ * Resize line, written when omk handles the resize event, before it renders:
7
+ * {"bytes":N,"cols":C,"rows":R,"t":T,"prevCols":PC,"prevRows":PR}
8
+ * Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM
9
+ * paths that stop the TUI), and on process exit if no final line with the same
10
+ * byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):
11
+ * {"final":true,"bytes":N}
12
+ *
13
+ * `bytes` is the cumulative UTF-8 length of everything omk handed to stdout
14
+ * through its terminal writer so far, counted at the write() call: omk-side
15
+ * bytes, not pty bytes (no ONLCR `\n` → `\r\n` correction). It is an upper
16
+ * bound on where the resize hit the byte stream (written bytes the terminal had
17
+ * not read yet may be processed at the new size); the external pipe-pane
18
+ * offset is the lower bound. `t` is `performance.now()` in ms.
19
+ *
20
+ * Lines are appended synchronously so they land before exit. Write errors are
21
+ * ignored (debug output, best-effort). Unset: no log object exists and the
22
+ * resize handler is not wrapped (TerminalOutput.withResizeLog).
23
+ *
24
+ * Node emits `resize` only when the tty size actually changed, so the SIGWINCH
25
+ * omk sends itself on start (stale size after suspend) logs a line only if the
26
+ * size changed while omk was stopped; there are no same-size lines. A
27
+ * suspend/resume cycle (external editor) writes a final line per stop, so
28
+ * readers take the last final line.
29
+ */
30
+ export declare class TerminalResizeLog {
31
+ private readonly path;
32
+ constructor(path: string);
33
+ resize(bytes: number, cols: number, rows: number, prevCols: number, prevRows: number): void;
34
+ private finalBytes;
35
+ /** Skipped when the previous final line already has these bytes (stop, then exit). */
36
+ final(bytes: number): void;
37
+ private append;
38
+ }
39
+ //# sourceMappingURL=terminal-resize-log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal-resize-log.d.ts","sourceRoot":"","sources":["../src/terminal-resize-log.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;IAE9B,YAAY,IAAI,EAAE,MAAM,EAEvB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE1F;IAED,OAAO,CAAC,UAAU,CAAM;IAExB,sFAAsF;IACtF,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAIzB;IAED,OAAO,CAAC,MAAM;CAOd","sourcesContent":["import { appendFileSync } from \"node:fs\";\nimport { performance } from \"node:perf_hooks\";\n\n/**\n * `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture\n * of omk's terminal output can be replayed with resizes at exact byte offsets\n * (tmux `pipe-pane` file sizes lag by several KB).\n *\n * Resize line, written when omk handles the resize event, before it renders:\n * {\"bytes\":N,\"cols\":C,\"rows\":R,\"t\":T,\"prevCols\":PC,\"prevRows\":PR}\n * Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM\n * paths that stop the TUI), and on process exit if no final line with the same\n * byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):\n * {\"final\":true,\"bytes\":N}\n *\n * `bytes` is the cumulative UTF-8 length of everything omk handed to stdout\n * through its terminal writer so far, counted at the write() call: omk-side\n * bytes, not pty bytes (no ONLCR `\\n` → `\\r\\n` correction). It is an upper\n * bound on where the resize hit the byte stream (written bytes the terminal had\n * not read yet may be processed at the new size); the external pipe-pane\n * offset is the lower bound. `t` is `performance.now()` in ms.\n *\n * Lines are appended synchronously so they land before exit. Write errors are\n * ignored (debug output, best-effort). Unset: no log object exists and the\n * resize handler is not wrapped (TerminalOutput.withResizeLog).\n *\n * Node emits `resize` only when the tty size actually changed, so the SIGWINCH\n * omk sends itself on start (stale size after suspend) logs a line only if the\n * size changed while omk was stopped; there are no same-size lines. A\n * suspend/resume cycle (external editor) writes a final line per stop, so\n * readers take the last final line.\n */\nexport class TerminalResizeLog {\n\tprivate readonly path: string;\n\n\tconstructor(path: string) {\n\t\tthis.path = path;\n\t}\n\n\tresize(bytes: number, cols: number, rows: number, prevCols: number, prevRows: number): void {\n\t\tthis.append({ bytes, cols, rows, t: performance.now(), prevCols, prevRows });\n\t}\n\n\tprivate finalBytes = -1;\n\n\t/** Skipped when the previous final line already has these bytes (stop, then exit). */\n\tfinal(bytes: number): void {\n\t\tif (bytes === this.finalBytes) return;\n\t\tthis.finalBytes = bytes;\n\t\tthis.append({ final: true, bytes });\n\t}\n\n\tprivate append(record: Record<string, unknown>): void {\n\t\ttry {\n\t\t\tappendFileSync(this.path, `${JSON.stringify(record)}\\n`, { encoding: \"utf8\" });\n\t\t} catch {\n\t\t\t/* Best-effort debug log. */\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,57 @@
1
+ import { appendFileSync } from "node:fs";
2
+ import { performance } from "node:perf_hooks";
3
+ /**
4
+ * `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture
5
+ * of omk's terminal output can be replayed with resizes at exact byte offsets
6
+ * (tmux `pipe-pane` file sizes lag by several KB).
7
+ *
8
+ * Resize line, written when omk handles the resize event, before it renders:
9
+ * {"bytes":N,"cols":C,"rows":R,"t":T,"prevCols":PC,"prevRows":PR}
10
+ * Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM
11
+ * paths that stop the TUI), and on process exit if no final line with the same
12
+ * byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):
13
+ * {"final":true,"bytes":N}
14
+ *
15
+ * `bytes` is the cumulative UTF-8 length of everything omk handed to stdout
16
+ * through its terminal writer so far, counted at the write() call: omk-side
17
+ * bytes, not pty bytes (no ONLCR `\n` → `\r\n` correction). It is an upper
18
+ * bound on where the resize hit the byte stream (written bytes the terminal had
19
+ * not read yet may be processed at the new size); the external pipe-pane
20
+ * offset is the lower bound. `t` is `performance.now()` in ms.
21
+ *
22
+ * Lines are appended synchronously so they land before exit. Write errors are
23
+ * ignored (debug output, best-effort). Unset: no log object exists and the
24
+ * resize handler is not wrapped (TerminalOutput.withResizeLog).
25
+ *
26
+ * Node emits `resize` only when the tty size actually changed, so the SIGWINCH
27
+ * omk sends itself on start (stale size after suspend) logs a line only if the
28
+ * size changed while omk was stopped; there are no same-size lines. A
29
+ * suspend/resume cycle (external editor) writes a final line per stop, so
30
+ * readers take the last final line.
31
+ */
32
+ export class TerminalResizeLog {
33
+ path;
34
+ constructor(path) {
35
+ this.path = path;
36
+ }
37
+ resize(bytes, cols, rows, prevCols, prevRows) {
38
+ this.append({ bytes, cols, rows, t: performance.now(), prevCols, prevRows });
39
+ }
40
+ finalBytes = -1;
41
+ /** Skipped when the previous final line already has these bytes (stop, then exit). */
42
+ final(bytes) {
43
+ if (bytes === this.finalBytes)
44
+ return;
45
+ this.finalBytes = bytes;
46
+ this.append({ final: true, bytes });
47
+ }
48
+ append(record) {
49
+ try {
50
+ appendFileSync(this.path, `${JSON.stringify(record)}\n`, { encoding: "utf8" });
51
+ }
52
+ catch {
53
+ /* Best-effort debug log. */
54
+ }
55
+ }
56
+ }
57
+ //# sourceMappingURL=terminal-resize-log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal-resize-log.js","sourceRoot":"","sources":["../src/terminal-resize-log.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,OAAO,iBAAiB;IACZ,IAAI,CAAS;IAE9B,YAAY,IAAY,EAAE;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,MAAM,CAAC,KAAa,EAAE,IAAY,EAAE,IAAY,EAAE,QAAgB,EAAE,QAAgB,EAAQ;QAC3F,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,WAAW,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC;IAAA,CAC7E;IAEO,UAAU,GAAG,CAAC,CAAC,CAAC;IAExB,sFAAsF;IACtF,KAAK,CAAC,KAAa,EAAQ;QAC1B,IAAI,KAAK,KAAK,IAAI,CAAC,UAAU;YAAE,OAAO;QACtC,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CACpC;IAEO,MAAM,CAAC,MAA+B,EAAQ;QACrD,IAAI,CAAC;YACJ,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAChF,CAAC;QAAC,MAAM,CAAC;YACR,4BAA4B;QAC7B,CAAC;IAAA,CACD;CACD","sourcesContent":["import { appendFileSync } from \"node:fs\";\nimport { performance } from \"node:perf_hooks\";\n\n/**\n * `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture\n * of omk's terminal output can be replayed with resizes at exact byte offsets\n * (tmux `pipe-pane` file sizes lag by several KB).\n *\n * Resize line, written when omk handles the resize event, before it renders:\n * {\"bytes\":N,\"cols\":C,\"rows\":R,\"t\":T,\"prevCols\":PC,\"prevRows\":PR}\n * Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM\n * paths that stop the TUI), and on process exit if no final line with the same\n * byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):\n * {\"final\":true,\"bytes\":N}\n *\n * `bytes` is the cumulative UTF-8 length of everything omk handed to stdout\n * through its terminal writer so far, counted at the write() call: omk-side\n * bytes, not pty bytes (no ONLCR `\\n` → `\\r\\n` correction). It is an upper\n * bound on where the resize hit the byte stream (written bytes the terminal had\n * not read yet may be processed at the new size); the external pipe-pane\n * offset is the lower bound. `t` is `performance.now()` in ms.\n *\n * Lines are appended synchronously so they land before exit. Write errors are\n * ignored (debug output, best-effort). Unset: no log object exists and the\n * resize handler is not wrapped (TerminalOutput.withResizeLog).\n *\n * Node emits `resize` only when the tty size actually changed, so the SIGWINCH\n * omk sends itself on start (stale size after suspend) logs a line only if the\n * size changed while omk was stopped; there are no same-size lines. A\n * suspend/resume cycle (external editor) writes a final line per stop, so\n * readers take the last final line.\n */\nexport class TerminalResizeLog {\n\tprivate readonly path: string;\n\n\tconstructor(path: string) {\n\t\tthis.path = path;\n\t}\n\n\tresize(bytes: number, cols: number, rows: number, prevCols: number, prevRows: number): void {\n\t\tthis.append({ bytes, cols, rows, t: performance.now(), prevCols, prevRows });\n\t}\n\n\tprivate finalBytes = -1;\n\n\t/** Skipped when the previous final line already has these bytes (stop, then exit). */\n\tfinal(bytes: number): void {\n\t\tif (bytes === this.finalBytes) return;\n\t\tthis.finalBytes = bytes;\n\t\tthis.append({ final: true, bytes });\n\t}\n\n\tprivate append(record: Record<string, unknown>): void {\n\t\ttry {\n\t\t\tappendFileSync(this.path, `${JSON.stringify(record)}\\n`, { encoding: \"utf8\" });\n\t\t} catch {\n\t\t\t/* Best-effort debug log. */\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * How far back a clearing repair repaint may reach, in viewport screens.
3
+ * Bounds the scrollback churn of fixing rows that already scrolled off
4
+ * (see the repaint budget note in TUI.doRender's fullRender helper). Shared
5
+ * by the above-viewport repair and the height-resize resync below.
6
+ */
7
+ export declare const REPAINT_BUDGET_SCREENS = 4;
8
+ /**
9
+ * Rows to write, relative to the cursor, before a height-change repaint.
10
+ *
11
+ * The height-change repaint homes the cursor and rewrites only the last
12
+ * `height` rows, which assumes the screen top is row `newLines.length - height`.
13
+ * A resize does not guarantee that: xterm.js drops the rows below the cursor
14
+ * (the editor footer) when the screen shrinks, and rows the stream appended
15
+ * since the last frame shift the tail down. Either way the screen top sits
16
+ * above the tail, and the repaint overwrote rows that never reached scrollback
17
+ * (scrollback-20 main-r4 lost `value1_3`..`value1_6`).
18
+ *
19
+ * What a resize does keep is the cursor's row and the rows above it (the
20
+ * terminal scrolls or pulls rows around the cursor, it does not move the
21
+ * cursor off its row). So walk up from the cursor's row to the first row that
22
+ * differs from the last frame and rewrite from there to the end with line
23
+ * feeds: rows that no longer fit scroll into scrollback in order, and the tail
24
+ * repaint that follows lands on a screen that already holds the same rows.
25
+ * If the walk up is clamped at the screen top (the first changed row already
26
+ * scrolled away), the changed rows print below their stale copies: duplicated,
27
+ * not lost. Already-printed rows more than REPAINT_BUDGET_SCREENS screens
28
+ * above the end are not re-sent; the start never moves below the cursor row.
29
+ *
30
+ * Rows are compared without overlays (`previousBase`/`currentBase`, the
31
+ * rows the components rendered): a full-height overlay such as the pinned
32
+ * status rail shifts relative to the content when the screen scrolls, so the
33
+ * composited rows above the cursor would all look changed and be re-sent on
34
+ * every resize step. What is written is the composited frame (`newLines`).
35
+ *
36
+ * A frame that fits the new screen needs no resync: the tail repaint writes
37
+ * all of it from the top. Resyncing it anyway is harmful when the frame was
38
+ * padded to the screen height (an overlay taller than short content): its
39
+ * rows are screen rows, not scrollback-anchored rows, so after a grow pulled
40
+ * rows back from scrollback the cursor's row no longer maps to the same
41
+ * content row and the line feeds push the pulled-back rows into scrollback a
42
+ * second time.
43
+ *
44
+ * @param previousBase pre-overlay rows of the last frame
45
+ * @param newLines composited rows of the frame about to be painted
46
+ * @param cursorRow content row the hardware cursor was left on by the last frame
47
+ * @param height terminal rows after the resize
48
+ * @param currentBase pre-overlay rows of the frame about to be painted (default: `newLines`)
49
+ */
50
+ export declare function resyncAfterResize(previousBase: readonly string[], newLines: readonly string[], cursorRow: number, height: number, currentBase?: readonly string[]): string;
51
+ /**
52
+ * First row the resync rewrites, the first changed row at or above the cursor
53
+ * row, and whether the repaint budget moved the start down from it. Requires
54
+ * `length > 0`.
55
+ */
56
+ export declare function resyncStart(previousBase: readonly string[], currentBase: readonly string[], length: number, cursorRow: number, height: number): {
57
+ first: number;
58
+ changed: number;
59
+ capped: boolean;
60
+ };
61
+ /** Per-TUI state for resyncAfterResize: the pre-overlay rows of the last two frames. */
62
+ export declare class ResizeResync {
63
+ private previousBase;
64
+ private currentBase;
65
+ /** Records a frame's rows before overlays are composited; returns them unchanged. Call once per render. */
66
+ track<T extends readonly string[]>(base: T): T;
67
+ /** How the last after() call chose its start, for OMK_DEBUG_REDRAW. */
68
+ detail: string;
69
+ /** resyncAfterResize for the frame last passed to track(), painted as `newLines`. */
70
+ after(newLines: readonly string[], cursorRow: number, height: number): string;
71
+ }
72
+ /** Termux changes height when the software keyboard shows or hides; those resizes skip the clearing repaint. */
73
+ export declare function isTermuxSession(): boolean;
74
+ //# sourceMappingURL=terminal-resync.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal-resync.d.ts","sourceRoot":"","sources":["../src/terminal-resync.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,IAAI,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,wBAAgB,iBAAiB,CAChC,YAAY,EAAE,SAAS,MAAM,EAAE,EAC/B,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,WAAW,GAAE,SAAS,MAAM,EAAa,GACvC,MAAM,CAUR;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAC1B,YAAY,EAAE,SAAS,MAAM,EAAE,EAC/B,WAAW,EAAE,SAAS,MAAM,EAAE,EAC9B,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,GACZ;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAerD;AAED,wFAAwF;AACxF,qBAAa,YAAY;IACxB,OAAO,CAAC,YAAY,CAAyB;IAC7C,OAAO,CAAC,WAAW,CAAyB;IAE5C,2GAA2G;IAC3G,KAAK,CAAC,CAAC,SAAS,SAAS,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,CAI7C;IAED,uEAAuE;IACvE,MAAM,SAAM;IAEZ,qFAAqF;IACrF,KAAK,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAe5E;CACD;AAED,gHAAgH;AAChH,wBAAgB,eAAe,IAAI,OAAO,CAEzC","sourcesContent":["/**\n * How far back a clearing repair repaint may reach, in viewport screens.\n * Bounds the scrollback churn of fixing rows that already scrolled off\n * (see the repaint budget note in TUI.doRender's fullRender helper). Shared\n * by the above-viewport repair and the height-resize resync below.\n */\nexport const REPAINT_BUDGET_SCREENS = 4;\n\n/**\n * Rows to write, relative to the cursor, before a height-change repaint.\n *\n * The height-change repaint homes the cursor and rewrites only the last\n * `height` rows, which assumes the screen top is row `newLines.length - height`.\n * A resize does not guarantee that: xterm.js drops the rows below the cursor\n * (the editor footer) when the screen shrinks, and rows the stream appended\n * since the last frame shift the tail down. Either way the screen top sits\n * above the tail, and the repaint overwrote rows that never reached scrollback\n * (scrollback-20 main-r4 lost `value1_3`..`value1_6`).\n *\n * What a resize does keep is the cursor's row and the rows above it (the\n * terminal scrolls or pulls rows around the cursor, it does not move the\n * cursor off its row). So walk up from the cursor's row to the first row that\n * differs from the last frame and rewrite from there to the end with line\n * feeds: rows that no longer fit scroll into scrollback in order, and the tail\n * repaint that follows lands on a screen that already holds the same rows.\n * If the walk up is clamped at the screen top (the first changed row already\n * scrolled away), the changed rows print below their stale copies: duplicated,\n * not lost. Already-printed rows more than REPAINT_BUDGET_SCREENS screens\n * above the end are not re-sent; the start never moves below the cursor row.\n *\n * Rows are compared without overlays (`previousBase`/`currentBase`, the\n * rows the components rendered): a full-height overlay such as the pinned\n * status rail shifts relative to the content when the screen scrolls, so the\n * composited rows above the cursor would all look changed and be re-sent on\n * every resize step. What is written is the composited frame (`newLines`).\n *\n * A frame that fits the new screen needs no resync: the tail repaint writes\n * all of it from the top. Resyncing it anyway is harmful when the frame was\n * padded to the screen height (an overlay taller than short content): its\n * rows are screen rows, not scrollback-anchored rows, so after a grow pulled\n * rows back from scrollback the cursor's row no longer maps to the same\n * content row and the line feeds push the pulled-back rows into scrollback a\n * second time.\n *\n * @param previousBase pre-overlay rows of the last frame\n * @param newLines composited rows of the frame about to be painted\n * @param cursorRow content row the hardware cursor was left on by the last frame\n * @param height terminal rows after the resize\n * @param currentBase pre-overlay rows of the frame about to be painted (default: `newLines`)\n */\nexport function resyncAfterResize(\n\tpreviousBase: readonly string[],\n\tnewLines: readonly string[],\n\tcursorRow: number,\n\theight: number,\n\tcurrentBase: readonly string[] = newLines,\n): string {\n\tif (newLines.length === 0 || newLines.length <= height) return \"\";\n\tconst { first } = resyncStart(previousBase, currentBase, newLines.length, cursorRow, height);\n\tconst up = cursorRow - first;\n\tlet buffer = up > 0 ? `\\x1b[${up}A\\r` : \"\\r\";\n\tfor (let i = first; i < newLines.length; i++) {\n\t\tif (i > first) buffer += \"\\r\\n\";\n\t\tbuffer += `\\x1b[2K${newLines[i]}`;\n\t}\n\treturn buffer;\n}\n\n/**\n * First row the resync rewrites, the first changed row at or above the cursor\n * row, and whether the repaint budget moved the start down from it. Requires\n * `length > 0`.\n */\nexport function resyncStart(\n\tpreviousBase: readonly string[],\n\tcurrentBase: readonly string[],\n\tlength: number,\n\tcursorRow: number,\n\theight: number,\n): { first: number; changed: number; capped: boolean } {\n\tconst top = Math.min(cursorRow, length - 1);\n\tlet changed = top;\n\tfor (let i = 0; i < top; i++) {\n\t\tif (previousBase[i] !== currentBase[i]) {\n\t\t\tchanged = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\t// The budget only limits how far UP already-printed rows are re-sent. It\n\t// must never push the start below the cursor: cursor-down stops at the\n\t// screen bottom, so the rows in between would never be written (a resize\n\t// frame that appended more than the budget lost them).\n\tconst first = Math.min(Math.max(changed, length - height * REPAINT_BUDGET_SCREENS, 0), top);\n\treturn { first, changed, capped: first > changed };\n}\n\n/** Per-TUI state for resyncAfterResize: the pre-overlay rows of the last two frames. */\nexport class ResizeResync {\n\tprivate previousBase: readonly string[] = [];\n\tprivate currentBase: readonly string[] = [];\n\n\t/** Records a frame's rows before overlays are composited; returns them unchanged. Call once per render. */\n\ttrack<T extends readonly string[]>(base: T): T {\n\t\tthis.previousBase = this.currentBase;\n\t\tthis.currentBase = base;\n\t\treturn base;\n\t}\n\n\t/** How the last after() call chose its start, for OMK_DEBUG_REDRAW. */\n\tdetail = \"\";\n\n\t/** resyncAfterResize for the frame last passed to track(), painted as `newLines`. */\n\tafter(newLines: readonly string[], cursorRow: number, height: number): string {\n\t\tconst output = resyncAfterResize(this.previousBase, newLines, cursorRow, height, this.currentBase);\n\t\tif (!output) {\n\t\t\tthis.detail = `resync none (frame fits: new=${newLines.length} <= height=${height})`;\n\t\t\treturn output;\n\t\t}\n\t\tconst { first, changed, capped } = resyncStart(\n\t\t\tthis.previousBase,\n\t\t\tthis.currentBase,\n\t\t\tnewLines.length,\n\t\t\tcursorRow,\n\t\t\theight,\n\t\t);\n\t\tthis.detail = `resync first=${first} changed=${changed} cursorRow=${cursorRow} capped=${capped}`;\n\t\treturn output;\n\t}\n}\n\n/** Termux changes height when the software keyboard shows or hides; those resizes skip the clearing repaint. */\nexport function isTermuxSession(): boolean {\n\treturn Boolean(process.env.TERMUX_VERSION);\n}\n"]}