@onekeyfe/hwk-adapter-core 1.2.3-alpha.3 → 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 -546
  15. package/dist/index.d.ts +74 -546
  16. package/dist/index.js +81 -616
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +72 -607
  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
@@ -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,27 +118,31 @@ var DeviceJobQueue = class {
148
118
  });
149
119
  return next;
150
120
  }
151
- /** Cancel the running job. `reason` becomes signal.reason. */
152
- cancelActive(deviceId, reason) {
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;
127
+ }
128
+ /** Force cancel the active job. `reason` becomes signal.reason. */
129
+ forceCancelActive(deviceId, reason) {
153
130
  if (!this._active) return false;
154
131
  if (deviceId && this._active.deviceId !== deviceId) return false;
155
- this._active.abortController.abort(reason ?? new Error("Cancelled"));
132
+ this._active.abortController.abort(reason ?? new Error("Force cancelled for recovery"));
156
133
  return true;
157
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
+ }
158
140
  /** Cancel the active job and invalidate queued jobs that have not started. */
159
141
  cancelActiveAndPending(deviceId, reason) {
160
- const cancelReason = reason ?? new Error("Cancelled by cancelActiveAndPending");
161
- if (deviceId) {
162
- let cancelled = false;
163
- for (const job of this._jobs.values()) {
164
- if (job.deviceId === deviceId) {
165
- job.abortController.abort(cancelReason);
166
- cancelled = true;
167
- }
168
- }
169
- return cancelled;
142
+ if (deviceId && this._active && this._active.deviceId !== deviceId) {
143
+ return false;
170
144
  }
171
- this.clear(cancelReason);
145
+ this.clear(reason ?? new Error("Cancelled by cancelActiveAndPending"));
172
146
  return true;
173
147
  }
174
148
  /** Get info about the currently active job, or null if idle. */
@@ -181,6 +155,10 @@ var DeviceJobQueue = class {
181
155
  startedAt: this._active.startedAt
182
156
  };
183
157
  }
158
+ /** True if any job is currently running. */
159
+ isBusy() {
160
+ return this._jobs.size > 0;
161
+ }
184
162
  clear(reason) {
185
163
  const cancelledGeneration = this._generation;
186
164
  this._generation++;
@@ -197,224 +175,6 @@ var DeviceJobQueue = class {
197
175
  }
198
176
  };
199
177
 
200
- // src/utils/hardwareRuntimeId.ts
201
- import { bytesToHex as bytesToHex2, randomBytes } from "@noble/hashes/utils";
202
- var HARDWARE_RUNTIME_ID_PREFIX = "hwk:runtime";
203
- var RANDOM_ID_BYTES = 16;
204
- var RANDOM_ID_PATTERN = /^[0-9a-f]{32}$/;
205
- var KINDS = /* @__PURE__ */ new Set([
206
- "operation",
207
- "search-target",
208
- "link"
209
- ]);
210
- var VENDORS = /* @__PURE__ */ new Set(["trezor", "ledger", "keystone"]);
211
- function create(kind, vendor) {
212
- return `${HARDWARE_RUNTIME_ID_PREFIX}:${kind}:${vendor}:${bytesToHex2(
213
- randomBytes(RANDOM_ID_BYTES)
214
- )}`;
215
- }
216
- function createHardwareOperationId(vendor) {
217
- return create("operation", vendor);
218
- }
219
- function createHardwareSearchTargetId(vendor) {
220
- return create("search-target", vendor);
221
- }
222
- function createHardwareLinkId(vendor) {
223
- return create("link", vendor);
224
- }
225
- function hasHardwareRuntimeIdPrefix(value) {
226
- return typeof value === "string" && value.startsWith(`${HARDWARE_RUNTIME_ID_PREFIX}:`);
227
- }
228
- function parseHardwareRuntimeId(value) {
229
- if (!hasHardwareRuntimeIdPrefix(value)) return void 0;
230
- const parts = value.split(":");
231
- if (parts.length !== 5) return void 0;
232
- const [, , kind, vendor, nonce] = parts;
233
- if (!KINDS.has(kind) || !VENDORS.has(vendor) || !RANDOM_ID_PATTERN.test(nonce)) {
234
- return void 0;
235
- }
236
- return { kind, vendor };
237
- }
238
- function isHardwareOperationId(value) {
239
- return parseHardwareRuntimeId(value)?.kind === "operation";
240
- }
241
-
242
- // src/utils/OperationRegistry.ts
243
- var OPERATION_DEFAULT_TTL_MS = 6e5;
244
- var OperationRegistry = class {
245
- constructor(options) {
246
- this._active = /* @__PURE__ */ new Map();
247
- this._ended = /* @__PURE__ */ new Map();
248
- this._vendor = options.vendor;
249
- this._ttlMs = options.ttlMs ?? OPERATION_DEFAULT_TTL_MS;
250
- this._onEnded = options.onEnded;
251
- }
252
- create(params) {
253
- const now = Date.now();
254
- const operationId = createHardwareOperationId(this._vendor);
255
- const operation = {
256
- operationId,
257
- connectId: params.connectId,
258
- device: params.device,
259
- connectionKeys: Array.from(
260
- new Set(
261
- [params.searchTargetId, params.connectId, ...params.connectionKeys ?? []].filter(
262
- Boolean
263
- )
264
- )
265
- ),
266
- createdAt: now,
267
- lastActiveAt: now
268
- };
269
- const timer = this._createTimer(operationId);
270
- this._active.set(operationId, { ...operation, timer, retainCount: 0 });
271
- return operation;
272
- }
273
- resolve(operationId) {
274
- const active = this._active.get(operationId);
275
- if (!active) {
276
- const ended = this._ended.get(operationId);
277
- if (ended) {
278
- throw createHwkError({
279
- code: 10113 /* OperationEnded */,
280
- message: `Hardware operation has ended (${ended.reason})`,
281
- params: { operationId, reason: ended.reason }
282
- });
283
- }
284
- throw createHwkError({
285
- code: 10112 /* OperationNotFound */,
286
- message: "Hardware operation was not found",
287
- params: { operationId }
288
- });
289
- }
290
- if (active.timer) clearTimeout(active.timer);
291
- active.lastActiveAt = Date.now();
292
- active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
293
- return active;
294
- }
295
- /** Keep an operation alive while one device job is actively using it. */
296
- retain(operationId) {
297
- const active = this.resolve(operationId);
298
- if (active.timer) clearTimeout(active.timer);
299
- active.timer = void 0;
300
- active.retainCount += 1;
301
- let released = false;
302
- return () => {
303
- if (released) return;
304
- released = true;
305
- const current = this._active.get(operationId);
306
- if (!current) return;
307
- current.retainCount = Math.max(0, current.retainCount - 1);
308
- current.lastActiveAt = Date.now();
309
- if (current.retainCount === 0) {
310
- current.timer = this._createTimer(operationId);
311
- }
312
- };
313
- }
314
- /** Return active or tombstoned binding data without refreshing its TTL. */
315
- find(operationId) {
316
- return this._active.get(operationId) ?? this._ended.get(operationId)?.operation;
317
- }
318
- findActiveByConnectionKey(connectionKey) {
319
- if (!connectionKey) return void 0;
320
- return [...this._active.values()].find(
321
- (operation) => operation.connectionKeys.includes(connectionKey)
322
- );
323
- }
324
- /** Replace the live transport binding after the same target was reconnected. */
325
- rebind(operationId, params) {
326
- const active = this._active.get(operationId);
327
- if (!active) {
328
- this.resolve(operationId);
329
- throw new Error("Unreachable operation rebind");
330
- }
331
- if (active.timer) clearTimeout(active.timer);
332
- active.connectId = params.connectId;
333
- active.device = params.device;
334
- active.connectionKeys = Array.from(
335
- new Set([params.connectId, ...params.connectionKeys ?? []].filter(Boolean))
336
- );
337
- active.lastActiveAt = Date.now();
338
- active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
339
- return active;
340
- }
341
- end(operationId, reason) {
342
- const active = this._active.get(operationId);
343
- if (!active) return void 0;
344
- if (active.timer) clearTimeout(active.timer);
345
- this._active.delete(operationId);
346
- this._rememberEnded(active, reason);
347
- this._onEnded?.(active, reason);
348
- return active;
349
- }
350
- endByConnectionKey(connectionKey, reason, exceptOperationId) {
351
- if (!connectionKey) return;
352
- for (const operation of [...this._active.values()]) {
353
- if (operation.operationId === exceptOperationId) continue;
354
- if (operation.connectionKeys.includes(connectionKey)) {
355
- this.end(operation.operationId, reason);
356
- }
357
- }
358
- }
359
- endAll(reason, exceptOperationId) {
360
- for (const operationId of [...this._active.keys()]) {
361
- if (operationId === exceptOperationId) continue;
362
- this.end(operationId, reason);
363
- }
364
- }
365
- _createTimer(operationId) {
366
- const timer = setTimeout(() => {
367
- this.end(operationId, "timeout");
368
- }, this._ttlMs);
369
- timer.unref?.();
370
- return timer;
371
- }
372
- _rememberEnded(operation, reason) {
373
- this._ended.set(operation.operationId, { reason, operation });
374
- if (this._ended.size <= 100) return;
375
- const oldest = this._ended.keys().next().value;
376
- if (oldest) this._ended.delete(oldest);
377
- }
378
- };
379
-
380
- // src/utils/hardwareOperationTarget.ts
381
- function resolveHardwareOperationTarget(positionalTargetId, commonOperationId, expectedVendor) {
382
- const normalizedPositionalTargetId = positionalTargetId ?? void 0;
383
- const normalizedCommonOperationId = commonOperationId || void 0;
384
- const positionalOperationId = isHardwareOperationId(normalizedPositionalTargetId) ? normalizedPositionalTargetId : void 0;
385
- const parsedPositionalTarget = parseHardwareRuntimeId(normalizedPositionalTargetId);
386
- const parsedCommonOperation = parseHardwareRuntimeId(normalizedCommonOperationId);
387
- if (normalizedPositionalTargetId && hasHardwareRuntimeIdPrefix(normalizedPositionalTargetId) && !parsedPositionalTarget) {
388
- return failure(10002 /* InvalidParams */, "Invalid hardware operation target id");
389
- }
390
- if (parsedPositionalTarget?.kind === "link") {
391
- return failure(
392
- 10002 /* InvalidParams */,
393
- "Hardware transport link id cannot be used as an operation target"
394
- );
395
- }
396
- if (normalizedCommonOperationId && parsedCommonOperation?.kind !== "operation") {
397
- return failure(10002 /* InvalidParams */, "Invalid hardware operation id");
398
- }
399
- if (expectedVendor && (parsedPositionalTarget && parsedPositionalTarget.vendor !== expectedVendor || parsedCommonOperation && parsedCommonOperation.vendor !== expectedVendor)) {
400
- return failure(
401
- 10002 /* InvalidParams */,
402
- `Hardware operation does not belong to ${expectedVendor}`
403
- );
404
- }
405
- if (positionalOperationId && normalizedCommonOperationId && positionalOperationId !== normalizedCommonOperationId) {
406
- return failure(10002 /* InvalidParams */, "Conflicting hardware operation ids", {
407
- positionalOperationId,
408
- commonOperationId: normalizedCommonOperationId
409
- });
410
- }
411
- const operationId = normalizedCommonOperationId ?? positionalOperationId;
412
- return success({
413
- operationId,
414
- targetId: operationId ?? normalizedPositionalTargetId
415
- });
416
- }
417
-
418
178
  // src/types/connector.ts
419
179
  var EConnectorInteraction = /* @__PURE__ */ ((EConnectorInteraction2) => {
420
180
  EConnectorInteraction2["Searching"] = "searching";
@@ -430,7 +190,7 @@ function createBridgedConnector(vendor, connectionType, bridge) {
430
190
  return {
431
191
  connectionType,
432
192
  searchDevices: (options) => bridge.searchDevices({ vendor, options }),
433
- connect: (deviceId, options) => bridge.connect({ vendor, deviceId, ...options ? { options } : {} }),
193
+ connect: (deviceId) => bridge.connect({ vendor, deviceId }),
434
194
  disconnect: (sessionId) => bridge.disconnect({ vendor, sessionId }),
435
195
  call: (sessionId, method, callParams) => bridge.call({ vendor, sessionId, method, callParams }),
436
196
  cancel: (sessionId) => bridge.cancel({ vendor, sessionId }),
@@ -571,14 +331,10 @@ function createCombinedConnector(connectors) {
571
331
  });
572
332
  }
573
333
  const searchDevices = async (options = {}) => {
574
- const selectedConnectors = connectors.map((child, index) => ({ child, index })).filter(
575
- ({ child }) => !options.transportType || child.connectionType === options.transportType
576
- );
577
- if (!selectedConnectors.length) return [];
578
334
  const perConnector = [];
579
- await new Promise((resolve, reject) => {
335
+ await new Promise((resolve) => {
580
336
  let finished = false;
581
- let remaining = selectedConnectors.length;
337
+ let remaining = connectors.length;
582
338
  let settleTimer;
583
339
  const finish = () => {
584
340
  if (finished) return;
@@ -586,20 +342,19 @@ function createCombinedConnector(connectors) {
586
342
  if (settleTimer) clearTimeout(settleTimer);
587
343
  resolve();
588
344
  };
589
- selectedConnectors.forEach(({ child, index }) => {
590
- void child.searchDevices(options.purpose ? { purpose: options.purpose } : void 0).then(
345
+ connectors.forEach((child, index) => {
346
+ void child.searchDevices().then(
591
347
  (devices) => devices.map((device) => ({
592
348
  ...device,
593
349
  connectionType: device.connectionType ?? child.connectionType
594
350
  }))
595
- ).catch((error) => {
596
- if (options.transportType) {
597
- finished = true;
598
- if (settleTimer) clearTimeout(settleTimer);
599
- reject(error);
600
- }
601
- return [];
602
- }).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) => {
603
358
  remaining -= 1;
604
359
  if (!finished) {
605
360
  perConnector.push({ index, devices });
@@ -616,12 +371,7 @@ function createCombinedConnector(connectors) {
616
371
  });
617
372
  });
618
373
  perConnector.sort((a, b) => a.index - b.index);
619
- if (!options.transportType) deviceOwner.clear();
620
- else {
621
- for (const [id, owner] of deviceOwner) {
622
- if (owner.connectionType === options.transportType) deviceOwner.delete(id);
623
- }
624
- }
374
+ deviceOwner.clear();
625
375
  const merged = [];
626
376
  perConnector.forEach(({ index, devices }) => {
627
377
  for (const device of devices) {
@@ -631,11 +381,11 @@ function createCombinedConnector(connectors) {
631
381
  });
632
382
  return merged.sort((a, b) => rank(a) - rank(b));
633
383
  };
634
- const resolveOwner = async (deviceId, transportType) => {
635
- if (deviceId && deviceOwner.has(deviceId) && (!transportType || deviceOwner.get(deviceId)?.connectionType === transportType)) {
384
+ const resolveOwner = async (deviceId) => {
385
+ if (deviceId && deviceOwner.has(deviceId)) {
636
386
  return { owner: deviceOwner.get(deviceId), deviceId };
637
387
  }
638
- const devices = await searchDevices({ waitForAll: Boolean(deviceId), transportType });
388
+ const devices = await searchDevices({ waitForAll: Boolean(deviceId) });
639
389
  if (deviceId) {
640
390
  const owner = deviceOwner.get(deviceId);
641
391
  if (!owner)
@@ -646,14 +396,13 @@ function createCombinedConnector(connectors) {
646
396
  if (!first) throw combinedDeviceNotFoundError("Combined connector: no devices found");
647
397
  return { owner: deviceOwner.get(first.connectId), deviceId: first.connectId };
648
398
  };
649
- const connectByExplicitId = async (deviceId, transportType) => {
399
+ const connectByExplicitId = async (deviceId) => {
650
400
  const cachedOwner = deviceOwner.get(deviceId);
651
- if (cachedOwner && (!transportType || cachedOwner.connectionType === transportType)) {
401
+ if (cachedOwner) {
652
402
  return { session: await cachedOwner.connect(deviceId), owner: cachedOwner };
653
403
  }
654
404
  let lastError;
655
405
  for (const child of connectors) {
656
- if (transportType && child.connectionType !== transportType) continue;
657
406
  try {
658
407
  const session = await child.connect(deviceId);
659
408
  deviceOwner.set(deviceId, child);
@@ -675,15 +424,14 @@ function createCombinedConnector(connectors) {
675
424
  // Nominal value only — the per-device `connectionType` is authoritative
676
425
  // for a fused connector.
677
426
  connectionType: connectors[0].connectionType,
678
- availableTransports: [...new Set(connectors.map((child) => child.connectionType))],
679
- searchDevices: (options) => searchDevices(options),
680
- connect: async (deviceId, options) => {
427
+ searchDevices: (options) => searchDevices({ waitForAll: options?.waitForAll }),
428
+ connect: async (deviceId) => {
681
429
  let owner;
682
430
  let session;
683
431
  if (deviceId) {
684
- ({ session, owner } = await connectByExplicitId(deviceId, options?.transportType));
432
+ ({ session, owner } = await connectByExplicitId(deviceId));
685
433
  } else {
686
- const resolved = await resolveOwner(void 0, options?.transportType);
434
+ const resolved = await resolveOwner();
687
435
  owner = resolved.owner;
688
436
  session = await owner.connect(resolved.deviceId);
689
437
  }
@@ -789,147 +537,6 @@ var TypedEventEmitter = class {
789
537
  }
790
538
  };
791
539
 
792
- // src/utils/requestSaveDeviceBinding.ts
793
- async function requestSaveDeviceBinding(emitter, registry, binding, signal) {
794
- const type = UI_REQUEST.REQUEST_SAVE_DEVICE_BINDING;
795
- const declined = (reason) => {
796
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
797
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
798
- payload: { selectionRequestId: binding.selectionRequestId, status: "failed" }
799
- });
800
- return { saved: false, reason };
801
- };
802
- if (!emitter.listenerCount(type)) {
803
- return declined("skipped");
804
- }
805
- if (signal?.aborted) throw signal.reason;
806
- const requestId = registry.createRequestId();
807
- const pending = registry.wait(type, { requestId });
808
- void pending.catch(() => void 0);
809
- const cancel = () => registry.cancel(type, requestId);
810
- signal?.addEventListener("abort", cancel, { once: true });
811
- try {
812
- emitter.emit(type, { type, payload: { ...binding, requestId } });
813
- const response = await pending;
814
- if (signal?.aborted) throw signal.reason;
815
- if (response?.saved !== true) {
816
- return declined(response?.reason ?? "skipped");
817
- }
818
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
819
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
820
- payload: { selectionRequestId: binding.selectionRequestId, status: "saved" }
821
- });
822
- return { saved: true };
823
- } catch (error) {
824
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
825
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
826
- payload: {
827
- selectionRequestId: binding.selectionRequestId,
828
- status: signal?.aborted ? "cancelled" : "failed"
829
- }
830
- });
831
- if (signal?.aborted) throw error;
832
- return { saved: false, reason: "skipped" };
833
- } finally {
834
- signal?.removeEventListener("abort", cancel);
835
- registry.cancel(type, requestId);
836
- }
837
- }
838
-
839
- // src/utils/requestBleDeviceSelection.ts
840
- async function requestBleDeviceSelection({
841
- emitter,
842
- registry,
843
- request,
844
- scan,
845
- signal,
846
- allowUsbFallback = false,
847
- pollIntervalMs = 1500
848
- }) {
849
- const type = UI_REQUEST.REQUEST_SELECT_DEVICE;
850
- if (signal.aborted) throw signal.reason;
851
- if (!emitter.listenerCount(type)) {
852
- throw createHwkError({
853
- code: 10100 /* DeviceNotFound */,
854
- message: "Select a Bluetooth device before continuing"
855
- });
856
- }
857
- const requestId = registry.createRequestId();
858
- let devices = allowUsbFallback ? request.devices.filter((device) => device.connectionType === "ble") : request.devices;
859
- const publishedDevices = /* @__PURE__ */ new Map();
860
- let stopped = false;
861
- let timer;
862
- let wake;
863
- const stop = () => {
864
- stopped = true;
865
- if (timer !== void 0) clearTimeout(timer);
866
- wake?.();
867
- };
868
- const waitForNextScan = () => new Promise((resolve) => {
869
- wake = resolve;
870
- timer = setTimeout(resolve, pollIntervalMs);
871
- if (stopped) resolve();
872
- });
873
- const cancel = () => registry.cancel(type, requestId);
874
- const reply = registry.wait(type, { requestId }).finally(stop);
875
- void reply.catch(() => void 0);
876
- const publish = () => {
877
- for (const device of devices) publishedDevices.set(device.connectId, device);
878
- emitter.emit(type, {
879
- type,
880
- payload: { ...request, devices, requestId, scanning: true }
881
- });
882
- };
883
- signal.addEventListener("abort", cancel, { once: true });
884
- let polling;
885
- try {
886
- publish();
887
- polling = (async () => {
888
- await Promise.resolve();
889
- while (!stopped) {
890
- const snapshot = await scan();
891
- if (stopped || signal.aborted) return;
892
- const usbFallback = allowUsbFallback ? snapshot.find((device2) => device2.connectionType === "usb") : void 0;
893
- if (usbFallback) return usbFallback;
894
- devices = snapshot;
895
- publish();
896
- if (stopped) return;
897
- await waitForNextScan();
898
- }
899
- })();
900
- const userSelection = reply.then((selected) => publishedDevices.get(selected.sdkConnectId));
901
- const device = await Promise.race([
902
- userSelection,
903
- polling.then((usbFallback) => usbFallback ?? userSelection)
904
- ]);
905
- stop();
906
- await polling;
907
- if (signal.aborted) throw signal.reason;
908
- if (!device) {
909
- throw createHwkError({
910
- code: 10100 /* DeviceNotFound */,
911
- message: "Selected Bluetooth device is no longer available"
912
- });
913
- }
914
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
915
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
916
- payload: { selectionRequestId: requestId, status: "verifying" }
917
- });
918
- return { device, requestId };
919
- } catch (error) {
920
- emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
921
- type: UI_REQUEST.DEVICE_BINDING_STATUS,
922
- payload: { selectionRequestId: requestId, status: signal.aborted ? "cancelled" : "failed" }
923
- });
924
- throw error;
925
- } finally {
926
- stop();
927
- signal.removeEventListener("abort", cancel);
928
- registry.cancel(type, requestId);
929
- await polling?.catch(() => void 0);
930
- }
931
- }
932
-
933
540
  // src/utils/semver.ts
934
541
  function compareSemver(a, b) {
935
542
  const pa = a.split(".").map(Number);
@@ -957,96 +564,14 @@ function padHex64(hex) {
957
564
  function hexToBytes(hex) {
958
565
  return nobleHexToBytes(stripHex(hex));
959
566
  }
960
- function bytesToHex3(bytes) {
567
+ function bytesToHex2(bytes) {
961
568
  return nobleBytesToHex(bytes);
962
569
  }
963
570
 
964
- // src/utils/solanaOffchainMessage.ts
965
- var SOLANA_OFFCHAIN_SIGNING_DOMAIN = Uint8Array.of(
966
- 255,
967
- ...Array.from("solana offchain", (character) => character.charCodeAt(0))
968
- );
969
- var SOLANA_PUBLIC_KEY_LENGTH = 32;
970
- var MAX_SOLANA_OFFCHAIN_SIGNERS = 255;
971
- function compareBytes(a, b) {
972
- for (let index = 0; index < a.length; index += 1) {
973
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
974
- if (difference !== 0) return difference;
975
- }
976
- return a.length - b.length;
977
- }
978
- function bytesEqual(a, b) {
979
- return a.length === b.length && a.every((value, index) => value === b[index]);
980
- }
981
- function decodeUtf8Strict(bytes) {
982
- let encoded = "";
983
- for (const value of bytes) {
984
- encoded += `%${value.toString(16).padStart(2, "0")}`;
985
- }
986
- return decodeURIComponent(encoded);
987
- }
988
- function prepareSolanaOffchainMessageV1({
989
- message,
990
- requiredSigners
991
- }) {
992
- if (message.length === 0) {
993
- throw new Error("Solana off-chain message cannot be empty");
994
- }
995
- if (requiredSigners.length === 0 || requiredSigners.length > MAX_SOLANA_OFFCHAIN_SIGNERS) {
996
- throw new Error("Solana off-chain message requires between 1 and 255 signers");
997
- }
998
- let messageText;
999
- try {
1000
- messageText = decodeUtf8Strict(message);
1001
- } catch {
1002
- throw new Error("Solana off-chain message must contain valid UTF-8");
1003
- }
1004
- const signerBytes = requiredSigners.map((signer, index) => {
1005
- let bytes;
1006
- try {
1007
- bytes = hexToBytes(signer);
1008
- } catch {
1009
- throw new Error(`Solana off-chain signer ${index} must be a hex public key`);
1010
- }
1011
- if (bytes.length !== SOLANA_PUBLIC_KEY_LENGTH) {
1012
- throw new Error(`Solana off-chain signer ${index} must be 32 bytes`);
1013
- }
1014
- return bytes;
1015
- });
1016
- signerBytes.sort(compareBytes);
1017
- for (let index = 1; index < signerBytes.length; index += 1) {
1018
- if (bytesEqual(signerBytes[index - 1], signerBytes[index])) {
1019
- throw new Error("Solana off-chain signers must be unique");
1020
- }
1021
- }
1022
- const serializedMessage = new Uint8Array(
1023
- SOLANA_OFFCHAIN_SIGNING_DOMAIN.length + 2 + signerBytes.length * SOLANA_PUBLIC_KEY_LENGTH + message.length
1024
- );
1025
- let offset = 0;
1026
- serializedMessage.set(SOLANA_OFFCHAIN_SIGNING_DOMAIN, offset);
1027
- offset += SOLANA_OFFCHAIN_SIGNING_DOMAIN.length;
1028
- serializedMessage[offset] = 1;
1029
- offset += 1;
1030
- serializedMessage[offset] = signerBytes.length;
1031
- offset += 1;
1032
- for (const signer of signerBytes) {
1033
- serializedMessage.set(signer, offset);
1034
- offset += SOLANA_PUBLIC_KEY_LENGTH;
1035
- }
1036
- serializedMessage.set(message, offset);
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
  }
@@ -1245,11 +731,8 @@ export {
1245
731
  DeviceJobQueue,
1246
732
  EConnectorInteraction,
1247
733
  HARDWARE_METHOD_CATALOG,
1248
- HARDWARE_RUNTIME_ID_PREFIX,
1249
734
  HardwareErrorCode,
1250
- OPERATION_DEFAULT_TTL_MS,
1251
735
  ORPHAN_ELIGIBLE_ERROR_CODES,
1252
- OperationRegistry,
1253
736
  SDK,
1254
737
  TypedEventEmitter,
1255
738
  UI_EVENT,
@@ -1262,41 +745,23 @@ export {
1262
745
  UiRequestRegistry,
1263
746
  batchCall,
1264
747
  buildUnsupportedMethodResponse,
1265
- bytesToHex3 as bytesToHex,
1266
- canReplayHardwareMethodAfterTransportFailure,
748
+ bytesToHex2 as bytesToHex,
1267
749
  compareSemver,
1268
750
  createBridgedConnector,
1269
751
  createCombinedConnector,
1270
- createHardwareLinkId,
1271
- createHardwareOperationId,
1272
- createHardwareSearchTargetId,
1273
752
  createHwkError,
1274
- defaultOriginForCode,
1275
- defaultRecoveryForCode,
1276
753
  deriveDeviceFingerprint,
1277
- deriveWalletId,
1278
754
  detectHardwareVendorFromDescriptor,
1279
755
  enrichErrorMessage,
1280
756
  ensure0x,
1281
757
  failure,
1282
758
  getAllNetworkMethodChain,
1283
759
  getHardwareMethodMetadata,
1284
- hasHardwareRuntimeIdPrefix,
1285
760
  hexToBytes,
1286
761
  isAllNetworkMethodName,
1287
- isHardwareOperationId,
1288
- isHwkRecoveryHint,
1289
762
  isKnownNonTargetHardwareVendor,
1290
- operationMayHaveCompletedParams,
1291
763
  padHex64,
1292
- parseBip32MasterFingerprint,
1293
- parseHardwareRuntimeId,
1294
- prepareSolanaOffchainMessageV1,
1295
764
  rehydrateConnectorError,
1296
- requestBleDeviceSelection,
1297
- requestSaveDeviceBinding,
1298
- resolveHardwareOperationTarget,
1299
- resolveSearchTargetReusePolicy,
1300
765
  runAllNetworkGetAddress,
1301
766
  serializeConnectorError,
1302
767
  stripHex,