@ghostlytools/cli 1.11.0 → 1.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +24 -16
  2. package/dist/assets/{api-CTqIcdu7.js → api-BM3PsXbB.js} +372 -123
  3. package/dist/assets/api-BM3PsXbB.js.map +1 -0
  4. package/dist/assets/{api-B-52sVYp.js → api-CtXgscmK.js} +2 -2
  5. package/dist/assets/{apiKit-CZq4Lq4f.js → apiKit-lCTQ0EBG.js} +17 -7
  6. package/dist/assets/apiKit-lCTQ0EBG.js.map +1 -0
  7. package/dist/assets/appFetch-BKHy5H8J.js +194 -0
  8. package/dist/assets/appFetch-BKHy5H8J.js.map +1 -0
  9. package/dist/assets/{apps-kRsY9S2S.js → apps-DO_gAZgm.js} +1 -1
  10. package/dist/assets/{apps-C_X0zgSG.js → apps-Do26w3c7.js} +44 -40
  11. package/dist/assets/apps-Do26w3c7.js.map +1 -0
  12. package/dist/assets/{arkade-_aaB7VbW.js → arkade-CZrLbz-M.js} +2 -2
  13. package/dist/assets/{arkade-_aaB7VbW.js.map → arkade-CZrLbz-M.js.map} +1 -1
  14. package/dist/assets/{backup-DBg388Ke.js → backup-D21x1f5P.js} +1 -1
  15. package/dist/assets/{backup-OTvrmk-w.js → backup-j47AzDvG.js} +84 -33
  16. package/dist/assets/backup-j47AzDvG.js.map +1 -0
  17. package/dist/assets/{bitcoind-CZchoh43.js → bitcoind-CdSmvy2y.js} +3 -3
  18. package/dist/assets/{bitcoind-CZchoh43.js.map → bitcoind-CdSmvy2y.js.map} +1 -1
  19. package/dist/assets/{bitcoindProvider-DGw3xBSa.js → bitcoindProvider-BvoRh0D5.js} +2 -2
  20. package/dist/assets/{bitcoindProvider-DGw3xBSa.js.map → bitcoindProvider-BvoRh0D5.js.map} +1 -1
  21. package/dist/assets/{buttons-DUu7hxxT.js → buttons-CiGlBVBT.js} +18 -7
  22. package/dist/assets/buttons-CiGlBVBT.js.map +1 -0
  23. package/dist/assets/buttons-D2l2bVCG.js +2 -0
  24. package/dist/assets/{childEnv-BVOQK9EA.js → childEnv-K_IzUqQx.js} +4 -3
  25. package/dist/assets/childEnv-K_IzUqQx.js.map +1 -0
  26. package/dist/assets/{client-DDpZP1R1.js → client-raIncVtF.js} +31 -3
  27. package/dist/assets/client-raIncVtF.js.map +1 -0
  28. package/dist/assets/{codec-DrryGcPT.js → codec-DcG2AeyE.js} +2 -2
  29. package/dist/assets/{codec-DrryGcPT.js.map → codec-DcG2AeyE.js.map} +1 -1
  30. package/dist/assets/endpoint-DarqblYE.js +5052 -0
  31. package/dist/assets/endpoint-DarqblYE.js.map +1 -0
  32. package/dist/assets/{envelope-Q_rMgoE9.js → envelope-Dud6lntA.js} +2 -2
  33. package/dist/assets/{envelope-Q_rMgoE9.js.map → envelope-Dud6lntA.js.map} +1 -1
  34. package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-DRKRSw14.js} +6 -3
  35. package/dist/assets/fedimintSdk-DRKRSw14.js.map +1 -0
  36. package/dist/assets/{fixedHosts-BV5GDiTU.js → fixedHosts-CNX7QiUD.js} +3 -3
  37. package/dist/assets/{fixedHosts-BV5GDiTU.js.map → fixedHosts-CNX7QiUD.js.map} +1 -1
  38. package/dist/assets/{host-BlUzZgQL.js → host-8RskzQgB.js} +306 -84
  39. package/dist/assets/host-8RskzQgB.js.map +1 -0
  40. package/dist/assets/{hyperdhtRelay-BvI_uNZO.js → hyperdhtRelay-uAThbFub.js} +2 -2
  41. package/dist/assets/{hyperdhtRelay-BvI_uNZO.js.map → hyperdhtRelay-uAThbFub.js.map} +1 -1
  42. package/dist/assets/{irohWeb-CqPN8VPY.js → irohWeb-DGelfgDJ.js} +695 -40
  43. package/dist/assets/irohWeb-DGelfgDJ.js.map +1 -0
  44. package/dist/assets/jsonOut-POtMBS_V.js +16 -0
  45. package/dist/assets/jsonOut-POtMBS_V.js.map +1 -0
  46. package/dist/assets/{main-vQjlgEnt.js → main-BC33ooYg.js} +175 -107
  47. package/dist/assets/main-BC33ooYg.js.map +1 -0
  48. package/dist/assets/{mainline-p6HOW7sb.js → mainline-DYrjsS1t.js} +27 -8
  49. package/dist/assets/mainline-DYrjsS1t.js.map +1 -0
  50. package/dist/assets/{networkReason-DMffkiJ6.js → networkReason-n2oBs4by.js} +3 -3
  51. package/dist/assets/{networkReason-DMffkiJ6.js.map → networkReason-n2oBs4by.js.map} +1 -1
  52. package/dist/assets/{nwc-2vH18oNy.js → nwc-Do3VSlIS.js} +6 -5
  53. package/dist/assets/nwc-Do3VSlIS.js.map +1 -0
  54. package/dist/assets/{nwcProvider-DpeDy0bV.js → nwcProvider-Du5aWNIn.js} +6 -3
  55. package/dist/assets/{nwcProvider-DpeDy0bV.js.map → nwcProvider-Du5aWNIn.js.map} +1 -1
  56. package/dist/assets/{ownDid-iKz8u_fM.js → ownDid-CwwYu8s2.js} +3 -3
  57. package/dist/assets/{ownDid-iKz8u_fM.js.map → ownDid-CwwYu8s2.js.map} +1 -1
  58. package/dist/assets/{ownStatus-BlRKnM5F.js → ownStatus-D7dB4zJB.js} +4 -3
  59. package/dist/assets/{ownStatus-BlRKnM5F.js.map → ownStatus-D7dB4zJB.js.map} +1 -1
  60. package/dist/assets/{profiles-B5e0TyvS.js → profiles-NyF5FnYF.js} +82 -6
  61. package/dist/assets/profiles-NyF5FnYF.js.map +1 -0
  62. package/dist/assets/{registry-Cc_PQb3k.js → registry-C734VrO9.js} +1 -1
  63. package/dist/assets/{registry-CnFO2Pp5.js → registry-DKDInr0A.js} +75 -23
  64. package/dist/assets/registry-DKDInr0A.js.map +1 -0
  65. package/dist/assets/{resolve-DI8uAM_Y.js → resolve-3Tqh9AWQ.js} +4 -3
  66. package/dist/assets/resolve-3Tqh9AWQ.js.map +1 -0
  67. package/dist/assets/{server-DdtPxkqI.js → server-B6PQ6iae.js} +430 -868
  68. package/dist/assets/server-B6PQ6iae.js.map +1 -0
  69. package/dist/assets/{src-BnpEQqzk.js → src-ChJijTlM.js} +1139 -243
  70. package/dist/assets/src-ChJijTlM.js.map +1 -0
  71. package/dist/assets/{sshForges-cdIAraDw.js → sshForges-Brf0fslM.js} +2 -2
  72. package/dist/assets/{sshForges-cdIAraDw.js.map → sshForges-Brf0fslM.js.map} +1 -1
  73. package/dist/assets/{translate-kNopA04L.js → translate-xLme9Rdh.js} +10 -8
  74. package/dist/assets/translate-xLme9Rdh.js.map +1 -0
  75. package/dist/assets/{types-C4_KafL_.js → types-Clyb52K2.js} +2 -1
  76. package/dist/assets/types-Clyb52K2.js.map +1 -0
  77. package/dist/assets/{usdt-CDaLhEYh.js → usdt-CSU5KzTV.js} +3 -3
  78. package/dist/assets/{usdt-CDaLhEYh.js.map → usdt-CSU5KzTV.js.map} +1 -1
  79. package/dist/ghostly.mjs +1 -1
  80. package/npm-shrinkwrap.json +3592 -0
  81. package/package.json +5 -3
  82. package/dist/assets/api-CTqIcdu7.js.map +0 -1
  83. package/dist/assets/apiKit-CZq4Lq4f.js.map +0 -1
  84. package/dist/assets/apps-C_X0zgSG.js.map +0 -1
  85. package/dist/assets/backup-OTvrmk-w.js.map +0 -1
  86. package/dist/assets/buttons-4EKtQl-7.js +0 -2
  87. package/dist/assets/buttons-DUu7hxxT.js.map +0 -1
  88. package/dist/assets/childEnv-BVOQK9EA.js.map +0 -1
  89. package/dist/assets/client-DDpZP1R1.js.map +0 -1
  90. package/dist/assets/endpoint-DWHkXWVM.js +0 -419
  91. package/dist/assets/endpoint-DWHkXWVM.js.map +0 -1
  92. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +0 -1
  93. package/dist/assets/host-BlUzZgQL.js.map +0 -1
  94. package/dist/assets/irohWeb-CqPN8VPY.js.map +0 -1
  95. package/dist/assets/main-vQjlgEnt.js.map +0 -1
  96. package/dist/assets/mainline-p6HOW7sb.js.map +0 -1
  97. package/dist/assets/nwc-2vH18oNy.js.map +0 -1
  98. package/dist/assets/profiles-B5e0TyvS.js.map +0 -1
  99. package/dist/assets/registry-CnFO2Pp5.js.map +0 -1
  100. package/dist/assets/resolve-DI8uAM_Y.js.map +0 -1
  101. package/dist/assets/server-DdtPxkqI.js.map +0 -1
  102. package/dist/assets/src-BnpEQqzk.js.map +0 -1
  103. package/dist/assets/translate-kNopA04L.js.map +0 -1
  104. package/dist/assets/types-C4_KafL_.js.map +0 -1
@@ -1,11 +1,11 @@
1
- import { $n as engineError, Bi as IdentityExchange, Dn as requestLnurlInvoice, Gi as identityRevocationValue, Gr as transferEnded, Ha as fileMessageText, J as meshMessageRef, Ji as newIdentityBinding, Ki as identityStatement, Ku as budgetRetryMs, Li as IDENTITY_MAX_VALIDITY, On as resolveLightningDestination, Ri as IDENTITY_REVOCATION_LABEL, Ui as emptyIdentityLedger, Ur as FileUplink, Vi as boundIdentityDisplay, Vr as ChatFiles, Wi as identityRefusal, Xi as revokesIdentity, Yi as receivedIdentityStatus, Za as RateWindow, _o as replySnippet, aa as irohRelayUrl, an as WALLET_NETWORKS, ar as GROUP_WANT_NO_FRAME, cr as isGroupMessageId, dn as walletNetworkOf, dr as readGroupWant, er as engineText, fd as fromBase64Url, fr as readGroupWantNo, hd as toBase64Url, ia as irohDescriptor, kn as decodeBolt11, md as randomBytes, nr as GROUP_FILE_LIMITS, or as fetchesByItself, qi as isIdentityBinding, qu as isDiscoveryBudgetError, ra as dialableIrohRelay, rr as GROUP_HAVE_FRAME, sr as groupFileFallback, ur as readGroupHave, zi as IdentityCheckUnavailable } from "./src-BnpEQqzk.js";
2
- import { a as describeProvider, c as offeredIn, d as sourceProblem, n as PROVIDER_PLATFORMS, o as isNothingSpentError, s as networkMode, t as NothingSpentError, u as redact } from "./types-C4_KafL_.js";
3
- import { r as nwcWalletName, t as nwc } from "./nwcProvider-DpeDy0bV.js";
4
- import { b as transact, p as fileStore, s as STORES, u as databaseName, x as wrap, y as store } from "./idb-CEuoNsTv.js";
5
- import { a as sealSeed, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, m as openSecret, o as unsealSeed, t as networkReason } from "./networkReason-DMffkiJ6.js";
6
- import { f as FILE_BYTES_STEP, o as fileBytes, s as fileBytesOf } from "./fileBytes-BLPZq9YU.js";
1
+ import { $i as receivedIdentityStatus, An as decodeBolt11, Bn as withoutAudioMetadata, Gi as boundIdentityDisplay, Gn as PICTURE_METADATA_LIMITS, Gr as ChatFiles, Hi as IDENTITY_REVOCATION_LABEL, Hn as videoMetadataPatches, Ji as identityRefusal, Ka as fileMessageText, Kn as isStrippedPicture, On as requestLnurlInvoice, Qi as newIdentityBinding, Ui as IdentityCheckUnavailable, Un as withoutVideoMetadata, Vi as IDENTITY_MAX_VALIDITY, Wi as IdentityExchange, Wn as NO_PICTURE_METADATA, Xi as identityStatement, Xu as budgetRetryMs, Y as meshMessageRef, Yi as identityRevocationValue, Yr as transferEnded, Zi as isIdentityBinding, Zu as isDiscoveryBudgetError, _d as fromBase64Url, bd as toBase64Url, ca as irohDescriptor, dr as groupFileFallback, ea as revokesIdentity, fd as dropLoneJoiners, fn as walletNetworkOf, fr as isGroupMessageId, gr as readGroupWantNo, hd as stripHidden, hr as readGroupWant, ir as engineText, kn as resolveLightningDestination, la as irohRelayUrl, lr as GROUP_WANT_NO_FRAME, mr as readGroupHave, on as WALLET_NETWORKS, or as GROUP_FILE_LIMITS, pd as hasVisible, qi as emptyIdentityLedger, qn as stripPictureMetadata, qr as FileUplink, rr as engineError, sa as dialableIrohRelay, sr as GROUP_HAVE_FRAME, to as RateWindow, ur as fetchesByItself, xo as replySnippet, yd as randomBytes, zn as audioMetadataPatches } from "./src-ChJijTlM.js";
2
+ import { a as describeProvider, c as offeredIn, d as sourceProblem, n as PROVIDER_PLATFORMS, o as isNothingSpentError, s as networkMode, t as NothingSpentError, u as redact } from "./types-Clyb52K2.js";
3
+ import { r as nwcWalletName, t as nwc } from "./nwcProvider-Du5aWNIn.js";
4
+ import { b as transact, f as errorLine, p as fileStore, s as STORES, u as databaseName, x as wrap, y as store } from "./idb-CEuoNsTv.js";
5
+ import { a as sealSeed, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, m as openSecret, o as unsealSeed, t as networkReason } from "./networkReason-n2oBs4by.js";
6
+ import { f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf } from "./fileBytes-BLPZq9YU.js";
7
7
  import { t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
8
- import { c as boundedIdentityFetch, l as verifyIdentity } from "./ownDid-iKz8u_fM.js";
8
+ import { c as boundedIdentityFetch, l as verifyIdentity } from "./ownDid-CwwYu8s2.js";
9
9
  import { sha256 } from "@noble/hashes/sha2.js";
10
10
  import { validateMnemonic } from "@scure/bip39";
11
11
  import { wordlist } from "@scure/bip39/wordlists/english.js";
@@ -173,8 +173,8 @@ function iceServerSetting(server) {
173
173
  //#endregion
174
174
  //#region ../browser/src/engine/paymentAdapters/providers/breezDatabases.ts
175
175
  var netOf = (network) => network === "bitcoin" || network === "mainnet" ? "mainnet" : "regtest";
176
- var hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
177
- var digest = (text) => hex(sha256(new TextEncoder().encode(text))).slice(0, 16);
176
+ var hex$2 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
177
+ var digest = (text) => hex$2(sha256(new TextEncoder().encode(text))).slice(0, 16);
178
178
  /** What a Breez database name looks like, old or new: nothing about the seed or the profile shows in it. */
179
179
  var BREEZ_DATABASE = /^ghostly-breez-(mainnet|regtest)-[0-9a-f]{16}$/;
180
180
  /** The name every profile of the origin used for this phrase before databases were per profile. */
@@ -316,6 +316,92 @@ async function dropBreezDatabase(name, options = {}) {
316
316
  }).catch(() => {});
317
317
  }
318
318
  //#endregion
319
+ //#region ../browser/src/engine/paymentAdapters/providers/breezSdk.ts
320
+ var loading$1;
321
+ /** Loads the WebAssembly once, on first use: profiles that never pick Breez never fetch its 12.8 MB. */
322
+ function loadBreezSdk() {
323
+ return loading$1 ??= (async () => {
324
+ const breez = await import("./web-DwgdhfcY.js");
325
+ await breez.default();
326
+ return { async connect({ network, mnemonic, apiKey, storage }) {
327
+ const config = breez.defaultConfig(network);
328
+ if (apiKey) config.apiKey = apiKey;
329
+ return breez.connect({
330
+ config,
331
+ seed: {
332
+ type: "mnemonic",
333
+ mnemonic
334
+ },
335
+ storageDir: storage
336
+ });
337
+ } };
338
+ })().catch((error) => {
339
+ loading$1 = void 0;
340
+ throw error;
341
+ });
342
+ }
343
+ var hex$1 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
344
+ var breezNetwork = (network) => network === "bitcoin" ? "mainnet" : "regtest";
345
+ var DISCONNECT_MS = 1e4;
346
+ /** One SDK instance per wallet storage: two over one database would each think the leaves are theirs. */
347
+ var open = /* @__PURE__ */ new Map();
348
+ /**
349
+ * Opens the Breez wallet of this seed on this network, or shares the one already open (the Spark rail and the
350
+ * Breez Lightning source of the same seed are one wallet). `release` gives this user's share back; the last one
351
+ * disconnects the SDK. `storage`: the database it opened, which `forgetBreez` deletes when the wallet is removed.
352
+ */
353
+ async function openBreez(params, sdk = loadBreezSdk, storage = breezDatabase) {
354
+ const name = await storage(params.network, params.mnemonic);
355
+ const key = `${name}|${params.apiKey ? hex$1(sha256(new TextEncoder().encode(params.apiKey))).slice(0, 8) : ""}`;
356
+ let entry = open.get(key);
357
+ if (!entry) {
358
+ const wallet = sdk().then((module) => module.connect({
359
+ network: breezNetwork(params.network),
360
+ mnemonic: params.mnemonic,
361
+ apiKey: params.apiKey,
362
+ storage: name
363
+ }));
364
+ entry = {
365
+ wallet,
366
+ refs: 0
367
+ };
368
+ open.set(key, entry);
369
+ wallet.catch(() => {
370
+ if (open.get(key) === entry) open.delete(key);
371
+ });
372
+ }
373
+ entry.refs++;
374
+ const held = entry;
375
+ let wallet;
376
+ try {
377
+ wallet = await held.wallet;
378
+ } catch (error) {
379
+ held.refs--;
380
+ throw error;
381
+ }
382
+ let released = false;
383
+ return {
384
+ wallet,
385
+ storage: name,
386
+ release: async () => {
387
+ if (released) return;
388
+ released = true;
389
+ if (--held.refs > 0) return;
390
+ if (open.get(key) === held) open.delete(key);
391
+ await Promise.race([wallet.disconnect(), new Promise((resolve) => setTimeout(resolve, DISCONNECT_MS))]);
392
+ }
393
+ };
394
+ }
395
+ /** Whether a wallet of this storage is open here (the Spark rail and a Breez card of one seed share it). */
396
+ var breezOpen = (storage) => [...open.keys()].some((key) => key.startsWith(`${storage}|`));
397
+ /**
398
+ * A wallet was removed: its Breez databases go, unless another user in this profile still has them open (a Breez
399
+ * Lightning card on the Spark wallet's own phrase). That one deletes them when it is removed in turn.
400
+ */
401
+ async function forgetBreez(storage) {
402
+ if (!breezOpen(storage)) await dropBreezDatabase(storage);
403
+ }
404
+ //#endregion
319
405
  //#region ../browser/src/engine/askBackoff.ts
320
406
  /**
321
407
  * A growing wait with a cap, for whatever a wallet asks about again until it gets an answer: a Cashu melt or swap whose
@@ -584,6 +670,8 @@ var ProviderSources = class {
584
670
  answeredMeanwhile = false;
585
671
  /** An answer to another call already brought a read since the last read that answered: the next ones wait their turn. */
586
672
  answerRead = false;
673
+ /** The balance changed while a read was under way (`balanceChanged`): it may say the old one, so one more follows it. */
674
+ changedMeanwhile = false;
587
675
  view = {
588
676
  mode: "mainnet",
589
677
  status: "none",
@@ -714,6 +802,21 @@ var ProviderSources = class {
714
802
  }
715
803
  this.refresh();
716
804
  }
805
+ /**
806
+ * What the connected source holds changed (a payment through it went through, an invoice of ours was seen paid): its
807
+ * balance is read now, failed reads or not, instead of on its timer: the card, the wallet's total and the Send
808
+ * picker would show the balance from before it for up to `refreshMs`. A read already under way may have started
809
+ * before: one more comes right after it, never two at once. It is also the one read an answer brings (`answered`).
810
+ */
811
+ balanceChanged(provider) {
812
+ if (this.stopped || provider !== this.provider || !this.options.refresh) return;
813
+ this.answerRead = true;
814
+ if (this.reading) {
815
+ this.changedMeanwhile = true;
816
+ return;
817
+ }
818
+ this.refresh();
819
+ }
717
820
  async connect(eager = false) {
718
821
  clearTimeout(this.retry);
719
822
  if (this.stopped || this.provider) return;
@@ -829,18 +932,31 @@ var ProviderSources = class {
829
932
  };
830
933
  }
831
934
  /**
832
- * Whether the saved source is this provider with these very settings (the same wallet added twice). Its secrets are
833
- * unsealed here to compare, and never leave.
935
+ * Whether the saved source is this provider reaching the same wallet (the same wallet added twice): the provider's
936
+ * `wallet` says which one (an NWC URI spelled another way, or another app connection to it, is the same), else these
937
+ * very settings. Its secrets are unsealed here to compare, and never leave.
834
938
  */
835
939
  async holds(providerId, settings) {
836
940
  const stored = this.stored;
837
941
  if (!stored || stored.providerId !== providerId) return false;
942
+ const unseal = async () => stored.secrets ? JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? "")) : {};
943
+ const wallet = this.find(providerId)?.wallet;
944
+ if (wallet) {
945
+ const secrets = await unseal();
946
+ try {
947
+ return wallet({
948
+ config: stored.config,
949
+ secrets
950
+ }) === wallet(settings);
951
+ } catch {
952
+ return false;
953
+ }
954
+ }
838
955
  const same = (a, b) => {
839
956
  const keys = Object.keys(a).sort();
840
957
  return JSON.stringify(keys) === JSON.stringify(Object.keys(b).sort()) && keys.every((k) => a[k] === b[k]);
841
958
  };
842
- if (!same(stored.config, settings.config)) return false;
843
- return same(stored.secrets ? JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? "")) : {}, settings.secrets);
959
+ return same(stored.config, settings.config) && same(await unseal(), settings.secrets);
844
960
  }
845
961
  /**
846
962
  * Changes the `changeable` fields (a server address) of this mode's saved source, keeping its sealed
@@ -1054,10 +1170,14 @@ var ProviderSources = class {
1054
1170
  ...was,
1055
1171
  ...after
1056
1172
  }).some((key) => was[key] !== after[key])) this.options.changed();
1057
- if (this.provider) {
1058
- clearTimeout(this.timer);
1059
- this.timer = setTimeout(() => void this.refresh(), wait);
1173
+ if (!this.provider) return;
1174
+ clearTimeout(this.timer);
1175
+ if (this.changedMeanwhile && !this.reading) {
1176
+ this.changedMeanwhile = false;
1177
+ this.refresh();
1178
+ return;
1060
1179
  }
1180
+ this.timer = setTimeout(() => void this.refresh(), wait);
1061
1181
  }
1062
1182
  /** Keeps the balance read, for the next start: written only when it changed. */
1063
1183
  remember({ balance, unconfirmed }) {
@@ -1082,6 +1202,7 @@ var ProviderSources = class {
1082
1202
  clearTimeout(this.retry);
1083
1203
  this.reads.forget("balance");
1084
1204
  this.answerRead = false;
1205
+ this.changedMeanwhile = false;
1085
1206
  this.controller.abort();
1086
1207
  this.controller = new AbortController();
1087
1208
  const provider = this.provider;
@@ -1481,7 +1602,8 @@ var LightningService = class {
1481
1602
  paying += 1;
1482
1603
  try {
1483
1604
  const result = await quote.provider.payInvoice(quote.invoice, quote.maxFee, context.note);
1484
- this.sources.answered(quote.provider);
1605
+ if (result.state === "paid") this.sources.balanceChanged(quote.provider);
1606
+ else this.sources.answered(quote.provider);
1485
1607
  op = result.state === "paid" ? {
1486
1608
  ...op,
1487
1609
  state: "paid",
@@ -1500,6 +1622,7 @@ var LightningService = class {
1500
1622
  state: "failed",
1501
1623
  error: redact(error)
1502
1624
  });
1625
+ await this.showRecent();
1503
1626
  throw error;
1504
1627
  }
1505
1628
  op = {
@@ -1511,9 +1634,18 @@ var LightningService = class {
1511
1634
  paying -= 1;
1512
1635
  }
1513
1636
  await this.put(op);
1637
+ await this.showRecent();
1514
1638
  if (op.state !== "paid") this.schedule(OUT_POLL_MS);
1515
1639
  return op.state === "paid";
1516
1640
  }
1641
+ /**
1642
+ * A payment ended (paid, refused, or left to be checked): the recent list says so now. It was read again only by a
1643
+ * later pass, which a balance that changed brought: one refused right after a paid one kept the paid one first. A
1644
+ * read that fails leaves it to the next pass: the payment's own outcome is what the caller hears.
1645
+ */
1646
+ async showRecent() {
1647
+ if (await this.loadRecent().catch(() => false)) this.events.changed();
1648
+ }
1517
1649
  /** The Cashu wallet settled a melt it had left pending. */
1518
1650
  async reportPaymentResolved(invoice, paid, context = {}) {
1519
1651
  const hash = decodeBolt11(invoice)?.paymentHash;
@@ -1601,6 +1733,7 @@ var LightningService = class {
1601
1733
  error: outcome === "failed" ? "The payment did not go through" : void 0,
1602
1734
  settledAt: Date.now()
1603
1735
  });
1736
+ if (outcome === "paid") this.sources.balanceChanged(provider);
1604
1737
  this.events.resolved(op, outcome === "paid");
1605
1738
  } catch {
1606
1739
  missed(op);
@@ -1640,6 +1773,7 @@ var LightningService = class {
1640
1773
  state: "paid",
1641
1774
  settledAt: Date.now()
1642
1775
  });
1776
+ this.sources.balanceChanged(provider);
1643
1777
  this.events.received(op);
1644
1778
  } else if (status.state === "expired" || op.expiresAt + INVOICE_PACE.expiryGraceMs < Date.now()) await this.put({
1645
1779
  ...op,
@@ -1666,6 +1800,7 @@ var LightningService = class {
1666
1800
  error: status.state === "failed" ? "The payment did not go through" : void 0,
1667
1801
  settledAt: Date.now()
1668
1802
  });
1803
+ if (status.state === "paid") this.sources.balanceChanged(provider);
1669
1804
  this.events.resolved(op, status.state === "paid");
1670
1805
  }
1671
1806
  } catch {
@@ -1774,6 +1909,278 @@ function shownExpiredAt(op) {
1774
1909
  var normalizePhrase = (text = "") => text.trim().toLowerCase().split(/\s+/).join(" ");
1775
1910
  var isRecoveryPhrase = (text) => validateMnemonic(normalizePhrase(text), wordlist);
1776
1911
  //#endregion
1912
+ //#region ../browser/src/engine/paymentAdapters/providers/breez.ts
1913
+ var BREEZ_SOURCE = "breez";
1914
+ /**
1915
+ * Where the Breez source is offered: Mainnet ("bitcoin", with the person's Breez API key, which the form requires
1916
+ * there) and Breez and Lightspark's hosted regtest (no API key).
1917
+ */
1918
+ var BREEZ_NETWORKS = ["bitcoin", "regtest"];
1919
+ /** WebAssembly and HTTPS only: the page, the extension's offscreen document and Tauri's WebView all run it. */
1920
+ var BREEZ_PLATFORMS = [
1921
+ "web",
1922
+ "extension",
1923
+ "desktop"
1924
+ ];
1925
+ var INVOICE_EXPIRY_SECS = 3600;
1926
+ /** How long `payInvoice` waits for the payment to settle before answering `pending`. */
1927
+ var COMPLETION_SECS = 30;
1928
+ /** A fee shown to the person is paid with the same prepared payment for this long, then prepared again. */
1929
+ var QUOTE_MS = 6e4;
1930
+ /** Payments read to find one by its hash: newest first, bounded. */
1931
+ var PAGE = 100;
1932
+ var PAGES = 10;
1933
+ /** Without any record of a payment, it is called failed only this long after its invoice expired. */
1934
+ var LOST_AFTER_MS = 36e5;
1935
+ var hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1936
+ var sats = (value) => {
1937
+ const n = Number(value);
1938
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error("Breez returned an invalid amount");
1939
+ return n;
1940
+ };
1941
+ var message = (error) => error instanceof Error ? error.message : typeof error === "string" ? error : "Breez refused the payment";
1942
+ /**
1943
+ * The idempotency key of one attempt at paying one invoice: asking the SDK twice with it pays once.
1944
+ * A new attempt (after one that failed) gets a new key, or the SDK would only hand back the failure.
1945
+ */
1946
+ function idempotencyKey(paymentHash, attempt) {
1947
+ const b = sha256(new TextEncoder().encode(`ghostly-breez-pay:${paymentHash}:${attempt}`)).slice(0, 16);
1948
+ b[6] = b[6] & 15 | 64;
1949
+ b[8] = b[8] & 63 | 128;
1950
+ const h = hex(b);
1951
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
1952
+ }
1953
+ /** The payment hash a Breez payment is about, when it is one (Lightning, or a Spark HTLC). */
1954
+ function hashOf(payment) {
1955
+ const details = payment.details;
1956
+ if (details?.type === "lightning") return details.htlcDetails.paymentHash;
1957
+ if (details?.type === "spark") return details.htlcDetails?.paymentHash;
1958
+ }
1959
+ function preimageOf(payment) {
1960
+ const details = payment.details;
1961
+ return details?.type === "lightning" ? details.htlcDetails.preimage : details?.type === "spark" ? details.htlcDetails?.preimage : void 0;
1962
+ }
1963
+ /**
1964
+ * Lightning through the Breez SDK, nodeless: a self-custodial wallet on Spark whose seed Ghostly
1965
+ * generated (or the person restored) and keeps sealed. Invoices are received and paid through Breez's
1966
+ * and Lightspark's Spark service providers; the sats are the seed's.
1967
+ *
1968
+ * Nothing is reported by itself: the engine polls `invoiceStatus` and `paymentStatus`, which find a
1969
+ * payment by its hash in the wallet's history.
1970
+ */
1971
+ var BreezLightning = class BreezLightning {
1972
+ wallet;
1973
+ network;
1974
+ release;
1975
+ storage;
1976
+ capabilities = {
1977
+ receive: true,
1978
+ send: true,
1979
+ balance: true,
1980
+ lookup: true
1981
+ };
1982
+ /** The prepared payment behind a fee just shown: `payInvoice` pays exactly that one while it is fresh. */
1983
+ quotes = /* @__PURE__ */ new Map();
1984
+ closed = false;
1985
+ /** `storage`: the Breez database this card opened (`breezDatabase`). */
1986
+ constructor(wallet, network, release, storage) {
1987
+ this.wallet = wallet;
1988
+ this.network = network;
1989
+ this.release = release;
1990
+ this.storage = storage;
1991
+ }
1992
+ static async connect(params, sdk = loadBreezSdk, storage = breezDatabase) {
1993
+ const opened = await openBreez(params, sdk, storage);
1994
+ return new BreezLightning(opened.wallet, params.network, opened.release, opened.storage);
1995
+ }
1996
+ async info() {
1997
+ const { balanceSats } = await this.wallet.getInfo({ ensureSynced: false });
1998
+ return {
1999
+ network: this.network,
2000
+ balance: sats(balanceSats)
2001
+ };
2002
+ }
2003
+ async createInvoice(amount, memo) {
2004
+ const { paymentRequest } = await this.wallet.receivePayment({ paymentMethod: {
2005
+ type: "bolt11Invoice",
2006
+ description: (memo ?? "").slice(0, 100),
2007
+ amountSats: amount,
2008
+ expirySecs: INVOICE_EXPIRY_SECS
2009
+ } });
2010
+ const decoded = decodeBolt11(paymentRequest);
2011
+ if (!decoded?.paymentHash || decoded.amountSat !== amount) throw new Error("Breez returned an invoice that does not match the request");
2012
+ return {
2013
+ invoice: decoded.invoice,
2014
+ paymentHash: decoded.paymentHash,
2015
+ amount,
2016
+ expiresAt: decoded.expiresAt * 1e3
2017
+ };
2018
+ }
2019
+ async invoiceStatus(invoice) {
2020
+ const payment = await this.find("receive", invoice.paymentHash, invoice.invoice);
2021
+ if (payment?.status === "completed") return {
2022
+ state: "paid",
2023
+ amount: sats(payment.amount)
2024
+ };
2025
+ if (payment?.status === "pending") return { state: "open" };
2026
+ return { state: invoice.expiresAt < Date.now() ? "expired" : "open" };
2027
+ }
2028
+ /** Prepares the payment (nothing is sent) and keeps it for `payInvoice`: its fee is the one shown. */
2029
+ async estimateFee(invoice, amount) {
2030
+ const prepared = await this.prepare(invoice, amount);
2031
+ this.quotes.set(decodeBolt11(invoice)?.invoice ?? invoice, {
2032
+ prepared,
2033
+ at: Date.now()
2034
+ });
2035
+ return this.feeOf(prepared);
2036
+ }
2037
+ async payInvoice(invoice, maxFee) {
2038
+ const decoded = decodeBolt11(invoice);
2039
+ if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError("That is not an invoice Breez can pay");
2040
+ const hash = decoded.paymentHash, amount = decoded.amountSat, key = decoded.invoice;
2041
+ let prepared, attempt;
2042
+ try {
2043
+ if (this.closed) throw new Error("The Breez wallet is closed");
2044
+ const previous = await this.history("send", hash, decoded.invoice, decoded.createdAt);
2045
+ const live = previous.find((p) => p.status !== "failed");
2046
+ if (live) return this.result(live);
2047
+ attempt = previous.length;
2048
+ const quote = this.quotes.get(key);
2049
+ this.quotes.delete(key);
2050
+ prepared = quote && Date.now() - quote.at < QUOTE_MS ? quote.prepared : await this.prepare(decoded.invoice, amount);
2051
+ const fee = this.feeOf(prepared);
2052
+ if (fee > maxFee) throw new Error(`The Lightning fee (${fee} sats) is above your limit (${maxFee})`);
2053
+ const { balanceSats } = await this.wallet.getInfo({ ensureSynced: false });
2054
+ if (sats(balanceSats) < amount + fee) throw new Error(`Not enough sats in the Breez wallet (${sats(balanceSats)}; ${amount + fee} needed)`);
2055
+ } catch (error) {
2056
+ throw isNothingSpentError(error) ? error : new NothingSpentError(message(error));
2057
+ }
2058
+ const { payment } = await this.wallet.sendPayment({
2059
+ prepareResponse: prepared,
2060
+ options: {
2061
+ type: "bolt11Invoice",
2062
+ preferSpark: false,
2063
+ completionTimeoutSecs: COMPLETION_SECS
2064
+ },
2065
+ idempotencyKey: idempotencyKey(hash, attempt)
2066
+ });
2067
+ return this.result(payment);
2068
+ }
2069
+ async paymentStatus(ref) {
2070
+ const decoded = decodeBolt11(ref.invoice);
2071
+ let payment = await this.find("send", ref.paymentHash, ref.invoice, decoded?.createdAt);
2072
+ if (!payment && ref.ref) {
2073
+ const byId = (await this.wallet.getPayment({ paymentId: ref.ref }).catch(() => void 0))?.payment;
2074
+ if (byId && hashOf(byId) === ref.paymentHash) payment = byId;
2075
+ }
2076
+ if (!payment) {
2077
+ await this.wallet.syncWallet({});
2078
+ payment = await this.find("send", ref.paymentHash, ref.invoice, decoded?.createdAt);
2079
+ }
2080
+ if (!payment) return { state: (decoded ? decoded.expiresAt * 1e3 + LOST_AFTER_MS < Date.now() : false) ? "failed" : "pending" };
2081
+ const state = payment.status === "completed" ? "paid" : payment.status === "failed" ? "failed" : "pending";
2082
+ return {
2083
+ state,
2084
+ fee: state === "paid" ? sats(payment.fees) : void 0,
2085
+ preimage: preimageOf(payment)
2086
+ };
2087
+ }
2088
+ async close() {
2089
+ if (this.closed) return;
2090
+ this.closed = true;
2091
+ this.quotes.clear();
2092
+ await this.release();
2093
+ }
2094
+ /** The card is removed: closed, and its Breez databases deleted unless the Spark wallet of this phrase has them open. */
2095
+ async forget() {
2096
+ await this.close();
2097
+ await forgetBreez(this.storage);
2098
+ }
2099
+ async prepare(invoice, amount) {
2100
+ const prepared = await this.wallet.prepareSendPayment({ paymentRequest: {
2101
+ type: "input",
2102
+ input: invoice
2103
+ } });
2104
+ const method = prepared.paymentMethod;
2105
+ if (method.type !== "bolt11Invoice") throw new Error("Breez would not pay this as a Lightning invoice");
2106
+ if (method.invoiceDetails.paymentHash !== decodeBolt11(invoice)?.paymentHash || sats(prepared.amount) !== amount) throw new Error("Breez prepared a payment that does not match the invoice");
2107
+ return prepared;
2108
+ }
2109
+ feeOf(prepared) {
2110
+ if (prepared.paymentMethod.type !== "bolt11Invoice") throw new Error("Breez would not pay this as a Lightning invoice");
2111
+ return sats(prepared.paymentMethod.lightningFeeSats);
2112
+ }
2113
+ /** `failed` is never an answer here: a payment the SDK gave up on is pending until `paymentStatus` says so. */
2114
+ result(payment) {
2115
+ if (payment.status === "completed") return {
2116
+ state: "paid",
2117
+ fee: sats(payment.fees),
2118
+ preimage: preimageOf(payment),
2119
+ ref: payment.id
2120
+ };
2121
+ return {
2122
+ state: "pending",
2123
+ ref: payment.id
2124
+ };
2125
+ }
2126
+ async find(type, hash, invoice, createdAt) {
2127
+ const found = await this.history(type, hash, invoice, createdAt);
2128
+ return found.find((p) => p.status === "completed") ?? found.find((p) => p.status === "pending") ?? found[0];
2129
+ }
2130
+ /** This wallet's payments of this hash, newest first. Only payments since the invoice was made are read. */
2131
+ async history(type, hash, invoice, createdAt = decodeBolt11(invoice)?.createdAt) {
2132
+ const found = [];
2133
+ for (let page = 0; page < PAGES; page++) {
2134
+ const { payments } = await this.wallet.listPayments({
2135
+ typeFilter: [type],
2136
+ fromTimestamp: createdAt ? createdAt - 600 : void 0,
2137
+ offset: page * PAGE,
2138
+ limit: PAGE,
2139
+ sortAscending: false
2140
+ });
2141
+ found.push(...payments.filter((p) => hashOf(p) === hash));
2142
+ if (payments.length < PAGE) break;
2143
+ }
2144
+ return found;
2145
+ }
2146
+ };
2147
+ /** The descriptor, with the SDK it loads (tests hand it a fake). */
2148
+ var breezDescriptor = (sdk = loadBreezSdk) => ({
2149
+ id: BREEZ_SOURCE,
2150
+ label: "Breez (Spark)",
2151
+ kind: "lightning",
2152
+ description: "A self-custodial Lightning wallet on Spark, through the Breez SDK. Its recovery phrase is sealed on this device; you hold the sats.",
2153
+ networks: BREEZ_NETWORKS,
2154
+ platforms: BREEZ_PLATFORMS,
2155
+ fields: [{
2156
+ name: "mnemonic",
2157
+ label: "Recovery phrase",
2158
+ kind: "secret",
2159
+ placeholder: "twelve words…",
2160
+ help: "Made by Ghostly for a new wallet, or yours to restore one."
2161
+ }, {
2162
+ name: "apiKey",
2163
+ label: "Breez API key",
2164
+ kind: "secret",
2165
+ optional: true,
2166
+ help: "Required on Mainnet (free, from Breez). Not needed in Testnet (regtest)."
2167
+ }],
2168
+ experimental: true,
2169
+ validate({ secrets }, mode) {
2170
+ if (!isRecoveryPhrase(secrets.mnemonic ?? "")) throw new Error("That is not a valid recovery phrase");
2171
+ if (mode === "mainnet" && !secrets.apiKey?.trim()) throw new Error("Breez needs an API key on Mainnet");
2172
+ },
2173
+ async create({ secrets }, host) {
2174
+ const network = host.mode === "mainnet" ? "bitcoin" : "regtest";
2175
+ return BreezLightning.connect({
2176
+ network,
2177
+ mnemonic: normalizePhrase(secrets.mnemonic),
2178
+ apiKey: secrets.apiKey?.trim() || void 0
2179
+ }, sdk);
2180
+ }
2181
+ });
2182
+ var breez = breezDescriptor();
2183
+ //#endregion
1777
2184
  //#region ../browser/src/engine/paymentAdapters/providers/lightningCards.ts
1778
2185
  /** The card of Lightning through the Cashu mints: at most one per network, shown while the network has mints. */
1779
2186
  var CASHU_CARD = "cashu";
@@ -1844,9 +2251,19 @@ var ALIAS_IN_NAME = 20;
1844
2251
  * ends, with "…", never in the middle of a word.
1845
2252
  */
1846
2253
  function defaultCardName(providerId, alias, short) {
1847
- const own = (alias && providerId === nwc.id ? nwcWalletName(alias) : alias ?? "").replace(/\s+/g, " ").trim();
2254
+ const own = cleanName(alias && providerId === nwc.id ? nwcWalletName(alias) : alias ?? "");
1848
2255
  return own ? `${cutAtWord(own, ALIAS_IN_NAME)} (${short})` : short;
1849
2256
  }
2257
+ /**
2258
+ * A card's name as shown: no invisible or direction-changing character (one from the wallet's service could make a
2259
+ * name read like another card's, or reorder the source's name after it), white space collapsed; "" with nothing visible.
2260
+ */
2261
+ function cleanName(name) {
2262
+ const clean = dropLoneJoiners(stripHidden(name.replace(/\s+/g, " "))).replace(/\s+/g, " ").trim();
2263
+ return hasVisible(clean) ? clean : "";
2264
+ }
2265
+ /** What two names that read alike share: a name stored before `cleanName` may still hold what it drops. */
2266
+ var nameKey = (name) => cleanName(name).toLowerCase();
1850
2267
  /** `text` in at most `max` UTF-16 units (the unit `rename` counts), cut after a whole word with "…" when longer. */
1851
2268
  function cutAtWord(text, max) {
1852
2269
  if (text.length <= max) return text;
@@ -1941,22 +2358,27 @@ var LightningCards = class {
1941
2358
  }
1942
2359
  views() {
1943
2360
  const receive = this.receivingId;
1944
- return this.shown().filter((card) => this.services.has(card.id)).map((card) => ({
1945
- ...this.services.get(card.id).view,
1946
- card: card.id,
1947
- name: card.name,
1948
- receive: card.id === receive
1949
- }));
2361
+ return this.shown().filter((card) => this.services.has(card.id)).map((card) => this.cardView(card, card.id === receive));
1950
2362
  }
1951
2363
  /** The default for receiving's view: what a caller from before cards reads as the network's Lightning. None before start. */
1952
2364
  get view() {
1953
2365
  const card = this.stored.cards.find((c) => c.id === this.receivingId) ?? this.stored.cards[0];
1954
- return card && this.services.has(card.id) ? {
1955
- ...this.services.get(card.id).view,
2366
+ return card && this.services.has(card.id) ? this.cardView(card, true) : void 0;
2367
+ }
2368
+ cardView(card, receive) {
2369
+ const service = this.services.get(card.id);
2370
+ return {
2371
+ ...service.view,
1956
2372
  card: card.id,
1957
2373
  name: card.name,
1958
- receive: true
1959
- } : void 0;
2374
+ receive,
2375
+ ...this.isSpark(service) ? { sameWalletAs: "spark" } : {}
2376
+ };
2377
+ }
2378
+ /** The card opened the Breez database the network's Spark wallet has open: one wallet behind both cards. */
2379
+ isSpark(service) {
2380
+ const spark = this.options.sparkStorage?.(), active = service.sources.active;
2381
+ return !!spark && active instanceof BreezLightning && active.storage === spark;
1960
2382
  }
1961
2383
  /** The card holding this quote (each card quotes through its own source). */
1962
2384
  withQuote(quote) {
@@ -2035,9 +2457,9 @@ var LightningCards = class {
2035
2457
  }
2036
2458
  /** A name no other card of the network has: "LND", then "LND 2". */
2037
2459
  freeName(name) {
2038
- const taken = new Set(this.stored.cards.map((c) => c.name.toLowerCase()));
2039
- if (!taken.has(name.toLowerCase())) return name;
2040
- for (let n = 2;; n++) if (!taken.has(`${name} ${n}`.toLowerCase())) return `${name} ${n}`;
2460
+ const taken = new Set(this.stored.cards.map((c) => nameKey(c.name)));
2461
+ if (!taken.has(nameKey(name))) return name;
2462
+ for (let n = 2;; n++) if (!taken.has(nameKey(`${name} ${n}`))) return `${name} ${n}`;
2041
2463
  }
2042
2464
  /**
2043
2465
  * Removes a card: its source and sealed secrets go (refused while a payment through it has not ended). The default
@@ -2082,11 +2504,11 @@ var LightningCards = class {
2082
2504
  /** Renames a card: 1 to 32 characters, unique on its network. */
2083
2505
  rename(id, name) {
2084
2506
  return this.serial(async () => {
2085
- const clean = name.replace(/\s+/g, " ").trim();
2507
+ const clean = cleanName(name);
2086
2508
  if (!clean) throw new Error("Enter a name");
2087
2509
  if (clean.length > NAME_MAX) throw new Error(`At most ${NAME_MAX} characters`);
2088
2510
  if (!this.services.has(id)) throw new Error("That Lightning card is gone");
2089
- if (this.stored.cards.some((c) => c.id !== id && c.name.toLowerCase() === clean.toLowerCase())) throw new Error("Another card has that name");
2511
+ if (this.stored.cards.some((c) => c.id !== id && nameKey(c.name) === nameKey(clean))) throw new Error("Another card has that name");
2090
2512
  await this.save({
2091
2513
  ...this.stored,
2092
2514
  cards: this.stored.cards.map((c) => c.id === id ? {
@@ -2200,7 +2622,7 @@ var registry;
2200
2622
  var loading;
2201
2623
  var listeners = /* @__PURE__ */ new Set();
2202
2624
  function loadIdentityProviders() {
2203
- return loading ??= import("./registry-Cc_PQb3k.js").then((m) => {
2625
+ return loading ??= import("./registry-C734VrO9.js").then((m) => {
2204
2626
  registry = m;
2205
2627
  for (const listener of listeners) listener();
2206
2628
  return m;
@@ -2470,7 +2892,7 @@ var IdentityProofs = class {
2470
2892
  let refused;
2471
2893
  let fetch = this.fetch;
2472
2894
  if (this.host.relayOnly?.()) {
2473
- const { fixedIdentityHosts } = await import("./fixedHosts-BV5GDiTU.js");
2895
+ const { fixedIdentityHosts } = await import("./fixedHosts-CNX7QiUD.js");
2474
2896
  const fixed = fixedIdentityHosts();
2475
2897
  fetch = async (url, options) => {
2476
2898
  const host = new URL(url).host;
@@ -2512,7 +2934,8 @@ var IdentityProofs = class {
2512
2934
  return p && {
2513
2935
  statement: identityStatement(p.binding),
2514
2936
  evidence: p.evidence,
2515
- seed: await this.seedOf(id, p.seed)
2937
+ seed: await this.seedOf(id, p.seed),
2938
+ account: p.verified.subject
2516
2939
  };
2517
2940
  }
2518
2941
  /** Step 1 of adding a proof: a fresh proof key and the statement the external identity must sign. */
@@ -3004,8 +3427,8 @@ var IdentityProofs = class {
3004
3427
  verified: r.verified,
3005
3428
  display: r.display,
3006
3429
  status,
3007
- verifiedAt: r.verifiedAt,
3008
- checkedAt: r.checkedAt,
3430
+ verifiedAt: Math.min(r.verifiedAt, t),
3431
+ checkedAt: Math.min(r.checkedAt, t),
3009
3432
  expiresAt: Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity),
3010
3433
  error: r.error,
3011
3434
  recheckDue: !!provider?.recheck && (r.checkedAt > t || t - r.checkedAt >= provider.recheck.afterSeconds),
@@ -3123,6 +3546,182 @@ var FileAppender = class {
3123
3546
  }
3124
3547
  };
3125
3548
  //#endregion
3549
+ //#region ../browser/src/engine/forwards.ts
3550
+ /**
3551
+ * Whether a message can be forwarded, and as what. Payments and payment requests (a bearer token or a request is for
3552
+ * the chat it was made in), a group's history lines and its payment notes cannot; neither can a message with nothing
3553
+ * in it. Identity shares and call lines are not messages here at all.
3554
+ */
3555
+ function forwardKind(message) {
3556
+ if (message.sender !== "me" && message.sender !== "peer") return { refused: "This message cannot be forwarded" };
3557
+ if (message.paymentId) return { refused: "Payments and payment requests cannot be forwarded" };
3558
+ if (message.event || message.groupPay) return { refused: "This line cannot be forwarded" };
3559
+ if (message.file) return "file";
3560
+ return message.text.trim() ? "text" : { refused: "This message cannot be forwarded" };
3561
+ }
3562
+ /**
3563
+ * Why a chat did not get a forward, as its result says it: never "" (a result with an error is a failure, whatever it
3564
+ * says). A copy that found no room says so in the words the app knows however the storage put it: IndexedDB's
3565
+ * QuotaExceededError (an empty message in Chromium), the OPFS worker's (named so), Desktop's io error (the system's English).
3566
+ */
3567
+ function forwardError(error) {
3568
+ const message = (error instanceof Error ? error.message : String(error)).trim();
3569
+ if (/^No space left on device\b/.test(message)) return `Not enough space on this device (${message})`;
3570
+ const name = error?.name;
3571
+ return errorLine(error).trim() || (typeof name === "string" && name ? name : "Error");
3572
+ }
3573
+ /** How many bytes of a stored file are actually here: all of them once it arrived. */
3574
+ async function bytesHere(file) {
3575
+ if (file.blob) return file.blob.size;
3576
+ return await (file.bytes ? await fileBytesOf(file.bytes) : null)?.size(file.id) ?? 0;
3577
+ }
3578
+ /** `read` with the parts `patches` replace (zeros where a patch has no bytes). */
3579
+ function patchedRead(read, patches) {
3580
+ return async (offset, length) => {
3581
+ const part = (await read(offset, length)).slice();
3582
+ const end = offset + part.length;
3583
+ for (const { start, end: until, bytes } of patches) {
3584
+ if (until <= offset || start >= end) continue;
3585
+ const from = Math.max(start, offset), to = Math.min(until, end);
3586
+ if (bytes) part.set(bytes.subarray(from - start, to - start), from - offset);
3587
+ else part.fill(0, from - offset, to - offset);
3588
+ }
3589
+ return part;
3590
+ };
3591
+ }
3592
+ /**
3593
+ * A received picture, video, audio file or voice note as it goes on: without its metadata (one from an app that sent
3594
+ * it with them keeps where its author took it, the device, the time, an audio file's tags), as one sent from here;
3595
+ * undefined for any other file, copied as it is. A picture is read whole; a video's or an audio file's stripped bytes
3596
+ * are a Blob when it is kept in one, else read through the parts changed. Refused with `NO_PICTURE_METADATA`,
3597
+ * `NO_VIDEO_METADATA` or `NO_AUDIO_METADATA` when its metadata cannot be removed.
3598
+ */
3599
+ async function withoutMetadata(source, size, file, read) {
3600
+ if (!size) return void 0;
3601
+ if (file.video || file.voice || !isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) {
3602
+ if (source.blob) return await withoutVideoMetadata(source.blob, file.mime) ?? await withoutAudioMetadata(source.blob, file.mime);
3603
+ const readFully = async (offset, length) => {
3604
+ const whole = new Uint8Array(Math.max(0, Math.min(length, size - offset)));
3605
+ for (let at = 0; at < whole.length;) {
3606
+ const part = await read(offset + at, whole.length - at);
3607
+ if (!part.length) break;
3608
+ whole.set(part, at);
3609
+ at += part.length;
3610
+ }
3611
+ return whole;
3612
+ };
3613
+ const patches = await videoMetadataPatches({
3614
+ size,
3615
+ read: readFully
3616
+ }, file.mime) ?? await audioMetadataPatches({
3617
+ size,
3618
+ read: readFully
3619
+ }, file.mime);
3620
+ return patches && patchedRead(read, patches);
3621
+ }
3622
+ if (size > PICTURE_METADATA_LIMITS.maxBytes) throw new Error(NO_PICTURE_METADATA);
3623
+ const whole = new Uint8Array(size);
3624
+ for (let offset = 0; offset < size;) {
3625
+ const part = await read(offset, Math.min(1048576, size - offset));
3626
+ if (!part.length) throw new Error("The file is shorter than it says");
3627
+ whole.set(part, offset);
3628
+ offset += part.length;
3629
+ }
3630
+ return new Blob(stripPictureMetadata(whole, file.mime), { type: source.blob?.type ?? file.mime });
3631
+ }
3632
+ /** What a forward of a message deleted meanwhile says, whether it went before the forward or while its file was copied. */
3633
+ var FORWARD_MESSAGE_GONE = "That message is not in this chat";
3634
+ /**
3635
+ * A copy of a file on this device, for sending in another chat under `file.id`: a small one whole, a larger one a
3636
+ * step at a time, never whole in memory; a picture without its metadata, read whole, and a video or an audio file
3637
+ * without its. Refused while it is still arriving, or when its bytes are gone. Resolves to `file` as it goes: a
3638
+ * stripped file's size is its copy's.
3639
+ *
3640
+ * A copy cut off because its source went meanwhile says why, as one started after would: its message deleted (here, or
3641
+ * for everyone by its sender, which takes its file: `messageGone`, asked only once the copy failed) is
3642
+ * `FORWARD_MESSAGE_GONE`, its record gone with the message still here is "not on this device any more". Only bytes
3643
+ * missing from a source still kept whole on record stay "shorter than it says".
3644
+ */
3645
+ async function copyForForward(sourceId, target, messageGone) {
3646
+ try {
3647
+ return await copyFile(sourceId, target);
3648
+ } catch (error) {
3649
+ if (await messageGone?.().catch(() => false)) throw Object.assign(/* @__PURE__ */ new Error(FORWARD_MESSAGE_GONE), { cause: error });
3650
+ if (!(await fileStore.get(sourceId).catch(() => ({ metadata: true })))?.metadata) throw Object.assign(/* @__PURE__ */ new Error("The file is not on this device any more"), { cause: error });
3651
+ throw error;
3652
+ }
3653
+ }
3654
+ async function copyFile(sourceId, target) {
3655
+ const source = await fileStore.get(sourceId);
3656
+ if (!source?.metadata) throw new Error("The file is not on this device any more");
3657
+ const stored = storedSize(source);
3658
+ const checked = source.wire3 ? source.wire3.state === "done" : !source.group || source.transfer?.state === "done";
3659
+ if (source.direction === "in" && !checked || await bytesHere(source) !== stored) throw new Error("The file has not arrived yet");
3660
+ const from = source.bytes ? await fileBytesOf(source.bytes) : null;
3661
+ const read = async (offset, length) => source.blob ? new Uint8Array(await source.blob.slice(offset, offset + length).arrayBuffer()) : from.read(source.id, offset, length);
3662
+ const stripped = await withoutMetadata(source, stored, target.file, read);
3663
+ const blob = typeof stripped === "function" ? void 0 : stripped ?? source.blob, size = blob && stripped ? blob.size : stored;
3664
+ const readCopy = typeof stripped === "function" ? stripped : read;
3665
+ const known = stripped ? void 0 : source.digest;
3666
+ const { linkId, wireId, timestamp } = target, file = stripped ? {
3667
+ ...target.file,
3668
+ size
3669
+ } : target.file;
3670
+ const metadata = {
3671
+ name: file.name,
3672
+ size: file.size,
3673
+ mime: file.mime,
3674
+ timestamp,
3675
+ voice: file.voice,
3676
+ video: file.video,
3677
+ image: file.image
3678
+ };
3679
+ const record = {
3680
+ id: file.id,
3681
+ linkId,
3682
+ createdAt: timestamp,
3683
+ direction: "out",
3684
+ wireId,
3685
+ metadata,
3686
+ transfer: {
3687
+ state: "transferring",
3688
+ transferred: 0,
3689
+ size: file.size
3690
+ }
3691
+ };
3692
+ if (size <= 16777216 && blob) {
3693
+ const copy = new Blob([await blob.slice(0, size).arrayBuffer()], { type: blob.type });
3694
+ const digest = known ?? (stripped ? await blobDigest(copy) : void 0);
3695
+ await fileStore.put({
3696
+ ...record,
3697
+ blob: copy,
3698
+ ...digest && { digest }
3699
+ });
3700
+ return file;
3701
+ }
3702
+ const bytes = await fileBytes();
3703
+ try {
3704
+ const appender = new FileAppender(bytes, file.id);
3705
+ for (let offset = 0; offset < size;) {
3706
+ const part = blob ? new Uint8Array(await blob.slice(offset, offset + 1048576).arrayBuffer()) : await readCopy(offset, Math.min(1048576, size - offset));
3707
+ if (!part.length) throw new Error("The file is shorter than it says");
3708
+ await appender.append(part);
3709
+ offset += part.length;
3710
+ }
3711
+ await appender.close();
3712
+ const digest = known ?? await bytes.digest(file.id);
3713
+ await fileStore.put({
3714
+ ...record,
3715
+ bytes: bytes.kind,
3716
+ digest
3717
+ });
3718
+ return file;
3719
+ } catch (error) {
3720
+ await bytes.remove(file.id).catch(() => {});
3721
+ throw error;
3722
+ }
3723
+ }
3724
+ //#endregion
3126
3725
  //#region ../browser/src/shared/types.ts
3127
3726
  var WALLET_TYPES = [
3128
3727
  "cashu",
@@ -4707,6 +5306,62 @@ function messageFile(kept) {
4707
5306
  };
4708
5307
  }
4709
5308
  //#endregion
5309
+ //#region ../browser/src/shared/payLinks.ts
5310
+ /**
5311
+ * The desk's links to members of a community group (WISP 903 · Group Community § Payments): payments with a member
5312
+ * go through the group, sealed to them, over `cpay:<group>:<member>`; a request to everyone over `cpay:<group>`.
5313
+ */
5314
+ var pairLinkId = (groupId, member) => `cpay:${groupId}:${member}`;
5315
+ var groupLinkId = (groupId) => `cpay:${groupId}`;
5316
+ /** The group and member of a community payment link, or undefined for any other link. */
5317
+ function parsePayLink(linkId) {
5318
+ const m = /^cpay:([A-Za-z0-9_-]{22})(?::([a-z0-9]{52}))?$/.exec(linkId);
5319
+ return m ? {
5320
+ groupId: m[1],
5321
+ ...m[2] ? { member: m[2] } : {}
5322
+ } : void 0;
5323
+ }
5324
+ //#endregion
5325
+ //#region ../browser/src/shared/groupPayNotes.ts
5326
+ /** The id of a group payment note's line in the group's history (WISP 902 § Payments). */
5327
+ var groupPayLineId = (noteId) => `gpay:${noteId}`;
5328
+ /** The group note a payment of this device is part of: a request's own, or the request a payment answers (by its id on the wire). */
5329
+ function groupPayNoteId(paymentId, payment) {
5330
+ return paymentWireId(payment?.kind === "payment" && payment.requestId ? payment.requestId : paymentId);
5331
+ }
5332
+ /**
5333
+ * The note that captions a payment bubble: the one about that bubble's own payment, which the member who started it
5334
+ * says (the payee of a request, the payer of a payment), never a note of another member that reuses its id.
5335
+ */
5336
+ function groupPayCaption(message, payment, noteOf, myKey) {
5337
+ if (!message.paymentId) return void 0;
5338
+ if (payment?.kind === "payment" && payment.requestId) return void 0;
5339
+ const note = noteOf(groupPayNoteId(message.paymentId, payment));
5340
+ const starter = message.sender === "me" ? myKey : message.member;
5341
+ return note && starter && (note.kind === "request" ? note.to : note.from) === starter ? note : void 0;
5342
+ }
5343
+ /** The member at the other end of a group's payment link: a mesh member's edge, or a community member's link. */
5344
+ function groupMemberOfLink(group, linkId) {
5345
+ return group?.members.find((m) => !m.me && m.edge?.linkId === linkId)?.key ?? parsePayLink(linkId)?.member;
5346
+ }
5347
+ /**
5348
+ * The note a payment bubble of this device says again (its own caption, or a payment answering it), by the note's id:
5349
+ * the group page draws the bubble and leaves that note's own line out, so the same payment shows once. Undefined for
5350
+ * a bubble no note of the group is about. A payment answers the note of the request it pays only when that note is a
5351
+ * request between the same two members (`memberOf`: the member at the other end of a link of mine): a request's id is
5352
+ * its sender's to choose, so it can be the id of another member's note.
5353
+ */
5354
+ function groupPayTwin(message, payment, noteOf, myKey, memberOf = () => void 0) {
5355
+ if (!message.paymentId) return void 0;
5356
+ if (groupPayCaption(message, payment, noteOf, myKey)) return groupPayNoteId(message.paymentId, payment);
5357
+ if (payment?.kind !== "payment" || !payment.requestId) return void 0;
5358
+ const note = noteOf(groupPayNoteId(message.paymentId, payment));
5359
+ const member = message.sender === "me" ? payment.linkId && memberOf(payment.linkId) : message.member;
5360
+ const [payer, payee] = message.sender === "me" ? [myKey, member] : [member, myKey];
5361
+ if (note?.kind !== "request" || !payer || !payee || note.to !== payee || note.from !== payer && note.from !== "*") return void 0;
5362
+ return note.id;
5363
+ }
5364
+ //#endregion
4710
5365
  //#region ../browser/src/platform/irohWeb.ts
4711
5366
  /**
4712
5367
  * Iroh (WISP 102) in a browser: the same QUIC/TLS session and binding as the
@@ -5069,6 +5724,6 @@ async function createIrohWebEndpoint(seedB64, options = {}) {
5069
5724
  return endpoint;
5070
5725
  }
5071
5726
  //#endregion
5072
- export { iceServerProblem as $, storedSize as A, journaledPayment as B, paymentNetworksOf as C, FileAppender as D, WALLET_TYPES as E, CASHU_CARD as F, sourceKey as G, INVOICE_PACE as H, LightningCards as I, AskBackoff as J, CASHU_MINT_SOURCE as K, cardsKey as L, waitingGroupFile as M, IDENTITY_DRAFT_TTL_MS as N, readStored as O, IdentityProofs as P, dropBreezDatabase as Q, isRecoveryPhrase as R, paymentNetwork as S, MESSAGE_DETAILS_MAX_BYTES as T, nextInvoiceAsk as U, lightningPaying as V, ProviderSources as W, breezDatabaseInUse as X, breezDatabase as Y, breezDatabasesFor as Z, WALLET_NAMES as _, GroupFileDesk as a, networkLabel as at, createTiming as b, groupOfFile as c, requireTurn as ct, pairedWireReply as d, iceServerSetting as et, receivedPairedReply as f, paymentWireId as g, paymentAlias as h, onPublicIrohRelay as i, WrongNetworkError as it, streamStored as j, removeStored as k, storedGroupFiles as l, setAwayWallets as lt, replyTo as m, createIrohWebEndpoint as n, ModeChanged as nt, groupFileId as o, awayFrom as ot, replyRef as p, cashuMint as q, irohRelayProblem as r, ModeGate as rt, groupFileText as s, refuseAway as st, DEFAULT_IROH_RELAYS as t, relayOnlyProblem as tt, groupReply as u, setSingleWriterGate as ut, assertConfirmedReal as v, walletInstances as w, crossNetwork as x, createFailure as y, normalizePhrase as z };
5727
+ export { lightningPaying as $, paymentNetworksOf as A, removeStored as B, paymentWireId as C, setSingleWriterGate as Ct, createTiming as D, createFailure as E, copyForForward as F, IdentityProofs as G, streamStored as H, forwardError as I, cardsKey as J, CASHU_CARD as K, forwardKind as L, MESSAGE_DETAILS_MAX_BYTES as M, WALLET_TYPES as N, crossNetwork as O, FORWARD_MESSAGE_GONE as P, journaledPayment as Q, FileAppender as R, paymentAlias as S, setAwayWallets as St, assertConfirmedReal as T, waitingGroupFile as U, storedSize as V, IDENTITY_DRAFT_TTL_MS as W, breez as X, BREEZ_SOURCE as Y, normalizePhrase as Z, groupReply as _, WrongNetworkError as _t, groupMemberOfLink as a, cashuMint as at, replyRef as b, refuseAway as bt, groupPayTwin as c, loadBreezSdk as ct, parsePayLink as d, breezDatabasesFor as dt, INVOICE_PACE as et, GroupFileDesk as f, iceServerProblem as ft, storedGroupFiles as g, ModeGate as gt, groupOfFile as h, ModeChanged as ht, onPublicIrohRelay as i, CASHU_MINT_SOURCE as it, walletInstances as j, paymentNetwork as k, groupLinkId as l, openBreez as lt, groupFileText as m, relayOnlyProblem as mt, createIrohWebEndpoint as n, ProviderSources as nt, groupPayLineId as o, AskBackoff as ot, groupFileId as p, iceServerSetting as pt, LightningCards as q, irohRelayProblem as r, sourceKey as rt, groupPayNoteId as s, forgetBreez as st, DEFAULT_IROH_RELAYS as t, nextInvoiceAsk as tt, pairLinkId as u, breezDatabaseInUse as ut, pairedWireReply as v, networkLabel as vt, WALLET_NAMES as w, replyTo as x, requireTurn as xt, receivedPairedReply as y, awayFrom as yt, readStored as z };
5073
5728
 
5074
- //# sourceMappingURL=irohWeb-CqPN8VPY.js.map
5729
+ //# sourceMappingURL=irohWeb-DGelfgDJ.js.map