@ghostlytools/cli 1.10.3 → 1.10.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 (92) hide show
  1. package/dist/assets/{api-C4MLg5Rs.js → api-DppWqAP3.js} +12 -12
  2. package/dist/assets/api-DppWqAP3.js.map +1 -0
  3. package/dist/assets/{api-BdaxsDvA.js → api-K-i5MrP-.js} +2 -2
  4. package/dist/assets/{apiKit-BbNaxZGZ.js → apiKit-DFIho4Ev.js} +2 -2
  5. package/dist/assets/{apiKit-BbNaxZGZ.js.map → apiKit-DFIho4Ev.js.map} +1 -1
  6. package/dist/assets/{apps-BtGFth7o.js → apps-1MkGMH8m.js} +1 -1
  7. package/dist/assets/{apps-BluQgEhv.js → apps-yBnbEtfV.js} +3 -3
  8. package/dist/assets/{apps-BluQgEhv.js.map → apps-yBnbEtfV.js.map} +1 -1
  9. package/dist/assets/{arkade-DdZx4b_I.js → arkade-bFAS6imn.js} +2 -2
  10. package/dist/assets/{arkade-DdZx4b_I.js.map → arkade-bFAS6imn.js.map} +1 -1
  11. package/dist/assets/{backup-I1n7ccz7.js → backup-ejIX59o7.js} +1 -1
  12. package/dist/assets/{backup-DyDsW7sC.js → backup-vj4J7M3e.js} +6 -6
  13. package/dist/assets/{backup-DyDsW7sC.js.map → backup-vj4J7M3e.js.map} +1 -1
  14. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  15. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  16. package/dist/assets/{blobFiles-BnjN_Vrz.js → blobFiles-XZ9PEXYy.js} +2 -2
  17. package/dist/assets/{blobFiles-BnjN_Vrz.js.map → blobFiles-XZ9PEXYy.js.map} +1 -1
  18. package/dist/assets/{buttons-Do7dCku6.js → buttons-BoDMx3Ky.js} +3 -3
  19. package/dist/assets/{buttons-Do7dCku6.js.map → buttons-BoDMx3Ky.js.map} +1 -1
  20. package/dist/assets/buttons-DG1CKgAI.js +2 -0
  21. package/dist/assets/{client-CWsjRiH8.js → client-BQArefYa.js} +10 -4
  22. package/dist/assets/client-BQArefYa.js.map +1 -0
  23. package/dist/assets/{codec-DPaXhuYc.js → codec-_MwTUz5E.js} +2 -2
  24. package/dist/assets/{codec-DPaXhuYc.js.map → codec-_MwTUz5E.js.map} +1 -1
  25. package/dist/assets/{envelope-5Gu9yGk_.js → envelope-CeZBNGX-.js} +2 -2
  26. package/dist/assets/{envelope-5Gu9yGk_.js.map → envelope-CeZBNGX-.js.map} +1 -1
  27. package/dist/assets/{fileBytes-DjBYYyXT.js → fileBytes-BABGEF13.js} +2 -2
  28. package/dist/assets/{fileBytes-DjBYYyXT.js.map → fileBytes-BABGEF13.js.map} +1 -1
  29. package/dist/assets/{fileBytes-DMzrIdCu.js → fileBytes-CQQK2uOh.js} +1 -1
  30. package/dist/assets/{fileBytes-Douk1yOp.js → fileBytes-DqnfKIkj.js} +2 -2
  31. package/dist/assets/{fileBytes-Douk1yOp.js.map → fileBytes-DqnfKIkj.js.map} +1 -1
  32. package/dist/assets/fileBytesIdb-BtXATa7j.js +2 -0
  33. package/dist/assets/{fileBytesIdb-CkClu9YI.js → fileBytesIdb-DrXmDUSy.js} +2 -2
  34. package/dist/assets/{fileBytesIdb-CkClu9YI.js.map → fileBytesIdb-DrXmDUSy.js.map} +1 -1
  35. package/dist/assets/{fileBytesOpfs-WryQuOgK.js → fileBytesOpfs-udKCzcLe.js} +6 -9
  36. package/dist/assets/{fileBytesOpfs-WryQuOgK.js.map → fileBytesOpfs-udKCzcLe.js.map} +1 -1
  37. package/dist/assets/{fixedHosts-PR1BcfKX.js → fixedHosts-B_2Rvyja.js} +3 -3
  38. package/dist/assets/{fixedHosts-PR1BcfKX.js.map → fixedHosts-B_2Rvyja.js.map} +1 -1
  39. package/dist/assets/{groupFiles-BuToTMUk.js → groupFiles-D-ZUUHrx.js} +104 -81
  40. package/dist/assets/groupFiles-D-ZUUHrx.js.map +1 -0
  41. package/dist/assets/{host-fkQYBvKH.js → host-DFLzzKNr.js} +183 -41
  42. package/dist/assets/host-DFLzzKNr.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-DDCak5PY.js → hyperdhtRelay-CV6qMrom.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-DDCak5PY.js.map → hyperdhtRelay-CV6qMrom.js.map} +1 -1
  45. package/dist/assets/{irohWeb-B4_swKx0.js → irohWeb-C_Wnw7Q9.js} +7 -3
  46. package/dist/assets/irohWeb-C_Wnw7Q9.js.map +1 -0
  47. package/dist/assets/{main-ClYsttvY.js → main-xO8MnXxD.js} +19 -19
  48. package/dist/assets/{main-ClYsttvY.js.map → main-xO8MnXxD.js.map} +1 -1
  49. package/dist/assets/{mainline-Hsk2SZ1B.js → mainline-Bx184Ixg.js} +94 -2
  50. package/dist/assets/mainline-Bx184Ixg.js.map +1 -0
  51. package/dist/assets/{networkReason-C9Hr-hO7.js → networkReason-BlQhTbXk.js} +3 -3
  52. package/dist/assets/{networkReason-C9Hr-hO7.js.map → networkReason-BlQhTbXk.js.map} +1 -1
  53. package/dist/assets/{nwc-BbK6qNxS.js → nwc-B3-PHX0L.js} +3 -3
  54. package/dist/assets/{nwc-BbK6qNxS.js.map → nwc-B3-PHX0L.js.map} +1 -1
  55. package/dist/assets/{nwcProvider-D_tt2X3Z.js → nwcProvider-BeQBPB2q.js} +2 -2
  56. package/dist/assets/{nwcProvider-D_tt2X3Z.js.map → nwcProvider-BeQBPB2q.js.map} +1 -1
  57. package/dist/assets/{ownDid-DkK_jem4.js → ownDid-DAzW-Urb.js} +3 -2
  58. package/dist/assets/ownDid-DAzW-Urb.js.map +1 -0
  59. package/dist/assets/{profiles-aV9vaK0B.js → profiles-Bg43mRXu.js} +3 -3
  60. package/dist/assets/{profiles-aV9vaK0B.js.map → profiles-Bg43mRXu.js.map} +1 -1
  61. package/dist/assets/{registry-CEjnubep.js → registry-BDnsZJBi.js} +123 -17
  62. package/dist/assets/registry-BDnsZJBi.js.map +1 -0
  63. package/dist/assets/{registry-C9T6tYCO.js → registry-CAk2-5BQ.js} +1 -1
  64. package/dist/assets/{resolve-BBOrN13E.js → resolve-UAfshn6j.js} +2 -2
  65. package/dist/assets/{resolve-BBOrN13E.js.map → resolve-UAfshn6j.js.map} +1 -1
  66. package/dist/assets/{server-BJ3T-kx3.js → server-DYdR0_Fj.js} +738 -194
  67. package/dist/assets/server-DYdR0_Fj.js.map +1 -0
  68. package/dist/assets/{src-BIdfHB7t.js → src-BTRPAi5X.js} +710 -153
  69. package/dist/assets/src-BTRPAi5X.js.map +1 -0
  70. package/dist/assets/{sshForges-CRg-NGld.js → sshForges-KtHK5x1x.js} +2 -2
  71. package/dist/assets/{sshForges-CRg-NGld.js.map → sshForges-KtHK5x1x.js.map} +1 -1
  72. package/dist/assets/{translate-b0X61WMI.js → translate-CYuygrvA.js} +2 -2
  73. package/dist/assets/{translate-b0X61WMI.js.map → translate-CYuygrvA.js.map} +1 -1
  74. package/dist/assets/{usdt-6CQdfye1.js → usdt-Dw9IENe_.js} +3 -3
  75. package/dist/assets/{usdt-6CQdfye1.js.map → usdt-Dw9IENe_.js.map} +1 -1
  76. package/dist/assets/{words-Dk6o6wz4.js → words-BvdNuw_v.js} +3 -3
  77. package/dist/assets/words-BvdNuw_v.js.map +1 -0
  78. package/dist/ghostly.mjs +1 -1
  79. package/package.json +1 -1
  80. package/dist/assets/api-C4MLg5Rs.js.map +0 -1
  81. package/dist/assets/buttons-DpjwXePb.js +0 -2
  82. package/dist/assets/client-CWsjRiH8.js.map +0 -1
  83. package/dist/assets/fileBytesIdb-CD5Uv490.js +0 -2
  84. package/dist/assets/groupFiles-BuToTMUk.js.map +0 -1
  85. package/dist/assets/host-fkQYBvKH.js.map +0 -1
  86. package/dist/assets/irohWeb-B4_swKx0.js.map +0 -1
  87. package/dist/assets/mainline-Hsk2SZ1B.js.map +0 -1
  88. package/dist/assets/ownDid-DkK_jem4.js.map +0 -1
  89. package/dist/assets/registry-CEjnubep.js.map +0 -1
  90. package/dist/assets/server-BJ3T-kx3.js.map +0 -1
  91. package/dist/assets/src-BIdfHB7t.js.map +0 -1
  92. package/dist/assets/words-Dk6o6wz4.js.map +0 -1
@@ -1,17 +1,17 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $a as ReactionWindow, $c as openRequest, $i as HOLD_DATED_BACK_MS, $l as deviceEchoFrame, $n as engineError, $o as PRESENCE_WINDOW, $r as PIN_LIMITS, $s as handoffReleaseFrame, $t as ONCHAIN_PROVIDER, $u as sanitizeDisplayText, A as knockIdentity, Ac as enrollProofFrame, An as ENDPOINT, Ao as claimedTime, Ar as lobbyKeys, As as HANDOFF_HELLO, Au as currentRelays, Ba as EDIT_RATE_WINDOW_MS, Bc as takeRequest, Bl as createDeviceInvite, Bn as NO_PICTURE_METADATA, Bo as rosterAdmin, Br as shouldBeHub, Bs as handoffAttemptFailed, C as communityHasFrame, Ca as peekDhtMailbox, Ci as UPGRADE_CAPABILITY, Cl as isAppHash, Cr as pickMeshHubs, Cs as HTTP_SERVICE_PROTO, Cu as turnVerifierMark, D as decodeGroupEntryLink, Da as sanitizeFileName, Dc as enrollDoneFrame, Di as dialDescriptors, Dl as readAppRevocationShape, Dr as doorHubs, Ds as HANDOFF_CANCEL, Du as RelayTransport, Ea as formatFileSize, Ec as enrollDigits, Ei as capsDescriptors, El as readAppRevocation, Eo as sameButtonText, Er as beaconRecords, Es as HANDOFF_ACK, F as GroupWakeLimiter, Fa as parseVoiceMeta, Fc as endedRequests, Fi as emptyIdentityLedger, Fn as parseCashuRequestPayload, Fo as GROUP_MEMBER_CAP, Fr as pickHubs, Fs as HANDOFF_TIMINGS, Gc as contactAskerHolds, Gi as emptyProofLedger, Gl as decodeInviteCode, Gn as GhostLink, Go as RatchetBox, Gr as transferEnded, Gs as handoffContextProof, Gt as didDhtDocument, Gu as createIdentity, H as GroupSession, Ha as REMOVED_TEXT, Hc as ContactRequestError, Hl as readDeviceInvite, Hn as isStrippedPicture, Ho as verifyCommitSignature, Hr as FILE_LIMITS, Hs as handoffBusyFrame, I as groupWakeFrame, Ic as inboxRecord, Il as readCanonicalJson, In as parseFedimintRequestPayload, Ir as rankHubs, Is as HANDOFF_VERIFIED, Iu as budgetRetryMs, J as meshMessageRef, Ja as forwardedAgain, Jc as knockSlotOf, Ji as automaticTransport, Jl as inviteOwnership, Jn as PAIRED_FRAME_TOO_LARGE, Jo as DirectPathWatch, Js as handoffEphemeral, Jt as encodeDidDhtPacket, Ju as publicKeyFromZ32, K as GROUP_EDIT_TEXT_BYTES, Kc as contactDay, Ki as validExternalKey, Kl as encodeInviteCode, Kn as INVITE_TAKEN, Ko as emptyRatchetState, Kr as transferStalled, Ks as handoffDataFrame, Kt as didDhtFromPublicKey, Ku as identityFromSeed, L as groupWakes, Lc as newInbox, Ll as createContactLink, Lo as MEMBER_KEY, Lr as readBeacon, Ls as NO_ATTEMPTS, Lu as isDiscoveryBudgetError, M as mergeKnocks, Mc as readEnrollHello, Ml as parseImageMeta, Mn as fedimintRequestPayload, Mo as receivedTimestamp, Mr as mergeBeacon, Ms as HANDOFF_PAKE, N as readKnocks, Nc as verifyEnrollProof, Nn as findEndpoint, No as shownTime, Nr as mergeLobby, Ns as HANDOFF_PIECE_BYTES, O as encodeGroupEntryLink, Oa as sanitizeMime, Oc as enrollGrantFrame, Oo as statusCardText, Or as freshHubs, Os as HANDOFF_DONE, Pa as fileMessageText, Pc as clearMissed, Pl as canonicalJson, Pn as isFederationId, Po as GROUP_ADMIN_OFF_ERROR, Pr as newerHead, Ps as HANDOFF_REQUEST, Pu as traceLink, Qa as REACTION_LIMITS, Qc as mergeContactKnocks, Qi as HOLD_CAPABILITY, Ql as HANDOFF_CAPABILITY, Qn as EngineError, Qs as handoffPakeFrame, Qt as EVM_TEST_CHAINS, Qu as hasVisible, R as parseGroupWakeFrame, Ra as parseVideoMeta, Rc as planKnocks, Rl as encodeContactLink, Rn as videoMetadataPatches, Ro as commitHash, Rr as readBeaconHead, Rs as filePartName, Ru as withRequestOptions, S as GROUP_READ_NOTE_COMMUNITY, Sa as DHT_MESSAGE_TTL, Si as STATUS_CARD_CAPABILITY, Sr as meshHubs, Ss as emptyLinkRecords, Su as turnStatedVerifier, T as encodeCommunityLink, Ta as dhtFileId, Tc as enrollCancelReason, Ti as DHT_TEXT_CAPABILITY, Tl as isAppRef, To as checkStatusCard, Tr as beaconKeys, Ts as serviceIdFromName, U as frameBytes, Ua as RateWindow, Uc as REQUEST_LIFETIME_MS, Ui as lastSharedWithMe, Ul as OwnInviteError, Un as stripPictureMetadata, Uo as edgeParams, Us as handoffCancelFrame, V as GROUP_READ_NOTE, Va as MAX_REMOVAL_NUMBER, Vc as turnOff, Vi as receivedIdentityStatus, Vl as deviceInviteJoinerParams, Vn as PICTURE_METADATA_LIMITS, Vo as rosterHas, Vr as ChatFiles, Vs as handoffAttemptSucceeded, Vu as createRelayPayload, Wa as dhtEditId, Wc as contactAskerFrame, Wi as PeerProofs, Wl as createChatInvite, Wo as RATCHET_CAPABILITY, Wr as sentWhole, Ws as handoffContext, X as mentionsMember, Xa as COMMUNITY_REACTION_FRAME, Xc as linkRecords, Xl as DEVICES_CAPABILITY, Xn as pairedMessageFits, Xs as handoffManifestFrames, Xt as signDidDhtPacket, Y as parseCommunityEdit, Ya as readForwarded, Yc as knockSlotRecords, Yn as pairedEditFits, Yr as TypingSender, Ys as handoffHelloFrame, Yu as verify, Z as groupName, Za as GROUP_REACTION_FRAME, Zc as makeStampPaced, Zl as ENROLL_CAPABILITY, Zn as pairedMessageFrame, Zo as DHT_POLL_INTERVALS, Zr as typingActivity, Zs as handoffOfferFrame, Zt as ETHEREUM_USDT, Zu as sanitizeAvatar, _ as groupTypingEpoch, _c as setUpdateFrame, _i as chatAppId, _t as isAtprotoDid, _u as signTurnPacket, a as appRevocationFor, aa as readManifest, ac as readHandoffCancel, ad as toBase64Url, ai as WAKE_CALL_INTERVAL_MS, al as APP_BUNDLE_MAGIC, an as WALLET_NETWORKS, ao as validReactionNumber, as as parseLocalTarget, au as seedSigner, b as COMMUNITY_LIMITS, bi as BUTTONS_CAPABILITY, bl as appRef, br as MESH_HUBS, bs as parseCallSignal, bu as turnKeys, c as checkAppBeforeRun, cc as readHandoffHello, cd as utf8Encode, ci as newWakeToken, cl as appDigest, cn as assertWholeSats, co as readReply, cs as decodeControl, cu as TURN_RAISE_READ_TIMEOUT_MS, dc as readHandoffVerified, di as wakeRequest, dn as walletNetworkOf, du as turnPutSummary, ea as HOLD_LIMITS, ec as handoffRetryAfter, ed as stripHidden, ei as mayPin, el as readKnockSlot, en as PaymentPreflightError, eo as nextReactionNumber, er as engineText, es as RELAY_POLL_INTERVALS, eu as deviceEchoNonce, fc as sealHandoffPiece, fi as checkPushEndpoint, fl as isAppUrl, fn as SPARK_NETWORKS, fu as TURN_LAST_SEQUENCE, g as GroupTypingBoard, gc as setAckFrame, gl as sha256Paced, gn as isBitcoinAddress, gu as readTurnPacket, hc as readSetUpdate, hi as isServeId, hl as readAppBundleAsync, hn as sparkInvoiceDetails, hu as nextTurnPosition, i as addedAppPermissions, ia as newMailbox, ic as readHandoffAck, id as randomBytes, ii as readPin, il as APP_BUNDLE_LIMITS, in as USDT_PUBLIC_RPC, io as readReaction, is as formatLocalTarget, iu as newDeviceSetSecret, j as knockRecords, jc as readEnrollGrant, jn as cashuRequestPayload, jo as heardTime, jr as lobbyRecords, js as HANDOFF_OFFER, ju as normalizeRelayUrl, k as entryParams, kc as enrollHelloFrame, kn as decodeBolt11, ko as arrivalKey, kr as hubRank, ks as HANDOFF_HAVE, l as planAppUpdate, lc as readHandoffPake, li as parseWakeFrame, ll as appViewOf, ln as formatPaymentAmount, lo as replySnippet, lr as readGroupFileMeta, ls as encodeControl, lu as TURN_SETTLE_MS, mi as APP_RANGE_LIMITS, mn as sparkAddressKind, mu as firstDeviceSetSecret, n as readX401SdJwtVc, na as HoldRefusedError, nc as handoffVersions, nd as fromBase64Url, ni as pinIsNewer, nl as requestRecords, no as reactionEmoji, nr as GROUP_FILE_LIMITS, ns as presenceSeenAt, nu as deviceLinkPairing, o as appStoreDecision, oc as readHandoffDone, od as toZ32, oi as WakeLimiter, on as arkAddressPrefix, oo as wireReaction, os as webLocalFetch, ou as webCryptoSigner, p as readAppStoreSteps, pi as vapidKeysMatch, pl as pacer, pn as SPARK_PROVIDER, pr as CarriedTransport, ps as RTC_CONFIG, pu as TURN_MAX, q as carryMentions, qa as parseLinkPreview, qc as knockSlotIdentity, qi as TRANSPORTS, ql as inviteLink, qn as LIVENESS_PING_MS, qo as ratchetSessionOf, qs as handoffDigest, qt as encodeDidDhtDeactivated, qu as identityFromSeedB64, r as sameX401HolderJwk, ra as isHoldUrl, rc as newHandoffId, ri as pinNumberHolds, rl as seenEntry, rn as TEST_USDT_FAUCET_AMOUNT, ro as reactionIsNewer, rr as GROUP_HAVE_FRAME, rs as GhostlyHttpError, ru as devicePingFrame, s as appUpdateDecision, sc as readHandoffHave, sd as utf8Decode, si as deviceWakeRequest, sn as assertTokenUnits, so as pairedReplyAuthor, sr as groupFileFallback, ss as LIMITS, t as newX401HolderKey, ta as HoldKeys, tc as handoffStreamKey, td as bytesEqual, ti as nextPinNumber, tl as readLinkRecord, tn as SEPOLIA_TEST_USDT, to as queueReaction, tr as parseEngineError, ts as WATCH_PEER_MS, tu as deviceKeyZ32, u as APP_STORE_LIMITS, uc as readHandoffTurnFrame, ui as relayRequest, un as validatePaymentTarget, uo as BUTTON_ID, uu as classifyTurnRead, v as openGroupTyping, vc as signTombstone, vi as isAppVersion, vl as APP_STATEMENT_LIMITS, vn as isPubkyKey, vo as STATUS_CARD_LIMITS, vr as groupSignalFrame, vs as contactRtcConfig, vt as normalizeAtprotoHandle, vu as signTurnRelease, w as decodeCommunityLink, wa as DHT_FILE_CAPABILITY, wc as enrollCancelFrame, wi as CapsExchange, wl as isAppKey, wr as COMMUNITY_TOPOLOGY, ws as LEGACY_SERVICES, wu as DEFAULT_RELAYS, x as CommunitySession, xi as EDIT_CAPABILITY, xl as appRefPublisher, xr as mayBeHub, xu as turnName, y as sealGroupTyping, yc as verifySetUpdate, yi as APPS_CAPABILITY, yl as appFingerprint, yr as readGroupSignal, yu as turnInstance, z as GROUP_LIMITS, za as EDIT_BUFFER_MS, zc as settleRequest, zl as readContactLink, zn as withoutVideoMetadata, zo as parseGroupCommit, zr as readLobby, zs as handoffAttemptAllowed, zu as PacketTooLargeError } from "./src-BIdfHB7t.js";
2
+ import { $a as ReactionWindow, $c as openRequest, $i as HOLD_DATED_BACK_MS, $l as deviceEchoFrame, $n as engineError, $o as PRESENCE_WINDOW, $r as PIN_LIMITS, $s as handoffReleaseFrame, $t as ONCHAIN_PROVIDER, $u as sanitizeDisplayText, A as knockIdentity, Ac as enrollProofFrame, An as ENDPOINT, Ao as claimedTime, Ar as lobbyKeys, As as HANDOFF_HELLO, Au as currentRelays, Ba as EDIT_RATE_WINDOW_MS, Bc as takeRequest, Bl as createDeviceInvite, Bn as NO_PICTURE_METADATA, Bo as rosterAdmin, Br as shouldBeHub, Bs as handoffAttemptFailed, C as communityHasFrame, Ca as peekDhtMailbox, Ci as UPGRADE_CAPABILITY, Cl as isAppHash, Cr as pickMeshHubs, Cs as HTTP_SERVICE_PROTO, Cu as turnVerifierMark, D as decodeGroupEntryLink, Da as sanitizeFileName, Dc as enrollDoneFrame, Di as dialDescriptors, Dl as readAppRevocationShape, Dr as doorHubs, Ds as HANDOFF_CANCEL, Du as RelayTransport, Ea as formatFileSize, Ec as enrollDigits, Ei as capsDescriptors, El as readAppRevocation, Eo as sameButtonText, Er as beaconRecords, Es as HANDOFF_ACK, F as GroupWakeLimiter, Fa as parseVoiceMeta, Fc as endedRequests, Fi as emptyIdentityLedger, Fn as parseCashuRequestPayload, Fo as GROUP_MEMBER_CAP, Fr as pickHubs, Fs as HANDOFF_TIMINGS, Gc as contactAskerHolds, Gi as emptyProofLedger, Gl as decodeInviteCode, Gn as GhostLink, Go as RatchetBox, Gr as transferEnded, Gs as handoffContextProof, Gt as didDhtDocument, Gu as createIdentity, H as GroupSession, Ha as REMOVED_TEXT, Hc as ContactRequestError, Hl as readDeviceInvite, Hn as isStrippedPicture, Ho as verifyCommitSignature, Hr as FILE_LIMITS, Hs as handoffBusyFrame, I as groupWakeFrame, Ic as inboxRecord, Il as readCanonicalJson, In as parseFedimintRequestPayload, Ir as rankHubs, Is as HANDOFF_VERIFIED, Iu as budgetRetryMs, J as meshMessageRef, Ja as forwardedAgain, Jc as knockSlotOf, Ji as automaticTransport, Jl as inviteOwnership, Jn as PAIRED_FRAME_TOO_LARGE, Jo as DirectPathWatch, Js as handoffEphemeral, Jt as encodeDidDhtPacket, Ju as publicKeyFromZ32, K as GROUP_EDIT_TEXT_BYTES, Kc as contactDay, Ki as validExternalKey, Kl as encodeInviteCode, Kn as INVITE_TAKEN, Ko as emptyRatchetState, Kr as transferStalled, Ks as handoffDataFrame, Kt as didDhtFromPublicKey, Ku as identityFromSeed, L as groupWakes, Lc as newInbox, Ll as createContactLink, Lo as MEMBER_KEY, Lr as readBeacon, Ls as NO_ATTEMPTS, Lu as isDiscoveryBudgetError, M as mergeKnocks, Mc as readEnrollHello, Ml as parseImageMeta, Mn as fedimintRequestPayload, Mo as receivedTimestamp, Mr as mergeBeacon, Ms as HANDOFF_PAKE, N as readKnocks, Nc as verifyEnrollProof, Nn as findEndpoint, No as shownTime, Nr as mergeLobby, Ns as HANDOFF_PIECE_BYTES, O as encodeGroupEntryLink, Oa as sanitizeMime, Oc as enrollGrantFrame, Oo as statusCardText, Or as freshHubs, Os as HANDOFF_DONE, Pa as fileMessageText, Pc as clearMissed, Pl as canonicalJson, Pn as isFederationId, Po as GROUP_ADMIN_OFF_ERROR, Pr as newerHead, Ps as HANDOFF_REQUEST, Pu as traceLink, Qa as REACTION_LIMITS, Qc as mergeContactKnocks, Qi as HOLD_CAPABILITY, Ql as HANDOFF_CAPABILITY, Qn as EngineError, Qs as handoffPakeFrame, Qt as EVM_TEST_CHAINS, Qu as hasVisible, R as parseGroupWakeFrame, Ra as parseVideoMeta, Rc as planKnocks, Rl as encodeContactLink, Rn as videoMetadataPatches, Ro as commitHash, Rr as readBeaconHead, Rs as filePartName, Ru as withRequestOptions, S as GROUP_READ_NOTE_COMMUNITY, Sa as DHT_MESSAGE_TTL, Si as STATUS_CARD_CAPABILITY, Sr as meshHubs, Ss as emptyLinkRecords, Su as turnStatedVerifier, T as encodeCommunityLink, Ta as dhtFileId, Tc as enrollCancelReason, Ti as DHT_TEXT_CAPABILITY, Tl as isAppRef, To as checkStatusCard, Tr as beaconKeys, Ts as serviceIdFromName, U as frameBytes, Ua as RateWindow, Uc as REQUEST_LIFETIME_MS, Ui as lastSharedWithMe, Ul as OwnInviteError, Un as stripPictureMetadata, Uo as edgeParams, Us as handoffCancelFrame, V as GROUP_READ_NOTE, Va as MAX_REMOVAL_NUMBER, Vc as turnOff, Vi as receivedIdentityStatus, Vl as deviceInviteJoinerParams, Vn as PICTURE_METADATA_LIMITS, Vo as rosterHas, Vr as ChatFiles, Vs as handoffAttemptSucceeded, Vu as createRelayPayload, Wa as dhtEditId, Wc as contactAskerFrame, Wi as PeerProofs, Wl as createChatInvite, Wo as RATCHET_CAPABILITY, Wr as sentWhole, Ws as handoffContext, X as mentionsMember, Xa as COMMUNITY_REACTION_FRAME, Xc as linkRecords, Xl as DEVICES_CAPABILITY, Xn as pairedMessageFits, Xs as handoffManifestFrames, Xt as signDidDhtPacket, Y as parseCommunityEdit, Ya as readForwarded, Yc as knockSlotRecords, Yn as pairedEditFits, Yr as TypingSender, Ys as handoffHelloFrame, Yu as verify, Z as groupName, Za as GROUP_REACTION_FRAME, Zc as makeStampPaced, Zl as ENROLL_CAPABILITY, Zn as pairedMessageFrame, Zo as DHT_POLL_INTERVALS, Zr as typingActivity, Zs as handoffOfferFrame, Zt as ETHEREUM_USDT, Zu as sanitizeAvatar, _ as groupTypingEpoch, _c as setUpdateFrame, _i as chatAppId, _t as isAtprotoDid, _u as signTurnPacket, a as appRevocationFor, aa as readManifest, ac as readHandoffCancel, ad as toBase64Url, ai as WAKE_CALL_INTERVAL_MS, al as APP_BUNDLE_MAGIC, an as WALLET_NETWORKS, ao as validReactionNumber, as as parseLocalTarget, au as seedSigner, b as COMMUNITY_LIMITS, bi as BUTTONS_CAPABILITY, bl as appRef, br as MESH_HUBS, bs as parseCallSignal, bu as turnKeys, c as checkAppBeforeRun, cc as readHandoffHello, cd as utf8Encode, ci as newWakeToken, cl as appDigest, cn as assertWholeSats, co as readReply, cs as decodeControl, cu as TURN_RAISE_READ_TIMEOUT_MS, dc as readHandoffVerified, di as wakeRequest, dn as walletNetworkOf, du as turnPutSummary, ea as HOLD_LIMITS, ec as handoffRetryAfter, ed as stripHidden, ei as mayPin, el as readKnockSlot, en as PaymentPreflightError, eo as nextReactionNumber, er as engineText, es as RELAY_POLL_INTERVALS, eu as deviceEchoNonce, fc as sealHandoffPiece, fi as checkPushEndpoint, fl as isAppUrl, fn as SPARK_NETWORKS, fu as TURN_LAST_SEQUENCE, g as GroupTypingBoard, gc as setAckFrame, gl as sha256Paced, gn as isBitcoinAddress, gu as readTurnPacket, hc as readSetUpdate, hi as isServeId, hl as readAppBundleAsync, hn as sparkInvoiceDetails, hu as nextTurnPosition, i as addedAppPermissions, ia as newMailbox, ic as readHandoffAck, id as randomBytes, ii as readPin, il as APP_BUNDLE_LIMITS, in as USDT_PUBLIC_RPC, io as readReaction, is as formatLocalTarget, iu as newDeviceSetSecret, j as knockRecords, jc as readEnrollGrant, jn as cashuRequestPayload, jo as heardTime, jr as lobbyRecords, js as HANDOFF_OFFER, ju as normalizeRelayUrl, k as entryParams, kc as enrollHelloFrame, kn as decodeBolt11, ko as arrivalKey, kr as hubRank, ks as HANDOFF_HAVE, l as planAppUpdate, lc as readHandoffPake, li as parseWakeFrame, ll as appViewOf, ln as formatPaymentAmount, lo as replySnippet, lr as readGroupFileMeta, ls as encodeControl, lu as TURN_SETTLE_MS, mi as APP_RANGE_LIMITS, mn as sparkAddressKind, mu as firstDeviceSetSecret, n as readX401SdJwtVc, na as HoldRefusedError, nc as handoffVersions, nd as fromBase64Url, ni as pinIsNewer, nl as requestRecords, no as reactionEmoji, nr as GROUP_FILE_LIMITS, ns as presenceSeenAt, nu as deviceLinkPairing, o as appStoreDecision, oc as readHandoffDone, od as toZ32, oi as WakeLimiter, on as arkAddressPrefix, oo as wireReaction, os as webLocalFetch, ou as webCryptoSigner, p as readAppStoreSteps, pi as vapidKeysMatch, pl as pacer, pn as SPARK_PROVIDER, pr as CarriedTransport, ps as RTC_CONFIG, pu as TURN_MAX, q as carryMentions, qa as parseLinkPreview, qc as knockSlotIdentity, qi as TRANSPORTS, ql as inviteLink, qn as LIVENESS_PING_MS, qo as ratchetSessionOf, qs as handoffDigest, qt as encodeDidDhtDeactivated, qu as identityFromSeedB64, r as sameX401HolderJwk, ra as isHoldUrl, rc as newHandoffId, ri as pinNumberHolds, rl as seenEntry, rn as TEST_USDT_FAUCET_AMOUNT, ro as reactionIsNewer, rr as GROUP_HAVE_FRAME, rs as GhostlyHttpError, ru as devicePingFrame, s as appUpdateDecision, sc as readHandoffHave, sd as utf8Decode, si as deviceWakeRequest, sn as assertTokenUnits, so as pairedReplyAuthor, sr as groupFileFallback, ss as LIMITS, t as newX401HolderKey, ta as HoldKeys, tc as handoffStreamKey, td as bytesEqual, ti as nextPinNumber, tl as readLinkRecord, tn as SEPOLIA_TEST_USDT, to as queueReaction, tr as parseEngineError, ts as WATCH_PEER_MS, tu as deviceKeyZ32, u as APP_STORE_LIMITS, uc as readHandoffTurnFrame, ui as relayRequest, un as validatePaymentTarget, uo as BUTTON_ID, uu as classifyTurnRead, v as openGroupTyping, vc as signTombstone, vi as isAppVersion, vl as APP_STATEMENT_LIMITS, vn as isPubkyKey, vo as STATUS_CARD_LIMITS, vr as groupSignalFrame, vs as contactRtcConfig, vt as normalizeAtprotoHandle, vu as signTurnRelease, w as decodeCommunityLink, wa as DHT_FILE_CAPABILITY, wc as enrollCancelFrame, wi as CapsExchange, wl as isAppKey, wr as COMMUNITY_TOPOLOGY, ws as LEGACY_SERVICES, wu as DEFAULT_RELAYS, x as CommunitySession, xi as EDIT_CAPABILITY, xl as appRefPublisher, xr as mayBeHub, xu as turnName, y as sealGroupTyping, yc as verifySetUpdate, yi as APPS_CAPABILITY, yl as appFingerprint, yr as readGroupSignal, yu as turnInstance, z as GROUP_LIMITS, za as EDIT_BUFFER_MS, zc as settleRequest, zl as readContactLink, zn as withoutVideoMetadata, zo as parseGroupCommit, zr as readLobby, zs as handoffAttemptAllowed, zu as PacketTooLargeError } from "./src-BTRPAi5X.js";
3
3
  import { i as SourceUnreachableError, n as PROVIDER_PLATFORMS, o as isNothingSpentError, r as SourceConfigError, t as NothingSpentError, u as redact } from "./types-C4_KafL_.js";
4
4
  import { t as bitcoindRpc } from "./bitcoindProvider-DGw3xBSa.js";
5
- import { t as nwc } from "./nwcProvider-D_tt2X3Z.js";
5
+ import { t as nwc } from "./nwcProvider-BeQBPB2q.js";
6
6
  import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BHsAqENE.js";
7
- import { a as sealSeed, c as openRow, d as sealRow, f as sealedStore, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, l as openRows, m as openSecret, o as unsealSeed, p as hasDataKey, r as intentRepository, s as RowSeals, u as proofKey } from "./networkReason-C9Hr-hO7.js";
8
- import { $ as ModeGate, A as IdentityProofs, B as ProviderSources, C as FileAppender, D as streamStored, E as storedSize, F as normalizePhrase, G as breezDatabase, H as AskBackoff, I as journaledPayment, J as dropBreezDatabase, K as breezDatabaseInUse, L as lightningPaying, M as LightningCards, N as cardsKey, P as isRecoveryPhrase, Q as ModeChanged, R as INVOICE_PACE, S as WALLET_TYPES, T as removeStored, U as CASHU_MINT_SOURCE, V as sourceKey, W as cashuMint, X as iceServerSetting, Y as iceServerProblem, Z as relayOnlyProblem, _ as crossNetwork, a as storedGroupFiles, at as setAwayWallets, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as WrongNetworkError, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as requireTurn, j as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as awayFrom, o as groupReply, ot as setSingleWriterGate, p as WALLET_NAMES, q as breezDatabasesFor, r as groupFileText, rt as refuseAway, s as pairedWireReply, t as GroupFileDesk, tt as networkLabel, u as replyTo, v as paymentNetwork, w as readStored$2, y as paymentNetworksOf, z as nextInvoiceAsk } from "./groupFiles-BuToTMUk.js";
9
- import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-B4_swKx0.js";
7
+ import { a as sealSeed, c as openRow, d as sealRow, f as sealedStore, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, l as openRows, m as openSecret, o as unsealSeed, p as hasDataKey, r as intentRepository, s as RowSeals, u as proofKey } from "./networkReason-BlQhTbXk.js";
8
+ import { $ as ModeGate, A as IdentityProofs, B as ProviderSources, C as FileAppender, D as streamStored, E as storedSize, F as normalizePhrase, G as breezDatabase, H as CASHU_MINT_SOURCE, I as journaledPayment, J as dropBreezDatabase, K as breezDatabaseInUse, L as lightningPaying, M as LightningCards, N as cardsKey, P as isRecoveryPhrase, Q as ModeChanged, R as INVOICE_PACE, S as WALLET_TYPES, T as removeStored, U as cashuMint, V as sourceKey, W as AskBackoff, X as iceServerSetting, Y as iceServerProblem, Z as relayOnlyProblem, _ as crossNetwork, a as storedGroupFiles, at as setAwayWallets, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as WrongNetworkError, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as requireTurn, j as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as awayFrom, o as groupReply, ot as setSingleWriterGate, p as WALLET_NAMES, q as breezDatabasesFor, r as groupFileText, rt as refuseAway, s as pairedWireReply, t as GroupFileDesk, tt as networkLabel, u as replyTo, v as paymentNetwork, w as readStored$2, y as paymentNetworksOf, z as nextInvoiceAsk } from "./groupFiles-D-ZUUHrx.js";
9
+ import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-C_Wnw7Q9.js";
10
10
  import { c as isTestMint, d as mintUrlSpelling, f as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
11
- import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-DkK_jem4.js";
12
- import { d as chosenResolver, m as setPkarrRelaySource, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-BBOrN13E.js";
13
- import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-DjBYYyXT.js";
14
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-5Gu9yGk_.js";
11
+ import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-DAzW-Urb.js";
12
+ import { d as chosenResolver, m as setPkarrRelaySource, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-UAfshn6j.js";
13
+ import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-BABGEF13.js";
14
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-CeZBNGX-.js";
15
15
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-1wzya_0L.js";
16
16
  import { sha256 } from "@noble/hashes/sha2.js";
17
17
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -199,7 +199,7 @@ function viewNews(before, after) {
199
199
  //#endregion
200
200
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
201
201
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
202
- var loadUsdt = () => import("./usdt-6CQdfye1.js");
202
+ var loadUsdt = () => import("./usdt-Dw9IENe_.js");
203
203
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
204
204
  var DEFAULT_USDT = {
205
205
  network: "ethereum",
@@ -686,7 +686,7 @@ async function restoreArkDatabase(walletId, snapshot) {
686
686
  //#endregion
687
687
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
688
688
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
689
- var loadArkade = () => import("./arkade-DdZx4b_I.js");
689
+ var loadArkade = () => import("./arkade-bFAS6imn.js");
690
690
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
691
691
  var RETIRE_READ_MS = 1e4;
692
692
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -1999,7 +1999,7 @@ var key = (mode) => `fedimintWallet-${mode}`;
1999
1999
  var sats$6 = (msats) => Math.floor(msats / 1e3);
2000
2000
  function assertFedimintAmount(amount) {
2001
2001
  if (!Number.isSafeInteger(amount) || amount <= 0) throw new Error("Enter an amount in sats");
2002
- if (amount > MAX_SATS) throw new Error(`Amounts above ${MAX_SATS.toLocaleString()} sats are not supported`);
2002
+ if (amount > MAX_SATS) throw new Error(`Amounts above ${MAX_SATS.toLocaleString("en-US")} sats are not supported`);
2003
2003
  }
2004
2004
  /** An invite code as the client takes it: bech32m with the prefix `fed1` (so `fed11…`), one line, bounded. */
2005
2005
  function normalizeInvite(text) {
@@ -2666,7 +2666,7 @@ var FedimintAdapter = class {
2666
2666
  if (!federation || federation.network !== target.network) throw new Error("You have not joined this federation in the Fedimint wallet of its network");
2667
2667
  if (!Number.isSafeInteger(feeCap) || feeCap < 0) throw new Error("Invalid maximum fee");
2668
2668
  const balance = Math.floor(await this.wallet.client(target.provider).balance() / 1e3);
2669
- if (balance < amount) throw new Error(`Not enough in this federation: ${balance.toLocaleString()} sats`);
2669
+ if (balance < amount) throw new Error(`Not enough in this federation: ${balance.toLocaleString("en-US")} sats`);
2670
2670
  return {
2671
2671
  fee: 0,
2672
2672
  prepared: {
@@ -3429,6 +3429,10 @@ var SparkWallet = class {
3429
3429
  };
3430
3430
  //#endregion
3431
3431
  //#region ../browser/src/engine/paymentAdapters/coordinator.ts
3432
+ /** A saved intent as text, to tell whether a reconcile changed it: amounts in bigints and bytes count too. */
3433
+ function snapshot(saved) {
3434
+ return JSON.stringify(saved, (_key, value) => typeof value === "bigint" ? `${value}n` : ArrayBuffer.isView(value) ? Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) : value instanceof ArrayBuffer ? Array.from(new Uint8Array(value)) : value);
3435
+ }
3432
3436
  /** Persist-before-spend; a submitted/unknown operation can only be reconciled, never re-executed. */
3433
3437
  var PaymentCoordinator = class {
3434
3438
  repository;
@@ -3511,6 +3515,7 @@ var PaymentCoordinator = class {
3511
3515
  const saved = await this.require(id);
3512
3516
  if (!["submitted", "unknown"].includes(saved.review.state)) return saved.review;
3513
3517
  if (saved.review.parked) return saved.review;
3518
+ const before = snapshot(saved);
3514
3519
  try {
3515
3520
  const result = await this.adapter(saved.review.method).reconcile(saved.review, saved.prepared, () => this.repository.put(saved));
3516
3521
  saved.review = {
@@ -3526,6 +3531,9 @@ var PaymentCoordinator = class {
3526
3531
  error: engineText("couldNotVerify")
3527
3532
  };
3528
3533
  }
3534
+ const latest = await this.repository.get(id);
3535
+ if (latest && !["submitted", "unknown"].includes(latest.review.state)) return latest.review;
3536
+ if (snapshot(saved) === before) return saved.review;
3529
3537
  await this.repository.put(saved);
3530
3538
  this.changed(saved.review);
3531
3539
  return saved.review;
@@ -3625,10 +3633,12 @@ var NEVER_REACHED_MINT = "The payment never reached the mint: nothing was sent,
3625
3633
  var CashuAdapter = class {
3626
3634
  wallet;
3627
3635
  publish;
3636
+ takingBack;
3628
3637
  method = "cashu";
3629
- constructor(wallet, publish) {
3638
+ constructor(wallet, publish, takingBack = () => void 0) {
3630
3639
  this.wallet = wallet;
3631
3640
  this.publish = publish;
3641
+ this.takingBack = takingBack;
3632
3642
  }
3633
3643
  async prepare(target, amount, feeCap) {
3634
3644
  if (target.method !== "cashu" || target.network !== (mintNetwork(target.provider) === "testnet" ? "cashu-test" : "bitcoin")) throw new Error("Cashu mint/network mismatch");
@@ -3657,15 +3667,31 @@ var CashuAdapter = class {
3657
3667
  * What the mint and this wallet know of a payment whose token went out: paid once the mint reads its ecash spent,
3658
3668
  * unless this wallet is the one that spent it, taking the payment back. Asked in that order: ecash taken back while
3659
3669
  * the mint was being asked reads spent too. Undefined while the contact has not taken it.
3670
+ * A Take it back of it under way when the mint is asked, or started while it answers, is waited for: its swap makes
3671
+ * the ecash read spent before the ecash is back here. Ended with the ecash back, the payment was taken back; ended
3672
+ * with the mint saying the contact had it first, it is paid; ended any other way, this round's spent read proves
3673
+ * nothing, and the next round asks again (nothing is sent meanwhile). One whose answer from the mint was lost is still
3674
+ * under way while its redeem is written down: asked before whether the ecash is back, which is stored as it ends.
3660
3675
  */
3661
3676
  async outcome(review, prepared) {
3677
+ const before = this.takingBack(review.id);
3662
3678
  const spent = await this.wallet.reviewedCashuSpent(prepared);
3663
- if (await this.wallet.reviewedCashuTakenBack(review.id)) return {
3679
+ const reclaim = this.takingBack(review.id) ?? before;
3680
+ const ended = await reclaim;
3681
+ const unsettled = await this.wallet.cashuTakingBack(review.id);
3682
+ const back = await this.takenBack(review.id);
3683
+ if (back) return back;
3684
+ if (unsettled || reclaim && ended !== "settled") return { settled: false };
3685
+ return spent ? { settled: true } : void 0;
3686
+ }
3687
+ /** Taken back, waiting for a Take it back under way first: the payment then ends failed, its sats back here. */
3688
+ async takenBack(id) {
3689
+ await this.takingBack(id);
3690
+ return await this.wallet.reviewedCashuTakenBack(id) ? {
3664
3691
  settled: false,
3665
3692
  failed: true,
3666
3693
  error: engineText("paymentTakenBack")
3667
- };
3668
- return spent ? { settled: true } : void 0;
3694
+ } : void 0;
3669
3695
  }
3670
3696
  /** `persist` saves the intent as it is: required, since the abandon path must be durable before it releases anything. */
3671
3697
  async reconcile(review, prepared, persist) {
@@ -3674,9 +3700,11 @@ var CashuAdapter = class {
3674
3700
  const known = await this.outcome(review, prepared);
3675
3701
  if (known) return known;
3676
3702
  const token = prepared.token ?? await this.wallet.recoverReviewedCashu(review, prepared);
3677
- if (token) await this.publish(review, token);
3678
- const after = await this.outcome(review, prepared);
3679
- if (after) return after;
3703
+ if (token) {
3704
+ await this.publish(review, token);
3705
+ const back = await this.takenBack(review.id);
3706
+ if (back) return back;
3707
+ }
3680
3708
  if (!token && Date.now() >= swapSettledAt(review, prepared) && await this.wallet.reviewedCashuNeverSwapped(prepared)) return this.abandon(prepared, persist);
3681
3709
  if (!token && await this.wallet.reviewedCashuSpentElsewhere(prepared)) return this.spentElsewhere(prepared, persist);
3682
3710
  return { settled: false };
@@ -4954,7 +4982,7 @@ var FedimintLightning = class {
4954
4982
  const fee = await this.estimateFee(invoice, amount);
4955
4983
  if (fee > maxFee) throw new Error(`The gateway's fee (${fee} sats) is above your maximum`);
4956
4984
  const balance = Math.floor(await this.client().balance() / 1e3);
4957
- if (balance < amount + fee) throw new Error(`Not enough in this federation (${balance.toLocaleString()} sats; ${(amount + fee).toLocaleString()} needed)`);
4985
+ if (balance < amount + fee) throw new Error(`Not enough in this federation (${balance.toLocaleString("en-US")} sats; ${(amount + fee).toLocaleString("en-US")} needed)`);
4958
4986
  } catch (error) {
4959
4987
  throw isNothingSpentError(error) ? error : new NothingSpentError(message$2(error));
4960
4988
  }
@@ -9234,7 +9262,7 @@ var HostNotContacted = class extends Error {};
9234
9262
  */
9235
9263
  function fixedHostsFetch(fetch) {
9236
9264
  return async (url, options) => {
9237
- const { fixedIdentityHosts } = await import("./fixedHosts-PR1BcfKX.js");
9265
+ const { fixedIdentityHosts } = await import("./fixedHosts-B_2Rvyja.js");
9238
9266
  const host = hostOf$1(url);
9239
9267
  if (!fixedIdentityHosts().has(host) && host !== hostOf$1("https://public.api.bsky.app") && host !== hostOf$1("https://nexus.pubky.app")) throw new HostNotContacted(`Hide my IP from contacts is on: ${host}, a server your contact chose, was not contacted`);
9240
9268
  return fetch(url, options);
@@ -11099,6 +11127,8 @@ function readCount(value) {
11099
11127
  return null;
11100
11128
  }
11101
11129
  }
11130
+ /** What a staged bundle is kept under (`AppPreview.stage`): one install screen's version and source, so another screen of it does not change it. */
11131
+ var stagedKey = (digest, from, store) => `${digest}\n${from}\n${store ?? ""}`;
11102
11132
  /**
11103
11133
  * `run` on every item, at most `limit` at a time (the next one starts when one ends): one promise per item, in the
11104
11134
  * items' order, whatever order they end in.
@@ -11433,7 +11463,10 @@ var Apps = class {
11433
11463
  /** Drops `previewed` past `STAGED.ms`: an index is up to 4 MiB, and a closed Add screen sends no call. */
11434
11464
  previewedSweep = null;
11435
11465
  checking = null;
11436
- /** Runs the person started with Run anyway (`<ref> <digest>`), for this engine's life: a removal does not cut them off. */
11466
+ /**
11467
+ * Runs the person started with Run anyway (`<ref> <digest>`): a removal does not cut them off. Only that run's: dropped
11468
+ * when the version starts without it, when a call finds it no longer removed, and at Uninstall.
11469
+ */
11437
11470
  anyway = /* @__PURE__ */ new Set();
11438
11471
  /** The apps started here (`entry`), for this engine's life: one of them uninstalled since may still have a frame open. */
11439
11472
  ran = /* @__PURE__ */ new Set();
@@ -11628,6 +11661,7 @@ var Apps = class {
11628
11661
  const version = this.versionRunning(app, digest);
11629
11662
  const run = this.runStatus(version, await this.heldViews(), app.revocations);
11630
11663
  if (run.status === "revoked") fail("stopped", "Its publisher revoked this version");
11664
+ if (run.status === "ok") this.anyway.delete(`${version.ref} ${version.digest}`);
11631
11665
  if (run.status === "removed" && !this.anyway.has(`${version.ref} ${version.digest}`)) fail("stopped", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
11632
11666
  return app;
11633
11667
  }
@@ -11675,9 +11709,15 @@ var Apps = class {
11675
11709
  if (!app && this.ran.has(ref)) fail("not-installed", "This app is not installed");
11676
11710
  if (app) await this.stillRunnable(app, digest);
11677
11711
  }
11712
+ /** Writes an app's record, keeping the revocations the record holds now (one kept since the caller read it among them). */
11678
11713
  async putApp(app) {
11714
+ const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
11715
+ const read = tx.objectStore(STORES$1.apps).get(app.ref);
11716
+ read.onsuccess = () => {
11717
+ tx.objectStore(STORES$1.apps).put(withRevocations(app, read.result?.revocations ?? []));
11718
+ };
11679
11719
  try {
11680
- await committed((await store(STORES$1.apps, "readwrite")).put(app));
11720
+ await done(tx);
11681
11721
  } finally {
11682
11722
  this.held.delete(app.ref);
11683
11723
  }
@@ -11687,7 +11727,8 @@ var Apps = class {
11687
11727
  * transaction: an app uninstalled (or installed again) while the update check was reading is not put back, nor is the
11688
11728
  * version it read over an update the person accepted meanwhile. `was` undefined: only while the app has no record.
11689
11729
  * A store removed since the caller read the stores pins nothing: it is judged at the write, as `removeStore` unpins
11690
- * only the records written before it.
11730
+ * only the records written before it. A revocation the record gained since `was` (`keepStoreRevocations`) is kept:
11731
+ * one `app` leaves out on purpose (the check's, of a version gone) was on `was` already.
11691
11732
  */
11692
11733
  async putAppIfUnchanged(app, was) {
11693
11734
  const stores = await this.records();
@@ -11695,7 +11736,10 @@ var Apps = class {
11695
11736
  let put = false;
11696
11737
  const read = tx.objectStore(STORES$1.apps).get(app.ref);
11697
11738
  read.onsuccess = () => {
11698
- if (!sameRecord(read.result, was)) return;
11739
+ const now = read.result;
11740
+ if (!sameRecord(now, was)) return;
11741
+ const had = new Set((was?.revocations ?? []).map((r) => canonicalJson(r)));
11742
+ app = withRevocations(app, (now?.revocations ?? []).filter((r) => !had.has(canonicalJson(r))));
11699
11743
  const { store: pin, ...unpinned } = app;
11700
11744
  tx.objectStore(STORES$1.apps).put(pin !== void 0 && stores.get(pin)?.removed ? unpinned : app);
11701
11745
  put = true;
@@ -11748,9 +11792,10 @@ var Apps = class {
11748
11792
  async keepStoreRevocations(record) {
11749
11793
  const revoked = record.index?.revoked ?? [];
11750
11794
  if (!revoked.length) return;
11751
- for (const app of await this.installed()) {
11795
+ const reread = async (ref) => wrap((await store(STORES$1.apps, "readonly")).get(ref));
11796
+ for (const first of await this.installed()) for (let app = first; app; app = await reread(first.ref)) {
11752
11797
  const next = withRevocations(app, stopping(this.versionsOf(app), revoked));
11753
- if ((next.revocations?.length ?? 0) > (app.revocations?.length ?? 0)) await this.putAppIfUnchanged(next, app);
11798
+ if ((next.revocations?.length ?? 0) <= (app.revocations?.length ?? 0) || await this.putAppIfUnchanged(next, app)) break;
11754
11799
  }
11755
11800
  }
11756
11801
  /** The stores' views, made once and again after a store is written here: an app's every storage call and chat frame checks them. */
@@ -12457,10 +12502,10 @@ var Apps = class {
12457
12502
  };
12458
12503
  } else fail("bad-source", "No app to fetch");
12459
12504
  if (!urls.length) fail("host", "This listing has no URL Ghostly reads from");
12460
- const kept = expect?.digest !== void 0 ? this.staged.get(expect.digest) : void 0;
12461
12505
  let last = null;
12462
12506
  for (const url of urls) try {
12463
- const { bundle, bytes } = kept && kept.from === url && this.now() - kept.at <= STAGED.ms ? kept : await this.fetchBundle(url);
12507
+ const kept = expect?.digest !== void 0 ? this.staged.get(stagedKey(expect.digest, url, fromStore)) : void 0;
12508
+ const { bundle, bytes } = kept && this.now() - kept.at <= STAGED.ms ? kept : await this.fetchBundle(url);
12464
12509
  const version = versionOf(bundle.manifest, bundle.digest);
12465
12510
  if (expect) {
12466
12511
  if (version.ref !== expect.ref) fail("other-app", "The URL holds another app");
@@ -12477,7 +12522,7 @@ var Apps = class {
12477
12522
  /** Drops the staged bundles past `STAGED.ms`, and comes back when the oldest left is due. */
12478
12523
  sweepStaged() {
12479
12524
  this.sweep = null;
12480
- for (const [digest, s] of this.staged) if (this.now() - s.at >= STAGED.ms) this.staged.delete(digest);
12525
+ for (const [key, s] of this.staged) if (this.now() - s.at >= STAGED.ms) this.staged.delete(key);
12481
12526
  const oldest = this.staged.values().next().value;
12482
12527
  if (oldest) this.sweep = setTimeout(() => this.sweepStaged(), STAGED.ms - (this.now() - oldest.at));
12483
12528
  }
@@ -12497,9 +12542,10 @@ var Apps = class {
12497
12542
  const install = decision === "other-app" ? "new" : decision;
12498
12543
  const asks = install === "new" ? [...manifest.permissions] : install === "update" ? manifest.permissions.filter((p) => !installed.permissions.includes(p)) : [];
12499
12544
  for (const [d, s] of this.staged) if (this.now() - s.at > STAGED.ms) this.staged.delete(d);
12500
- this.staged.delete(digest);
12545
+ const stage = stagedKey(digest, from, fromStore);
12546
+ this.staged.delete(stage);
12501
12547
  while (this.staged.size >= STAGED.max) this.staged.delete(this.staged.keys().next().value);
12502
- this.staged.set(digest, {
12548
+ this.staged.set(stage, {
12503
12549
  bundle,
12504
12550
  bytes,
12505
12551
  from,
@@ -12523,7 +12569,8 @@ var Apps = class {
12523
12569
  run: this.runStatus(version, this.storeViews(stores), [...installed?.revocations ?? [], ...revocations]),
12524
12570
  listedBy,
12525
12571
  unknownPublisher: !listedBy.some((s) => s.kind === "curated"),
12526
- ...carried && { carried: true }
12572
+ ...carried && { carried: true },
12573
+ stage
12527
12574
  };
12528
12575
  }
12529
12576
  /**
@@ -12531,12 +12578,16 @@ var Apps = class {
12531
12578
  * for (WISP 1200 § Permissions: none is granted by a store or a contact). A revoked or removed version is not
12532
12579
  * installed; neither is a rollback, nor another bundle under an installed `sequence` (marked on the app). `asks` is
12533
12580
  * what the person's screen listed (`AppPreview.asks`; the last screen of this bundle when not given): what this install
12534
- * adds to the record it writes over must be among it, else the screen is shown again first.
12535
- */
12536
- async install({ digest, grant, asks }) {
12537
- const staged = this.staged.get(digest);
12538
- if (!staged || this.now() - staged.at > STAGED.ms) {
12539
- this.staged.delete(digest);
12581
+ * adds to the record it writes over must be among it, else the screen is shown again first. `stage` is the screen's
12582
+ * (`AppPreview.stage`): it installs from that screen's source and store; without it, only while one source of the
12583
+ * bundle waits.
12584
+ */
12585
+ async install({ stage, digest, grant, asks }) {
12586
+ const live = [...this.staged].filter(([key, s]) => s.bundle.digest === digest && (stage === void 0 || key === stage) && this.now() - s.at <= STAGED.ms);
12587
+ if (live.length > 1) fail("screens", "This app was fetched from more than one place; install it from its screen");
12588
+ const [key, staged] = live[0] ?? [stage ?? ""];
12589
+ if (!staged) {
12590
+ this.staged.delete(key);
12540
12591
  fail("expired", "Fetch the app again");
12541
12592
  }
12542
12593
  const { bundle, bytes, from, store: fromStore, revocations } = staged;
@@ -12587,7 +12638,7 @@ var Apps = class {
12587
12638
  }, installed)) continue;
12588
12639
  if (pin && pending) await this.removeBundle(pending.bytes, pending.digest);
12589
12640
  }
12590
- this.staged.delete(digest);
12641
+ this.staged.delete(key);
12591
12642
  return this.view(await this.app(version.ref), stores);
12592
12643
  }
12593
12644
  const kind = wrote = await this.writeBundle(digest, bytes);
@@ -12596,7 +12647,7 @@ var Apps = class {
12596
12647
  if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
12597
12648
  if (installed && installed.digest !== digest) await this.removeBundle(installed.bytes, installed.digest);
12598
12649
  if (installed?.pending && next.pending?.digest !== installed.pending.digest && installed.pending.digest !== digest) await this.removeBundle(installed.pending.bytes, installed.pending.digest);
12599
- this.staged.delete(digest);
12650
+ this.staged.delete(key);
12600
12651
  return this.view(next, stores);
12601
12652
  }
12602
12653
  } catch (error) {
@@ -12981,13 +13032,15 @@ var Apps = class {
12981
13032
  let app = await this.installedOrFail(ref);
12982
13033
  let run = await this.runCheckOf(app, await this.stores());
12983
13034
  if (run.status === "needs-files") {
12984
- run = await this.fetchFiles({ ref });
13035
+ await this.fetchFiles({ ref });
12985
13036
  app = await this.installedOrFail(ref);
13037
+ run = await this.runCheckOf(app, await this.stores());
12986
13038
  }
12987
13039
  if (run.status === "revoked") fail("revoked", "Its publisher revoked this version");
12988
13040
  if (run.status === "removed" && runAnyway !== true) fail("removed", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
12989
13041
  if (run.status === "needs-files") fail("needs-files", "This app's files are not on this device yet");
12990
13042
  if (run.status === "removed") this.anyway.add(`${app.ref} ${app.digest}`);
13043
+ else this.anyway.delete(`${app.ref} ${app.digest}`);
12991
13044
  const bundle = await this.verifiedBundle(app, true);
12992
13045
  const entry = bundle.files.get(bundle.manifest.entry) ?? fail("damaged", "The entry is missing");
12993
13046
  this.ran.add(app.ref);
@@ -13118,6 +13171,7 @@ var Apps = class {
13118
13171
  }
13119
13172
  for (const key of [...this.usage.keys()]) if (key.startsWith(`${ref}\0`)) this.usage.delete(key);
13120
13173
  this.started.delete(ref);
13174
+ for (const key of [...this.anyway]) if (key.startsWith(`${ref} `)) this.anyway.delete(key);
13121
13175
  if (!app) return;
13122
13176
  await this.removeBundle(app.bytes, app.digest);
13123
13177
  if (app.pending) await this.removeBundle(app.pending.bytes, app.pending.digest);
@@ -16119,7 +16173,8 @@ var EnrollJoiner = class extends Enrollment {
16119
16173
  return;
16120
16174
  }
16121
16175
  this.proven = true;
16122
- const grantMs = this.options.timing?.grantMs ?? Math.max(0, this.invite.invite.expires * 1e3 - this.now()) + 6e4;
16176
+ const left = Math.min(Math.max(0, this.invite.invite.expires * 1e3 - this.now()), 6e5);
16177
+ const grantMs = this.options.timing?.grantMs ?? left + 6e4;
16123
16178
  this.timer(grantMs, () => {
16124
16179
  if (!this.committed && this.view.step === "confirm") this.fail("unanswered", "failed");
16125
16180
  });
@@ -19067,6 +19122,7 @@ var HandoffGiver = class {
19067
19122
  const record = await this.ports.records.read();
19068
19123
  if (!record || record.state !== "active") throw new Error("handoff-refused: Only the active device moves the profile.");
19069
19124
  if (slotOf(record, key) < 0) throw new Error("handoff-refused: That device is not one of this profile's.");
19125
+ if (this.ports.setChanging?.()) throw new Error("handoff-busy: Another move is in progress.");
19070
19126
  const busy = reportOf(await this.ports.busy(this.takerFacts(key)));
19071
19127
  if (busy) throw new Error(`handoff-${busy.why}:${busy.wallet ? `${busy.wallet}:` : ""} This device cannot move the profile now.`);
19072
19128
  if (!this.ports.links.live(key)) {
@@ -19131,7 +19187,7 @@ var HandoffGiver = class {
19131
19187
  if (key !== this.peer) return;
19132
19188
  if (!live) {
19133
19189
  this.sender.stop();
19134
- if (this.phase === "authorizing") this.reset("dropped");
19190
+ if (this.phase === "authorizing") await this.unproved(key);
19135
19191
  if (this.phase === "pass2") this.arm(HANDOFF_TIMINGS.idleMs, () => this.backToActive());
19136
19192
  this.changed();
19137
19193
  return;
@@ -19273,6 +19329,7 @@ var HandoffGiver = class {
19273
19329
  if (slotOf(record, from) < 0) return busy("refused", 0);
19274
19330
  const pushed = this.phase === "offered" && from === this.peer && request.id === this.id;
19275
19331
  if (this.phase !== "idle" && this.phase !== "failed" && !pushed) return busy("handoff");
19332
+ if (this.ports.setChanging?.()) return busy("handoff");
19276
19333
  const session = this.sessionFor(from);
19277
19334
  if (!session?.peer) return busy("handoff", 5);
19278
19335
  const local = reportOf(await this.ports.busy(this.takerFacts(from)));
@@ -19337,7 +19394,7 @@ var HandoffGiver = class {
19337
19394
  n: 2,
19338
19395
  m: this.pake.second
19339
19396
  }), from);
19340
- this.arm(HANDOFF_TIMINGS.idleMs, () => this.reset("dropped"));
19397
+ this.arm(HANDOFF_TIMINGS.idleMs, () => this.unproved(from));
19341
19398
  return;
19342
19399
  }
19343
19400
  if (pake.n !== 3 || !this.pake) return;
@@ -19369,6 +19426,16 @@ var HandoffGiver = class {
19369
19426
  const record = await this.ports.records.read();
19370
19427
  this.reset("password", handoffAttemptAllowed(record?.handoffAttempts?.[from], this.now()) === "refused");
19371
19428
  }
19429
+ /**
19430
+ * A pull that ends in `authorizing` with no proof (its link closed, or the minute out). Past the second message the
19431
+ * taker could check its password on it alone, so stopping there is a guess like a wrong password, and said as one;
19432
+ * before it, the move just stopped. The try stays counted either way.
19433
+ */
19434
+ async unproved(from) {
19435
+ if (this.phase !== "authorizing") return;
19436
+ if (this.pake) await this.wrongPassword(from);
19437
+ else this.reset("dropped");
19438
+ }
19372
19439
  /** The proof held (a pull) or the person agreed (a push): the first session's key, and pass 1. */
19373
19440
  authorized(session, k) {
19374
19441
  session.key = handoffStreamKey(session.ephemeral.secret, fromBase64Url(session.peer.e), k, session.transcript);
@@ -20655,6 +20722,11 @@ var ANNOUNCED_FOR_MS = 6048e5;
20655
20722
  var floorRefusal = (why) => why === "no-room" ? "No room on this device for this file" : why === "too-many" ? "Too many files are waiting here" : "It was refused here";
20656
20723
  /** Progress is written to the database at most this often; every change of state is written at once. */
20657
20724
  var SAVE_EVERY_MS = 2e3;
20725
+ /**
20726
+ * The clock of a transfer's durations kept in memory (when it last moved, its speed, its last progress write): monotonic,
20727
+ * so the device's clock set back mid-transfer neither hides it stuck nor freezes its speed for as long as the step.
20728
+ */
20729
+ var elapsed = () => performance.now();
20658
20730
  /** A transfer's state the database refused is written again this often, until it goes (`FileDesk.save`). */
20659
20731
  var REWRITE_AFTER_MS = 5e3;
20660
20732
  /** The views of finished transfers the states carry, the newest (`FileDesk.finished`). */
@@ -20734,7 +20806,7 @@ var FileDesk = class {
20734
20806
  if (!transferEnded(file.wire3)) this.restored.add(file.id);
20735
20807
  else if (file.wire3.state !== "done" || !unsettled.has(file.id)) this.ended.add(file.id);
20736
20808
  if (file.wire3.state === "done") continue;
20737
- this.deps.transfers.set(file.id, this.view(chat, file.wire3, file.wire3.confirmed, transferStalled(file.wire3, Date.now(), this.restored.has(file.id), Date.now())));
20809
+ this.deps.transfers.set(file.id, this.view(chat, file.wire3, file.wire3.confirmed, transferStalled(file.wire3, elapsed(), this.restored.has(file.id), elapsed())));
20738
20810
  }
20739
20811
  chat.files.restore(records);
20740
20812
  }
@@ -20901,7 +20973,7 @@ var FileDesk = class {
20901
20973
  if (action === "resend" !== out) throw new Error(out ? "A file you sent is sent again, not asked for" : "A file you receive is asked for again, not sent");
20902
20974
  const now = out ? chat.files.resend(wireId) : chat.files.request(wireId);
20903
20975
  this.restored.delete(fileId);
20904
- this.moved.set(fileId, { at: Date.now() });
20976
+ this.moved.set(fileId, { at: elapsed() });
20905
20977
  const current = chat.files.get(direction, wireId);
20906
20978
  if (current) this.show(linkId, chat, current, chat.files.transferred(direction, wireId));
20907
20979
  this.deps.changed();
@@ -21158,7 +21230,7 @@ var FileDesk = class {
21158
21230
  this.show(linkId, chat, record, transferred, progress);
21159
21231
  if (offered) this.deps.flush?.();
21160
21232
  const id = record.direction === "out" ? outgoingFileId(linkId, record.id) : chat.local.get(record.id);
21161
- const now = Date.now(), last = chat.lastSaved.get(id) ?? 0;
21233
+ const now = elapsed(), last = chat.lastSaved.get(id) ?? -Infinity;
21162
21234
  if (!progress || now - last >= SAVE_EVERY_MS) this.save(chat, id, record);
21163
21235
  else {
21164
21236
  const held = chat.unsaved.get(id);
@@ -21214,7 +21286,7 @@ var FileDesk = class {
21214
21286
  chat.unsaved.delete(id);
21215
21287
  }
21216
21288
  if (transferEnded(record)) chat.lastSaved.delete(id);
21217
- else chat.lastSaved.set(id, Date.now());
21289
+ else chat.lastSaved.set(id, elapsed());
21218
21290
  const transfer = this.deps.transfers.get(id);
21219
21291
  const change = {
21220
21292
  wire3: record,
@@ -21251,7 +21323,7 @@ var FileDesk = class {
21251
21323
  if (!id) return;
21252
21324
  const view = this.view(chat, record, transferred, this.stalled(linkId, id, record, progress));
21253
21325
  if (view.state === "transferring" && !view.stage) {
21254
- const now = Date.now(), last = this.speeds.get(id);
21326
+ const now = elapsed(), last = this.speeds.get(id);
21255
21327
  if (!last) this.speeds.set(id, {
21256
21328
  bytes: transferred,
21257
21329
  at: now,
@@ -21294,7 +21366,7 @@ var FileDesk = class {
21294
21366
  this.unwatch(id);
21295
21367
  return false;
21296
21368
  }
21297
- const now = Date.now();
21369
+ const now = elapsed();
21298
21370
  if (progress || !this.moved.has(id)) this.moved.set(id, { at: now });
21299
21371
  if (progress) this.restored.delete(id);
21300
21372
  const movedAt = this.moved.get(id).at;
@@ -21716,8 +21788,31 @@ var RESEND_POLICY = {
21716
21788
  /** Queued this long with the contact away, it is handed to store-and-forward when the chat allows it. */
21717
21789
  holdAfterMs: 6e4
21718
21790
  };
21791
+ /**
21792
+ * What a send hands back when the message did not leave this device: every relay refused it or was not asked, and it
21793
+ * was not out before (`PublishFailedError`). Nothing about it is unconfirmed: a message that had not gone before waits
21794
+ * again (`waiting`, so it can be cancelled), and the ones written after it wait behind it (`NotSent.REASON`).
21795
+ */
21796
+ var NotSent = class {
21797
+ error;
21798
+ /** What a message that waits again says, in its details. */
21799
+ static REASON = "No relay took it, so it has not left this device. It is sent by itself once one does.";
21800
+ /** `error`: what the send said, kept as it was for a message queued already. */
21801
+ constructor(error) {
21802
+ this.error = error;
21803
+ }
21804
+ };
21719
21805
  /** How long one turn of an outbox may hold the next one back: a send that never returns must not stop the chat. */
21720
21806
  var TURN_MS = 3e4;
21807
+ /** The newest messages deleted here an outbox keeps from going (`Outbox.cancel`); their rows are long gone by the oldest. */
21808
+ var KEPT_CANCELLED = 1e3;
21809
+ /**
21810
+ * How far past a whole window ahead a stored deadline may be before it counts as set by a clock that went back since
21811
+ * (`Outbox.pastDeadline`): the wall clock and the monotonic one drift apart a little in a session.
21812
+ */
21813
+ var DEADLINE_SKEW_MS = 6e4;
21814
+ /** The longest delay a timer keeps: past it (about 24.8 days) `setTimeout` fires at once, in Node and in browsers. */
21815
+ var MAX_TIMER_MS = 2 ** 31 - 1;
21721
21816
  /** The most rows a new message's look reads one by one (`Outbox.look`), where the store cannot read them in one go. */
21722
21817
  var KNOWN_ROWS = 16;
21723
21818
  /**
@@ -21751,10 +21846,35 @@ var Outbox = class {
21751
21846
  pendingUntil;
21752
21847
  /** Sent, awaiting a receipt. */
21753
21848
  receipts = /* @__PURE__ */ new Map();
21754
- /** Queued: when it is looked at again, how far along the backoff, since when. */
21849
+ /**
21850
+ * Queued: when it is looked at again, how far along the backoff, since when. `at` and `since` are on the monotonic
21851
+ * clock (`monotonic`): they live only in this session, and a step of the device clock must not move them. Read by the
21852
+ * wall clock, a clock set back an hour after a text was queued handed it to store-and-forward an hour late, not at
21853
+ * its first check past a minute (`holdAfterMs`).
21854
+ */
21755
21855
  waiting = /* @__PURE__ */ new Map();
21856
+ /**
21857
+ * Stored deadlines (`resendUntil`) found further ahead than a whole window after the device clock went back, each
21858
+ * with the deadline it is held to in this session: a window from when it was found so (`pastDeadline`).
21859
+ */
21860
+ deadlines = /* @__PURE__ */ new Map();
21756
21861
  attempts = /* @__PURE__ */ new Map();
21757
21862
  busy = /* @__PURE__ */ new Set();
21863
+ /**
21864
+ * Texts whose last send did not leave this device (`NotSent`) and had not gone before, by id, with their time: what
21865
+ * was written after one goes only once it has (`behindUnsent`), so the contact reads them in order.
21866
+ */
21867
+ unsent = /* @__PURE__ */ new Map();
21868
+ /**
21869
+ * Texts found waiting behind an unsent one, with their time. While that one cannot go in a turn (`parkedBehind`), a
21870
+ * look does not read them: none of them can go before it, and each new text read every one of them again, 200 rows
21871
+ * per send with 200 waiting.
21872
+ */
21873
+ behind = /* @__PURE__ */ new Map();
21874
+ /** The unsent texts this turn read and found still to go: read once per turn, not once per text behind them. */
21875
+ stillUnsent = /* @__PURE__ */ new Map();
21876
+ /** Unsent texts whose followers this turn's look did not read: they go at their own check, not in this turn. */
21877
+ parked = /* @__PURE__ */ new Set();
21758
21878
  /** Still in flight when the look a reopened chat asked for began (`flush({ reopened })`): sent again once that send returns. */
21759
21879
  reopenedWhileBusy = /* @__PURE__ */ new Set();
21760
21880
  /** The turns taken so far, one after the other (`turn`). */
@@ -21784,9 +21904,19 @@ var Outbox = class {
21784
21904
  looks = 0;
21785
21905
  looked = 0;
21786
21906
  stopped = false;
21907
+ /**
21908
+ * Messages deleted here (`cancel`): never handed to `send`, whatever a look in progress read of them. A look reads a
21909
+ * row, then marks it and sends what it read: a Cancel sending in between deleted the row and the text went anyway.
21910
+ */
21911
+ cancelled = /* @__PURE__ */ new Set();
21912
+ /** Handed to `send` and not back yet, each with whether it was waiting (it had not left this device) when its send began. */
21913
+ handed = /* @__PURE__ */ new Map();
21787
21914
  resender;
21788
21915
  policy;
21789
21916
  now;
21917
+ monotonic;
21918
+ /** The wall clock and the monotonic clock when this outbox began: `clock` counts on from there. */
21919
+ origin;
21790
21920
  constructor(store, send, timeoutMs = 2e4, pendingUntil, options = {}) {
21791
21921
  this.store = store;
21792
21922
  this.send = send;
@@ -21798,6 +21928,37 @@ var Outbox = class {
21798
21928
  ...options.policy
21799
21929
  };
21800
21930
  this.now = options.now ?? Date.now;
21931
+ this.monotonic = options.monotonic ?? (() => performance.now());
21932
+ this.origin = {
21933
+ wall: this.now(),
21934
+ monotonic: this.monotonic()
21935
+ };
21936
+ }
21937
+ /**
21938
+ * The time a stored deadline (`resendUntil`, set by the wall clock) is judged by: the wall clock, never ahead of the
21939
+ * time this session has run since it began. A clock set forward 8 days failed every queued text at its next check,
21940
+ * as not confirmed within 7 days, a few seconds after it was written.
21941
+ */
21942
+ clock() {
21943
+ return Math.min(this.now(), this.origin.wall + this.monotonic() - this.origin.monotonic);
21944
+ }
21945
+ /**
21946
+ * Its window to go is over (`resendUntil`, by `clock`). A deadline further ahead than a whole window was set before
21947
+ * the device clock went back: it counts a window from the moment it is found so, as `DhtDelivery` bounds its times,
21948
+ * not for as long as the clock went back. The row keeps what was stored.
21949
+ */
21950
+ pastDeadline(message) {
21951
+ const stored = message.resendUntil;
21952
+ if (stored === void 0) return false;
21953
+ const now = this.clock(), held = this.deadlines.get(message.id);
21954
+ let until = held?.stored === stored ? held.until : stored;
21955
+ if (until > now + this.policy.windowMs + DEADLINE_SKEW_MS) until = now + this.policy.windowMs;
21956
+ if (until !== stored) this.deadlines.set(message.id, {
21957
+ stored,
21958
+ until
21959
+ });
21960
+ else this.deadlines.delete(message.id);
21961
+ return until <= now;
21801
21962
  }
21802
21963
  /** `messages`: the chat's history as the caller just read it (a start has), so it is not read a second time. */
21803
21964
  async recover(messages) {
@@ -21816,7 +21977,7 @@ var Outbox = class {
21816
21977
  const until = this.pendingUntil?.(message);
21817
21978
  if (until && until > this.now()) {
21818
21979
  await this.store.update(message.id, "sent");
21819
- this.track(message.id, until - this.now());
21980
+ this.track(message.id, Math.min(until - this.now(), this.receiptWindow(message)));
21820
21981
  } else if (until !== void 0) await this.expired(message);
21821
21982
  else await this.queue(message, "Not confirmed before the app closed. It is sent again, under the same ID, once your contact is reachable.");
21822
21983
  }
@@ -21836,6 +21997,8 @@ var Outbox = class {
21836
21997
  await this.requeueUnconfirmed();
21837
21998
  }
21838
21999
  this.began = this.closed;
22000
+ this.stillUnsent.clear();
22001
+ this.parked.clear();
21839
22002
  return run();
21840
22003
  });
21841
22004
  this.line = before.then(() => new Promise((next) => {
@@ -21856,6 +22019,20 @@ var Outbox = class {
21856
22019
  for (const wait of this.waiting.values()) if (wait.timer) return true;
21857
22020
  return false;
21858
22021
  }
22022
+ /**
22023
+ * The message is deleted here (Cancel sending, a delete, a delete for everyone): from now on it never goes, and
22024
+ * nothing of it is retried. A send already handed to the link cannot be called back: true when that send is of a text
22025
+ * that was waiting (it had not left this device), so the caller, who meant it never to leave, removes it from the
22026
+ * contact too. No row is read: the answer is what this outbox is doing with it right now.
22027
+ */
22028
+ cancel(id) {
22029
+ this.cancelled.delete(id);
22030
+ this.cancelled.add(id);
22031
+ if (this.cancelled.size > KEPT_CANCELLED) this.cancelled.delete(this.cancelled.values().next().value);
22032
+ this.clear(id);
22033
+ this.forget(id);
22034
+ return this.handed.get(id) === true;
22035
+ }
21859
22036
  /** One message as stored now: by its id when the store can, else picked out of the chat's history. */
21860
22037
  async one(id) {
21861
22038
  return this.store.get ? this.store.get(id) : (await this.store.read()).find((m) => m.id === id);
@@ -21930,16 +22107,46 @@ var Outbox = class {
21930
22107
  * are never more than the history.
21931
22108
  */
21932
22109
  async look(id) {
21933
- if (!this.store.get || !this.known || !this.store.getMany && this.waiting.size + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
22110
+ if (!this.store.get || !this.known) return this.store.read();
22111
+ const { skip, parked } = await this.parkedBehind();
22112
+ const waiting = [...this.waiting.keys()].filter((known) => known === id || !skip.has(known) || this.receipts.has(known) || this.onTheirWay.has(known));
22113
+ if (!this.store.getMany && waiting.length + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
22114
+ if (waiting.length < this.waiting.size) for (const unsent of parked) this.parked.add(unsent);
21934
22115
  const ids = /* @__PURE__ */ new Set([
21935
22116
  ...id === void 0 ? [] : [id],
21936
- ...this.waiting.keys(),
22117
+ ...waiting,
21937
22118
  ...this.receipts.keys(),
21938
22119
  ...this.onTheirWay.keys()
21939
22120
  ]);
21940
22121
  return (this.store.getMany ? await this.store.getMany([...ids]) : await Promise.all([...ids].map((known) => this.store.get(known)))).filter((row) => !!row);
21941
22122
  }
21942
22123
  /**
22124
+ * The texts no relay took that cannot go in this turn: each waits for its own check to be published again (`attempt`),
22125
+ * and is still to go, within its window. What waits behind one of them (`behind`) cannot go in this turn either.
22126
+ */
22127
+ async parkedBehind() {
22128
+ const skip = /* @__PURE__ */ new Set(), parked = [];
22129
+ if (!this.behind.size || !this.resender.via) return {
22130
+ skip,
22131
+ parked
22132
+ };
22133
+ let from = Infinity;
22134
+ for (const [id, timestamp] of this.unsent) {
22135
+ if (!this.waiting.get(id)?.timer || this.busy.has(id)) continue;
22136
+ const row = this.stillUnsent.get(id) ?? await this.one(id);
22137
+ if (!row || !toGo(row)) continue;
22138
+ this.stillUnsent.set(id, row);
22139
+ if (this.pastDeadline(row) || this.resender.via(row) !== "pkarr") continue;
22140
+ parked.push(id);
22141
+ from = Math.min(from, timestamp);
22142
+ }
22143
+ for (const [id, timestamp] of this.behind) if (timestamp >= from && !parked.includes(id)) skip.add(id);
22144
+ return {
22145
+ skip,
22146
+ parked
22147
+ };
22148
+ }
22149
+ /**
21943
22150
  * What a look at the chat takes up comes from: the rows this outbox holds, by id, where it knows them all (`look`);
21944
22151
  * else the chat's whole history, which, when it shows nothing of mine to go that this outbox did not know of, says
21945
22152
  * so until the next row stored by someone else. A session that opened with nothing queued, nothing awaiting a
@@ -22006,6 +22213,10 @@ var Outbox = class {
22006
22213
  /** A waiting file is said on the link, after the older messages passed by that can go now. False: the link cannot carry it. */
22007
22214
  async fileGoes(message, passed) {
22008
22215
  if (!this.resender.ready(message)) {
22216
+ if (message.fileOnFloor) {
22217
+ this.holdUnchecked(message.id);
22218
+ return false;
22219
+ }
22009
22220
  if (!this.waiting.get(message.id)?.timer) this.schedule(message.id);
22010
22221
  return false;
22011
22222
  }
@@ -22014,7 +22225,15 @@ var Outbox = class {
22014
22225
  if (!this.stopped && !this.waiting.get(message.id)?.timer) this.schedule(message.id);
22015
22226
  return true;
22016
22227
  }
22017
- await this.resender.sendFile(message).catch(() => {});
22228
+ if (await this.behindUnsent(message)) {
22229
+ if (!this.waiting.get(message.id)?.timer) this.schedule(message.id);
22230
+ return true;
22231
+ }
22232
+ if (this.cancelled.has(message.id)) {
22233
+ this.forget(message.id);
22234
+ return true;
22235
+ }
22236
+ await this.resender.sendFile(message, () => this.cancelled.has(message.id)).catch(() => {});
22018
22237
  this.forget(message.id);
22019
22238
  this.stamp++;
22020
22239
  return true;
@@ -22054,12 +22273,15 @@ var Outbox = class {
22054
22273
  }
22055
22274
  /** `read`: the message's row, when it was read just now with nothing awaited since. */
22056
22275
  async transmitNow(id, { manual = false } = {}, read) {
22057
- if (this.stopped || this.busy.has(id) || this.receipts.has(id)) return;
22276
+ if (this.stopped || this.busy.has(id) || this.receipts.has(id) || this.cancelled.has(id)) return;
22058
22277
  this.busy.add(id);
22059
22278
  let again;
22060
22279
  try {
22061
22280
  let message = read ?? await this.one(id);
22062
22281
  if (!message?.wireId || !message.delivery || message.delivery === "delivered") return;
22282
+ if (!manual && await this.behindUnsent(message)) return await this.waitBehind(message);
22283
+ this.behind.delete(id);
22284
+ const unsentBefore = message.delivery === "waiting" || message.delivery === "sending" && !this.attempts.get(id);
22063
22285
  const wait = this.waiting.get(id);
22064
22286
  if (wait?.timer) {
22065
22287
  clearTimeout(wait.timer);
@@ -22070,7 +22292,8 @@ var Outbox = class {
22070
22292
  this.waiting.delete(id);
22071
22293
  }
22072
22294
  this.attempts.set(id, (this.attempts.get(id) ?? 0) + 1);
22073
- const via = this.resender.via?.(message) ?? message.via;
22295
+ const via = this.resender.via?.(message) ?? message.via, wasWaiting = message.delivery === "waiting";
22296
+ if (this.cancelled.has(id)) return this.forget(id);
22074
22297
  await this.store.update(id, "sending", void 0, {
22075
22298
  via,
22076
22299
  ...manual ? { resendUntil: void 0 } : {}
@@ -22088,14 +22311,30 @@ var Outbox = class {
22088
22311
  }, "Connection closed. Delivery is unconfirmed.");
22089
22312
  return;
22090
22313
  }
22314
+ if (this.cancelled.has(id)) return this.forget(id);
22091
22315
  this.track(id, typeof this.timeoutMs === "number" ? this.timeoutMs : this.timeoutMs(message));
22092
22316
  this.sentUnder.set(id, this.opened);
22093
- const error = await this.send(message);
22094
- if (error) {
22317
+ this.handed.set(id, wasWaiting);
22318
+ let error;
22319
+ try {
22320
+ error = await this.send(message);
22321
+ } finally {
22322
+ this.handed.delete(id);
22323
+ }
22324
+ if (this.cancelled.has(id)) {
22325
+ this.clear(id);
22326
+ return this.forget(id);
22327
+ }
22328
+ if (!(error instanceof NotSent)) this.unsent.delete(id);
22329
+ if (error instanceof NotSent && unsentBefore) {
22330
+ this.clear(id);
22331
+ await this.notSent(id);
22332
+ } else if (error) {
22095
22333
  this.clear(id);
22096
- await this.requeue(id, error);
22334
+ await this.requeue(id, error instanceof NotSent ? error.error : error);
22097
22335
  } else if (this.receipts.has(id)) await this.store.update(id, "sent");
22098
22336
  } catch (error) {
22337
+ this.unsent.delete(id);
22099
22338
  this.clear(id);
22100
22339
  await this.requeue(id, error instanceof Error ? error.message : "Sending failed");
22101
22340
  } finally {
@@ -22166,7 +22405,7 @@ var Outbox = class {
22166
22405
  await this.attempt(id);
22167
22406
  return;
22168
22407
  }
22169
- const soon = this.now() + this.policy.backoffMs[0], taken = [];
22408
+ const soon = this.monotonic() + this.policy.backoffMs[0], taken = [];
22170
22409
  let until = message.timestamp;
22171
22410
  for (const m of messages) {
22172
22411
  const wait = this.waiting.get(m.id);
@@ -22191,7 +22430,7 @@ var Outbox = class {
22191
22430
  */
22192
22431
  waitsOn(message) {
22193
22432
  const wait = this.waiting.get(message.id);
22194
- return !!wait && (message.delivery === "queued" || message.delivery === "waiting") && message.via !== "hold" && (message.resendUntil ?? Infinity) > this.now() && !this.resender.ready(message) && !(this.resender.divert && this.now() - wait.since >= this.policy.holdAfterMs);
22433
+ return !!wait && (message.delivery === "queued" || message.delivery === "waiting") && message.via !== "hold" && !this.pastDeadline(message) && !this.resender.ready(message) && !(this.resender.divert && this.monotonic() - wait.since >= this.policy.holdAfterMs);
22195
22434
  }
22196
22435
  /**
22197
22436
  * A queued or waiting message is looked at; one sent and awaiting its receipt goes again now, if the chat can carry
@@ -22237,6 +22476,7 @@ var Outbox = class {
22237
22476
  this.reopenedWhileBusy.clear();
22238
22477
  for (const wait of this.waiting.values()) if (wait.timer) clearTimeout(wait.timer);
22239
22478
  this.waiting.clear();
22479
+ this.behind.clear();
22240
22480
  this.dropped = false;
22241
22481
  await this.requeueUnconfirmed();
22242
22482
  }
@@ -22248,44 +22488,104 @@ var Outbox = class {
22248
22488
  */
22249
22489
  async attempt(id, passed, read) {
22250
22490
  if (this.stopped || this.busy.has(id)) return true;
22491
+ if (this.cancelled.has(id)) {
22492
+ this.forget(id);
22493
+ return true;
22494
+ }
22251
22495
  if (read && this.waitsOn(read)) {
22252
22496
  if (!this.waiting.get(id)?.timer) this.schedule(id);
22253
22497
  return false;
22254
22498
  }
22499
+ if (read?.wireId && this.unsent.size && !this.unsent.has(id) && !this.receipts.has(id) && (read.delivery === "queued" || read.delivery === "waiting") && read.via !== "hold" && !this.pastDeadline(read) && this.resender.ready(read)) {
22500
+ if (passed) await this.catchUp(passed);
22501
+ if (!this.busy.has(id) && await this.behindUnsent(read)) {
22502
+ await this.waitBehind(read);
22503
+ return true;
22504
+ }
22505
+ }
22255
22506
  const message = await this.one(id);
22256
22507
  if (!message || message.delivery !== "queued" && message.delivery !== "waiting" || message.via === "hold") {
22257
22508
  this.forget(id);
22258
22509
  return true;
22259
22510
  }
22260
- if ((message.resendUntil ?? Infinity) <= this.now()) {
22511
+ if (this.pastDeadline(message)) {
22261
22512
  if (message.delivery === "waiting") {
22262
22513
  this.forget(id);
22263
22514
  await this.store.update(id, "failed", `Your contact was not reachable within ${days(this.policy.windowMs)}. It was not sent; Retry sends it.`);
22264
22515
  } else await this.fail(id, `Not confirmed within ${days(this.policy.windowMs)}.`);
22265
22516
  return true;
22266
22517
  }
22518
+ const wait = this.waiting.get(id);
22519
+ if (wait?.timer && this.unsent.has(id) && this.resender.via?.(message) === "pkarr") return false;
22520
+ if (this.parked.has(id)) {
22521
+ if (!wait?.timer) this.schedule(id);
22522
+ return false;
22523
+ }
22267
22524
  if (this.resender.ready(message)) {
22268
22525
  if (passed) await this.catchUp(passed);
22269
22526
  await this.transmitNow(id);
22270
22527
  return true;
22271
22528
  }
22272
- const wait = this.waiting.get(id);
22273
- if (this.resender.divert && wait && this.now() - wait.since >= this.policy.holdAfterMs && await this.resender.divert(message)) {
22529
+ if (this.resender.divert && wait && this.monotonic() - wait.since >= this.policy.holdAfterMs && await this.resender.divert(message)) {
22274
22530
  this.forget(id);
22275
22531
  return true;
22276
22532
  }
22277
22533
  if (!wait?.timer) this.schedule(id);
22278
22534
  return false;
22279
22535
  }
22536
+ /**
22537
+ * A send that did not leave this device, of a message that had not gone before: it waits again, as it did, and counts
22538
+ * no attempt. It keeps the path a new message's turn gives it (`waitsItsTurn`): it goes the way the chat can carry it.
22539
+ */
22540
+ async notSent(id) {
22541
+ const left = (this.attempts.get(id) ?? 1) - 1;
22542
+ if (left > 0) this.attempts.set(id, left);
22543
+ else this.attempts.delete(id);
22544
+ const message = await this.one(id);
22545
+ if (!message || message.delivery === "delivered") return;
22546
+ this.unsent.set(id, message.timestamp);
22547
+ await this.store.update(id, "waiting", NotSent.REASON, {
22548
+ via: "datalink",
22549
+ resendUntil: message.resendUntil ?? this.now() + this.policy.windowMs
22550
+ });
22551
+ if (!this.stopped) this.schedule(id);
22552
+ }
22553
+ /**
22554
+ * An older text of mine has not left this device (`unsent`) and still waits to go: this one must not go before it.
22555
+ * One cancelled meanwhile (its row gone) or gone another way (held, failed) holds nothing back any more.
22556
+ */
22557
+ async behindUnsent(message) {
22558
+ for (const [id, timestamp] of this.unsent) {
22559
+ if (id === message.id || timestamp > message.timestamp) continue;
22560
+ const older = this.stillUnsent.get(id) ?? await this.one(id);
22561
+ if (older && toGo(older)) {
22562
+ this.stillUnsent.set(id, older);
22563
+ this.behind.set(message.id, message.timestamp);
22564
+ return true;
22565
+ }
22566
+ this.unsent.delete(id);
22567
+ }
22568
+ this.behind.delete(message.id);
22569
+ return false;
22570
+ }
22571
+ /** A message behind an unsent text: it waits as it did, and one that was about to go waits its turn. */
22572
+ async waitBehind(message) {
22573
+ if (message.delivery === "sending") await this.waitsItsTurn(message);
22574
+ else if (message.delivery !== "waiting") await this.queue(message, message.deliveryError ?? "Not confirmed yet.");
22575
+ else if (!this.waiting.get(message.id)?.timer) this.schedule(message.id);
22576
+ }
22280
22577
  /** After a failed attempt: queued again, unless its window or its attempts are spent. */
22281
22578
  async requeue(id, reason) {
22282
22579
  const message = await this.one(id);
22283
22580
  if (message && message.delivery !== "delivered") await this.queue(message, reason);
22284
22581
  }
22285
22582
  async queue(message, reason) {
22286
- const now = this.now(), until = message.resendUntil ?? now + this.policy.windowMs;
22583
+ const until = message.resendUntil ?? this.now() + this.policy.windowMs;
22287
22584
  const sent = this.attempts.get(message.id) ?? 0;
22288
- if (until <= now) return this.fail(message.id, `${reason} Not confirmed within ${days(this.policy.windowMs)}.`);
22585
+ if (this.pastDeadline({
22586
+ ...message,
22587
+ resendUntil: until
22588
+ })) return this.fail(message.id, `${reason} Not confirmed within ${days(this.policy.windowMs)}.`);
22289
22589
  if (sent >= this.policy.maxAttempts) return this.fail(message.id, `${reason} Sent ${sent} times without a receipt.`);
22290
22590
  if (message.delivery !== "queued" || message.deliveryError !== reason || message.resendUntil !== until) await this.store.update(message.id, "queued", reason, { resendUntil: until });
22291
22591
  if (!this.stopped) this.schedule(message.id);
@@ -22301,14 +22601,15 @@ var Outbox = class {
22301
22601
  await this.store.update(id, "failed", `${reason} Your contact may have received it; Retry uses the same message ID, so it is never shown twice.`);
22302
22602
  }
22303
22603
  schedule(id) {
22604
+ if (this.cancelled.has(id)) return;
22304
22605
  const wait = this.waiting.get(id) ?? {
22305
22606
  step: 0,
22306
- since: this.now(),
22607
+ since: this.monotonic(),
22307
22608
  at: 0
22308
22609
  };
22309
22610
  if (wait.timer) clearTimeout(wait.timer);
22310
22611
  const delay = this.policy.backoffMs[Math.min(wait.step, this.policy.backoffMs.length - 1)];
22311
- wait.at = this.now() + delay;
22612
+ wait.at = this.monotonic() + delay;
22312
22613
  wait.timer = setTimeout(() => {
22313
22614
  wait.timer = void 0;
22314
22615
  wait.step++;
@@ -22316,13 +22617,34 @@ var Outbox = class {
22316
22617
  }, delay);
22317
22618
  this.waiting.set(id, wait);
22318
22619
  }
22620
+ /** Held, so a look reads its row by id (`look`), with no timer: nothing but a look at the chat sends it. */
22621
+ holdUnchecked(id) {
22622
+ if (this.cancelled.has(id)) return;
22623
+ const wait = this.waiting.get(id);
22624
+ if (wait?.timer) {
22625
+ clearTimeout(wait.timer);
22626
+ wait.timer = void 0;
22627
+ }
22628
+ if (!wait) this.waiting.set(id, {
22629
+ step: 0,
22630
+ since: this.monotonic(),
22631
+ at: 0
22632
+ });
22633
+ }
22319
22634
  forget(id) {
22635
+ this.unsent.delete(id);
22636
+ this.behind.delete(id);
22320
22637
  const wait = this.waiting.get(id);
22321
22638
  if (wait?.timer) clearTimeout(wait.timer);
22322
22639
  this.waiting.delete(id);
22640
+ this.deadlines.delete(id);
22323
22641
  this.attempts.delete(id);
22324
22642
  this.sentUnder.delete(id);
22325
22643
  }
22644
+ /** How long a receipt is awaited for this message when it goes now. */
22645
+ receiptWindow(message) {
22646
+ return typeof this.timeoutMs === "number" ? this.timeoutMs : this.timeoutMs(message);
22647
+ }
22326
22648
  track(id, duration) {
22327
22649
  this.clear(id);
22328
22650
  const timer = setTimeout(() => {
@@ -22333,7 +22655,7 @@ var Outbox = class {
22333
22655
  if (message?.via === "pkarr") await this.expired(message);
22334
22656
  else await this.requeue(id, "No receipt received yet.");
22335
22657
  }).catch(() => {});
22336
- }, duration);
22658
+ }, Math.min(Math.max(duration, 0), MAX_TIMER_MS));
22337
22659
  this.receipts.set(id, timer);
22338
22660
  }
22339
22661
  clear(id) {
@@ -24530,6 +24852,23 @@ var ENTRY_LINGER_MS$1 = 2e4;
24530
24852
  var FULL_TELL_MS = 3e5;
24531
24853
  var FULL_LINGER_MS = 5e3;
24532
24854
  var FULL_SAID_MS = 66e4;
24855
+ /**
24856
+ * Whether this device can let in no one new now (WISP 903 § Admissions while the admin is away): members signed
24857
+ * `COMMUNITY_LIMITS.memberAdmissions` admissions in a row, counted as the session's `commit` counts them. Its hub
24858
+ * answered every knock all the same: an entry session, an invite, the joiner told it was in "in a moment", and then
24859
+ * the accept refused, every turn of the door for as long as the admin was away.
24860
+ */
24861
+ function admissionsHeld(s) {
24862
+ if (s.isAdmin) return false;
24863
+ const admin = s.admin, chain = s.state.chain;
24864
+ let n = 0;
24865
+ for (let i = chain.length - 1; i >= 0; i--) {
24866
+ const c = chain[i];
24867
+ if (c.k === "create" || c.k === "role" || c.by === admin && c.k !== "remove" && c.k !== "leave") break;
24868
+ if (c.k === "add") n++;
24869
+ }
24870
+ return n >= COMMUNITY_LIMITS.memberAdmissions;
24871
+ }
24533
24872
  var RELAYED_KEPT = 4096;
24534
24873
  /**
24535
24874
  * Someone the chain took out while its app was closed comes back believing it is a member: it asks in a hub's lobby,
@@ -25979,7 +26318,7 @@ var Communities = class {
25979
26318
  async answerKnocks(groupId, live, now, busy) {
25980
26319
  const s = live.session;
25981
26320
  if (!s.adminWork || !s.entryKey || !s.state.entry.seedB64) return;
25982
- const full = s.roster.length >= COMMUNITY_LIMITS.members;
26321
+ const full = s.roster.length >= COMMUNITY_LIMITS.members, held = admissionsHeld(s);
25983
26322
  for (const [key, at] of live.fullTold) if (now - at >= FULL_TELL_MS) live.fullTold.delete(key);
25984
26323
  const link = {
25985
26324
  g: groupId,
@@ -26025,7 +26364,7 @@ var Communities = class {
26025
26364
  const stillKnocking = now - ts < 2 * this.timings.slowKnockMs;
26026
26365
  if (rosterHas(s.roster, key)) {
26027
26366
  if (!stillKnocking || ts < this.addedAt(s, key) + this.timings.knockFallbackMs) continue;
26028
- } else if (full && (door !== s.myKey || live.fullTold.has(key))) continue;
26367
+ } else if (full ? door !== s.myKey || live.fullTold.has(key) : held) continue;
26029
26368
  const seen = live.knocksSeen.get(key);
26030
26369
  const changed = !!seen && seen.doors !== doorSig;
26031
26370
  const first = seen && !changed ? seen.first : now;
@@ -26179,6 +26518,11 @@ var Communities = class {
26179
26518
  live.lingering.set(linkId, now + FULL_LINGER_MS);
26180
26519
  return true;
26181
26520
  }
26521
+ if (!rosterHas(s.roster, peer) && admissionsHeld(s)) {
26522
+ live.pendingEntries.delete(peer);
26523
+ this.host.closeEdge(linkId).catch(() => {});
26524
+ return true;
26525
+ }
26182
26526
  try {
26183
26527
  this.host.sendOnLink(linkId, live.session.inviteFrame());
26184
26528
  traceJoin(groupId, "invite.sent");
@@ -29872,6 +30216,18 @@ var Groups = class {
29872
30216
  admin: frame.admin,
29873
30217
  ...invitationClaims(frame)
29874
30218
  });
30219
+ const ownWaiting = existing?.invitation && !existing.invitation.takenBack && existing.invitation.linkId === linkId || existing?.others?.some((o) => "linkId" in o && o.linkId === linkId);
30220
+ const waiting = [...this.stored.values()].flatMap((x) => [...x.invitation && !x.invitation.takenBack ? [x.invitation.linkId] : [], ...(x.others ?? []).flatMap((o) => "linkId" in o ? [o.linkId] : [])]);
30221
+ if (!ownWaiting && waiting.length >= 32) return;
30222
+ if (!ownWaiting && waiting.filter((chat) => chat === linkId).length >= MAX_INVITATIONS_PER_CHAT) {
30223
+ try {
30224
+ this.host.sendOnLink(linkId, {
30225
+ t: "group-decline",
30226
+ g
30227
+ });
30228
+ } catch {}
30229
+ return;
30230
+ }
29875
30231
  if (existing?.invitation?.entry && !existing.state) {
29876
30232
  if (existing.invitation.linkId !== linkId) return other();
29877
30233
  existing.invitation = {
@@ -29904,16 +30260,6 @@ var Groups = class {
29904
30260
  if (existing?.invitation?.seedB64 && existing.invitation.admin !== frame.admin) return;
29905
30261
  if (existing?.left && (existing.left.admin !== frame.admin || existing.contacts?.[existing.left.admin] !== linkId)) return;
29906
30262
  if (existing?.invitation && !existing.state && existing.invitation.linkId !== linkId && !(existing.invitation.genesis && linkId === keptAdminChat(existing.previous)) && !existing.invitation.takenBack) return other();
29907
- if ([...this.stored.values()].filter((x) => x.invitation && !x.invitation.takenBack).length >= 32) return;
29908
- if (!(existing?.invitation && !existing.invitation.takenBack && existing.invitation.linkId === linkId) && [...this.stored.values()].filter((x) => x.invitation?.linkId === linkId && !x.invitation.takenBack).length >= MAX_INVITATIONS_PER_CHAT) {
29909
- try {
29910
- this.host.sendOnLink(linkId, {
29911
- t: "group-decline",
29912
- g
29913
- });
29914
- } catch {}
29915
- return;
29916
- }
29917
30263
  const known = {
29918
30264
  ...existing?.formerNames,
29919
30265
  ...existing?.state?.nicks
@@ -31447,11 +31793,33 @@ function authoredNote(p, at, all, current, memberOf = () => void 0, federationNe
31447
31793
  };
31448
31794
  return null;
31449
31795
  }
31796
+ /**
31797
+ * What GroupPayments needs of a group's view: my key and who is in it while I am an active member, and when this
31798
+ * membership began here (the group's row is made anew when I create it, am invited or join by its link, and goes
31799
+ * when I leave or forget it).
31800
+ */
31801
+ function paymentsMembership(view) {
31802
+ return view?.status === "active" && view.myKey ? {
31803
+ me: view.myKey,
31804
+ members: new Set(view.members.map((m) => m.key)),
31805
+ since: view.createdAt
31806
+ } : void 0;
31807
+ }
31808
+ /** The keys a note of mine names: one of them is mine as the member I was when I said it. */
31809
+ var named = (frame) => [
31810
+ frame.f,
31811
+ frame.to,
31812
+ ...frame.by ? [frame.by] : []
31813
+ ];
31450
31814
  var GroupPayments = class {
31451
31815
  host;
31452
31816
  notes = /* @__PURE__ */ new Map();
31453
31817
  /** Per group, the ids of others' notes still `undescribed`, oldest first. */
31454
31818
  waiting = /* @__PURE__ */ new Map();
31819
+ /** Counts the groups forgotten (`forget`): a pass under way asks again whether it is still in a group. */
31820
+ forgotten = 0;
31821
+ /** Per group, how many times it was forgotten in this run: notes read from its history before that are not kept. */
31822
+ ends = /* @__PURE__ */ new Map();
31455
31823
  queue = Promise.resolve();
31456
31824
  constructor(host) {
31457
31825
  this.host = host;
@@ -31461,8 +31829,9 @@ var GroupPayments = class {
31461
31829
  return this.run(async () => {
31462
31830
  const frame = parseGroupPay(raw, groupId), membership = this.host.membership(groupId);
31463
31831
  if (!frame || !membership) return;
31464
- const next = mergeGroupPay((await this.load(groupId)).get(frame.id), frame, author, membership.members);
31465
- if (next) await this.write(groupId, membership.me, next);
31832
+ const notes = await this.load(groupId);
31833
+ const next = mergeGroupPay(notes.get(frame.id), frame, author, membership.members);
31834
+ if (next) await this.write(groupId, membership.me, next, notes);
31466
31835
  });
31467
31836
  }
31468
31837
  /** Says what changed about this device's own payments in groups. The engine calls it whenever payments change. */
@@ -31472,7 +31841,9 @@ var GroupPayments = class {
31472
31841
  /** An edge came up: the member hears again what I said lately, in case it missed it. */
31473
31842
  edgeReady(groupId, linkId) {
31474
31843
  return this.run(async () => {
31475
- const mine = [...(await this.load(groupId)).values()].filter((n) => n.mine).sort((a, b) => b.createdAt - a.createdAt).slice(0, RESEND);
31844
+ const me = this.host.membership(groupId)?.me;
31845
+ if (!me) return;
31846
+ const mine = [...(await this.load(groupId)).values()].filter((n) => n.mine && named(n.mine).includes(me)).sort((a, b) => b.createdAt - a.createdAt).slice(0, RESEND);
31476
31847
  for (const note of mine.reverse()) try {
31477
31848
  this.host.send(linkId, note.mine);
31478
31849
  } catch {
@@ -31480,6 +31851,17 @@ var GroupPayments = class {
31480
31851
  }
31481
31852
  });
31482
31853
  }
31854
+ /**
31855
+ * A group left or forgotten here (its history went with it; switching to another group under its id forgets it
31856
+ * first): what this run kept of its notes goes too. A later membership under the same id, mine again by its link or
31857
+ * another group's, starts with none of them.
31858
+ */
31859
+ forget(groupId) {
31860
+ this.notes.delete(groupId);
31861
+ this.waiting.delete(groupId);
31862
+ this.ends.set(groupId, (this.ends.get(groupId) ?? 0) + 1);
31863
+ this.forgotten++;
31864
+ }
31483
31865
  run(task) {
31484
31866
  const next = this.queue.then(task, task);
31485
31867
  this.queue = next.catch(() => {});
@@ -31488,7 +31870,12 @@ var GroupPayments = class {
31488
31870
  async author() {
31489
31871
  const all = this.host.payments();
31490
31872
  const known = /* @__PURE__ */ new Map();
31873
+ let forgotten = this.forgotten;
31491
31874
  const membership = (groupId) => {
31875
+ if (forgotten !== this.forgotten) {
31876
+ known.clear();
31877
+ forgotten = this.forgotten;
31878
+ }
31492
31879
  if (!known.has(groupId)) known.set(groupId, this.host.membership(groupId));
31493
31880
  return known.get(groupId);
31494
31881
  };
@@ -31501,7 +31888,8 @@ var GroupPayments = class {
31501
31888
  for (const p of all) {
31502
31889
  const at = this.placement(p, membership);
31503
31890
  if (!at) continue;
31504
- const current = (await this.load(at.groupId)).get(paymentWireId(p.id));
31891
+ const notes = await this.load(at.groupId);
31892
+ const current = notes.get(paymentWireId(p.id));
31505
31893
  const frame = authoredNote(p, at, answers.get(p.id) ?? [], current, (linkId) => this.host.edgeOf(linkId)?.member, (federation) => this.host.federationNetwork?.(federation));
31506
31894
  if (!frame) continue;
31507
31895
  const members = membership(at.groupId).members;
@@ -31510,19 +31898,20 @@ var GroupPayments = class {
31510
31898
  if (!next && JSON.stringify(frame) === JSON.stringify(current?.mine)) continue;
31511
31899
  const merged = next ?? current;
31512
31900
  if (!merged) continue;
31513
- await this.write(at.groupId, at.me, {
31901
+ if (!await this.write(at.groupId, at.me, {
31514
31902
  ...merged,
31515
31903
  mine: frame
31516
- });
31904
+ }, notes)) continue;
31517
31905
  for (const linkId of this.host.edges(at.groupId).values()) try {
31518
31906
  this.host.send(linkId, frame);
31519
31907
  } catch {}
31520
31908
  }
31521
31909
  }
31522
31910
  placement(p, membership) {
31911
+ const current = (m) => !!m && !(p.direction === "out" && m.since !== void 0 && p.createdAt < m.since);
31523
31912
  if (p.group) {
31524
31913
  const m = membership(p.group);
31525
- return m ? {
31914
+ return current(m) ? {
31526
31915
  groupId: p.group,
31527
31916
  me: m.me
31528
31917
  } : void 0;
@@ -31530,7 +31919,7 @@ var GroupPayments = class {
31530
31919
  const edge = this.host.edgeOf(p.linkId);
31531
31920
  if (!edge) return void 0;
31532
31921
  const m = membership(edge.groupId);
31533
- return m ? {
31922
+ return current(m) ? {
31534
31923
  groupId: edge.groupId,
31535
31924
  me: m.me,
31536
31925
  peer: edge.member
@@ -31539,14 +31928,19 @@ var GroupPayments = class {
31539
31928
  async load(groupId) {
31540
31929
  let notes = this.notes.get(groupId);
31541
31930
  if (!notes) {
31931
+ const ends = this.ends.get(groupId);
31542
31932
  notes = new Map((await this.host.messages(groupId)).filter((m) => m.groupPay).map((m) => [m.groupPay.id, m.groupPay]));
31543
- this.notes.set(groupId, notes);
31933
+ if (this.ends.get(groupId) === ends) this.notes.set(groupId, notes);
31544
31934
  }
31545
31935
  return notes;
31546
31936
  }
31547
- async write(groupId, me, note) {
31548
- const notes = this.notes.get(groupId);
31549
- notes?.set(note.id, note);
31937
+ /**
31938
+ * Keeps `note` in `notes` (the group's, as `load` gave them) and in the group's history; false when the group was
31939
+ * forgotten since they were loaded: nothing goes back into a history that is gone.
31940
+ */
31941
+ async write(groupId, me, note, notes) {
31942
+ if (this.notes.get(groupId) !== notes) return false;
31943
+ notes.set(note.id, note);
31550
31944
  let waiting = this.waiting.get(groupId);
31551
31945
  if (note.undescribed && !note.mine) {
31552
31946
  if (!waiting) this.waiting.set(groupId, waiting = /* @__PURE__ */ new Set());
@@ -31554,10 +31948,10 @@ var GroupPayments = class {
31554
31948
  for (const id of waiting) {
31555
31949
  if (waiting.size <= 256) break;
31556
31950
  waiting.delete(id);
31557
- notes?.delete(id);
31951
+ notes.delete(id);
31558
31952
  }
31559
31953
  } else waiting?.delete(note.id);
31560
- if (note.undescribed) return;
31954
+ if (note.undescribed) return true;
31561
31955
  const initiator = note.kind === "request" ? note.to : note.from;
31562
31956
  await this.host.putMessage({
31563
31957
  linkId: `group:${groupId}`,
@@ -31569,6 +31963,7 @@ var GroupPayments = class {
31569
31963
  via: "datalink",
31570
31964
  groupPay: note
31571
31965
  });
31966
+ return true;
31572
31967
  }
31573
31968
  };
31574
31969
  /** A plain line for previews and old views; the group page draws the note itself. */
@@ -31814,7 +32209,8 @@ var GroupEdits = class {
31814
32209
  }
31815
32210
  /**
31816
32211
  * An edit past what a member's window takes: kept, the highest number per message, `GROUP_EDITS_HELD` messages a
31817
- * group at most (the oldest go first), and taken when the window has room. The work stays what the window allows.
32212
+ * group at most (the oldest of the member holding the most go first), and taken when the window has room. The work
32213
+ * stays what the window allows.
31818
32214
  */
31819
32215
  hold(groupId, sender, edit, pace) {
31820
32216
  const key = `${groupId}\n${sender}`;
@@ -31828,13 +32224,18 @@ var GroupEdits = class {
31828
32224
  waiting.set(edit.id, edit);
31829
32225
  let count = 0;
31830
32226
  for (const member of group.values()) count += member.size;
31831
- for (const [member, edits] of group) {
31832
- if (count <= 256) break;
31833
- while (count > 256 && edits.size) {
31834
- edits.delete(edits.keys().next().value);
31835
- count--;
32227
+ while (count > 256) {
32228
+ let most = key;
32229
+ for (const [member, edits] of group) if (edits.size > group.get(most).size) most = member;
32230
+ const edits = group.get(most);
32231
+ let oldest = edits.keys().next().value;
32232
+ for (const [id, held] of edits) if (!held.rm) {
32233
+ oldest = id;
32234
+ break;
31836
32235
  }
31837
- if (!edits.size && member !== key) group.delete(member);
32236
+ edits.delete(oldest);
32237
+ count--;
32238
+ if (!edits.size && most !== key) group.delete(most);
31838
32239
  }
31839
32240
  if (!this.heldTimers.has(key) && !this.stopped) this.heldTimers.set(key, setTimeout(() => {
31840
32241
  this.takeHeld(groupId, sender).catch(() => {});
@@ -34586,7 +34987,7 @@ function normalizeMintUrl(input) {
34586
34987
  }
34587
34988
  function assertAmount(amount) {
34588
34989
  if (!Number.isSafeInteger(amount) || amount <= 0) throw new Error("Enter an amount in sats");
34589
- if (amount > MAX_AMOUNT) throw new Error(`Amounts above ${MAX_AMOUNT.toLocaleString()} sats are not supported`);
34990
+ if (amount > MAX_AMOUNT) throw new Error(`Amounts above ${MAX_AMOUNT.toLocaleString("en-US")} sats are not supported`);
34590
34991
  }
34591
34992
  /** Stored proofs are plain objects (amounts as numbers), which is what the library calls ProofLike. */
34592
34993
  var asProofLike = (proofs) => proofs;
@@ -34715,6 +35116,8 @@ var CashuWallet = class CashuWallet {
34715
35116
  events;
34716
35117
  getKnownMints;
34717
35118
  wallets = /* @__PURE__ */ new Map();
35119
+ /** When the load in `wallets` of a mint failed: it is tried again once `MINT_FAILED_MS` passed. */
35120
+ failedLoads = /* @__PURE__ */ new Map();
34718
35121
  names = /* @__PURE__ */ new Map();
34719
35122
  infos = /* @__PURE__ */ new Map();
34720
35123
  locks = /* @__PURE__ */ new Map();
@@ -35304,7 +35707,7 @@ var CashuWallet = class CashuWallet {
35304
35707
  async recoverReviewedCashu(review, prepared) {
35305
35708
  const stored = await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
35306
35709
  if (stored?.token) return stored.token;
35307
- const wallet = await this.wallet(prepared.mint);
35710
+ const wallet = await this.wallet(prepared.mint, true);
35308
35711
  const { OutputData } = await loadCashu();
35309
35712
  const keep = (prepared.swap.keepOutputs ?? []).map(OutputData.deserialize);
35310
35713
  const send = (prepared.swap.sendOutputs ?? []).map(OutputData.deserialize);
@@ -35396,7 +35799,7 @@ var CashuWallet = class CashuWallet {
35396
35799
  const { OutputData, deserializeSwapPreview } = await loadCashu();
35397
35800
  const preview = deserializeSwapPreview(prepared.swap);
35398
35801
  if (!preview.inputs.length) return false;
35399
- const wallet = await this.wallet(prepared.mint);
35802
+ const wallet = await this.wallet(prepared.mint, true);
35400
35803
  const states = await wallet.checkProofsStates(preview.inputs.map((p) => ({
35401
35804
  secret: p.secret,
35402
35805
  id: p.id
@@ -35415,7 +35818,7 @@ var CashuWallet = class CashuWallet {
35415
35818
  const { OutputData, deserializeSwapPreview } = await loadCashu();
35416
35819
  const preview = deserializeSwapPreview(prepared.swap);
35417
35820
  if (!preview.inputs.length) return false;
35418
- const wallet = await this.wallet(prepared.mint);
35821
+ const wallet = await this.wallet(prepared.mint, true);
35419
35822
  const outputs = [...prepared.swap.keepOutputs ?? [], ...prepared.swap.sendOutputs ?? []].map(OutputData.deserialize);
35420
35823
  if (await this.signedOutputs(wallet, outputs) !== "none") return false;
35421
35824
  const states = await wallet.checkProofsStates(preview.inputs.map((p) => ({
@@ -35499,9 +35902,16 @@ var CashuWallet = class CashuWallet {
35499
35902
  async reviewedCashuTakenBack(id) {
35500
35903
  return (await wrap((await store(STORES$1.payments, "readonly")).get(id)))?.state === "reclaimed";
35501
35904
  }
35905
+ /**
35906
+ * Whether a Take it back of this payment of ours is still written down: its redeem reached the mint, whose answer was
35907
+ * lost (`SwapUnsettledError`), and `pollSwaps` settles it. Its ecash reads SPENT meanwhile, by this wallet.
35908
+ */
35909
+ async cashuTakingBack(id) {
35910
+ return (await this.readSwaps()).some((s) => s.kind === "receive" && !s.released && s.payment?.id === id && s.payment.direction === "out");
35911
+ }
35502
35912
  async reviewedCashuSpent(prepared) {
35503
35913
  const outputs = (prepared.swap.sendOutputs ?? []).map((await loadCashu()).OutputData.deserialize);
35504
- const states = await (await this.wallet(prepared.mint)).checkProofsStates(outputs.map((o) => ({
35914
+ const states = await (await this.wallet(prepared.mint, true)).checkProofsStates(outputs.map((o) => ({
35505
35915
  secret: new TextDecoder().decode(o.secret),
35506
35916
  id: o.blindedMessage.id
35507
35917
  })));
@@ -35589,8 +35999,12 @@ var CashuWallet = class CashuWallet {
35589
35999
  ...records(preview.amount.toNumber())
35590
36000
  };
35591
36001
  await this.putSwap(swap);
35592
- }
35593
- const { keep } = await this.completeSwap(swap);
36002
+ } else if (payment && !this.swapAsk.due(swap.id, Date.now())) throw new SwapUnsettledError(swap);
36003
+ const sent = swap;
36004
+ const { keep } = await this.completeSwap(sent).catch((error) => {
36005
+ if (error instanceof SwapUnsettledError) this.swapAsk.missed(sent.id, Date.now());
36006
+ throw error;
36007
+ });
35594
36008
  const credited = sats(keep);
35595
36009
  if (swap.tx && credited !== swap.tx.amount) swap = {
35596
36010
  ...swap,
@@ -36193,6 +36607,9 @@ var CashuWallet = class CashuWallet {
36193
36607
  if (swap) stores[STORES$1.swaps].delete(swap.id);
36194
36608
  });
36195
36609
  this.shownQuotes.delete(quoteId);
36610
+ const unpaid = () => {
36611
+ this.shownQuotes.set(quoteId, shown);
36612
+ };
36196
36613
  let result;
36197
36614
  try {
36198
36615
  result = await wallet.completeMelt(preview);
@@ -36200,6 +36617,7 @@ var CashuWallet = class CashuWallet {
36200
36617
  if (!mintRefused(error) && !(error instanceof MeltChangeError)) return "pending";
36201
36618
  const outcome = await this.settleMelt(melt, true).catch(() => "pending");
36202
36619
  if (outcome === "unpaid") {
36620
+ unpaid();
36203
36621
  const lost = this.takeFailedFee(melt.quote);
36204
36622
  if (this.spentAway.delete(melt.quote)) throw Object.assign(engineError("ecashAlreadySpent"), { cause: error });
36205
36623
  if (lost > 0) throw Object.assign(/* @__PURE__ */ new Error(`${error instanceof Error ? error.message : String(error)} ${backInWallet(lost)}`), { cause: error });
@@ -36211,7 +36629,9 @@ var CashuWallet = class CashuWallet {
36211
36629
  await this.finishMelt(melt, result.change);
36212
36630
  return "paid";
36213
36631
  }
36214
- return this.settleMelt(melt, true).catch(() => "pending");
36632
+ const outcome = await this.settleMelt(melt, true).catch(() => "pending");
36633
+ if (outcome === "unpaid") unpaid();
36634
+ return outcome;
36215
36635
  }
36216
36636
  /**
36217
36637
  * Whether a Lightning payment of this invoice is written down as in flight. A melt is written before the mint sees
@@ -36385,18 +36805,28 @@ var CashuWallet = class CashuWallet {
36385
36805
  }
36386
36806
  return out;
36387
36807
  }
36388
- wallet(mint) {
36808
+ /**
36809
+ * A mint's loaded wallet. A failed load is tried again by the next caller, unless that one takes `recentFailure`
36810
+ * (a payment's reads in the poll): a load failed within `MINT_FAILED_MS` is its answer too.
36811
+ */
36812
+ wallet(mint, recentFailure = false) {
36813
+ const failed = this.failedLoads.get(mint);
36389
36814
  let wallet = this.wallets.get(mint);
36815
+ if (failed !== void 0 && !(recentFailure && Date.now() - failed < 5e3)) wallet = void 0;
36390
36816
  if (!wallet) {
36391
- wallet = (async () => {
36817
+ const loading = (async () => {
36392
36818
  const instance = new (await (loadCashu())).Wallet(mint, { unit: UNIT$1 });
36393
36819
  await within$1(MINT_TIMEOUT_MS, instance.loadMint(), mint);
36394
36820
  const info = instance.getMintInfo();
36395
36821
  if (info.isSupported(5).params.some(saysAmountlessBeside)) instance.loadMintFromCache(amountlessUnderOptions(info.cache), instance.keyChain.cache);
36396
36822
  return instance;
36397
36823
  })();
36398
- this.wallets.set(mint, wallet);
36399
- wallet.catch(() => this.wallets.delete(mint));
36824
+ wallet = loading;
36825
+ this.failedLoads.delete(mint);
36826
+ this.wallets.set(mint, loading);
36827
+ loading.catch(() => {
36828
+ if (this.wallets.get(mint) === loading) this.failedLoads.set(mint, Date.now());
36829
+ });
36400
36830
  }
36401
36831
  return wallet;
36402
36832
  }
@@ -36483,6 +36913,15 @@ var UNIT = "sat";
36483
36913
  /** A contact's requests in one chat: the new ones taken per minute, and how many may wait to be paid. */
36484
36914
  var REQUESTS_PER_MINUTE = 20;
36485
36915
  var OPEN_REQUESTS = 50;
36916
+ /**
36917
+ * A contact's ecash in one chat (Cashu and Fedimint `pay` frames): the new ones taken per minute. Each asks the mint
36918
+ * (under its lock, which this side's own payments there wait on) or the federation. One past it is refused unredeemed,
36919
+ * so the contact takes it back and can send it again a minute later.
36920
+ */
36921
+ var PAYMENTS_PER_MINUTE = 10;
36922
+ var PAYMENTS_BUSY = "Too many payments at once: send it again in a minute";
36923
+ /** Refusal lines one chat gets in an hour; past it the contact is still told, and the chat stays as it is. */
36924
+ var REFUSAL_LINES_PER_HOUR = 5;
36486
36925
  var INVOICE_CLAIMS_KEY = "invoicePaidClaims";
36487
36926
  var sameClaim = (a, b) => a.linkId === b.linkId && a.invoice.toLowerCase() === b.invoice.toLowerCase();
36488
36927
  var satsWord = (n) => `${n} sat${n === 1 ? "" : "s"}`;
@@ -36718,6 +37157,11 @@ var PaymentDesk = class {
36718
37157
  reclaims = /* @__PURE__ */ new Map();
36719
37158
  /** Receipts older than `RECEIPT_FRESH_MS` said again in this run of the app, by payment id (`receiptOwed`). */
36720
37159
  receiptsSaid = /* @__PURE__ */ new Set();
37160
+ /**
37161
+ * Reviewed Cashu payments whose token went out in this run, by id: `replay` sends it again whenever the link opens
37162
+ * again, so reconciling one does not (`resendCashu`).
37163
+ */
37164
+ cashuSent = /* @__PURE__ */ new Set();
36721
37165
  checkingArk = false;
36722
37166
  checkingUsdt = false;
36723
37167
  checkingBark = false;
@@ -37369,6 +37813,16 @@ var PaymentDesk = class {
37369
37813
  }
37370
37814
  return running;
37371
37815
  }
37816
+ /**
37817
+ * The Take it back of this payment under way, if one is: settles, never rejects, once it is over, with the
37818
+ * payment's state then (`reclaimed` when the ecash came back, `settled` when the contact had taken it first).
37819
+ * A status check waits for it: the mint reads ecash this wallet is taking back as spent too.
37820
+ */
37821
+ takingBack(paymentId) {
37822
+ const running = this.reclaims.get(paymentId);
37823
+ const after = () => this.payments.get(paymentId)?.state;
37824
+ return running?.then(after, after);
37825
+ }
37372
37826
  async reclaimOnce(paymentId) {
37373
37827
  const payment = this.payments.get(paymentId);
37374
37828
  if (payment?.target?.method === "fedimint" && payment.direction === "out" && payment.kind === "payment") {
@@ -37522,6 +37976,40 @@ var PaymentDesk = class {
37522
37976
  for (const p of this.payments.values()) if (p.linkId === linkId && p.kind === "request" && p.direction === "in" && p.state === "pending" && ++open >= OPEN_REQUESTS) return false;
37523
37977
  return true;
37524
37978
  }
37979
+ /** New ecash taken from each chat's contact lately, and the refusal lines each chat got (with their latest ids). */
37980
+ paymentsFrom = /* @__PURE__ */ new Map();
37981
+ refusalLines = /* @__PURE__ */ new Map();
37982
+ /** Whether this chat has room for one more new payment of its contact's ecash (`PAYMENTS_PER_MINUTE`). */
37983
+ roomForPayment(linkId) {
37984
+ let recent = this.paymentsFrom.get(linkId);
37985
+ if (!recent) this.paymentsFrom.set(linkId, recent = new RateWindow(PAYMENTS_PER_MINUTE, 6e4));
37986
+ return recent.take();
37987
+ }
37988
+ /**
37989
+ * Stores a refusal line in its chat, unless the chat had `REFUSAL_LINES_PER_HOUR` already. One stored again under an
37990
+ * id the chat got lately (spent ecash sent again) adds no line, and is not counted. Never throws: the contact was told.
37991
+ */
37992
+ async refusalLine(linkId, id, line, timestamp) {
37993
+ let lines = this.refusalLines.get(linkId);
37994
+ if (!lines) this.refusalLines.set(linkId, lines = {
37995
+ recent: new RateWindow(REFUSAL_LINES_PER_HOUR, 36e5),
37996
+ ids: []
37997
+ });
37998
+ if (!lines.ids.includes(id)) {
37999
+ if (!lines.recent.take()) return;
38000
+ lines.ids = [...lines.ids, id].slice(-5);
38001
+ }
38002
+ try {
38003
+ await this.host.storeMessage({
38004
+ linkId,
38005
+ id,
38006
+ ...line,
38007
+ sender: "peer",
38008
+ timestamp,
38009
+ via: "datalink"
38010
+ });
38011
+ } catch {}
38012
+ }
37525
38013
  /** `held`: picked up from the contact's storage while it was away (WISP 404): only what this device allows counts, and only Cashu or Lightning. */
37526
38014
  async onPaymentRequest(linkId, request, held = false) {
37527
38015
  if (this.find(linkId, request.id)?.linkId === linkId) return;
@@ -37688,6 +38176,14 @@ var PaymentDesk = class {
37688
38176
  });
37689
38177
  return;
37690
38178
  }
38179
+ if (!this.roomForPayment(linkId)) {
38180
+ link?.sendPaymentResult({
38181
+ id: payment.id,
38182
+ ok: false,
38183
+ error: PAYMENTS_BUSY
38184
+ });
38185
+ return;
38186
+ }
37691
38187
  if (!link?.allowsPayment("cashu")) {
37692
38188
  link?.sendPaymentResult({
37693
38189
  id: payment.id,
@@ -37767,21 +38263,11 @@ var PaymentDesk = class {
37767
38263
  const sats = parseSats(payment.amount.value, payment.amount.asset);
37768
38264
  const spent = error instanceof EngineError && error.engineCode === "ecashAlreadySpent";
37769
38265
  const network = inspected?.kind === "token" ? mintNetwork(inspected.mint) : void 0;
37770
- const line = refusedRow({
38266
+ await this.refusalLine(linkId, spent ? `peer_spent_${digestHex(token).slice(0, 32)}` : `peer_${payment.timestamp}_refused`, refusedRow({
37771
38267
  amount: sats ?? void 0,
37772
38268
  network,
37773
38269
  reason
37774
- });
37775
- try {
37776
- await this.host.storeMessage({
37777
- linkId,
37778
- id: spent ? `peer_spent_${digestHex(token).slice(0, 32)}` : `peer_${payment.timestamp}_refused`,
37779
- ...line,
37780
- sender: "peer",
37781
- timestamp: payment.timestamp,
37782
- via: "datalink"
37783
- });
37784
- } catch {}
38270
+ }), payment.timestamp);
37785
38271
  }
37786
38272
  }
37787
38273
  /**
@@ -37843,21 +38329,11 @@ var PaymentDesk = class {
37843
38329
  ok: false,
37844
38330
  error: reason
37845
38331
  });
37846
- const line = refusedRow({
38332
+ await this.refusalLine(record.linkId, `peer_${record.createdAt}_refused`, refusedRow({
37847
38333
  amount: record.amount,
37848
38334
  network: record.mint ? mintNetwork(record.mint) : void 0,
37849
38335
  reason
37850
- });
37851
- try {
37852
- await this.host.storeMessage({
37853
- linkId: record.linkId,
37854
- id: `peer_${record.createdAt}_refused`,
37855
- ...line,
37856
- sender: "peer",
37857
- timestamp: record.createdAt,
37858
- via: "datalink"
37859
- });
37860
- } catch {}
38336
+ }), record.createdAt);
37861
38337
  }
37862
38338
  async onPaymentResult(linkId, result) {
37863
38339
  const payment = this.find(linkId, result.id);
@@ -38366,11 +38842,13 @@ var PaymentDesk = class {
38366
38842
  async recordCashu(review, token) {
38367
38843
  if (!review.linkId || review.method !== "cashu") throw new Error("Cashu chat recipient missing");
38368
38844
  const link = this.requireLink(review.linkId);
38369
- await link.requirePaymentSupport();
38370
38845
  const existing = await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
38371
38846
  if (!existing || existing.linkId !== review.linkId || existing.requestId !== review.requestId) throw new Error("Cashu outbox does not match the reviewed payment");
38847
+ if (!await this.cashuSendable(this.payments.get(existing.id) ?? existing)) return;
38372
38848
  this.payments.set(existing.id, existing);
38373
38849
  this.host.onChange();
38850
+ await link.requirePaymentSupport();
38851
+ if (!await this.cashuSendable(this.payments.get(existing.id) ?? existing)) return;
38374
38852
  await this.host.storeMessage({
38375
38853
  linkId: review.linkId,
38376
38854
  id: `me_${review.createdAt}`,
@@ -38391,6 +38869,24 @@ var PaymentDesk = class {
38391
38869
  memo: review.memo,
38392
38870
  endpoint: [ENDPOINT.cashu, token]
38393
38871
  });
38872
+ this.cashuSent.add(review.id);
38873
+ }
38874
+ async cashuSendable(payment) {
38875
+ return payment.state === "pending" && !await this.cashuTakingBack(payment.id);
38876
+ }
38877
+ /**
38878
+ * A Take it back of this payment under way: running here, or its redeem written down after the mint's answer was lost
38879
+ * (`CashuWallet.cashuTakingBack`), whose ecash the mint already reads spent. Unreadable: not sent now, asked again.
38880
+ */
38881
+ async cashuTakingBack(id) {
38882
+ return this.reclaims.has(id) || await Promise.resolve(this.wallet.cashuTakingBack?.(id)).then(Boolean, () => true);
38883
+ }
38884
+ /**
38885
+ * A reviewed Cashu payment's token again, as reconciling it asks: only if it never went in this run. One that went is
38886
+ * the same token on the same link, and `replay` sends it again when the link opens again (a contact who missed it).
38887
+ */
38888
+ async resendCashu(review, token) {
38889
+ if (!this.cashuSent.has(review.id)) await this.recordCashu(review, token);
38394
38890
  }
38395
38891
  async confirmReviewedCashu(review) {
38396
38892
  if (review.method !== "cashu" || review.state !== "settled") return;
@@ -38873,22 +39369,12 @@ var PaymentDesk = class {
38873
39369
  ok: false,
38874
39370
  error: reason
38875
39371
  });
38876
- const line = refusedRow({
39372
+ await this.refusalLine(linkId, `peer_${payment.timestamp}_refused`, refusedRow({
38877
39373
  amount: parseSats(payment.amount.value, payment.amount.asset) ?? void 0,
38878
39374
  network,
38879
39375
  method: "fedimint",
38880
39376
  reason
38881
- });
38882
- try {
38883
- await this.host.storeMessage({
38884
- linkId,
38885
- id: `peer_${payment.timestamp}_refused`,
38886
- ...line,
38887
- sender: "peer",
38888
- timestamp: payment.timestamp,
38889
- via: "datalink"
38890
- });
38891
- } catch {}
39377
+ }), payment.timestamp);
38892
39378
  };
38893
39379
  if (!link?.allowsPayment("fedimint")) {
38894
39380
  await refuse("Fedimint is off in this chat");
@@ -38934,6 +39420,14 @@ var PaymentDesk = class {
38934
39420
  });
38935
39421
  return;
38936
39422
  }
39423
+ if (!this.roomForPayment(linkId)) {
39424
+ link.sendPaymentResult({
39425
+ id: payment.id,
39426
+ ok: false,
39427
+ error: PAYMENTS_BUSY
39428
+ });
39429
+ return;
39430
+ }
38937
39431
  await this.save({
38938
39432
  id: payment.id,
38939
39433
  linkId,
@@ -38997,22 +39491,12 @@ var PaymentDesk = class {
38997
39491
  ok: false,
38998
39492
  error: "These notes were already redeemed"
38999
39493
  });
39000
- const line = refusedRow({
39494
+ await this.refusalLine(payment.linkId, `peer_${payment.createdAt}_refused`, refusedRow({
39001
39495
  amount: payment.amount,
39002
39496
  network: payment.network,
39003
39497
  method: "fedimint",
39004
39498
  reason: "These notes were already redeemed"
39005
- });
39006
- try {
39007
- await this.host.storeMessage({
39008
- linkId: payment.linkId,
39009
- id: `peer_${payment.createdAt}_refused`,
39010
- ...line,
39011
- sender: "peer",
39012
- timestamp: payment.createdAt,
39013
- via: "datalink"
39014
- });
39015
- } catch {}
39499
+ }), payment.createdAt);
39016
39500
  return;
39017
39501
  }
39018
39502
  if (state) {
@@ -39450,6 +39934,7 @@ var PaymentDesk = class {
39450
39934
  }
39451
39935
  if (payment.state !== "pending") continue;
39452
39936
  if (payment.kind === "payment" && payment.token) {
39937
+ if (await this.cashuTakingBack(payment.id)) continue;
39453
39938
  await this.host.storeMessage(ecashLine(payment));
39454
39939
  await this.sendTo(link, {
39455
39940
  id: payment.id,
@@ -39462,6 +39947,7 @@ var PaymentDesk = class {
39462
39947
  memo: payment.memo,
39463
39948
  endpoint: [ENDPOINT.cashu, payment.token]
39464
39949
  });
39950
+ this.cashuSent.add(payment.id);
39465
39951
  } else if (payment.kind === "request" && (payment.invoice || payment.mints?.length)) await link.sendPaymentRequest({
39466
39952
  id: payment.id,
39467
39953
  timestamp: payment.createdAt,
@@ -40389,6 +40875,12 @@ var GhostlyNode = class GhostlyNode {
40389
40875
  * from a read of the store or a change of a review, and leaves when the poll finds its review ended or gone.
40390
40876
  */
40391
40877
  openReviews = null;
40878
+ /**
40879
+ * The pace of each submitted Cashu payment the contact has not taken: asked at 10 s while new, then twice as late up
40880
+ * to 10 min (as a payee retries a redeem). At the poll's own 10 s, a contact online whose redeems fail cost the mint
40881
+ * 12 checkstates a minute for each such payment, for as long as the app ran. The contact taking one says so at once.
40882
+ */
40883
+ cashuPayAsk = new AskBackoff(1e4, 6e5);
40392
40884
  noteOpenReviews(reviews) {
40393
40885
  const open = this.openReviews ??= /* @__PURE__ */ new Set();
40394
40886
  for (const review of reviews) if (review.state === "submitted" || review.state === "unknown") open.add(review.id);
@@ -40508,10 +41000,10 @@ var GhostlyNode = class GhostlyNode {
40508
41000
  {
40509
41001
  method: "cashu",
40510
41002
  prepare: (target, amount, feeCap) => new CashuAdapter(this.wallet, (r, t) => this.desk.recordCashu(r, t)).prepare(target, amount, feeCap),
40511
- execute: (review, prepared, persist) => new CashuAdapter(this.wallet, (r, t) => this.desk.recordCashu(r, t)).execute(review, prepared, persist),
41003
+ execute: (review, prepared, persist) => new CashuAdapter(this.wallet, (r, t) => this.desk.recordCashu(r, t), (id) => this.desk.takingBack(id)).execute(review, prepared, persist),
40512
41004
  reconcile: (review, prepared, persist) => {
40513
41005
  if (!persist) throw new Error("A Cashu payment is reconciled with its intent saved");
40514
- return new CashuAdapter(this.wallet, (r, t) => this.desk.recordCashu(r, t)).reconcile(review, prepared, persist);
41006
+ return new CashuAdapter(this.wallet, (r, t) => this.desk.resendCashu(r, t), (id) => this.desk.takingBack(id)).reconcile(review, prepared, persist);
40515
41007
  }
40516
41008
  }
40517
41009
  ], (review) => {
@@ -41498,7 +41990,7 @@ var GhostlyNode = class GhostlyNode {
41498
41990
  } : void 0;
41499
41991
  },
41500
41992
  edges: (groupId) => this.groups.isCommunityGroup(groupId) ? /* @__PURE__ */ new Map([["*", groupLinkId(groupId)]]) : this.memberEdges(groupId),
41501
- membership: (groupId) => this.membership(groupId),
41993
+ membership: (groupId) => paymentsMembership(this.groups.view(groupId)),
41502
41994
  send: (linkId, frame) => {
41503
41995
  const pay = parsePayLink(linkId);
41504
41996
  if (pay) {
@@ -41800,15 +42292,21 @@ var GhostlyNode = class GhostlyNode {
41800
42292
  try {
41801
42293
  if (!this.openReviews) this.noteOpenReviews((await intentRepository.list()).map((saved) => saved.review));
41802
42294
  const open = this.openReviews;
42295
+ this.cashuPayAsk.keepOnly(open);
41803
42296
  for (const id of [...open]) {
41804
- const review = (await intentRepository.get(id))?.review;
42297
+ if (!this.cashuPayAsk.due(id, Date.now())) continue;
42298
+ const saved = await intentRepository.get(id), review = saved?.review;
41805
42299
  if (!review || !["submitted", "unknown"].includes(review.state)) {
41806
42300
  open.delete(id);
41807
42301
  continue;
41808
42302
  }
41809
42303
  const network = walletNetworkOf(review.network);
41810
42304
  if (review.method === "arkade" && !this.arkWallets[network].adapter || review.method === "bark" && !this.barkWallets[network].adapter || review.method === "spark" && !this.sparkWallets[network].adapter || review.method === "usdt" && !this.usdtWallets[network].adapter || review.method === "bitcoin" && !this.bitcoins[network].sources.active || review.method === "fedimint" && !this.fedimintWallets[network].federation(review.provider)) continue;
41811
- await this.reconcilePayment({ id: review.id }).catch(() => {});
42305
+ const after = await this.reconcilePayment({ id: review.id }).catch(() => review);
42306
+ if (review.method === "cashu" && ["submitted", "unknown"].includes(after.state)) {
42307
+ const prepared = saved.prepared;
42308
+ this.cashuPayAsk.missed(id, Date.now(), Date.now() < (prepared.token ? (review.submittedAt ?? review.createdAt) + 6e4 : swapSettledAt(review, prepared)));
42309
+ }
41812
42310
  }
41813
42311
  } finally {
41814
42312
  if (!this.shuttingDown) this.paymentTimer = setTimeout(() => void this.pollPaymentStatus(), 1e4);
@@ -42745,7 +43243,9 @@ var GhostlyNode = class GhostlyNode {
42745
43243
  prepareSpare(after = 0, aged = false) {
42746
43244
  if (this.shuttingDown || !this.networkOn) return;
42747
43245
  if (this.spare && after === 0 && (aged || Date.now() - this.spare.madeAt >= SPARE_INVITE_MAX_AGE_MS)) {
42748
- for (const identity of [identityFromSeedB64(this.spare.mine.seedB64), this.spare.inviteKey]) this.warmedKeys.delete(identity.pubKeyZ32);
43246
+ const keys = [identityFromSeedB64(this.spare.mine.seedB64), this.spare.inviteKey].map((identity) => identity.pubKeyZ32);
43247
+ for (const key of keys) this.warmedKeys.delete(key);
43248
+ this.transport.forget?.(keys);
42749
43249
  this.spare = null;
42750
43250
  }
42751
43251
  if (!this.spare) this.spare = this.makeSpare();
@@ -43287,6 +43787,7 @@ var GhostlyNode = class GhostlyNode {
43287
43787
  groupHistoryGone(groupId) {
43288
43788
  const linkId = `group:${groupId}`;
43289
43789
  this.groupEdits.forget(groupId);
43790
+ this.groupPayments.forget(groupId);
43290
43791
  this.newestAt.delete(linkId);
43291
43792
  this.lateAt.delete(linkId);
43292
43793
  for (const clock of this.clockLeads.keys()) if (clock.startsWith(`${linkId} `)) this.clockLeads.delete(clock);
@@ -44324,6 +44825,7 @@ var GhostlyNode = class GhostlyNode {
44324
44825
  const error = message.card ? await link.sendMessage(message.text, message.timestamp, message.wireId, message.preview, reply, message.forwarded, message.card) : message.forwarded ? await link.sendMessage(message.text, message.timestamp, message.wireId, message.preview, reply, message.forwarded) : reply ? await link.sendMessage(message.text, message.timestamp, message.wireId, message.preview, reply) : await link.sendMessage(message.text, message.timestamp, message.wireId, ...message.preview ? [message.preview] : []);
44325
44826
  await this.noteTextSend(linkId, message, snapshot, at, error, link);
44326
44827
  if (!error && message.via === "pkarr") await this.cardWentBare(linkId, message);
44828
+ if (error && message.via === "pkarr" && message.wireId && link.dhtWentNowhere(message.wireId)) return new NotSent(error);
44327
44829
  return error;
44328
44830
  }, (message) => message.via === "pkarr" ? DHT_MESSAGE_TTL : 2e4, (message) => {
44329
44831
  const pending = this.links.get(linkId)?.stored.dhtDeliveryState?.pending;
@@ -44336,7 +44838,7 @@ var GhostlyNode = class GhostlyNode {
44336
44838
  return !!link?.canSendText && !!message.wireId && !link.validateText(message.text, message.timestamp, message.wireId, GhostlyNode.wireReply(message));
44337
44839
  },
44338
44840
  requeueExpired: () => !GhostlyNode.dhtByChoice(this.links.get(linkId)),
44339
- ...!!chat?.profile && !chat.group && { sendFile: (message) => this.sendWaitingFile(linkId, message) },
44841
+ ...!!chat?.profile && !chat.group && { sendFile: (message, cancelled) => this.sendWaitingFile(linkId, message, cancelled) },
44340
44842
  via: (message) => {
44341
44843
  const delivery = this.links.get(linkId)?.link?.textDelivery;
44342
44844
  return delivery === "dht" ? "pkarr" : delivery === "stream" ? "datalink" : message.via;
@@ -44612,6 +45114,13 @@ var GhostlyNode = class GhostlyNode {
44612
45114
  }
44613
45115
  }
44614
45116
  deleteMessage({ linkId, messageId }) {
45117
+ if (this.outboxes.get(linkId)?.cancel(messageId)) {
45118
+ this.removeMessage({
45119
+ linkId,
45120
+ messageId
45121
+ }).then(({ refused }) => refused ? this.forgetMessage(linkId, messageId) : void 0).catch(() => {});
45122
+ return;
45123
+ }
44615
45124
  this.forgetMessage(linkId, messageId);
44616
45125
  }
44617
45126
  /**
@@ -44633,7 +45142,8 @@ var GhostlyNode = class GhostlyNode {
44633
45142
  if (!canRemove(message)) return refuse("A payment, a request or a notice cannot be deleted for everyone");
44634
45143
  const out = `${linkId}-out-`;
44635
45144
  const wireId = message.wireId ?? (message.file?.id.startsWith(out) ? message.file.id.slice(out.length) : void 0);
44636
- if (!wireId || message.delivery === "waiting") {
45145
+ const going = this.outboxes.get(linkId)?.cancel(messageId) ?? false;
45146
+ if (!wireId || message.delivery === "waiting" && !going) {
44637
45147
  await this.forgetMessage(linkId, messageId, message);
44638
45148
  return { error: null };
44639
45149
  }
@@ -44755,15 +45265,7 @@ var GhostlyNode = class GhostlyNode {
44755
45265
  }
44756
45266
  if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
44757
45267
  if (message?.paymentId && message.sender === "peer") await this.desk.dropReceipt(message.paymentId).catch(() => {});
44758
- if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) {
44759
- const wireId = message.file.id.slice(`${linkId}-out-`.length);
44760
- live.link?.settleDht(dhtFileId(wireId)).catch(() => {});
44761
- live.stored = {
44762
- ...live.stored,
44763
- withdrawnFiles: [...(live.stored.withdrawnFiles ?? []).filter((id) => id !== wireId), wireId].slice(-64)
44764
- };
44765
- await db.patchLink(linkId, { withdrawnFiles: live.stored.withdrawnFiles });
44766
- }
45268
+ if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) await this.withdrawFloorFile(live, message.file.id.slice(`${linkId}-out-`.length));
44767
45269
  if (message?.file) {
44768
45270
  const stored = await fileStore.get(message.file.id);
44769
45271
  if (stored && !stored.wire3 && !stored.announced && (stored.direction === "in" || !stored.direction && message.sender === "peer")) live.files.receivedBytes = Math.max(0, live.files.receivedBytes - storedSize(stored));
@@ -45016,17 +45518,22 @@ var GhostlyNode = class GhostlyNode {
45016
45518
  * A file that waited for the chat to be live goes: said on the open session (see `transferFile`), and this returns
45017
45519
  * then, so the chat's outbox sends it in its place among the texts that waited (WISP 400, requirement 10). A file
45018
45520
  * for an app that turns out not to take files fails with that reason instead of waiting forever (WISP 03).
45521
+ * `cancelled`: whether it was deleted here since the outbox read it (`Outbox.cancel`); then nothing of it goes.
45019
45522
  */
45020
- async sendWaitingFile(linkId, message) {
45523
+ async sendWaitingFile(linkId, message, cancelled) {
45021
45524
  const live = this.links.get(linkId), file = message.file;
45022
- if (live?.link && file && !live.link.isDataLinkOpen) return this.sayFileOnFloor(live, message);
45525
+ if (live?.link && file && !live.link.isDataLinkOpen) return this.sayFileOnFloor(live, message, cancelled);
45023
45526
  if (!live?.link?.isDataLinkOpen || !file) return;
45024
45527
  if (message.fileOnFloor === "sent" || message.fileOnFloor === "seen") live.link.settleDht(dhtFileId(file.id.slice(`${linkId}-out-`.length))).catch(() => {});
45025
45528
  if (!GhostlyNode.takesFiles(live.link)) await GhostlyNode.largeFilesAgreed(live.link);
45026
- if (!live.link.isDataLinkOpen) return;
45529
+ if (cancelled() || !live.link.isDataLinkOpen) return;
45027
45530
  if (!GhostlyNode.takesFiles(live.link)) await db.updateDelivery(linkId, message.id, "failed", "Your contact's app cannot receive files.");
45028
45531
  else {
45029
- await db.putMessage(sentNow(message));
45532
+ if (!await db.patchMessage(linkId, message.id, (current) => current.delivery !== "waiting" ? null : {
45533
+ delivery: void 0,
45534
+ deliveryError: void 0,
45535
+ resendUntil: void 0
45536
+ }) || cancelled()) return;
45030
45537
  await this.transferFile(live, file, file.id.slice(`${linkId}-out-`.length), message.timestamp, (error) => {
45031
45538
  this.transfers.set(file.id, {
45032
45539
  state: "failed",
@@ -45066,8 +45573,9 @@ var GhostlyNode = class GhostlyNode {
45066
45573
  /**
45067
45574
  * Says a waiting file's offer on the DHT floor: the contact's chat shows its bubble in its place, and the bytes go once
45068
45575
  * live (the file stays `waiting`). Once only: an offer that cannot go there (a name too long) waits as before.
45576
+ * `cancelled`: whether it was deleted here since the outbox read it (`Outbox.cancel`).
45069
45577
  */
45070
- async sayFileOnFloor(live, message) {
45578
+ async sayFileOnFloor(live, message, cancelled = () => false) {
45071
45579
  const link = live.link, file = message.file, linkId = live.stored.id;
45072
45580
  if (!link || !file || message.fileOnFloor || !this.fileFloorReady(live, message)) return;
45073
45581
  const offer = GhostlyNode.floorOffer(linkId, file), at = Date.now();
@@ -45082,9 +45590,22 @@ var GhostlyNode = class GhostlyNode {
45082
45590
  result: "sent"
45083
45591
  }) }
45084
45592
  });
45085
- if (said && noted) await live.floorFiles?.then((known) => known.set(dhtFileId(offer.wireId), message.id), () => {});
45593
+ if (said && cancelled()) await this.withdrawFloorFile(live, offer.wireId);
45594
+ else if (said && noted) await live.floorFiles?.then((known) => known.set(dhtFileId(offer.wireId), message.id), () => {});
45086
45595
  await this.messagesChanged(linkId, [message.id]);
45087
45596
  }
45597
+ /**
45598
+ * A file of mine said on the floor and deleted here before it went live: the floor stops saying it, and the next
45599
+ * session that carries files/3 tells the contact's bubble it was cancelled (`sayWithdrawnFiles`).
45600
+ */
45601
+ async withdrawFloorFile(live, wireId) {
45602
+ live.link?.settleDht(dhtFileId(wireId)).catch(() => {});
45603
+ live.stored = {
45604
+ ...live.stored,
45605
+ withdrawnFiles: [...(live.stored.withdrawnFiles ?? []).filter((id) => id !== wireId), wireId].slice(-64)
45606
+ };
45607
+ await db.patchLink(live.stored.id, { withdrawnFiles: live.stored.withdrawnFiles });
45608
+ }
45088
45609
  /** A receipt on the DHT floor that names a waiting file's offer (`dhtFileId`): its bubble is in place on the contact's side. */
45089
45610
  async fileSeenOnFloor(linkId, id) {
45090
45611
  const live = this.links.get(linkId);
@@ -45220,7 +45741,14 @@ var GhostlyNode = class GhostlyNode {
45220
45741
  continue;
45221
45742
  }
45222
45743
  const file = message.file, wireId = file.id.slice(`${linkId}-out-`.length);
45223
- await db.putMessage(sentNow(message));
45744
+ if (!await db.patchMessage(linkId, message.id, (current) => current.delivery !== "waiting" ? null : {
45745
+ delivery: void 0,
45746
+ deliveryError: void 0,
45747
+ resendUntil: void 0
45748
+ })) {
45749
+ known.delete(message.id);
45750
+ continue;
45751
+ }
45224
45752
  this.transferFile(live, file, wireId, message.timestamp, (error) => {
45225
45753
  this.transfers.set(file.id, {
45226
45754
  state: "failed",
@@ -45506,12 +46034,13 @@ var GhostlyNode = class GhostlyNode {
45506
46034
  }
45507
46035
  if (live?.stored.deliveryMode === "dht") {
45508
46036
  const preferredTransport = transport === "auto" ? void 0 : transport;
46037
+ const native = transport === "auto" ? !live.link?.availableTransports.includes("webrtc/1") : transport !== "webrtc/1";
45509
46038
  live.stored = {
45510
46039
  ...live.stored,
45511
46040
  preferredTransport
45512
46041
  };
45513
46042
  await db.patchLink(linkId, { preferredTransport });
45514
- await this.switchDeliveryMode(linkId, "stream", true);
46043
+ await this.switchDeliveryMode(linkId, "stream", native);
45515
46044
  }
45516
46045
  if (transport !== "auto") {
45517
46046
  await this.setTransportPreference({
@@ -47848,6 +48377,9 @@ var GhostlyNode = class GhostlyNode {
47848
48377
  if (this.options.singleDevice) throw new Error("enroll-single: A profile of the command line is on one device only");
47849
48378
  if (this.limitedMode) throw new Error(LIMITED_MODE_ERROR);
47850
48379
  if (!this.networkOn) throw new Error("enroll-offline: You are offline");
48380
+ if (this.settingMove) throw new Error("enroll-busy: The device set is already changing. Try again after it.");
48381
+ const handoff = this.handoffGiver?.view();
48382
+ if (handoff && handoff.step !== "failed") throw new Error("enroll-busy: The profile is moving. Try again after it.");
47851
48383
  }
47852
48384
  /**
47853
48385
  * The active device's links to the other devices, and its stored turn record put again (WISP 06 § Publishing and
@@ -48007,6 +48539,14 @@ var GhostlyNode = class GhostlyNode {
48007
48539
  const handoff = this.handoffGiver?.view();
48008
48540
  if (handoff && handoff.step !== "failed") throw new Error(`${prefix}-busy: The profile is moving. Try again after it.`);
48009
48541
  }
48542
+ /**
48543
+ * A device being added or a move of the set in progress: the handoff waits for it (`GiverPorts.setChanging`). A move
48544
+ * that cancelled an Add after its grant went out would leave the note of that grant on a device no longer active.
48545
+ */
48546
+ deviceSetChanging() {
48547
+ const view = this.enrollment?.current();
48548
+ return this.settingMove !== null || !!view && view.step !== "done" && view.step !== "failed";
48549
+ }
48010
48550
  async moveDeviceSet(remove) {
48011
48551
  this.setMoveAllowed();
48012
48552
  if (this.settingMove) throw new Error("remove-busy: The device set is already changing.");
@@ -48303,6 +48843,7 @@ var GhostlyNode = class GhostlyNode {
48303
48843
  source: host.source(profile),
48304
48844
  verifier: () => this.handoffVerifier(),
48305
48845
  busy: (taker) => this.handoffBusy(taker),
48846
+ setChanging: () => this.deviceSetChanging(),
48306
48847
  staying: (taker) => this.handoffStaying(taker),
48307
48848
  quiesce: (patch, taker) => this.quiesceForHandoff(patch, taker)
48308
48849
  });
@@ -49679,10 +50220,13 @@ var GhostlyNode = class GhostlyNode {
49679
50220
  nativeFactoriesFor(relayOnly) {
49680
50221
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
49681
50222
  return {
49682
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-DDCak5PY.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
50223
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CV6qMrom.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
49683
50224
  ...relayOnly ? {} : this.options.nativeTransports,
49684
50225
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
49685
- ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
50226
+ ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, {
50227
+ relays: this.irohRelays,
50228
+ ...this.options.irohPublicRelay && { publicRelay: this.options.irohPublicRelay }
50229
+ }) } : {}
49686
50230
  };
49687
50231
  }
49688
50232
  /** The host runs Iroh itself and homes it on the relays it is given (the Desktop). */
@@ -51059,4 +51603,4 @@ function signalKind(signal) {
51059
51603
  //#endregion
51060
51604
  export { EngineServer };
51061
51605
 
51062
- //# sourceMappingURL=server-BJ3T-kx3.js.map
51606
+ //# sourceMappingURL=server-DYdR0_Fj.js.map