tabby-rdp 0.6.1 → 0.6.4

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 (44) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +16 -11
  3. package/bin/SHA256SUMS +8 -8
  4. package/bin/darwin-arm64/tabby-rdp-proxy +0 -0
  5. package/bin/darwin-x64/tabby-rdp-proxy +0 -0
  6. package/bin/linux-arm/tabby-rdp-proxy +0 -0
  7. package/bin/linux-arm64/tabby-rdp-proxy +0 -0
  8. package/bin/linux-x64/tabby-rdp-proxy +0 -0
  9. package/bin/win32-arm64/tabby-rdp-proxy.exe +0 -0
  10. package/bin/win32-x64/tabby-rdp-proxy.exe +0 -0
  11. package/dist/audio.js +26 -5
  12. package/dist/clipboard.js +8 -2
  13. package/dist/desktop.service.js +60 -14
  14. package/dist/desktopForm.js +1 -1
  15. package/dist/fileTransfer.js +41 -8
  16. package/dist/freerdp.js +36 -14
  17. package/dist/freerdpClipboard.js +39 -9
  18. package/dist/freerdpFiles.js +183 -0
  19. package/dist/freerdpView.js +6 -0
  20. package/dist/freerdpWasm.js +183 -0
  21. package/dist/freerdpWasmSocket.js +28 -0
  22. package/dist/freerdpWasmWorker.js +174 -0
  23. package/dist/pduTrace.js +27 -5
  24. package/dist/rdpClient.js +2 -2
  25. package/dist/rdpProfile.js +2 -2
  26. package/dist/settingsPage.js +6 -6
  27. package/dist/ui.js +2 -2
  28. package/dist/zgfx.js +33 -18
  29. package/native/README.md +74 -33
  30. package/package.json +6 -18
  31. package/vendor/SHA256SUMS +16 -5
  32. package/vendor/iron-remote-desktop-rdp.js +301 -301
  33. package/vendor/iron-remote-desktop.js +770 -736
  34. package/vendor/ironrdp-factory.js +301 -301
  35. package/vendor/ironrdp_web_bg.wasm +0 -0
  36. package/wasm/freerdp/BUILD.json +63 -0
  37. package/wasm/freerdp/licenses/Emscripten-LICENSE +102 -0
  38. package/wasm/freerdp/licenses/FreeRDP-LICENSE +202 -0
  39. package/wasm/freerdp/licenses/FreeRDP-NOTICE +13 -0
  40. package/wasm/freerdp/licenses/LibreSSL-LICENSE +133 -0
  41. package/wasm/freerdp/licenses/Unicode-NOTICE +21 -0
  42. package/wasm/freerdp/licenses/zlib-LICENSE +22 -0
  43. package/wasm/freerdp/tabby-freerdp.js +2 -0
  44. package/wasm/freerdp/tabby-freerdp.wasm +0 -0
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_WASM_SOCKET_BACKLOG = void 0;
4
+ exports.boundedWebSocket = boundedWebSocket;
5
+ /** Maximum data retained by a WASM socket when its peer stops reading. */
6
+ exports.MAX_WASM_SOCKET_BACKLOG = 64 * 1024 * 1024;
7
+ /** Used only in the isolated WASM worker, before Emscripten loads its ws constructor. */
8
+ function boundedWebSocket(Socket, overflow) {
9
+ return class extends Socket {
10
+ constructor() {
11
+ super(...arguments);
12
+ this.overflowed = false;
13
+ }
14
+ send(data, ...args) {
15
+ if (this.overflowed) {
16
+ return;
17
+ }
18
+ const size = typeof data === 'string' ? Buffer.byteLength(data) : data?.byteLength ?? data?.length ?? 0;
19
+ if (!Number.isSafeInteger(size) || size < 0 || this.bufferedAmount + size > exports.MAX_WASM_SOCKET_BACKLOG) {
20
+ this.overflowed = true;
21
+ this.terminate();
22
+ overflow();
23
+ return;
24
+ }
25
+ super.send(data, ...args);
26
+ }
27
+ };
28
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /** Runs one FreeRDP WASM instance and its pthreads away from Tabby's renderer. */
4
+ const worker_threads_1 = require("worker_threads");
5
+ const freerdpWasmSocket_1 = require("./freerdpWasmSocket");
6
+ let utilityChannel;
7
+ const utilityPort = process.parentPort;
8
+ const port = worker_threads_1.parentPort ? {
9
+ postMessage: (message, transfer) => worker_threads_1.parentPort.postMessage(message, transfer ?? []),
10
+ on: (event, listener) => worker_threads_1.parentPort.on(event, listener),
11
+ } : {
12
+ postMessage: message => utilityChannel?.postMessage(message),
13
+ on: (event, listener) => utilityPort.on(event, (message) => {
14
+ if (message.data?.type !== 'port' || utilityChannel)
15
+ return;
16
+ utilityChannel = message.ports[0];
17
+ utilityChannel.on('close', ownerGone);
18
+ utilityChannel.on('message', (message) => listener(message.data));
19
+ utilityChannel.start();
20
+ utilityChannel.postMessage({ type: 'ready' });
21
+ }),
22
+ };
23
+ const SIZE = 1024 * 1024;
24
+ let moduleInstance;
25
+ let starting = false;
26
+ let inputAddress = 0, outputAddress = 0;
27
+ let input;
28
+ let outputWaiting = false;
29
+ let timer;
30
+ let stopping = false;
31
+ /** Wake blocked certificate/input/output waits when the renderer or pipe disappears. */
32
+ function closeRings() {
33
+ if (!moduleInstance || !inputAddress || !outputAddress) {
34
+ return;
35
+ }
36
+ for (const address of [inputAddress, outputAddress]) {
37
+ const counters = new Int32Array(moduleInstance.HEAPU8.buffer, address, 3);
38
+ Atomics.store(counters, 2, 1);
39
+ Atomics.notify(counters, 0);
40
+ Atomics.notify(counters, 1);
41
+ }
42
+ }
43
+ function ownerGone() {
44
+ if (stopping) {
45
+ return;
46
+ }
47
+ stopping = true;
48
+ clearInterval(timer);
49
+ input = undefined;
50
+ closeRings();
51
+ // A thread blocked outside the rings must not keep an ownerless session alive.
52
+ setTimeout(() => process.exit(0), 250);
53
+ }
54
+ worker_threads_1.parentPort?.on('close', ownerGone);
55
+ utilityPort?.on('close', ownerGone);
56
+ function pumpInput() {
57
+ if (!input || !moduleInstance) {
58
+ return;
59
+ }
60
+ const heap = moduleInstance.HEAPU8;
61
+ const counters = new Int32Array(heap.buffer, inputAddress, 3);
62
+ let read = Atomics.load(counters, 0) >>> 0, write = Atomics.load(counters, 1) >>> 0;
63
+ while (input.offset < input.data.length) {
64
+ const available = SIZE - ((write - read) >>> 0);
65
+ if (!available) {
66
+ return;
67
+ }
68
+ const count = Math.min(available, SIZE - write % SIZE, input.data.length - input.offset);
69
+ heap.set(input.data.subarray(input.offset, input.offset + count), inputAddress + 12 + write % SIZE);
70
+ input.offset += count;
71
+ write = (write + count) >>> 0;
72
+ Atomics.store(counters, 1, write);
73
+ Atomics.notify(counters, 1);
74
+ read = Atomics.load(counters, 0) >>> 0;
75
+ }
76
+ input = undefined;
77
+ port.postMessage({ type: 'input-ack' });
78
+ }
79
+ function pumpOutput(ending = false) {
80
+ if (!moduleInstance || outputWaiting && !ending) {
81
+ return;
82
+ }
83
+ const heap = moduleInstance.HEAPU8;
84
+ const counters = new Int32Array(heap.buffer, outputAddress, 3);
85
+ let read = Atomics.load(counters, 0) >>> 0;
86
+ const write = Atomics.load(counters, 1) >>> 0;
87
+ while (read !== write) {
88
+ const count = Math.min((write - read) >>> 0, SIZE - read % SIZE);
89
+ const bytes = new Uint8Array(count);
90
+ bytes.set(heap.subarray(outputAddress + 12 + read % SIZE, outputAddress + 12 + read % SIZE + count));
91
+ read = (read + count) >>> 0;
92
+ Atomics.store(counters, 0, read);
93
+ Atomics.notify(counters, 0);
94
+ outputWaiting = true;
95
+ port.postMessage({ type: 'output', data: bytes }, [bytes.buffer]);
96
+ if (!ending) {
97
+ break;
98
+ }
99
+ }
100
+ }
101
+ port.on('message', message => {
102
+ if (message.type === 'eof') {
103
+ ownerGone();
104
+ return;
105
+ }
106
+ if (stopping) {
107
+ return;
108
+ }
109
+ if (message.type === 'init' && !starting) {
110
+ starting = true;
111
+ start(message.config).catch(failed);
112
+ }
113
+ else if (message.type === 'input') {
114
+ if (input) {
115
+ throw new Error('FreeRDP WASM input queue overflow');
116
+ }
117
+ input = { data: message.data, offset: 0 };
118
+ pumpInput();
119
+ }
120
+ else if (message.type === 'output-ack') {
121
+ outputWaiting = false;
122
+ pumpOutput();
123
+ }
124
+ });
125
+ async function start(config) {
126
+ // Emscripten's nonblocking socket shim calls ws.send in this isolated worker. Bound that
127
+ // final queue as well as the IPC rings: a peer can request file ranges without reading them.
128
+ const wsPath = require.resolve('ws');
129
+ const Socket = require(wsPath);
130
+ require.cache[wsPath].exports = (0, freerdpWasmSocket_1.boundedWebSocket)(Socket, () => failed('FreeRDP stopped: the server is not reading uploaded data'));
131
+ const createFreeRDP = require(config.module);
132
+ moduleInstance = await createFreeRDP({
133
+ noInitialRun: true,
134
+ websocket: { url: config.websocket, subprotocol: 'binary' },
135
+ // FreeRDP logs can contain authentication details. Only framed IPC leaves this worker.
136
+ print: () => { }, printErr: () => { },
137
+ onAbort: () => failed('FreeRDP WebAssembly aborted'),
138
+ onExit: (code) => {
139
+ clearInterval(timer);
140
+ if (!stopping) {
141
+ pumpOutput(true);
142
+ port.postMessage({ type: 'exit', code });
143
+ }
144
+ stopping = true;
145
+ // The renderer normally kills us after receiving the ordered final output and exit
146
+ // messages. Leave time for Electron's message port to flush; bound a missing owner.
147
+ setTimeout(() => process.exit(code), 5000);
148
+ },
149
+ });
150
+ inputAddress = moduleInstance._tabby_input_buffer();
151
+ outputAddress = moduleInstance._tabby_output_buffer();
152
+ if (stopping) {
153
+ closeRings();
154
+ return;
155
+ }
156
+ timer = setInterval(() => { pumpInput(); pumpOutput(); }, 1);
157
+ pumpInput();
158
+ moduleInstance.callMain([]);
159
+ }
160
+ function failed(reason) {
161
+ if (stopping) {
162
+ return;
163
+ }
164
+ try {
165
+ port.postMessage({ type: 'failure', message: typeof reason === 'string' ? reason : 'Could not initialise FreeRDP WebAssembly' });
166
+ }
167
+ finally {
168
+ ownerGone();
169
+ }
170
+ }
171
+ if (worker_threads_1.workerData) {
172
+ starting = true;
173
+ start(worker_threads_1.workerData).catch(failed);
174
+ }
package/dist/pduTrace.js CHANGED
@@ -286,11 +286,25 @@ function parseSps(nal) {
286
286
  rbsp.push(nal[i]);
287
287
  }
288
288
  let pos = 0;
289
- const bit = () => { const b = (rbsp[pos >> 3] >> (7 - (pos & 7))) & 1; pos++; return b; };
289
+ const bit = () => {
290
+ if (pos >= rbsp.length * 8) {
291
+ throw new Error('Truncated SPS');
292
+ }
293
+ const b = (rbsp[pos >> 3] >> (7 - (pos & 7))) & 1;
294
+ pos++;
295
+ return b;
296
+ };
290
297
  const bits = (n) => { let v = 0; for (let i = 0; i < n; i++)
291
298
  v = v * 2 + bit(); return v; };
292
- const ue = () => { let zeros = 0; while (bit() === 0 && zeros < 32)
293
- zeros++; return (1 << zeros) - 1 + bits(zeros); };
299
+ const ue = () => {
300
+ let zeros = 0;
301
+ while (bit() === 0) {
302
+ if (++zeros > 31) {
303
+ throw new Error('Oversized SPS value');
304
+ }
305
+ }
306
+ return 2 ** zeros - 1 + bits(zeros);
307
+ };
294
308
  const se = () => { const v = ue(); return v & 1 ? (v + 1) / 2 : -v / 2; };
295
309
  const profile = bits(8);
296
310
  bits(8); // constraints
@@ -329,6 +343,9 @@ function parseSps(nal) {
329
343
  se();
330
344
  se();
331
345
  const n = ue();
346
+ if (n > 255) {
347
+ return null;
348
+ }
332
349
  for (let i = 0; i < n; i++)
333
350
  se();
334
351
  }
@@ -452,6 +469,9 @@ class PduTrace {
452
469
  const trace = this;
453
470
  const handed = new Map();
454
471
  const wrapper = Object.create(decoder);
472
+ if (typeof decoder.close === 'function') {
473
+ wrapper.close = () => { handed.clear(); decoder.close(); };
474
+ }
455
475
  wrapper.decode = (frame, done) => {
456
476
  const t = trace.now();
457
477
  handed.set(frame.id, t);
@@ -535,8 +555,10 @@ class PduTrace {
535
555
  }
536
556
  this.events.push(event);
537
557
  if (this.events.length > exports.MAX_EVENTS) {
538
- this.events.splice(0, this.events.length - exports.MAX_EVENTS);
539
- this.dropped++;
558
+ // Trim in batches so a long trace does not shift 150,000 entries for every event.
559
+ const count = Math.max(this.events.length - exports.MAX_EVENTS, Math.ceil(exports.MAX_EVENTS / 10));
560
+ this.events.splice(0, count);
561
+ this.dropped += count;
540
562
  }
541
563
  return event;
542
564
  }
package/dist/rdpClient.js CHANGED
@@ -6,11 +6,11 @@ exports.rdpClient = rdpClient;
6
6
  exports.isRDPElement = isRDPElement;
7
7
  exports.RDP_CLIENT_LABELS = {
8
8
  ironrdp: 'IronRDP',
9
- freerdp: 'FreeRDP (experimental)',
9
+ freerdp: 'FreeRDP',
10
10
  };
11
11
  /** An absent or invalid override follows the global setting. Existing installations keep IronRDP. */
12
12
  function ownRDPClient(value) {
13
- return value === 'ironrdp' || value === 'freerdp' ? value : undefined;
13
+ return value === 'freerdp-wasm' ? 'freerdp' : value === 'ironrdp' || value === 'freerdp' ? value : undefined;
14
14
  }
15
15
  function rdpClient(value) {
16
16
  return ownRDPClient(value) ?? 'ironrdp';
@@ -158,8 +158,8 @@ let RDPProfileSettingsComponent = class RDPProfileSettingsComponent {
158
158
  <div class="mb-3">
159
159
  <label>RDP client</label>
160
160
  <select class="form-control" name="client" aria-label="RDP client"></select>
161
- <div class="text-muted small">Applies on the next connection. FreeRDP preview supports display and input;
162
- clipboard, sound and shared folders are unavailable.</div>
161
+ <div class="text-muted small">Applies on the next connection. FreeRDP supports display, input and clipboard text/files.
162
+ Clipboard images, sound, microphone and shared folders require IronRDP.</div>
163
163
  </div>` + `
164
164
  <div class="mb-3">
165
165
  <label>Account</label>
@@ -258,7 +258,7 @@ let RemoteDesktopSettingsComponent = class RemoteDesktopSettingsComponent {
258
258
  <div class="header">
259
259
  <div class="title">RDP client</div>
260
260
  <div class="description">Default for new connections. Each desktop can choose its own client.
261
- FreeRDP preview supports display and input; clipboard, sound and shared folders are unavailable.</div>
261
+ FreeRDP WebAssembly supports display, input and text/file clipboard transfers. Sound, microphone, clipboard pictures, shared folders and H.264 require IronRDP.</div>
262
262
  </div>
263
263
  <select class="form-control" data-setting="client" aria-label="RDP client">
264
264
  ${Object.entries(rdpClient_1.RDP_CLIENT_LABELS).map(([id, label]) => `<option value="${id}">${(0, help_1.esc)(label)}</option>`).join('')}
@@ -287,7 +287,7 @@ let RemoteDesktopSettingsComponent = class RemoteDesktopSettingsComponent {
287
287
  <option value="retina">Retina</option>
288
288
  </select>
289
289
  </div>
290
- ${this.toggleLine('h264', 'Video decoding (H.264)', 'Hardware acceleration where available. Applies on the next connection.')}
290
+ ${this.toggleLine('h264', 'Video decoding (H.264)', 'IronRDP only. Hardware acceleration where available. Applies on the next connection.')}
291
291
  <div class="form-line">
292
292
  <div class="header">
293
293
  <div class="title">Auto-hide header</div>
@@ -326,8 +326,8 @@ let RemoteDesktopSettingsComponent = class RemoteDesktopSettingsComponent {
326
326
  </div>
327
327
 
328
328
  <h5>Sound</h5>
329
- ${this.toggleLine('sound', 'Sound', 'Play remote audio. Applies on the next connection.')}
330
- ${this.toggleLine('microphone', 'Microphone', `Share your microphone when a remote app requests it. Applies on the next connection; turning it off stops sharing immediately. ${this.info('A red indicator remains visible while sharing, including from background desktops. Its menu can stop sharing with an individual desktop. That desktop stays muted through reconnects until re-enabled or Tabby closes.')}`)}` + `
329
+ ${this.toggleLine('sound', 'Sound', 'IronRDP only. Play remote audio. Applies on the next connection.')}
330
+ ${this.toggleLine('microphone', 'Microphone', `IronRDP only. Share your microphone when a remote app requests it. Applies on the next connection; turning it off stops sharing immediately. ${this.info('A red indicator remains visible while sharing, including from background desktops. Its menu can stop sharing with an individual desktop. That desktop stays muted through reconnects until re-enabled or Tabby closes.')}`)}` + `
331
331
 
332
332
  <h5>Clipboard</h5>
333
333
  <div class="form-line">
@@ -343,7 +343,7 @@ let RemoteDesktopSettingsComponent = class RemoteDesktopSettingsComponent {
343
343
  </div>` + `
344
344
 
345
345
  <h5>Shared folders</h5>
346
- <div class="trd-lead">Available as remote drives (<code>\\\\tsclient</code> on Windows). Applies on the next connection.
346
+ <div class="trd-lead">IronRDP only. Available as remote drives (<code>\\\\tsclient</code> on Windows). Applies on the next connection.
347
347
  ${this.info('Shared with every remote desktop. Use read-only to prevent remote changes. Supported by Windows and xrdp with FUSE; unavailable on GNOME Remote Desktop.')}</div>
348
348
  <div class="trd-list" data-list="folders"></div>
349
349
  <div class="trd-add"><button class="btn btn-secondary btn-sm" data-action="folder">Share a folder…</button></div>
@@ -448,7 +448,7 @@ let RemoteDesktopSettingsComponent = class RemoteDesktopSettingsComponent {
448
448
  <tr><td>${k('⌃⌘')} + key</td><td>The Windows key with it: ${k('⌃⌘R')} for Win+R, ${k('⌃⌘E')} for Explorer.</td></tr>` : ''}
449
449
  <tr><td>Right-click › <b>Send keys</b></td><td>Ctrl+Alt+Del, Win+L, Task Manager and others this computer keeps for itself.</td></tr>
450
450
  <tr><td>Drop files on the desktop</td><td>Then paste them in Files or Explorer. Files copied there offer <b>Save to Downloads</b>.</td></tr>
451
- <tr><td>Right-click › <b>View only</b></td><td>Watch without touching: no keys or clicks go to the desktop.</td></tr>
451
+ <tr><td>Right-click › <b>View only</b></td><td>Watch without touching: no keys or clicks go to the desktop, and no clipboard either way.</td></tr>
452
452
  <tr><td>Right-click › <b>Save a screenshot</b></td><td>The full-resolution screen, to Downloads and the clipboard.</td></tr>
453
453
  </tbody></table>
454
454
  </section>` + `
package/dist/ui.js CHANGED
@@ -191,13 +191,13 @@ function desktopActions(desktop, keyboard, pane) {
191
191
  },
192
192
  {
193
193
  type: 'checkbox',
194
- label: 'View only (no keyboard or mouse input)',
194
+ label: 'View only (no keyboard, mouse or clipboard)',
195
195
  checked: viewOnly,
196
196
  click: () => desktop.setViewOnly(pane, !viewOnly),
197
197
  },
198
198
  // With the setting on, every desktop gets the microphone when it asks for it; this one can be left out,
199
199
  // reconnects included, and taken back in (see RemoteDesktopService.stopMicrophone).
200
- ...desktop.settings().microphone ? [{
200
+ ...desktop.settings().microphone && desktop.canUseMicrophone(pane) ? [{
201
201
  type: 'checkbox',
202
202
  label: 'Send the microphone (when this desktop asks for it)',
203
203
  checked: !microphoneStopped,
package/dist/zgfx.js CHANGED
@@ -13,8 +13,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.ZgfxDecompressor = exports.ZgfxError = exports.HISTORY_SIZE = void 0;
14
14
  /** Sliding window size (MS-RDPEGFX 3.1.9.1.1). */
15
15
  exports.HISTORY_SIZE = 2_500_000;
16
- /** The most one segment decompresses to (a resource limit, as IronRDP's). */
17
- const MAX_DECOMPRESSED_PER_SEGMENT = 64 * 1024 * 1024;
16
+ /** MS-RDPEGFX 3.1.9.1.2 limits each segment to 65,535 uncompressed bytes. */
17
+ const MAX_DECOMPRESSED_PER_SEGMENT = 65535;
18
+ /** Diagnostic output only; reject before allocating a large declared message. */
19
+ const MAX_DECOMPRESSED_MESSAGE = 64 * 1024 * 1024;
18
20
  const SEGMENTED_SINGLE = 0xe0;
19
21
  const SEGMENTED_MULTIPART = 0xe1;
20
22
  const COMPRESSION_TYPE_RDP8 = 0x04;
@@ -151,6 +153,9 @@ class ZgfxDecompressor {
151
153
  const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
152
154
  const count = view.getUint16(1, true);
153
155
  const uncompressedSize = view.getUint32(3, true);
156
+ if (uncompressedSize > MAX_DECOMPRESSED_MESSAGE) {
157
+ throw new ZgfxError('message decompresses beyond the limit');
158
+ }
154
159
  let offset = 7;
155
160
  let total = 0;
156
161
  for (let i = 0; i < count; i++) {
@@ -165,6 +170,9 @@ class ZgfxDecompressor {
165
170
  const part = this.segment(input.subarray(offset, offset + size));
166
171
  offset += size;
167
172
  total += part.length;
173
+ if (total > uncompressedSize) {
174
+ throw new ZgfxError('multipart output exceeds its declared size');
175
+ }
168
176
  out.push(part);
169
177
  }
170
178
  if (total !== uncompressedSize) {
@@ -190,6 +198,9 @@ class ZgfxDecompressor {
190
198
  return new Uint8Array(0);
191
199
  }
192
200
  if (!(header & PACKET_COMPRESSED)) {
201
+ if (data.length > MAX_DECOMPRESSED_PER_SEGMENT) {
202
+ throw new ZgfxError('segment decompresses beyond the limit');
203
+ }
193
204
  this.write(data);
194
205
  return data;
195
206
  }
@@ -204,7 +215,13 @@ class ZgfxDecompressor {
204
215
  throw new ZgfxError('invalid trailing bit count');
205
216
  }
206
217
  const bits = new BitReader(encoded, bitCount);
207
- const out = [];
218
+ const out = new Uint8Array(MAX_DECOMPRESSED_PER_SEGMENT);
219
+ let produced = 0;
220
+ const reserve = (length) => {
221
+ if (produced + length > out.length) {
222
+ throw new ZgfxError('segment decompresses beyond the limit');
223
+ }
224
+ };
208
225
  while (bits.remaining > 0) {
209
226
  let token;
210
227
  for (let len = 1; len <= MAX_PREFIX; len++) {
@@ -227,12 +244,14 @@ class ZgfxDecompressor {
227
244
  }
228
245
  if (token.kind === 'null') {
229
246
  const value = bits.bits(8);
247
+ reserve(1);
230
248
  this.writeByte(value);
231
- out.push(value);
249
+ out[produced++] = value;
232
250
  }
233
251
  else if (token.kind === 'literal') {
252
+ reserve(1);
234
253
  this.writeByte(token.value);
235
- out.push(token.value);
254
+ out[produced++] = token.value;
236
255
  }
237
256
  else {
238
257
  const distance = token.value + bits.bits(token.bits);
@@ -241,10 +260,10 @@ class ZgfxDecompressor {
241
260
  const length = bits.bits(15);
242
261
  bits.alignToByte();
243
262
  const raw = bits.bytes(length);
263
+ reserve(length);
244
264
  this.write(raw);
245
- for (const b of raw) {
246
- out.push(b);
247
- }
265
+ out.set(raw, produced);
266
+ produced += length;
248
267
  }
249
268
  else {
250
269
  if (distance > exports.HISTORY_SIZE) {
@@ -263,17 +282,13 @@ class ZgfxDecompressor {
263
282
  }
264
283
  length = (1 << valueBits) + bits.bits(valueBits);
265
284
  }
266
- if (out.length + length > MAX_DECOMPRESSED_PER_SEGMENT) {
267
- throw new ZgfxError('segment decompresses beyond the limit');
268
- }
269
- this.copyMatch(distance, length, out);
285
+ reserve(length);
286
+ this.copyMatch(distance, length, out, produced);
287
+ produced += length;
270
288
  }
271
289
  }
272
- if (out.length > MAX_DECOMPRESSED_PER_SEGMENT) {
273
- throw new ZgfxError('segment decompresses beyond the limit');
274
- }
275
290
  }
276
- return Uint8Array.from(out);
291
+ return out.slice(0, produced);
277
292
  }
278
293
  writeByte(value) {
279
294
  this.history[this.at] = value;
@@ -288,7 +303,7 @@ class ZgfxDecompressor {
288
303
  }
289
304
  }
290
305
  /** Copies `length` bytes from `distance` back in the history (overlapping as a match may), to the output and history. */
291
- copyMatch(distance, length, out) {
306
+ copyMatch(distance, length, out, offset) {
292
307
  if (distance > this.filled) {
293
308
  throw new ZgfxError(`match distance ${distance} beyond what the history holds (${this.filled})`);
294
309
  }
@@ -297,7 +312,7 @@ class ZgfxDecompressor {
297
312
  const b = this.history[from];
298
313
  from = (from + 1) % exports.HISTORY_SIZE;
299
314
  this.writeByte(b);
300
- out.push(b);
315
+ out[offset + i] = b;
301
316
  }
302
317
  }
303
318
  }