@tbsoft-gmbh/signature-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2540 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __commonJS = (cb, mod) => function __require() {
7
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
8
+ };
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+
23
+ // node_modules/node-gyp-build/node-gyp-build.js
24
+ var require_node_gyp_build = __commonJS({
25
+ "node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
26
+ "use strict";
27
+ var fs = require("fs");
28
+ var path = require("path");
29
+ var os = require("os");
30
+ var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
31
+ var vars = process.config && process.config.variables || {};
32
+ var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
33
+ var abi = process.versions.modules;
34
+ var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
35
+ var arch = process.env.npm_config_arch || os.arch();
36
+ var platform = process.env.npm_config_platform || os.platform();
37
+ var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
38
+ var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
39
+ var uv = (process.versions.uv || "").split(".")[0];
40
+ module2.exports = load;
41
+ function load(dir) {
42
+ return runtimeRequire(load.resolve(dir));
43
+ }
44
+ load.resolve = load.path = function(dir) {
45
+ dir = path.resolve(dir || ".");
46
+ try {
47
+ var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
48
+ if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
49
+ } catch (err) {
50
+ }
51
+ if (!prebuildsOnly) {
52
+ var release = getFirst(path.join(dir, "build/Release"), matchBuild);
53
+ if (release) return release;
54
+ var debug = getFirst(path.join(dir, "build/Debug"), matchBuild);
55
+ if (debug) return debug;
56
+ }
57
+ var prebuild = resolve(dir);
58
+ if (prebuild) return prebuild;
59
+ var nearby = resolve(path.dirname(process.execPath));
60
+ if (nearby) return nearby;
61
+ var target = [
62
+ "platform=" + platform,
63
+ "arch=" + arch,
64
+ "runtime=" + runtime,
65
+ "abi=" + abi,
66
+ "uv=" + uv,
67
+ armv ? "armv=" + armv : "",
68
+ "libc=" + libc,
69
+ "node=" + process.versions.node,
70
+ process.versions.electron ? "electron=" + process.versions.electron : "",
71
+ typeof __webpack_require__ === "function" ? "webpack=true" : ""
72
+ // eslint-disable-line
73
+ ].filter(Boolean).join(" ");
74
+ throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
75
+ function resolve(dir2) {
76
+ var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple);
77
+ var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
78
+ if (!tuple) return;
79
+ var prebuilds = path.join(dir2, "prebuilds", tuple.name);
80
+ var parsed = readdirSync(prebuilds).map(parseTags);
81
+ var candidates = parsed.filter(matchTags(runtime, abi));
82
+ var winner = candidates.sort(compareTags(runtime))[0];
83
+ if (winner) return path.join(prebuilds, winner.file);
84
+ }
85
+ };
86
+ function readdirSync(dir) {
87
+ try {
88
+ return fs.readdirSync(dir);
89
+ } catch (err) {
90
+ return [];
91
+ }
92
+ }
93
+ function getFirst(dir, filter) {
94
+ var files = readdirSync(dir).filter(filter);
95
+ return files[0] && path.join(dir, files[0]);
96
+ }
97
+ function matchBuild(name) {
98
+ return /\.node$/.test(name);
99
+ }
100
+ function parseTuple(name) {
101
+ var arr = name.split("-");
102
+ if (arr.length !== 2) return;
103
+ var platform2 = arr[0];
104
+ var architectures = arr[1].split("+");
105
+ if (!platform2) return;
106
+ if (!architectures.length) return;
107
+ if (!architectures.every(Boolean)) return;
108
+ return { name, platform: platform2, architectures };
109
+ }
110
+ function matchTuple(platform2, arch2) {
111
+ return function(tuple) {
112
+ if (tuple == null) return false;
113
+ if (tuple.platform !== platform2) return false;
114
+ return tuple.architectures.includes(arch2);
115
+ };
116
+ }
117
+ function compareTuples(a, b) {
118
+ return a.architectures.length - b.architectures.length;
119
+ }
120
+ function parseTags(file) {
121
+ var arr = file.split(".");
122
+ var extension = arr.pop();
123
+ var tags = { file, specificity: 0 };
124
+ if (extension !== "node") return;
125
+ for (var i = 0; i < arr.length; i++) {
126
+ var tag = arr[i];
127
+ if (tag === "node" || tag === "electron" || tag === "node-webkit") {
128
+ tags.runtime = tag;
129
+ } else if (tag === "napi") {
130
+ tags.napi = true;
131
+ } else if (tag.slice(0, 3) === "abi") {
132
+ tags.abi = tag.slice(3);
133
+ } else if (tag.slice(0, 2) === "uv") {
134
+ tags.uv = tag.slice(2);
135
+ } else if (tag.slice(0, 4) === "armv") {
136
+ tags.armv = tag.slice(4);
137
+ } else if (tag === "glibc" || tag === "musl") {
138
+ tags.libc = tag;
139
+ } else {
140
+ continue;
141
+ }
142
+ tags.specificity++;
143
+ }
144
+ return tags;
145
+ }
146
+ function matchTags(runtime2, abi2) {
147
+ return function(tags) {
148
+ if (tags == null) return false;
149
+ if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
150
+ if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
151
+ if (tags.uv && tags.uv !== uv) return false;
152
+ if (tags.armv && tags.armv !== armv) return false;
153
+ if (tags.libc && tags.libc !== libc) return false;
154
+ return true;
155
+ };
156
+ }
157
+ function runtimeAgnostic(tags) {
158
+ return tags.runtime === "node" && tags.napi;
159
+ }
160
+ function compareTags(runtime2) {
161
+ return function(a, b) {
162
+ if (a.runtime !== b.runtime) {
163
+ return a.runtime === runtime2 ? -1 : 1;
164
+ } else if (a.abi !== b.abi) {
165
+ return a.abi ? -1 : 1;
166
+ } else if (a.specificity !== b.specificity) {
167
+ return a.specificity > b.specificity ? -1 : 1;
168
+ } else {
169
+ return 0;
170
+ }
171
+ };
172
+ }
173
+ function isNwjs() {
174
+ return !!(process.versions && process.versions.nw);
175
+ }
176
+ function isElectron() {
177
+ if (process.versions && process.versions.electron) return true;
178
+ if (process.env.ELECTRON_RUN_AS_NODE) return true;
179
+ return typeof window !== "undefined" && window.process && window.process.type === "renderer";
180
+ }
181
+ function isAlpine(platform2) {
182
+ return platform2 === "linux" && fs.existsSync("/etc/alpine-release");
183
+ }
184
+ load.parseTags = parseTags;
185
+ load.matchTags = matchTags;
186
+ load.compareTags = compareTags;
187
+ load.parseTuple = parseTuple;
188
+ load.matchTuple = matchTuple;
189
+ load.compareTuples = compareTuples;
190
+ }
191
+ });
192
+
193
+ // node_modules/node-gyp-build/index.js
194
+ var require_node_gyp_build2 = __commonJS({
195
+ "node_modules/node-gyp-build/index.js"(exports2, module2) {
196
+ "use strict";
197
+ var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
198
+ if (typeof runtimeRequire.addon === "function") {
199
+ module2.exports = runtimeRequire.addon.bind(runtimeRequire);
200
+ } else {
201
+ module2.exports = require_node_gyp_build();
202
+ }
203
+ }
204
+ });
205
+
206
+ // node_modules/usb/dist/usb/bindings.js
207
+ var require_bindings = __commonJS({
208
+ "node_modules/usb/dist/usb/bindings.js"(exports2, module2) {
209
+ "use strict";
210
+ Object.defineProperty(exports2, "__esModule", { value: true });
211
+ var path_1 = require("path");
212
+ var usb = require_node_gyp_build2()(process.env.NODE_USB_PATH || (0, path_1.join)(__dirname, "..", ".."));
213
+ module2.exports = usb;
214
+ }
215
+ });
216
+
217
+ // node_modules/usb/dist/usb/endpoint.js
218
+ var require_endpoint = __commonJS({
219
+ "node_modules/usb/dist/usb/endpoint.js"(exports2) {
220
+ "use strict";
221
+ Object.defineProperty(exports2, "__esModule", { value: true });
222
+ exports2.OutEndpoint = exports2.InEndpoint = exports2.Endpoint = void 0;
223
+ var events_1 = require("events");
224
+ var bindings_1 = require_bindings();
225
+ var util_1 = require("util");
226
+ var isBuffer = (obj) => obj && obj instanceof Buffer;
227
+ var Endpoint = class extends events_1.EventEmitter {
228
+ constructor(device, descriptor) {
229
+ super();
230
+ this.device = device;
231
+ this.timeout = 0;
232
+ this.descriptor = descriptor;
233
+ this.address = descriptor.bEndpointAddress;
234
+ this.transferType = descriptor.bmAttributes & 3;
235
+ }
236
+ /** Clear the halt/stall condition for this endpoint. */
237
+ clearHalt(callback) {
238
+ return this.device.__clearHalt(this.address, callback);
239
+ }
240
+ /**
241
+ * Create a new `Transfer` object for this endpoint.
242
+ *
243
+ * The passed callback will be called when the transfer is submitted and finishes. Its arguments are the error (if any), the submitted buffer, and the amount of data actually written (for
244
+ * OUT transfers) or read (for IN transfers).
245
+ *
246
+ * @param timeout Timeout for the transfer (0 means unlimited).
247
+ * @param callback Transfer completion callback.
248
+ */
249
+ makeTransfer(timeout, callback) {
250
+ return new bindings_1.Transfer(this.device, this.address, this.transferType, timeout, callback);
251
+ }
252
+ };
253
+ exports2.Endpoint = Endpoint;
254
+ var InEndpoint = class extends Endpoint {
255
+ constructor(device, descriptor) {
256
+ super(device, descriptor);
257
+ this.direction = "in";
258
+ this.pollTransfers = [];
259
+ this.pollTransferSize = 0;
260
+ this.pollPending = 0;
261
+ this.pollActive = false;
262
+ this.transferAsync = (0, util_1.promisify)(this.transfer).bind(this);
263
+ }
264
+ /**
265
+ * Perform a transfer to read data from the endpoint.
266
+ *
267
+ * If length is greater than maxPacketSize, libusb will automatically split the transfer in multiple packets, and you will receive one callback with all data once all packets are complete.
268
+ *
269
+ * `this` in the callback is the InEndpoint object.
270
+ *
271
+ * The device must be open to use this method.
272
+ * @param length
273
+ * @param callback
274
+ */
275
+ transfer(length, callback) {
276
+ const buffer = Buffer.alloc(length);
277
+ const cb = (error, _buffer, actualLength) => {
278
+ callback.call(this, error, buffer.slice(0, actualLength));
279
+ };
280
+ try {
281
+ this.makeTransfer(this.timeout, cb).submit(buffer);
282
+ } catch (e) {
283
+ process.nextTick(() => callback.call(this, e));
284
+ }
285
+ return this;
286
+ }
287
+ /**
288
+ * Start polling the endpoint.
289
+ *
290
+ * The library will keep `nTransfers` transfers of size `transferSize` pending in the kernel at all times to ensure continuous data flow.
291
+ * This is handled by the libusb event thread, so it continues even if the Node v8 thread is busy. The `data` and `error` events are emitted as transfers complete.
292
+ *
293
+ * The device must be open to use this method.
294
+ * @param nTransfers
295
+ * @param transferSize
296
+ * @param callback
297
+ */
298
+ startPoll(nTransfers, transferSize, callback) {
299
+ const transferDone = (error, transfer, buffer, actualLength) => {
300
+ if (!error) {
301
+ this.emit("data", buffer.slice(0, actualLength));
302
+ } else if (error.errno !== bindings_1.LIBUSB_TRANSFER_CANCELLED) {
303
+ if (this.pollActive) {
304
+ this.emit("error", error);
305
+ this.stopPoll();
306
+ }
307
+ }
308
+ if (this.pollActive) {
309
+ startTransfer(transfer);
310
+ } else {
311
+ this.pollPending--;
312
+ if (this.pollPending === 0) {
313
+ this.pollTransfers = [];
314
+ this.pollActive = false;
315
+ this.emit("end");
316
+ if (callback) {
317
+ const cancelled = (error === null || error === void 0 ? void 0 : error.errno) === bindings_1.LIBUSB_TRANSFER_CANCELLED;
318
+ callback(cancelled ? void 0 : error, buffer, actualLength, cancelled);
319
+ }
320
+ }
321
+ }
322
+ };
323
+ const startTransfer = (transfer) => {
324
+ try {
325
+ transfer.submit(Buffer.alloc(this.pollTransferSize), (error, buffer, actualLength) => {
326
+ transferDone(error, transfer, buffer, actualLength);
327
+ });
328
+ } catch (e) {
329
+ this.emit("error", e);
330
+ this.stopPoll();
331
+ }
332
+ };
333
+ this.pollTransfers = this.startPollTransfers(nTransfers, transferSize, function(error, buffer, actualLength) {
334
+ transferDone(error, this, buffer, actualLength);
335
+ });
336
+ this.pollTransfers.forEach(startTransfer);
337
+ this.pollPending = this.pollTransfers.length;
338
+ return this.pollTransfers;
339
+ }
340
+ startPollTransfers(nTransfers = 3, transferSize = this.descriptor.wMaxPacketSize, callback) {
341
+ if (this.pollActive) {
342
+ throw new Error("Polling already active");
343
+ }
344
+ this.pollTransferSize = transferSize;
345
+ this.pollActive = true;
346
+ this.pollPending = 0;
347
+ const transfers = [];
348
+ for (let i = 0; i < nTransfers; i++) {
349
+ const transfer = this.makeTransfer(0, callback);
350
+ transfers[i] = transfer;
351
+ }
352
+ return transfers;
353
+ }
354
+ /**
355
+ * Stop polling.
356
+ *
357
+ * Further data may still be received. The `end` event is emitted and the callback is called once all transfers have completed or canceled.
358
+ *
359
+ * The device must be open to use this method.
360
+ * @param callback
361
+ */
362
+ stopPoll(callback) {
363
+ if (!this.pollActive) {
364
+ throw new Error("Polling is not active.");
365
+ }
366
+ for (let i = 0; i < this.pollTransfers.length; i++) {
367
+ try {
368
+ this.pollTransfers[i].cancel();
369
+ } catch (error) {
370
+ this.emit("error", error);
371
+ }
372
+ }
373
+ this.pollActive = false;
374
+ if (callback)
375
+ this.once("end", callback);
376
+ }
377
+ };
378
+ exports2.InEndpoint = InEndpoint;
379
+ var OutEndpoint = class extends Endpoint {
380
+ constructor(device, descriptor) {
381
+ super(device, descriptor);
382
+ this.direction = "out";
383
+ this.transferAsync = (0, util_1.promisify)(this.transfer).bind(this);
384
+ }
385
+ /**
386
+ * Perform a transfer to write `data` to the endpoint.
387
+ *
388
+ * If length is greater than maxPacketSize, libusb will automatically split the transfer in multiple packets, and you will receive one callback once all packets are complete.
389
+ *
390
+ * `this` in the callback is the OutEndpoint object.
391
+ *
392
+ * The device must be open to use this method.
393
+ * @param buffer
394
+ * @param callback
395
+ */
396
+ transfer(buffer, callback) {
397
+ if (!buffer) {
398
+ buffer = Buffer.alloc(0);
399
+ } else if (!isBuffer(buffer)) {
400
+ buffer = Buffer.from(buffer);
401
+ }
402
+ const cb = (error, _buffer, actual) => {
403
+ if (callback) {
404
+ callback.call(this, error, actual || 0);
405
+ }
406
+ };
407
+ try {
408
+ this.makeTransfer(this.timeout, cb).submit(buffer);
409
+ } catch (e) {
410
+ process.nextTick(() => cb(e));
411
+ }
412
+ return this;
413
+ }
414
+ transferWithZLP(buffer, callback) {
415
+ if (buffer.length % this.descriptor.wMaxPacketSize === 0) {
416
+ this.transfer(buffer);
417
+ this.transfer(Buffer.alloc(0), callback);
418
+ } else {
419
+ this.transfer(buffer, callback);
420
+ }
421
+ }
422
+ };
423
+ exports2.OutEndpoint = OutEndpoint;
424
+ }
425
+ });
426
+
427
+ // node_modules/usb/dist/usb/interface.js
428
+ var require_interface = __commonJS({
429
+ "node_modules/usb/dist/usb/interface.js"(exports2) {
430
+ "use strict";
431
+ Object.defineProperty(exports2, "__esModule", { value: true });
432
+ exports2.Interface = void 0;
433
+ var bindings_1 = require_bindings();
434
+ var endpoint_1 = require_endpoint();
435
+ var util_1 = require("util");
436
+ var Interface = class {
437
+ constructor(device, id) {
438
+ this.device = device;
439
+ this.id = id;
440
+ this.altSetting = 0;
441
+ this.refresh();
442
+ this.releaseAsync = (0, util_1.promisify)(this.release).bind(this);
443
+ this.setAltSettingAsync = (0, util_1.promisify)(this.setAltSetting).bind(this);
444
+ }
445
+ refresh() {
446
+ if (!this.device.configDescriptor) {
447
+ return;
448
+ }
449
+ this.descriptor = this.device.configDescriptor.interfaces[this.id][this.altSetting];
450
+ this.interfaceNumber = this.descriptor.bInterfaceNumber;
451
+ this.endpoints = [];
452
+ const len = this.descriptor.endpoints.length;
453
+ for (let i = 0; i < len; i++) {
454
+ const desc = this.descriptor.endpoints[i];
455
+ const c = desc.bEndpointAddress & bindings_1.LIBUSB_ENDPOINT_IN ? endpoint_1.InEndpoint : endpoint_1.OutEndpoint;
456
+ this.endpoints[i] = new c(this.device, desc);
457
+ }
458
+ }
459
+ /**
460
+ * Claims the interface. This method must be called before using any endpoints of this interface.
461
+ *
462
+ * The device must be open to use this method.
463
+ */
464
+ claim() {
465
+ this.device.__claimInterface(this.id);
466
+ }
467
+ release(closeEndpointsOrCallback, callback) {
468
+ let closeEndpoints = false;
469
+ if (typeof closeEndpointsOrCallback === "boolean") {
470
+ closeEndpoints = closeEndpointsOrCallback;
471
+ } else {
472
+ callback = closeEndpointsOrCallback;
473
+ }
474
+ const next = () => {
475
+ this.device.__releaseInterface(this.id, (error) => {
476
+ if (!error) {
477
+ this.altSetting = 0;
478
+ this.refresh();
479
+ }
480
+ if (callback) {
481
+ callback.call(this, error);
482
+ }
483
+ });
484
+ };
485
+ if (!closeEndpoints || this.endpoints.length === 0) {
486
+ next();
487
+ } else {
488
+ let n = this.endpoints.length;
489
+ this.endpoints.forEach((ep) => {
490
+ if (ep.direction === "in" && ep.pollActive) {
491
+ ep.once("end", () => {
492
+ if (--n === 0) {
493
+ next();
494
+ }
495
+ });
496
+ ep.stopPoll();
497
+ } else {
498
+ if (--n === 0) {
499
+ next();
500
+ }
501
+ }
502
+ });
503
+ }
504
+ }
505
+ /**
506
+ * Returns `false` if a kernel driver is not active; `true` if active.
507
+ *
508
+ * The device must be open to use this method.
509
+ */
510
+ isKernelDriverActive() {
511
+ return this.device.__isKernelDriverActive(this.id);
512
+ }
513
+ /**
514
+ * Detaches the kernel driver from the interface.
515
+ *
516
+ * The device must be open to use this method.
517
+ */
518
+ detachKernelDriver() {
519
+ return this.device.__detachKernelDriver(this.id);
520
+ }
521
+ /**
522
+ * Re-attaches the kernel driver for the interface.
523
+ *
524
+ * The device must be open to use this method.
525
+ */
526
+ attachKernelDriver() {
527
+ return this.device.__attachKernelDriver(this.id);
528
+ }
529
+ /**
530
+ * Sets the alternate setting. It updates the `interface.endpoints` array to reflect the endpoints found in the alternate setting.
531
+ *
532
+ * The device must be open to use this method.
533
+ * @param altSetting
534
+ * @param callback
535
+ */
536
+ setAltSetting(altSetting, callback) {
537
+ this.device.__setInterface(this.id, altSetting, (error) => {
538
+ if (!error) {
539
+ this.altSetting = altSetting;
540
+ this.refresh();
541
+ }
542
+ if (callback) {
543
+ callback.call(this, error);
544
+ }
545
+ });
546
+ }
547
+ /**
548
+ * Return the InEndpoint or OutEndpoint with the specified address.
549
+ *
550
+ * The device must be open to use this method.
551
+ * @param addr
552
+ */
553
+ endpoint(addr) {
554
+ return this.endpoints.find((item) => item.address === addr);
555
+ }
556
+ };
557
+ exports2.Interface = Interface;
558
+ }
559
+ });
560
+
561
+ // node_modules/usb/dist/usb/capability.js
562
+ var require_capability = __commonJS({
563
+ "node_modules/usb/dist/usb/capability.js"(exports2) {
564
+ "use strict";
565
+ Object.defineProperty(exports2, "__esModule", { value: true });
566
+ exports2.Capability = void 0;
567
+ var Capability = class {
568
+ constructor(device, id) {
569
+ this.device = device;
570
+ this.id = id;
571
+ if (!device._bosDescriptor) {
572
+ throw new Error("bosDescriptor not found");
573
+ }
574
+ this.descriptor = device._bosDescriptor.capabilities[this.id];
575
+ this.type = this.descriptor.bDevCapabilityType;
576
+ this.data = this.descriptor.dev_capability_data;
577
+ }
578
+ };
579
+ exports2.Capability = Capability;
580
+ }
581
+ });
582
+
583
+ // node_modules/usb/dist/usb/device.js
584
+ var require_device = __commonJS({
585
+ "node_modules/usb/dist/usb/device.js"(exports2) {
586
+ "use strict";
587
+ Object.defineProperty(exports2, "__esModule", { value: true });
588
+ exports2.ExtendedDevice = void 0;
589
+ var usb = require_bindings();
590
+ var interface_1 = require_interface();
591
+ var capability_1 = require_capability();
592
+ var isBuffer = (obj) => !!obj && obj instanceof Uint8Array;
593
+ var DEFAULT_TIMEOUT = 1e3;
594
+ var ExtendedDevice = class {
595
+ constructor() {
596
+ this._timeout = DEFAULT_TIMEOUT;
597
+ }
598
+ /**
599
+ * Timeout in milliseconds to use for control transfers.
600
+ */
601
+ get timeout() {
602
+ return this._timeout || DEFAULT_TIMEOUT;
603
+ }
604
+ set timeout(value) {
605
+ this._timeout = value;
606
+ }
607
+ /**
608
+ * Object with properties for the fields of the active configuration descriptor.
609
+ */
610
+ get configDescriptor() {
611
+ try {
612
+ return this.__getConfigDescriptor();
613
+ } catch (e) {
614
+ const errno = e.errno;
615
+ if (errno === usb.LIBUSB_ERROR_NOT_FOUND || errno === usb.LIBUSB_ERROR_NO_DEVICE) {
616
+ return void 0;
617
+ }
618
+ throw e;
619
+ }
620
+ }
621
+ /**
622
+ * Contains all config descriptors of the device (same structure as .configDescriptor above)
623
+ */
624
+ get allConfigDescriptors() {
625
+ try {
626
+ return this.__getAllConfigDescriptors();
627
+ } catch (e) {
628
+ const errno = e.errno;
629
+ if (errno === usb.LIBUSB_ERROR_NOT_FOUND || errno === usb.LIBUSB_ERROR_NO_DEVICE) {
630
+ return [];
631
+ }
632
+ throw e;
633
+ }
634
+ }
635
+ /**
636
+ * Contains the parent of the device, such as a hub. If there is no parent this property is set to `null`.
637
+ */
638
+ get parent() {
639
+ return this.__getParent();
640
+ }
641
+ /**
642
+ * Open the device.
643
+ * @param defaultConfig
644
+ */
645
+ open(defaultConfig = true) {
646
+ this.__open();
647
+ this.interfaces = [];
648
+ if (defaultConfig === false) {
649
+ return;
650
+ }
651
+ const len = this.configDescriptor ? this.configDescriptor.interfaces.length : 0;
652
+ for (let i = 0; i < len; i++) {
653
+ this.interfaces[i] = new interface_1.Interface(this, i);
654
+ }
655
+ }
656
+ /**
657
+ * Close the device.
658
+ *
659
+ * The device must be open to use this method.
660
+ */
661
+ close() {
662
+ this.__close();
663
+ this.interfaces = void 0;
664
+ }
665
+ /**
666
+ * Set the device configuration to something other than the default (0). To use this, first call `.open(false)` (which tells it not to auto configure),
667
+ * then before claiming an interface, call this method.
668
+ *
669
+ * The device must be open to use this method.
670
+ * @param desired
671
+ * @param callback
672
+ */
673
+ setConfiguration(desired, callback) {
674
+ this.__setConfiguration(desired, (error) => {
675
+ if (!error) {
676
+ this.interfaces = [];
677
+ const len = this.configDescriptor ? this.configDescriptor.interfaces.length : 0;
678
+ for (let i = 0; i < len; i++) {
679
+ this.interfaces[i] = new interface_1.Interface(this, i);
680
+ }
681
+ }
682
+ if (callback) {
683
+ callback.call(this, error);
684
+ }
685
+ });
686
+ }
687
+ /**
688
+ * Enable/disable libusb's automatic kernel driver detachment
689
+ * When this is enabled libusb will automatically detach the kernel driver on an interface when claiming the interface, and attach it when releasing the interface
690
+ *
691
+ * The device must be open to use this method.
692
+ */
693
+ setAutoDetachKernelDriver(enable) {
694
+ return this.__setAutoDetachKernelDriver(enable ? 1 : 0);
695
+ }
696
+ /**
697
+ * Perform a control transfer with `libusb_control_transfer`.
698
+ *
699
+ * Parameter `data_or_length` can be an integer length for an IN transfer, or a `Buffer` for an OUT transfer. The type must match the direction specified in the MSB of bmRequestType.
700
+ *
701
+ * The `data` parameter of the callback is actual transferred for OUT transfers, or will be passed a Buffer for IN transfers.
702
+ *
703
+ * The device must be open to use this method.
704
+ * @param bmRequestType
705
+ * @param bRequest
706
+ * @param wValue
707
+ * @param wIndex
708
+ * @param data_or_length
709
+ * @param callback
710
+ */
711
+ controlTransfer(bmRequestType, bRequest, wValue, wIndex, data_or_length, callback) {
712
+ const isIn = !!(bmRequestType & usb.LIBUSB_ENDPOINT_IN);
713
+ const wLength = isIn ? data_or_length : data_or_length.length;
714
+ if (isIn) {
715
+ if (wLength < 0) {
716
+ throw new TypeError("Expected size number for IN transfer (based on bmRequestType)");
717
+ }
718
+ } else {
719
+ if (!isBuffer(data_or_length)) {
720
+ throw new TypeError("Expected buffer for OUT transfer (based on bmRequestType)");
721
+ }
722
+ }
723
+ const buf = Buffer.alloc(wLength + usb.LIBUSB_CONTROL_SETUP_SIZE);
724
+ buf.writeUInt8(bmRequestType, 0);
725
+ buf.writeUInt8(bRequest, 1);
726
+ buf.writeUInt16LE(wValue, 2);
727
+ buf.writeUInt16LE(wIndex, 4);
728
+ buf.writeUInt16LE(wLength, 6);
729
+ if (!isIn) {
730
+ buf.set(data_or_length, usb.LIBUSB_CONTROL_SETUP_SIZE);
731
+ }
732
+ const transfer = new usb.Transfer(this, 0, usb.LIBUSB_TRANSFER_TYPE_CONTROL, this.timeout, (error, buf2, actual) => {
733
+ if (callback) {
734
+ if (isIn) {
735
+ callback.call(this, error, buf2.slice(usb.LIBUSB_CONTROL_SETUP_SIZE, usb.LIBUSB_CONTROL_SETUP_SIZE + actual));
736
+ } else {
737
+ callback.call(this, error, actual);
738
+ }
739
+ }
740
+ });
741
+ try {
742
+ transfer.submit(buf);
743
+ } catch (e) {
744
+ if (callback) {
745
+ process.nextTick(() => callback.call(this, e, void 0));
746
+ }
747
+ }
748
+ return this;
749
+ }
750
+ /**
751
+ * Return the interface with the specified interface number.
752
+ *
753
+ * The device must be open to use this method.
754
+ * @param addr
755
+ */
756
+ interface(addr) {
757
+ if (!this.interfaces) {
758
+ throw new Error("Device must be open before searching for interfaces");
759
+ }
760
+ addr = addr || 0;
761
+ for (let i = 0; i < this.interfaces.length; i++) {
762
+ if (this.interfaces[i].interfaceNumber === addr) {
763
+ return this.interfaces[i];
764
+ }
765
+ }
766
+ throw new Error(`Interface not found for address: ${addr}`);
767
+ }
768
+ /**
769
+ * Perform a control transfer to retrieve a string descriptor
770
+ *
771
+ * The device must be open to use this method.
772
+ * @param desc_index
773
+ * @param callback
774
+ */
775
+ getStringDescriptor(desc_index, callback) {
776
+ if (desc_index === 0) {
777
+ callback();
778
+ return;
779
+ }
780
+ const langid = 1033;
781
+ const length = 255;
782
+ this.controlTransfer(usb.LIBUSB_ENDPOINT_IN, usb.LIBUSB_REQUEST_GET_DESCRIPTOR, usb.LIBUSB_DT_STRING << 8 | desc_index, langid, length, (error, buffer) => {
783
+ if (error) {
784
+ return callback(error);
785
+ }
786
+ callback(void 0, isBuffer(buffer) ? buffer.toString("utf16le", 2) : void 0);
787
+ });
788
+ }
789
+ /**
790
+ * Perform a control transfer to retrieve an object with properties for the fields of the Binary Object Store descriptor.
791
+ *
792
+ * The device must be open to use this method.
793
+ * @param callback
794
+ */
795
+ getBosDescriptor(callback) {
796
+ if (this._bosDescriptor) {
797
+ return callback(void 0, this._bosDescriptor);
798
+ }
799
+ if (this.deviceDescriptor.bcdUSB < 513) {
800
+ return callback(void 0, void 0);
801
+ }
802
+ this.controlTransfer(usb.LIBUSB_ENDPOINT_IN, usb.LIBUSB_REQUEST_GET_DESCRIPTOR, usb.LIBUSB_DT_BOS << 8, 0, usb.LIBUSB_DT_BOS_SIZE, (error, buffer) => {
803
+ if (error) {
804
+ if (error.errno === usb.LIBUSB_TRANSFER_STALL)
805
+ return callback(void 0, void 0);
806
+ return callback(error, void 0);
807
+ }
808
+ if (!isBuffer(buffer)) {
809
+ return callback(void 0, void 0);
810
+ }
811
+ const totalLength = buffer.readUInt16LE(2);
812
+ this.controlTransfer(usb.LIBUSB_ENDPOINT_IN, usb.LIBUSB_REQUEST_GET_DESCRIPTOR, usb.LIBUSB_DT_BOS << 8, 0, totalLength, (error2, buffer2) => {
813
+ if (error2) {
814
+ if (error2.errno === usb.LIBUSB_TRANSFER_STALL)
815
+ return callback(void 0, void 0);
816
+ return callback(error2, void 0);
817
+ }
818
+ if (!isBuffer(buffer2)) {
819
+ return callback(void 0, void 0);
820
+ }
821
+ const descriptor = {
822
+ bLength: buffer2.readUInt8(0),
823
+ bDescriptorType: buffer2.readUInt8(1),
824
+ wTotalLength: buffer2.readUInt16LE(2),
825
+ bNumDeviceCaps: buffer2.readUInt8(4),
826
+ capabilities: []
827
+ };
828
+ let i = usb.LIBUSB_DT_BOS_SIZE;
829
+ while (i < descriptor.wTotalLength) {
830
+ const capability = {
831
+ bLength: buffer2.readUInt8(i + 0),
832
+ bDescriptorType: buffer2.readUInt8(i + 1),
833
+ bDevCapabilityType: buffer2.readUInt8(i + 2),
834
+ dev_capability_data: buffer2.slice(i + 3, i + buffer2.readUInt8(i + 0))
835
+ };
836
+ descriptor.capabilities.push(capability);
837
+ i += capability.bLength;
838
+ }
839
+ this._bosDescriptor = descriptor;
840
+ callback(void 0, this._bosDescriptor);
841
+ });
842
+ });
843
+ }
844
+ /**
845
+ * Retrieve a list of Capability objects for the Binary Object Store capabilities of the device.
846
+ *
847
+ * The device must be open to use this method.
848
+ * @param callback
849
+ */
850
+ getCapabilities(callback) {
851
+ const capabilities = [];
852
+ this.getBosDescriptor((error, descriptor) => {
853
+ if (error)
854
+ return callback(error, void 0);
855
+ const len = descriptor ? descriptor.capabilities.length : 0;
856
+ for (let i = 0; i < len; i++) {
857
+ capabilities.push(new capability_1.Capability(this, i));
858
+ }
859
+ callback(void 0, capabilities);
860
+ });
861
+ }
862
+ };
863
+ exports2.ExtendedDevice = ExtendedDevice;
864
+ }
865
+ });
866
+
867
+ // node_modules/usb/dist/usb/index.js
868
+ var require_usb = __commonJS({
869
+ "node_modules/usb/dist/usb/index.js"(exports2, module2) {
870
+ "use strict";
871
+ var events_1 = require("events");
872
+ var device_1 = require_device();
873
+ var usb = require_bindings();
874
+ if (usb.INIT_ERROR) {
875
+ console.warn("Failed to initialize libusb.");
876
+ }
877
+ Object.setPrototypeOf(usb, events_1.EventEmitter.prototype);
878
+ Object.defineProperty(usb, "pollHotplug", {
879
+ value: false,
880
+ writable: true
881
+ });
882
+ Object.defineProperty(usb, "pollHotplugDelay", {
883
+ value: 500,
884
+ writable: true
885
+ });
886
+ if (usb.Device) {
887
+ Object.getOwnPropertyNames(device_1.ExtendedDevice.prototype).forEach((name) => {
888
+ Object.defineProperty(usb.Device.prototype, name, Object.getOwnPropertyDescriptor(device_1.ExtendedDevice.prototype, name) || /* @__PURE__ */ Object.create(null));
889
+ });
890
+ }
891
+ var hotPlugDevices = /* @__PURE__ */ new Set();
892
+ var emitHotplugEvents = () => {
893
+ const devices = new Set(usb.getDeviceList());
894
+ for (const device of devices) {
895
+ if (!hotPlugDevices.has(device)) {
896
+ usb.emit("attach", device);
897
+ }
898
+ }
899
+ for (const device of hotPlugDevices) {
900
+ if (!devices.has(device)) {
901
+ usb.emit("detach", device);
902
+ }
903
+ }
904
+ hotPlugDevices = devices;
905
+ };
906
+ var pollingHotplug = false;
907
+ var pollHotplug = (start = false) => {
908
+ if (start) {
909
+ pollingHotplug = true;
910
+ } else if (!pollingHotplug) {
911
+ return;
912
+ } else {
913
+ emitHotplugEvents();
914
+ }
915
+ setTimeout(() => pollHotplug(), usb.pollHotplugDelay);
916
+ };
917
+ var devicesChanged = () => setTimeout(() => emitHotplugEvents(), usb.pollHotplugDelay);
918
+ var hotplugSupported = 0;
919
+ var startHotplug = () => {
920
+ hotplugSupported = usb.pollHotplug ? 0 : usb._supportedHotplugEvents();
921
+ if (hotplugSupported !== 1) {
922
+ hotPlugDevices = new Set(usb.getDeviceList());
923
+ }
924
+ if (hotplugSupported) {
925
+ usb._enableHotplugEvents();
926
+ if (hotplugSupported === 2) {
927
+ usb.on("attachIds", devicesChanged);
928
+ usb.on("detachIds", devicesChanged);
929
+ }
930
+ } else {
931
+ pollHotplug(true);
932
+ }
933
+ };
934
+ var stopHotplug = () => {
935
+ if (hotplugSupported) {
936
+ usb._disableHotplugEvents();
937
+ if (hotplugSupported === 2) {
938
+ usb.off("attachIds", devicesChanged);
939
+ usb.off("detachIds", devicesChanged);
940
+ }
941
+ } else {
942
+ pollingHotplug = false;
943
+ }
944
+ };
945
+ usb.on("newListener", (event) => {
946
+ if (event !== "attach" && event !== "detach") {
947
+ return;
948
+ }
949
+ const listenerCount = usb.listenerCount("attach") + usb.listenerCount("detach");
950
+ if (listenerCount === 0) {
951
+ startHotplug();
952
+ }
953
+ });
954
+ usb.on("removeListener", (event) => {
955
+ if (event !== "attach" && event !== "detach") {
956
+ return;
957
+ }
958
+ const listenerCount = usb.listenerCount("attach") + usb.listenerCount("detach");
959
+ if (listenerCount === 0) {
960
+ stopHotplug();
961
+ }
962
+ });
963
+ module2.exports = usb;
964
+ }
965
+ });
966
+
967
+ // node_modules/usb/dist/webusb/webusb-device.js
968
+ var require_webusb_device = __commonJS({
969
+ "node_modules/usb/dist/webusb/webusb-device.js"(exports2) {
970
+ "use strict";
971
+ Object.defineProperty(exports2, "__esModule", { value: true });
972
+ exports2.WebUSBDevice = void 0;
973
+ var usb = require_usb();
974
+ var util_1 = require("util");
975
+ var os_1 = require("os");
976
+ var LIBUSB_TRANSFER_TYPE_MASK = 3;
977
+ var ENDPOINT_NUMBER_MASK = 127;
978
+ var CLEAR_FEATURE = 1;
979
+ var ENDPOINT_HALT = 0;
980
+ var WebUSBDevice = class _WebUSBDevice {
981
+ static async createInstance(device, autoDetachKernelDriver = true) {
982
+ const instance = new _WebUSBDevice(device, autoDetachKernelDriver);
983
+ await instance.initialize();
984
+ return instance;
985
+ }
986
+ constructor(device, autoDetachKernelDriver) {
987
+ this.device = device;
988
+ this.autoDetachKernelDriver = autoDetachKernelDriver;
989
+ this.manufacturerName = null;
990
+ this.productName = null;
991
+ this.serialNumber = null;
992
+ this.configurations = [];
993
+ const usbVersion = this.decodeVersion(device.deviceDescriptor.bcdUSB);
994
+ this.usbVersionMajor = usbVersion.major;
995
+ this.usbVersionMinor = usbVersion.minor;
996
+ this.usbVersionSubminor = usbVersion.sub;
997
+ this.deviceClass = device.deviceDescriptor.bDeviceClass;
998
+ this.deviceSubclass = device.deviceDescriptor.bDeviceSubClass;
999
+ this.deviceProtocol = device.deviceDescriptor.bDeviceProtocol;
1000
+ this.vendorId = device.deviceDescriptor.idVendor;
1001
+ this.productId = device.deviceDescriptor.idProduct;
1002
+ const deviceVersion = this.decodeVersion(device.deviceDescriptor.bcdDevice);
1003
+ this.deviceVersionMajor = deviceVersion.major;
1004
+ this.deviceVersionMinor = deviceVersion.minor;
1005
+ this.deviceVersionSubminor = deviceVersion.sub;
1006
+ this.controlTransferAsync = (0, util_1.promisify)(this.device.controlTransfer).bind(this.device);
1007
+ this.setConfigurationAsync = (0, util_1.promisify)(this.device.setConfiguration).bind(this.device);
1008
+ this.resetAsync = (0, util_1.promisify)(this.device.reset).bind(this.device);
1009
+ this.getStringDescriptorAsync = (0, util_1.promisify)(this.device.getStringDescriptor).bind(this.device);
1010
+ }
1011
+ get configuration() {
1012
+ if (!this.device.configDescriptor) {
1013
+ return null;
1014
+ }
1015
+ const currentConfiguration = this.device.configDescriptor.bConfigurationValue;
1016
+ return this.configurations.find((configuration) => configuration.configurationValue === currentConfiguration) || null;
1017
+ }
1018
+ get opened() {
1019
+ return !!this.device.interfaces;
1020
+ }
1021
+ async open() {
1022
+ try {
1023
+ if (this.opened) {
1024
+ return;
1025
+ }
1026
+ this.device.open();
1027
+ if ((0, os_1.platform)() !== "win32") {
1028
+ this.device.setAutoDetachKernelDriver(this.autoDetachKernelDriver);
1029
+ }
1030
+ } catch (error) {
1031
+ throw new Error(`open error: ${error}`);
1032
+ }
1033
+ }
1034
+ async close() {
1035
+ try {
1036
+ if (!this.opened) {
1037
+ return;
1038
+ }
1039
+ try {
1040
+ if (this.configuration) {
1041
+ for (const iface of this.configuration.interfaces) {
1042
+ await this._releaseInterface(iface.interfaceNumber);
1043
+ this.configuration.interfaces[this.configuration.interfaces.indexOf(iface)] = {
1044
+ interfaceNumber: iface.interfaceNumber,
1045
+ alternate: iface.alternate,
1046
+ alternates: iface.alternates,
1047
+ claimed: false
1048
+ };
1049
+ }
1050
+ }
1051
+ } catch (_error) {
1052
+ }
1053
+ this.device.close();
1054
+ } catch (error) {
1055
+ throw new Error(`close error: ${error}`);
1056
+ }
1057
+ }
1058
+ async selectConfiguration(configurationValue) {
1059
+ if (!this.opened || !this.device.configDescriptor) {
1060
+ throw new Error("selectConfiguration error: invalid state");
1061
+ }
1062
+ if (this.device.configDescriptor.bConfigurationValue === configurationValue) {
1063
+ return;
1064
+ }
1065
+ const config = this.configurations.find((configuration) => configuration.configurationValue === configurationValue);
1066
+ if (!config) {
1067
+ throw new Error("selectConfiguration error: configuration not found");
1068
+ }
1069
+ try {
1070
+ await this.setConfigurationAsync(configurationValue);
1071
+ } catch (error) {
1072
+ throw new Error(`selectConfiguration error: ${error}`);
1073
+ }
1074
+ }
1075
+ async claimInterface(interfaceNumber) {
1076
+ if (!this.opened) {
1077
+ throw new Error("claimInterface error: invalid state");
1078
+ }
1079
+ if (!this.configuration) {
1080
+ throw new Error("claimInterface error: interface not found");
1081
+ }
1082
+ const iface = this.configuration.interfaces.find((usbInterface) => usbInterface.interfaceNumber === interfaceNumber);
1083
+ if (!iface) {
1084
+ throw new Error("claimInterface error: interface not found");
1085
+ }
1086
+ if (iface.claimed) {
1087
+ return;
1088
+ }
1089
+ try {
1090
+ this.device.interface(interfaceNumber).claim();
1091
+ this.configuration.interfaces[this.configuration.interfaces.indexOf(iface)] = {
1092
+ interfaceNumber,
1093
+ alternate: iface.alternate,
1094
+ alternates: iface.alternates,
1095
+ claimed: true
1096
+ };
1097
+ } catch (error) {
1098
+ throw new Error(`claimInterface error: ${error}`);
1099
+ }
1100
+ }
1101
+ async releaseInterface(interfaceNumber) {
1102
+ await this._releaseInterface(interfaceNumber);
1103
+ if (this.configuration) {
1104
+ const iface = this.configuration.interfaces.find((usbInterface) => usbInterface.interfaceNumber === interfaceNumber);
1105
+ if (iface) {
1106
+ this.configuration.interfaces[this.configuration.interfaces.indexOf(iface)] = {
1107
+ interfaceNumber,
1108
+ alternate: iface.alternate,
1109
+ alternates: iface.alternates,
1110
+ claimed: false
1111
+ };
1112
+ }
1113
+ }
1114
+ }
1115
+ async selectAlternateInterface(interfaceNumber, alternateSetting) {
1116
+ if (!this.opened) {
1117
+ throw new Error("selectAlternateInterface error: invalid state");
1118
+ }
1119
+ if (!this.configuration) {
1120
+ throw new Error("selectAlternateInterface error: interface not found");
1121
+ }
1122
+ const iface = this.configuration.interfaces.find((usbInterface) => usbInterface.interfaceNumber === interfaceNumber);
1123
+ if (!iface) {
1124
+ throw new Error("selectAlternateInterface error: interface not found");
1125
+ }
1126
+ if (!iface.claimed) {
1127
+ throw new Error("selectAlternateInterface error: invalid state");
1128
+ }
1129
+ try {
1130
+ const iface2 = this.device.interface(interfaceNumber);
1131
+ await iface2.setAltSettingAsync(alternateSetting);
1132
+ } catch (error) {
1133
+ throw new Error(`selectAlternateInterface error: ${error}`);
1134
+ }
1135
+ }
1136
+ async controlTransferIn(setup, length) {
1137
+ try {
1138
+ this.checkDeviceOpen();
1139
+ const type = this.controlTransferParamsToType(setup, usb.LIBUSB_ENDPOINT_IN);
1140
+ const result = await this.controlTransferAsync(type, setup.request, setup.value, setup.index, length);
1141
+ return {
1142
+ data: result ? new DataView(new Uint8Array(result).buffer) : void 0,
1143
+ status: "ok"
1144
+ };
1145
+ } catch (error) {
1146
+ if (error.errno === usb.LIBUSB_TRANSFER_STALL) {
1147
+ return {
1148
+ status: "stall"
1149
+ };
1150
+ }
1151
+ if (error.errno === usb.LIBUSB_TRANSFER_OVERFLOW) {
1152
+ return {
1153
+ status: "babble"
1154
+ };
1155
+ }
1156
+ throw new Error(`controlTransferIn error: ${error}`);
1157
+ }
1158
+ }
1159
+ async controlTransferOut(setup, data) {
1160
+ try {
1161
+ this.checkDeviceOpen();
1162
+ const type = this.controlTransferParamsToType(setup, usb.LIBUSB_ENDPOINT_OUT);
1163
+ const buffer = data ? Buffer.from(data) : Buffer.alloc(0);
1164
+ const bytesWritten = await this.controlTransferAsync(type, setup.request, setup.value, setup.index, buffer);
1165
+ return {
1166
+ bytesWritten,
1167
+ status: "ok"
1168
+ };
1169
+ } catch (error) {
1170
+ if (error.errno === usb.LIBUSB_TRANSFER_STALL) {
1171
+ return {
1172
+ bytesWritten: 0,
1173
+ status: "stall"
1174
+ };
1175
+ }
1176
+ throw new Error(`controlTransferOut error: ${error}`);
1177
+ }
1178
+ }
1179
+ async clearHalt(direction, endpointNumber) {
1180
+ try {
1181
+ const wIndex = endpointNumber | (direction === "in" ? usb.LIBUSB_ENDPOINT_IN : usb.LIBUSB_ENDPOINT_OUT);
1182
+ await this.controlTransferAsync(usb.LIBUSB_RECIPIENT_ENDPOINT, CLEAR_FEATURE, ENDPOINT_HALT, wIndex, Buffer.from(new Uint8Array()));
1183
+ } catch (error) {
1184
+ throw new Error(`clearHalt error: ${error}`);
1185
+ }
1186
+ }
1187
+ async transferIn(endpointNumber, length) {
1188
+ try {
1189
+ this.checkDeviceOpen();
1190
+ const endpoint = this.getEndpoint(endpointNumber | usb.LIBUSB_ENDPOINT_IN);
1191
+ const result = await endpoint.transferAsync(length);
1192
+ return {
1193
+ data: result ? new DataView(new Uint8Array(result).buffer) : void 0,
1194
+ status: "ok"
1195
+ };
1196
+ } catch (error) {
1197
+ if (error.errno === usb.LIBUSB_TRANSFER_STALL) {
1198
+ return {
1199
+ status: "stall"
1200
+ };
1201
+ }
1202
+ if (error.errno === usb.LIBUSB_TRANSFER_OVERFLOW) {
1203
+ return {
1204
+ status: "babble"
1205
+ };
1206
+ }
1207
+ throw new Error(`transferIn error: ${error}`);
1208
+ }
1209
+ }
1210
+ async transferOut(endpointNumber, data) {
1211
+ try {
1212
+ this.checkDeviceOpen();
1213
+ const endpoint = this.getEndpoint(endpointNumber | usb.LIBUSB_ENDPOINT_OUT);
1214
+ const buffer = Buffer.from(data);
1215
+ const bytesWritten = await endpoint.transferAsync(buffer);
1216
+ return {
1217
+ bytesWritten,
1218
+ status: "ok"
1219
+ };
1220
+ } catch (error) {
1221
+ if (error.errno === usb.LIBUSB_TRANSFER_STALL) {
1222
+ return {
1223
+ bytesWritten: 0,
1224
+ status: "stall"
1225
+ };
1226
+ }
1227
+ throw new Error(`transferOut error: ${error}`);
1228
+ }
1229
+ }
1230
+ async reset() {
1231
+ try {
1232
+ await this.resetAsync();
1233
+ } catch (error) {
1234
+ throw new Error(`reset error: ${error}`);
1235
+ }
1236
+ }
1237
+ async isochronousTransferIn(_endpointNumber, _packetLengths) {
1238
+ throw new Error("isochronousTransferIn error: method not implemented");
1239
+ }
1240
+ async isochronousTransferOut(_endpointNumber, _data, _packetLengths) {
1241
+ throw new Error("isochronousTransferOut error: method not implemented");
1242
+ }
1243
+ async forget() {
1244
+ throw new Error("forget error: method not implemented");
1245
+ }
1246
+ async initialize() {
1247
+ try {
1248
+ if (!this.opened) {
1249
+ this.device.open();
1250
+ if (this.deviceClass === 255 && (0, os_1.platform)() === "darwin") {
1251
+ await this.setConfigurationAsync(1);
1252
+ }
1253
+ }
1254
+ this.manufacturerName = await this.getStringDescriptor(this.device.deviceDescriptor.iManufacturer);
1255
+ this.productName = await this.getStringDescriptor(this.device.deviceDescriptor.iProduct);
1256
+ this.serialNumber = await this.getStringDescriptor(this.device.deviceDescriptor.iSerialNumber);
1257
+ this.configurations = await this.getConfigurations();
1258
+ } catch (error) {
1259
+ throw new Error(`initialize error: ${error}`);
1260
+ } finally {
1261
+ if (this.opened) {
1262
+ this.device.close();
1263
+ }
1264
+ }
1265
+ }
1266
+ decodeVersion(version) {
1267
+ const hex = `0000${version.toString(16)}`.slice(-4);
1268
+ return {
1269
+ major: parseInt(hex.substr(0, 2), void 0),
1270
+ minor: parseInt(hex.substr(2, 1), void 0),
1271
+ sub: parseInt(hex.substr(3, 1), void 0)
1272
+ };
1273
+ }
1274
+ async getStringDescriptor(index) {
1275
+ try {
1276
+ const buffer = await this.getStringDescriptorAsync(index);
1277
+ return buffer ? buffer.toString() : "";
1278
+ } catch (error) {
1279
+ return "";
1280
+ }
1281
+ }
1282
+ async getConfigurations() {
1283
+ const configs = [];
1284
+ for (const config of this.device.allConfigDescriptors) {
1285
+ const interfaces = [];
1286
+ for (const iface of config.interfaces) {
1287
+ const alternates = [];
1288
+ for (const alternate2 of iface) {
1289
+ const endpoints = [];
1290
+ for (const endpoint of alternate2.endpoints) {
1291
+ endpoints.push({
1292
+ endpointNumber: endpoint.bEndpointAddress & ENDPOINT_NUMBER_MASK,
1293
+ direction: endpoint.bEndpointAddress & usb.LIBUSB_ENDPOINT_IN ? "in" : "out",
1294
+ type: (endpoint.bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) === usb.LIBUSB_TRANSFER_TYPE_BULK ? "bulk" : (endpoint.bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) === usb.LIBUSB_TRANSFER_TYPE_INTERRUPT ? "interrupt" : "isochronous",
1295
+ packetSize: endpoint.wMaxPacketSize
1296
+ });
1297
+ }
1298
+ alternates.push({
1299
+ alternateSetting: alternate2.bAlternateSetting,
1300
+ interfaceClass: alternate2.bInterfaceClass,
1301
+ interfaceSubclass: alternate2.bInterfaceSubClass,
1302
+ interfaceProtocol: alternate2.bInterfaceProtocol,
1303
+ interfaceName: await this.getStringDescriptor(alternate2.iInterface),
1304
+ endpoints
1305
+ });
1306
+ }
1307
+ const interfaceNumber = iface[0].bInterfaceNumber;
1308
+ const alternate = alternates.find((alt) => alt.alternateSetting === this.device.interface(interfaceNumber).altSetting);
1309
+ if (alternate) {
1310
+ interfaces.push({
1311
+ interfaceNumber,
1312
+ alternate,
1313
+ alternates,
1314
+ claimed: false
1315
+ });
1316
+ }
1317
+ }
1318
+ configs.push({
1319
+ configurationValue: config.bConfigurationValue,
1320
+ configurationName: await this.getStringDescriptor(config.iConfiguration),
1321
+ interfaces
1322
+ });
1323
+ }
1324
+ return configs;
1325
+ }
1326
+ getEndpoint(address) {
1327
+ if (!this.device.interfaces) {
1328
+ return void 0;
1329
+ }
1330
+ for (const iface of this.device.interfaces) {
1331
+ const endpoint = iface.endpoint(address);
1332
+ if (endpoint) {
1333
+ return endpoint;
1334
+ }
1335
+ }
1336
+ return void 0;
1337
+ }
1338
+ controlTransferParamsToType(setup, direction) {
1339
+ const recipient = setup.recipient === "device" ? usb.LIBUSB_RECIPIENT_DEVICE : setup.recipient === "interface" ? usb.LIBUSB_RECIPIENT_INTERFACE : setup.recipient === "endpoint" ? usb.LIBUSB_RECIPIENT_ENDPOINT : usb.LIBUSB_RECIPIENT_OTHER;
1340
+ const requestType = setup.requestType === "standard" ? usb.LIBUSB_REQUEST_TYPE_STANDARD : setup.requestType === "class" ? usb.LIBUSB_REQUEST_TYPE_CLASS : usb.LIBUSB_REQUEST_TYPE_VENDOR;
1341
+ return recipient | requestType | direction;
1342
+ }
1343
+ async _releaseInterface(interfaceNumber) {
1344
+ if (!this.opened) {
1345
+ throw new Error("releaseInterface error: invalid state");
1346
+ }
1347
+ if (!this.configuration) {
1348
+ throw new Error("releaseInterface error: interface not found");
1349
+ }
1350
+ const iface = this.configuration.interfaces.find((usbInterface) => usbInterface.interfaceNumber === interfaceNumber);
1351
+ if (!iface) {
1352
+ throw new Error("releaseInterface error: interface not found");
1353
+ }
1354
+ if (!iface.claimed) {
1355
+ return;
1356
+ }
1357
+ try {
1358
+ const iface2 = this.device.interface(interfaceNumber);
1359
+ await iface2.releaseAsync();
1360
+ } catch (error) {
1361
+ throw new Error(`releaseInterface error: ${error}`);
1362
+ }
1363
+ }
1364
+ checkDeviceOpen() {
1365
+ if (!this.opened) {
1366
+ throw new Error("The device must be opened first");
1367
+ }
1368
+ }
1369
+ };
1370
+ exports2.WebUSBDevice = WebUSBDevice;
1371
+ }
1372
+ });
1373
+
1374
+ // node_modules/usb/dist/webusb/index.js
1375
+ var require_webusb = __commonJS({
1376
+ "node_modules/usb/dist/webusb/index.js"(exports2) {
1377
+ "use strict";
1378
+ Object.defineProperty(exports2, "__esModule", { value: true });
1379
+ exports2.WebUSB = exports2.getWebUsb = void 0;
1380
+ var usb = require_usb();
1381
+ var events_1 = require("events");
1382
+ var webusb_device_1 = require_webusb_device();
1383
+ var getWebUsb = () => {
1384
+ if (navigator && navigator.usb) {
1385
+ return navigator.usb;
1386
+ }
1387
+ return new WebUSB();
1388
+ };
1389
+ exports2.getWebUsb = getWebUsb;
1390
+ var NamedError = class extends Error {
1391
+ constructor(message, name) {
1392
+ super(message);
1393
+ this.name = name;
1394
+ }
1395
+ };
1396
+ var WebUSB = class {
1397
+ constructor(options = {}) {
1398
+ this.options = options;
1399
+ this.emitter = new events_1.EventEmitter();
1400
+ this.knownDevices = /* @__PURE__ */ new Map();
1401
+ this.authorisedDevices = /* @__PURE__ */ new Set();
1402
+ const deviceConnectCallback = async (device) => {
1403
+ const webDevice = await this.getWebDevice(device);
1404
+ if (webDevice && this.isAuthorisedDevice(webDevice)) {
1405
+ const event = {
1406
+ type: "connect",
1407
+ device: webDevice
1408
+ };
1409
+ this.emitter.emit("connect", event);
1410
+ }
1411
+ };
1412
+ const deviceDisconnectCallback = async (device) => {
1413
+ if (this.knownDevices.has(device)) {
1414
+ const webDevice = this.knownDevices.get(device);
1415
+ if (webDevice && this.isAuthorisedDevice(webDevice)) {
1416
+ const event = {
1417
+ type: "disconnect",
1418
+ device: webDevice
1419
+ };
1420
+ this.emitter.emit("disconnect", event);
1421
+ }
1422
+ }
1423
+ };
1424
+ this.emitter.on("newListener", (event) => {
1425
+ const listenerCount = this.emitter.listenerCount(event);
1426
+ if (listenerCount !== 0) {
1427
+ return;
1428
+ }
1429
+ if (event === "connect") {
1430
+ usb.addListener("attach", deviceConnectCallback);
1431
+ } else if (event === "disconnect") {
1432
+ usb.addListener("detach", deviceDisconnectCallback);
1433
+ }
1434
+ });
1435
+ this.emitter.on("removeListener", (event) => {
1436
+ const listenerCount = this.emitter.listenerCount(event);
1437
+ if (listenerCount !== 0) {
1438
+ return;
1439
+ }
1440
+ if (event === "connect") {
1441
+ usb.removeListener("attach", deviceConnectCallback);
1442
+ } else if (event === "disconnect") {
1443
+ usb.removeListener("detach", deviceDisconnectCallback);
1444
+ }
1445
+ });
1446
+ }
1447
+ set onconnect(fn) {
1448
+ if (this._onconnect) {
1449
+ this.removeEventListener("connect", this._onconnect);
1450
+ this._onconnect = void 0;
1451
+ }
1452
+ if (fn) {
1453
+ this._onconnect = fn;
1454
+ this.addEventListener("connect", this._onconnect);
1455
+ }
1456
+ }
1457
+ set ondisconnect(fn) {
1458
+ if (this._ondisconnect) {
1459
+ this.removeEventListener("disconnect", this._ondisconnect);
1460
+ this._ondisconnect = void 0;
1461
+ }
1462
+ if (fn) {
1463
+ this._ondisconnect = fn;
1464
+ this.addEventListener("disconnect", this._ondisconnect);
1465
+ }
1466
+ }
1467
+ addEventListener(type, listener) {
1468
+ this.emitter.addListener(type, listener);
1469
+ }
1470
+ removeEventListener(type, callback) {
1471
+ this.emitter.removeListener(type, callback);
1472
+ }
1473
+ dispatchEvent(_event) {
1474
+ return false;
1475
+ }
1476
+ /**
1477
+ * Requests a single Web USB device
1478
+ * @param options The options to use when scanning
1479
+ * @returns Promise containing the selected device
1480
+ */
1481
+ async requestDevice(options) {
1482
+ if (!options) {
1483
+ throw new TypeError("requestDevice error: 1 argument required, but only 0 present");
1484
+ }
1485
+ if (options.constructor !== {}.constructor) {
1486
+ throw new TypeError("requestDevice error: parameter 1 (options) is not an object");
1487
+ }
1488
+ if (!options.filters) {
1489
+ throw new TypeError("requestDevice error: required member filters is undefined");
1490
+ }
1491
+ if (options.filters.constructor !== [].constructor) {
1492
+ throw new TypeError("requestDevice error: the provided value cannot be converted to a sequence");
1493
+ }
1494
+ options.filters.forEach((filter) => {
1495
+ if (filter.protocolCode && !filter.subclassCode) {
1496
+ throw new TypeError("requestDevice error: subclass code is required");
1497
+ }
1498
+ if (filter.subclassCode && !filter.classCode) {
1499
+ throw new TypeError("requestDevice error: class code is required");
1500
+ }
1501
+ });
1502
+ let devices = await this.loadDevices(options.filters);
1503
+ devices = devices.filter((device) => this.filterDevice(device, options.filters));
1504
+ if (devices.length === 0) {
1505
+ throw new NamedError("Failed to execute 'requestDevice' on 'USB': No device selected.", "NotFoundError");
1506
+ }
1507
+ try {
1508
+ const device = this.options.devicesFound ? await this.options.devicesFound(devices) : devices[0];
1509
+ if (!device) {
1510
+ throw new NamedError("Failed to execute 'requestDevice' on 'USB': No device selected.", "NotFoundError");
1511
+ }
1512
+ this.authorisedDevices.add({
1513
+ vendorId: device.vendorId,
1514
+ productId: device.productId,
1515
+ classCode: device.deviceClass,
1516
+ subclassCode: device.deviceSubclass,
1517
+ protocolCode: device.deviceProtocol,
1518
+ serialNumber: device.serialNumber || void 0
1519
+ });
1520
+ return device;
1521
+ } catch (error) {
1522
+ throw new NamedError("Failed to execute 'requestDevice' on 'USB': No device selected.", "NotFoundError");
1523
+ }
1524
+ }
1525
+ /**
1526
+ * Gets all allowed Web USB devices which are connected
1527
+ * @returns Promise containing an array of devices
1528
+ */
1529
+ async getDevices() {
1530
+ const preFilters = this.options.allowAllDevices ? void 0 : this.options.allowedDevices;
1531
+ const devices = await this.loadDevices(preFilters);
1532
+ return devices.filter((device) => this.isAuthorisedDevice(device));
1533
+ }
1534
+ async loadDevices(preFilters) {
1535
+ let devices = usb.getDeviceList();
1536
+ devices = this.quickFilter(devices, preFilters);
1537
+ const refreshedKnownDevices = /* @__PURE__ */ new Map();
1538
+ for (const device of devices) {
1539
+ const webDevice = await this.getWebDevice(device);
1540
+ if (webDevice) {
1541
+ refreshedKnownDevices.set(device, webDevice);
1542
+ }
1543
+ }
1544
+ this.knownDevices = refreshedKnownDevices;
1545
+ return [...this.knownDevices.values()];
1546
+ }
1547
+ // Get a WebUSBDevice corresponding to underlying device.
1548
+ // Returns undefined the device was not found and could not be created.
1549
+ async getWebDevice(device) {
1550
+ if (!this.knownDevices.has(device)) {
1551
+ if (this.options.deviceTimeout) {
1552
+ device.timeout = this.options.deviceTimeout;
1553
+ }
1554
+ try {
1555
+ const webDevice = await webusb_device_1.WebUSBDevice.createInstance(device, this.options.autoDetachKernelDriver);
1556
+ this.knownDevices.set(device, webDevice);
1557
+ } catch {
1558
+ }
1559
+ }
1560
+ return this.knownDevices.get(device);
1561
+ }
1562
+ // Undertake quick filter on devices before creating WebUSB devices if possible
1563
+ quickFilter(devices, preFilters) {
1564
+ if (!preFilters || !preFilters.length) {
1565
+ return devices;
1566
+ }
1567
+ return devices.filter((device) => preFilters.some((filter) => {
1568
+ if (filter.vendorId && filter.vendorId !== device.deviceDescriptor.idVendor)
1569
+ return false;
1570
+ if (filter.productId && filter.productId !== device.deviceDescriptor.idProduct)
1571
+ return false;
1572
+ return true;
1573
+ }));
1574
+ }
1575
+ // Filter WebUSB devices
1576
+ filterDevice(device, filters) {
1577
+ if (!filters || !filters.length) {
1578
+ return true;
1579
+ }
1580
+ return filters.some((filter) => {
1581
+ if (filter.vendorId && filter.vendorId !== device.vendorId)
1582
+ return false;
1583
+ if (filter.productId && filter.productId !== device.productId)
1584
+ return false;
1585
+ if (filter.classCode) {
1586
+ if (!device.configuration) {
1587
+ return false;
1588
+ }
1589
+ const match = device.configuration.interfaces.some((iface) => {
1590
+ if (filter.classCode && filter.classCode !== iface.alternate.interfaceClass)
1591
+ return false;
1592
+ if (filter.subclassCode && filter.subclassCode !== iface.alternate.interfaceSubclass)
1593
+ return false;
1594
+ if (filter.protocolCode && filter.protocolCode !== iface.alternate.interfaceProtocol)
1595
+ return false;
1596
+ return true;
1597
+ });
1598
+ if (match) {
1599
+ return true;
1600
+ }
1601
+ }
1602
+ if (filter.classCode && filter.classCode !== device.deviceClass)
1603
+ return false;
1604
+ if (filter.subclassCode && filter.subclassCode !== device.deviceSubclass)
1605
+ return false;
1606
+ if (filter.protocolCode && filter.protocolCode !== device.deviceProtocol)
1607
+ return false;
1608
+ if (filter.serialNumber && filter.serialNumber !== device.serialNumber)
1609
+ return false;
1610
+ return true;
1611
+ });
1612
+ }
1613
+ // Check whether a device is authorised
1614
+ isAuthorisedDevice(device) {
1615
+ if (this.options.allowAllDevices) {
1616
+ return true;
1617
+ }
1618
+ if (this.options.allowedDevices && this.filterDevice(device, this.options.allowedDevices)) {
1619
+ return true;
1620
+ }
1621
+ return [...this.authorisedDevices.values()].some((authorised) => authorised.vendorId === device.vendorId && authorised.productId === device.productId && authorised.classCode === device.deviceClass && authorised.subclassCode === device.deviceSubclass && authorised.protocolCode === device.deviceProtocol && authorised.serialNumber === device.serialNumber);
1622
+ }
1623
+ };
1624
+ exports2.WebUSB = WebUSB;
1625
+ }
1626
+ });
1627
+
1628
+ // node_modules/usb/dist/usb/descriptors.js
1629
+ var require_descriptors = __commonJS({
1630
+ "node_modules/usb/dist/usb/descriptors.js"(exports2) {
1631
+ "use strict";
1632
+ Object.defineProperty(exports2, "__esModule", { value: true });
1633
+ }
1634
+ });
1635
+
1636
+ // node_modules/usb/dist/index.js
1637
+ var require_dist = __commonJS({
1638
+ "node_modules/usb/dist/index.js"(exports2) {
1639
+ "use strict";
1640
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
1641
+ if (k2 === void 0) k2 = k;
1642
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1643
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1644
+ desc = { enumerable: true, get: function() {
1645
+ return m[k];
1646
+ } };
1647
+ }
1648
+ Object.defineProperty(o, k2, desc);
1649
+ } : function(o, m, k, k2) {
1650
+ if (k2 === void 0) k2 = k;
1651
+ o[k2] = m[k];
1652
+ });
1653
+ var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
1654
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
1655
+ };
1656
+ Object.defineProperty(exports2, "__esModule", { value: true });
1657
+ exports2.LibUSBException = exports2.useUsbDkBackend = exports2.getDeviceList = exports2.Transfer = exports2.Device = exports2.webusb = exports2.findBySerialNumber = exports2.findByIds = exports2.usb = void 0;
1658
+ var util_1 = require("util");
1659
+ var webusb_1 = require_webusb();
1660
+ var usb = require_usb();
1661
+ exports2.usb = usb;
1662
+ var findByIds = (vid, pid) => {
1663
+ const devices = usb.getDeviceList();
1664
+ return devices.find((item) => item.deviceDescriptor.idVendor === vid && item.deviceDescriptor.idProduct === pid);
1665
+ };
1666
+ exports2.findByIds = findByIds;
1667
+ var findBySerialNumber = async (serialNumber) => {
1668
+ const devices = usb.getDeviceList();
1669
+ const opened = (device) => !!device.interfaces;
1670
+ for (const device of devices) {
1671
+ try {
1672
+ if (!opened(device)) {
1673
+ device.open();
1674
+ }
1675
+ const getStringDescriptor = (0, util_1.promisify)(device.getStringDescriptor).bind(device);
1676
+ const buffer = await getStringDescriptor(device.deviceDescriptor.iSerialNumber);
1677
+ if (buffer && buffer.toString() === serialNumber) {
1678
+ return device;
1679
+ }
1680
+ } catch {
1681
+ } finally {
1682
+ try {
1683
+ if (opened(device)) {
1684
+ device.close();
1685
+ }
1686
+ } catch {
1687
+ }
1688
+ }
1689
+ }
1690
+ return void 0;
1691
+ };
1692
+ exports2.findBySerialNumber = findBySerialNumber;
1693
+ var webusb = new webusb_1.WebUSB();
1694
+ exports2.webusb = webusb;
1695
+ var usb_1 = require_usb();
1696
+ Object.defineProperty(exports2, "Device", { enumerable: true, get: function() {
1697
+ return usb_1.Device;
1698
+ } });
1699
+ Object.defineProperty(exports2, "Transfer", { enumerable: true, get: function() {
1700
+ return usb_1.Transfer;
1701
+ } });
1702
+ Object.defineProperty(exports2, "getDeviceList", { enumerable: true, get: function() {
1703
+ return usb_1.getDeviceList;
1704
+ } });
1705
+ Object.defineProperty(exports2, "useUsbDkBackend", { enumerable: true, get: function() {
1706
+ return usb_1.useUsbDkBackend;
1707
+ } });
1708
+ Object.defineProperty(exports2, "LibUSBException", { enumerable: true, get: function() {
1709
+ return usb_1.LibUSBException;
1710
+ } });
1711
+ __exportStar(require_capability(), exports2);
1712
+ __exportStar(require_descriptors(), exports2);
1713
+ __exportStar(require_endpoint(), exports2);
1714
+ __exportStar(require_interface(), exports2);
1715
+ __exportStar(require_webusb(), exports2);
1716
+ __exportStar(require_webusb_device(), exports2);
1717
+ }
1718
+ });
1719
+
1720
+ // src/hid-protocol.ts
1721
+ var hid_protocol_exports = {};
1722
+ __export(hid_protocol_exports, {
1723
+ CMD: () => CMD,
1724
+ HidProtocol: () => HidProtocol,
1725
+ REG: () => REG,
1726
+ RESP: () => RESP,
1727
+ SIG_EVENT: () => SIG_EVENT
1728
+ });
1729
+ module.exports = __toCommonJS(hid_protocol_exports);
1730
+
1731
+ // src/usb-transport.ts
1732
+ var import_events = require("events");
1733
+ var SIGNOTEC_VID = 8499;
1734
+ var SIGNOTEC_PID = 1;
1735
+ var REPORT_SIZE = 63;
1736
+ var UsbTransportDevice = class extends import_events.EventEmitter {
1737
+ constructor(usbDevice, log) {
1738
+ super();
1739
+ this.usbDevice = null;
1740
+ this.iface = null;
1741
+ this.inEndpoint = null;
1742
+ this.outEndpoint = null;
1743
+ this.closed = false;
1744
+ this.polling = false;
1745
+ this.transferSize = REPORT_SIZE;
1746
+ /**
1747
+ * Write queue: each entry is a callback that starts the OUT transfer and
1748
+ * calls `next()` when the transfer completes. This ensures the previous
1749
+ * USB transfer is fully on the wire before the next one starts — matching
1750
+ * node-hid's synchronous write() behavior.
1751
+ */
1752
+ this.writeQueue = [];
1753
+ this.writeBusy = false;
1754
+ /** Resolve callback for close() waiting on the write queue to drain. */
1755
+ this.drainResolve = null;
1756
+ this.usbDevice = usbDevice;
1757
+ this.log = log;
1758
+ try {
1759
+ this.usbDevice.open();
1760
+ } catch (err) {
1761
+ throw new Error(`Cannot open USB device: ${err.message}`);
1762
+ }
1763
+ const { iface, inEp, outEp } = this.findEndpoints();
1764
+ this.iface = iface;
1765
+ this.inEndpoint = inEp;
1766
+ this.outEndpoint = outEp;
1767
+ this.transferSize = this.inEndpoint.descriptor?.wMaxPacketSize || REPORT_SIZE;
1768
+ this.log.info?.(`USB endpoint max packet size: ${this.transferSize}`);
1769
+ try {
1770
+ if (this.iface.isKernelDriverActive?.()) {
1771
+ this.iface.detachKernelDriver();
1772
+ }
1773
+ } catch {
1774
+ }
1775
+ try {
1776
+ this.iface.claim();
1777
+ } catch (err) {
1778
+ this.usbDevice.close();
1779
+ throw new Error(
1780
+ `Cannot claim USB interface: ${err.message}. On Windows, you may need to install WinUSB driver using Zadig.`
1781
+ );
1782
+ }
1783
+ this.startPolling();
1784
+ }
1785
+ findEndpoints() {
1786
+ const interfaces = this.usbDevice.interfaces;
1787
+ for (const iface of interfaces) {
1788
+ let inEp = null;
1789
+ let outEp = null;
1790
+ for (const ep of iface.endpoints) {
1791
+ if (ep.transferType === 3) {
1792
+ if (ep.direction === "in") inEp = ep;
1793
+ else if (ep.direction === "out") outEp = ep;
1794
+ }
1795
+ }
1796
+ if (inEp && outEp) {
1797
+ return { iface, inEp, outEp };
1798
+ }
1799
+ }
1800
+ throw new Error(
1801
+ "No suitable USB interface found with interrupt IN+OUT endpoints. The device may require a different driver."
1802
+ );
1803
+ }
1804
+ startPolling() {
1805
+ if (this.closed || !this.inEndpoint || this.polling) return;
1806
+ this.polling = true;
1807
+ this.inEndpoint.startPoll(3, this.transferSize);
1808
+ this.inEndpoint.on("data", (data) => {
1809
+ if (this.closed) return;
1810
+ if (!data || data.length === 0) return;
1811
+ this.emit("data", Buffer.from(data));
1812
+ });
1813
+ this.inEndpoint.on("error", (err) => {
1814
+ if (this.closed) return;
1815
+ if (err.message?.includes("LIBUSB_TRANSFER_CANCELLED")) return;
1816
+ if (err.message?.includes("LIBUSB_TRANSFER_NO_DEVICE")) {
1817
+ this.emit("error", new Error("Device disconnected"));
1818
+ return;
1819
+ }
1820
+ this.log.error?.("USB IN error:", err.message);
1821
+ this.emit("error", err);
1822
+ });
1823
+ }
1824
+ /**
1825
+ * Queue an OUT transfer. Transfers are serialized: each one completes
1826
+ * before the next starts. This matches node-hid's synchronous write().
1827
+ */
1828
+ write(data) {
1829
+ if (this.closed || !this.outEndpoint) {
1830
+ throw new Error("Device not connected");
1831
+ }
1832
+ const buf = Buffer.alloc(REPORT_SIZE, 0);
1833
+ for (let i = 0; i < Math.min(data.length, REPORT_SIZE); i++) {
1834
+ buf[i] = data[i];
1835
+ }
1836
+ this.writeQueue.push(() => {
1837
+ if (this.closed || !this.outEndpoint) {
1838
+ queueMicrotask(() => this.drainNext());
1839
+ return;
1840
+ }
1841
+ this.outEndpoint.transfer(buf, (err) => {
1842
+ if (err && !this.closed) {
1843
+ this.log.error("USB write error:", err.message);
1844
+ this.emit("error", err);
1845
+ }
1846
+ this.drainNext();
1847
+ });
1848
+ });
1849
+ if (!this.writeBusy) {
1850
+ this.drainNext();
1851
+ }
1852
+ }
1853
+ drainNext() {
1854
+ const next = this.writeQueue.shift();
1855
+ if (next) {
1856
+ this.writeBusy = true;
1857
+ next();
1858
+ } else {
1859
+ this.writeBusy = false;
1860
+ this.drainResolve?.();
1861
+ this.drainResolve = null;
1862
+ }
1863
+ }
1864
+ /**
1865
+ * Close the device. Waits up to 1s for any in-flight transfer to complete
1866
+ * before releasing the USB interface.
1867
+ */
1868
+ close() {
1869
+ if (this.closed) return;
1870
+ this.closed = true;
1871
+ this.writeQueue.length = 0;
1872
+ const finish = () => {
1873
+ if (this.polling && this.inEndpoint) {
1874
+ try {
1875
+ this.inEndpoint.removeAllListeners("data");
1876
+ this.inEndpoint.removeAllListeners("error");
1877
+ this.inEndpoint.stopPoll(() => this.releaseAndClose());
1878
+ } catch {
1879
+ this.releaseAndClose();
1880
+ }
1881
+ } else {
1882
+ this.releaseAndClose();
1883
+ }
1884
+ this.polling = false;
1885
+ this.removeAllListeners();
1886
+ };
1887
+ if (this.writeBusy) {
1888
+ const timeout = setTimeout(() => {
1889
+ this.log.warn("USB close: in-flight transfer did not complete in 1s, forcing close");
1890
+ this.writeBusy = false;
1891
+ finish();
1892
+ }, 1e3);
1893
+ new Promise((resolve) => {
1894
+ this.drainResolve = resolve;
1895
+ }).then(() => {
1896
+ clearTimeout(timeout);
1897
+ finish();
1898
+ });
1899
+ } else {
1900
+ finish();
1901
+ }
1902
+ }
1903
+ releaseAndClose() {
1904
+ if (this.iface) {
1905
+ try {
1906
+ this.iface.release(true, () => {
1907
+ try {
1908
+ this.usbDevice?.close();
1909
+ } catch {
1910
+ }
1911
+ this.usbDevice = null;
1912
+ });
1913
+ } catch {
1914
+ try {
1915
+ this.usbDevice?.close();
1916
+ } catch {
1917
+ }
1918
+ this.usbDevice = null;
1919
+ }
1920
+ } else {
1921
+ try {
1922
+ this.usbDevice?.close();
1923
+ } catch {
1924
+ }
1925
+ this.usbDevice = null;
1926
+ }
1927
+ this.inEndpoint = null;
1928
+ this.outEndpoint = null;
1929
+ this.iface = null;
1930
+ }
1931
+ };
1932
+ function listUsbDevices(log) {
1933
+ let usb;
1934
+ try {
1935
+ usb = require_dist();
1936
+ } catch {
1937
+ log.debug?.("usb package not available, skipping raw USB discovery");
1938
+ return [];
1939
+ }
1940
+ try {
1941
+ const deviceList = usb.getDeviceList();
1942
+ const results = [];
1943
+ for (const device of deviceList) {
1944
+ const desc = device.deviceDescriptor;
1945
+ if (desc.idVendor === SIGNOTEC_VID && desc.idProduct === SIGNOTEC_PID) {
1946
+ results.push({
1947
+ path: `usb:${desc.idVendor}:${desc.idProduct}:${device.busNumber}:${device.deviceAddress}`,
1948
+ serialNumber: "",
1949
+ product: "Signotec Pad",
1950
+ _usbDevice: device
1951
+ });
1952
+ }
1953
+ }
1954
+ return results;
1955
+ } catch (err) {
1956
+ log.error?.("Failed to enumerate USB devices:", err.message);
1957
+ return [];
1958
+ }
1959
+ }
1960
+ function openUsbDevice(descriptor, log) {
1961
+ return new UsbTransportDevice(descriptor._usbDevice, log);
1962
+ }
1963
+
1964
+ // src/hid-protocol.ts
1965
+ var SIGNOTEC_VID2 = 8499;
1966
+ var SIGNOTEC_PID2 = 1;
1967
+ var HID_REPORT_SIZE = 63;
1968
+ var DEFAULTS = {
1969
+ commandTimeout: 3e3,
1970
+ imageTransferTimeout: 15e3,
1971
+ flashStoreTimeout: 25e3,
1972
+ chunkDelayMs: 2,
1973
+ maxRetries: 2,
1974
+ reconnectAttempts: 10,
1975
+ reconnectIntervalMs: 2e3,
1976
+ logger: console
1977
+ };
1978
+ var CMD = {
1979
+ READ_REG: 1,
1980
+ WRITE_REG: 16,
1981
+ START_SIGN: 130,
1982
+ STOP_SIGN: 131,
1983
+ DRAW_IMAGE: 132,
1984
+ IMAGE_DONE: 133,
1985
+ ERASE_DISPLAY: 134,
1986
+ STORE_IMAGE: 137,
1987
+ SHOW_STORED: 138,
1988
+ DATA_CHUNK: 96,
1989
+ STORE_CHUNK: 112,
1990
+ SLIDESHOW_CONFIG: 164,
1991
+ EXTENDED: 168,
1992
+ ADVANCED_BUTTON: 173
1993
+ };
1994
+ var BUTTON_CMD = {
1995
+ CLEAR_ALL: 1,
1996
+ SET_RECT: 4,
1997
+ ENABLE_MONITORING: 10
1998
+ };
1999
+ var RESP = {
2000
+ READ: 32,
2001
+ ACK: 144,
2002
+ START_ACK: 146,
2003
+ STOP_ACK: 147,
2004
+ IMAGE_ACK: 148,
2005
+ ERROR: 224,
2006
+ IDLE: 80
2007
+ };
2008
+ var REG = {
2009
+ DEVICE_ID: 0,
2010
+ FW_VERSION1: 1,
2011
+ FW_VERSION2: 2,
2012
+ STATE: 16,
2013
+ CAPABILITIES: 17,
2014
+ SERIAL: 20,
2015
+ DISPLAY_WIDTH: 21,
2016
+ DISPLAY_HEIGHT: 22,
2017
+ SIGN_LEFT: 50,
2018
+ SIGN_TOP: 51,
2019
+ SIGN_RIGHT: 52,
2020
+ SIGN_BOTTOM: 53
2021
+ };
2022
+ var SIG_EVENT = {
2023
+ PEN_UP: 64,
2024
+ PEN_DATA: 65,
2025
+ PEN_DATA_EXT: 66,
2026
+ HOTSPOT: 67
2027
+ };
2028
+ var HidProtocol = class {
2029
+ constructor(config) {
2030
+ this.device = null;
2031
+ this.pending = null;
2032
+ this.signatureCallback = null;
2033
+ this.disconnectCallback = null;
2034
+ this.connected = false;
2035
+ this.closing = false;
2036
+ /** Cached USB device descriptors from last listDevices() call (for USB fallback). */
2037
+ this.usbDeviceMap = /* @__PURE__ */ new Map();
2038
+ this.config = {
2039
+ commandTimeout: config?.commandTimeout ?? DEFAULTS.commandTimeout,
2040
+ imageTransferTimeout: config?.imageTransferTimeout ?? DEFAULTS.imageTransferTimeout,
2041
+ flashStoreTimeout: config?.flashStoreTimeout ?? DEFAULTS.flashStoreTimeout,
2042
+ chunkDelayMs: config?.chunkDelayMs ?? DEFAULTS.chunkDelayMs,
2043
+ maxRetries: config?.maxRetries ?? DEFAULTS.maxRetries,
2044
+ reconnectAttempts: config?.reconnectAttempts ?? DEFAULTS.reconnectAttempts,
2045
+ reconnectIntervalMs: config?.reconnectIntervalMs ?? DEFAULTS.reconnectIntervalMs
2046
+ };
2047
+ this.log = config?.logger === null ? { info() {
2048
+ }, warn() {
2049
+ }, error() {
2050
+ }, debug() {
2051
+ } } : config?.logger ?? DEFAULTS.logger;
2052
+ try {
2053
+ this.HID = require("node-hid");
2054
+ } catch {
2055
+ throw new Error(
2056
+ "node-hid is required for Signotec HID support. Install with: npm install node-hid"
2057
+ );
2058
+ }
2059
+ }
2060
+ // ─── Device Management ──────────────────────────────────────────────────────
2061
+ /**
2062
+ * Discover all connected Signotec pads.
2063
+ * Tries node-hid first; falls back to raw USB enumeration (libusb) if no
2064
+ * HID devices are found (e.g., Windows without HID class driver).
2065
+ * @returns Array of device descriptors (never throws).
2066
+ */
2067
+ listDevices() {
2068
+ this.usbDeviceMap.clear();
2069
+ try {
2070
+ const hidDevices = this.HID.devices().filter((d) => d.vendorId === SIGNOTEC_VID2 && d.productId === SIGNOTEC_PID2).map((d) => ({
2071
+ path: d.path,
2072
+ serialNumber: d.serialNumber || "",
2073
+ product: d.product || "Signotec Pad"
2074
+ }));
2075
+ if (hidDevices.length > 0) {
2076
+ this.log.info(`Found ${hidDevices.length} Signotec pad(s) via HID`);
2077
+ return hidDevices;
2078
+ }
2079
+ } catch (err) {
2080
+ this.log.warn("HID enumeration failed:", err.message);
2081
+ }
2082
+ this.log.info("No Signotec pads found via HID, trying raw USB...");
2083
+ try {
2084
+ const usbDevices = listUsbDevices(this.log);
2085
+ if (usbDevices.length > 0) {
2086
+ this.log.info(`Found ${usbDevices.length} Signotec pad(s) via raw USB`);
2087
+ for (const d of usbDevices) {
2088
+ this.usbDeviceMap.set(d.path, d);
2089
+ }
2090
+ return usbDevices.map((d) => ({
2091
+ path: d.path,
2092
+ serialNumber: d.serialNumber || "",
2093
+ product: d.product || "Signotec Pad"
2094
+ }));
2095
+ }
2096
+ } catch (err) {
2097
+ this.log.warn("USB enumeration failed:", err.message);
2098
+ }
2099
+ this.logDiscoveryDiagnostics();
2100
+ return [];
2101
+ }
2102
+ /** Log diagnostic info when no devices are found. */
2103
+ logDiscoveryDiagnostics() {
2104
+ try {
2105
+ const allHid = this.HID.devices();
2106
+ const signotecHid = allHid.filter((d) => d.vendorId === SIGNOTEC_VID2);
2107
+ this.log.warn(
2108
+ `No Signotec pads found. HID bus: ${allHid.length} devices total, ${signotecHid.length} matching VID=0x${SIGNOTEC_VID2.toString(16)}.`
2109
+ );
2110
+ if (signotecHid.length > 0) {
2111
+ this.log.warn("Signotec HID entries (wrong PID?):", JSON.stringify(
2112
+ signotecHid.map((d) => ({ pid: d.productId, usagePage: d.usagePage, product: d.product }))
2113
+ ));
2114
+ }
2115
+ } catch {
2116
+ }
2117
+ const platform = process.platform;
2118
+ if (platform === "linux") {
2119
+ this.log.warn(
2120
+ "Linux: ensure udev rules are installed. Copy 99-signotec.rules to /etc/udev/rules.d/ and run: sudo udevadm control --reload-rules && sudo udevadm trigger"
2121
+ );
2122
+ } else if (platform === "darwin") {
2123
+ this.log.warn(
2124
+ "macOS: check System Preferences > Security & Privacy > Input Monitoring permissions."
2125
+ );
2126
+ } else if (platform === "win32") {
2127
+ this.log.warn(
2128
+ "Windows: the device may need the WinUSB driver. Install it using Zadig (https://zadig.akeo.ie/) by selecting the Signotec device and choosing WinUSB."
2129
+ );
2130
+ }
2131
+ }
2132
+ /**
2133
+ * Open a device by its path (HID path or USB path).
2134
+ * USB paths start with "usb:" and use the raw USB transport fallback.
2135
+ * @throws Error if the device cannot be opened.
2136
+ */
2137
+ open(devicePath) {
2138
+ if (this.device) this.close();
2139
+ this.closing = false;
2140
+ const usbDescriptor = this.usbDeviceMap.get(devicePath);
2141
+ if (usbDescriptor) {
2142
+ this.log.info("Opening Signotec pad via raw USB transport");
2143
+ this.device = openUsbDevice(usbDescriptor, this.log);
2144
+ } else {
2145
+ this.device = new this.HID.HID(devicePath);
2146
+ }
2147
+ this.connected = true;
2148
+ this.device.on("data", (data) => this.handleData(Buffer.from(data)));
2149
+ this.device.on("error", (err) => {
2150
+ if (this.closing) return;
2151
+ this.log.error("Signotec HID error:", err.message);
2152
+ this.connected = false;
2153
+ this.disconnectCallback?.();
2154
+ });
2155
+ }
2156
+ /** Close the device connection and release resources. */
2157
+ close() {
2158
+ this.closing = true;
2159
+ this.connected = false;
2160
+ if (this.pending) {
2161
+ clearTimeout(this.pending.timer);
2162
+ this.pending.resolve(null);
2163
+ this.pending = null;
2164
+ }
2165
+ if (this.device) {
2166
+ try {
2167
+ this.device.removeAllListeners?.();
2168
+ } catch {
2169
+ }
2170
+ try {
2171
+ this.device.close();
2172
+ } catch (err) {
2173
+ this.log.warn("Error closing HID device:", err.message);
2174
+ }
2175
+ this.device = null;
2176
+ }
2177
+ this.signatureCallback = null;
2178
+ }
2179
+ /** Check if the device connection is alive. */
2180
+ isConnected() {
2181
+ return this.connected && this.device !== null && !this.closing;
2182
+ }
2183
+ /**
2184
+ * Verify the device is actually responsive (sends a register read and checks response).
2185
+ * Useful after reconnection or before starting a session.
2186
+ */
2187
+ async isResponsive() {
2188
+ if (!this.isConnected()) return false;
2189
+ const resp = await this.readRegister(REG.STATE);
2190
+ return resp !== null;
2191
+ }
2192
+ /** Register a callback for device disconnect events. */
2193
+ onDisconnect(cb) {
2194
+ this.disconnectCallback = cb;
2195
+ }
2196
+ /** Register a callback for signature/hotspot events from the device. */
2197
+ onSignatureEvent(cb) {
2198
+ this.signatureCallback = cb;
2199
+ }
2200
+ // ─── Core I/O ─────────────────────────────────────────────────────────────────
2201
+ send(bytes) {
2202
+ if (!this.device || !this.connected) throw new Error("Device not connected");
2203
+ const buf = Buffer.alloc(HID_REPORT_SIZE, 0);
2204
+ for (let i = 0; i < Math.min(bytes.length, HID_REPORT_SIZE); i++) {
2205
+ buf[i] = bytes[i];
2206
+ }
2207
+ this.device.write([...buf]);
2208
+ }
2209
+ /**
2210
+ * Send a command and wait for the response.
2211
+ * @returns Response buffer, or null on timeout/error.
2212
+ */
2213
+ sendCommand(bytes, timeout) {
2214
+ const t = timeout ?? this.config.commandTimeout;
2215
+ if (!this.device || !this.connected) return Promise.resolve(null);
2216
+ if (this.pending) {
2217
+ clearTimeout(this.pending.timer);
2218
+ this.pending.resolve(null);
2219
+ this.pending = null;
2220
+ }
2221
+ return new Promise((resolve) => {
2222
+ const timer = setTimeout(() => {
2223
+ if (this.pending?.resolve === resolve) {
2224
+ this.pending = null;
2225
+ resolve(null);
2226
+ }
2227
+ }, t);
2228
+ this.pending = { resolve, timer };
2229
+ try {
2230
+ this.send(bytes);
2231
+ } catch {
2232
+ clearTimeout(timer);
2233
+ this.pending = null;
2234
+ this.connected = false;
2235
+ resolve(null);
2236
+ }
2237
+ });
2238
+ }
2239
+ /**
2240
+ * Send a command with automatic retry on failure.
2241
+ * @param bytes Command bytes to send
2242
+ * @param validateFn Function to check if response is valid (defaults to non-null + non-error)
2243
+ * @param timeout Timeout per attempt
2244
+ * @param maxRetries Max retry count (from config if not specified)
2245
+ */
2246
+ async sendCommandWithRetry(bytes, validateFn, timeout, maxRetries) {
2247
+ const retries = maxRetries ?? this.config.maxRetries;
2248
+ const validate = validateFn ?? ((r) => r[0] !== RESP.ERROR);
2249
+ for (let attempt = 0; attempt <= retries; attempt++) {
2250
+ const resp = await this.sendCommand(bytes, timeout);
2251
+ if (resp && validate(resp)) return resp;
2252
+ if (attempt < retries) {
2253
+ this.log.warn(`HID command 0x${bytes[0]?.toString(16)} failed (attempt ${attempt + 1}/${retries + 1}), retrying...`);
2254
+ await new Promise((r) => setTimeout(r, 100 * (attempt + 1)));
2255
+ }
2256
+ }
2257
+ return null;
2258
+ }
2259
+ /** Send raw bytes without waiting for a response (fire-and-forget). */
2260
+ sendRaw(bytes) {
2261
+ try {
2262
+ this.send(bytes);
2263
+ } catch {
2264
+ this.connected = false;
2265
+ }
2266
+ }
2267
+ /**
2268
+ * Send a bulk data chunk for image transfers.
2269
+ * @param cmdByte Command byte (0x60 for display, 0x70 for flash store)
2270
+ * @param data Source buffer
2271
+ * @param offset Starting offset in data
2272
+ * @param maxPayload Max bytes per chunk (default 62)
2273
+ */
2274
+ sendChunk(cmdByte, data, offset, maxPayload = 62) {
2275
+ const chunk = Buffer.alloc(HID_REPORT_SIZE, 0);
2276
+ chunk[0] = cmdByte;
2277
+ const toCopy = Math.min(maxPayload, data.length - offset);
2278
+ data.copy(chunk, 1, offset, offset + toCopy);
2279
+ try {
2280
+ this.device?.write([...chunk]);
2281
+ } catch {
2282
+ this.connected = false;
2283
+ }
2284
+ }
2285
+ handleData(buf) {
2286
+ const type = buf[0];
2287
+ if (type === RESP.IDLE || type === 81) return;
2288
+ if (type === SIG_EVENT.PEN_DATA || type === SIG_EVENT.PEN_UP || type === SIG_EVENT.PEN_DATA_EXT || type === SIG_EVENT.HOTSPOT) {
2289
+ this.signatureCallback?.(type, buf);
2290
+ return;
2291
+ }
2292
+ if (this.pending) {
2293
+ clearTimeout(this.pending.timer);
2294
+ const p = this.pending;
2295
+ this.pending = null;
2296
+ p.resolve(buf);
2297
+ }
2298
+ }
2299
+ // ─── Register Operations ──────────────────────────────────────────────────────
2300
+ /** Read a device register. Returns the data portion or null on error/timeout. */
2301
+ async readRegister(reg) {
2302
+ const resp = await this.sendCommand([CMD.READ_REG, reg]);
2303
+ if (resp && (resp[0] & 240) === 32) {
2304
+ const len = resp[2];
2305
+ return Buffer.from(resp.slice(3, 3 + len));
2306
+ }
2307
+ return null;
2308
+ }
2309
+ /** Write a 4-byte little-endian value to a register. */
2310
+ async writeRegister(reg, value) {
2311
+ const resp = await this.sendCommand([
2312
+ CMD.WRITE_REG,
2313
+ reg,
2314
+ 4,
2315
+ value & 255,
2316
+ value >> 8 & 255,
2317
+ value >> 16 & 255,
2318
+ value >> 24 & 255
2319
+ ]);
2320
+ if (!resp) return false;
2321
+ return (resp[0] & 240) === 32 || (resp[0] & 240) === 144;
2322
+ }
2323
+ /** Read full device info from registers. */
2324
+ async getDeviceInfo() {
2325
+ const info = {
2326
+ serialNo: "unknown",
2327
+ displayWidth: 320,
2328
+ displayHeight: 160,
2329
+ sensorWidth: 320,
2330
+ sensorHeight: 160,
2331
+ deviceId: 0,
2332
+ fwMajor: 0,
2333
+ fwMinor: 0,
2334
+ capabilities: 0
2335
+ };
2336
+ const serial = await this.readRegister(REG.SERIAL);
2337
+ if (serial) info.serialNo = serial.toString("utf16le").replace(/[\0#]/g, "");
2338
+ const devId = await this.readRegister(REG.DEVICE_ID);
2339
+ if (devId?.length && devId.length >= 4) info.deviceId = devId.readUInt32LE(0);
2340
+ const fw1 = await this.readRegister(REG.FW_VERSION1);
2341
+ if (fw1?.length && fw1.length >= 4) {
2342
+ info.fwMajor = fw1.readUInt16LE(0);
2343
+ info.fwMinor = fw1.readUInt16LE(2);
2344
+ }
2345
+ const caps = await this.readRegister(REG.CAPABILITIES);
2346
+ if (caps?.length && caps.length >= 4) info.capabilities = caps.readUInt32LE(0);
2347
+ const dw = await this.readRegister(REG.DISPLAY_WIDTH);
2348
+ if (dw?.length && dw.length >= 4) info.displayWidth = dw.readUInt32LE(0);
2349
+ const dh = await this.readRegister(REG.DISPLAY_HEIGHT);
2350
+ if (dh?.length && dh.length >= 4) info.displayHeight = dh.readUInt32LE(0);
2351
+ return info;
2352
+ }
2353
+ // ─── Display Commands ─────────────────────────────────────────────────────────
2354
+ /** Erase the pad display (clear to white). */
2355
+ async eraseDisplay() {
2356
+ const resp = await this.sendCommandWithRetry(
2357
+ [CMD.ERASE_DISPLAY],
2358
+ (r) => r[0] === RESP.ACK
2359
+ );
2360
+ return resp !== null;
2361
+ }
2362
+ /**
2363
+ * Send monochrome 1bpp bitmap data to the pad display.
2364
+ * Protocol: 0x84 header → 0x60 data chunks → 0x85 done.
2365
+ * Automatically inverts polarity (pad uses 1=black, framebuffer uses 0=black).
2366
+ */
2367
+ async drawImage(x, y, width, height, bitmapData) {
2368
+ const imgHeader = Buffer.alloc(25, 0);
2369
+ imgHeader[0] = CMD.DRAW_IMAGE;
2370
+ imgHeader.writeInt32LE(x, 1);
2371
+ imgHeader.writeInt32LE(y, 5);
2372
+ imgHeader.writeInt32LE(width, 9);
2373
+ imgHeader.writeInt32LE(height, 13);
2374
+ const resp = await this.sendCommandWithRetry(
2375
+ [...imgHeader],
2376
+ (r) => r[0] === RESP.ACK,
2377
+ this.config.imageTransferTimeout
2378
+ );
2379
+ if (!resp) return false;
2380
+ const invertedData = Buffer.alloc(bitmapData.length);
2381
+ for (let i = 0; i < bitmapData.length; i++) {
2382
+ invertedData[i] = bitmapData[i] ^ 255;
2383
+ }
2384
+ const chunkPayload = 62;
2385
+ for (let offset = 0; offset < invertedData.length; offset += chunkPayload) {
2386
+ this.sendChunk(CMD.DATA_CHUNK, invertedData, offset, chunkPayload);
2387
+ if (offset % (chunkPayload * 10) === 0 && offset > 0) {
2388
+ await new Promise((r) => setTimeout(r, this.config.chunkDelayMs));
2389
+ }
2390
+ }
2391
+ const doneResp = await this.sendCommand([CMD.IMAGE_DONE], this.config.imageTransferTimeout);
2392
+ return doneResp !== null && (doneResp[0] === RESP.IMAGE_ACK || doneResp[0] === RESP.ACK);
2393
+ }
2394
+ // ─── Flash Storage ────────────────────────────────────────────────────────────
2395
+ /**
2396
+ * Store a 1bpp bitmap to the pad's non-volatile flash as standby image.
2397
+ * Persists across power cycles and USB disconnects.
2398
+ *
2399
+ * Protocol: 0x89 header → 0x70 data chunks → 0xA4 standby config.
2400
+ * Flash uses direct polarity (opposite of display), auto-detected.
2401
+ */
2402
+ async storeStandbyImage(width, height, bitmapData) {
2403
+ let ones = 0;
2404
+ for (let i = 0; i < bitmapData.length; i++) {
2405
+ for (let b = 0; b < 8; b++) {
2406
+ if (bitmapData[i] & 1 << b) ones++;
2407
+ }
2408
+ }
2409
+ const needsInvert = ones > bitmapData.length * 4;
2410
+ const storeData = Buffer.alloc(bitmapData.length);
2411
+ for (let i = 0; i < bitmapData.length; i++) {
2412
+ storeData[i] = needsInvert ? bitmapData[i] ^ 255 : bitmapData[i];
2413
+ }
2414
+ const storeHeader = Buffer.alloc(33, 0);
2415
+ storeHeader[0] = CMD.STORE_IMAGE;
2416
+ storeHeader.writeInt32LE(0, 1);
2417
+ storeHeader.writeInt32LE(0, 5);
2418
+ storeHeader.writeInt32LE(width, 9);
2419
+ storeHeader.writeInt32LE(height, 13);
2420
+ storeHeader.writeInt32LE(0, 17);
2421
+ storeHeader.writeInt32LE(1, 21);
2422
+ storeHeader.writeInt32LE(1, 25);
2423
+ storeHeader.writeInt32LE(0, 29);
2424
+ const resp1 = await this.sendCommand([...storeHeader], this.config.flashStoreTimeout);
2425
+ if (!resp1 || resp1[0] !== RESP.ACK) {
2426
+ this.log.error("Flash store header rejected:", resp1 ? `0x${resp1[0].toString(16)}` : "timeout");
2427
+ return false;
2428
+ }
2429
+ const chunkPayload = 62;
2430
+ for (let offset = 0; offset < storeData.length; offset += chunkPayload) {
2431
+ this.sendChunk(CMD.STORE_CHUNK, storeData, offset, chunkPayload);
2432
+ if (offset % (chunkPayload * 20) === 0 && offset > 0) {
2433
+ await new Promise((r) => setTimeout(r, this.config.chunkDelayMs * 3));
2434
+ }
2435
+ }
2436
+ await new Promise((r) => setTimeout(r, 500));
2437
+ return this.sendSlideshowConfig(2, 3, 100, 1);
2438
+ }
2439
+ /**
2440
+ * Show the stored standby image from flash on the display.
2441
+ * Command 0x8A = "draw stored image" (from APIClosePad → APIDrawStoredImage).
2442
+ *
2443
+ * Single HID command - no image data transfer. Works regardless of who
2444
+ * stored the image (our library, Signotec SlideShow tool, etc.)
2445
+ */
2446
+ async showStandbyFromFlash() {
2447
+ const cmd = Buffer.alloc(33, 0);
2448
+ cmd[0] = CMD.SHOW_STORED;
2449
+ const resp = await this.sendCommand([...cmd], this.config.imageTransferTimeout);
2450
+ return resp !== null && (resp[0] === RESP.ACK || resp[0] === 152);
2451
+ }
2452
+ /**
2453
+ * Send a slideshow/standby configuration command (0xA4).
2454
+ * Automatically wraps in 0xA8 for Sigma pads (which don't support direct 0xA4).
2455
+ */
2456
+ async sendSlideshowConfig(action, mode, count, flag) {
2457
+ const configCmd = Buffer.alloc(49, 0);
2458
+ configCmd[0] = CMD.SLIDESHOW_CONFIG;
2459
+ configCmd.writeInt32LE(action, 1);
2460
+ configCmd.writeInt32LE(mode, 5);
2461
+ configCmd.writeInt32LE(count, 9);
2462
+ configCmd.writeInt32LE(flag, 13);
2463
+ let resp = await this.sendCommand([...configCmd], 5e3);
2464
+ if (!resp || resp[0] === RESP.ERROR) {
2465
+ const a8cmd = Buffer.alloc(50, 0);
2466
+ a8cmd[0] = CMD.EXTENDED;
2467
+ configCmd.copy(a8cmd, 1, 0, 49);
2468
+ resp = await this.sendCommand([...a8cmd], 5e3);
2469
+ }
2470
+ return resp !== null && (resp[0] === RESP.ACK || (resp[0] & 240) === 144);
2471
+ }
2472
+ // ─── Sensor / Hotspot Commands ────────────────────────────────────────────────
2473
+ /** Set the signature capture rectangle (left, top, width, height → registers 0x32-0x35). */
2474
+ async setSignRect(left, top, width, height) {
2475
+ const r1 = await this.writeRegister(REG.SIGN_LEFT, Math.round(left));
2476
+ const r2 = await this.writeRegister(REG.SIGN_TOP, Math.round(top));
2477
+ const r3 = await this.writeRegister(REG.SIGN_RIGHT, Math.round(left + width));
2478
+ const r4 = await this.writeRegister(REG.SIGN_BOTTOM, Math.round(top + height));
2479
+ return r1 && r2 && r3 && r4;
2480
+ }
2481
+ /** Clear all hotspot areas. */
2482
+ async clearHotSpots() {
2483
+ const resp = await this.sendCommand([CMD.ADVANCED_BUTTON, BUTTON_CMD.CLEAR_ALL]);
2484
+ return resp !== null && (resp[0] & 240) === 144;
2485
+ }
2486
+ /**
2487
+ * Add a hotspot (touch-sensitive button area).
2488
+ * @param index Hotspot index (0-based)
2489
+ * @param left X position
2490
+ * @param top Y position
2491
+ * @param width Width in pixels
2492
+ * @param height Height in pixels
2493
+ */
2494
+ async addHotSpot(index, left, top, width, height) {
2495
+ const resp = await this.sendCommand([
2496
+ CMD.ADVANCED_BUTTON,
2497
+ BUTTON_CMD.SET_RECT,
2498
+ 1,
2499
+ Math.round(index) & 127 | 128,
2500
+ Math.round(left) & 255,
2501
+ Math.round(left) >> 8 & 255,
2502
+ Math.round(top) & 255,
2503
+ Math.round(top) >> 8 & 255,
2504
+ 0,
2505
+ Math.round(width) & 255,
2506
+ Math.round(width) >> 8 & 255,
2507
+ Math.round(height) & 255,
2508
+ Math.round(height) >> 8 & 255
2509
+ ]);
2510
+ return resp !== null && (resp[0] & 240) === 144;
2511
+ }
2512
+ /** Enable hotspot monitoring (call after addHotSpot). */
2513
+ async enableHotspotMonitoring() {
2514
+ const resp = await this.sendCommand([CMD.ADVANCED_BUTTON, BUTTON_CMD.ENABLE_MONITORING]);
2515
+ return resp !== null && (resp[0] & 240) === 144;
2516
+ }
2517
+ // ─── Signature Session ────────────────────────────────────────────────────────
2518
+ /** Start signature capture. Protocol: [0x82, 0x00, 0x00, 0x00, 0x00]. */
2519
+ async startSignature() {
2520
+ const resp = await this.sendCommandWithRetry(
2521
+ [CMD.START_SIGN, 0, 0, 0, 0],
2522
+ (r) => r[0] === RESP.START_ACK
2523
+ );
2524
+ return resp !== null;
2525
+ }
2526
+ /** Stop signature capture. */
2527
+ async stopSignature() {
2528
+ const resp = await this.sendCommand([CMD.STOP_SIGN]);
2529
+ return resp !== null && resp[0] === RESP.STOP_ACK;
2530
+ }
2531
+ };
2532
+ // Annotate the CommonJS export names for ESM import in node:
2533
+ 0 && (module.exports = {
2534
+ CMD,
2535
+ HidProtocol,
2536
+ REG,
2537
+ RESP,
2538
+ SIG_EVENT
2539
+ });
2540
+ //# sourceMappingURL=hid-protocol.js.map