@onekeyfe/hwk-adapter-core 1.2.3-alpha.4 → 1.2.3-alpha.5

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-S7X2HM7P.js → chunk-BAGEFFFY.js} +3 -32
  2. package/dist/chunk-BAGEFFFY.js.map +1 -0
  3. package/dist/{chunk-Z3IH25KV.js → chunk-SZZF623R.js} +55 -146
  4. package/dist/chunk-SZZF623R.js.map +1 -0
  5. package/dist/{chunk-ELC6PLKH.mjs → chunk-U63HTLGJ.mjs} +2 -31
  6. package/dist/chunk-U63HTLGJ.mjs.map +1 -0
  7. package/dist/{chunk-E3UPXUN5.mjs → chunk-YA4BWFTZ.mjs} +55 -146
  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 +74 -561
  15. package/dist/index.d.ts +74 -561
  16. package/dist/index.js +80 -645
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +71 -636
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{ui-events-CbZdnS8a.d.ts → ui-events-Cb7haAeE.d.mts} +3 -28
  21. package/dist/{ui-events-CbZdnS8a.d.mts → ui-events-Cb7haAeE.d.ts} +3 -28
  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-3M3GMF64.mjs +0 -68
  29. package/dist/chunk-3M3GMF64.mjs.map +0 -1
  30. package/dist/chunk-7SFFS2NL.js +0 -68
  31. package/dist/chunk-7SFFS2NL.js.map +0 -1
  32. package/dist/chunk-E3UPXUN5.mjs.map +0 -1
  33. package/dist/chunk-ELC6PLKH.mjs.map +0 -1
  34. package/dist/chunk-S7X2HM7P.js.map +0 -1
  35. package/dist/chunk-Z3IH25KV.js.map +0 -1
  36. package/dist/errors-C5GWtyVN.d.mts +0 -304
  37. package/dist/errors-C5GWtyVN.d.ts +0 -304
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-3M3GMF64.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-ELC6PLKH.mjs";
14
- import {
15
- HardwareErrorCode,
16
- ORPHAN_ELIGIBLE_ERROR_CODES,
17
- createHwkError,
18
- defaultOriginForCode,
19
- defaultRecoveryForCode,
20
- isHwkRecoveryHint,
21
- operationMayHaveCompletedParams
22
- } from "./chunk-E3UPXUN5.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,53 +118,31 @@ 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
- /** Cancel the running job. `reason` becomes signal.reason. */
173
- cancelActive(deviceId, reason) {
128
+ /** Force cancel the active job. `reason` becomes signal.reason. */
129
+ forceCancelActive(deviceId, reason) {
174
130
  if (!this._active) return false;
175
131
  if (deviceId && this._active.deviceId !== deviceId) return false;
176
- this._active.abortController.abort(reason ?? new Error("Cancelled"));
132
+ this._active.abortController.abort(reason ?? new Error("Force cancelled for recovery"));
177
133
  return true;
178
134
  }
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
+ }
179
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) {
183
- let cancelled = false;
184
- for (const job of this._jobs.values()) {
185
- if (job.deviceId === deviceId) {
186
- job.abortController.abort(cancelReason);
187
- cancelled = true;
188
- }
189
- }
190
- for (const scope of this._cancelScopes.values()) {
191
- if (scope.deviceId === deviceId) {
192
- scope.abortController.abort(cancelReason);
193
- cancelled = true;
194
- }
195
- }
196
- return cancelled;
142
+ if (deviceId && this._active && this._active.deviceId !== deviceId) {
143
+ return false;
197
144
  }
198
- this.clear(cancelReason);
145
+ this.clear(reason ?? new Error("Cancelled by cancelActiveAndPending"));
199
146
  return true;
200
147
  }
201
148
  /** Get info about the currently active job, or null if idle. */
@@ -208,6 +155,10 @@ var DeviceJobQueue = class {
208
155
  startedAt: this._active.startedAt
209
156
  };
210
157
  }
158
+ /** True if any job is currently running. */
159
+ isBusy() {
160
+ return this._jobs.size > 0;
161
+ }
211
162
  clear(reason) {
212
163
  const cancelledGeneration = this._generation;
213
164
  this._generation++;
@@ -221,230 +172,9 @@ var DeviceJobQueue = class {
221
172
  if (this._active) {
222
173
  this._active.abortController.abort(cancelReason);
223
174
  }
224
- for (const scope of this._cancelScopes.values()) {
225
- scope.abortController.abort(cancelReason);
226
- }
227
- }
228
- };
229
-
230
- // src/utils/hardwareRuntimeId.ts
231
- import { bytesToHex as bytesToHex2, randomBytes } from "@noble/hashes/utils";
232
- var HARDWARE_RUNTIME_ID_PREFIX = "hwk:runtime";
233
- var RANDOM_ID_BYTES = 16;
234
- var RANDOM_ID_PATTERN = /^[0-9a-f]{32}$/;
235
- var KINDS = /* @__PURE__ */ new Set([
236
- "operation",
237
- "search-target",
238
- "link"
239
- ]);
240
- var VENDORS = /* @__PURE__ */ new Set(["trezor", "ledger", "keystone"]);
241
- function create(kind, vendor) {
242
- return `${HARDWARE_RUNTIME_ID_PREFIX}:${kind}:${vendor}:${bytesToHex2(
243
- randomBytes(RANDOM_ID_BYTES)
244
- )}`;
245
- }
246
- function createHardwareOperationId(vendor) {
247
- return create("operation", vendor);
248
- }
249
- function createHardwareSearchTargetId(vendor) {
250
- return create("search-target", vendor);
251
- }
252
- function createHardwareLinkId(vendor) {
253
- return create("link", vendor);
254
- }
255
- function hasHardwareRuntimeIdPrefix(value) {
256
- return typeof value === "string" && value.startsWith(`${HARDWARE_RUNTIME_ID_PREFIX}:`);
257
- }
258
- function parseHardwareRuntimeId(value) {
259
- if (!hasHardwareRuntimeIdPrefix(value)) return void 0;
260
- const parts = value.split(":");
261
- if (parts.length !== 5) return void 0;
262
- const [, , kind, vendor, nonce] = parts;
263
- if (!KINDS.has(kind) || !VENDORS.has(vendor) || !RANDOM_ID_PATTERN.test(nonce)) {
264
- return void 0;
265
- }
266
- return { kind, vendor };
267
- }
268
- function isHardwareOperationId(value) {
269
- return parseHardwareRuntimeId(value)?.kind === "operation";
270
- }
271
-
272
- // src/utils/OperationRegistry.ts
273
- var OPERATION_DEFAULT_TTL_MS = 6e5;
274
- var OperationRegistry = class {
275
- constructor(options) {
276
- this._active = /* @__PURE__ */ new Map();
277
- this._ended = /* @__PURE__ */ new Map();
278
- this._vendor = options.vendor;
279
- this._ttlMs = options.ttlMs ?? OPERATION_DEFAULT_TTL_MS;
280
- this._onEnded = options.onEnded;
281
- }
282
- create(params) {
283
- const now = Date.now();
284
- const operationId = createHardwareOperationId(this._vendor);
285
- const operation = {
286
- operationId,
287
- connectId: params.connectId,
288
- device: params.device,
289
- connectionKeys: Array.from(
290
- new Set(
291
- [params.searchTargetId, params.connectId, ...params.connectionKeys ?? []].filter(
292
- Boolean
293
- )
294
- )
295
- ),
296
- createdAt: now,
297
- lastActiveAt: now
298
- };
299
- const timer = this._createTimer(operationId);
300
- this._active.set(operationId, { ...operation, timer, retainCount: 0 });
301
- return operation;
302
- }
303
- resolve(operationId) {
304
- const active = this._active.get(operationId);
305
- if (!active) {
306
- const ended = this._ended.get(operationId);
307
- if (ended) {
308
- throw createHwkError({
309
- code: 10113 /* OperationEnded */,
310
- message: `Hardware operation has ended (${ended.reason})`,
311
- params: { operationId, reason: ended.reason }
312
- });
313
- }
314
- throw createHwkError({
315
- code: 10112 /* OperationNotFound */,
316
- message: "Hardware operation was not found",
317
- params: { operationId }
318
- });
319
- }
320
- if (active.timer) clearTimeout(active.timer);
321
- active.lastActiveAt = Date.now();
322
- active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
323
- return active;
324
- }
325
- /** Keep an operation alive while one device job is actively using it. */
326
- retain(operationId) {
327
- const active = this.resolve(operationId);
328
- if (active.timer) clearTimeout(active.timer);
329
- active.timer = void 0;
330
- active.retainCount += 1;
331
- let released = false;
332
- return () => {
333
- if (released) return;
334
- released = true;
335
- const current = this._active.get(operationId);
336
- if (!current) return;
337
- current.retainCount = Math.max(0, current.retainCount - 1);
338
- current.lastActiveAt = Date.now();
339
- if (current.retainCount === 0) {
340
- current.timer = this._createTimer(operationId);
341
- }
342
- };
343
- }
344
- /** Return active or tombstoned binding data without refreshing its TTL. */
345
- find(operationId) {
346
- return this._active.get(operationId) ?? this._ended.get(operationId)?.operation;
347
- }
348
- findActiveByConnectionKey(connectionKey) {
349
- if (!connectionKey) return void 0;
350
- return [...this._active.values()].find(
351
- (operation) => operation.connectionKeys.includes(connectionKey)
352
- );
353
- }
354
- /** Replace the live transport binding after the same target was reconnected. */
355
- rebind(operationId, params) {
356
- const active = this._active.get(operationId);
357
- if (!active) {
358
- this.resolve(operationId);
359
- throw new Error("Unreachable operation rebind");
360
- }
361
- if (active.timer) clearTimeout(active.timer);
362
- active.connectId = params.connectId;
363
- active.device = params.device;
364
- active.connectionKeys = Array.from(
365
- new Set([params.connectId, ...params.connectionKeys ?? []].filter(Boolean))
366
- );
367
- active.lastActiveAt = Date.now();
368
- active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
369
- return active;
370
- }
371
- end(operationId, reason) {
372
- const active = this._active.get(operationId);
373
- if (!active) return void 0;
374
- if (active.timer) clearTimeout(active.timer);
375
- this._active.delete(operationId);
376
- this._rememberEnded(active, reason);
377
- this._onEnded?.(active, reason);
378
- return active;
379
- }
380
- endByConnectionKey(connectionKey, reason, exceptOperationId) {
381
- if (!connectionKey) return;
382
- for (const operation of [...this._active.values()]) {
383
- if (operation.operationId === exceptOperationId) continue;
384
- if (operation.connectionKeys.includes(connectionKey)) {
385
- this.end(operation.operationId, reason);
386
- }
387
- }
388
- }
389
- endAll(reason, exceptOperationId) {
390
- for (const operationId of [...this._active.keys()]) {
391
- if (operationId === exceptOperationId) continue;
392
- this.end(operationId, reason);
393
- }
394
- }
395
- _createTimer(operationId) {
396
- const timer = setTimeout(() => {
397
- this.end(operationId, "timeout");
398
- }, this._ttlMs);
399
- timer.unref?.();
400
- return timer;
401
- }
402
- _rememberEnded(operation, reason) {
403
- this._ended.set(operation.operationId, { reason, operation });
404
- if (this._ended.size <= 100) return;
405
- const oldest = this._ended.keys().next().value;
406
- if (oldest) this._ended.delete(oldest);
407
175
  }
408
176
  };
409
177
 
410
- // src/utils/hardwareOperationTarget.ts
411
- function resolveHardwareOperationTarget(positionalTargetId, commonOperationId, expectedVendor) {
412
- const normalizedPositionalTargetId = positionalTargetId ?? void 0;
413
- const normalizedCommonOperationId = commonOperationId || void 0;
414
- const positionalOperationId = isHardwareOperationId(normalizedPositionalTargetId) ? normalizedPositionalTargetId : void 0;
415
- const parsedPositionalTarget = parseHardwareRuntimeId(normalizedPositionalTargetId);
416
- const parsedCommonOperation = parseHardwareRuntimeId(normalizedCommonOperationId);
417
- if (normalizedPositionalTargetId && hasHardwareRuntimeIdPrefix(normalizedPositionalTargetId) && !parsedPositionalTarget) {
418
- return failure(10002 /* InvalidParams */, "Invalid hardware operation target id");
419
- }
420
- if (parsedPositionalTarget?.kind === "link") {
421
- return failure(
422
- 10002 /* InvalidParams */,
423
- "Hardware transport link id cannot be used as an operation target"
424
- );
425
- }
426
- if (normalizedCommonOperationId && parsedCommonOperation?.kind !== "operation") {
427
- return failure(10002 /* InvalidParams */, "Invalid hardware operation id");
428
- }
429
- if (expectedVendor && (parsedPositionalTarget && parsedPositionalTarget.vendor !== expectedVendor || parsedCommonOperation && parsedCommonOperation.vendor !== expectedVendor)) {
430
- return failure(
431
- 10002 /* InvalidParams */,
432
- `Hardware operation does not belong to ${expectedVendor}`
433
- );
434
- }
435
- if (positionalOperationId && normalizedCommonOperationId && positionalOperationId !== normalizedCommonOperationId) {
436
- return failure(10002 /* InvalidParams */, "Conflicting hardware operation ids", {
437
- positionalOperationId,
438
- commonOperationId: normalizedCommonOperationId
439
- });
440
- }
441
- const operationId = normalizedCommonOperationId ?? positionalOperationId;
442
- return success({
443
- operationId,
444
- targetId: operationId ?? normalizedPositionalTargetId
445
- });
446
- }
447
-
448
178
  // src/types/connector.ts
449
179
  var EConnectorInteraction = /* @__PURE__ */ ((EConnectorInteraction2) => {
450
180
  EConnectorInteraction2["Searching"] = "searching";
@@ -460,7 +190,7 @@ function createBridgedConnector(vendor, connectionType, bridge) {
460
190
  return {
461
191
  connectionType,
462
192
  searchDevices: (options) => bridge.searchDevices({ vendor, options }),
463
- connect: (deviceId, options) => bridge.connect({ vendor, deviceId, ...options ? { options } : {} }),
193
+ connect: (deviceId) => bridge.connect({ vendor, deviceId }),
464
194
  disconnect: (sessionId) => bridge.disconnect({ vendor, sessionId }),
465
195
  call: (sessionId, method, callParams) => bridge.call({ vendor, sessionId, method, callParams }),
466
196
  cancel: (sessionId) => bridge.cancel({ vendor, sessionId }),
@@ -601,14 +331,10 @@ function createCombinedConnector(connectors) {
601
331
  });
602
332
  }
603
333
  const searchDevices = async (options = {}) => {
604
- const selectedConnectors = connectors.map((child, index) => ({ child, index })).filter(
605
- ({ child }) => !options.transportType || child.connectionType === options.transportType
606
- );
607
- if (!selectedConnectors.length) return [];
608
334
  const perConnector = [];
609
- await new Promise((resolve, reject) => {
335
+ await new Promise((resolve) => {
610
336
  let finished = false;
611
- let remaining = selectedConnectors.length;
337
+ let remaining = connectors.length;
612
338
  let settleTimer;
613
339
  const finish = () => {
614
340
  if (finished) return;
@@ -616,20 +342,19 @@ function createCombinedConnector(connectors) {
616
342
  if (settleTimer) clearTimeout(settleTimer);
617
343
  resolve();
618
344
  };
619
- selectedConnectors.forEach(({ child, index }) => {
620
- void child.searchDevices(options.purpose ? { purpose: options.purpose } : void 0).then(
345
+ connectors.forEach((child, index) => {
346
+ void child.searchDevices().then(
621
347
  (devices) => devices.map((device) => ({
622
348
  ...device,
623
349
  connectionType: device.connectionType ?? child.connectionType
624
350
  }))
625
- ).catch((error) => {
626
- if (options.transportType) {
627
- finished = true;
628
- if (settleTimer) clearTimeout(settleTimer);
629
- reject(error);
630
- }
631
- return [];
632
- }).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) => {
633
358
  remaining -= 1;
634
359
  if (!finished) {
635
360
  perConnector.push({ index, devices });
@@ -646,12 +371,7 @@ function createCombinedConnector(connectors) {
646
371
  });
647
372
  });
648
373
  perConnector.sort((a, b) => a.index - b.index);
649
- if (!options.transportType) deviceOwner.clear();
650
- else {
651
- for (const [id, owner] of deviceOwner) {
652
- if (owner.connectionType === options.transportType) deviceOwner.delete(id);
653
- }
654
- }
374
+ deviceOwner.clear();
655
375
  const merged = [];
656
376
  perConnector.forEach(({ index, devices }) => {
657
377
  for (const device of devices) {
@@ -661,11 +381,11 @@ function createCombinedConnector(connectors) {
661
381
  });
662
382
  return merged.sort((a, b) => rank(a) - rank(b));
663
383
  };
664
- const resolveOwner = async (deviceId, transportType) => {
665
- if (deviceId && deviceOwner.has(deviceId) && (!transportType || deviceOwner.get(deviceId)?.connectionType === transportType)) {
384
+ const resolveOwner = async (deviceId) => {
385
+ if (deviceId && deviceOwner.has(deviceId)) {
666
386
  return { owner: deviceOwner.get(deviceId), deviceId };
667
387
  }
668
- const devices = await searchDevices({ waitForAll: Boolean(deviceId), transportType });
388
+ const devices = await searchDevices({ waitForAll: Boolean(deviceId) });
669
389
  if (deviceId) {
670
390
  const owner = deviceOwner.get(deviceId);
671
391
  if (!owner)
@@ -676,14 +396,13 @@ function createCombinedConnector(connectors) {
676
396
  if (!first) throw combinedDeviceNotFoundError("Combined connector: no devices found");
677
397
  return { owner: deviceOwner.get(first.connectId), deviceId: first.connectId };
678
398
  };
679
- const connectByExplicitId = async (deviceId, transportType) => {
399
+ const connectByExplicitId = async (deviceId) => {
680
400
  const cachedOwner = deviceOwner.get(deviceId);
681
- if (cachedOwner && (!transportType || cachedOwner.connectionType === transportType)) {
401
+ if (cachedOwner) {
682
402
  return { session: await cachedOwner.connect(deviceId), owner: cachedOwner };
683
403
  }
684
404
  let lastError;
685
405
  for (const child of connectors) {
686
- if (transportType && child.connectionType !== transportType) continue;
687
406
  try {
688
407
  const session = await child.connect(deviceId);
689
408
  deviceOwner.set(deviceId, child);
@@ -705,15 +424,14 @@ function createCombinedConnector(connectors) {
705
424
  // Nominal value only — the per-device `connectionType` is authoritative
706
425
  // for a fused connector.
707
426
  connectionType: connectors[0].connectionType,
708
- availableTransports: [...new Set(connectors.map((child) => child.connectionType))],
709
- searchDevices: (options) => searchDevices(options),
710
- connect: async (deviceId, options) => {
427
+ searchDevices: (options) => searchDevices({ waitForAll: options?.waitForAll }),
428
+ connect: async (deviceId) => {
711
429
  let owner;
712
430
  let session;
713
431
  if (deviceId) {
714
- ({ session, owner } = await connectByExplicitId(deviceId, options?.transportType));
432
+ ({ session, owner } = await connectByExplicitId(deviceId));
715
433
  } else {
716
- const resolved = await resolveOwner(void 0, options?.transportType);
434
+ const resolved = await resolveOwner();
717
435
  owner = resolved.owner;
718
436
  session = await owner.connect(resolved.deviceId);
719
437
  }
@@ -819,147 +537,6 @@ var TypedEventEmitter = class {
819
537
  }
820
538
  };
821
539
 
822
- // src/utils/requestSaveDeviceBinding.ts
823
- async function requestSaveDeviceBinding(emitter, registry, binding, signal) {
824
- const type = UI_REQUEST.REQUEST_SAVE_DEVICE_BINDING;
825
- const declined = (reason) => {
826
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
827
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
828
- payload: { selectionRequestId: binding.selectionRequestId, status: "failed" }
829
- });
830
- return { saved: false, reason };
831
- };
832
- if (!emitter.listenerCount(type)) {
833
- return declined("skipped");
834
- }
835
- if (signal?.aborted) throw signal.reason;
836
- const requestId = registry.createRequestId();
837
- const pending = registry.wait(type, { requestId });
838
- void pending.catch(() => void 0);
839
- const cancel = () => registry.cancel(type, requestId);
840
- signal?.addEventListener("abort", cancel, { once: true });
841
- try {
842
- emitter.emit(type, { type, payload: { ...binding, requestId } });
843
- const response = await pending;
844
- if (signal?.aborted) throw signal.reason;
845
- if (response?.saved !== true) {
846
- return declined(response?.reason ?? "skipped");
847
- }
848
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
849
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
850
- payload: { selectionRequestId: binding.selectionRequestId, status: "saved" }
851
- });
852
- return { saved: true };
853
- } catch (error) {
854
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
855
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
856
- payload: {
857
- selectionRequestId: binding.selectionRequestId,
858
- status: signal?.aborted ? "cancelled" : "failed"
859
- }
860
- });
861
- if (signal?.aborted) throw error;
862
- return { saved: false, reason: "skipped" };
863
- } finally {
864
- signal?.removeEventListener("abort", cancel);
865
- registry.cancel(type, requestId);
866
- }
867
- }
868
-
869
- // src/utils/requestBleDeviceSelection.ts
870
- async function requestBleDeviceSelection({
871
- emitter,
872
- registry,
873
- request,
874
- scan,
875
- signal,
876
- allowUsbFallback = false,
877
- pollIntervalMs = 1500
878
- }) {
879
- const type = UI_REQUEST.REQUEST_SELECT_DEVICE;
880
- if (signal.aborted) throw signal.reason;
881
- if (!emitter.listenerCount(type)) {
882
- throw createHwkError({
883
- code: 10100 /* DeviceNotFound */,
884
- message: "Select a Bluetooth device before continuing"
885
- });
886
- }
887
- const requestId = registry.createRequestId();
888
- let devices = allowUsbFallback ? request.devices.filter((device) => device.connectionType === "ble") : request.devices;
889
- const publishedDevices = /* @__PURE__ */ new Map();
890
- let stopped = false;
891
- let timer;
892
- let wake;
893
- const stop = () => {
894
- stopped = true;
895
- if (timer !== void 0) clearTimeout(timer);
896
- wake?.();
897
- };
898
- const waitForNextScan = () => new Promise((resolve) => {
899
- wake = resolve;
900
- timer = setTimeout(resolve, pollIntervalMs);
901
- if (stopped) resolve();
902
- });
903
- const cancel = () => registry.cancel(type, requestId);
904
- const reply = registry.wait(type, { requestId }).finally(stop);
905
- void reply.catch(() => void 0);
906
- const publish = () => {
907
- for (const device of devices) publishedDevices.set(device.connectId, device);
908
- emitter.emit(type, {
909
- type,
910
- payload: { ...request, devices, requestId, scanning: true }
911
- });
912
- };
913
- signal.addEventListener("abort", cancel, { once: true });
914
- let polling;
915
- try {
916
- publish();
917
- polling = (async () => {
918
- await Promise.resolve();
919
- while (!stopped) {
920
- const snapshot = await scan();
921
- if (stopped || signal.aborted) return;
922
- const usbFallback = allowUsbFallback ? snapshot.find((device2) => device2.connectionType === "usb") : void 0;
923
- if (usbFallback) return usbFallback;
924
- devices = snapshot;
925
- publish();
926
- if (stopped) return;
927
- await waitForNextScan();
928
- }
929
- })();
930
- const userSelection = reply.then((selected) => publishedDevices.get(selected.sdkConnectId));
931
- const device = await Promise.race([
932
- userSelection,
933
- polling.then((usbFallback) => usbFallback ?? userSelection)
934
- ]);
935
- stop();
936
- await polling;
937
- if (signal.aborted) throw signal.reason;
938
- if (!device) {
939
- throw createHwkError({
940
- code: 10100 /* DeviceNotFound */,
941
- message: "Selected Bluetooth device is no longer available"
942
- });
943
- }
944
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
945
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
946
- payload: { selectionRequestId: requestId, status: "verifying" }
947
- });
948
- return { device, requestId };
949
- } catch (error) {
950
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
951
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
952
- payload: { selectionRequestId: requestId, status: signal.aborted ? "cancelled" : "failed" }
953
- });
954
- throw error;
955
- } finally {
956
- stop();
957
- signal.removeEventListener("abort", cancel);
958
- registry.cancel(type, requestId);
959
- await polling?.catch(() => void 0);
960
- }
961
- }
962
-
963
540
  // src/utils/semver.ts
964
541
  function compareSemver(a, b) {
965
542
  const pa = a.split(".").map(Number);
@@ -987,96 +564,14 @@ function padHex64(hex) {
987
564
  function hexToBytes(hex) {
988
565
  return nobleHexToBytes(stripHex(hex));
989
566
  }
990
- function bytesToHex3(bytes) {
567
+ function bytesToHex2(bytes) {
991
568
  return nobleBytesToHex(bytes);
992
569
  }
993
570
 
994
- // src/utils/solanaOffchainMessage.ts
995
- var SOLANA_OFFCHAIN_SIGNING_DOMAIN = Uint8Array.of(
996
- 255,
997
- ...Array.from("solana offchain", (character) => character.charCodeAt(0))
998
- );
999
- var SOLANA_PUBLIC_KEY_LENGTH = 32;
1000
- var MAX_SOLANA_OFFCHAIN_SIGNERS = 255;
1001
- function compareBytes(a, b) {
1002
- for (let index = 0; index < a.length; index += 1) {
1003
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
1004
- if (difference !== 0) return difference;
1005
- }
1006
- return a.length - b.length;
1007
- }
1008
- function bytesEqual(a, b) {
1009
- return a.length === b.length && a.every((value, index) => value === b[index]);
1010
- }
1011
- function decodeUtf8Strict(bytes) {
1012
- let encoded = "";
1013
- for (const value of bytes) {
1014
- encoded += `%${value.toString(16).padStart(2, "0")}`;
1015
- }
1016
- return decodeURIComponent(encoded);
1017
- }
1018
- function prepareSolanaOffchainMessageV1({
1019
- message,
1020
- requiredSigners
1021
- }) {
1022
- if (message.length === 0) {
1023
- throw new Error("Solana off-chain message cannot be empty");
1024
- }
1025
- if (requiredSigners.length === 0 || requiredSigners.length > MAX_SOLANA_OFFCHAIN_SIGNERS) {
1026
- throw new Error("Solana off-chain message requires between 1 and 255 signers");
1027
- }
1028
- let messageText;
1029
- try {
1030
- messageText = decodeUtf8Strict(message);
1031
- } catch {
1032
- throw new Error("Solana off-chain message must contain valid UTF-8");
1033
- }
1034
- const signerBytes = requiredSigners.map((signer, index) => {
1035
- let bytes;
1036
- try {
1037
- bytes = hexToBytes(signer);
1038
- } catch {
1039
- throw new Error(`Solana off-chain signer ${index} must be a hex public key`);
1040
- }
1041
- if (bytes.length !== SOLANA_PUBLIC_KEY_LENGTH) {
1042
- throw new Error(`Solana off-chain signer ${index} must be 32 bytes`);
1043
- }
1044
- return bytes;
1045
- });
1046
- signerBytes.sort(compareBytes);
1047
- for (let index = 1; index < signerBytes.length; index += 1) {
1048
- if (bytesEqual(signerBytes[index - 1], signerBytes[index])) {
1049
- throw new Error("Solana off-chain signers must be unique");
1050
- }
1051
- }
1052
- const serializedMessage = new Uint8Array(
1053
- SOLANA_OFFCHAIN_SIGNING_DOMAIN.length + 2 + signerBytes.length * SOLANA_PUBLIC_KEY_LENGTH + message.length
1054
- );
1055
- let offset = 0;
1056
- serializedMessage.set(SOLANA_OFFCHAIN_SIGNING_DOMAIN, offset);
1057
- offset += SOLANA_OFFCHAIN_SIGNING_DOMAIN.length;
1058
- serializedMessage[offset] = 1;
1059
- offset += 1;
1060
- serializedMessage[offset] = signerBytes.length;
1061
- offset += 1;
1062
- for (const signer of signerBytes) {
1063
- serializedMessage.set(signer, offset);
1064
- offset += SOLANA_PUBLIC_KEY_LENGTH;
1065
- }
1066
- serializedMessage.set(message, offset);
1067
- return {
1068
- messageText,
1069
- requiredSigners: signerBytes.map(bytesToHex3),
1070
- serializedMessage
1071
- };
1072
- }
1073
-
1074
571
  // src/utils/deviceIdentity.ts
1075
572
  var ONEKEY_BLE_SERVICE_UUID = "00000001-0000-1000-8000-00805f9b34fb";
1076
573
  var TREZOR_BLE_SERVICE_UUID = "8c000001-a59b-4d58-a9ad-073df69fa1b1";
1077
574
  var LEDGER_USB_VENDOR_ID = 11415;
1078
- var KEYSTONE_USB_VENDOR_ID = 4617;
1079
- var KEYSTONE_USB_PRODUCT_ID = 12289;
1080
575
  var lower = (value) => value?.trim().toLowerCase() ?? "";
1081
576
  var hasServiceUuid = (input, uuid) => {
1082
577
  const expected = uuid.toLowerCase();
@@ -1099,11 +594,6 @@ function detectHardwareVendorFromDescriptor(input) {
1099
594
  if (typeof input.vendor === "number" && input.vendor === LEDGER_USB_VENDOR_ID || input.vendorId === LEDGER_USB_VENDOR_ID || manufacturerName.includes("ledger")) {
1100
595
  return "ledger";
1101
596
  }
1102
- const usbVendorId = typeof input.vendor === "number" ? input.vendor : input.vendorId;
1103
- const usbProductId = typeof input.product === "number" ? input.product : input.productId;
1104
- if (usbVendorId === KEYSTONE_USB_VENDOR_ID && usbProductId === KEYSTONE_USB_PRODUCT_ID || manufacturerName.includes("keystone")) {
1105
- return "keystone";
1106
- }
1107
597
  return void 0;
1108
598
  }
1109
599
  function isKnownNonTargetHardwareVendor(input, targetVendor) {
@@ -1127,62 +617,28 @@ async function batchCall(params, callFn, onProgress) {
1127
617
 
1128
618
  // src/utils/methodCatalog.ts
1129
619
  var HARDWARE_METHOD_CATALOG = {
1130
- evmGetAddress: { chain: "evm", allNetwork: true, replayAfterTransportFailure: "safe" },
1131
- evmSignTransaction: {
1132
- chain: "evm",
1133
- allNetwork: false,
1134
- replayAfterTransportFailure: "unsafe"
1135
- },
1136
- evmSignMessage: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1137
- evmSignTypedData: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1138
- btcGetAddress: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1139
- btcGetPublicKey: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1140
- btcSignTransaction: {
1141
- chain: "btc",
1142
- allNetwork: false,
1143
- replayAfterTransportFailure: "unsafe"
1144
- },
1145
- btcSignPsbt: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1146
- btcSignMessage: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1147
- btcGetMasterFingerprint: {
1148
- chain: "btc",
1149
- allNetwork: false,
1150
- replayAfterTransportFailure: "safe"
1151
- },
1152
- solGetAddress: { chain: "sol", allNetwork: true, replayAfterTransportFailure: "safe" },
1153
- solSignTransaction: {
1154
- chain: "sol",
1155
- allNetwork: false,
1156
- replayAfterTransportFailure: "unsafe"
1157
- },
1158
- solSignMessage: { chain: "sol", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1159
- tronGetAddress: { chain: "tron", allNetwork: true, replayAfterTransportFailure: "safe" },
1160
- tronSignTransaction: {
1161
- chain: "tron",
1162
- allNetwork: false,
1163
- replayAfterTransportFailure: "unsafe"
1164
- },
1165
- tronSignMessage: { chain: "tron", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1166
- zcashGetFullViewingKey: {
1167
- chain: "zcash",
1168
- allNetwork: false,
1169
- replayAfterTransportFailure: "safe"
1170
- },
1171
- zcashGetShieldedAddress: {
1172
- chain: "zcash",
1173
- allNetwork: false,
1174
- replayAfterTransportFailure: "safe"
1175
- }
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 }
1176
636
  };
1177
637
  var ALL_NETWORK_METHOD_NAMES = Object.entries(HARDWARE_METHOD_CATALOG).filter(([, metadata]) => metadata.allNetwork).map(([method]) => method);
1178
638
  var ALL_NETWORK_METHOD_SET = new Set(ALL_NETWORK_METHOD_NAMES);
1179
639
  function getHardwareMethodMetadata(method) {
1180
640
  return HARDWARE_METHOD_CATALOG[method];
1181
641
  }
1182
- var SAFE_NON_CHAIN_METHODS = /* @__PURE__ */ new Set(["getFeatures", "authenticateDevice"]);
1183
- function canReplayHardwareMethodAfterTransportFailure(method) {
1184
- return getHardwareMethodMetadata(method)?.replayAfterTransportFailure === "safe" || SAFE_NON_CHAIN_METHODS.has(method);
1185
- }
1186
642
  function isAllNetworkMethodName(method) {
1187
643
  return ALL_NETWORK_METHOD_SET.has(method);
1188
644
  }
@@ -1275,11 +731,8 @@ export {
1275
731
  DeviceJobQueue,
1276
732
  EConnectorInteraction,
1277
733
  HARDWARE_METHOD_CATALOG,
1278
- HARDWARE_RUNTIME_ID_PREFIX,
1279
734
  HardwareErrorCode,
1280
- OPERATION_DEFAULT_TTL_MS,
1281
735
  ORPHAN_ELIGIBLE_ERROR_CODES,
1282
- OperationRegistry,
1283
736
  SDK,
1284
737
  TypedEventEmitter,
1285
738
  UI_EVENT,
@@ -1292,41 +745,23 @@ export {
1292
745
  UiRequestRegistry,
1293
746
  batchCall,
1294
747
  buildUnsupportedMethodResponse,
1295
- bytesToHex3 as bytesToHex,
1296
- canReplayHardwareMethodAfterTransportFailure,
748
+ bytesToHex2 as bytesToHex,
1297
749
  compareSemver,
1298
750
  createBridgedConnector,
1299
751
  createCombinedConnector,
1300
- createHardwareLinkId,
1301
- createHardwareOperationId,
1302
- createHardwareSearchTargetId,
1303
752
  createHwkError,
1304
- defaultOriginForCode,
1305
- defaultRecoveryForCode,
1306
753
  deriveDeviceFingerprint,
1307
- deriveWalletId,
1308
754
  detectHardwareVendorFromDescriptor,
1309
755
  enrichErrorMessage,
1310
756
  ensure0x,
1311
757
  failure,
1312
758
  getAllNetworkMethodChain,
1313
759
  getHardwareMethodMetadata,
1314
- hasHardwareRuntimeIdPrefix,
1315
760
  hexToBytes,
1316
761
  isAllNetworkMethodName,
1317
- isHardwareOperationId,
1318
- isHwkRecoveryHint,
1319
762
  isKnownNonTargetHardwareVendor,
1320
- operationMayHaveCompletedParams,
1321
763
  padHex64,
1322
- parseBip32MasterFingerprint,
1323
- parseHardwareRuntimeId,
1324
- prepareSolanaOffchainMessageV1,
1325
764
  rehydrateConnectorError,
1326
- requestBleDeviceSelection,
1327
- requestSaveDeviceBinding,
1328
- resolveHardwareOperationTarget,
1329
- resolveSearchTargetReusePolicy,
1330
765
  runAllNetworkGetAddress,
1331
766
  serializeConnectorError,
1332
767
  stripHex,