@onekeyfe/hwk-desktop-noble-ble 1.2.10 → 1.2.11-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24,14 +24,21 @@ __export(index_exports, {
24
24
  NobleBleHandler: () => NobleBleHandler,
25
25
  THIRD_PARTY_BLE_CHANNELS: () => THIRD_PARTY_BLE_CHANNELS,
26
26
  THIRD_PARTY_BLE_DEVICE_TTL_MS: () => THIRD_PARTY_BLE_DEVICE_TTL_MS,
27
+ THIRD_PARTY_BLE_IPC_ERROR_TYPE: () => THIRD_PARTY_BLE_IPC_ERROR_TYPE,
27
28
  THIRD_PARTY_BLE_POWER_ON_TIMEOUT_MS: () => THIRD_PARTY_BLE_POWER_ON_TIMEOUT_MS,
28
29
  THIRD_PARTY_BLE_SCAN_DURATION_MS: () => THIRD_PARTY_BLE_SCAN_DURATION_MS,
29
30
  THIRD_PARTY_BLE_SCAN_IDLE_STOP_MS: () => THIRD_PARTY_BLE_SCAN_IDLE_STOP_MS,
31
+ createThirdPartyBleIpcErrorResponse: () => createThirdPartyBleIpcErrorResponse,
30
32
  initThirdPartyBleSupport: () => initThirdPartyBleSupport,
31
- redactBleDebugLogData: () => redactBleDebugLogData
33
+ isThirdPartyBleIpcErrorResponse: () => isThirdPartyBleIpcErrorResponse,
34
+ redactBleDebugLogData: () => redactBleDebugLogData,
35
+ withThirdPartyBleIpcErrors: () => withThirdPartyBleIpcErrors
32
36
  });
33
37
  module.exports = __toCommonJS(index_exports);
34
38
 
39
+ // src/NobleBleHandler.ts
40
+ var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
41
+
35
42
  // src/debugLog.ts
36
43
  var REDACTED_KEYS = /* @__PURE__ */ new Set([
37
44
  // Secrets the user types or the device derives.
@@ -110,6 +117,12 @@ var THIRD_PARTY_BLE_CHANNELS = {
110
117
  /** push event: main → renderer when device disconnects unexpectedly */
111
118
  disconnected: "$onekey-3p-ble-disconnected"
112
119
  };
120
+ var THIRD_PARTY_BLE_IPC_ERROR_TYPE = "ThirdPartyBleIpcError";
121
+ function isThirdPartyBleIpcErrorResponse(response) {
122
+ if (!response || typeof response !== "object") return false;
123
+ const candidate = response;
124
+ return candidate.type === THIRD_PARTY_BLE_IPC_ERROR_TYPE && candidate.success === false && typeof candidate.error?.message === "string";
125
+ }
113
126
  var THIRD_PARTY_BLE_SCAN_DURATION_MS = 5e3;
114
127
  var THIRD_PARTY_BLE_SCAN_IDLE_STOP_MS = 1e4;
115
128
  var THIRD_PARTY_BLE_DEVICE_TTL_MS = 5e3;
@@ -161,15 +174,411 @@ var DEFAULT_THIRD_PARTY_BLE_VENDORS = Object.freeze({
161
174
  trezor: trezorProfile
162
175
  });
163
176
 
177
+ // src/windowsPairing.ts
178
+ var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
179
+
180
+ // src/windowsPairingHelper.ts
181
+ var import_child_process = require("child_process");
182
+ var import_hwk_adapter_core = require("@onekeyfe/hwk-adapter-core");
183
+ function isHelperEvent(value) {
184
+ if (!value || typeof value !== "object") return false;
185
+ const event = value;
186
+ switch (event.type) {
187
+ case "diag":
188
+ return typeof event.t_ms === "number" && typeof event.msg === "string";
189
+ case "link":
190
+ return typeof event.connected === "boolean";
191
+ case "pairing-result":
192
+ return typeof event.status === "number" && Number.isInteger(event.status);
193
+ case "pairing":
194
+ return typeof event.pin === "string";
195
+ case "paired":
196
+ case "already-paired":
197
+ return true;
198
+ case "error":
199
+ return typeof event.message === "string";
200
+ default:
201
+ return false;
202
+ }
203
+ }
204
+ var PAIR_TIMEOUT_MS = 6e4;
205
+ var PAIR_COMPLETION_TIMEOUT_MS = 3e4;
206
+ var PAIR_DECLINE_GRACE_MS = 5e3;
207
+ function helperFailure(message) {
208
+ const status = /DevicePairingResultStatus\((\d+)\)/.exec(message)?.[1];
209
+ if (status === void 0) {
210
+ return { code: import_hwk_adapter_core.HardwareErrorCode.BleConnectFailed, message, params: { phase: "pairing" } };
211
+ }
212
+ const pairingStatus = Number(status);
213
+ let code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
214
+ if (pairingStatus === 12) code = import_hwk_adapter_core.HardwareErrorCode.DevicePermissionDenied;
215
+ else if (pairingStatus === 14) code = import_hwk_adapter_core.HardwareErrorCode.BlePairingCancelled;
216
+ return {
217
+ code,
218
+ message,
219
+ params: {
220
+ phase: "pairing",
221
+ pairingStatus,
222
+ ...pairingStatus === 12 ? { permissionDeniedReason: "permissionDenied" } : {}
223
+ }
224
+ };
225
+ }
226
+ function pairWindowsBleDevice(options, target, signal, logger) {
227
+ return new Promise((resolve, reject) => {
228
+ const log = (event, data) => {
229
+ try {
230
+ logger?.({ level: "info", scope: "windows-pairing", event, data });
231
+ } catch {
232
+ }
233
+ };
234
+ const prompt = new AbortController();
235
+ const child = (0, import_child_process.spawn)(options.helperPath, ["pair", "--address", target.address], {
236
+ stdio: ["pipe", "pipe", "pipe"],
237
+ windowsHide: true
238
+ });
239
+ let settled = false;
240
+ let failure;
241
+ let outcome;
242
+ let waitingForDecision = false;
243
+ let decisionSent = false;
244
+ let stdout = "";
245
+ let confirmationTimer;
246
+ let disconnectTimer;
247
+ let completionTimer;
248
+ let killTimer;
249
+ const clearDisconnect = () => {
250
+ clearTimeout(disconnectTimer);
251
+ disconnectTimer = void 0;
252
+ };
253
+ const stopWaiting = () => {
254
+ waitingForDecision = false;
255
+ clearTimeout(confirmationTimer);
256
+ clearDisconnect();
257
+ };
258
+ const lockFailure = (error) => {
259
+ failure ?? (failure = error);
260
+ stopWaiting();
261
+ prompt.abort();
262
+ };
263
+ const decline = (error) => {
264
+ if (settled || failure) return;
265
+ lockFailure(error);
266
+ clearTimeout(timer);
267
+ clearTimeout(completionTimer);
268
+ child.stdin?.write("cancel\n", (error2) => {
269
+ if (error2) child.kill();
270
+ });
271
+ killTimer = setTimeout(() => child.kill(), PAIR_DECLINE_GRACE_MS);
272
+ };
273
+ const timeout = (message, params = {}) => decline({
274
+ code: import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout,
275
+ message,
276
+ params: { phase: "pairing", timedOut: true, ...params }
277
+ });
278
+ const timer = setTimeout(
279
+ () => timeout(`BLE pairing timed out after ${PAIR_TIMEOUT_MS}ms`),
280
+ PAIR_TIMEOUT_MS
281
+ );
282
+ const cancel = () => decline({
283
+ code: import_hwk_adapter_core.HardwareErrorCode.BlePairingCancelled,
284
+ message: "BLE pairing declined by user",
285
+ params: { phase: "pairing" }
286
+ });
287
+ const decide = (decision) => {
288
+ if (settled || failure || prompt.signal.aborted || decisionSent) return;
289
+ decisionSent = true;
290
+ stopWaiting();
291
+ if (decision !== "confirm") {
292
+ cancel();
293
+ return;
294
+ }
295
+ clearTimeout(timer);
296
+ completionTimer = setTimeout(
297
+ () => timeout(
298
+ `BLE pairing did not complete ${PAIR_COMPLETION_TIMEOUT_MS}ms after confirmation`
299
+ ),
300
+ PAIR_COMPLETION_TIMEOUT_MS
301
+ );
302
+ child.stdin?.write("confirm\n", (error) => {
303
+ if (error) {
304
+ decline({
305
+ code: import_hwk_adapter_core.HardwareErrorCode.BleConnectFailed,
306
+ message: "BLE pairing helper could not receive confirmation",
307
+ params: { phase: "pairing" }
308
+ });
309
+ }
310
+ });
311
+ };
312
+ const finish = (error) => {
313
+ if (settled) return;
314
+ settled = true;
315
+ signal.removeEventListener("abort", cancel);
316
+ clearTimeout(timer);
317
+ clearTimeout(completionTimer);
318
+ clearTimeout(killTimer);
319
+ stopWaiting();
320
+ prompt.abort();
321
+ const reason = failure ?? error;
322
+ if (reason) reject((0, import_hwk_adapter_core.createHwkError)(reason));
323
+ else if (outcome) resolve(outcome);
324
+ else
325
+ reject(
326
+ (0, import_hwk_adapter_core.createHwkError)({
327
+ code: import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout,
328
+ message: "BLE pairing did not complete",
329
+ params: { phase: "pairing" }
330
+ })
331
+ );
332
+ };
333
+ signal.addEventListener("abort", cancel, { once: true });
334
+ if (signal.aborted) cancel();
335
+ const endDisconnected = () => {
336
+ if (!waitingForDecision) return;
337
+ decline({
338
+ code: import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout,
339
+ message: "BLE pairing ended because the device disconnected",
340
+ params: { phase: "pairing", deviceDisconnected: true }
341
+ });
342
+ };
343
+ child.stdout?.on("data", (chunk) => {
344
+ stdout += chunk.toString("utf8");
345
+ let newline = stdout.indexOf("\n");
346
+ while (newline >= 0) {
347
+ const line = stdout.slice(0, newline).trim();
348
+ stdout = stdout.slice(newline + 1);
349
+ newline = stdout.indexOf("\n");
350
+ if (!line) continue;
351
+ let event;
352
+ try {
353
+ event = JSON.parse(line);
354
+ } catch {
355
+ log("helper.stdout.invalid");
356
+ continue;
357
+ }
358
+ if (!isHelperEvent(event)) {
359
+ log("helper.event.invalid");
360
+ continue;
361
+ }
362
+ log("helper.event", { type: event.type });
363
+ if (event.type === "pairing" && !failure && !decisionSent && !prompt.signal.aborted) {
364
+ if (waitingForDecision) continue;
365
+ waitingForDecision = true;
366
+ confirmationTimer = setTimeout(
367
+ () => timeout("BLE pairing confirmation timed out", { confirmationTimedOut: true }),
368
+ target.vendor === "ledger" ? 3e4 : PAIR_TIMEOUT_MS
369
+ );
370
+ const { pin } = event;
371
+ void Promise.resolve().then(() => {
372
+ if (prompt.signal.aborted) return "cancel";
373
+ return options.onPairingRequest({
374
+ id: target.id,
375
+ vendor: target.vendor,
376
+ pin,
377
+ signal: prompt.signal
378
+ });
379
+ }).then(decide, () => decide("cancel"));
380
+ } else if (event.type === "link") {
381
+ if (event.connected) clearDisconnect();
382
+ else if (waitingForDecision && !failure && !disconnectTimer) {
383
+ if (target.vendor === "trezor") {
384
+ disconnectTimer = setTimeout(endDisconnected, 1e3);
385
+ } else endDisconnected();
386
+ }
387
+ } else if (event.type === "pairing-result") {
388
+ log("helper.result", { status: event.status });
389
+ if (event.status === 0 || event.status === 3) {
390
+ stopWaiting();
391
+ prompt.abort();
392
+ } else {
393
+ lockFailure(
394
+ helperFailure(`pairing failed with status DevicePairingResultStatus(${event.status})`)
395
+ );
396
+ killTimer ?? (killTimer = setTimeout(() => child.kill(), PAIR_DECLINE_GRACE_MS));
397
+ }
398
+ } else if (event.type === "error") {
399
+ lockFailure(helperFailure(event.message));
400
+ killTimer ?? (killTimer = setTimeout(() => child.kill(), PAIR_DECLINE_GRACE_MS));
401
+ } else if (event.type === "paired" || event.type === "already-paired") {
402
+ outcome = event.type;
403
+ stopWaiting();
404
+ prompt.abort();
405
+ } else if (event.type === "diag") {
406
+ log("helper.diag", { elapsedMs: event.t_ms, message: event.msg });
407
+ }
408
+ }
409
+ });
410
+ child.stderr?.on("data", () => void 0);
411
+ child.stdin?.on("error", () => {
412
+ if (settled) return;
413
+ lockFailure({
414
+ code: import_hwk_adapter_core.HardwareErrorCode.BleConnectFailed,
415
+ message: "BLE pairing helper input pipe closed",
416
+ params: { phase: "pairing" }
417
+ });
418
+ child.kill();
419
+ });
420
+ child.on(
421
+ "error",
422
+ (error) => finish({
423
+ code: import_hwk_adapter_core.HardwareErrorCode.BleConnectFailed,
424
+ message: `BLE pairing helper failed to run: ${error.message}`,
425
+ params: { phase: "pairing" }
426
+ })
427
+ );
428
+ child.on("close", (code) => {
429
+ log("helper.closed", { code });
430
+ finish(
431
+ code === 0 ? void 0 : helperFailure(`BLE pairing helper exited with code ${code ?? "unknown"}`)
432
+ );
433
+ });
434
+ });
435
+ }
436
+
437
+ // src/windowsPairing.ts
438
+ var pairingQueue = Promise.resolve();
439
+ var cancelledError = () => (0, import_hwk_adapter_core2.createHwkError)({
440
+ code: import_hwk_adapter_core2.HardwareErrorCode.BlePairingCancelled,
441
+ message: "BLE connect cancelled",
442
+ params: { phase: "connect" }
443
+ });
444
+ var connectFacts = (error) => error?.params ?? {};
445
+ function waitForRetry(signal) {
446
+ return new Promise((resolve, reject) => {
447
+ const onAbort = () => {
448
+ clearTimeout(timer);
449
+ signal.removeEventListener("abort", onAbort);
450
+ reject(cancelledError());
451
+ };
452
+ const timer = setTimeout(() => {
453
+ signal.removeEventListener("abort", onAbort);
454
+ resolve();
455
+ }, 3e3);
456
+ signal.addEventListener("abort", onAbort, { once: true });
457
+ if (signal.aborted) onAbort();
458
+ });
459
+ }
460
+ var WindowsBlePairing = class {
461
+ constructor(options, preparationTimeoutMs, logger) {
462
+ this.pending = /* @__PURE__ */ new Set();
463
+ this.options = options;
464
+ this.logger = logger;
465
+ this.preparationTimeoutMs = preparationTimeoutMs;
466
+ }
467
+ cancel(target) {
468
+ for (const entry of this.pending) {
469
+ if (!target || target.vendor === entry.vendor && (target.id === void 0 || target.id === entry.id)) {
470
+ entry.controller.abort();
471
+ }
472
+ }
473
+ }
474
+ async connect(id, vendor, resolveDevice, pauseScan, connect) {
475
+ if (vendor !== "ledger" && vendor !== "trezor") return connect();
476
+ const entry = { id, vendor, controller: new AbortController() };
477
+ this.pending.add(entry);
478
+ const { signal } = entry.controller;
479
+ const assertActive = () => {
480
+ if (signal.aborted) throw cancelledError();
481
+ };
482
+ let resumeScan;
483
+ let pairingCleanup = Promise.resolve();
484
+ try {
485
+ let outcome = "skipped";
486
+ const preparing = (async () => {
487
+ const device2 = await resolveDevice(signal);
488
+ assertActive();
489
+ if (device2?.address) {
490
+ const resume = await pauseScan();
491
+ if (signal.aborted) {
492
+ resume();
493
+ throw cancelledError();
494
+ }
495
+ resumeScan = resume;
496
+ }
497
+ return device2;
498
+ })();
499
+ let onAbort;
500
+ let timer;
501
+ const interrupted = new Promise((_, reject) => {
502
+ onAbort = () => reject(cancelledError());
503
+ signal.addEventListener("abort", onAbort, { once: true });
504
+ if (signal.aborted) onAbort();
505
+ timer = setTimeout(() => {
506
+ reject(
507
+ (0, import_hwk_adapter_core2.createHwkError)({
508
+ code: import_hwk_adapter_core2.HardwareErrorCode.DeviceNotFound,
509
+ message: "BLE discovery did not complete before the connection deadline",
510
+ params: { phase: "connect", stage: "discovery", timedOut: true }
511
+ })
512
+ );
513
+ entry.controller.abort();
514
+ }, this.preparationTimeoutMs);
515
+ });
516
+ let device;
517
+ try {
518
+ device = await Promise.race([preparing, interrupted]);
519
+ } finally {
520
+ clearTimeout(timer);
521
+ signal.removeEventListener("abort", onAbort);
522
+ }
523
+ assertActive();
524
+ const address = device?.address;
525
+ if (address) {
526
+ const operation = pairingQueue.then(async () => {
527
+ assertActive();
528
+ return pairWindowsBleDevice(this.options, { id, vendor, address }, signal, this.logger);
529
+ });
530
+ pairingCleanup = operation.then(
531
+ () => void 0,
532
+ () => void 0
533
+ );
534
+ pairingQueue = pairingCleanup;
535
+ let onPairingAbort;
536
+ const aborted = new Promise((_, reject) => {
537
+ onPairingAbort = () => reject(cancelledError());
538
+ signal.addEventListener("abort", onPairingAbort, { once: true });
539
+ });
540
+ try {
541
+ outcome = await Promise.race([operation, aborted]);
542
+ } finally {
543
+ signal.removeEventListener("abort", onPairingAbort);
544
+ }
545
+ }
546
+ assertActive();
547
+ try {
548
+ return await connect();
549
+ } catch (error) {
550
+ assertActive();
551
+ const facts = connectFacts(error);
552
+ if (outcome === "paired" && !facts.timedOut) {
553
+ await waitForRetry(signal);
554
+ assertActive();
555
+ return await connect();
556
+ }
557
+ if (vendor === "ledger" && outcome === "already-paired" && facts.gattUnreachable && typeof facts.msSinceLink === "number" && facts.msSinceLink < 2e3) {
558
+ throw (0, import_hwk_adapter_core2.createHwkError)({
559
+ code: import_hwk_adapter_core2.HardwareErrorCode.BleBondInvalid,
560
+ message: "The Ledger dropped the link Windows holds a pairing for",
561
+ params: { phase: "connect", ...facts }
562
+ });
563
+ }
564
+ throw error;
565
+ }
566
+ } finally {
567
+ this.pending.delete(entry);
568
+ if (resumeScan) void pairingCleanup.then(resumeScan);
569
+ }
570
+ }
571
+ };
572
+
164
573
  // src/NobleBleHandler.ts
165
574
  var DEFAULT_NOBLE_FACTORY = () => {
166
575
  const noble = require("@stoprocent/noble");
167
576
  return noble;
168
577
  };
169
578
  var BLE_NAME_MATCH_MAX_LENGTH = 64;
170
- var matchesPeripheral = (p, profile, narrowTo) => {
579
+ var matchesPeripheral = (p, profile, narrowTo, remembered) => {
171
580
  const adv = p.advertisement ?? {};
172
- const advertised = adv.serviceUuids ?? [];
581
+ const advertised = [...adv.serviceUuids ?? [], ...remembered ?? []];
173
582
  if (advertised.some(
174
583
  (uuid) => typeof uuid === "string" && profile.isServiceUuid(uuid) && (!narrowTo || narrowTo.has(normalizeBleUuid(uuid)))
175
584
  )) {
@@ -185,7 +594,7 @@ var requestedServiceUuids = (options) => {
185
594
  const uuids = requested.filter((uuid) => typeof uuid === "string");
186
595
  return uuids.length ? new Set(uuids.map(normalizeBleUuid)) : void 0;
187
596
  };
188
- var peripheralToInfo = (p) => {
597
+ var peripheralToInfo = (p, remembered) => {
189
598
  const adv = p.advertisement ?? {};
190
599
  return {
191
600
  id: p.id,
@@ -193,7 +602,8 @@ var peripheralToInfo = (p) => {
193
602
  localName: adv.localName,
194
603
  rssi: p.rssi,
195
604
  isConnectable: p.connectable ?? null,
196
- advertisedServiceUuids: adv.serviceUuids,
605
+ // A name-only packet must not erase previously advertised services.
606
+ advertisedServiceUuids: [.../* @__PURE__ */ new Set([...adv.serviceUuids ?? [], ...remembered ?? []])],
197
607
  serviceSolicitationUuids: adv.serviceSolicitationUuids,
198
608
  txPowerLevel: adv.txPowerLevel,
199
609
  manufacturerDataHex: adv.manufacturerData ? Buffer.from(adv.manufacturerData).toString("hex") : void 0,
@@ -207,6 +617,70 @@ var peripheralToInfo = (p) => {
207
617
  };
208
618
  };
209
619
  var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
620
+ var nativeErrorFields = (error) => {
621
+ const { nativeErrorDomain, nativeErrorCode } = error ?? {};
622
+ return { nativeErrorDomain, nativeErrorCode };
623
+ };
624
+ var shuttingDownError = () => (0, import_hwk_adapter_core3.createHwkError)({
625
+ code: import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
626
+ message: "Desktop BLE is shutting down"
627
+ });
628
+ var invariantError = (message) => (0, import_hwk_adapter_core3.createHwkError)({ code: import_hwk_adapter_core3.HardwareErrorCode.UnknownError, message });
629
+ var bluetoothUnavailableError = (state) => (0, import_hwk_adapter_core3.createHwkError)({
630
+ code: state === "unsupported" ? import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable : import_hwk_adapter_core3.HardwareErrorCode.DevicePermissionDenied,
631
+ message: `Bluetooth is unavailable (state: ${state})`,
632
+ params: {
633
+ ...state === "unauthorized" ? { permissionDeniedReason: "permissionDenied" } : {},
634
+ ...state === "poweredOff" ? { permissionDeniedReason: "bluetoothTurnedOff" } : {},
635
+ bluetoothState: state
636
+ }
637
+ });
638
+ var BLE_UNUSABLE_STATES = /* @__PURE__ */ new Set(["poweredOff", "unauthorized", "unsupported"]);
639
+ var toCanonicalBleError = (error, phase, { linkLost = false, facts } = {}) => {
640
+ if ((0, import_hwk_adapter_core3.isHardwareErrorCode)(error?.code)) return error;
641
+ const native = nativeErrorFields(error);
642
+ const params = { phase, ...native, ...facts };
643
+ if (native.nativeErrorDomain === "CBErrorDomain" && native.nativeErrorCode === 14) {
644
+ return (0, import_hwk_adapter_core3.createHwkError)({
645
+ code: import_hwk_adapter_core3.HardwareErrorCode.BleBondInvalid,
646
+ message: "The device removed its Bluetooth pairing with this computer",
647
+ params
648
+ });
649
+ }
650
+ if (native.nativeErrorDomain === "CBATTErrorDomain" && native.nativeErrorCode === 15) {
651
+ return (0, import_hwk_adapter_core3.createHwkError)({
652
+ code: import_hwk_adapter_core3.HardwareErrorCode.BlePairingTimeout,
653
+ message: "Bluetooth pairing did not complete",
654
+ params
655
+ });
656
+ }
657
+ if (linkLost || phase === "write") {
658
+ return (0, import_hwk_adapter_core3.createHwkError)({
659
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected,
660
+ message: `BLE link dropped during ${phase}`,
661
+ params
662
+ });
663
+ }
664
+ return (0, import_hwk_adapter_core3.createHwkError)({
665
+ code: import_hwk_adapter_core3.HardwareErrorCode.BleConnectFailed,
666
+ message: error instanceof Error ? error.message : `BLE ${phase} failed`,
667
+ params
668
+ });
669
+ };
670
+ async function failOnNativeLinkLoss(peripheral, operation, phase) {
671
+ let onDisconnect;
672
+ const linkLost = new Promise((_, reject) => {
673
+ onDisconnect = (reason) => {
674
+ if (reason instanceof Error) reject(toCanonicalBleError(reason, phase, { linkLost: true }));
675
+ };
676
+ });
677
+ peripheral.on("disconnect", onDisconnect);
678
+ try {
679
+ return await Promise.race([operation, linkLost]);
680
+ } finally {
681
+ peripheral.removeListener("disconnect", onDisconnect);
682
+ }
683
+ }
210
684
  var raceTimeout = async (work, ms, onTimeout) => {
211
685
  let timer;
212
686
  try {
@@ -226,16 +700,23 @@ var raceTimeout = async (work, ms, onTimeout) => {
226
700
  var BLE_CONNECT_SETTLE_MS = 300;
227
701
  var BLE_CONNECT_TIMEOUT_MS = 31e3;
228
702
  var BLE_DISCONNECT_TIMEOUT_MS = 2e3;
703
+ var BLE_SUBSCRIBE_TIMEOUT_MS = 6e4;
229
704
  var NOBLE_RECOVER_COOLDOWN_MS = 1e4;
230
705
  var NobleBleHandler = class {
231
706
  constructor(options = {}) {
232
707
  this._discovered = /* @__PURE__ */ new Map();
233
708
  // id -> last advertisement time (snapshot TTL).
234
709
  this._lastSeen = /* @__PURE__ */ new Map();
710
+ // id -> service UUIDs seen since the device was last forgotten. noble-win replaces them with
711
+ // every packet, so a scan response without them would hide the device; CoreBluetooth merges.
712
+ this._advertisedUuids = /* @__PURE__ */ new Map();
713
+ // Devices a scan kept only by their remembered UUIDs; logged once each.
714
+ this._keptByMemory = /* @__PURE__ */ new Set();
235
715
  this._connected = /* @__PURE__ */ new Map();
236
716
  this._scanning = false;
237
717
  this._scanOwners = /* @__PURE__ */ new Set();
238
718
  this._scanTransition = Promise.resolve();
719
+ this._pairingScanPauses = 0;
239
720
  this._initialized = false;
240
721
  this._disposed = false;
241
722
  this._nobleInstances = /* @__PURE__ */ new Set();
@@ -244,12 +725,20 @@ var NobleBleHandler = class {
244
725
  this._nativeReleased = false;
245
726
  this._factory = options.nobleFactory ?? DEFAULT_NOBLE_FACTORY;
246
727
  this._connectTimeoutMs = options.connectTimeoutMs ?? BLE_CONNECT_TIMEOUT_MS;
728
+ this._subscribeTimeoutMs = options.subscribeTimeoutMs ?? BLE_SUBSCRIBE_TIMEOUT_MS;
247
729
  this._logger = options.logger;
730
+ if (process.platform === "win32" && options.windowsPairing) {
731
+ this._windowsPairing = new WindowsBlePairing(
732
+ options.windowsPairing,
733
+ this._connectTimeoutMs,
734
+ options.logger
735
+ );
736
+ }
248
737
  this._vendors = new Map(Object.entries(options.vendors ?? DEFAULT_THIRD_PARTY_BLE_VENDORS));
249
738
  }
250
739
  _resolveVendor(vendor) {
251
740
  const profile = typeof vendor === "string" ? this._vendors.get(vendor) : void 0;
252
- if (typeof vendor !== "string" || !profile) throw new Error("Unsupported BLE vendor");
741
+ if (typeof vendor !== "string" || !profile) throw invariantError("Unsupported BLE vendor");
253
742
  return { vendor, profile };
254
743
  }
255
744
  setNotificationListener(handler) {
@@ -268,6 +757,7 @@ var NobleBleHandler = class {
268
757
  this._discoverHandler ?? (this._discoverHandler = (peripheral) => {
269
758
  this._discovered.set(peripheral.id, peripheral);
270
759
  this._lastSeen.set(peripheral.id, Date.now());
760
+ this._rememberServiceUuids(peripheral);
271
761
  });
272
762
  this._noble.removeListener("discover", this._discoverHandler);
273
763
  this._noble.on("discover", this._discoverHandler);
@@ -332,6 +822,18 @@ var NobleBleHandler = class {
332
822
  }
333
823
  return devices;
334
824
  }
825
+ _rememberServiceUuids(peripheral) {
826
+ const uuids = peripheral.advertisement?.serviceUuids;
827
+ if (!uuids?.length) return;
828
+ let seen = this._advertisedUuids.get(peripheral.id);
829
+ if (!seen) {
830
+ seen = /* @__PURE__ */ new Set();
831
+ this._advertisedUuids.set(peripheral.id, seen);
832
+ }
833
+ for (const uuid of uuids) {
834
+ if (typeof uuid === "string") seen.add(uuid);
835
+ }
836
+ }
335
837
  /**
336
838
  * In-range devices matching the caller, minus TTL-expired ones. `_discovered`
337
839
  * is only a cache; a missing device can still be reached by `_directConnect`.
@@ -340,18 +842,26 @@ var NobleBleHandler = class {
340
842
  const now = Date.now();
341
843
  const result = [];
342
844
  for (const [id, peripheral] of this._discovered) {
343
- if (now - (this._lastSeen.get(id) ?? 0) > THIRD_PARTY_BLE_DEVICE_TTL_MS) {
845
+ if (this._pairingScanPauses === 0 && now - (this._lastSeen.get(id) ?? 0) > THIRD_PARTY_BLE_DEVICE_TTL_MS) {
344
846
  this._discovered.delete(id);
345
847
  this._lastSeen.delete(id);
848
+ this._advertisedUuids.delete(id);
849
+ this._keptByMemory.delete(id);
850
+ continue;
851
+ }
852
+ if (!matchesPeripheral(peripheral, profile, narrowTo, this._advertisedUuids.get(id))) {
346
853
  continue;
347
854
  }
348
- if (!matchesPeripheral(peripheral, profile, narrowTo)) continue;
349
- result.push(peripheralToInfo(peripheral));
855
+ if (!this._keptByMemory.has(id) && !matchesPeripheral(peripheral, profile, narrowTo)) {
856
+ this._keptByMemory.add(id);
857
+ this._log("info", "scan.keptByMemory", { id });
858
+ }
859
+ result.push(peripheralToInfo(peripheral, this._advertisedUuids.get(id)));
350
860
  }
351
861
  for (const [id, entry] of this._connected) {
352
862
  if (entry.vendor !== vendor) continue;
353
863
  if (result.some((info) => info.id === id)) continue;
354
- result.push(peripheralToInfo(entry.peripheral));
864
+ result.push(peripheralToInfo(entry.peripheral, this._advertisedUuids.get(id)));
355
865
  }
356
866
  return result;
357
867
  }
@@ -396,6 +906,8 @@ var NobleBleHandler = class {
396
906
  this._scanning = false;
397
907
  this._discovered.clear();
398
908
  this._lastSeen.clear();
909
+ this._advertisedUuids.clear();
910
+ this._keptByMemory.clear();
399
911
  await this._waitForPoweredOn(THIRD_PARTY_BLE_POWER_ON_TIMEOUT_MS);
400
912
  this._log("warn", "noble.recover.done", { state: this._noble?.state });
401
913
  } catch (error) {
@@ -403,7 +915,7 @@ var NobleBleHandler = class {
403
915
  }
404
916
  }
405
917
  _armIdleStop() {
406
- if (this._disposed) return;
918
+ if (this._disposed || this._pairingScanPauses > 0) return;
407
919
  this._clearIdleStop();
408
920
  this._idleStopTimer = setTimeout(() => {
409
921
  void this._stopContinuousScan();
@@ -421,7 +933,7 @@ var NobleBleHandler = class {
421
933
  const transition = this._scanTransition.then(async () => {
422
934
  if (scanning) {
423
935
  this._assertActive();
424
- if (this._scanOwners.size === 0) return;
936
+ if (this._scanOwners.size === 0 || this._pairingScanPauses > 0) return;
425
937
  }
426
938
  if (this._scanning === scanning) return;
427
939
  this._scanning = scanning;
@@ -445,11 +957,26 @@ var NobleBleHandler = class {
445
957
  this._clearIdleStop();
446
958
  await this._setScanning(false);
447
959
  }
960
+ async _pauseScanForPairing(vendor) {
961
+ this._scanOwners.delete(vendor);
962
+ this._pairingScanPauses += 1;
963
+ await this._pauseScan();
964
+ return () => {
965
+ this._pairingScanPauses -= 1;
966
+ if (this._disposed || this._pairingScanPauses > 0 || this._scanOwners.size === 0) return;
967
+ this._armIdleStop();
968
+ void this._setScanning(true).catch((error) => {
969
+ this._log("warn", "scan.resume.error", { error: String(error) });
970
+ });
971
+ };
972
+ }
448
973
  /** Stop scanning and forget discovered devices (idle timeout / teardown). */
449
974
  async _stopContinuousScan() {
450
975
  this._scanOwners.clear();
451
976
  this._discovered.clear();
452
977
  this._lastSeen.clear();
978
+ this._advertisedUuids.clear();
979
+ this._keptByMemory.clear();
453
980
  await this._pauseScan();
454
981
  }
455
982
  /** A vendor releasing discovery must not stop another vendor's scan. */
@@ -458,6 +985,11 @@ var NobleBleHandler = class {
458
985
  this._scanOwners.delete(vendor);
459
986
  if (this._scanOwners.size > 0) return;
460
987
  }
988
+ if (process.platform === "win32") {
989
+ this._scanOwners.clear();
990
+ await this._pauseScan();
991
+ return;
992
+ }
461
993
  await this._stopContinuousScan();
462
994
  }
463
995
  /**
@@ -466,10 +998,13 @@ var NobleBleHandler = class {
466
998
  */
467
999
  getDevice(id) {
468
1000
  const p = this._discovered.get(id);
469
- if (!p || ![...this._vendors.values()].some((profile) => matchesPeripheral(p, profile))) {
1001
+ const remembered = this._advertisedUuids.get(id);
1002
+ if (!p || ![...this._vendors.values()].some(
1003
+ (profile) => matchesPeripheral(p, profile, void 0, remembered)
1004
+ )) {
470
1005
  return null;
471
1006
  }
472
- return peripheralToInfo(p);
1007
+ return peripheralToInfo(p, remembered);
473
1008
  }
474
1009
  /** Live RSSI (dBm) of a connected peripheral, else the cached scan-time value. */
475
1010
  async readRssi(id) {
@@ -481,10 +1016,17 @@ var NobleBleHandler = class {
481
1016
  }
482
1017
  /** Abandon matching pairing attempts without touching another owner's links. */
483
1018
  async cancelPairing(options) {
1019
+ this._windowsPairing?.cancel(options);
484
1020
  const matches = (id, vendor) => options === void 0 || vendor === options.vendor && (options.id === void 0 || id === options.id);
485
1021
  for (const attempt of this._connectAttempts) {
486
1022
  if (!matches(attempt.id, attempt.vendor)) continue;
487
- attempt.abandon(new Error(`connect cancelled: ${attempt.id}`));
1023
+ attempt.abandon(
1024
+ (0, import_hwk_adapter_core3.createHwkError)({
1025
+ code: import_hwk_adapter_core3.HardwareErrorCode.BlePairingCancelled,
1026
+ message: `connect cancelled: ${attempt.id}`,
1027
+ params: { phase: "connect" }
1028
+ })
1029
+ );
488
1030
  try {
489
1031
  attempt.cancelNative();
490
1032
  } catch (error) {
@@ -581,17 +1123,44 @@ var NobleBleHandler = class {
581
1123
  BLE_DISCONNECT_TIMEOUT_MS
582
1124
  );
583
1125
  }
584
- // One timeout covers connect and service discovery; the connector maps
585
- // `timed out` (unreachable) and `connection failed` (stale bond) differently.
1126
+ // One timeout covers connect and service discovery.
586
1127
  async connect(id, options) {
587
1128
  if (!options || !options.vendor || ![options.serviceUuid, options.writeUuid, options.notifyUuid].every(
588
1129
  (uuid) => typeof uuid === "string" && /^[0-9a-f]{32}$/i.test(normalizeBleUuid(uuid))
589
1130
  )) {
590
- throw new Error("Invalid BLE GATT profile");
1131
+ throw invariantError("Invalid BLE GATT profile");
591
1132
  }
592
1133
  if (!this._resolveVendor(options.vendor).profile.acceptsConnect(options)) {
593
- throw new Error(`BLE GATT profile not allowed for ${options.vendor}`);
1134
+ throw invariantError(`BLE GATT profile not allowed for ${options.vendor}`);
1135
+ }
1136
+ this._assertActive();
1137
+ if (this._windowsPairing) {
1138
+ return this._windowsPairing.connect(
1139
+ id,
1140
+ options.vendor,
1141
+ async (signal) => {
1142
+ const claim = { abandoned: signal.aborted };
1143
+ const cancel = () => {
1144
+ claim.abandoned = true;
1145
+ claim.cancelScan?.();
1146
+ };
1147
+ signal.addEventListener("abort", cancel, { once: true });
1148
+ try {
1149
+ const peripheral = this._discovered.get(id) ?? await this._scanUntilFound(id, THIRD_PARTY_BLE_SCAN_DURATION_MS, claim);
1150
+ const { profile } = this._resolveVendor(options.vendor);
1151
+ const remembered = this._advertisedUuids.get(id);
1152
+ return peripheral && matchesPeripheral(peripheral, profile, void 0, remembered) ? peripheralToInfo(peripheral, remembered) : void 0;
1153
+ } finally {
1154
+ signal.removeEventListener("abort", cancel);
1155
+ }
1156
+ },
1157
+ () => this._pauseScanForPairing(options.vendor),
1158
+ () => this._connectWithTimeout(id, options)
1159
+ );
594
1160
  }
1161
+ return this._connectWithTimeout(id, options);
1162
+ }
1163
+ async _connectWithTimeout(id, options) {
595
1164
  this._assertActive();
596
1165
  const claim = { abandoned: false };
597
1166
  let abandon;
@@ -602,10 +1171,26 @@ var NobleBleHandler = class {
602
1171
  claim.cancelScan?.();
603
1172
  };
604
1173
  });
605
- const timer = setTimeout(
606
- () => abandon(new Error(`connect timed out after ${this._connectTimeoutMs}ms`)),
607
- this._connectTimeoutMs
608
- );
1174
+ const timer = setTimeout(() => {
1175
+ abandon(
1176
+ (0, import_hwk_adapter_core3.createHwkError)({
1177
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
1178
+ message: `connect timed out after ${this._connectTimeoutMs}ms`,
1179
+ // A device no scan surfaced is not advertising; the Ledger adapter retries that one.
1180
+ params: {
1181
+ phase: "connect",
1182
+ timedOut: true,
1183
+ ...claim.directPending ? { notAdvertising: true } : {}
1184
+ }
1185
+ })
1186
+ );
1187
+ if (this._connected.has(id)) return;
1188
+ try {
1189
+ claim.cancelNative?.();
1190
+ } catch (error) {
1191
+ this._log("warn", "connect.timeout.cancelConnect.error", { id, error: String(error) });
1192
+ }
1193
+ }, this._connectTimeoutMs);
609
1194
  const attempt = {
610
1195
  id,
611
1196
  vendor: options.vendor,
@@ -621,7 +1206,12 @@ var NobleBleHandler = class {
621
1206
  } catch (error) {
622
1207
  const peripheral = this._discovered.get(id);
623
1208
  if (peripheral && !this._connected.has(id)) await this._safeDisconnect(peripheral);
624
- throw error;
1209
+ this._log("warn", "connect.error", {
1210
+ id,
1211
+ error: String(error),
1212
+ ...nativeErrorFields(error)
1213
+ });
1214
+ throw toCanonicalBleError(error, "connect");
625
1215
  } finally {
626
1216
  clearTimeout(timer);
627
1217
  }
@@ -639,6 +1229,7 @@ var NobleBleHandler = class {
639
1229
  async _connectInner(id, claim, options) {
640
1230
  let route = "cache";
641
1231
  let peripheral;
1232
+ const startedAt = Date.now();
642
1233
  const abortIfAbandoned = async (stage) => {
643
1234
  if (!claim.abandoned && !this._disposed) return;
644
1235
  if (peripheral && peripheral.state === "connected" && !this._connected.has(id)) {
@@ -663,7 +1254,10 @@ var NobleBleHandler = class {
663
1254
  route = "direct";
664
1255
  const native2 = this._requireNoble();
665
1256
  claim.cancelNative = () => native2.cancelConnect?.(id);
1257
+ claim.directPending = true;
666
1258
  peripheral = await this._directConnect(id);
1259
+ claim.directPending = false;
1260
+ await abortIfAbandoned("direct");
667
1261
  }
668
1262
  if (!peripheral) {
669
1263
  this._log("warn", "connect.notFound", {
@@ -671,7 +1265,11 @@ var NobleBleHandler = class {
671
1265
  route: "none",
672
1266
  discoveredCount: this._discovered.size
673
1267
  });
674
- throw new Error(`BLE device not found: ${id}`);
1268
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1269
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
1270
+ message: `BLE device not found: ${id}`,
1271
+ params: { phase: "connect", notAdvertising: true }
1272
+ });
675
1273
  }
676
1274
  await abortIfAbandoned("resolve");
677
1275
  const wasConnected = peripheral.state === "connected";
@@ -688,27 +1286,43 @@ var NobleBleHandler = class {
688
1286
  id,
689
1287
  route,
690
1288
  wasConnected,
691
- name: peripheral.advertisement?.localName
1289
+ name: peripheral.advertisement?.localName,
1290
+ elapsedMs: Date.now() - startedAt
692
1291
  });
693
1292
  if (!wasConnected) {
694
1293
  await peripheral.connectAsync();
1294
+ this._log("info", "connect.linked", { id, elapsedMs: Date.now() - startedAt });
695
1295
  await abortIfAbandoned("link");
696
1296
  }
1297
+ const linkedAt = Date.now();
697
1298
  try {
698
- const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(
699
- [options.serviceUuid],
700
- [options.writeUuid, options.notifyUuid]
1299
+ const { characteristics } = await failOnNativeLinkLoss(
1300
+ peripheral,
1301
+ peripheral.discoverSomeServicesAndCharacteristicsAsync(
1302
+ [options.serviceUuid],
1303
+ [options.writeUuid, options.notifyUuid]
1304
+ ),
1305
+ "connect"
701
1306
  );
702
1307
  const writeUuid = normalizeBleUuid(options.writeUuid);
703
1308
  const notifyUuid = normalizeBleUuid(options.notifyUuid);
704
1309
  const writeChar = characteristics.find((c) => normalizeBleUuid(c.uuid) === writeUuid);
705
1310
  const notifyChar = characteristics.find((c) => normalizeBleUuid(c.uuid) === notifyUuid);
706
1311
  if (!writeChar || !notifyChar) {
707
- throw new Error(`BLE characteristics not found on device ${id}`);
1312
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1313
+ code: import_hwk_adapter_core3.HardwareErrorCode.BleConnectFailed,
1314
+ message: `BLE device ${id} lacks the expected characteristics`,
1315
+ params: { phase: "connect" }
1316
+ });
708
1317
  }
709
1318
  await abortIfAbandoned("discovery");
710
- const disconnectHandler = () => {
1319
+ const disconnectHandler = (reason) => {
711
1320
  if (this._connected.get(id)?.disconnectHandler !== disconnectHandler) return;
1321
+ this._log("warn", "disconnect.reason", {
1322
+ id,
1323
+ reason: String(reason),
1324
+ ...nativeErrorFields(reason)
1325
+ });
712
1326
  this._cleanupDevice(
713
1327
  id,
714
1328
  /* unexpected */
@@ -724,11 +1338,20 @@ var NobleBleHandler = class {
724
1338
  vendor: options.vendor,
725
1339
  write: options.write
726
1340
  });
727
- this._log("info", "connect.done", { id, name: peripheral.advertisement.localName });
1341
+ this._log("info", "connect.done", {
1342
+ id,
1343
+ name: peripheral.advertisement.localName,
1344
+ elapsedMs: Date.now() - startedAt
1345
+ });
728
1346
  return { id, name: peripheral.advertisement.localName };
729
1347
  } catch (error) {
730
- if (!wasConnected) await this._safeDisconnect(peripheral);
731
- throw error;
1348
+ const msSinceLink = Date.now() - linkedAt;
1349
+ const openedLink = !wasConnected || route === "direct" && !this._connected.has(id);
1350
+ if (openedLink) await this._safeDisconnect(peripheral);
1351
+ const unreachable = error instanceof Error && /\bunreachable\b/i.test(error.message);
1352
+ throw toCanonicalBleError(error, "connect", {
1353
+ facts: unreachable ? { gattUnreachable: true, msSinceLink } : void 0
1354
+ });
732
1355
  }
733
1356
  }
734
1357
  async disconnect(id) {
@@ -751,18 +1374,67 @@ var NobleBleHandler = class {
751
1374
  }
752
1375
  async subscribe(id) {
753
1376
  const entry = this._requireEntry(id);
754
- if (!entry.notifyChar) throw new Error(`BLE notify characteristic missing for ${id}`);
1377
+ if (!entry.notifyChar) throw invariantError(`BLE notify characteristic missing for ${id}`);
1378
+ if (entry.subscribing) return entry.subscribing;
755
1379
  if (entry.notifyHandler) return;
1380
+ const characteristic = entry.notifyChar;
756
1381
  const handler = (data) => {
757
- this._onNotification?.(id, data.toString("hex"));
1382
+ if (this._connected.get(id) === entry) this._onNotification?.(id, data.toString("hex"));
758
1383
  };
759
1384
  entry.notifyHandler = handler;
760
1385
  entry.notifyChar.on("data", handler);
761
- await entry.notifyChar.subscribeAsync();
1386
+ const subscribing = failOnNativeLinkLoss(
1387
+ entry.peripheral,
1388
+ this._withSubscribeTimeout(Promise.resolve().then(() => characteristic.subscribeAsync())),
1389
+ "subscribe"
1390
+ ).catch(async (error) => {
1391
+ this._log("warn", "subscribe.error", {
1392
+ id,
1393
+ error: String(error),
1394
+ ...nativeErrorFields(error)
1395
+ });
1396
+ const canonical = toCanonicalBleError(error, "subscribe", {
1397
+ linkLost: entry.peripheral.state !== "connected"
1398
+ });
1399
+ if (this._connected.get(id) === entry) {
1400
+ this._cleanupDevice(id, true, entry);
1401
+ await this._safeDisconnect(entry.peripheral);
1402
+ }
1403
+ throw canonical;
1404
+ }).finally(() => {
1405
+ if (entry.subscribing === subscribing) entry.subscribing = void 0;
1406
+ });
1407
+ entry.subscribing = subscribing;
1408
+ return subscribing;
1409
+ }
1410
+ async _withSubscribeTimeout(subscribing) {
1411
+ let timer;
1412
+ let cancel;
1413
+ const expired = new Promise((_, reject) => {
1414
+ timer = setTimeout(() => {
1415
+ reject(
1416
+ (0, import_hwk_adapter_core3.createHwkError)({
1417
+ code: import_hwk_adapter_core3.HardwareErrorCode.BleConnectFailed,
1418
+ message: `subscribe timed out after ${this._subscribeTimeoutMs}ms`,
1419
+ params: { phase: "subscribe" }
1420
+ })
1421
+ );
1422
+ }, this._subscribeTimeoutMs);
1423
+ cancel = () => reject(shuttingDownError());
1424
+ this._pendingCancellations.add(cancel);
1425
+ });
1426
+ try {
1427
+ await Promise.race([subscribing, expired]);
1428
+ } finally {
1429
+ clearTimeout(timer);
1430
+ if (cancel) this._pendingCancellations.delete(cancel);
1431
+ }
762
1432
  }
763
1433
  async unsubscribe(id) {
764
1434
  const entry = this._connected.get(id);
765
1435
  if (!entry?.notifyChar) return;
1436
+ await entry.subscribing?.catch(() => void 0);
1437
+ if (this._connected.get(id) !== entry) return;
766
1438
  if (entry.notifyHandler) {
767
1439
  entry.notifyChar.removeListener("data", entry.notifyHandler);
768
1440
  entry.notifyHandler = void 0;
@@ -775,26 +1447,35 @@ var NobleBleHandler = class {
775
1447
  }
776
1448
  async write(id, hexData) {
777
1449
  const entry = this._requireEntry(id);
778
- if (!entry.writeChar) throw new Error(`BLE write characteristic missing for ${id}`);
1450
+ const { writeChar } = entry;
1451
+ if (!writeChar) throw invariantError(`BLE write characteristic missing for ${id}`);
779
1452
  const buffer = Buffer.from(hexData, "hex");
780
1453
  const framing = entry.write;
781
- if (!framing) throw new Error(`No BLE write framing recorded for ${id}`);
1454
+ if (!framing) throw invariantError(`No BLE write framing recorded for ${id}`);
1455
+ const writeChunk = async (chunk) => {
1456
+ try {
1457
+ await writeChar.writeAsync(chunk, false);
1458
+ } catch (error) {
1459
+ this._log("warn", "write.error", { id, error: String(error), ...nativeErrorFields(error) });
1460
+ throw toCanonicalBleError(error, "write");
1461
+ }
1462
+ };
782
1463
  if (framing.mode === "raw") {
783
1464
  const maxLength = framing.maxLength ?? buffer.length;
784
1465
  if (!/^(?:[0-9a-f]{2})+$/i.test(hexData) || buffer.length > maxLength) {
785
- throw new Error(`Invalid BLE frame for ${entry.vendor ?? "device"}`);
1466
+ throw invariantError(`Invalid BLE frame for ${entry.vendor ?? "device"}`);
786
1467
  }
787
- await entry.writeChar.writeAsync(buffer, false);
1468
+ await writeChunk(buffer);
788
1469
  return;
789
1470
  }
790
1471
  const { chunkSize } = framing;
791
- if (!chunkSize) throw new Error(`Padded BLE writes need a chunkSize for ${id}`);
1472
+ if (!chunkSize) throw invariantError(`Padded BLE writes need a chunkSize for ${id}`);
792
1473
  for (let offset = 0; offset < buffer.length; offset += chunkSize) {
793
1474
  this._assertActive();
794
1475
  const slice = buffer.subarray(offset, offset + chunkSize);
795
1476
  const chunk = Buffer.alloc(chunkSize);
796
1477
  slice.copy(chunk);
797
- await entry.writeChar.writeAsync(chunk, false);
1478
+ await writeChunk(chunk);
798
1479
  if (offset + chunkSize < buffer.length && framing.chunkDelayMs) {
799
1480
  await delay(framing.chunkDelayMs);
800
1481
  }
@@ -804,13 +1485,14 @@ var NobleBleHandler = class {
804
1485
  dispose() {
805
1486
  if (this._disposePromise) return this._disposePromise;
806
1487
  this._disposed = true;
1488
+ this._windowsPairing?.cancel();
807
1489
  this._clearIdleStop();
808
1490
  this._scanning = false;
809
1491
  this._onNotification = void 0;
810
1492
  this._onDeviceDisconnected = void 0;
811
1493
  const connections = Array.from(this._connectAttempts);
812
1494
  for (const attempt of connections) {
813
- attempt.abandon(new Error("Desktop BLE is shutting down"));
1495
+ attempt.abandon(shuttingDownError());
814
1496
  try {
815
1497
  attempt.cancelNative();
816
1498
  } catch (error) {
@@ -846,6 +1528,8 @@ var NobleBleHandler = class {
846
1528
  } finally {
847
1529
  this._discovered.clear();
848
1530
  this._lastSeen.clear();
1531
+ this._advertisedUuids.clear();
1532
+ this._keptByMemory.clear();
849
1533
  this._initialized = false;
850
1534
  }
851
1535
  })();
@@ -875,7 +1559,7 @@ var NobleBleHandler = class {
875
1559
  return this._releasePromise;
876
1560
  }
877
1561
  _assertActive() {
878
- if (this._disposed) throw new Error("Desktop BLE is shutting down");
1562
+ if (this._disposed) throw shuttingDownError();
879
1563
  }
880
1564
  _cleanupDevice(id, unexpected, expected) {
881
1565
  const entry = this._connected.get(id);
@@ -896,12 +1580,17 @@ var NobleBleHandler = class {
896
1580
  _requireEntry(id) {
897
1581
  this._assertActive();
898
1582
  const entry = this._connected.get(id);
899
- if (!entry) throw new Error(`BLE device is not connected: ${id}`);
1583
+ if (!entry) {
1584
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1585
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected,
1586
+ message: `BLE device is not connected: ${id}`
1587
+ });
1588
+ }
900
1589
  return entry;
901
1590
  }
902
1591
  _requireNoble() {
903
1592
  this._assertActive();
904
- if (!this._noble) throw new Error("Desktop BLE: noble was not initialized");
1593
+ if (!this._noble) throw invariantError("Desktop BLE: noble was not initialized");
905
1594
  return this._noble;
906
1595
  }
907
1596
  /** A fresh noble reads `unknown` until its bindings report; wait for that first report. */
@@ -923,6 +1612,7 @@ var NobleBleHandler = class {
923
1612
  async _waitForPoweredOn(timeoutMs) {
924
1613
  const noble = this._requireNoble();
925
1614
  if (noble.state === "poweredOn") return;
1615
+ if (BLE_UNUSABLE_STATES.has(noble.state)) throw bluetoothUnavailableError(noble.state);
926
1616
  await new Promise((resolve, reject) => {
927
1617
  const cleanup = () => {
928
1618
  clearTimeout(timer);
@@ -931,23 +1621,19 @@ var NobleBleHandler = class {
931
1621
  };
932
1622
  const cancel = () => {
933
1623
  cleanup();
934
- reject(new Error("Desktop BLE is shutting down"));
1624
+ reject(shuttingDownError());
935
1625
  };
936
1626
  const timer = setTimeout(() => {
937
1627
  cleanup();
938
- reject(
939
- new Error(
940
- `Desktop BLE: noble did not reach poweredOn within ${timeoutMs}ms (last state: ${noble.state})`
941
- )
942
- );
1628
+ reject(bluetoothUnavailableError(noble.state));
943
1629
  }, timeoutMs);
944
1630
  const handler = (state) => {
945
1631
  if (state === "poweredOn") {
946
1632
  cleanup();
947
1633
  resolve();
948
- } else if (state === "unsupported" || state === "unauthorized") {
1634
+ } else if (BLE_UNUSABLE_STATES.has(state)) {
949
1635
  cleanup();
950
- reject(new Error(`Desktop BLE: noble state ${state}`));
1636
+ reject(bluetoothUnavailableError(state));
951
1637
  }
952
1638
  };
953
1639
  this._pendingCancellations.add(cancel);
@@ -965,6 +1651,36 @@ var NobleBleHandler = class {
965
1651
  };
966
1652
 
967
1653
  // src/main.ts
1654
+ var import_hwk_adapter_core4 = require("@onekeyfe/hwk-adapter-core");
1655
+ function createThirdPartyBleIpcErrorResponse(error) {
1656
+ const { message, code, params } = error ?? {};
1657
+ const serialized = {
1658
+ message: typeof message === "string" ? message : "Unknown error",
1659
+ // A host error's own code (the app's -99999) must not read as a HardwareErrorCode.
1660
+ ...(0, import_hwk_adapter_core4.isHardwareErrorCode)(code) ? { code } : {}
1661
+ };
1662
+ if (params && typeof params === "object") {
1663
+ try {
1664
+ serialized.params = JSON.parse(JSON.stringify(params));
1665
+ } catch {
1666
+ }
1667
+ }
1668
+ return { type: THIRD_PARTY_BLE_IPC_ERROR_TYPE, success: false, error: serialized };
1669
+ }
1670
+ function withThirdPartyBleIpcErrors(ipcMain) {
1671
+ return {
1672
+ handle: (channel, listener) => {
1673
+ ipcMain.handle(channel, async (event, ...args) => {
1674
+ try {
1675
+ return await Promise.resolve(listener(event, ...args));
1676
+ } catch (error) {
1677
+ return createThirdPartyBleIpcErrorResponse(error);
1678
+ }
1679
+ });
1680
+ },
1681
+ removeHandler: (channel) => ipcMain.removeHandler(channel)
1682
+ };
1683
+ }
968
1684
  var DEFAULT_IPC_MAIN = () => {
969
1685
  const { ipcMain } = require("electron");
970
1686
  return ipcMain;
@@ -1033,10 +1749,14 @@ function initThirdPartyBleSupport(webContents, options = {}) {
1033
1749
  NobleBleHandler,
1034
1750
  THIRD_PARTY_BLE_CHANNELS,
1035
1751
  THIRD_PARTY_BLE_DEVICE_TTL_MS,
1752
+ THIRD_PARTY_BLE_IPC_ERROR_TYPE,
1036
1753
  THIRD_PARTY_BLE_POWER_ON_TIMEOUT_MS,
1037
1754
  THIRD_PARTY_BLE_SCAN_DURATION_MS,
1038
1755
  THIRD_PARTY_BLE_SCAN_IDLE_STOP_MS,
1756
+ createThirdPartyBleIpcErrorResponse,
1039
1757
  initThirdPartyBleSupport,
1040
- redactBleDebugLogData
1758
+ isThirdPartyBleIpcErrorResponse,
1759
+ redactBleDebugLogData,
1760
+ withThirdPartyBleIpcErrors
1041
1761
  });
1042
1762
  //# sourceMappingURL=index.js.map