@onekeyfe/hwk-adapter-core 1.2.3-alpha.8 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{chunk-WUIWRX56.js → chunk-BAGEFFFY.js} +13 -49
  2. package/dist/chunk-BAGEFFFY.js.map +1 -0
  3. package/dist/{chunk-CQM2P5IG.js → chunk-SZZF623R.js} +55 -155
  4. package/dist/chunk-SZZF623R.js.map +1 -0
  5. package/dist/{chunk-EQYPRCWU.mjs → chunk-U63HTLGJ.mjs} +12 -48
  6. package/dist/chunk-U63HTLGJ.mjs.map +1 -0
  7. package/dist/{chunk-IOFMG7YO.mjs → chunk-YA4BWFTZ.mjs} +55 -155
  8. package/dist/chunk-YA4BWFTZ.mjs.map +1 -0
  9. package/dist/errors.d.mts +207 -1
  10. package/dist/errors.d.ts +207 -1
  11. package/dist/errors.js +2 -8
  12. package/dist/errors.js.map +1 -1
  13. package/dist/errors.mjs +3 -9
  14. package/dist/index.d.mts +98 -635
  15. package/dist/index.d.ts +98 -635
  16. package/dist/index.js +82 -680
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +73 -671
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{ui-events-BGUpXxvP.d.ts → ui-events-Cb7haAeE.d.mts} +3 -44
  21. package/dist/{ui-events-BGUpXxvP.d.mts → ui-events-Cb7haAeE.d.ts} +3 -44
  22. package/dist/ui-events.d.mts +1 -1
  23. package/dist/ui-events.d.ts +1 -1
  24. package/dist/ui-events.js +2 -3
  25. package/dist/ui-events.js.map +1 -1
  26. package/dist/ui-events.mjs +1 -2
  27. package/package.json +2 -2
  28. package/dist/chunk-CQM2P5IG.js.map +0 -1
  29. package/dist/chunk-DB4JOPZO.mjs +0 -74
  30. package/dist/chunk-DB4JOPZO.mjs.map +0 -1
  31. package/dist/chunk-EQYPRCWU.mjs.map +0 -1
  32. package/dist/chunk-IOFMG7YO.mjs.map +0 -1
  33. package/dist/chunk-WUIWRX56.js.map +0 -1
  34. package/dist/chunk-YLCHSNXO.js +0 -74
  35. package/dist/chunk-YLCHSNXO.js.map +0 -1
  36. package/dist/errors-Cm8XpjmX.d.mts +0 -321
  37. package/dist/errors-Cm8XpjmX.d.ts +0 -321
package/dist/index.mjs CHANGED
@@ -1,6 +1,9 @@
1
1
  import {
2
+ HardwareErrorCode,
3
+ ORPHAN_ELIGIBLE_ERROR_CODES,
4
+ createHwkError,
2
5
  enrichErrorMessage
3
- } from "./chunk-DB4JOPZO.mjs";
6
+ } from "./chunk-YA4BWFTZ.mjs";
4
7
  import {
5
8
  UI_EVENT,
6
9
  UI_REQUEST,
@@ -10,40 +13,19 @@ import {
10
13
  UI_REQUEST_TIMEOUT_TAG,
11
14
  UI_RESPONSE,
12
15
  UiRequestRegistry
13
- } from "./chunk-EQYPRCWU.mjs";
14
- import {
15
- HardwareErrorCode,
16
- ORPHAN_ELIGIBLE_ERROR_CODES,
17
- createHwkError,
18
- defaultOriginForCode,
19
- defaultRecoveryForCode,
20
- isHwkRecoveryHint,
21
- operationMayHaveCompletedParams
22
- } from "./chunk-IOFMG7YO.mjs";
16
+ } from "./chunk-U63HTLGJ.mjs";
23
17
 
24
18
  // src/types/response.ts
25
19
  function success(payload) {
26
20
  return { success: true, payload };
27
21
  }
28
- function failure(code, error, params, origin, recovery) {
22
+ function failure(code, error, params) {
29
23
  return {
30
24
  success: false,
31
- payload: {
32
- error,
33
- code,
34
- ...origin !== void 0 ? { origin } : {},
35
- recovery: recovery ?? defaultRecoveryForCode(code),
36
- ...params ? { params } : {}
37
- }
25
+ payload: { error, code, ...params ? { params } : {} }
38
26
  };
39
27
  }
40
28
 
41
- // src/types/device.ts
42
- function resolveSearchTargetReusePolicy(device) {
43
- if (device.capabilities?.persistentDeviceIdentity) return "reconnectable";
44
- return "current-discovery";
45
- }
46
-
47
29
  // src/types/fingerprint.ts
48
30
  import { sha256 } from "@noble/hashes/sha256";
49
31
  import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils";
@@ -53,21 +35,11 @@ var CHAIN_FINGERPRINT_PATHS = {
53
35
  // Cointype 1 (testnet) is rejected by some Ledger BTC App configurations.
54
36
  btc: "m/44'/0'/0'",
55
37
  sol: "m/44'/501'/0'",
56
- tron: "m/44'/195'/0'/0/0",
57
- // Shielded UA (single Orchard receiver) derived from the transparent path.
58
- zcash: "m/44'/133'/0'/0/0"
38
+ tron: "m/44'/195'/0'/0/0"
59
39
  };
60
- function parseBip32MasterFingerprint(value) {
61
- if (typeof value !== "string") return void 0;
62
- const normalized = value.trim().toLowerCase();
63
- return /^[0-9a-f]{8}$/.test(normalized) ? normalized : void 0;
64
- }
65
40
  function deriveDeviceFingerprint(value) {
66
41
  return bytesToHex(sha256(utf8ToBytes(value))).slice(0, 16);
67
42
  }
68
- function deriveWalletId(canonicalPublicMaterial) {
69
- return bytesToHex(sha256(utf8ToBytes(`onekey-hwk-wallet-id:v1:${canonicalPublicMaterial}`)));
70
- }
71
43
 
72
44
  // src/events/device.ts
73
45
  var DEVICE_EVENT = "DEVICE_EVENT";
@@ -94,8 +66,7 @@ var SDK = {
94
66
  DEVICE_STUCK: "device-stuck",
95
67
  DEVICE_UNRESPONSIVE: "device-unresponsive",
96
68
  DEVICE_RECOVERED: "device-recovered",
97
- DEVICE_INTERACTION: "device-interaction",
98
- OPERATION_ENDED: "operation-ended"
69
+ DEVICE_INTERACTION: "device-interaction"
99
70
  };
100
71
 
101
72
  // src/utils/DeviceJobQueue.ts
@@ -104,7 +75,6 @@ var DeviceJobQueue = class {
104
75
  this._tail = Promise.resolve();
105
76
  this._active = null;
106
77
  this._jobs = /* @__PURE__ */ new Map();
107
- this._cancelScopes = /* @__PURE__ */ new Map();
108
78
  /** Incremented on clear() so queued-but-not-yet-running jobs detect invalidation. */
109
79
  this._generation = 0;
110
80
  this._generationCancelReasons = /* @__PURE__ */ new Map();
@@ -127,13 +97,12 @@ var DeviceJobQueue = class {
127
97
  abortController: ac,
128
98
  startedAt: Date.now()
129
99
  };
130
- this._jobs.set(jobToken, activeJob);
100
+ this._jobs.set(jobToken, { deviceId });
131
101
  const next = prev.catch(() => {
132
102
  }).then(async () => {
133
103
  if (this._generation !== gen) {
134
104
  throw this._generationCancelReasons.get(gen) ?? new Error("Job cancelled: queue was cleared");
135
105
  }
136
- if (ac.signal.aborted) throw ac.signal.reason;
137
106
  this._active = activeJob;
138
107
  try {
139
108
  return await job(ac.signal);
@@ -149,69 +118,32 @@ var DeviceJobQueue = class {
149
118
  });
150
119
  return next;
151
120
  }
152
- /**
153
- * Open a cancellation scope that outlives the individual jobs under it.
154
- *
155
- * A bundle (all-network) does not enqueue itself — it enqueues one job per
156
- * item. Between two items the queue is empty, so a cancel landing in that
157
- * gap finds nothing to abort and the next item goes to the device anyway.
158
- * The scope holds the cancel across those gaps; the bundle checks its
159
- * signal before each item. Callers must `release()` when the bundle ends.
160
- */
161
- createCancelScope(deviceId) {
162
- const scopeToken = {};
163
- const abortController = new AbortController();
164
- this._cancelScopes.set(scopeToken, { deviceId, abortController });
165
- return {
166
- signal: abortController.signal,
167
- release: () => {
168
- this._cancelScopes.delete(scopeToken);
169
- }
170
- };
121
+ /** Cancel the active job. If `deviceId` is given, only cancels when it matches. */
122
+ cancelActive(deviceId) {
123
+ if (!this._active) return false;
124
+ if (deviceId && this._active.deviceId !== deviceId) return false;
125
+ this._active.abortController.abort(new Error("Manually cancelled"));
126
+ return true;
171
127
  }
172
- /**
173
- * Cancel the running job. `reason` becomes signal.reason.
174
- *
175
- * No caller today: every adapter cancel wants the queued work invalidated
176
- * too and uses `cancelActiveAndPending`. Kept for a connector layer that
177
- * needs to stop only what is on the wire and leave the queue behind it.
178
- */
179
- cancelActive(deviceId, reason) {
128
+ /** Force cancel the active job. `reason` becomes signal.reason. */
129
+ forceCancelActive(deviceId, reason) {
180
130
  if (!this._active) return false;
181
131
  if (deviceId && this._active.deviceId !== deviceId) return false;
182
- this._active.abortController.abort(reason ?? new Error("Cancelled"));
132
+ this._active.abortController.abort(reason ?? new Error("Force cancelled for recovery"));
183
133
  return true;
184
134
  }
185
- /**
186
- * Cancel the active job and invalidate queued jobs that have not started.
187
- *
188
- * Only `undefined` means "everything". An empty string is a queue key that
189
- * derived to nothing, so it matches nothing and reports `false` rather than
190
- * silently tearing the whole queue down.
191
- *
192
- * Returns what the cancel actually reached, not whether it was accepted.
193
- */
135
+ /** Cancel the active job (alias for callers that previously needed multi-device cancel). */
136
+ cancelAllActive(reason) {
137
+ if (!this._active) return;
138
+ this._active.abortController.abort(reason ?? new Error("Cancelled by cancelAllActive"));
139
+ }
140
+ /** Cancel the active job and invalidate queued jobs that have not started. */
194
141
  cancelActiveAndPending(deviceId, reason) {
195
- const cancelReason = reason ?? new Error("Cancelled by cancelActiveAndPending");
196
- if (deviceId !== void 0) {
197
- let cancelled = false;
198
- for (const job of this._jobs.values()) {
199
- if (job.deviceId === deviceId) {
200
- job.abortController.abort(cancelReason);
201
- cancelled = true;
202
- }
203
- }
204
- for (const scope of this._cancelScopes.values()) {
205
- if (scope.deviceId === deviceId) {
206
- scope.abortController.abort(cancelReason);
207
- cancelled = true;
208
- }
209
- }
210
- return cancelled;
142
+ if (deviceId && this._active && this._active.deviceId !== deviceId) {
143
+ return false;
211
144
  }
212
- const reached = this._active !== null || this._jobs.size > 0 || this._cancelScopes.size > 0;
213
- this.clear(cancelReason);
214
- return reached;
145
+ this.clear(reason ?? new Error("Cancelled by cancelActiveAndPending"));
146
+ return true;
215
147
  }
216
148
  /** Get info about the currently active job, or null if idle. */
217
149
  getActiveJob(deviceId) {
@@ -223,6 +155,10 @@ var DeviceJobQueue = class {
223
155
  startedAt: this._active.startedAt
224
156
  };
225
157
  }
158
+ /** True if any job is currently running. */
159
+ isBusy() {
160
+ return this._jobs.size > 0;
161
+ }
226
162
  clear(reason) {
227
163
  const cancelledGeneration = this._generation;
228
164
  this._generation++;
@@ -236,232 +172,9 @@ var DeviceJobQueue = class {
236
172
  if (this._active) {
237
173
  this._active.abortController.abort(cancelReason);
238
174
  }
239
- for (const scope of this._cancelScopes.values()) {
240
- scope.abortController.abort(cancelReason);
241
- }
242
- }
243
- };
244
-
245
- // src/utils/hardwareRuntimeId.ts
246
- import { bytesToHex as bytesToHex2, randomBytes } from "@noble/hashes/utils";
247
- var HARDWARE_RUNTIME_ID_PREFIX = "hwk:runtime";
248
- var RANDOM_ID_BYTES = 16;
249
- var RANDOM_ID_PATTERN = /^[0-9a-f]{32}$/;
250
- var KINDS = /* @__PURE__ */ new Set([
251
- "operation",
252
- "search-target",
253
- "link"
254
- ]);
255
- var VENDORS = /* @__PURE__ */ new Set(["trezor", "ledger", "keystone"]);
256
- function create(kind, vendor) {
257
- return `${HARDWARE_RUNTIME_ID_PREFIX}:${kind}:${vendor}:${bytesToHex2(
258
- randomBytes(RANDOM_ID_BYTES)
259
- )}`;
260
- }
261
- function createHardwareOperationId(vendor) {
262
- return create("operation", vendor);
263
- }
264
- function createHardwareSearchTargetId(vendor) {
265
- return create("search-target", vendor);
266
- }
267
- function createHardwareLinkId(vendor) {
268
- return create("link", vendor);
269
- }
270
- function hasHardwareRuntimeIdPrefix(value) {
271
- return typeof value === "string" && value.startsWith(`${HARDWARE_RUNTIME_ID_PREFIX}:`);
272
- }
273
- function parseHardwareRuntimeId(value) {
274
- if (!hasHardwareRuntimeIdPrefix(value)) return void 0;
275
- const parts = value.split(":");
276
- if (parts.length !== 5) return void 0;
277
- const [, , kind, vendor, nonce] = parts;
278
- if (!KINDS.has(kind) || !VENDORS.has(vendor) || !RANDOM_ID_PATTERN.test(nonce)) {
279
- return void 0;
280
- }
281
- return { kind, vendor };
282
- }
283
- function isHardwareOperationId(value) {
284
- return parseHardwareRuntimeId(value)?.kind === "operation";
285
- }
286
-
287
- // src/utils/OperationRegistry.ts
288
- var OPERATION_DEFAULT_TTL_MS = 6e5;
289
- var OperationRegistry = class {
290
- constructor(options) {
291
- this._active = /* @__PURE__ */ new Map();
292
- this._ended = /* @__PURE__ */ new Map();
293
- this._vendor = options.vendor;
294
- this._ttlMs = options.ttlMs ?? OPERATION_DEFAULT_TTL_MS;
295
- this._onEnded = options.onEnded;
296
- }
297
- create(params) {
298
- const now = Date.now();
299
- const operationId = createHardwareOperationId(this._vendor);
300
- const operation = {
301
- operationId,
302
- connectId: params.connectId,
303
- device: params.device,
304
- connectionType: params.connectionType,
305
- connectionKeys: Array.from(
306
- new Set(
307
- [params.searchTargetId, params.connectId, ...params.connectionKeys ?? []].filter(
308
- Boolean
309
- )
310
- )
311
- ),
312
- createdAt: now,
313
- lastActiveAt: now
314
- };
315
- const timer = this._createTimer(operationId);
316
- this._active.set(operationId, { ...operation, timer, retainCount: 0 });
317
- return operation;
318
- }
319
- resolve(operationId) {
320
- const active = this._active.get(operationId);
321
- if (!active) {
322
- const ended = this._ended.get(operationId);
323
- if (ended) {
324
- throw createHwkError({
325
- code: 10113 /* OperationEnded */,
326
- message: `Hardware operation has ended (${ended.reason})`,
327
- params: { operationId, reason: ended.reason }
328
- });
329
- }
330
- throw createHwkError({
331
- code: 10112 /* OperationNotFound */,
332
- message: "Hardware operation was not found",
333
- params: { operationId }
334
- });
335
- }
336
- if (active.timer) clearTimeout(active.timer);
337
- active.lastActiveAt = Date.now();
338
- active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
339
- return active;
340
- }
341
- /** Keep an operation alive while one device job is actively using it. */
342
- retain(operationId) {
343
- const active = this.resolve(operationId);
344
- if (active.timer) clearTimeout(active.timer);
345
- active.timer = void 0;
346
- active.retainCount += 1;
347
- let released = false;
348
- return () => {
349
- if (released) return;
350
- released = true;
351
- const current = this._active.get(operationId);
352
- if (!current) return;
353
- current.retainCount = Math.max(0, current.retainCount - 1);
354
- current.lastActiveAt = Date.now();
355
- if (current.retainCount === 0) {
356
- current.timer = this._createTimer(operationId);
357
- }
358
- };
359
- }
360
- /** Return active or tombstoned binding data without refreshing its TTL. */
361
- find(operationId) {
362
- return this._active.get(operationId) ?? this._ended.get(operationId)?.operation;
363
- }
364
- findActiveByConnectionKey(connectionKey) {
365
- if (!connectionKey) return void 0;
366
- return [...this._active.values()].find(
367
- (operation) => operation.connectionKeys.includes(connectionKey)
368
- );
369
- }
370
- /** Replace the live transport binding after the same target was reconnected. */
371
- rebind(operationId, params) {
372
- const active = this._active.get(operationId);
373
- if (!active) {
374
- this.resolve(operationId);
375
- throw new Error("Unreachable operation rebind");
376
- }
377
- if (active.timer) clearTimeout(active.timer);
378
- active.connectId = params.connectId;
379
- active.device = params.device;
380
- active.connectionType = params.connectionType;
381
- active.connectionKeys = Array.from(
382
- new Set([params.connectId, ...params.connectionKeys ?? []].filter(Boolean))
383
- );
384
- active.lastActiveAt = Date.now();
385
- active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
386
- return active;
387
- }
388
- end(operationId, reason) {
389
- const active = this._active.get(operationId);
390
- if (!active) return void 0;
391
- if (active.timer) clearTimeout(active.timer);
392
- this._active.delete(operationId);
393
- this._rememberEnded(active, reason);
394
- this._onEnded?.(active, reason);
395
- return active;
396
- }
397
- endByConnectionKey(connectionKey, reason, exceptOperationId) {
398
- if (!connectionKey) return;
399
- for (const operation of [...this._active.values()]) {
400
- if (operation.operationId === exceptOperationId) continue;
401
- if (operation.connectionKeys.includes(connectionKey)) {
402
- this.end(operation.operationId, reason);
403
- }
404
- }
405
- }
406
- endAll(reason, exceptOperationId) {
407
- for (const operationId of [...this._active.keys()]) {
408
- if (operationId === exceptOperationId) continue;
409
- this.end(operationId, reason);
410
- }
411
- }
412
- _createTimer(operationId) {
413
- const timer = setTimeout(() => {
414
- this.end(operationId, "timeout");
415
- }, this._ttlMs);
416
- timer.unref?.();
417
- return timer;
418
- }
419
- _rememberEnded(operation, reason) {
420
- this._ended.set(operation.operationId, { reason, operation });
421
- if (this._ended.size <= 100) return;
422
- const oldest = this._ended.keys().next().value;
423
- if (oldest) this._ended.delete(oldest);
424
175
  }
425
176
  };
426
177
 
427
- // src/utils/hardwareOperationTarget.ts
428
- function resolveHardwareOperationTarget(positionalTargetId, commonOperationId, expectedVendor) {
429
- const normalizedPositionalTargetId = positionalTargetId ?? void 0;
430
- const normalizedCommonOperationId = commonOperationId || void 0;
431
- const positionalOperationId = isHardwareOperationId(normalizedPositionalTargetId) ? normalizedPositionalTargetId : void 0;
432
- const parsedPositionalTarget = parseHardwareRuntimeId(normalizedPositionalTargetId);
433
- const parsedCommonOperation = parseHardwareRuntimeId(normalizedCommonOperationId);
434
- if (normalizedPositionalTargetId && hasHardwareRuntimeIdPrefix(normalizedPositionalTargetId) && !parsedPositionalTarget) {
435
- return failure(10002 /* InvalidParams */, "Invalid hardware operation target id");
436
- }
437
- if (parsedPositionalTarget?.kind === "link") {
438
- return failure(
439
- 10002 /* InvalidParams */,
440
- "Hardware transport link id cannot be used as an operation target"
441
- );
442
- }
443
- if (normalizedCommonOperationId && parsedCommonOperation?.kind !== "operation") {
444
- return failure(10002 /* InvalidParams */, "Invalid hardware operation id");
445
- }
446
- if (expectedVendor && (parsedPositionalTarget && parsedPositionalTarget.vendor !== expectedVendor || parsedCommonOperation && parsedCommonOperation.vendor !== expectedVendor)) {
447
- return failure(
448
- 10002 /* InvalidParams */,
449
- `Hardware operation does not belong to ${expectedVendor}`
450
- );
451
- }
452
- if (positionalOperationId && normalizedCommonOperationId && positionalOperationId !== normalizedCommonOperationId) {
453
- return failure(10002 /* InvalidParams */, "Conflicting hardware operation ids", {
454
- positionalOperationId,
455
- commonOperationId: normalizedCommonOperationId
456
- });
457
- }
458
- const operationId = normalizedCommonOperationId ?? positionalOperationId;
459
- return success({
460
- operationId,
461
- targetId: operationId ?? normalizedPositionalTargetId
462
- });
463
- }
464
-
465
178
  // src/types/connector.ts
466
179
  var EConnectorInteraction = /* @__PURE__ */ ((EConnectorInteraction2) => {
467
180
  EConnectorInteraction2["Searching"] = "searching";
@@ -477,7 +190,7 @@ function createBridgedConnector(vendor, connectionType, bridge) {
477
190
  return {
478
191
  connectionType,
479
192
  searchDevices: (options) => bridge.searchDevices({ vendor, options }),
480
- connect: (deviceId, options) => bridge.connect({ vendor, deviceId, ...options ? { options } : {} }),
193
+ connect: (deviceId) => bridge.connect({ vendor, deviceId }),
481
194
  disconnect: (sessionId) => bridge.disconnect({ vendor, sessionId }),
482
195
  call: (sessionId, method, callParams) => bridge.call({ vendor, sessionId, method, callParams }),
483
196
  cancel: (sessionId) => bridge.cancel({ vendor, sessionId }),
@@ -618,14 +331,10 @@ function createCombinedConnector(connectors) {
618
331
  });
619
332
  }
620
333
  const searchDevices = async (options = {}) => {
621
- const selectedConnectors = connectors.map((child, index) => ({ child, index })).filter(
622
- ({ child }) => !options.transportType || child.connectionType === options.transportType
623
- );
624
- if (!selectedConnectors.length) return [];
625
334
  const perConnector = [];
626
- await new Promise((resolve, reject) => {
335
+ await new Promise((resolve) => {
627
336
  let finished = false;
628
- let remaining = selectedConnectors.length;
337
+ let remaining = connectors.length;
629
338
  let settleTimer;
630
339
  const finish = () => {
631
340
  if (finished) return;
@@ -633,20 +342,19 @@ function createCombinedConnector(connectors) {
633
342
  if (settleTimer) clearTimeout(settleTimer);
634
343
  resolve();
635
344
  };
636
- selectedConnectors.forEach(({ child, index }) => {
637
- void child.searchDevices(options.purpose ? { purpose: options.purpose } : void 0).then(
345
+ connectors.forEach((child, index) => {
346
+ void child.searchDevices().then(
638
347
  (devices) => devices.map((device) => ({
639
348
  ...device,
640
349
  connectionType: device.connectionType ?? child.connectionType
641
350
  }))
642
- ).catch((error) => {
643
- if (options.transportType) {
644
- finished = true;
645
- if (settleTimer) clearTimeout(settleTimer);
646
- reject(error);
647
- }
648
- return [];
649
- }).then((devices) => {
351
+ ).catch(
352
+ () => (
353
+ // A transport that can't scan (powered off, unauthorized, absent)
354
+ // must not fail the whole fused search.
355
+ []
356
+ )
357
+ ).then((devices) => {
650
358
  remaining -= 1;
651
359
  if (!finished) {
652
360
  perConnector.push({ index, devices });
@@ -663,12 +371,7 @@ function createCombinedConnector(connectors) {
663
371
  });
664
372
  });
665
373
  perConnector.sort((a, b) => a.index - b.index);
666
- if (!options.transportType) deviceOwner.clear();
667
- else {
668
- for (const [id, owner] of deviceOwner) {
669
- if (owner.connectionType === options.transportType) deviceOwner.delete(id);
670
- }
671
- }
374
+ deviceOwner.clear();
672
375
  const merged = [];
673
376
  perConnector.forEach(({ index, devices }) => {
674
377
  for (const device of devices) {
@@ -678,11 +381,11 @@ function createCombinedConnector(connectors) {
678
381
  });
679
382
  return merged.sort((a, b) => rank(a) - rank(b));
680
383
  };
681
- const resolveOwner = async (deviceId, transportType) => {
682
- if (deviceId && deviceOwner.has(deviceId) && (!transportType || deviceOwner.get(deviceId)?.connectionType === transportType)) {
384
+ const resolveOwner = async (deviceId) => {
385
+ if (deviceId && deviceOwner.has(deviceId)) {
683
386
  return { owner: deviceOwner.get(deviceId), deviceId };
684
387
  }
685
- const devices = await searchDevices({ waitForAll: Boolean(deviceId), transportType });
388
+ const devices = await searchDevices({ waitForAll: Boolean(deviceId) });
686
389
  if (deviceId) {
687
390
  const owner = deviceOwner.get(deviceId);
688
391
  if (!owner)
@@ -693,14 +396,13 @@ function createCombinedConnector(connectors) {
693
396
  if (!first) throw combinedDeviceNotFoundError("Combined connector: no devices found");
694
397
  return { owner: deviceOwner.get(first.connectId), deviceId: first.connectId };
695
398
  };
696
- const connectByExplicitId = async (deviceId, transportType) => {
399
+ const connectByExplicitId = async (deviceId) => {
697
400
  const cachedOwner = deviceOwner.get(deviceId);
698
- if (cachedOwner && (!transportType || cachedOwner.connectionType === transportType)) {
401
+ if (cachedOwner) {
699
402
  return { session: await cachedOwner.connect(deviceId), owner: cachedOwner };
700
403
  }
701
404
  let lastError;
702
405
  for (const child of connectors) {
703
- if (transportType && child.connectionType !== transportType) continue;
704
406
  try {
705
407
  const session = await child.connect(deviceId);
706
408
  deviceOwner.set(deviceId, child);
@@ -722,15 +424,14 @@ function createCombinedConnector(connectors) {
722
424
  // Nominal value only — the per-device `connectionType` is authoritative
723
425
  // for a fused connector.
724
426
  connectionType: connectors[0].connectionType,
725
- availableTransports: [...new Set(connectors.map((child) => child.connectionType))],
726
- searchDevices: (options) => searchDevices(options),
727
- connect: async (deviceId, options) => {
427
+ searchDevices: (options) => searchDevices({ waitForAll: options?.waitForAll }),
428
+ connect: async (deviceId) => {
728
429
  let owner;
729
430
  let session;
730
431
  if (deviceId) {
731
- ({ session, owner } = await connectByExplicitId(deviceId, options?.transportType));
432
+ ({ session, owner } = await connectByExplicitId(deviceId));
732
433
  } else {
733
- const resolved = await resolveOwner(void 0, options?.transportType);
434
+ const resolved = await resolveOwner();
734
435
  owner = resolved.owner;
735
436
  session = await owner.connect(resolved.deviceId);
736
437
  }
@@ -836,148 +537,6 @@ var TypedEventEmitter = class {
836
537
  }
837
538
  };
838
539
 
839
- // src/utils/requestSaveDeviceBinding.ts
840
- async function requestSaveDeviceBinding(emitter, registry, binding, signal) {
841
- const type = UI_REQUEST.REQUEST_SAVE_DEVICE_BINDING;
842
- const declined = (reason) => {
843
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
844
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
845
- payload: { selectionRequestId: binding.selectionRequestId, status: "failed" }
846
- });
847
- return { saved: false, reason };
848
- };
849
- if (!emitter.listenerCount(type)) {
850
- return declined("skipped");
851
- }
852
- if (signal?.aborted) throw signal.reason;
853
- const requestId = registry.createRequestId();
854
- const pending = registry.wait(type, { requestId, operationId: binding.operationId });
855
- void pending.catch(() => void 0);
856
- const cancel = () => registry.cancel(type, requestId);
857
- signal?.addEventListener("abort", cancel, { once: true });
858
- try {
859
- emitter.emit(type, { type, payload: { ...binding, requestId } });
860
- const response = await pending;
861
- if (signal?.aborted) throw signal.reason;
862
- if (response?.saved !== true) {
863
- return declined(response?.reason ?? "skipped");
864
- }
865
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
866
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
867
- payload: { selectionRequestId: binding.selectionRequestId, status: "saved" }
868
- });
869
- return { saved: true };
870
- } catch (error) {
871
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
872
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
873
- payload: {
874
- selectionRequestId: binding.selectionRequestId,
875
- status: signal?.aborted ? "cancelled" : "failed"
876
- }
877
- });
878
- if (signal?.aborted) throw error;
879
- return { saved: false, reason: "skipped" };
880
- } finally {
881
- signal?.removeEventListener("abort", cancel);
882
- registry.cancel(type, requestId);
883
- }
884
- }
885
-
886
- // src/utils/requestBleDeviceSelection.ts
887
- async function requestBleDeviceSelection({
888
- emitter,
889
- registry,
890
- request,
891
- scan,
892
- signal,
893
- allowUsbFallback = false,
894
- pollIntervalMs = 1500
895
- }) {
896
- const type = UI_REQUEST.REQUEST_SELECT_DEVICE;
897
- if (signal.aborted) throw signal.reason;
898
- if (!emitter.listenerCount(type)) {
899
- throw createHwkError({
900
- code: 10100 /* DeviceNotFound */,
901
- message: "Select a Bluetooth device before continuing"
902
- });
903
- }
904
- const requestId = registry.createRequestId();
905
- const { operationId } = request;
906
- let devices = allowUsbFallback ? request.devices.filter((device) => device.connectionType === "ble") : request.devices;
907
- const publishedDevices = /* @__PURE__ */ new Map();
908
- let stopped = false;
909
- let timer;
910
- let wake;
911
- const stop = () => {
912
- stopped = true;
913
- if (timer !== void 0) clearTimeout(timer);
914
- wake?.();
915
- };
916
- const waitForNextScan = () => new Promise((resolve) => {
917
- wake = resolve;
918
- timer = setTimeout(resolve, pollIntervalMs);
919
- if (stopped) resolve();
920
- });
921
- const cancel = () => registry.cancel(type, requestId);
922
- const reply = registry.wait(type, { requestId, operationId }).finally(stop);
923
- void reply.catch(() => void 0);
924
- const publish = () => {
925
- for (const device of devices) publishedDevices.set(device.connectId, device);
926
- emitter.emit(type, {
927
- type,
928
- payload: { ...request, devices, requestId, scanning: true }
929
- });
930
- };
931
- signal.addEventListener("abort", cancel, { once: true });
932
- let polling;
933
- try {
934
- publish();
935
- polling = (async () => {
936
- await Promise.resolve();
937
- while (!stopped) {
938
- const snapshot = await scan();
939
- if (stopped || signal.aborted) return;
940
- const usbFallback = allowUsbFallback ? snapshot.find((device2) => device2.connectionType === "usb") : void 0;
941
- if (usbFallback) return usbFallback;
942
- devices = snapshot;
943
- publish();
944
- if (stopped) return;
945
- await waitForNextScan();
946
- }
947
- })();
948
- const userSelection = reply.then((selected) => publishedDevices.get(selected.sdkConnectId));
949
- const device = await Promise.race([
950
- userSelection,
951
- polling.then((usbFallback) => usbFallback ?? userSelection)
952
- ]);
953
- stop();
954
- await polling;
955
- if (signal.aborted) throw signal.reason;
956
- if (!device) {
957
- throw createHwkError({
958
- code: 10100 /* DeviceNotFound */,
959
- message: "Selected Bluetooth device is no longer available"
960
- });
961
- }
962
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
963
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
964
- payload: { selectionRequestId: requestId, status: "verifying" }
965
- });
966
- return { device, requestId };
967
- } catch (error) {
968
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
969
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
970
- payload: { selectionRequestId: requestId, status: signal.aborted ? "cancelled" : "failed" }
971
- });
972
- throw error;
973
- } finally {
974
- stop();
975
- signal.removeEventListener("abort", cancel);
976
- registry.cancel(type, requestId);
977
- await polling?.catch(() => void 0);
978
- }
979
- }
980
-
981
540
  // src/utils/semver.ts
982
541
  function compareSemver(a, b) {
983
542
  const pa = a.split(".").map(Number);
@@ -1005,96 +564,14 @@ function padHex64(hex) {
1005
564
  function hexToBytes(hex) {
1006
565
  return nobleHexToBytes(stripHex(hex));
1007
566
  }
1008
- function bytesToHex3(bytes) {
567
+ function bytesToHex2(bytes) {
1009
568
  return nobleBytesToHex(bytes);
1010
569
  }
1011
570
 
1012
- // src/utils/solanaOffchainMessage.ts
1013
- var SOLANA_OFFCHAIN_SIGNING_DOMAIN = Uint8Array.of(
1014
- 255,
1015
- ...Array.from("solana offchain", (character) => character.charCodeAt(0))
1016
- );
1017
- var SOLANA_PUBLIC_KEY_LENGTH = 32;
1018
- var MAX_SOLANA_OFFCHAIN_SIGNERS = 255;
1019
- function compareBytes(a, b) {
1020
- for (let index = 0; index < a.length; index += 1) {
1021
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
1022
- if (difference !== 0) return difference;
1023
- }
1024
- return a.length - b.length;
1025
- }
1026
- function bytesEqual(a, b) {
1027
- return a.length === b.length && a.every((value, index) => value === b[index]);
1028
- }
1029
- function decodeUtf8Strict(bytes) {
1030
- let encoded = "";
1031
- for (const value of bytes) {
1032
- encoded += `%${value.toString(16).padStart(2, "0")}`;
1033
- }
1034
- return decodeURIComponent(encoded);
1035
- }
1036
- function prepareSolanaOffchainMessageV1({
1037
- message,
1038
- requiredSigners
1039
- }) {
1040
- if (message.length === 0) {
1041
- throw new Error("Solana off-chain message cannot be empty");
1042
- }
1043
- if (requiredSigners.length === 0 || requiredSigners.length > MAX_SOLANA_OFFCHAIN_SIGNERS) {
1044
- throw new Error("Solana off-chain message requires between 1 and 255 signers");
1045
- }
1046
- let messageText;
1047
- try {
1048
- messageText = decodeUtf8Strict(message);
1049
- } catch {
1050
- throw new Error("Solana off-chain message must contain valid UTF-8");
1051
- }
1052
- const signerBytes = requiredSigners.map((signer, index) => {
1053
- let bytes;
1054
- try {
1055
- bytes = hexToBytes(signer);
1056
- } catch {
1057
- throw new Error(`Solana off-chain signer ${index} must be a hex public key`);
1058
- }
1059
- if (bytes.length !== SOLANA_PUBLIC_KEY_LENGTH) {
1060
- throw new Error(`Solana off-chain signer ${index} must be 32 bytes`);
1061
- }
1062
- return bytes;
1063
- });
1064
- signerBytes.sort(compareBytes);
1065
- for (let index = 1; index < signerBytes.length; index += 1) {
1066
- if (bytesEqual(signerBytes[index - 1], signerBytes[index])) {
1067
- throw new Error("Solana off-chain signers must be unique");
1068
- }
1069
- }
1070
- const serializedMessage = new Uint8Array(
1071
- SOLANA_OFFCHAIN_SIGNING_DOMAIN.length + 2 + signerBytes.length * SOLANA_PUBLIC_KEY_LENGTH + message.length
1072
- );
1073
- let offset = 0;
1074
- serializedMessage.set(SOLANA_OFFCHAIN_SIGNING_DOMAIN, offset);
1075
- offset += SOLANA_OFFCHAIN_SIGNING_DOMAIN.length;
1076
- serializedMessage[offset] = 1;
1077
- offset += 1;
1078
- serializedMessage[offset] = signerBytes.length;
1079
- offset += 1;
1080
- for (const signer of signerBytes) {
1081
- serializedMessage.set(signer, offset);
1082
- offset += SOLANA_PUBLIC_KEY_LENGTH;
1083
- }
1084
- serializedMessage.set(message, offset);
1085
- return {
1086
- messageText,
1087
- requiredSigners: signerBytes.map(bytesToHex3),
1088
- serializedMessage
1089
- };
1090
- }
1091
-
1092
571
  // src/utils/deviceIdentity.ts
1093
572
  var ONEKEY_BLE_SERVICE_UUID = "00000001-0000-1000-8000-00805f9b34fb";
1094
573
  var TREZOR_BLE_SERVICE_UUID = "8c000001-a59b-4d58-a9ad-073df69fa1b1";
1095
574
  var LEDGER_USB_VENDOR_ID = 11415;
1096
- var KEYSTONE_USB_VENDOR_ID = 4617;
1097
- var KEYSTONE_USB_PRODUCT_ID = 12289;
1098
575
  var lower = (value) => value?.trim().toLowerCase() ?? "";
1099
576
  var hasServiceUuid = (input, uuid) => {
1100
577
  const expected = uuid.toLowerCase();
@@ -1117,11 +594,6 @@ function detectHardwareVendorFromDescriptor(input) {
1117
594
  if (typeof input.vendor === "number" && input.vendor === LEDGER_USB_VENDOR_ID || input.vendorId === LEDGER_USB_VENDOR_ID || manufacturerName.includes("ledger")) {
1118
595
  return "ledger";
1119
596
  }
1120
- const usbVendorId = typeof input.vendor === "number" ? input.vendor : input.vendorId;
1121
- const usbProductId = typeof input.product === "number" ? input.product : input.productId;
1122
- if (usbVendorId === KEYSTONE_USB_VENDOR_ID && usbProductId === KEYSTONE_USB_PRODUCT_ID || manufacturerName.includes("keystone")) {
1123
- return "keystone";
1124
- }
1125
597
  return void 0;
1126
598
  }
1127
599
  function isKnownNonTargetHardwareVendor(input, targetVendor) {
@@ -1145,62 +617,28 @@ async function batchCall(params, callFn, onProgress) {
1145
617
 
1146
618
  // src/utils/methodCatalog.ts
1147
619
  var HARDWARE_METHOD_CATALOG = {
1148
- evmGetAddress: { chain: "evm", allNetwork: true, replayAfterTransportFailure: "safe" },
1149
- evmSignTransaction: {
1150
- chain: "evm",
1151
- allNetwork: false,
1152
- replayAfterTransportFailure: "unsafe"
1153
- },
1154
- evmSignMessage: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1155
- evmSignTypedData: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1156
- btcGetAddress: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1157
- btcGetPublicKey: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1158
- btcSignTransaction: {
1159
- chain: "btc",
1160
- allNetwork: false,
1161
- replayAfterTransportFailure: "unsafe"
1162
- },
1163
- btcSignPsbt: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1164
- btcSignMessage: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1165
- btcGetMasterFingerprint: {
1166
- chain: "btc",
1167
- allNetwork: false,
1168
- replayAfterTransportFailure: "safe"
1169
- },
1170
- solGetAddress: { chain: "sol", allNetwork: true, replayAfterTransportFailure: "safe" },
1171
- solSignTransaction: {
1172
- chain: "sol",
1173
- allNetwork: false,
1174
- replayAfterTransportFailure: "unsafe"
1175
- },
1176
- solSignMessage: { chain: "sol", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1177
- tronGetAddress: { chain: "tron", allNetwork: true, replayAfterTransportFailure: "safe" },
1178
- tronSignTransaction: {
1179
- chain: "tron",
1180
- allNetwork: false,
1181
- replayAfterTransportFailure: "unsafe"
1182
- },
1183
- tronSignMessage: { chain: "tron", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1184
- zcashGetFullViewingKey: {
1185
- chain: "zcash",
1186
- allNetwork: false,
1187
- replayAfterTransportFailure: "safe"
1188
- },
1189
- zcashGetShieldedAddress: {
1190
- chain: "zcash",
1191
- allNetwork: false,
1192
- replayAfterTransportFailure: "safe"
1193
- }
620
+ evmGetAddress: { chain: "evm", allNetwork: true },
621
+ evmSignTransaction: { chain: "evm", allNetwork: false },
622
+ evmSignMessage: { chain: "evm", allNetwork: false },
623
+ evmSignTypedData: { chain: "evm", allNetwork: false },
624
+ btcGetAddress: { chain: "btc", allNetwork: true },
625
+ btcGetPublicKey: { chain: "btc", allNetwork: true },
626
+ btcSignTransaction: { chain: "btc", allNetwork: false },
627
+ btcSignPsbt: { chain: "btc", allNetwork: false },
628
+ btcSignMessage: { chain: "btc", allNetwork: false },
629
+ btcGetMasterFingerprint: { chain: "btc", allNetwork: false },
630
+ solGetAddress: { chain: "sol", allNetwork: true },
631
+ solSignTransaction: { chain: "sol", allNetwork: false },
632
+ solSignMessage: { chain: "sol", allNetwork: false },
633
+ tronGetAddress: { chain: "tron", allNetwork: true },
634
+ tronSignTransaction: { chain: "tron", allNetwork: false },
635
+ tronSignMessage: { chain: "tron", allNetwork: false }
1194
636
  };
1195
637
  var ALL_NETWORK_METHOD_NAMES = Object.entries(HARDWARE_METHOD_CATALOG).filter(([, metadata]) => metadata.allNetwork).map(([method]) => method);
1196
638
  var ALL_NETWORK_METHOD_SET = new Set(ALL_NETWORK_METHOD_NAMES);
1197
639
  function getHardwareMethodMetadata(method) {
1198
640
  return HARDWARE_METHOD_CATALOG[method];
1199
641
  }
1200
- var SAFE_NON_CHAIN_METHODS = /* @__PURE__ */ new Set(["getFeatures", "authenticateDevice"]);
1201
- function canReplayHardwareMethodAfterTransportFailure(method) {
1202
- return getHardwareMethodMetadata(method)?.replayAfterTransportFailure === "safe" || SAFE_NON_CHAIN_METHODS.has(method);
1203
- }
1204
642
  function isAllNetworkMethodName(method) {
1205
643
  return ALL_NETWORK_METHOD_SET.has(method);
1206
644
  }
@@ -1260,19 +698,6 @@ async function runAllNetworkGetAddress({
1260
698
  }
1261
699
  return success(responses);
1262
700
  }
1263
- function isUserRefusal(code) {
1264
- return code === 10005 /* UserAborted */ || code === 10001 /* UserRejected */;
1265
- }
1266
- function isConnectionLost(code) {
1267
- const codes = [
1268
- 10101 /* DeviceDisconnected */,
1269
- 10003 /* OperationTimeout */,
1270
- 10300 /* TransportError */,
1271
- 10113 /* OperationEnded */,
1272
- 10112 /* OperationNotFound */
1273
- ];
1274
- return code !== void 0 && codes.includes(code);
1275
- }
1276
701
  function buildUnsupportedMethodResponse(item) {
1277
702
  return {
1278
703
  ...item,
@@ -1306,11 +731,8 @@ export {
1306
731
  DeviceJobQueue,
1307
732
  EConnectorInteraction,
1308
733
  HARDWARE_METHOD_CATALOG,
1309
- HARDWARE_RUNTIME_ID_PREFIX,
1310
734
  HardwareErrorCode,
1311
- OPERATION_DEFAULT_TTL_MS,
1312
735
  ORPHAN_ELIGIBLE_ERROR_CODES,
1313
- OperationRegistry,
1314
736
  SDK,
1315
737
  TypedEventEmitter,
1316
738
  UI_EVENT,
@@ -1323,43 +745,23 @@ export {
1323
745
  UiRequestRegistry,
1324
746
  batchCall,
1325
747
  buildUnsupportedMethodResponse,
1326
- bytesToHex3 as bytesToHex,
1327
- canReplayHardwareMethodAfterTransportFailure,
748
+ bytesToHex2 as bytesToHex,
1328
749
  compareSemver,
1329
750
  createBridgedConnector,
1330
751
  createCombinedConnector,
1331
- createHardwareLinkId,
1332
- createHardwareOperationId,
1333
- createHardwareSearchTargetId,
1334
752
  createHwkError,
1335
- defaultOriginForCode,
1336
- defaultRecoveryForCode,
1337
753
  deriveDeviceFingerprint,
1338
- deriveWalletId,
1339
754
  detectHardwareVendorFromDescriptor,
1340
755
  enrichErrorMessage,
1341
756
  ensure0x,
1342
757
  failure,
1343
758
  getAllNetworkMethodChain,
1344
759
  getHardwareMethodMetadata,
1345
- hasHardwareRuntimeIdPrefix,
1346
760
  hexToBytes,
1347
761
  isAllNetworkMethodName,
1348
- isConnectionLost,
1349
- isHardwareOperationId,
1350
- isHwkRecoveryHint,
1351
762
  isKnownNonTargetHardwareVendor,
1352
- isUserRefusal,
1353
- operationMayHaveCompletedParams,
1354
763
  padHex64,
1355
- parseBip32MasterFingerprint,
1356
- parseHardwareRuntimeId,
1357
- prepareSolanaOffchainMessageV1,
1358
764
  rehydrateConnectorError,
1359
- requestBleDeviceSelection,
1360
- requestSaveDeviceBinding,
1361
- resolveHardwareOperationTarget,
1362
- resolveSearchTargetReusePolicy,
1363
765
  runAllNetworkGetAddress,
1364
766
  serializeConnectorError,
1365
767
  stripHex,