@gkoreli/ghostty-vt-js 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -0
  3. package/THIRD_PARTY_NOTICES.md +45 -0
  4. package/dist/browser-terminal/buffer.d.ts +93 -0
  5. package/dist/browser-terminal/buffer.d.ts.map +1 -0
  6. package/dist/browser-terminal/buffer.js +337 -0
  7. package/dist/browser-terminal/buffer.js.map +1 -0
  8. package/dist/browser-terminal/encoding.d.ts +17 -0
  9. package/dist/browser-terminal/encoding.d.ts.map +1 -0
  10. package/dist/browser-terminal/encoding.js +22 -0
  11. package/dist/browser-terminal/encoding.js.map +1 -0
  12. package/dist/browser-terminal/event-emitter.d.ts +8 -0
  13. package/dist/browser-terminal/event-emitter.d.ts.map +1 -0
  14. package/dist/browser-terminal/event-emitter.js +27 -0
  15. package/dist/browser-terminal/event-emitter.js.map +1 -0
  16. package/dist/browser-terminal/frame-hold.d.ts +13 -0
  17. package/dist/browser-terminal/frame-hold.d.ts.map +1 -0
  18. package/dist/browser-terminal/frame-hold.js +17 -0
  19. package/dist/browser-terminal/frame-hold.js.map +1 -0
  20. package/dist/browser-terminal/geometry.d.ts +229 -0
  21. package/dist/browser-terminal/geometry.d.ts.map +1 -0
  22. package/dist/browser-terminal/geometry.js +299 -0
  23. package/dist/browser-terminal/geometry.js.map +1 -0
  24. package/dist/browser-terminal/ghostty.d.ts +478 -0
  25. package/dist/browser-terminal/ghostty.d.ts.map +1 -0
  26. package/dist/browser-terminal/ghostty.js +1212 -0
  27. package/dist/browser-terminal/ghostty.js.map +1 -0
  28. package/dist/browser-terminal/gpu/adapter.d.ts +70 -0
  29. package/dist/browser-terminal/gpu/adapter.d.ts.map +1 -0
  30. package/dist/browser-terminal/gpu/adapter.js +260 -0
  31. package/dist/browser-terminal/gpu/adapter.js.map +1 -0
  32. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.d.ts +33 -0
  33. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.d.ts.map +1 -0
  34. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.js +159 -0
  35. package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.js.map +1 -0
  36. package/dist/browser-terminal/gpu/core/context-loss-watchdog.d.ts +35 -0
  37. package/dist/browser-terminal/gpu/core/context-loss-watchdog.d.ts.map +1 -0
  38. package/dist/browser-terminal/gpu/core/context-loss-watchdog.js +73 -0
  39. package/dist/browser-terminal/gpu/core/context-loss-watchdog.js.map +1 -0
  40. package/dist/browser-terminal/gpu/core/frame.d.ts +68 -0
  41. package/dist/browser-terminal/gpu/core/frame.d.ts.map +1 -0
  42. package/dist/browser-terminal/gpu/core/frame.js +167 -0
  43. package/dist/browser-terminal/gpu/core/frame.js.map +1 -0
  44. package/dist/browser-terminal/gpu/core/glyph-atlas.d.ts +136 -0
  45. package/dist/browser-terminal/gpu/core/glyph-atlas.d.ts.map +1 -0
  46. package/dist/browser-terminal/gpu/core/glyph-atlas.js +281 -0
  47. package/dist/browser-terminal/gpu/core/glyph-atlas.js.map +1 -0
  48. package/dist/browser-terminal/gpu/core/procedural-shapes.d.ts +24 -0
  49. package/dist/browser-terminal/gpu/core/procedural-shapes.d.ts.map +1 -0
  50. package/dist/browser-terminal/gpu/core/procedural-shapes.js +316 -0
  51. package/dist/browser-terminal/gpu/core/procedural-shapes.js.map +1 -0
  52. package/dist/browser-terminal/gpu/core/webgl2-renderer.d.ts +107 -0
  53. package/dist/browser-terminal/gpu/core/webgl2-renderer.d.ts.map +1 -0
  54. package/dist/browser-terminal/gpu/core/webgl2-renderer.js +698 -0
  55. package/dist/browser-terminal/gpu/core/webgl2-renderer.js.map +1 -0
  56. package/dist/browser-terminal/gpu/create-renderer.d.ts +15 -0
  57. package/dist/browser-terminal/gpu/create-renderer.d.ts.map +1 -0
  58. package/dist/browser-terminal/gpu/create-renderer.js +33 -0
  59. package/dist/browser-terminal/gpu/create-renderer.js.map +1 -0
  60. package/dist/browser-terminal/index.d.ts +47 -0
  61. package/dist/browser-terminal/index.d.ts.map +1 -0
  62. package/dist/browser-terminal/index.js +75 -0
  63. package/dist/browser-terminal/index.js.map +1 -0
  64. package/dist/browser-terminal/input-handler.d.ts +262 -0
  65. package/dist/browser-terminal/input-handler.d.ts.map +1 -0
  66. package/dist/browser-terminal/input-handler.js +978 -0
  67. package/dist/browser-terminal/input-handler.js.map +1 -0
  68. package/dist/browser-terminal/interfaces.d.ts +230 -0
  69. package/dist/browser-terminal/interfaces.d.ts.map +1 -0
  70. package/dist/browser-terminal/interfaces.js +5 -0
  71. package/dist/browser-terminal/interfaces.js.map +1 -0
  72. package/dist/browser-terminal/link-detector.d.ts +76 -0
  73. package/dist/browser-terminal/link-detector.d.ts.map +1 -0
  74. package/dist/browser-terminal/link-detector.js +165 -0
  75. package/dist/browser-terminal/link-detector.js.map +1 -0
  76. package/dist/browser-terminal/providers/osc8-link-provider.d.ts +56 -0
  77. package/dist/browser-terminal/providers/osc8-link-provider.d.ts.map +1 -0
  78. package/dist/browser-terminal/providers/osc8-link-provider.js +204 -0
  79. package/dist/browser-terminal/providers/osc8-link-provider.js.map +1 -0
  80. package/dist/browser-terminal/providers/url-regex-provider.d.ts +68 -0
  81. package/dist/browser-terminal/providers/url-regex-provider.d.ts.map +1 -0
  82. package/dist/browser-terminal/providers/url-regex-provider.js +107 -0
  83. package/dist/browser-terminal/providers/url-regex-provider.js.map +1 -0
  84. package/dist/browser-terminal/renderer-interface.d.ts +59 -0
  85. package/dist/browser-terminal/renderer-interface.d.ts.map +1 -0
  86. package/dist/browser-terminal/renderer-interface.js +2 -0
  87. package/dist/browser-terminal/renderer-interface.js.map +1 -0
  88. package/dist/browser-terminal/renderer.d.ts +254 -0
  89. package/dist/browser-terminal/renderer.d.ts.map +1 -0
  90. package/dist/browser-terminal/renderer.js +905 -0
  91. package/dist/browser-terminal/renderer.js.map +1 -0
  92. package/dist/browser-terminal/scrollbar-overlay.d.ts +45 -0
  93. package/dist/browser-terminal/scrollbar-overlay.d.ts.map +1 -0
  94. package/dist/browser-terminal/scrollbar-overlay.js +89 -0
  95. package/dist/browser-terminal/scrollbar-overlay.js.map +1 -0
  96. package/dist/browser-terminal/selection-manager.d.ts +180 -0
  97. package/dist/browser-terminal/selection-manager.d.ts.map +1 -0
  98. package/dist/browser-terminal/selection-manager.js +913 -0
  99. package/dist/browser-terminal/selection-manager.js.map +1 -0
  100. package/dist/browser-terminal/terminal.d.ts +423 -0
  101. package/dist/browser-terminal/terminal.d.ts.map +1 -0
  102. package/dist/browser-terminal/terminal.js +1754 -0
  103. package/dist/browser-terminal/terminal.js.map +1 -0
  104. package/dist/browser-terminal/types.d.ts +595 -0
  105. package/dist/browser-terminal/types.d.ts.map +1 -0
  106. package/dist/browser-terminal/types.js +467 -0
  107. package/dist/browser-terminal/types.js.map +1 -0
  108. package/dist/browser-terminal/viewport-scroller.d.ts +94 -0
  109. package/dist/browser-terminal/viewport-scroller.d.ts.map +1 -0
  110. package/dist/browser-terminal/viewport-scroller.js +159 -0
  111. package/dist/browser-terminal/viewport-scroller.js.map +1 -0
  112. package/dist/browser-terminal/vt/effects.d.ts +114 -0
  113. package/dist/browser-terminal/vt/effects.d.ts.map +1 -0
  114. package/dist/browser-terminal/vt/effects.js +143 -0
  115. package/dist/browser-terminal/vt/effects.js.map +1 -0
  116. package/dist/browser-terminal/vt/enums.d.ts +155 -0
  117. package/dist/browser-terminal/vt/enums.d.ts.map +1 -0
  118. package/dist/browser-terminal/vt/enums.js +161 -0
  119. package/dist/browser-terminal/vt/enums.js.map +1 -0
  120. package/dist/browser-terminal/vt/mouse.d.ts +166 -0
  121. package/dist/browser-terminal/vt/mouse.d.ts.map +1 -0
  122. package/dist/browser-terminal/vt/mouse.js +259 -0
  123. package/dist/browser-terminal/vt/mouse.js.map +1 -0
  124. package/dist/browser-terminal/vt/paste.d.ts +53 -0
  125. package/dist/browser-terminal/vt/paste.d.ts.map +1 -0
  126. package/dist/browser-terminal/vt/paste.js +89 -0
  127. package/dist/browser-terminal/vt/paste.js.map +1 -0
  128. package/dist/browser-terminal/vt/render-state.d.ts +208 -0
  129. package/dist/browser-terminal/vt/render-state.d.ts.map +1 -0
  130. package/dist/browser-terminal/vt/render-state.js +776 -0
  131. package/dist/browser-terminal/vt/render-state.js.map +1 -0
  132. package/dist/browser-terminal/vt/style.d.ts +54 -0
  133. package/dist/browser-terminal/vt/style.d.ts.map +1 -0
  134. package/dist/browser-terminal/vt/style.js +92 -0
  135. package/dist/browser-terminal/vt/style.js.map +1 -0
  136. package/dist/browser-terminal/wasm-loader.d.ts +39 -0
  137. package/dist/browser-terminal/wasm-loader.d.ts.map +1 -0
  138. package/dist/browser-terminal/wasm-loader.js +73 -0
  139. package/dist/browser-terminal/wasm-loader.js.map +1 -0
  140. package/dist/browser-terminal/write-buffer.d.ts +40 -0
  141. package/dist/browser-terminal/write-buffer.d.ts.map +1 -0
  142. package/dist/browser-terminal/write-buffer.js +144 -0
  143. package/dist/browser-terminal/write-buffer.js.map +1 -0
  144. package/dist/protocol/index.d.ts +135 -0
  145. package/dist/protocol/index.d.ts.map +1 -0
  146. package/dist/protocol/index.js +76 -0
  147. package/dist/protocol/index.js.map +1 -0
  148. package/dist/react/index.d.ts +59 -0
  149. package/dist/react/index.d.ts.map +1 -0
  150. package/dist/react/index.js +146 -0
  151. package/dist/react/index.js.map +1 -0
  152. package/dist/server/index.d.ts +130 -0
  153. package/dist/server/index.d.ts.map +1 -0
  154. package/dist/server/index.js +191 -0
  155. package/dist/server/index.js.map +1 -0
  156. package/dist/terminal-screen-emulator/emulator.d.ts +66 -0
  157. package/dist/terminal-screen-emulator/emulator.d.ts.map +1 -0
  158. package/dist/terminal-screen-emulator/emulator.js +286 -0
  159. package/dist/terminal-screen-emulator/emulator.js.map +1 -0
  160. package/dist/terminal-screen-emulator/index.d.ts +82 -0
  161. package/dist/terminal-screen-emulator/index.d.ts.map +1 -0
  162. package/dist/terminal-screen-emulator/index.js +92 -0
  163. package/dist/terminal-screen-emulator/index.js.map +1 -0
  164. package/dist/terminal-screen-emulator/types.d.ts +382 -0
  165. package/dist/terminal-screen-emulator/types.d.ts.map +1 -0
  166. package/dist/terminal-screen-emulator/types.js +91 -0
  167. package/dist/terminal-screen-emulator/types.js.map +1 -0
  168. package/dist/terminal-screen-emulator/wasm-loader.d.ts +71 -0
  169. package/dist/terminal-screen-emulator/wasm-loader.d.ts.map +1 -0
  170. package/dist/terminal-screen-emulator/wasm-loader.js +162 -0
  171. package/dist/terminal-screen-emulator/wasm-loader.js.map +1 -0
  172. package/dist/themes/index.d.ts +6 -0
  173. package/dist/themes/index.d.ts.map +1 -0
  174. package/dist/themes/index.js +51 -0
  175. package/dist/themes/index.js.map +1 -0
  176. package/dist/wasm/alloc.d.ts +170 -0
  177. package/dist/wasm/alloc.d.ts.map +1 -0
  178. package/dist/wasm/alloc.js +307 -0
  179. package/dist/wasm/alloc.js.map +1 -0
  180. package/dist/wasm/compile.d.ts +73 -0
  181. package/dist/wasm/compile.d.ts.map +1 -0
  182. package/dist/wasm/compile.js +82 -0
  183. package/dist/wasm/compile.js.map +1 -0
  184. package/dist/wasm/exports.d.ts +234 -0
  185. package/dist/wasm/exports.d.ts.map +1 -0
  186. package/dist/wasm/exports.js +15 -0
  187. package/dist/wasm/exports.js.map +1 -0
  188. package/dist/wasm/fn-table.d.ts +119 -0
  189. package/dist/wasm/fn-table.d.ts.map +1 -0
  190. package/dist/wasm/fn-table.js +168 -0
  191. package/dist/wasm/fn-table.js.map +1 -0
  192. package/dist/wasm/memory.d.ts +59 -0
  193. package/dist/wasm/memory.d.ts.map +1 -0
  194. package/dist/wasm/memory.js +89 -0
  195. package/dist/wasm/memory.js.map +1 -0
  196. package/dist/wasm/type-layouts.d.ts +61 -0
  197. package/dist/wasm/type-layouts.d.ts.map +1 -0
  198. package/dist/wasm/type-layouts.js +32 -0
  199. package/dist/wasm/type-layouts.js.map +1 -0
  200. package/package.json +94 -0
  201. package/wasm/ghostty-vt.wasm +0 -0
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Terminal session host — the PTY-side endpoint of the session protocol.
3
+ *
4
+ * ## What this owns (the geometry-authority design)
5
+ *
6
+ * - **Geometry authority.** It is the *only* writer of the pty's size. Clients
7
+ * send proposals; this class arbitrates them under a {@link GeometryPolicy}
8
+ * and pushes the decision to the pty and to every attached client
9
+ * (Decision 1, tmux model).
10
+ * - **A mirror engine.** Every byte the pty emits is also fed to a headless VT
11
+ * engine, so the host knows the *current screen*, not just a byte log.
12
+ * - **Serialized replay.** On attach, the screen is serialized to a
13
+ * self-contained escape sequence (Decision 4) instead of replaying a raw
14
+ * scrollback slice, which can start mid-sequence and carries none of the
15
+ * state its discarded prefix established.
16
+ * - **Send ordering.** The host performs the sends, so the `attached` frame
17
+ * cannot be overtaken by live output — the interleaving window is closed by
18
+ * construction rather than by a lock.
19
+ *
20
+ * ## What this deliberately does NOT own
21
+ *
22
+ * Session *policy* stays with the application: the session registry, spawn
23
+ * command/cwd resolution, scope keys, retention, capacity limits, auth. This
24
+ * class takes an already-spawned {@link PtyHandle} so it stays runtime-agnostic
25
+ * (Bun, node-pty, ssh, a test double) and product-agnostic.
26
+ */
27
+ import { arbitrateGeometry, gridEquals, } from "../protocol/index.js";
28
+ import { createTerminalScreen } from "../terminal-screen-emulator/index.js";
29
+ import { OutputFormat } from "../terminal-screen-emulator/types.js";
30
+ export class TerminalSessionHost {
31
+ sessionId;
32
+ pty;
33
+ policy;
34
+ screen;
35
+ /** Attach order matters for `latest`; Map preserves insertion order. */
36
+ clients = new Map();
37
+ _geometry;
38
+ disposed = false;
39
+ constructor(opts, screen) {
40
+ this.sessionId = opts.sessionId;
41
+ this.pty = opts.pty;
42
+ this.policy = opts.policy ?? "latest";
43
+ this.screen = screen;
44
+ this._geometry = { ...opts.initialGeometry };
45
+ }
46
+ /** Create a host and its mirror engine. */
47
+ static async create(opts) {
48
+ const screen = await createTerminalScreen({
49
+ columns: opts.initialGeometry.cols,
50
+ rows: opts.initialGeometry.rows,
51
+ maxScrollbackLines: opts.mirrorScrollback ?? 0,
52
+ });
53
+ return new TerminalSessionHost(opts, screen);
54
+ }
55
+ /** The decided grid — authoritative for the pty, the mirror, and all clients. */
56
+ get geometry() {
57
+ return { ...this._geometry };
58
+ }
59
+ /** Number of attached clients (arbitration degrades to `smallest` above 1). */
60
+ get clientCount() {
61
+ return this.clients.size;
62
+ }
63
+ /**
64
+ * Feed pty output through the mirror engine and fan it out to clients.
65
+ *
66
+ * Ordering: the mirror is updated *before* the broadcast, so a client that
67
+ * attaches during this call (impossible today — single-threaded — but true of
68
+ * any future async transport) can never receive a replay that lags the bytes
69
+ * its peers already have.
70
+ */
71
+ ingest(data) {
72
+ if (this.disposed)
73
+ return;
74
+ this.screen.write(data);
75
+ this.broadcast({ kind: "output", data });
76
+ }
77
+ /**
78
+ * Attach a client with its geometry proposal, and send it the `attached`
79
+ * frame containing the decided geometry and a serialized screen.
80
+ *
81
+ * The host sends the frame itself, which is what closes the
82
+ * replay-vs-live-output interleaving window: registration and the snapshot
83
+ * send happen in one uninterrupted step, so no `output` frame can land
84
+ * between them.
85
+ */
86
+ attach(client, viewport) {
87
+ if (this.disposed)
88
+ return;
89
+ this.clients.set(client, { ...viewport });
90
+ // Re-arbitrate first: the replay must describe the screen at the geometry
91
+ // the client is about to adopt, not the previous one. The newcomer is
92
+ // excluded from the broadcast — its decided geometry rides the `attached`
93
+ // frame below, and a `geometry` frame arriving *before* `attached` would be
94
+ // the very out-of-order delivery this design exists to prevent.
95
+ this.rearbitrate(client);
96
+ client.send({
97
+ kind: "attached",
98
+ sessionId: this.sessionId,
99
+ geometry: this.geometry,
100
+ replay: this.serialize(),
101
+ });
102
+ }
103
+ /** Detach a client and re-arbitrate (its proposal no longer constrains). */
104
+ detach(client) {
105
+ if (!this.clients.delete(client))
106
+ return;
107
+ this.rearbitrate();
108
+ }
109
+ /**
110
+ * Handle a client frame. Input is forwarded byte-exact; `viewport` is a
111
+ * proposal that may or may not become the decision.
112
+ */
113
+ handle(client, frame) {
114
+ if (this.disposed)
115
+ return;
116
+ switch (frame.kind) {
117
+ case "attach":
118
+ this.attach(client, frame.viewport);
119
+ return;
120
+ case "viewport":
121
+ if (!this.clients.has(client))
122
+ return; // proposals from detached clients are noise
123
+ this.clients.set(client, { ...frame.viewport });
124
+ this.rearbitrate();
125
+ return;
126
+ case "input":
127
+ this.pty.write(frame.data);
128
+ return;
129
+ case "kill":
130
+ this.pty.kill();
131
+ return;
132
+ }
133
+ }
134
+ /**
135
+ * Serialize the current screen as a self-contained sequence.
136
+ *
137
+ * `RIS` (`ESC c`) first so the client's engine starts from a known state
138
+ * regardless of what it had before — the property a raw scrollback slice can
139
+ * never offer.
140
+ *
141
+ * Known limitation: this restores screen content and styling, not cursor
142
+ * position or application modes (the emulator renders cells, and
143
+ * `libghostty-vt` has no state-dump API yet). After a replay the cursor sits
144
+ * after the restored content. For a shell session the following resize nudge
145
+ * (or any keystroke) makes the app redraw and the cursor snaps back to truth.
146
+ * Cursor-exact replay needs an upstream state-dump — tracked in NEXT.md.
147
+ */
148
+ serialize() {
149
+ return `\x1bc${this.screen.render(OutputFormat.AnsiEscapes)}`;
150
+ }
151
+ /** Notify clients that the process exited. */
152
+ notifyExit(code) {
153
+ this.broadcast({ kind: "exit", code });
154
+ }
155
+ /** Release the mirror engine. Does not kill the pty (the app owns lifetime). */
156
+ dispose() {
157
+ if (this.disposed)
158
+ return;
159
+ this.disposed = true;
160
+ this.clients.clear();
161
+ this.screen.dispose();
162
+ }
163
+ /**
164
+ * Recompute the decision from all attached proposals and, if it changed,
165
+ * write it to the pty (sole writer), the mirror engine, and every client.
166
+ *
167
+ * The client broadcast goes through the same ordered channel as `output`, so
168
+ * each client applies the resize in the right position relative to the bytes
169
+ * around it.
170
+ *
171
+ * @param exclude A client that must not receive the broadcast because it is
172
+ * mid-attach and will learn the decision from its `attached` frame.
173
+ */
174
+ rearbitrate(exclude) {
175
+ const decided = arbitrateGeometry([...this.clients.values()], this.policy);
176
+ if (!decided || gridEquals(decided, this._geometry))
177
+ return;
178
+ this._geometry = decided;
179
+ this.pty.resize(decided);
180
+ this.screen.resize(decided.cols, decided.rows);
181
+ this.broadcast({ kind: "geometry", geometry: this.geometry }, exclude);
182
+ }
183
+ broadcast(frame, exclude) {
184
+ for (const client of this.clients.keys()) {
185
+ if (client === exclude)
186
+ continue;
187
+ client.send(frame);
188
+ }
189
+ }
190
+ }
191
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EACL,iBAAiB,EACjB,UAAU,GAKX,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAuB,MAAM,sCAAsC,CAAC;AAgCzF,MAAM,OAAO,mBAAmB;IACrB,SAAS,CAAS;IACV,GAAG,CAAY;IACf,MAAM,CAAiB;IACvB,MAAM,CAAiB;IACxC,wEAAwE;IACvD,OAAO,GAAG,IAAI,GAAG,EAAgC,CAAC;IAC3D,SAAS,CAAe;IACxB,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAoB,IAAgC,EAAE,MAAsB;QAC1E,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACpB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,QAAQ,CAAC;QACtC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,EAAE,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;IAC/C,CAAC;IAED,2CAA2C;IAC3C,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAA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AO;QAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED;;;;;;;;;;OAUG;IACK,WAAW,CAAC,OAAwB;QAC1C,MAAM,OAAO,GAAG,iBAAiB,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3E,IAAI,CAAC,OAAO,IAAI,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC;YAAE,OAAO;QAC5D,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC;QACzB,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACzB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,EAAE,OAAO,CAAC,CAAC;IACzE,CAAC;IAEO,SAAS,CAAC,KAA0B,EAAE,OAAwB;QACpE,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;YACzC,IAAI,MAAM,KAAK,OAAO;gBAAE,SAAS;YACjC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @module terminal-screen-emulator/emulator
3
+ *
4
+ * The core terminal screen emulator implementation.
5
+ *
6
+ * This module creates {@link TerminalScreen} instances backed by Ghostty's
7
+ * terminal emulator running in WebAssembly. Each instance maintains its own
8
+ * WASM linear memory and operates independently.
9
+ *
10
+ * Architecture:
11
+ * ```
12
+ * createTerminalScreen()
13
+ * → instantiateEmulator() (wasm-loader)
14
+ * → allocates terminal in WASM memory
15
+ * → returns TerminalScreen interface
16
+ * → write() feeds bytes to WASM terminal
17
+ * → render() creates formatter, extracts output, frees formatter
18
+ * → dispose() frees terminal + WASM instance
19
+ * ```
20
+ *
21
+ * @internal The implementation details are not part of the public API.
22
+ * Users interact only through the {@link TerminalScreen} interface.
23
+ */
24
+ import type { TerminalScreen, TerminalScreenConfig } from "./types.js";
25
+ /**
26
+ * Create a new terminal screen emulator instance.
27
+ *
28
+ * This is the primary entry point for the module. Each call creates an
29
+ * independent terminal emulator with its own WASM memory, screen buffer,
30
+ * and cursor state. Multiple instances can coexist without interference.
31
+ *
32
+ * The returned {@link TerminalScreen} provides a high-level, declarative API:
33
+ * - `write()` — feed raw terminal bytes (as if from a PTY)
34
+ * - `render()` — get the screen content in any format
35
+ * - `resize()` — change terminal dimensions
36
+ * - `reset()` — clear everything and start fresh
37
+ * - `dispose()` — free WASM memory when done
38
+ *
39
+ * @param config - Terminal dimensions and scrollback configuration.
40
+ * @returns A ready-to-use terminal screen emulator.
41
+ *
42
+ * @throws {Error} If the WASM binary cannot be found or loaded.
43
+ * @throws {Error} If terminal allocation fails.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * import { createTerminalScreen, OutputFormat } from "./index.js";
48
+ *
49
+ * const screen = await createTerminalScreen({ columns: 120, rows: 40 });
50
+ *
51
+ * // Feed it terminal output
52
+ * screen.write("\x1b[1;31mERROR\x1b[0m: connection refused\r\n");
53
+ * screen.write("\x1b[32m✓\x1b[0m All tests passed\r\n");
54
+ *
55
+ * // Get plain text (for AI agents)
56
+ * console.log(screen.render(OutputFormat.PlainText));
57
+ *
58
+ * // Get styled HTML (for web UIs)
59
+ * console.log(screen.render(OutputFormat.Html));
60
+ *
61
+ * // Clean up
62
+ * screen.dispose();
63
+ * ```
64
+ */
65
+ export declare function createTerminalScreen(config?: TerminalScreenConfig): Promise<TerminalScreen>;
66
+ //# sourceMappingURL=emulator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emulator.d.ts","sourceRoot":"","sources":["../../src/terminal-screen-emulator/emulator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EAGrB,MAAM,YAAY,CAAC;AAkPpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAsB,oBAAoB,CACxC,MAAM,GAAE,oBAAyB,GAChC,OAAO,CAAC,cAAc,CAAC,CAqGzB"}
@@ -0,0 +1,286 @@
1
+ /**
2
+ * @module terminal-screen-emulator/emulator
3
+ *
4
+ * The core terminal screen emulator implementation.
5
+ *
6
+ * This module creates {@link TerminalScreen} instances backed by Ghostty's
7
+ * terminal emulator running in WebAssembly. Each instance maintains its own
8
+ * WASM linear memory and operates independently.
9
+ *
10
+ * Architecture:
11
+ * ```
12
+ * createTerminalScreen()
13
+ * → instantiateEmulator() (wasm-loader)
14
+ * → allocates terminal in WASM memory
15
+ * → returns TerminalScreen interface
16
+ * → write() feeds bytes to WASM terminal
17
+ * → render() creates formatter, extracts output, frees formatter
18
+ * → dispose() frees terminal + WASM instance
19
+ * ```
20
+ *
21
+ * @internal The implementation details are not part of the public API.
22
+ * Users interact only through the {@link TerminalScreen} interface.
23
+ */
24
+ import { instantiateEmulator, } from "./wasm-loader.js";
25
+ // ─── Constants ───────────────────────────────────────────────────────────────
26
+ /** Return code indicating success from all ghostty_* functions. */
27
+ const GHOSTTY_SUCCESS = 0;
28
+ // ─── WASM Memory Helpers ─────────────────────────────────────────────────────
29
+ /**
30
+ * Write a value into a struct field in WASM memory.
31
+ *
32
+ * Uses the self-describing type layouts from `ghostty_type_json()` to
33
+ * determine the correct byte offset and encoding for each field.
34
+ * This means the wrapper adapts automatically if Ghostty reorders or
35
+ * resizes struct fields in a future version.
36
+ *
37
+ * @param view - DataView over the struct's memory region.
38
+ * @param layouts - All struct layouts from the WASM binary.
39
+ * @param structName - Name of the struct (e.g., "GhosttyTerminalOptions").
40
+ * @param fieldName - Name of the field within the struct.
41
+ * @param value - Numeric value to write.
42
+ * @param baseOffset - Additional offset (for nested structs).
43
+ *
44
+ * @throws {Error} If the struct or field name is not found in layouts.
45
+ * @throws {Error} If the field type is not supported.
46
+ */
47
+ function writeStructField(view, layouts, structName, fieldName, value, baseOffset = 0) {
48
+ const struct = layouts[structName];
49
+ if (!struct) {
50
+ throw new Error(`Unknown WASM struct: "${structName}". ` +
51
+ `Available: ${Object.keys(layouts).join(", ")}`);
52
+ }
53
+ const field = struct.fields[fieldName];
54
+ if (!field) {
55
+ throw new Error(`Unknown field "${fieldName}" in struct "${structName}". ` +
56
+ `Available: ${Object.keys(struct.fields).join(", ")}`);
57
+ }
58
+ const offset = baseOffset + field.offset;
59
+ switch (field.type) {
60
+ case "u8":
61
+ case "bool":
62
+ view.setUint8(offset, value);
63
+ break;
64
+ case "u16":
65
+ view.setUint16(offset, value, true); // little-endian
66
+ break;
67
+ case "u32":
68
+ case "enum":
69
+ view.setUint32(offset, value, true); // little-endian
70
+ break;
71
+ default:
72
+ throw new Error(`Unsupported field type "${field.type}" for field "${structName}.${fieldName}". ` +
73
+ `Supported: u8, u16, u32, bool, enum.`);
74
+ }
75
+ }
76
+ // ─── Terminal Allocation ─────────────────────────────────────────────────────
77
+ /**
78
+ * Allocate and initialize a terminal in WASM memory.
79
+ *
80
+ * Sets up the GhosttyTerminalOptions struct with the requested dimensions,
81
+ * calls `ghostty_terminal_new`, and returns the terminal pointer.
82
+ *
83
+ * @returns Pointer to the allocated terminal in WASM memory.
84
+ * @throws {Error} If terminal allocation fails.
85
+ */
86
+ function allocateTerminal(exports, layouts, columns, rows, maxScrollbackLines) {
87
+ // VT_NOTE: vendor/ghostty@6ad1fe7d8 removed `GhosttyTerminalOptions`;
88
+ // `ghostty_terminal_new` now takes (allocator, &handle, cols, rows) and
89
+ // scrollback is set via `ghostty_terminal_set(OPT_SCROLLBACK_MAX_LINES)`.
90
+ // libghostty-vt is pre-1.0 and declares its API unstable (vt.h:25), so this
91
+ // kind of shape change is expected on a bump.
92
+ void layouts;
93
+ const terminalOutPtr = exports.ghostty_wasm_alloc_opaque();
94
+ const result = exports.ghostty_terminal_new(0, terminalOutPtr, columns, rows);
95
+ if (result !== GHOSTTY_SUCCESS) {
96
+ exports.ghostty_wasm_free_opaque(terminalOutPtr);
97
+ throw new Error(`Failed to create terminal emulator (error code: ${result}). ` +
98
+ `Requested dimensions: ${columns}×${rows}, scrollback: ${maxScrollbackLines}.`);
99
+ }
100
+ // Read the terminal pointer from the out-parameter
101
+ const terminalPtr = new DataView(exports.memory.buffer).getUint32(terminalOutPtr, true);
102
+ exports.ghostty_wasm_free_opaque(terminalOutPtr);
103
+ return terminalPtr;
104
+ }
105
+ // ─── Screen Rendering ────────────────────────────────────────────────────────
106
+ /**
107
+ * Render the terminal screen content using Ghostty's formatter.
108
+ *
109
+ * Creates a formatter with the specified options, executes it to produce
110
+ * output, reads the result from WASM memory, and cleans up all temporary
111
+ * allocations.
112
+ *
113
+ * @returns The rendered screen content as a string.
114
+ * @throws {Error} If formatter creation or execution fails.
115
+ */
116
+ function renderScreen(exports, layouts, terminalPtr, format, unwrapSoftWraps, trimTrailingWhitespace) {
117
+ // ─── Build formatter options struct ────────────────────────────────────
118
+ const formatterOptionsSize = layouts.GhosttyFormatterTerminalOptions.size;
119
+ const formatterOptionsPtr = exports.ghostty_wasm_alloc_u8_array(formatterOptionsSize);
120
+ new Uint8Array(exports.memory.buffer, formatterOptionsPtr, formatterOptionsSize).fill(0);
121
+ const optionsView = new DataView(exports.memory.buffer, formatterOptionsPtr, formatterOptionsSize);
122
+ // Top-level fields
123
+ writeStructField(optionsView, layouts, "GhosttyFormatterTerminalOptions", "size", formatterOptionsSize);
124
+ writeStructField(optionsView, layouts, "GhosttyFormatterTerminalOptions", "emit", format);
125
+ writeStructField(optionsView, layouts, "GhosttyFormatterTerminalOptions", "unwrap", unwrapSoftWraps ? 1 : 0);
126
+ writeStructField(optionsView, layouts, "GhosttyFormatterTerminalOptions", "trim", trimTrailingWhitespace ? 1 : 0);
127
+ // Nested struct sizes (Ghostty's versioned struct pattern requires these)
128
+ const extraFieldOffset = layouts.GhosttyFormatterTerminalOptions.fields.extra.offset;
129
+ const extraStructSize = layouts.GhosttyFormatterTerminalExtra.size;
130
+ const extraSizeFieldOffset = layouts.GhosttyFormatterTerminalExtra.fields.size.offset;
131
+ optionsView.setUint32(extraFieldOffset + extraSizeFieldOffset, extraStructSize, true);
132
+ const screenFieldOffset = layouts.GhosttyFormatterTerminalExtra.fields.screen.offset;
133
+ const screenStructSize = layouts.GhosttyFormatterScreenExtra.size;
134
+ const screenSizeFieldOffset = layouts.GhosttyFormatterScreenExtra.fields.size.offset;
135
+ optionsView.setUint32(extraFieldOffset + screenFieldOffset + screenSizeFieldOffset, screenStructSize, true);
136
+ // ─── Create formatter ──────────────────────────────────────────────────
137
+ const formatterOutPtr = exports.ghostty_wasm_alloc_opaque();
138
+ const createResult = exports.ghostty_formatter_terminal_new(0, formatterOutPtr, terminalPtr, formatterOptionsPtr);
139
+ // Free options (no longer needed after formatter creation)
140
+ exports.ghostty_wasm_free_u8_array(formatterOptionsPtr, formatterOptionsSize);
141
+ if (createResult !== GHOSTTY_SUCCESS) {
142
+ exports.ghostty_wasm_free_opaque(formatterOutPtr);
143
+ throw new Error(`Failed to create screen formatter (error code: ${createResult}). ` +
144
+ `Format: ${format}, unwrap: ${unwrapSoftWraps}, trim: ${trimTrailingWhitespace}.`);
145
+ }
146
+ const formatterPtr = new DataView(exports.memory.buffer).getUint32(formatterOutPtr, true);
147
+ exports.ghostty_wasm_free_opaque(formatterOutPtr);
148
+ // ─── Execute formatter ─────────────────────────────────────────────────
149
+ const outputPtrPtr = exports.ghostty_wasm_alloc_opaque();
150
+ const outputLenPtr = exports.ghostty_wasm_alloc_usize();
151
+ const formatResult = exports.ghostty_formatter_format_alloc(formatterPtr, 0, outputPtrPtr, outputLenPtr);
152
+ if (formatResult !== GHOSTTY_SUCCESS) {
153
+ exports.ghostty_formatter_free(formatterPtr);
154
+ exports.ghostty_wasm_free_opaque(outputPtrPtr);
155
+ exports.ghostty_wasm_free_usize(outputLenPtr);
156
+ throw new Error(`Screen formatter execution failed (error code: ${formatResult}).`);
157
+ }
158
+ // ─── Read output from WASM memory ──────────────────────────────────────
159
+ const outputPtr = new DataView(exports.memory.buffer).getUint32(outputPtrPtr, true);
160
+ const outputLen = new DataView(exports.memory.buffer).getUint32(outputLenPtr, true);
161
+ let renderedText = "";
162
+ if (outputLen > 0) {
163
+ const outputBytes = new Uint8Array(exports.memory.buffer, outputPtr, outputLen);
164
+ renderedText = new TextDecoder().decode(outputBytes);
165
+ exports.ghostty_free(0, outputPtr, outputLen);
166
+ }
167
+ // ─── Cleanup ───────────────────────────────────────────────────────────
168
+ exports.ghostty_wasm_free_opaque(outputPtrPtr);
169
+ exports.ghostty_wasm_free_usize(outputLenPtr);
170
+ exports.ghostty_formatter_free(formatterPtr);
171
+ return renderedText;
172
+ }
173
+ // ─── Factory ─────────────────────────────────────────────────────────────────
174
+ /**
175
+ * Create a new terminal screen emulator instance.
176
+ *
177
+ * This is the primary entry point for the module. Each call creates an
178
+ * independent terminal emulator with its own WASM memory, screen buffer,
179
+ * and cursor state. Multiple instances can coexist without interference.
180
+ *
181
+ * The returned {@link TerminalScreen} provides a high-level, declarative API:
182
+ * - `write()` — feed raw terminal bytes (as if from a PTY)
183
+ * - `render()` — get the screen content in any format
184
+ * - `resize()` — change terminal dimensions
185
+ * - `reset()` — clear everything and start fresh
186
+ * - `dispose()` — free WASM memory when done
187
+ *
188
+ * @param config - Terminal dimensions and scrollback configuration.
189
+ * @returns A ready-to-use terminal screen emulator.
190
+ *
191
+ * @throws {Error} If the WASM binary cannot be found or loaded.
192
+ * @throws {Error} If terminal allocation fails.
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * import { createTerminalScreen, OutputFormat } from "./index.js";
197
+ *
198
+ * const screen = await createTerminalScreen({ columns: 120, rows: 40 });
199
+ *
200
+ * // Feed it terminal output
201
+ * screen.write("\x1b[1;31mERROR\x1b[0m: connection refused\r\n");
202
+ * screen.write("\x1b[32m✓\x1b[0m All tests passed\r\n");
203
+ *
204
+ * // Get plain text (for AI agents)
205
+ * console.log(screen.render(OutputFormat.PlainText));
206
+ *
207
+ * // Get styled HTML (for web UIs)
208
+ * console.log(screen.render(OutputFormat.Html));
209
+ *
210
+ * // Clean up
211
+ * screen.dispose();
212
+ * ```
213
+ */
214
+ export async function createTerminalScreen(config = {}) {
215
+ const { columns = 80, rows = 24, maxScrollbackLines = 0, } = config;
216
+ // Instantiate a fresh WASM instance
217
+ const { exports, typeLayouts } = await instantiateEmulator();
218
+ // Allocate the terminal in WASM memory
219
+ const terminalPtr = allocateTerminal(exports, typeLayouts, columns, rows, maxScrollbackLines);
220
+ // Track disposal state
221
+ let isDisposed = false;
222
+ /**
223
+ * Guard against use-after-dispose.
224
+ * @throws {Error} If the screen has been disposed.
225
+ */
226
+ function assertAlive() {
227
+ if (isDisposed) {
228
+ throw new Error("This TerminalScreen has been disposed and cannot be used. " +
229
+ "Create a new instance with createTerminalScreen().");
230
+ }
231
+ }
232
+ // ─── Build the TerminalScreen interface ────────────────────────────────
233
+ const screen = {
234
+ write(data) {
235
+ assertAlive();
236
+ const bytes = typeof data === "string"
237
+ ? new TextEncoder().encode(data)
238
+ : data;
239
+ if (bytes.length === 0)
240
+ return;
241
+ // Copy bytes into WASM memory and feed to terminal
242
+ const dataPtr = exports.ghostty_wasm_alloc_u8_array(bytes.length);
243
+ new Uint8Array(exports.memory.buffer).set(bytes, dataPtr);
244
+ exports.ghostty_terminal_vt_write(terminalPtr, dataPtr, bytes.length);
245
+ exports.ghostty_wasm_free_u8_array(dataPtr, bytes.length);
246
+ },
247
+ render(options) {
248
+ assertAlive();
249
+ // Normalize options
250
+ let format;
251
+ let unwrapSoftWraps = false;
252
+ let trimTrailingWhitespace = true;
253
+ if (options === undefined) {
254
+ format = 0; // PlainText
255
+ }
256
+ else if (typeof options === "number") {
257
+ format = options;
258
+ }
259
+ else {
260
+ format = options.format;
261
+ unwrapSoftWraps = options.unwrapSoftWraps ?? false;
262
+ trimTrailingWhitespace = options.trimTrailingWhitespace ?? true;
263
+ }
264
+ return renderScreen(exports, typeLayouts, terminalPtr, format, unwrapSoftWraps, trimTrailingWhitespace);
265
+ },
266
+ resize(newColumns, newRows) {
267
+ assertAlive();
268
+ if (newColumns <= 0 || newRows <= 0) {
269
+ throw new Error(`Invalid dimensions: ${newColumns}×${newRows}. Both must be positive integers.`);
270
+ }
271
+ exports.ghostty_terminal_resize(terminalPtr, newColumns, newRows);
272
+ },
273
+ reset() {
274
+ assertAlive();
275
+ exports.ghostty_terminal_reset(terminalPtr);
276
+ },
277
+ dispose() {
278
+ if (isDisposed)
279
+ return; // Idempotent
280
+ isDisposed = true;
281
+ exports.ghostty_terminal_free(terminalPtr);
282
+ },
283
+ };
284
+ return screen;
285
+ }
286
+ //# sourceMappingURL=emulator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emulator.js","sourceRoot":"","sources":["../../src/terminal-screen-emulator/emulator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AASH,OAAO,EACL,mBAAmB,GAGpB,MAAM,kBAAkB,CAAC;AAE1B,gFAAgF;AAEhF,mEAAmE;AACnE,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,gFAAgF;AAEhF;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAS,gBAAgB,CACvB,IAAc,EACd,OAAwB,EACxB,UAAkB,EAClB,SAAiB,EACjB,KAAa,EACb,UAAU,GAAG,CAAC;IAEd,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IACnC,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CACb,yBAAyB,UAAU,KAAK;YACtC,cAAc,MAAM,CAAC,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,WAAW,EACX,WAAW,EACX,MAAM,EACN,eAAe,EACf,sBAAsB,CACvB,CAAC;QACJ,CAAC;QAED,MAAM,CAAC,UAAkB,EAAE,OAAe;YACxC,WAAW,EAAE,CAAC;YAEd,IAAI,UAAU,IAAI,CAAC,IAAI,OAAO,IAAI,CAAC,EAAE,CAAC;gBACpC,MAAM,IAAI,KAAK,CACb,uBAAuB,UAAU,IAAI,OAAO,mCAAmC,CAChF,CAAC;YACJ,CAAC;YAED,OAAO,CAAC,uBAAuB,CAAC,WAAW,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC;QAED,KAAK;YACH,WAAW,EAAE,CAAC;YACd,OAAO,CAAC,sBAAsB,CAAC,WAAW,CAAC,CAAC;QAC9C,CAAC;QAED,OAAO;YACL,IAAI,UAAU;gBAAE,OAAO,CAAC,aAAa;YACrC,UAAU,GAAG,IAAI,CAAC;YAClB,OAAO,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAC;QAC7C,CAAC;KACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,82 @@
1
+ /**
2
+ * # Terminal Screen Emulator
3
+ *
4
+ * A virtual terminal that processes raw VT/ANSI escape sequences and renders
5
+ * the screen content as plain text, styled HTML, or preserved escape sequences.
6
+ *
7
+ * Powered by [Ghostty](https://github.com/ghostty-org/ghostty)'s terminal
8
+ * emulator compiled to WebAssembly — the same engine that renders Ghostty's
9
+ * actual terminal UI, running in Node.js.
10
+ *
11
+ * ## What It Does
12
+ *
13
+ * Feed it raw bytes (as if from a PTY or terminal process) and it maintains
14
+ * a complete in-memory terminal screen — cursor position, colors, text
15
+ * attributes, line wrapping, scrollback, alternate buffer, and all.
16
+ *
17
+ * Then ask it to render the screen in any format:
18
+ * - **PlainText** — just the visible characters (for AI agents, search, logs)
19
+ * - **Html** — styled `<span>` elements with inline CSS (for web UIs)
20
+ * - **AnsiEscapes** — preserved VT sequences (for piping to another terminal)
21
+ *
22
+ * ## Quick Start
23
+ *
24
+ * ```typescript
25
+ * import {
26
+ * createTerminalScreen,
27
+ * OutputFormat,
28
+ * } from "@gkoreli/ghostty-vt-js/terminal-screen-emulator";
29
+ *
30
+ * // Create a virtual 120×40 terminal
31
+ * const screen = await createTerminalScreen({ columns: 120, rows: 40 });
32
+ *
33
+ * // Feed it terminal output (raw bytes with escape sequences)
34
+ * screen.write("\x1b[1;31mERROR\x1b[0m: connection refused\r\n");
35
+ * screen.write("\x1b[32m✓\x1b[0m 42 tests passed\r\n");
36
+ *
37
+ * // Render as plain text (for AI consumption)
38
+ * const text = screen.render(OutputFormat.PlainText);
39
+ * // → "ERROR: connection refused\n✓ 42 tests passed\n"
40
+ *
41
+ * // Render as HTML (for web display)
42
+ * const html = screen.render(OutputFormat.Html);
43
+ * // → '<span style="font-weight: bold; color: #ff0000">ERROR</span>: ...'
44
+ *
45
+ * // Resize the terminal (reflows content)
46
+ * screen.resize(80, 24);
47
+ *
48
+ * // Clean up WASM memory when done
49
+ * screen.dispose();
50
+ * ```
51
+ *
52
+ * ## Architecture
53
+ *
54
+ * ```
55
+ * ┌─────────────────────────────────────────────────────────┐
56
+ * │ Your Code │
57
+ * │ screen.write(bytes) → screen.render(format) │
58
+ * ├─────────────────────────────────────────────────────────┤
59
+ * │ Terminal Screen Emulator (this module) │
60
+ * │ TypeScript wrapper — types, validation, memory mgmt │
61
+ * ├─────────────────────────────────────────────────────────┤
62
+ * │ ghostty-vt.wasm (542KB) │
63
+ * │ Ghostty's terminal emulator compiled to WebAssembly │
64
+ * │ Full VT100/VT220/xterm protocol implementation │
65
+ * └─────────────────────────────────────────────────────────┘
66
+ * ```
67
+ *
68
+ * ## Design Principles
69
+ *
70
+ * - **Declarative** — describe what you want (format, dimensions), not how
71
+ * - **Zero manual memory management** — all WASM pointers handled internally
72
+ * - **Self-describing** — adapts to Ghostty version changes via runtime introspection
73
+ * - **Independent instances** — each screen has its own WASM memory, no shared state
74
+ * - **Fail-fast** — clear errors with context, never silent corruption
75
+ *
76
+ * @module terminal-screen-emulator
77
+ * @packageDocumentation
78
+ */
79
+ export { createTerminalScreen } from "./emulator.js";
80
+ export { preloadEmulatorWasm } from "./wasm-loader.js";
81
+ export { type TerminalScreen, type TerminalScreenConfig, OutputFormat, type RenderOptions, UnderlineStyle, type RgbColor, type TextAttributes, type StyledTextSpan, type StyledTextLine, } from "./types.js";
82
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/terminal-screen-emulator/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6EG;AAKH,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAKrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAGvD,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,oBAAoB,EAGzB,YAAY,EACZ,KAAK,aAAa,EAGlB,cAAc,EACd,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,cAAc,GACpB,MAAM,YAAY,CAAC"}