@onekeyfe/hwk-adapter-core 1.2.5-alpha.2 → 1.2.5-alpha.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-H7BZ2C6J.js → chunk-BAGEFFFY.js} +13 -45
  2. package/dist/chunk-BAGEFFFY.js.map +1 -0
  3. package/dist/{chunk-T5HIQPNG.js → chunk-SZZF623R.js} +55 -155
  4. package/dist/chunk-SZZF623R.js.map +1 -0
  5. package/dist/{chunk-AYA6FQES.mjs → chunk-U63HTLGJ.mjs} +12 -44
  6. package/dist/chunk-U63HTLGJ.mjs.map +1 -0
  7. package/dist/{chunk-KTRQZ5AJ.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 +104 -578
  15. package/dist/index.d.ts +104 -578
  16. package/dist/index.js +85 -635
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +76 -626
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{ui-events-DdttFKj9.d.ts → ui-events-Cb7haAeE.d.mts} +3 -37
  21. package/dist/{ui-events-DdttFKj9.d.mts → ui-events-Cb7haAeE.d.ts} +3 -37
  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-AYA6FQES.mjs.map +0 -1
  29. package/dist/chunk-DB4JOPZO.mjs +0 -74
  30. package/dist/chunk-DB4JOPZO.mjs.map +0 -1
  31. package/dist/chunk-H7BZ2C6J.js.map +0 -1
  32. package/dist/chunk-KTRQZ5AJ.mjs.map +0 -1
  33. package/dist/chunk-T5HIQPNG.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-BgJ4kzRx.d.mts +0 -276
  37. package/dist/errors-BgJ4kzRx.d.ts +0 -276
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,39 +13,19 @@ import {
10
13
  UI_REQUEST_TIMEOUT_TAG,
11
14
  UI_RESPONSE,
12
15
  UiRequestRegistry
13
- } from "./chunk-AYA6FQES.mjs";
14
- import {
15
- HardwareErrorCode,
16
- ORPHAN_ELIGIBLE_ERROR_CODES,
17
- createHwkError,
18
- defaultOriginForCode,
19
- defaultRecoveryForCode,
20
- isHwkRecoveryHint,
21
- operationMayHaveCompletedParams
22
- } from "./chunk-KTRQZ5AJ.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
- return device.capabilities?.persistentDeviceIdentity ? "reconnectable" : "current-discovery";
44
- }
45
-
46
29
  // src/types/fingerprint.ts
47
30
  import { sha256 } from "@noble/hashes/sha256";
48
31
  import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils";
@@ -52,21 +35,11 @@ var CHAIN_FINGERPRINT_PATHS = {
52
35
  // Cointype 1 (testnet) is rejected by some Ledger BTC App configurations.
53
36
  btc: "m/44'/0'/0'",
54
37
  sol: "m/44'/501'/0'",
55
- tron: "m/44'/195'/0'/0/0",
56
- // Shielded UA (single Orchard receiver) derived from the transparent path.
57
- zcash: "m/44'/133'/0'/0/0"
38
+ tron: "m/44'/195'/0'/0/0"
58
39
  };
59
- function parseBip32MasterFingerprint(value) {
60
- if (typeof value !== "string") return void 0;
61
- const normalized = value.trim().toLowerCase();
62
- return /^[0-9a-f]{8}$/.test(normalized) ? normalized : void 0;
63
- }
64
40
  function deriveDeviceFingerprint(value) {
65
41
  return bytesToHex(sha256(utf8ToBytes(value))).slice(0, 16);
66
42
  }
67
- function deriveWalletId(canonicalPublicMaterial) {
68
- return bytesToHex(sha256(utf8ToBytes(`onekey-hwk-wallet-id:v1:${canonicalPublicMaterial}`)));
69
- }
70
43
 
71
44
  // src/events/device.ts
72
45
  var DEVICE_EVENT = "DEVICE_EVENT";
@@ -93,8 +66,7 @@ var SDK = {
93
66
  DEVICE_STUCK: "device-stuck",
94
67
  DEVICE_UNRESPONSIVE: "device-unresponsive",
95
68
  DEVICE_RECOVERED: "device-recovered",
96
- DEVICE_INTERACTION: "device-interaction",
97
- OPERATION_ENDED: "operation-ended"
69
+ DEVICE_INTERACTION: "device-interaction"
98
70
  };
99
71
 
100
72
  // src/utils/DeviceJobQueue.ts
@@ -103,7 +75,6 @@ var DeviceJobQueue = class {
103
75
  this._tail = Promise.resolve();
104
76
  this._active = null;
105
77
  this._jobs = /* @__PURE__ */ new Map();
106
- this._cancelScopes = /* @__PURE__ */ new Map();
107
78
  /** Incremented on clear() so queued-but-not-yet-running jobs detect invalidation. */
108
79
  this._generation = 0;
109
80
  this._generationCancelReasons = /* @__PURE__ */ new Map();
@@ -126,13 +97,12 @@ var DeviceJobQueue = class {
126
97
  abortController: ac,
127
98
  startedAt: Date.now()
128
99
  };
129
- this._jobs.set(jobToken, activeJob);
100
+ this._jobs.set(jobToken, { deviceId });
130
101
  const next = prev.catch(() => {
131
102
  }).then(async () => {
132
103
  if (this._generation !== gen) {
133
104
  throw this._generationCancelReasons.get(gen) ?? new Error("Job cancelled: queue was cleared");
134
105
  }
135
- if (ac.signal.aborted) throw ac.signal.reason;
136
106
  this._active = activeJob;
137
107
  try {
138
108
  return await job(ac.signal);
@@ -148,52 +118,32 @@ var DeviceJobQueue = class {
148
118
  });
149
119
  return next;
150
120
  }
151
- /**
152
- * Holds a cancel across the gaps between a bundle's per-item jobs, when the queue is empty.
153
- * Callers must `release()` when the bundle ends.
154
- */
155
- createCancelScope(deviceId) {
156
- const scopeToken = {};
157
- const abortController = new AbortController();
158
- this._cancelScopes.set(scopeToken, { deviceId, abortController });
159
- return {
160
- signal: abortController.signal,
161
- release: () => {
162
- this._cancelScopes.delete(scopeToken);
163
- }
164
- };
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;
165
127
  }
166
- /**
167
- * Cancels the running job only; `reason` becomes signal.reason. Adapters use
168
- * `cancelActiveAndPending`; this stays for a connector layer that stops only what is on the wire.
169
- */
170
- cancelActive(deviceId, reason) {
128
+ /** Force cancel the active job. `reason` becomes signal.reason. */
129
+ forceCancelActive(deviceId, reason) {
171
130
  if (!this._active) return false;
172
131
  if (deviceId && this._active.deviceId !== deviceId) return false;
173
- this._active.abortController.abort(reason ?? new Error("Cancelled"));
132
+ this._active.abortController.abort(reason ?? new Error("Force cancelled for recovery"));
174
133
  return true;
175
134
  }
176
- /**
177
- * Cancels the active job and unstarted queued jobs; returns whether anything was reached. Only
178
- * `undefined` means everything: an empty key matches nothing instead of tearing the queue down.
179
- */
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. */
180
141
  cancelActiveAndPending(deviceId, reason) {
181
- const cancelReason = reason ?? new Error("Cancelled by cancelActiveAndPending");
182
- if (deviceId !== void 0) {
183
- let cancelled = false;
184
- const targets = [this._jobs, this._cancelScopes];
185
- for (const map of targets) {
186
- for (const target of map.values()) {
187
- if (target.deviceId !== deviceId) continue;
188
- target.abortController.abort(cancelReason);
189
- cancelled = true;
190
- }
191
- }
192
- return cancelled;
142
+ if (deviceId && this._active && this._active.deviceId !== deviceId) {
143
+ return false;
193
144
  }
194
- const reached = this._active !== null || this._jobs.size > 0 || this._cancelScopes.size > 0;
195
- this.clear(cancelReason);
196
- return reached;
145
+ this.clear(reason ?? new Error("Cancelled by cancelActiveAndPending"));
146
+ return true;
197
147
  }
198
148
  /** Get info about the currently active job, or null if idle. */
199
149
  getActiveJob(deviceId) {
@@ -205,6 +155,10 @@ var DeviceJobQueue = class {
205
155
  startedAt: this._active.startedAt
206
156
  };
207
157
  }
158
+ /** True if any job is currently running. */
159
+ isBusy() {
160
+ return this._jobs.size > 0;
161
+ }
208
162
  clear(reason) {
209
163
  const cancelledGeneration = this._generation;
210
164
  this._generation++;
@@ -218,219 +172,9 @@ var DeviceJobQueue = class {
218
172
  if (this._active) {
219
173
  this._active.abortController.abort(cancelReason);
220
174
  }
221
- for (const scope of this._cancelScopes.values()) {
222
- scope.abortController.abort(cancelReason);
223
- }
224
- }
225
- };
226
-
227
- // src/utils/hardwareRuntimeId.ts
228
- import { bytesToHex as bytesToHex2, randomBytes } from "@noble/hashes/utils";
229
- var HARDWARE_RUNTIME_ID_PREFIX = "hwk:runtime";
230
- var RANDOM_ID_BYTES = 16;
231
- var RANDOM_ID_PATTERN = /^[0-9a-f]{32}$/;
232
- var KINDS = /* @__PURE__ */ new Set([
233
- "operation",
234
- "search-target",
235
- "link"
236
- ]);
237
- var VENDORS = /* @__PURE__ */ new Set(["trezor", "ledger", "keystone"]);
238
- function create(kind, vendor) {
239
- return `${HARDWARE_RUNTIME_ID_PREFIX}:${kind}:${vendor}:${bytesToHex2(
240
- randomBytes(RANDOM_ID_BYTES)
241
- )}`;
242
- }
243
- function createHardwareOperationId(vendor) {
244
- return create("operation", vendor);
245
- }
246
- function createHardwareSearchTargetId(vendor) {
247
- return create("search-target", vendor);
248
- }
249
- function createHardwareLinkId(vendor) {
250
- return create("link", vendor);
251
- }
252
- function hasHardwareRuntimeIdPrefix(value) {
253
- return typeof value === "string" && value.startsWith(`${HARDWARE_RUNTIME_ID_PREFIX}:`);
254
- }
255
- function parseHardwareRuntimeId(value) {
256
- if (!hasHardwareRuntimeIdPrefix(value)) return void 0;
257
- const parts = value.split(":");
258
- if (parts.length !== 5) return void 0;
259
- const [, , kind, vendor, nonce] = parts;
260
- if (!KINDS.has(kind) || !VENDORS.has(vendor) || !RANDOM_ID_PATTERN.test(nonce)) {
261
- return void 0;
262
- }
263
- return { kind, vendor };
264
- }
265
- function isHardwareOperationId(value) {
266
- return parseHardwareRuntimeId(value)?.kind === "operation";
267
- }
268
-
269
- // src/utils/OperationRegistry.ts
270
- var OPERATION_DEFAULT_TTL_MS = 6e5;
271
- var uniqueKeys = (keys) => Array.from(new Set(keys.filter(Boolean)));
272
- var OperationRegistry = class {
273
- constructor(options) {
274
- this._active = /* @__PURE__ */ new Map();
275
- this._ended = /* @__PURE__ */ new Map();
276
- this._vendor = options.vendor;
277
- this._ttlMs = options.ttlMs ?? OPERATION_DEFAULT_TTL_MS;
278
- this._onEnded = options.onEnded;
279
- }
280
- create(params) {
281
- const now = Date.now();
282
- const operationId = createHardwareOperationId(this._vendor);
283
- const operation = {
284
- operationId,
285
- connectId: params.connectId,
286
- device: params.device,
287
- connectionType: params.connectionType,
288
- connectionKeys: uniqueKeys([
289
- params.searchTargetId,
290
- params.connectId,
291
- ...params.connectionKeys ?? []
292
- ]),
293
- createdAt: now,
294
- lastActiveAt: now
295
- };
296
- const timer = this._createTimer(operationId);
297
- this._active.set(operationId, { ...operation, timer, retainCount: 0 });
298
- return operation;
299
- }
300
- resolve(operationId) {
301
- const active = this._active.get(operationId);
302
- if (!active) {
303
- const ended = this._ended.get(operationId);
304
- if (ended) {
305
- throw createHwkError({
306
- code: 10113 /* OperationEnded */,
307
- message: `Hardware operation has ended (${ended.reason})`,
308
- params: { operationId, reason: ended.reason }
309
- });
310
- }
311
- throw createHwkError({
312
- code: 10112 /* OperationNotFound */,
313
- message: "Hardware operation was not found",
314
- params: { operationId }
315
- });
316
- }
317
- this._touch(active);
318
- return active;
319
- }
320
- /** Keep an operation alive while one device job is actively using it. */
321
- retain(operationId) {
322
- const active = this.resolve(operationId);
323
- active.retainCount += 1;
324
- this._touch(active);
325
- let released = false;
326
- return () => {
327
- if (released) return;
328
- released = true;
329
- const current = this._active.get(operationId);
330
- if (!current) return;
331
- current.retainCount = Math.max(0, current.retainCount - 1);
332
- this._touch(current);
333
- };
334
- }
335
- /** Return active or tombstoned binding data without refreshing its TTL. */
336
- find(operationId) {
337
- return this._active.get(operationId) ?? this._ended.get(operationId)?.operation;
338
- }
339
- findActiveByConnectionKey(connectionKey) {
340
- if (!connectionKey) return void 0;
341
- return [...this._active.values()].find(
342
- (operation) => operation.connectionKeys.includes(connectionKey)
343
- );
344
- }
345
- /** Replace the live transport binding after the same target was reconnected. */
346
- rebind(operationId, params) {
347
- const active = this.resolve(operationId);
348
- active.connectId = params.connectId;
349
- active.device = params.device;
350
- active.connectionType = params.connectionType;
351
- active.connectionKeys = uniqueKeys([params.connectId, ...params.connectionKeys ?? []]);
352
- this._touch(active);
353
- return active;
354
- }
355
- end(operationId, reason) {
356
- const active = this._active.get(operationId);
357
- if (!active) return void 0;
358
- if (active.timer) clearTimeout(active.timer);
359
- this._active.delete(operationId);
360
- this._rememberEnded(active, reason);
361
- this._onEnded?.(active, reason);
362
- return active;
363
- }
364
- endByConnectionKey(connectionKey, reason, exceptOperationId) {
365
- if (!connectionKey) return;
366
- for (const operation of [...this._active.values()]) {
367
- if (operation.operationId === exceptOperationId) continue;
368
- if (operation.connectionKeys.includes(connectionKey)) {
369
- this.end(operation.operationId, reason);
370
- }
371
- }
372
- }
373
- endAll(reason, exceptOperationId) {
374
- for (const operationId of [...this._active.keys()]) {
375
- if (operationId === exceptOperationId) continue;
376
- this.end(operationId, reason);
377
- }
378
- }
379
- _touch(active) {
380
- if (active.timer) clearTimeout(active.timer);
381
- active.lastActiveAt = Date.now();
382
- active.timer = active.retainCount === 0 ? this._createTimer(active.operationId) : void 0;
383
- }
384
- _createTimer(operationId) {
385
- const timer = setTimeout(() => {
386
- this.end(operationId, "timeout");
387
- }, this._ttlMs);
388
- timer.unref?.();
389
- return timer;
390
- }
391
- _rememberEnded(operation, reason) {
392
- this._ended.set(operation.operationId, { reason, operation });
393
- if (this._ended.size <= 100) return;
394
- const oldest = this._ended.keys().next().value;
395
- if (oldest) this._ended.delete(oldest);
396
175
  }
397
176
  };
398
177
 
399
- // src/utils/hardwareOperationTarget.ts
400
- function resolveHardwareOperationTarget(positionalTargetId, commonOperationId, expectedVendor) {
401
- const targetId = positionalTargetId ?? void 0;
402
- const commonId = commonOperationId || void 0;
403
- const parsedTarget = parseHardwareRuntimeId(targetId);
404
- const parsedCommon = parseHardwareRuntimeId(commonId);
405
- const positionalOperationId = parsedTarget?.kind === "operation" ? targetId : void 0;
406
- if (hasHardwareRuntimeIdPrefix(targetId) && !parsedTarget) {
407
- return failure(10002 /* InvalidParams */, "Invalid hardware operation target id");
408
- }
409
- if (parsedTarget?.kind === "link") {
410
- return failure(
411
- 10002 /* InvalidParams */,
412
- "Hardware transport link id cannot be used as an operation target"
413
- );
414
- }
415
- if (commonId && parsedCommon?.kind !== "operation") {
416
- return failure(10002 /* InvalidParams */, "Invalid hardware operation id");
417
- }
418
- if (expectedVendor && [parsedTarget, parsedCommon].some((parsed) => parsed && parsed.vendor !== expectedVendor)) {
419
- return failure(
420
- 10002 /* InvalidParams */,
421
- `Hardware operation does not belong to ${expectedVendor}`
422
- );
423
- }
424
- if (positionalOperationId && commonId && positionalOperationId !== commonId) {
425
- return failure(10002 /* InvalidParams */, "Conflicting hardware operation ids", {
426
- positionalOperationId,
427
- commonOperationId: commonId
428
- });
429
- }
430
- const operationId = commonId ?? positionalOperationId;
431
- return success({ operationId, targetId: operationId ?? targetId });
432
- }
433
-
434
178
  // src/types/connector.ts
435
179
  var EConnectorInteraction = /* @__PURE__ */ ((EConnectorInteraction2) => {
436
180
  EConnectorInteraction2["Searching"] = "searching";
@@ -446,7 +190,7 @@ function createBridgedConnector(vendor, connectionType, bridge) {
446
190
  return {
447
191
  connectionType,
448
192
  searchDevices: (options) => bridge.searchDevices({ vendor, options }),
449
- connect: (deviceId, options) => bridge.connect({ vendor, deviceId, ...options ? { options } : {} }),
193
+ connect: (deviceId) => bridge.connect({ vendor, deviceId }),
450
194
  disconnect: (sessionId) => bridge.disconnect({ vendor, sessionId }),
451
195
  call: (sessionId, method, callParams) => bridge.call({ vendor, sessionId, method, callParams }),
452
196
  cancel: (sessionId) => bridge.cancel({ vendor, sessionId }),
@@ -586,14 +330,11 @@ function createCombinedConnector(connectors) {
586
330
  if (mergeShared(data.credentials)) void broadcastCredentials();
587
331
  });
588
332
  }
589
- const onTransport = (child, transportType) => !transportType || child.connectionType === transportType;
590
333
  const searchDevices = async (options = {}) => {
591
- const selectedConnectors = connectors.map((child, index) => ({ child, index })).filter(({ child }) => onTransport(child, options.transportType));
592
- if (!selectedConnectors.length) return [];
593
334
  const perConnector = [];
594
- await new Promise((resolve, reject) => {
335
+ await new Promise((resolve) => {
595
336
  let finished = false;
596
- let remaining = selectedConnectors.length;
337
+ let remaining = connectors.length;
597
338
  let settleTimer;
598
339
  const finish = () => {
599
340
  if (finished) return;
@@ -601,20 +342,19 @@ function createCombinedConnector(connectors) {
601
342
  if (settleTimer) clearTimeout(settleTimer);
602
343
  resolve();
603
344
  };
604
- selectedConnectors.forEach(({ child, index }) => {
605
- void child.searchDevices(options.purpose ? { purpose: options.purpose } : void 0).then(
345
+ connectors.forEach((child, index) => {
346
+ void child.searchDevices().then(
606
347
  (devices) => devices.map((device) => ({
607
348
  ...device,
608
349
  connectionType: device.connectionType ?? child.connectionType
609
350
  }))
610
- ).catch((error) => {
611
- if (options.transportType) {
612
- finished = true;
613
- if (settleTimer) clearTimeout(settleTimer);
614
- reject(error);
615
- }
616
- return [];
617
- }).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) => {
618
358
  remaining -= 1;
619
359
  if (!finished) {
620
360
  perConnector.push({ index, devices });
@@ -631,9 +371,7 @@ function createCombinedConnector(connectors) {
631
371
  });
632
372
  });
633
373
  perConnector.sort((a, b) => a.index - b.index);
634
- for (const [id, owner] of deviceOwner) {
635
- if (onTransport(owner, options.transportType)) deviceOwner.delete(id);
636
- }
374
+ deviceOwner.clear();
637
375
  const merged = [];
638
376
  perConnector.forEach(({ index, devices }) => {
639
377
  for (const device of devices) {
@@ -643,12 +381,11 @@ function createCombinedConnector(connectors) {
643
381
  });
644
382
  return merged.sort((a, b) => rank(a) - rank(b));
645
383
  };
646
- const resolveOwner = async (deviceId, transportType) => {
647
- const cachedOwner = deviceId ? deviceOwner.get(deviceId) : void 0;
648
- if (cachedOwner && onTransport(cachedOwner, transportType)) {
649
- return { owner: cachedOwner, deviceId };
384
+ const resolveOwner = async (deviceId) => {
385
+ if (deviceId && deviceOwner.has(deviceId)) {
386
+ return { owner: deviceOwner.get(deviceId), deviceId };
650
387
  }
651
- const devices = await searchDevices({ waitForAll: Boolean(deviceId), transportType });
388
+ const devices = await searchDevices({ waitForAll: Boolean(deviceId) });
652
389
  if (deviceId) {
653
390
  const owner = deviceOwner.get(deviceId);
654
391
  if (!owner)
@@ -659,14 +396,13 @@ function createCombinedConnector(connectors) {
659
396
  if (!first) throw combinedDeviceNotFoundError("Combined connector: no devices found");
660
397
  return { owner: deviceOwner.get(first.connectId), deviceId: first.connectId };
661
398
  };
662
- const connectByExplicitId = async (deviceId, transportType) => {
399
+ const connectByExplicitId = async (deviceId) => {
663
400
  const cachedOwner = deviceOwner.get(deviceId);
664
- if (cachedOwner && onTransport(cachedOwner, transportType)) {
401
+ if (cachedOwner) {
665
402
  return { session: await cachedOwner.connect(deviceId), owner: cachedOwner };
666
403
  }
667
404
  let lastError;
668
405
  for (const child of connectors) {
669
- if (!onTransport(child, transportType)) continue;
670
406
  try {
671
407
  const session = await child.connect(deviceId);
672
408
  deviceOwner.set(deviceId, child);
@@ -688,15 +424,14 @@ function createCombinedConnector(connectors) {
688
424
  // Nominal value only — the per-device `connectionType` is authoritative
689
425
  // for a fused connector.
690
426
  connectionType: connectors[0].connectionType,
691
- availableTransports: [...new Set(connectors.map((child) => child.connectionType))],
692
- searchDevices: (options) => searchDevices(options),
693
- connect: async (deviceId, options) => {
427
+ searchDevices: (options) => searchDevices({ waitForAll: options?.waitForAll }),
428
+ connect: async (deviceId) => {
694
429
  let owner;
695
430
  let session;
696
431
  if (deviceId) {
697
- ({ session, owner } = await connectByExplicitId(deviceId, options?.transportType));
432
+ ({ session, owner } = await connectByExplicitId(deviceId));
698
433
  } else {
699
- const resolved = await resolveOwner(void 0, options?.transportType);
434
+ const resolved = await resolveOwner();
700
435
  owner = resolved.owner;
701
436
  session = await owner.connect(resolved.deviceId);
702
437
  }
@@ -718,11 +453,8 @@ function createCombinedConnector(connectors) {
718
453
  },
719
454
  cancel: async (sessionId) => {
720
455
  const owner = sessionOwner.get(sessionId);
721
- if (owner) {
722
- await owner.cancel(sessionId);
723
- return;
724
- }
725
- await Promise.all(connectors.map((child) => child.cancel(sessionId)));
456
+ if (!owner) return;
457
+ await owner.cancel(sessionId);
726
458
  },
727
459
  uiResponse: (response) => {
728
460
  for (const child of connectors) child.uiResponse(response);
@@ -805,141 +537,6 @@ var TypedEventEmitter = class {
805
537
  }
806
538
  };
807
539
 
808
- // src/utils/requestSaveDeviceBinding.ts
809
- async function requestSaveDeviceBinding(emitter, registry, binding, signal) {
810
- const type = UI_REQUEST.REQUEST_SAVE_DEVICE_BINDING;
811
- const emitStatus = (status) => emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
812
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
813
- payload: { selectionRequestId: binding.selectionRequestId, status }
814
- });
815
- const declined = (reason) => {
816
- emitStatus("failed");
817
- return { saved: false, reason };
818
- };
819
- if (!emitter.listenerCount(type)) {
820
- return declined("skipped");
821
- }
822
- if (signal?.aborted) throw signal.reason;
823
- const requestId = registry.createRequestId();
824
- const pending = registry.wait(type, { requestId, operationId: binding.operationId });
825
- void pending.catch(() => void 0);
826
- const cancel = () => registry.cancel(type, requestId);
827
- signal?.addEventListener("abort", cancel, { once: true });
828
- try {
829
- emitter.emit(type, { type, payload: { ...binding, requestId } });
830
- const response = await pending;
831
- if (signal?.aborted) throw signal.reason;
832
- if (response?.saved !== true) {
833
- return declined(response?.reason ?? "skipped");
834
- }
835
- emitStatus("saved");
836
- return { saved: true };
837
- } catch (error) {
838
- if (signal?.aborted) {
839
- emitStatus("cancelled");
840
- throw error;
841
- }
842
- return declined("skipped");
843
- } finally {
844
- signal?.removeEventListener("abort", cancel);
845
- registry.cancel(type, requestId);
846
- }
847
- }
848
-
849
- // src/utils/requestBleDeviceSelection.ts
850
- async function requestBleDeviceSelection({
851
- emitter,
852
- registry,
853
- request,
854
- scan,
855
- signal,
856
- allowUsbFallback = false,
857
- pollIntervalMs = 1500
858
- }) {
859
- const type = UI_REQUEST.REQUEST_SELECT_DEVICE;
860
- if (signal.aborted) throw signal.reason;
861
- if (!emitter.listenerCount(type)) {
862
- throw createHwkError({
863
- code: 10100 /* DeviceNotFound */,
864
- message: "Select a Bluetooth device before continuing"
865
- });
866
- }
867
- const requestId = registry.createRequestId();
868
- const { operationId } = request;
869
- let devices = allowUsbFallback ? request.devices.filter((device) => device.connectionType === "ble") : request.devices;
870
- const publishedDevices = /* @__PURE__ */ new Map();
871
- let stopped = false;
872
- let timer;
873
- let wake;
874
- const stop = () => {
875
- stopped = true;
876
- if (timer !== void 0) clearTimeout(timer);
877
- wake?.();
878
- };
879
- const waitForNextScan = () => new Promise((resolve) => {
880
- wake = resolve;
881
- timer = setTimeout(resolve, pollIntervalMs);
882
- if (stopped) resolve();
883
- });
884
- const cancel = () => registry.cancel(type, requestId);
885
- const reply = registry.wait(type, { requestId, operationId }).finally(stop);
886
- void reply.catch(() => void 0);
887
- const publish = () => {
888
- for (const device of devices) publishedDevices.set(device.connectId, device);
889
- emitter.emit(type, {
890
- type,
891
- payload: { ...request, devices, requestId, scanning: true }
892
- });
893
- };
894
- signal.addEventListener("abort", cancel, { once: true });
895
- let polling;
896
- try {
897
- publish();
898
- polling = (async () => {
899
- await Promise.resolve();
900
- while (!stopped) {
901
- const snapshot = await scan();
902
- if (stopped || signal.aborted) return;
903
- const usbFallback = allowUsbFallback ? snapshot.find((device2) => device2.connectionType === "usb") : void 0;
904
- if (usbFallback) return usbFallback;
905
- devices = snapshot;
906
- publish();
907
- await waitForNextScan();
908
- }
909
- })();
910
- const userSelection = reply.then((selected) => publishedDevices.get(selected.sdkConnectId));
911
- const device = await Promise.race([
912
- userSelection,
913
- polling.then((usbFallback) => usbFallback ?? userSelection)
914
- ]);
915
- stop();
916
- await polling;
917
- if (signal.aborted) throw signal.reason;
918
- if (!device) {
919
- throw createHwkError({
920
- code: 10100 /* DeviceNotFound */,
921
- message: "Selected Bluetooth device is no longer available"
922
- });
923
- }
924
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
925
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
926
- payload: { selectionRequestId: requestId, status: "verifying" }
927
- });
928
- return { device, requestId };
929
- } catch (error) {
930
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
931
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
932
- payload: { selectionRequestId: requestId, status: signal.aborted ? "cancelled" : "failed" }
933
- });
934
- throw error;
935
- } finally {
936
- stop();
937
- signal.removeEventListener("abort", cancel);
938
- registry.cancel(type, requestId);
939
- await polling?.catch(() => void 0);
940
- }
941
- }
942
-
943
540
  // src/utils/semver.ts
944
541
  function compareSemver(a, b) {
945
542
  const pa = a.split(".").map(Number);
@@ -967,86 +564,14 @@ function padHex64(hex) {
967
564
  function hexToBytes(hex) {
968
565
  return nobleHexToBytes(stripHex(hex));
969
566
  }
970
- function bytesToHex3(bytes) {
567
+ function bytesToHex2(bytes) {
971
568
  return nobleBytesToHex(bytes);
972
569
  }
973
570
 
974
- // src/utils/solanaOffchainMessage.ts
975
- var SOLANA_OFFCHAIN_SIGNING_DOMAIN = Uint8Array.of(
976
- 255,
977
- ...Array.from("solana offchain", (character) => character.charCodeAt(0))
978
- );
979
- var SOLANA_PUBLIC_KEY_LENGTH = 32;
980
- var MAX_SOLANA_OFFCHAIN_SIGNERS = 255;
981
- function compareBytes(a, b) {
982
- for (let index = 0; index < a.length; index += 1) {
983
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
984
- if (difference !== 0) return difference;
985
- }
986
- return a.length - b.length;
987
- }
988
- function bytesEqual(a, b) {
989
- return a.length === b.length && a.every((value, index) => value === b[index]);
990
- }
991
- function decodeUtf8Strict(bytes) {
992
- return decodeURIComponent(
993
- Array.from(bytes, (value) => `%${value.toString(16).padStart(2, "0")}`).join("")
994
- );
995
- }
996
- function prepareSolanaOffchainMessageV1({
997
- message,
998
- requiredSigners
999
- }) {
1000
- if (message.length === 0) {
1001
- throw new Error("Solana off-chain message cannot be empty");
1002
- }
1003
- if (requiredSigners.length === 0 || requiredSigners.length > MAX_SOLANA_OFFCHAIN_SIGNERS) {
1004
- throw new Error("Solana off-chain message requires between 1 and 255 signers");
1005
- }
1006
- let messageText;
1007
- try {
1008
- messageText = decodeUtf8Strict(message);
1009
- } catch {
1010
- throw new Error("Solana off-chain message must contain valid UTF-8");
1011
- }
1012
- const signerBytes = requiredSigners.map((signer, index) => {
1013
- let bytes;
1014
- try {
1015
- bytes = hexToBytes(signer);
1016
- } catch {
1017
- throw new Error(`Solana off-chain signer ${index} must be a hex public key`);
1018
- }
1019
- if (bytes.length !== SOLANA_PUBLIC_KEY_LENGTH) {
1020
- throw new Error(`Solana off-chain signer ${index} must be 32 bytes`);
1021
- }
1022
- return bytes;
1023
- });
1024
- signerBytes.sort(compareBytes);
1025
- if (signerBytes.some((bytes, index) => index > 0 && bytesEqual(signerBytes[index - 1], bytes))) {
1026
- throw new Error("Solana off-chain signers must be unique");
1027
- }
1028
- const signersOffset = SOLANA_OFFCHAIN_SIGNING_DOMAIN.length + 2;
1029
- const messageOffset = signersOffset + signerBytes.length * SOLANA_PUBLIC_KEY_LENGTH;
1030
- const serializedMessage = new Uint8Array(messageOffset + message.length);
1031
- serializedMessage.set(SOLANA_OFFCHAIN_SIGNING_DOMAIN);
1032
- serializedMessage.set([1, signerBytes.length], SOLANA_OFFCHAIN_SIGNING_DOMAIN.length);
1033
- signerBytes.forEach(
1034
- (signer, index) => serializedMessage.set(signer, signersOffset + index * SOLANA_PUBLIC_KEY_LENGTH)
1035
- );
1036
- serializedMessage.set(message, messageOffset);
1037
- return {
1038
- messageText,
1039
- requiredSigners: signerBytes.map(bytesToHex3),
1040
- serializedMessage
1041
- };
1042
- }
1043
-
1044
571
  // src/utils/deviceIdentity.ts
1045
572
  var ONEKEY_BLE_SERVICE_UUID = "00000001-0000-1000-8000-00805f9b34fb";
1046
573
  var TREZOR_BLE_SERVICE_UUID = "8c000001-a59b-4d58-a9ad-073df69fa1b1";
1047
574
  var LEDGER_USB_VENDOR_ID = 11415;
1048
- var KEYSTONE_USB_VENDOR_ID = 4617;
1049
- var KEYSTONE_USB_PRODUCT_ID = 12289;
1050
575
  var lower = (value) => value?.trim().toLowerCase() ?? "";
1051
576
  var hasServiceUuid = (input, uuid) => {
1052
577
  const expected = uuid.toLowerCase();
@@ -1069,11 +594,6 @@ function detectHardwareVendorFromDescriptor(input) {
1069
594
  if (typeof input.vendor === "number" && input.vendor === LEDGER_USB_VENDOR_ID || input.vendorId === LEDGER_USB_VENDOR_ID || manufacturerName.includes("ledger")) {
1070
595
  return "ledger";
1071
596
  }
1072
- const usbVendorId = typeof input.vendor === "number" ? input.vendor : input.vendorId;
1073
- const usbProductId = typeof input.product === "number" ? input.product : input.productId;
1074
- if (usbVendorId === KEYSTONE_USB_VENDOR_ID && usbProductId === KEYSTONE_USB_PRODUCT_ID || manufacturerName.includes("keystone")) {
1075
- return "keystone";
1076
- }
1077
597
  return void 0;
1078
598
  }
1079
599
  function isKnownNonTargetHardwareVendor(input, targetVendor) {
@@ -1097,62 +617,28 @@ async function batchCall(params, callFn, onProgress) {
1097
617
 
1098
618
  // src/utils/methodCatalog.ts
1099
619
  var HARDWARE_METHOD_CATALOG = {
1100
- evmGetAddress: { chain: "evm", allNetwork: true, replayAfterTransportFailure: "safe" },
1101
- evmSignTransaction: {
1102
- chain: "evm",
1103
- allNetwork: false,
1104
- replayAfterTransportFailure: "unsafe"
1105
- },
1106
- evmSignMessage: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1107
- evmSignTypedData: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1108
- btcGetAddress: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1109
- btcGetPublicKey: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1110
- btcSignTransaction: {
1111
- chain: "btc",
1112
- allNetwork: false,
1113
- replayAfterTransportFailure: "unsafe"
1114
- },
1115
- btcSignPsbt: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1116
- btcSignMessage: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1117
- btcGetMasterFingerprint: {
1118
- chain: "btc",
1119
- allNetwork: false,
1120
- replayAfterTransportFailure: "safe"
1121
- },
1122
- solGetAddress: { chain: "sol", allNetwork: true, replayAfterTransportFailure: "safe" },
1123
- solSignTransaction: {
1124
- chain: "sol",
1125
- allNetwork: false,
1126
- replayAfterTransportFailure: "unsafe"
1127
- },
1128
- solSignMessage: { chain: "sol", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1129
- tronGetAddress: { chain: "tron", allNetwork: true, replayAfterTransportFailure: "safe" },
1130
- tronSignTransaction: {
1131
- chain: "tron",
1132
- allNetwork: false,
1133
- replayAfterTransportFailure: "unsafe"
1134
- },
1135
- tronSignMessage: { chain: "tron", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1136
- zcashGetFullViewingKey: {
1137
- chain: "zcash",
1138
- allNetwork: false,
1139
- replayAfterTransportFailure: "safe"
1140
- },
1141
- zcashGetShieldedAddress: {
1142
- chain: "zcash",
1143
- allNetwork: false,
1144
- replayAfterTransportFailure: "safe"
1145
- }
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 }
1146
636
  };
1147
637
  var ALL_NETWORK_METHOD_NAMES = Object.entries(HARDWARE_METHOD_CATALOG).filter(([, metadata]) => metadata.allNetwork).map(([method]) => method);
1148
638
  var ALL_NETWORK_METHOD_SET = new Set(ALL_NETWORK_METHOD_NAMES);
1149
639
  function getHardwareMethodMetadata(method) {
1150
640
  return HARDWARE_METHOD_CATALOG[method];
1151
641
  }
1152
- var SAFE_NON_CHAIN_METHODS = /* @__PURE__ */ new Set(["getFeatures", "authenticateDevice"]);
1153
- function canReplayHardwareMethodAfterTransportFailure(method) {
1154
- return getHardwareMethodMetadata(method)?.replayAfterTransportFailure === "safe" || SAFE_NON_CHAIN_METHODS.has(method);
1155
- }
1156
642
  function isAllNetworkMethodName(method) {
1157
643
  return ALL_NETWORK_METHOD_SET.has(method);
1158
644
  }
@@ -1212,19 +698,6 @@ async function runAllNetworkGetAddress({
1212
698
  }
1213
699
  return success(responses);
1214
700
  }
1215
- function isUserRefusal(code) {
1216
- return code === 10005 /* UserAborted */ || code === 10001 /* UserRejected */ || code === 10401 /* PinCancelled */;
1217
- }
1218
- function isConnectionLost(code) {
1219
- const codes = [
1220
- 10101 /* DeviceDisconnected */,
1221
- 10003 /* OperationTimeout */,
1222
- 10300 /* TransportError */,
1223
- 10113 /* OperationEnded */,
1224
- 10112 /* OperationNotFound */
1225
- ];
1226
- return code !== void 0 && codes.includes(code);
1227
- }
1228
701
  function buildUnsupportedMethodResponse(item) {
1229
702
  return {
1230
703
  ...item,
@@ -1258,11 +731,8 @@ export {
1258
731
  DeviceJobQueue,
1259
732
  EConnectorInteraction,
1260
733
  HARDWARE_METHOD_CATALOG,
1261
- HARDWARE_RUNTIME_ID_PREFIX,
1262
734
  HardwareErrorCode,
1263
- OPERATION_DEFAULT_TTL_MS,
1264
735
  ORPHAN_ELIGIBLE_ERROR_CODES,
1265
- OperationRegistry,
1266
736
  SDK,
1267
737
  TypedEventEmitter,
1268
738
  UI_EVENT,
@@ -1275,43 +745,23 @@ export {
1275
745
  UiRequestRegistry,
1276
746
  batchCall,
1277
747
  buildUnsupportedMethodResponse,
1278
- bytesToHex3 as bytesToHex,
1279
- canReplayHardwareMethodAfterTransportFailure,
748
+ bytesToHex2 as bytesToHex,
1280
749
  compareSemver,
1281
750
  createBridgedConnector,
1282
751
  createCombinedConnector,
1283
- createHardwareLinkId,
1284
- createHardwareOperationId,
1285
- createHardwareSearchTargetId,
1286
752
  createHwkError,
1287
- defaultOriginForCode,
1288
- defaultRecoveryForCode,
1289
753
  deriveDeviceFingerprint,
1290
- deriveWalletId,
1291
754
  detectHardwareVendorFromDescriptor,
1292
755
  enrichErrorMessage,
1293
756
  ensure0x,
1294
757
  failure,
1295
758
  getAllNetworkMethodChain,
1296
759
  getHardwareMethodMetadata,
1297
- hasHardwareRuntimeIdPrefix,
1298
760
  hexToBytes,
1299
761
  isAllNetworkMethodName,
1300
- isConnectionLost,
1301
- isHardwareOperationId,
1302
- isHwkRecoveryHint,
1303
762
  isKnownNonTargetHardwareVendor,
1304
- isUserRefusal,
1305
- operationMayHaveCompletedParams,
1306
763
  padHex64,
1307
- parseBip32MasterFingerprint,
1308
- parseHardwareRuntimeId,
1309
- prepareSolanaOffchainMessageV1,
1310
764
  rehydrateConnectorError,
1311
- requestBleDeviceSelection,
1312
- requestSaveDeviceBinding,
1313
- resolveHardwareOperationTarget,
1314
- resolveSearchTargetReusePolicy,
1315
765
  runAllNetworkGetAddress,
1316
766
  serializeConnectorError,
1317
767
  stripHex,