@ghostlytools/cli 1.7.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +22 -12
  2. package/dist/assets/{api-BnCmJLiQ.js → api-CcuCtc1H.js} +2 -2
  3. package/dist/assets/{api-BIqr8SpM.js → api-tSZELCPQ.js} +133 -40
  4. package/dist/assets/api-tSZELCPQ.js.map +1 -0
  5. package/dist/assets/{apiKit-CWalYh1t.js → apiKit-BFk7GAk9.js} +9 -5
  6. package/dist/assets/{apiKit-CWalYh1t.js.map → apiKit-BFk7GAk9.js.map} +1 -1
  7. package/dist/assets/{apps-Bx3tXbJ9.js → apps-C5Mi6x9Q.js} +36 -13
  8. package/dist/assets/apps-C5Mi6x9Q.js.map +1 -0
  9. package/dist/assets/{apps-_hVUaHIT.js → apps-D6THreq_.js} +1 -1
  10. package/dist/assets/{arkade-AxrcyS1C.js → arkade-Cz0B9bJ0.js} +2 -2
  11. package/dist/assets/{arkade-AxrcyS1C.js.map → arkade-Cz0B9bJ0.js.map} +1 -1
  12. package/dist/assets/{backup-d_XvXpEK.js → backup-A0hIa9GE.js} +1 -1
  13. package/dist/assets/{backup-Y1V1Yxqr.js → backup-Wb2sm2dd.js} +6 -6
  14. package/dist/assets/{backup-Y1V1Yxqr.js.map → backup-Wb2sm2dd.js.map} +1 -1
  15. package/dist/assets/{blobFiles-B6nf0gCG.js → blobFiles-Bckz9fjp.js} +2 -2
  16. package/dist/assets/{blobFiles-B6nf0gCG.js.map → blobFiles-Bckz9fjp.js.map} +1 -1
  17. package/dist/assets/buttons-Bxxu3lSk.js +2 -0
  18. package/dist/assets/{buttons-BiQyQBb0.js → buttons-Cf70NVYq.js} +12 -7
  19. package/dist/assets/buttons-Cf70NVYq.js.map +1 -0
  20. package/dist/assets/{daemonProof-ui8jtIw0.js → daemonProof-Bp9lJDxf.js} +2 -2
  21. package/dist/assets/{daemonProof-ui8jtIw0.js.map → daemonProof-Bp9lJDxf.js.map} +1 -1
  22. package/dist/assets/{envelope-D3oeVhv8.js → envelope-kQ5kYjVE.js} +2 -2
  23. package/dist/assets/{envelope-D3oeVhv8.js.map → envelope-kQ5kYjVE.js.map} +1 -1
  24. package/dist/assets/{errors-CzXgR8Cc.js → errors-mnjSQlbX.js} +2 -1
  25. package/dist/assets/errors-mnjSQlbX.js.map +1 -0
  26. package/dist/assets/{fileBytes-BMEBas7S.js → fileBytes-BD0v3rRG.js} +10 -2
  27. package/dist/assets/{fileBytes-BMEBas7S.js.map → fileBytes-BD0v3rRG.js.map} +1 -1
  28. package/dist/assets/{fileBytes-CtwagJ8h.js → fileBytes-OolN5cSY.js} +1 -1
  29. package/dist/assets/{fileBytes-CFNrRfcl.js → fileBytes-_fd-2JRY.js} +2 -2
  30. package/dist/assets/{fileBytes-CFNrRfcl.js.map → fileBytes-_fd-2JRY.js.map} +1 -1
  31. package/dist/assets/fileBytesIdb-CsSQcSxD.js +2 -0
  32. package/dist/assets/{fileBytesIdb-BXAN7i-N.js → fileBytesIdb-NtA8r9EM.js} +2 -2
  33. package/dist/assets/{fileBytesIdb-BXAN7i-N.js.map → fileBytesIdb-NtA8r9EM.js.map} +1 -1
  34. package/dist/assets/{fileBytesOpfs-Do1Vpkis.js → fileBytesOpfs-B8fJwkwM.js} +3 -3
  35. package/dist/assets/{fileBytesOpfs-Do1Vpkis.js.map → fileBytesOpfs-B8fJwkwM.js.map} +1 -1
  36. package/dist/assets/{ghostly_iroh_web-BXCsSxxo.js → ghostly_iroh_web-CO0onry8.js} +33 -27
  37. package/dist/assets/ghostly_iroh_web-CO0onry8.js.map +1 -0
  38. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  39. package/dist/assets/{groupFiles-DU1wMGI9.js → groupFiles-D9Ttlm3M.js} +41 -25
  40. package/dist/assets/groupFiles-D9Ttlm3M.js.map +1 -0
  41. package/dist/assets/{host-DDMQfR7B.js → host-DpypH-fR.js} +44 -21
  42. package/dist/assets/host-DpypH-fR.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-B2v8eqRd.js → hyperdhtRelay-D1rj84v2.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-B2v8eqRd.js.map → hyperdhtRelay-D1rj84v2.js.map} +1 -1
  45. package/dist/assets/{irohWeb-9RVIbF_l.js → irohWeb-BTSlWgEX.js} +3 -3
  46. package/dist/assets/{irohWeb-9RVIbF_l.js.map → irohWeb-BTSlWgEX.js.map} +1 -1
  47. package/dist/assets/{main-BNwNEPEy.js → main-BwgoQZVu.js} +270 -97
  48. package/dist/assets/main-BwgoQZVu.js.map +1 -0
  49. package/dist/assets/{mainline-RXv5_Fby.js → mainline-B1urhbEZ.js} +27 -8
  50. package/dist/assets/mainline-B1urhbEZ.js.map +1 -0
  51. package/dist/assets/{networkReason-CIn4yN9h.js → networkReason-D2Z0BdIj.js} +2 -2
  52. package/dist/assets/{networkReason-CIn4yN9h.js.map → networkReason-D2Z0BdIj.js.map} +1 -1
  53. package/dist/assets/{nwc-BNPzuT-6.js → nwc-T2aUK6bi.js} +3 -3
  54. package/dist/assets/{nwc-BNPzuT-6.js.map → nwc-T2aUK6bi.js.map} +1 -1
  55. package/dist/assets/{nwcProvider-C9Y6PUNC.js → nwcProvider-Dz-ty_DE.js} +2 -2
  56. package/dist/assets/{nwcProvider-C9Y6PUNC.js.map → nwcProvider-Dz-ty_DE.js.map} +1 -1
  57. package/dist/assets/{profiles-CEnZfN78.js → profiles-C6XWqre5.js} +92 -20
  58. package/dist/assets/profiles-C6XWqre5.js.map +1 -0
  59. package/dist/assets/{registry-B9aYHNNf.js → registry-Bazitl0a.js} +3 -3
  60. package/dist/assets/{registry-B9aYHNNf.js.map → registry-Bazitl0a.js.map} +1 -1
  61. package/dist/assets/{registry-DOkDhUAu.js → registry-BlSTJlbv.js} +1 -1
  62. package/dist/assets/{resolve-imkCgogd.js → resolve-Bx1Eeg-w.js} +2 -2
  63. package/dist/assets/{resolve-imkCgogd.js.map → resolve-Bx1Eeg-w.js.map} +1 -1
  64. package/dist/assets/{server-CB9_JuWZ.js → server-CnPj9wWh.js} +661 -229
  65. package/dist/assets/server-CnPj9wWh.js.map +1 -0
  66. package/dist/assets/{src-BBG_NwMc.js → src-BsznF3XG.js} +305 -83
  67. package/dist/assets/src-BsznF3XG.js.map +1 -0
  68. package/dist/assets/{translate-BcP139SV.js → translate-cDBotA-b.js} +11 -11
  69. package/dist/assets/{translate-BcP139SV.js.map → translate-cDBotA-b.js.map} +1 -1
  70. package/dist/assets/types-C4_KafL_.js.map +1 -1
  71. package/dist/assets/{usdt-C5Gf9-IC.js → usdt-DxxLdG60.js} +3 -3
  72. package/dist/assets/{usdt-C5Gf9-IC.js.map → usdt-DxxLdG60.js.map} +1 -1
  73. package/dist/assets/{words-ZUiQo4yo.js → words-qH8gGtmc.js} +2 -2
  74. package/dist/assets/{words-ZUiQo4yo.js.map → words-qH8gGtmc.js.map} +1 -1
  75. package/dist/ghostly.mjs +1 -1
  76. package/package.json +1 -1
  77. package/dist/assets/api-BIqr8SpM.js.map +0 -1
  78. package/dist/assets/apps-Bx3tXbJ9.js.map +0 -1
  79. package/dist/assets/buttons-BiQyQBb0.js.map +0 -1
  80. package/dist/assets/buttons-LO3Ql1Hd.js +0 -2
  81. package/dist/assets/errors-CzXgR8Cc.js.map +0 -1
  82. package/dist/assets/fileBytesIdb-C20oXDdr.js +0 -2
  83. package/dist/assets/ghostly_iroh_web-BXCsSxxo.js.map +0 -1
  84. package/dist/assets/groupFiles-DU1wMGI9.js.map +0 -1
  85. package/dist/assets/host-DDMQfR7B.js.map +0 -1
  86. package/dist/assets/main-BNwNEPEy.js.map +0 -1
  87. package/dist/assets/mainline-RXv5_Fby.js.map +0 -1
  88. package/dist/assets/profiles-CEnZfN78.js.map +0 -1
  89. package/dist/assets/server-CB9_JuWZ.js.map +0 -1
  90. package/dist/assets/src-BBG_NwMc.js.map +0 -1
@@ -1,16 +1,16 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $c as createContactLink, $i as automaticTransport, $l as PacketTooLargeError, $o as HANDOFF_OFFER, $r as vapidKeysMatch, $s as readEnrollHello, A as knockRecords, Aa as GROUP_REACTION_FRAME, Al as firstDeviceSetSecret, An as findEndpoint, Ao as webLocalFetch, As as readHandoffPake, B as GROUP_READ_NOTE, Ba as pairedReplyAuthor, Bi as IdentityExchange, Bl as DEFAULT_RELAYS, Bn as EngineError, Bo as contactRtcConfig, Br as mayPin, Bs as verifySetUpdate, C as decodeCommunityLink, Ca as REMOVED_TEXT, Cc as APP_BUNDLE_LIMITS, Cr as rankHubs, Cs as handoffVersions, D as encodeGroupEntryLink, Da as forwardedAgain, Dc as appDigest, Dl as turnPutSummary, Dn as ENDPOINT, Do as GhostlyHttpError, Dr as shouldBeHub, Ds as readHandoffDone, E as decodeGroupEntryLink, Ea as parseLinkPreview, El as classifyTurnRead, En as decodeBolt11, Eo as presenceSeenAt, Er as readLobby, Es as readHandoffCancel, F as groupWakeFrame, Fa as reactionEmoji, Fc as sha256Paced, Fi as dialDescriptors, Fl as turnInstance, Fn as INVITE_TAKEN, Fo as RTC_CONFIG, Fr as TypingSender, G as GROUP_EDIT_TEXT_BYTES, Gi as newIdentityBinding, Go as HTTP_SERVICE_PROTO, Gr as WAKE_CALL_INTERVAL_MS, Gs as enrollCancelFrame, Gt as encodeDidDhtPacket, H as frameBytes, Ha as replySnippet, Hc as isAppKey, Hi as emptyIdentityLedger, Hn as engineText, Ho as parseCallSignal, Hr as pinIsNewer, Ht as didDhtDocument, I as groupWakes, Ia as reactionIsNewer, Il as turnKeys, In as LIVENESS_PING_MS, Is as readSetUpdate, J as mentionsMember, Jc as parseImageMeta, Ji as lastSharedWithMe, Jo as HANDOFF_ACK, Jr as newWakeToken, Js as enrollDoneFrame, Jt as ETHEREUM_USDT, K as carryMentions, Ki as receivedIdentityStatus, Kl as currentRelays, Ko as LEGACY_SERVICES, Kr as WakeLimiter, Ks as enrollCancelReason, L as parseGroupWakeFrame, La as readReaction, Lc as APP_STATEMENT_LIMITS, Ll as turnName, Ln as PAIRED_FRAME_TOO_LARGE, Lr as typingActivity, Ls as setAckFrame, M as readKnocks, Ma as ReactionWindow, Mc as pacer, Mi as CapsExchange, Ml as readTurnPacket, Mn as parseCashuRequestPayload, Mo as decodeControl, Mr as transferStalled, Ms as readHandoffVerified, Na as nextReactionNumber, Ni as DHT_TEXT_CAPABILITY, Nl as signTurnPacket, Nn as parseFedimintRequestPayload, No as encodeControl, Ns as sealHandoffPiece, O as entryParams, Oa as readForwarded, Oc as appViewOf, Ol as TURN_LAST_SEQUENCE, On as cashuRequestPayload, Oo as formatLocalTarget, Or as ChatFiles, Os as readHandoffHave, P as GroupWakeLimiter, Pa as queueReaction, Pc as readAppBundleAsync, Pi as capsDescriptors, Pl as signTurnRelease, Pn as GhostLink, Qc as readCanonicalJson, Qi as TRANSPORTS, Ql as withRequestOptions, Qo as HANDOFF_HELLO, Qr as checkPushEndpoint, Qs as readEnrollGrant, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as validReactionNumber, Rc as appFingerprint, Ri as IDENTITY_REVOCATION_LABEL, Rl as turnStatedVerifier, Rn as pairedMessageFits, Rs as setUpdateFrame, S as communityHasFrame, Sa as MAX_REMOVAL_NUMBER, Sc as seenEntry, Sl as webCryptoSigner, So as DHT_POLL_INTERVALS, Sr as pickHubs, Ss as handoffStreamKey, Ta as dhtEditId, Tc as APP_ICON_PATH, Tl as TURN_SETTLE_MS, To as WATCH_PEER_MS, Tr as readBeaconHead, Ts as readHandoffAck, Ua as BUTTON_ID, Uc as isAppRef, Ui as identityRevocationValue, Ul as RelayTransport, Un as parseEngineError, Ur as pinNumberHolds, Ut as didDhtFromPublicKey, V as GroupSession, Va as readReply, Vc as isAppHash, Vn as engineError, Vr as nextPinNumber, Wc as readAppRevocation, Wi as identityStatement, Wn as GROUP_FILE_LIMITS, Wo as emptyLinkRecords, Wr as readPin, Wt as encodeDidDhtDeactivated, Xa as STATUS_CARD_LIMITS, Xc as canonicalJson, Xi as emptyProofLedger, Xl as budgetRetryMs, Xo as HANDOFF_DONE, Xr as relayRequest, Xs as enrollHelloFrame, Xt as ONCHAIN_PROVIDER, Y as groupName, Yi as PeerProofs, Yl as traceLink, Yn as groupFileFallback, Yo as HANDOFF_CANCEL, Yr as parseWakeFrame, Ys as enrollGrantFrame, Yt as EVM_TEST_CHAINS, Zi as validExternalKey, Zl as isDiscoveryBudgetError, Zn as readGroupFileMeta, Zo as HANDOFF_HAVE, Zr as wakeRequest, Zs as enrollProofFrame, Zt as PaymentPreflightError, _ as openGroupTyping, _c as mergeContactKnocks, _i as readManifest, _l as deviceKeyZ32, _o as rosterHas, _r as lobbyKeys, _s as handoffManifestFrames, _u as toBase64Url, a as appStoreDecision, aa as DHT_FILE_CAPABILITY, ac as planKnocks, ai as APPS_CAPABILITY, al as OwnInviteError, an as assertWholeSats, ao as arrivalKey, as as filePartName, au as createIdentity, b as CommunitySession, ba as EDIT_BUFFER_MS, bc as readLinkRecord, bl as newDeviceSetSecret, bo as DirectPathWatch, br as mergeLobby, bs as handoffReleaseFrame, bu as utf8Encode, c as planAppUpdate, ca as sanitizeFileName, cc as turnOff, ci as STATUS_CARD_CAPABILITY, cl as encodeInviteCode, cn as walletNetworkOf, co as receivedTimestamp, cr as MESH_HUBS, cs as handoffAttemptSucceeded, cu as publicKeyFromZ32, dc as contactDay, di as HOLD_DATED_BACK_MS, dn as sparkAddressKind, do as GROUP_MEMBER_CAP, dr as pickMeshHubs, ds as handoffContext, du as sanitizeAvatar, ec as verifyEnrollProof, ei as APP_RANGE_LIMITS, el as encodeContactLink, en as TEST_USDT_FAUCET_AMOUNT, es as HANDOFF_PAKE, f as readAppStoreSteps, fc as knockSlotIdentity, fi as HOLD_LIMITS, fl as DEVICES_CAPABILITY, fn as sparkInvoiceDetails, fr as COMMUNITY_TOPOLOGY, fs as handoffContextProof, fu as sanitizeDisplayText, g as groupTypingEpoch, ga as parseVoiceMeta, gc as makeStampPaced, gi as newMailbox, gl as deviceEchoNonce, go as rosterAdmin, gr as freshHubs, gs as handoffHelloFrame, gt as normalizeAtprotoHandle, gu as randomBytes, h as GroupTypingBoard, ha as fileMessageText, hc as linkRecords, hi as isHoldUrl, hl as deviceEchoFrame, hn as isPubkyKey, ho as parseGroupCommit, hr as doorHubs, hs as handoffEphemeral, ht as isAtprotoDid, i as appRevocationFor, ia as peekDhtMailbox, ic as newInbox, ii as isAppVersion, il as readDeviceInvite, in as assertTokenUnits, io as statusCardText, is as HANDOFF_VERIFIED, j as mergeKnocks, ja as REACTION_LIMITS, jc as isAppUrl, jl as nextTurnPosition, jn as isFederationId, jo as LIMITS, jr as transferEnded, js as readHandoffTurnFrame, k as knockIdentity, ka as COMMUNITY_REACTION_FRAME, kl as TURN_MAX, kn as fedimintRequestPayload, ko as parseLocalTarget, kr as FILE_LIMITS, ks as readHandoffHello, l as APP_STORE_LIMITS, la as sanitizeMime, lc as ContactRequestError, li as UPGRADE_CAPABILITY, ll as inviteLink, ln as SPARK_NETWORKS, lo as shownTime, lr as mayBeHub, ls as handoffBusyFrame, lu as verify, mc as knockSlotRecords, mi as HoldRefusedError, ml as HANDOFF_CAPABILITY, mo as commitHash, mr as beaconRecords, ms as handoffDigest, mu as fromBase64Url, n as readX401SdJwtVc, nc as endedRequests, nl as createDeviceInvite, nn as WALLET_NETWORKS, no as checkStatusCard, ns as HANDOFF_REQUEST, o as appUpdateDecision, oa as dhtFileId, oc as settleRequest, oi as BUTTONS_CAPABILITY, ol as createChatInvite, on as formatPaymentAmount, oo as claimedTime, or as groupSignalFrame, os as handoffAttemptAllowed, ou as identityFromSeed, pc as knockSlotOf, pi as HoldKeys, pl as ENROLL_CAPABILITY, pn as isBitcoinAddress, po as MEMBER_KEY, pr as beaconKeys, ps as handoffDataFrame, pu as bytesEqual, q as parseCommunityEdit, qi as revokesIdentity, ql as normalizeRelayUrl, qo as serviceIdFromName, qr as deviceWakeRequest, qs as enrollDigits, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_MESSAGE_TTL, rc as inboxRecord, ri as chatAppId, rl as deviceInviteJoinerParams, rn as arkAddressPrefix, ro as sameButtonText, rs as HANDOFF_TIMINGS, s as checkAppBeforeRun, sa as formatFileSize, sc as takeRequest, si as EDIT_CAPABILITY, sl as decodeInviteCode, sn as validatePaymentTarget, so as heardTime, sr as readGroupSignal, ss as handoffAttemptFailed, su as identityFromSeedB64, t as newX401HolderKey, tc as clearMissed, ti as isServeId, tl as readContactLink, tn as USDT_PUBLIC_RPC, tr as CarriedTransport, ts as HANDOFF_PIECE_BYTES, tu as createRelayPayload, uc as REQUEST_LIFETIME_MS, ui as HOLD_CAPABILITY, ul as inviteOwnership, un as SPARK_PROVIDER, uo as GROUP_ADMIN_OFF_ERROR, ur as meshHubs, us as handoffCancelFrame, v as sealGroupTyping, vc as openRequest, vl as deviceLinkPairing, vo as verifyCommitSignature, vr as lobbyRecords, vs as handoffOfferFrame, vu as toZ32, w as encodeCommunityLink, wa as RateWindow, wc as APP_BUNDLE_MAGIC, wl as TURN_RAISE_READ_TIMEOUT_MS, wo as RELAY_POLL_INTERVALS, wr as readBeacon, ws as newHandoffId, x as GROUP_READ_NOTE_COMMUNITY, xa as EDIT_RATE_WINDOW_MS, xc as requestRecords, xl as seedSigner, xr as newerHead, xs as handoffRetryAfter, y as COMMUNITY_LIMITS, ya as parseVideoMeta, yc as readKnockSlot, yl as devicePingFrame, yo as edgeParams, yr as mergeBeacon, ys as handoffPakeFrame, yu as utf8Decode, za as wireReaction, zc as appRef, zl as turnVerifierMark, zn as pairedMessageFrame, zr as PIN_LIMITS, zs as signTombstone } from "./src-BBG_NwMc.js";
2
+ import { $i as automaticTransport, $l as traceLink, $o as HANDOFF_HAVE, $r as vapidKeysMatch, $s as enrollHelloFrame, A as knockRecords, Aa as GROUP_REACTION_FRAME, Ac as appDigest, Al as classifyTurnRead, An as findEndpoint, Ao as formatLocalTarget, As as readHandoffDone, B as GROUP_READ_NOTE, Ba as pairedReplyAuthor, Bc as APP_STATEMENT_LIMITS, Bi as IdentityExchange, Bl as turnKeys, Bn as EngineError, Br as mayPin, Bs as setAckFrame, C as decodeCommunityLink, Ca as REMOVED_TEXT, Cc as readLinkRecord, Cl as devicePingFrame, Cr as rankHubs, Cs as handoffReleaseFrame, Cu as utf8Decode, D as encodeGroupEntryLink, Da as forwardedAgain, Dc as APP_BUNDLE_MAGIC, Dn as ENDPOINT, Do as WATCH_PEER_MS, Dr as shouldBeHub, Ds as newHandoffId, E as decodeGroupEntryLink, Ea as parseLinkPreview, Ec as APP_BUNDLE_LIMITS, El as webCryptoSigner, En as decodeBolt11, Eo as RELAY_POLL_INTERVALS, Er as readLobby, Es as handoffVersions, F as groupWakeFrame, Fa as reactionEmoji, Fc as pacer, Fi as dialDescriptors, Fl as nextTurnPosition, Fn as INVITE_TAKEN, Fo as encodeControl, Fr as TypingSender, Fs as readHandoffVerified, G as GROUP_EDIT_TEXT_BYTES, Gc as isAppKey, Gi as newIdentityBinding, Gr as WAKE_CALL_INTERVAL_MS, Gt as encodeDidDhtPacket, H as frameBytes, Ha as replySnippet, Hc as appRef, Hi as emptyIdentityLedger, Hl as turnStatedVerifier, Hn as engineText, Ho as contactRtcConfig, Hr as pinIsNewer, Hs as signTombstone, Ht as didDhtDocument, I as groupWakes, Ia as reactionIsNewer, Il as readTurnPacket, In as LIVENESS_PING_MS, Is as sealHandoffPiece, J as mentionsMember, Ji as lastSharedWithMe, Jo as LEGACY_SERVICES, Jr as newWakeToken, Js as enrollCancelFrame, Jt as ETHEREUM_USDT, K as carryMentions, Kc as isAppRef, Ki as receivedIdentityStatus, Ko as emptyLinkRecords, Kr as WakeLimiter, L as parseGroupWakeFrame, La as readReaction, Lc as readAppBundleAsync, Ll as signTurnPacket, Ln as PAIRED_FRAME_TOO_LARGE, Lo as RTC_CONFIG, Lr as typingActivity, M as readKnocks, Ma as ReactionWindow, Mi as CapsExchange, Ml as TURN_LAST_SEQUENCE, Mn as parseCashuRequestPayload, Mo as webLocalFetch, Mr as transferStalled, Ms as readHandoffHello, Na as nextReactionNumber, Ni as DHT_TEXT_CAPABILITY, Nl as TURN_MAX, Nn as parseFedimintRequestPayload, No as LIMITS, Ns as readHandoffPake, O as entryParams, Oa as readForwarded, Oc as APP_ICON_PATH, Ol as TURN_RAISE_READ_TIMEOUT_MS, On as cashuRequestPayload, Oo as presenceSeenAt, Or as ChatFiles, Os as readHandoffAck, P as GroupWakeLimiter, Pa as queueReaction, Pc as isAppUrl, Pi as capsDescriptors, Pl as firstDeviceSetSecret, Pn as GhostLink, Po as decodeControl, Ps as readHandoffTurnFrame, Qc as parseImageMeta, Qi as TRANSPORTS, Qo as HANDOFF_DONE, Qr as checkPushEndpoint, Qs as enrollGrantFrame, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as validReactionNumber, Rc as sha256Paced, Ri as IDENTITY_REVOCATION_LABEL, Rl as signTurnRelease, Rn as pairedMessageFits, S as communityHasFrame, Sa as MAX_REMOVAL_NUMBER, Sc as readKnockSlot, Sl as deviceLinkPairing, So as DirectPathWatch, Sr as pickHubs, Ss as handoffPakeFrame, Su as toZ32, Ta as dhtEditId, Tc as seenEntry, Tl as seedSigner, Tr as readBeaconHead, Ts as handoffStreamKey, Ua as BUTTON_ID, Ui as identityRevocationValue, Ul as turnVerifierMark, Un as parseEngineError, Ur as pinNumberHolds, Us as verifySetUpdate, Ut as didDhtFromPublicKey, V as GroupSession, Va as readReply, Vc as appFingerprint, Vl as turnName, Vn as engineError, Vr as nextPinNumber, Vs as setUpdateFrame, Wc as isAppHash, Wi as identityStatement, Wl as DEFAULT_RELAYS, Wn as GROUP_FILE_LIMITS, Wo as parseCallSignal, Wr as readPin, Wt as encodeDidDhtDeactivated, Xi as emptyProofLedger, Xl as currentRelays, Xo as HANDOFF_ACK, Xr as relayRequest, Xs as enrollDigits, Xt as ONCHAIN_PROVIDER, Y as groupName, Yi as PeerProofs, Yn as groupFileFallback, Yo as serviceIdFromName, Yr as parseWakeFrame, Ys as enrollCancelReason, Yt as EVM_TEST_CHAINS, Za as STATUS_CARD_LIMITS, Zi as validExternalKey, Zl as normalizeRelayUrl, Zn as readGroupFileMeta, Zo as HANDOFF_CANCEL, Zr as wakeRequest, Zs as enrollDoneFrame, Zt as PaymentPreflightError, _ as openGroupTyping, _c as knockSlotRecords, _i as readManifest, _l as ENROLL_CAPABILITY, _o as parseGroupCommit, _r as lobbyKeys, _s as handoffDigest, _u as bytesEqual, a as appStoreDecision, aa as DHT_FILE_CAPABILITY, ac as endedRequests, ai as APPS_CAPABILITY, al as readContactLink, an as assertWholeSats, as as HANDOFF_TIMINGS, au as createRelayPayload, b as CommunitySession, ba as EDIT_BUFFER_MS, bc as mergeContactKnocks, bl as deviceEchoNonce, bo as verifyCommitSignature, br as mergeLobby, bs as handoffManifestFrames, bu as randomBytes, c as planAppUpdate, ca as sanitizeFileName, cc as planKnocks, ci as STATUS_CARD_CAPABILITY, cl as readDeviceInvite, cn as walletNetworkOf, co as claimedTime, cr as MESH_HUBS, cs as filePartName, dc as turnOff, di as HOLD_DATED_BACK_MS, dl as decodeInviteCode, dn as sparkAddressKind, do as shownTime, dr as pickMeshHubs, ds as handoffAttemptSucceeded, du as identityFromSeedB64, ec as enrollProofFrame, ei as APP_RANGE_LIMITS, el as canonicalJson, en as TEST_USDT_FAUCET_AMOUNT, es as HANDOFF_HELLO, eu as budgetRetryMs, f as readAppStoreSteps, fc as ContactRequestError, fi as HOLD_LIMITS, fl as encodeInviteCode, fn as sparkInvoiceDetails, fo as GROUP_ADMIN_OFF_ERROR, fr as COMMUNITY_TOPOLOGY, fs as handoffBusyFrame, fu as publicKeyFromZ32, g as groupTypingEpoch, ga as parseVoiceMeta, gc as knockSlotOf, gi as newMailbox, gl as DEVICES_CAPABILITY, go as commitHash, gr as freshHubs, gs as handoffDataFrame, gt as normalizeAtprotoHandle, gu as sanitizeDisplayText, h as GroupTypingBoard, ha as fileMessageText, hc as knockSlotIdentity, hi as isHoldUrl, hn as isPubkyKey, ho as MEMBER_KEY, hr as doorHubs, hs as handoffContextProof, ht as isAtprotoDid, hu as sanitizeAvatar, i as appRevocationFor, ia as peekDhtMailbox, ic as clearMissed, ii as isAppVersion, il as encodeContactLink, in as assertTokenUnits, io as sameButtonText, is as HANDOFF_REQUEST, j as mergeKnocks, ja as REACTION_LIMITS, jc as appViewOf, jl as turnPutSummary, jn as isFederationId, jo as parseLocalTarget, jr as transferEnded, js as readHandoffHave, k as knockIdentity, ka as COMMUNITY_REACTION_FRAME, kl as TURN_SETTLE_MS, kn as fedimintRequestPayload, ko as GhostlyHttpError, kr as FILE_LIMITS, ks as readHandoffCancel, l as APP_STORE_LIMITS, la as sanitizeMime, lc as settleRequest, li as UPGRADE_CAPABILITY, ll as OwnInviteError, ln as SPARK_NETWORKS, lo as heardTime, lr as mayBeHub, ls as handoffAttemptAllowed, lu as createIdentity, mc as contactDay, mi as HoldRefusedError, ml as inviteOwnership, mr as beaconRecords, ms as handoffContext, n as readX401SdJwtVc, nc as readEnrollHello, nl as readCanonicalJson, nn as WALLET_NETWORKS, ns as HANDOFF_PAKE, nu as withRequestOptions, o as appUpdateDecision, oa as dhtFileId, oc as inboxRecord, oi as BUTTONS_CAPABILITY, ol as createDeviceInvite, on as formatPaymentAmount, oo as statusCardText, or as groupSignalFrame, os as HANDOFF_VERIFIED, pc as REQUEST_LIFETIME_MS, pi as HoldKeys, pl as inviteLink, pn as isBitcoinAddress, po as GROUP_MEMBER_CAP, pr as beaconKeys, ps as handoffCancelFrame, pu as verify, q as parseCommunityEdit, qc as readAppRevocation, qi as revokesIdentity, ql as RelayTransport, qo as HTTP_SERVICE_PROTO, qr as deviceWakeRequest, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_MESSAGE_TTL, rc as verifyEnrollProof, ri as chatAppId, rl as createContactLink, rn as arkAddressPrefix, ro as checkStatusCard, rs as HANDOFF_PIECE_BYTES, ru as PacketTooLargeError, s as checkAppBeforeRun, sa as formatFileSize, sc as newInbox, si as EDIT_CAPABILITY, sl as deviceInviteJoinerParams, sn as validatePaymentTarget, so as arrivalKey, sr as readGroupSignal, ss as NO_ATTEMPTS, t as newX401HolderKey, tc as readEnrollGrant, ti as isServeId, tn as USDT_PUBLIC_RPC, tr as CarriedTransport, ts as HANDOFF_OFFER, tu as isDiscoveryBudgetError, uc as takeRequest, ui as HOLD_CAPABILITY, ul as createChatInvite, un as SPARK_PROVIDER, uo as receivedTimestamp, ur as meshHubs, us as handoffAttemptFailed, uu as identityFromSeed, v as sealGroupTyping, vc as linkRecords, vl as HANDOFF_CAPABILITY, vo as rosterAdmin, vr as lobbyRecords, vs as handoffEphemeral, vu as fromBase64Url, w as encodeCommunityLink, wa as RateWindow, wc as requestRecords, wl as newDeviceSetSecret, wo as DHT_POLL_INTERVALS, wr as readBeacon, ws as handoffRetryAfter, wu as utf8Encode, x as GROUP_READ_NOTE_COMMUNITY, xa as EDIT_RATE_WINDOW_MS, xc as openRequest, xl as deviceKeyZ32, xo as edgeParams, xr as newerHead, xs as handoffOfferFrame, xu as toBase64Url, y as COMMUNITY_LIMITS, ya as parseVideoMeta, yc as makeStampPaced, yl as deviceEchoFrame, yo as rosterHas, yr as mergeBeacon, ys as handoffHelloFrame, za as wireReaction, zl as turnInstance, zn as pairedMessageFrame, zr as PIN_LIMITS, zs as readSetUpdate } from "./src-BsznF3XG.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-C9Y6PUNC.js";
5
+ import { t as nwc } from "./nwcProvider-Dz-ty_DE.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-BlH8-O3R.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-CIn4yN9h.js";
8
- import { $ as setAwayWallets, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as relayOnlyProblem, H as dropBreezDatabase, I as sourceKey, J as WrongNetworkError, K as ModeChanged, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as requireTurn, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as awayFrom, Y as networkLabel, Z as refuseAway, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as setSingleWriterGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as ModeGate, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-DU1wMGI9.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-9RVIbF_l.js";
7
+ import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-D2Z0BdIj.js";
8
+ import { $ as setAwayWallets, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as relayOnlyProblem, H as dropBreezDatabase, I as sourceKey, J as WrongNetworkError, K as ModeChanged, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as requireTurn, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as awayFrom, Y as networkLabel, Z as refuseAway, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as setSingleWriterGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as ModeGate, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-D9Ttlm3M.js";
9
+ import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-BTSlWgEX.js";
10
10
  import { c as isTestMint, d 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-BrlY773j.js";
11
- import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-imkCgogd.js";
12
- import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-D3oeVhv8.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-BMEBas7S.js";
11
+ import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-Bx1Eeg-w.js";
12
+ import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-kQ5kYjVE.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-BD0v3rRG.js";
14
14
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-BT_wRxab.js";
15
15
  import { sha256 } from "@noble/hashes/sha2.js";
16
16
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -198,7 +198,7 @@ function viewNews(before, after) {
198
198
  //#endregion
199
199
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
200
200
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
201
- var loadUsdt = () => import("./usdt-C5Gf9-IC.js");
201
+ var loadUsdt = () => import("./usdt-DxxLdG60.js");
202
202
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
203
203
  var DEFAULT_USDT = {
204
204
  network: "ethereum",
@@ -647,7 +647,7 @@ async function restoreArkDatabase(walletId, snapshot) {
647
647
  //#endregion
648
648
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
649
649
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
650
- var loadArkade = () => import("./arkade-AxrcyS1C.js");
650
+ var loadArkade = () => import("./arkade-Cz0B9bJ0.js");
651
651
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
652
652
  var RETIRE_READ_MS = 1e4;
653
653
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -1299,9 +1299,20 @@ var BarkAdapter = class BarkAdapter {
1299
1299
  board() {
1300
1300
  return this.serial(() => this.wallet.boardAll());
1301
1301
  }
1302
+ /**
1303
+ * Asks the Ark server what changed. One made in the last 3 s is not made again and one under way is shared, as
1304
+ * BdkOnchain.sync: the wallet's refresh and the look at the chat requests it starts right after need one.
1305
+ */
1302
1306
  sync() {
1303
- return this.outside(() => this.wallet.sync());
1307
+ if (Date.now() - this.syncedAt < 3e3) return Promise.resolve();
1308
+ return this.syncing ??= this.outside(() => this.wallet.sync()).then(() => {
1309
+ this.syncedAt = Date.now();
1310
+ }).finally(() => {
1311
+ this.syncing = void 0;
1312
+ });
1304
1313
  }
1314
+ syncedAt = 0;
1315
+ syncing;
1305
1316
  /**
1306
1317
  * How long until the first coin expires. A coin left past its expiry can be swept by the server, so the wallet
1307
1318
  * renews coins near it (maintenance); this is what the page shows so the person knows to open Ghostly in time.
@@ -1396,12 +1407,19 @@ var BarkAdapter = class BarkAdapter {
1396
1407
  * the amount asked, made after the request. Nothing the payer says is trusted.
1397
1408
  */
1398
1409
  async received(address, amount, since, claimed = /* @__PURE__ */ new Set()) {
1399
- for (const m of await this.outside(() => this.wallet.history())) {
1400
- if (m.subsystemKind !== "receive" || m.status !== "successful" || m.effectiveBalanceSats < amount || Date.parse(m.createdAt) < since - 6e4) continue;
1401
- if (!m.receivedOnAddresses.map(addressOf).includes(address)) continue;
1402
- const id = outputTxid(m) ?? `movement-${m.id}`;
1403
- if (!claimed.has(id)) return id;
1404
- }
1410
+ return (await this.receipts())(address, amount, since, claimed);
1411
+ }
1412
+ /** `received` for every open request of one look: the history is read once, not once per request. */
1413
+ async receipts() {
1414
+ const history = await this.outside(() => this.wallet.history());
1415
+ return (address, amount, since, claimed = /* @__PURE__ */ new Set()) => {
1416
+ for (const m of history) {
1417
+ if (m.subsystemKind !== "receive" || m.status !== "successful" || m.effectiveBalanceSats < amount || Date.parse(m.createdAt) < since - 6e4) continue;
1418
+ if (!m.receivedOnAddresses.map(addressOf).includes(address)) continue;
1419
+ const id = outputTxid(m) ?? `movement-${m.id}`;
1420
+ if (!claimed.has(id)) return id;
1421
+ }
1422
+ };
1405
1423
  }
1406
1424
  outcome(m) {
1407
1425
  const txid = outputTxid(m);
@@ -6836,7 +6854,7 @@ var registry;
6836
6854
  var loading$1;
6837
6855
  var listeners = /* @__PURE__ */ new Set();
6838
6856
  function loadIdentityProviders() {
6839
- return loading$1 ??= import("./registry-DOkDhUAu.js").then((m) => {
6857
+ return loading$1 ??= import("./registry-BlSTJlbv.js").then((m) => {
6840
6858
  registry = m;
6841
6859
  for (const listener of listeners) listener();
6842
6860
  return m;
@@ -15171,6 +15189,12 @@ async function openTurnKeeper(profile, network, options = {}) {
15171
15189
  }
15172
15190
  /** A joiner with no session yet puts its packet out again this often: another device on the same code may have replaced it. */
15173
15191
  var ENROLL_REPUT_MS = 5e3;
15192
+ /**
15193
+ * Both devices are on the link and no session opened over WebRTC in this long: the link goes on without it, over the
15194
+ * native transports (Iroh's browser build, HyperDHT through the person's relay), well inside the joiner's
15195
+ * `ENROLL_PROOF_TIMEOUT_MS`. Over WebRTC that works, a session opens in a few seconds.
15196
+ */
15197
+ var ENROLL_RTC_MS = 2e4;
15174
15198
  /** How long, and how often, the joiner reads the turn record for the record that lists it. */
15175
15199
  var ENROLL_FINISH = {
15176
15200
  rounds: 20,
@@ -15282,9 +15306,9 @@ var Enrollment = class {
15282
15306
  ...device ? { device } : {}
15283
15307
  });
15284
15308
  }
15285
- /** The person stops it, on either side. */
15286
- cancel() {
15287
- return this.fail("cancelled", "cancelled");
15309
+ /** The person stops it, on either side (`offline`: by turning the network off). */
15310
+ cancel(reason = "cancelled") {
15311
+ return this.fail(reason, "cancelled");
15288
15312
  }
15289
15313
  /** A step that throws (a crash a test asked for, a store that failed) ends it, except a crash: that leaves everything as it was. */
15290
15314
  guard(work) {
@@ -15883,9 +15907,11 @@ function ghostLinkEnrollChannel(options) {
15883
15907
  signer
15884
15908
  };
15885
15909
  let link = null;
15886
- const rtc = !!options.createPeerConnection;
15910
+ /** WebRTC on this link: this page has it, and it did not fail to connect the two (`withoutRtc`). */
15911
+ let rtc = !!options.createPeerConnection;
15887
15912
  const intervals = options.pollIntervals ?? DHT_POLL_INTERVALS;
15888
15913
  let offered = false;
15914
+ let rtcTimer = null;
15889
15915
  const reput = pinned && rtc ? setInterval(() => {
15890
15916
  if (!opened) link?.republish();
15891
15917
  }, ENROLL_REPUT_MS) : null;
@@ -15896,85 +15922,117 @@ function ghostLinkEnrollChannel(options) {
15896
15922
  opened = true;
15897
15923
  events.onOpen(publicKeyFromZ32(key), hash);
15898
15924
  };
15899
- link = new GhostLink({
15900
- params,
15901
- pairing: {
15902
- credentials,
15903
- pinPeer: async (key) => {
15904
- if (taken && key !== taken) throw new Error("Not the device this code is for");
15905
- taken = key;
15925
+ const make = () => {
15926
+ const made = new GhostLink({
15927
+ params,
15928
+ pairing: {
15929
+ credentials,
15930
+ pinPeer: async (key) => {
15931
+ if (taken && key !== taken) throw new Error("Not the device this code is for");
15932
+ taken = key;
15933
+ },
15934
+ trustOnFirstUse: !pinned
15906
15935
  },
15907
- trustOnFirstUse: !pinned
15908
- },
15909
- deviceCapabilities: [ENROLL_CAPABILITY],
15910
- rtcAvailable: rtc,
15911
- native: { automatic: true },
15912
- packetTransports: true,
15913
- transport: options.transport,
15914
- pollIntervals: {
15915
- ...intervals,
15916
- connected: intervals.active
15917
- },
15918
- autoConnect: true,
15919
- createPeerConnection: () => {
15920
- if (!options.createPeerConnection) throw new ReferenceError("RTCPeerConnection is not defined");
15921
- return options.createPeerConnection();
15922
- },
15923
- localFetch: async () => {
15924
- throw new Error("An enrollment link serves no local web app");
15925
- },
15926
- getServices: () => [{
15927
- id: "chat",
15928
- type: "chat"
15929
- }],
15930
- getHostedHttpService: () => void 0,
15931
- events: {
15932
- onDeviceCapabilities: () => tryOpen(),
15933
- onPairingState: () => tryOpen(),
15934
- onDataLinkState: (state) => {
15935
- if (state === "open") {
15936
- tryOpen();
15937
- return;
15938
- }
15939
- if (opened) {
15940
- opened = false;
15941
- events.onClose();
15942
- }
15936
+ deviceCapabilities: [ENROLL_CAPABILITY],
15937
+ rtcAvailable: rtc,
15938
+ native: { automatic: true },
15939
+ packetTransports: true,
15940
+ transport: options.transport,
15941
+ pollIntervals: {
15942
+ ...intervals,
15943
+ connected: intervals.active
15943
15944
  },
15944
- onDeviceFrame: (frame) => {
15945
- if (opened) events.onFrame(frame);
15945
+ autoConnect: true,
15946
+ createPeerConnection: () => {
15947
+ if (!options.createPeerConnection) throw new ReferenceError("RTCPeerConnection is not defined");
15948
+ return options.createPeerConnection();
15946
15949
  },
15947
- onPeerKeyRefused: () => events.onPeerRefused(),
15948
- onPresence: (presence) => {
15949
- if (!presence.online) return;
15950
- events.onPeerSeen?.();
15951
- if (!pinned || !rtc || offered || opened) return;
15952
- offered = true;
15953
- link?.connect().catch(() => {});
15950
+ localFetch: async () => {
15951
+ throw new Error("An enrollment link serves no local web app");
15954
15952
  },
15955
- onPacketTransports: (transports) => {
15956
- if (!transports.includes("webrtc/1")) startNative();
15953
+ getServices: () => [{
15954
+ id: "chat",
15955
+ type: "chat"
15956
+ }],
15957
+ getHostedHttpService: () => void 0,
15958
+ events: {
15959
+ onDeviceCapabilities: () => {
15960
+ if (link === made) tryOpen();
15961
+ },
15962
+ onPairingState: () => {
15963
+ if (link === made) tryOpen();
15964
+ },
15965
+ onDataLinkState: (state) => {
15966
+ if (link !== made) return;
15967
+ if (state === "open") {
15968
+ tryOpen();
15969
+ return;
15970
+ }
15971
+ if (opened) {
15972
+ opened = false;
15973
+ events.onClose();
15974
+ }
15975
+ },
15976
+ onDeviceFrame: (frame) => {
15977
+ if (opened && link === made) events.onFrame(frame);
15978
+ },
15979
+ onPeerKeyRefused: () => {
15980
+ if (link === made) events.onPeerRefused();
15981
+ },
15982
+ onRtcStalled: () => withoutRtc(made),
15983
+ onDirectEvidence: (evidence) => {
15984
+ if (evidence !== "open" && evidence !== "closed") withoutRtc(made);
15985
+ },
15986
+ onAnswersRefused: () => withoutRtc(made),
15987
+ onPresence: (presence) => {
15988
+ if (!presence.online || link !== made) return;
15989
+ events.onPeerSeen?.();
15990
+ if (rtc && !rtcTimer && !opened) rtcTimer = setTimeout(() => {
15991
+ if (link) withoutRtc(link);
15992
+ }, ENROLL_RTC_MS);
15993
+ if (!pinned || !rtc || offered || opened) return;
15994
+ offered = true;
15995
+ made.connect().catch(() => {});
15996
+ },
15997
+ onPacketTransports: (transports) => {
15998
+ if (link === made && !transports.includes("webrtc/1")) startNative();
15999
+ }
15957
16000
  }
16001
+ });
16002
+ return made;
16003
+ };
16004
+ const withoutRtc = (from) => {
16005
+ if (link !== from || !rtc || opened || started.has(from) || !Object.values(options.nativeTransports ?? {}).some(Boolean)) return;
16006
+ rtc = false;
16007
+ if (rtcTimer) {
16008
+ clearTimeout(rtcTimer);
16009
+ rtcTimer = null;
15958
16010
  }
15959
- });
15960
- let native = false;
16011
+ link = make();
16012
+ link.start();
16013
+ startNative();
16014
+ from.stop(false).catch(() => {});
16015
+ };
15961
16016
  const startNative = () => {
15962
- if (native) return;
15963
- native = true;
16017
+ const target = link;
16018
+ if (!target || started.has(target)) return;
16019
+ started.add(target);
15964
16020
  (async () => {
15965
16021
  for (const [transport, factory] of Object.entries(options.nativeTransports ?? {})) {
15966
- if (!factory || !link || link.availableTransports.includes(transport)) continue;
16022
+ if (!factory || link !== target || target.availableTransports.includes(transport)) continue;
15967
16023
  try {
15968
16024
  const endpoint = await factory(randomSeed());
15969
- if (!link) {
16025
+ if (link !== target) {
15970
16026
  await endpoint.close();
15971
16027
  return;
15972
16028
  }
15973
- link.registerEndpoint(endpoint);
16029
+ target.registerEndpoint(endpoint);
15974
16030
  } catch {}
15975
16031
  }
15976
16032
  })();
15977
16033
  };
16034
+ const started = /* @__PURE__ */ new WeakSet();
16035
+ link = make();
15978
16036
  link.start();
15979
16037
  if (!rtc) startNative();
15980
16038
  return {
@@ -15983,6 +16041,7 @@ function ghostLinkEnrollChannel(options) {
15983
16041
  const running = link;
15984
16042
  link = null;
15985
16043
  if (reput) clearInterval(reput);
16044
+ if (rtcTimer) clearTimeout(rtcTimer);
15986
16045
  await running?.stop().catch(() => {});
15987
16046
  }
15988
16047
  };
@@ -16595,29 +16654,48 @@ function verifierStands(record, latest) {
16595
16654
  return !stated || bytesEqual(stated, turnVerifierMark(record.verifier));
16596
16655
  }
16597
16656
  var sameName = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16657
+ /** One try at a time on this device, whoever asks: tries sent at once would all be checked against the same count. */
16658
+ var tries = Promise.resolve();
16659
+ function oneTry(work) {
16660
+ const run = tries.catch(() => {}).then(work);
16661
+ tries = run;
16662
+ return run;
16663
+ }
16664
+ /**
16665
+ * The limits, then the lock password against the verifier the active device left, when the copy needs it. Run inside
16666
+ * `oneTry`, on the record read there. As a pull is, the try is counted before the password is checked, and taken back
16667
+ * when it is the right one. Throws `TakeoverRefusal`.
16668
+ */
16669
+ async function checkTakeoverPassword(ports, record, password) {
16670
+ const now = ports.now ?? Date.now;
16671
+ const allowed = handoffAttemptAllowed(record.takeoverAttempts, now());
16672
+ if (allowed !== "ok") throw new TakeoverRefusal(allowed, allowed === "locked-out" ? "Too many tries. Try again later." : "Too many tries on this device.", allowed === "locked-out" ? handoffRetryAfter(record.takeoverAttempts, now()) : void 0);
16673
+ if (record.copy !== "frozen" && !record.verifier) return;
16674
+ if (!record.verifier) throw new TakeoverRefusal("no-password", "This device cannot check the profile's password yet.");
16675
+ if (typeof password !== "string" || !password) throw new TakeoverRefusal("password", "Type the profile's password.");
16676
+ await ports.amend({ takeoverAttempts: handoffAttemptFailed(record.takeoverAttempts, now()) });
16677
+ if (!await ports.proves(record.verifier, password).catch(() => false)) throw new TakeoverRefusal("password", "Wrong password.");
16678
+ await ports.amend({ takeoverAttempts: record.takeoverAttempts ?? NO_ATTEMPTS });
16679
+ }
16598
16680
  /**
16599
16681
  * Checks the request and forces the takeover. Resolves to the keeper's outcome: `start` when this device is the active
16600
16682
  * one now (its record says `active`, with the raise to make before the engine starts), anything else when it is not.
16601
16683
  * Throws `TakeoverRefusal` before anything is written.
16602
16684
  */
16603
16685
  async function forceTakeover(ports, request) {
16604
- const now = ports.now ?? Date.now;
16605
- const record = await ports.read();
16606
- if (!record || record.state !== "standby" && record.state !== "superseded") throw new TakeoverRefusal("state", "Only a device on standby takes over.");
16607
- if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile. Use here moves it from the active device.");
16608
- const allowed = handoffAttemptAllowed(record.takeoverAttempts, now());
16609
- if (allowed !== "ok") throw new TakeoverRefusal(allowed, allowed === "locked-out" ? "Too many tries. Try again later." : "Too many tries on this device.", allowed === "locked-out" ? handoffRetryAfter(record.takeoverAttempts, now()) : void 0);
16610
- if (record.copy === "frozen" || record.verifier) {
16611
- if (!record.verifier) throw new TakeoverRefusal("no-password", "This device cannot check the profile's password yet.");
16612
- if (typeof request.password !== "string" || !request.password) throw new TakeoverRefusal("password", "Type the profile's password.");
16613
- if (!await ports.proves(record.verifier, request.password).catch(() => false)) {
16614
- await ports.amend({ takeoverAttempts: handoffAttemptFailed(record.takeoverAttempts, now()) });
16615
- throw new TakeoverRefusal("password", "Wrong password.");
16616
- }
16617
- }
16618
- const target = takeoverTarget(record);
16619
- if (target && (typeof request.name !== "string" || !sameName(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16620
- if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16686
+ const { record, target } = await oneTry(async () => {
16687
+ const record = await ports.read();
16688
+ if (!record || record.state !== "standby" && record.state !== "superseded") throw new TakeoverRefusal("state", "Only a device on standby takes over.");
16689
+ if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile. Use here moves it from the active device.");
16690
+ await checkTakeoverPassword(ports, record, request.password);
16691
+ const target = takeoverTarget(record);
16692
+ if (target && (typeof request.name !== "string" || !sameName(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16693
+ if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16694
+ return {
16695
+ record,
16696
+ target
16697
+ };
16698
+ });
16621
16699
  const keeper = await ports.keeper();
16622
16700
  if (!keeper) throw new TakeoverRefusal("offline", "Go online to take over.");
16623
16701
  const outcome = await keeper.raise({ before: (latest) => {
@@ -16637,27 +16715,22 @@ function canStartOwnSet(record) {
16637
16715
  * settles. Throws `TakeoverRefusal` before anything is written.
16638
16716
  */
16639
16717
  async function startOwnSet(ports, request) {
16640
- const now = ports.now ?? Date.now;
16641
- const record = await ports.read();
16642
- if (!record || record.state !== "moving") throw new TakeoverRefusal("state", "Only a device that waits for its devices' new secret starts a set of its own.");
16643
- if (record.ownSet) return resumeOwnSet(ports);
16644
- if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile.");
16645
- if (!canStartOwnSet(record)) throw new TakeoverRefusal("state", "This device cannot start a device set of its own.");
16646
- const allowed = handoffAttemptAllowed(record.takeoverAttempts, now());
16647
- if (allowed !== "ok") throw new TakeoverRefusal(allowed, allowed === "locked-out" ? "Too many tries. Try again later." : "Too many tries on this device.", allowed === "locked-out" ? handoffRetryAfter(record.takeoverAttempts, now()) : void 0);
16648
- if (record.copy === "frozen" || record.verifier) {
16649
- if (!record.verifier) throw new TakeoverRefusal("no-password", "This device cannot check the profile's password yet.");
16650
- if (typeof request.password !== "string" || !request.password) throw new TakeoverRefusal("password", "Type the profile's password.");
16651
- if (!await ports.proves(record.verifier, request.password).catch(() => false)) {
16652
- await ports.amend({ takeoverAttempts: handoffAttemptFailed(record.takeoverAttempts, now()) });
16653
- throw new TakeoverRefusal("password", "Wrong password.");
16654
- }
16655
- }
16656
- const target = takeoverTarget(record);
16657
- const same = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16658
- if (target && (typeof request.name !== "string" || !same(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16718
+ const record = await oneTry(async () => {
16719
+ const record = await ports.read();
16720
+ if (!record || record.state !== "moving") throw new TakeoverRefusal("state", "Only a device that waits for its devices' new secret starts a set of its own.");
16721
+ if (record.ownSet) return null;
16722
+ if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile.");
16723
+ if (!canStartOwnSet(record)) throw new TakeoverRefusal("state", "This device cannot start a device set of its own.");
16724
+ await checkTakeoverPassword(ports, record, request.password);
16725
+ const target = takeoverTarget(record);
16726
+ const same = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16727
+ if (target && (typeof request.name !== "string" || !same(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16728
+ if (!ports.network) throw new TakeoverRefusal("offline", "Go online to take over.");
16729
+ if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16730
+ return record;
16731
+ });
16732
+ if (!record) return resumeOwnSet(ports);
16659
16733
  if (!ports.network) throw new TakeoverRefusal("offline", "Go online to take over.");
16660
- if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16661
16734
  if (!record.d || record.ownSlot === void 0 || !record.deviceSet[record.ownSlot]) throw new TakeoverRefusal("state", "This device has no device set.");
16662
16735
  const keys = turnKeys(fromBase64Url(record.d));
16663
16736
  const standing = classifyTurnRead({
@@ -17126,6 +17199,8 @@ function handoffNotices(was, handoff, session) {
17126
17199
  */
17127
17200
  var NATIVE_RETRY_MS$1 = 1e4;
17128
17201
  var NATIVE_RETRY_MAX_MS = 12e4;
17202
+ /** The other device is there and no session opened over WebRTC in this long: the link goes on without it (`withoutRtc`). */
17203
+ var DEVICE_RTC_MS = 2e4;
17129
17204
  /** How often a standby reads the turn while its screen shows (WISP 06 § When a device checks), and the jitter on it. */
17130
17205
  var STANDBY_TURN_EVERY_MS = 6e5;
17131
17206
  var STANDBY_TURN_JITTER_MS = 6e4;
@@ -17321,9 +17396,9 @@ var DeviceLinks = class {
17321
17396
  }
17322
17397
  return wanted;
17323
17398
  }
17324
- open(want) {
17399
+ open(want, rtcOff = false) {
17325
17400
  const signer = this.key;
17326
- const rtc = !!this.createPeerConnection;
17401
+ const rtc = !!this.createPeerConnection && !rtcOff;
17327
17402
  const running = {
17328
17403
  id: want.id,
17329
17404
  d: want.id.slice(0, want.id.indexOf("|")),
@@ -17335,7 +17410,9 @@ var DeviceLinks = class {
17335
17410
  agreed: false,
17336
17411
  native: false,
17337
17412
  starting: /* @__PURE__ */ new Set(),
17413
+ moved: /* @__PURE__ */ new Set(),
17338
17414
  nativeMisses: 0,
17415
+ rtcOff,
17339
17416
  waiting: /* @__PURE__ */ new Map()
17340
17417
  };
17341
17418
  running.link = new GhostLink({
@@ -17377,6 +17454,10 @@ var DeviceLinks = class {
17377
17454
  this.changed();
17378
17455
  },
17379
17456
  onDataLinkState: (state) => {
17457
+ if (state === "open" && running.rtcWait) {
17458
+ clearTimeout(running.rtcWait);
17459
+ running.rtcWait = void 0;
17460
+ }
17380
17461
  if (state !== "open") {
17381
17462
  running.agreed = false;
17382
17463
  this.failPings(running, "The device link closed");
@@ -17384,10 +17465,23 @@ var DeviceLinks = class {
17384
17465
  running.handoff = false;
17385
17466
  if (!running.earlier) this.handoffLink(running.key, false);
17386
17467
  }
17468
+ if (running.moved.size) this.moveNative(running);
17387
17469
  }
17388
17470
  this.changed();
17389
17471
  },
17390
17472
  onDeviceFrame: (frame) => this.receive(running, frame),
17473
+ onRtcStalled: () => this.withoutRtc(running),
17474
+ onDirectEvidence: (evidence) => {
17475
+ if (evidence !== "open" && evidence !== "closed") this.withoutRtc(running);
17476
+ },
17477
+ onAnswersRefused: () => this.withoutRtc(running),
17478
+ onPresence: (presence) => {
17479
+ if (!presence.online || running.rtcOff || running.rtcWait || running.link.isDataLinkOpen) return;
17480
+ running.rtcWait = setTimeout(() => {
17481
+ running.rtcWait = void 0;
17482
+ if (!running.link.isDataLinkOpen) this.withoutRtc(running);
17483
+ }, DEVICE_RTC_MS);
17484
+ },
17391
17485
  onPacketTransports: (transports) => {
17392
17486
  if (!running.native && !transports.includes("webrtc/1")) this.startNative(running);
17393
17487
  },
@@ -17443,14 +17537,37 @@ var DeviceLinks = class {
17443
17537
  }
17444
17538
  /**
17445
17539
  * The native transports this app runs changed (the person set a HyperDHT relay, or other Iroh relays): every link
17446
- * that runs native endpoints starts the ones it lacks now.
17540
+ * that runs native endpoints starts the ones it lacks now. Its endpoints of the `moved` transports, on the relay the
17541
+ * person changed or removed, go first, as a chat's do: each once no session runs on it.
17447
17542
  */
17448
- nativeChanged() {
17543
+ nativeChanged(moved = []) {
17449
17544
  for (const running of this.running.values()) {
17450
17545
  if (!running.native) continue;
17451
17546
  running.nativeMisses = 0;
17452
- this.startNative(running);
17547
+ for (const transport of moved) if (running.link.availableTransports.includes(transport)) running.moved.add(transport);
17548
+ this.moveNative(running);
17549
+ }
17550
+ }
17551
+ /**
17552
+ * Lets go of the link's endpoints on an old relay that no session runs on, and starts the native transports it lacks
17553
+ * then: the new relay's, or none where the relay was removed. One carrying the session goes when the session ends.
17554
+ */
17555
+ async moveNative(running) {
17556
+ for (const transport of [...running.moved]) {
17557
+ if (!running.link.availableTransports.includes(transport)) {
17558
+ running.moved.delete(transport);
17559
+ continue;
17560
+ }
17561
+ if (!running.link.canReleaseEndpoint(transport)) continue;
17562
+ running.moved.delete(transport);
17563
+ running.starting.add(transport);
17564
+ try {
17565
+ await running.link.releaseEndpoint(transport);
17566
+ } finally {
17567
+ running.starting.delete(transport);
17568
+ }
17453
17569
  }
17570
+ if (!this.stopped && this.running.get(running.id) === running) this.startNative(running);
17454
17571
  }
17455
17572
  async receive(running, frame) {
17456
17573
  const echo = deviceEchoFrame(frame);
@@ -17732,14 +17849,47 @@ var DeviceLinks = class {
17732
17849
  waiter.reject(new Error(why));
17733
17850
  }
17734
17851
  }
17735
- async close(running) {
17852
+ /** `announce`: the link says goodbye (false where another link on the same keys takes its place at once). */
17853
+ async close(running, announce = true) {
17736
17854
  if (running.nativeRetry) {
17737
17855
  clearTimeout(running.nativeRetry);
17738
17856
  running.nativeRetry = void 0;
17739
17857
  }
17858
+ if (running.rtcWait) {
17859
+ clearTimeout(running.rtcWait);
17860
+ running.rtcWait = void 0;
17861
+ }
17740
17862
  this.failPings(running, "The device link closed");
17741
17863
  running.agreed = false;
17742
- await running.link.stop().catch(() => {});
17864
+ await running.link.stop(announce).catch(() => {});
17865
+ }
17866
+ /**
17867
+ * WebRTC on both devices that connects nothing (two browsers whose host candidates the other does not resolve, a
17868
+ * router that does not hairpin, no TURN): neither packet says it has no WebRTC, so neither device starts a native
17869
+ * endpoint, and the link never went live. It starts again as on an app with no WebRTC, for this run, as a group's edge
17870
+ * does (node.ts `edgeWithoutRtc`): its native endpoints run and its packet lists no `webrtc/1`, the other device starts
17871
+ * its own for it as for a Linux Desktop, and the two meet over Iroh's relay. Only with no session open, and only
17872
+ * where this app has a native transport to go on with.
17873
+ */
17874
+ withoutRtc(running) {
17875
+ if (this.stopped || running.rtcOff || running.native || !this.createPeerConnection || running.link.isDataLinkOpen) return;
17876
+ if (!Object.values(this.nativeFactories()).some(Boolean)) return;
17877
+ const run = this.queue.catch(() => {}).then(async () => {
17878
+ if (this.stopped || this.running.get(running.id) !== running || running.link.isDataLinkOpen) return;
17879
+ this.running.delete(running.id);
17880
+ await this.close(running, false);
17881
+ if (this.stopped) return;
17882
+ this.open({
17883
+ id: running.id,
17884
+ d: fromBase64Url(running.d),
17885
+ key: running.key,
17886
+ name: running.name,
17887
+ slot: running.slot,
17888
+ earlier: running.earlier
17889
+ }, true);
17890
+ this.changed();
17891
+ });
17892
+ this.queue = run;
17743
17893
  }
17744
17894
  find(key) {
17745
17895
  const all = [...this.running.values()].filter((r) => r.key === key);
@@ -18665,8 +18815,15 @@ var HandoffGiver = class {
18665
18815
  });
18666
18816
  const parts = [...send];
18667
18817
  if (pass === 2) {
18668
- const bundle = await this.ports.source.bundle();
18669
- const digest = toBase64Url(sha256(bundle));
18818
+ this.bundleMade ??= this.ports.source.bundle().then((bytes) => ({
18819
+ bytes,
18820
+ digest: toBase64Url(sha256(bytes))
18821
+ }));
18822
+ const made = this.bundleMade;
18823
+ const { bytes: bundle, digest } = await made.catch((error) => {
18824
+ if (this.bundleMade === made) this.bundleMade = null;
18825
+ throw error;
18826
+ });
18670
18827
  parts.push([
18671
18828
  "db/peer",
18672
18829
  bundle.length,
@@ -18714,6 +18871,7 @@ var HandoffGiver = class {
18714
18871
  else this.arm(HANDOFF_TIMINGS.verifiedMs, () => this.backToActive());
18715
18872
  }
18716
18873
  bundlePart = null;
18874
+ bundleMade = null;
18717
18875
  paused = false;
18718
18876
  stallTimer;
18719
18877
  laterParts = [];
@@ -18798,6 +18956,7 @@ var HandoffGiver = class {
18798
18956
  }
18799
18957
  });
18800
18958
  if (this.timer) clearTimeout(this.timer);
18959
+ this.bundleMade = null;
18801
18960
  this.phase = "released";
18802
18961
  this.out({
18803
18962
  ...handoffReleaseFrame(release),
@@ -18810,6 +18969,7 @@ var HandoffGiver = class {
18810
18969
  async backToActive() {
18811
18970
  if (this.phase === "released" || this.phase === "failed") return;
18812
18971
  this.sender.stop();
18972
+ this.bundleMade = null;
18813
18973
  clearInterval(this.stuckTimer);
18814
18974
  if (this.timer) {
18815
18975
  clearTimeout(this.timer);
@@ -18836,6 +18996,7 @@ var HandoffGiver = class {
18836
18996
  this.planned = null;
18837
18997
  this.pake = null;
18838
18998
  this.secret = null;
18999
+ this.bundleMade = null;
18839
19000
  this.offerHellos.clear();
18840
19001
  this.sender = new PartSender(this.now);
18841
19002
  }
@@ -18851,6 +19012,7 @@ var HandoffGiver = class {
18851
19012
  this.have = null;
18852
19013
  this.planned = null;
18853
19014
  this.secret = null;
19015
+ this.bundleMade = null;
18854
19016
  this.changed();
18855
19017
  }
18856
19018
  fail(failure, why) {
@@ -19827,8 +19989,12 @@ var FileDesk = class {
19827
19989
  chat = made;
19828
19990
  return chat;
19829
19991
  }
19830
- /** At start: the chat's unfinished and finished files/3 transfers, as they were kept. */
19831
- restore(linkId, files) {
19992
+ /**
19993
+ * At start: the chat's unfinished and finished files/3 transfers, as they were kept. One that ended before this run is
19994
+ * reported ended already (a session opening walks them all), unless it finished and `unsettled` names it: a sent file
19995
+ * whose message never got its receipt, which its next session gives.
19996
+ */
19997
+ restore(linkId, files, unsettled = /* @__PURE__ */ new Set()) {
19832
19998
  const records = [];
19833
19999
  const chat = this.chat(linkId);
19834
20000
  for (const file of files) {
@@ -19844,6 +20010,7 @@ var FileDesk = class {
19844
20010
  records.push(file.wire3);
19845
20011
  if (file.wire3.direction === "in") chat.local.set(file.wire3.id, file.id);
19846
20012
  if (!transferEnded(file.wire3)) this.restored.add(file.id);
20013
+ else if (file.wire3.state !== "done" || !unsettled.has(file.id)) this.ended.add(file.id);
19847
20014
  if (file.wire3.state === "done") continue;
19848
20015
  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())));
19849
20016
  }
@@ -21075,7 +21242,11 @@ var Outbox = class {
21075
21242
  ...manual ? { resendUntil: void 0 } : {}
21076
21243
  };
21077
21244
  if (this.stopped) {
21078
- await this.queue(message, "Connection closed. Delivery is unconfirmed.");
21245
+ await this.queue({
21246
+ ...message,
21247
+ delivery: "sending",
21248
+ deliveryError: void 0
21249
+ }, "Connection closed. Delivery is unconfirmed.");
21079
21250
  return;
21080
21251
  }
21081
21252
  this.track(id, typeof this.timeoutMs === "number" ? this.timeoutMs : this.timeoutMs(message));
@@ -21275,7 +21446,7 @@ var Outbox = class {
21275
21446
  const sent = this.attempts.get(message.id) ?? 0;
21276
21447
  if (until <= now) return this.fail(message.id, `${reason} Not confirmed within ${days(this.policy.windowMs)}.`);
21277
21448
  if (sent >= this.policy.maxAttempts) return this.fail(message.id, `${reason} Sent ${sent} times without a receipt.`);
21278
- await this.store.update(message.id, "queued", reason, { resendUntil: until });
21449
+ if (message.delivery !== "queued" || message.deliveryError !== reason || message.resendUntil !== until) await this.store.update(message.id, "queued", reason, { resendUntil: until });
21279
21450
  if (!this.stopped) this.schedule(message.id);
21280
21451
  }
21281
21452
  /** The DHT path retried within its own budget until expiry: only the live link may take it from here. */
@@ -22640,7 +22811,7 @@ var Reactions = class {
22640
22811
  take(chat, by, reaction) {
22641
22812
  return this.run(async () => {
22642
22813
  const target = await this.find(chat, reaction.id, true);
22643
- if (!target) return this.wait(chat, by, reaction);
22814
+ if (!target) return await this.wait(chat, by, reaction);
22644
22815
  if (!reactionIsNewer(target.reactions?.[by], reaction.n)) return "stale";
22645
22816
  await this.write(chat, target, by, reaction);
22646
22817
  return "applied";
@@ -22726,8 +22897,10 @@ var Reactions = class {
22726
22897
  return this.run(async () => {
22727
22898
  const now = this.now(), all = (this.waiting.get(message.linkId) ?? []).filter((w) => w.until > now);
22728
22899
  const mine = all.filter((w) => w.reaction.id === id).sort((a, b) => a.reaction.n - b.reaction.n);
22729
- this.waiting.set(message.linkId, all.filter((w) => w.reaction.id !== id));
22900
+ const rest = all.filter((w) => w.reaction.id !== id);
22901
+ this.waiting.set(message.linkId, rest);
22730
22902
  for (const { by, reaction } of mine) await this.write(message.linkId, message, by, reaction);
22903
+ await this.keep(message.linkId, rest).catch(() => {});
22731
22904
  });
22732
22905
  }
22733
22906
  /** The row I react to: by its id here, as the pages name it, read alone; else by the id both sides know it by. */
@@ -22793,10 +22966,36 @@ var Reactions = class {
22793
22966
  }] : [];
22794
22967
  });
22795
22968
  if (!found.length) return;
22796
- this.waiting.set(chat, list.filter((w) => !found.some((f) => f.by === w.by && f.reaction === w.reaction)));
22969
+ const rest = list.filter((w) => !found.some((f) => f.by === w.by && f.reaction === w.reaction));
22970
+ this.waiting.set(chat, rest);
22971
+ for (const { target, by, reaction } of found.sort((a, b) => a.reaction.n - b.reaction.n)) await this.write(chat, target, by, reaction);
22972
+ await this.keep(chat, rest).catch(() => {});
22973
+ });
22974
+ }
22975
+ /**
22976
+ * At start, what waited in a 1:1 chat when the engine stopped (`ReactionsHost.keep`): it waits again until its time,
22977
+ * and one whose message landed before the stop wrote it is written now. `messages`: the chat's history.
22978
+ */
22979
+ restore(chat, waiting, messages) {
22980
+ return this.run(async () => {
22981
+ const now = this.now(), list = waiting.filter((w) => w.until > now);
22982
+ const found = list.flatMap((w) => {
22983
+ const target = reactionTarget(messages, w.reaction.id, false);
22984
+ return target ? [{
22985
+ ...w,
22986
+ target
22987
+ }] : [];
22988
+ });
22989
+ const rest = list.filter((w) => !found.some((f) => f.by === w.by && f.reaction === w.reaction));
22990
+ this.waiting.set(chat, [...this.waiting.get(chat) ?? [], ...rest]);
22797
22991
  for (const { target, by, reaction } of found.sort((a, b) => a.reaction.n - b.reaction.n)) await this.write(chat, target, by, reaction);
22992
+ if (rest.length < waiting.length) await this.keep(chat, this.waiting.get(chat)).catch(() => {});
22798
22993
  });
22799
22994
  }
22995
+ /** What waits in a 1:1 chat, on disk (`ReactionsHost.keep`); a group's stays in memory. */
22996
+ keep(chat, waiting) {
22997
+ return isGroup$1(chat) || !this.host.keep ? Promise.resolve() : this.host.keep(chat, [...waiting]);
22998
+ }
22800
22999
  /** A chat is gone: nothing waits for it any more, and my highest number in it is read again if it comes back. */
22801
23000
  forget(chat) {
22802
23001
  this.dropHeld(chat);
@@ -22805,7 +23004,8 @@ var Reactions = class {
22805
23004
  clearTimeout(this.lookups.get(chat)?.timer);
22806
23005
  this.lookups.delete(chat);
22807
23006
  }
22808
- wait(chat, by, reaction) {
23007
+ /** A reaction to a message not here yet waits for it: in a 1:1 chat, on disk before it is confirmed (`keep`). */
23008
+ async wait(chat, by, reaction) {
22809
23009
  const now = this.now();
22810
23010
  const list = (this.waiting.get(chat) ?? []).filter((w) => w.until > now);
22811
23011
  const same = list.find((w) => w.by === by && w.reaction.id === reaction.id);
@@ -22813,11 +23013,18 @@ var Reactions = class {
22813
23013
  const kept = list.filter((w) => w !== same);
22814
23014
  this.waiting.set(chat, kept);
22815
23015
  if (kept.filter((w) => w.by === by).length >= REACTION_LIMITS.buffer) return "dropped";
22816
- kept.push({
23016
+ const entry = {
22817
23017
  by,
22818
23018
  reaction,
22819
23019
  until: now + REACTION_LIMITS.bufferMs
22820
- });
23020
+ };
23021
+ kept.push(entry);
23022
+ try {
23023
+ await this.keep(chat, kept);
23024
+ } catch {
23025
+ kept.splice(kept.indexOf(entry), 1);
23026
+ return "dropped";
23027
+ }
22821
23028
  return "waiting";
22822
23029
  }
22823
23030
  async write(chat, target, by, reaction) {
@@ -26416,6 +26623,21 @@ var ENTRY_TIMEOUT_MS = 18e4;
26416
26623
  /** A joiner refused (its app cannot follow the group) is not answered again for this long. */
26417
26624
  var REFUSED_FOR_MS = 6e5;
26418
26625
  /**
26626
+ * The removed ids with this one noted. Full, the oldest of the author who has the most goes (the one just noted's own on
26627
+ * a tie): a member's removals of messages that are not here, as many as they like, push out only their own.
26628
+ */
26629
+ function withRemovedId(ids, messageId) {
26630
+ const next = [...ids, messageId];
26631
+ if (next.length <= 500) return next;
26632
+ const authorOf = (id) => id.slice(0, Math.max(0, id.indexOf(":")));
26633
+ const counts = /* @__PURE__ */ new Map();
26634
+ for (const id of next) counts.set(authorOf(id), (counts.get(authorOf(id)) ?? 0) + 1);
26635
+ let most = authorOf(messageId);
26636
+ for (const [author, count] of counts) if (count > counts.get(most)) most = author;
26637
+ next.splice(next.findIndex((id) => authorOf(id) === most), 1);
26638
+ return next;
26639
+ }
26640
+ /**
26419
26641
  * A joiner whose entry session timed out (the relays failing, its app closed a moment) is answered again after this,
26420
26642
  * doubling with each timeout in a row up to `REFUSED_FOR_MS`: a slow network is no refusal.
26421
26643
  */
@@ -26639,6 +26861,9 @@ var Groups = class {
26639
26861
  typings;
26640
26862
  /** A member's pins taken per window in a private group (group and member key). */
26641
26863
  pinPaces = /* @__PURE__ */ new Map();
26864
+ /** Records whose removals changed and wait to be written (`saveSoon`), by group. */
26865
+ unsaved = /* @__PURE__ */ new Map();
26866
+ saveTimer;
26642
26867
  /** Edge signaling through members (WISP 902 · Group Mesh § Signaling through members). */
26643
26868
  signals;
26644
26869
  /** Files and voice messages in every group, private or community (WISP 503 · Group Files). */
@@ -26692,9 +26917,32 @@ var Groups = class {
26692
26917
  this.communities.files = this.files;
26693
26918
  }
26694
26919
  }
26695
- /** Writes what the private groups' sessions still have to save (`GROUP_LIMITS.saveWithinMs`): the app is stopping. */
26920
+ /**
26921
+ * Writes what the private groups' sessions still have to save (`GROUP_LIMITS.saveWithinMs`), and the removals taken
26922
+ * since the last save (`saveSoon`): the app is stopping.
26923
+ */
26696
26924
  async flush() {
26697
- await Promise.allSettled([...this.sessions.values()].map((session) => session.flush()));
26925
+ await Promise.allSettled([...[...this.sessions.values()].map((session) => session.flush()), this.saveUnsaved()]);
26926
+ }
26927
+ /**
26928
+ * A group's record written within `GROUP_LIMITS.saveWithinMs`, for what may change many times a second (a catch-up
26929
+ * hands back up to 256 removals): it holds the group's whole state (a community's chain and store), not worth writing each time.
26930
+ */
26931
+ saveSoon(group) {
26932
+ this.unsaved.set(group.id, group);
26933
+ this.saveTimer ??= setTimeout(() => {
26934
+ this.saveTimer = void 0;
26935
+ this.saveUnsaved().catch(() => {});
26936
+ }, GROUP_LIMITS.saveWithinMs);
26937
+ }
26938
+ async saveUnsaved() {
26939
+ if (this.saveTimer) {
26940
+ clearTimeout(this.saveTimer);
26941
+ this.saveTimer = void 0;
26942
+ }
26943
+ const due = [...this.unsaved.values()];
26944
+ this.unsaved.clear();
26945
+ for (const group of due) if (this.record(group.id) === group) await this.store.putGroup(group);
26698
26946
  }
26699
26947
  /** `asItIs`: a copy that must stay as it was stored (limited mode, WISP 06), so nothing left over is cleared from it. */
26700
26948
  async load(asItIs = false) {
@@ -27074,7 +27322,7 @@ var Groups = class {
27074
27322
  }
27075
27323
  if (this.stored.get(group.id) !== group) return;
27076
27324
  delete group.declined;
27077
- if (group.state) return this.store.putGroup(group);
27325
+ if (group.state || group.invitation) return this.store.putGroup(group);
27078
27326
  this.stored.delete(group.id);
27079
27327
  await this.store.deleteGroup(group.id);
27080
27328
  }
@@ -27230,7 +27478,7 @@ var Groups = class {
27230
27478
  at: Date.now(),
27231
27479
  admin,
27232
27480
  ...hubs.length ? { hubs } : {},
27233
- ...bye ? { bye } : {}
27481
+ bye: bye ?? session.byeFrame()
27234
27482
  };
27235
27483
  delete group.entry;
27236
27484
  this.takeBack(groupId, group);
@@ -27272,6 +27520,16 @@ var Groups = class {
27272
27520
  this.host.emit();
27273
27521
  return next;
27274
27522
  }
27523
+ /**
27524
+ * The signed leave of my old key the admin has still to hear (`StoredGroup.owedBye`): none once the old key is out of
27525
+ * the roster, or a week after the leave, and then it is dropped from the row.
27526
+ */
27527
+ owedBye(group, session, now) {
27528
+ const bye = group.owedBye;
27529
+ if (!bye || session.status === "active" && rosterHas(session.roster, bye.k) && now - bye.ts <= LEFT_KEPT_MS) return bye;
27530
+ delete group.owedBye;
27531
+ this.store.putGroup(group).catch(() => {});
27532
+ }
27275
27533
  /** The admin heard me: the tombstone of a group I left can go. */
27276
27534
  async leaveConfirmed(groupId) {
27277
27535
  if (!this.stored.get(groupId)?.left) return;
@@ -27358,23 +27616,25 @@ var Groups = class {
27358
27616
  async setRemovals(groupId, removals) {
27359
27617
  const group = this.record(groupId);
27360
27618
  if (!group) return;
27619
+ const added = removals.some((r) => !group.removals?.some((kept) => kept.id === r.id));
27361
27620
  group.removals = removals;
27362
- await this.store.putGroup(group);
27621
+ if (added) await this.store.putGroup(group);
27622
+ else this.saveSoon(group);
27363
27623
  }
27364
27624
  /** A member's message its author deleted for everyone (WISP 400 § Delete for everyone): a copy that comes again is not kept. */
27365
27625
  isRemoved(groupId, messageId) {
27366
27626
  return !!this.record(groupId)?.removedIds?.includes(messageId);
27367
27627
  }
27368
27628
  /**
27369
- * Its author deleted a message for everyone: noted so (the newest `MAX_REMOVED_IDS`, also when the message is not here
27370
- * yet, so it is taken as gone when it comes), and its file goes from this device.
27629
+ * Its author deleted a message for everyone: noted so (`MAX_REMOVED_IDS` at most, each author's newest: `withRemovedId`;
27630
+ * also when the message is not here yet, so it is taken as gone when it comes), and its file goes from this device.
27371
27631
  */
27372
27632
  async removed(groupId, messageId) {
27373
27633
  const group = this.record(groupId);
27374
27634
  if (!group) return;
27375
27635
  if (!group.removedIds?.includes(messageId)) {
27376
- group.removedIds = [...group.removedIds ?? [], messageId].slice(-500);
27377
- await this.store.putGroup(group);
27636
+ group.removedIds = withRemovedId(group.removedIds ?? [], messageId);
27637
+ this.saveSoon(group);
27378
27638
  }
27379
27639
  this.communities.session(groupId)?.forget(messageId);
27380
27640
  await this.files?.forget(groupId, messageId);
@@ -27594,6 +27854,7 @@ var Groups = class {
27594
27854
  if (existing?.invitation?.seedB64 && !existing.invitation.entry) throw new Error("You are already joining this group");
27595
27855
  if (existing?.invitation && !existing.invitation.entry) throw new Error("You have an invitation to this group. Answer it first.");
27596
27856
  if (existing?.state && !existing.left) throw new Error("You are out of this group and its history is still here. Delete it from this device to join with a link.");
27857
+ const owedBye = existing?.left?.bye ?? existing?.owedBye, declined = existing?.declined;
27597
27858
  if (existing) await this.forget(link.g);
27598
27859
  const seedB64 = dialedKey(link);
27599
27860
  const linkId = await this.host.openEntry(link, "guest", seedB64, link.host);
@@ -27609,7 +27870,9 @@ var Groups = class {
27609
27870
  seedB64,
27610
27871
  pieces: [],
27611
27872
  entry: link.host
27612
- }
27873
+ },
27874
+ ...owedBye ? { owedBye } : {},
27875
+ ...declined ? { declined } : {}
27613
27876
  };
27614
27877
  this.stored.set(link.g, group);
27615
27878
  await this.store.putGroup(group);
@@ -27633,7 +27896,7 @@ var Groups = class {
27633
27896
  }
27634
27897
  if (group.declined) {
27635
27898
  await this.declineOwed(group, now);
27636
- if (!group.state) continue;
27899
+ if (!group.state && !group.invitation) continue;
27637
27900
  }
27638
27901
  if (group.invitation?.takenBack && !group.state) {
27639
27902
  if (now - group.invitation.takenBack > LEFT_KEPT_MS) await this.forget(group.id, false);
@@ -27659,6 +27922,7 @@ var Groups = class {
27659
27922
  continue;
27660
27923
  }
27661
27924
  const session = this.sessions.get(group.id);
27925
+ if (group.owedBye && session) this.owedBye(group, session, now);
27662
27926
  if (group.invited) await this.ageInvited(group, now);
27663
27927
  if (!group.entry || !session) continue;
27664
27928
  if (!session.isAdmin) {
@@ -28186,7 +28450,9 @@ var Groups = class {
28186
28450
  id: g,
28187
28451
  createdAt: group.createdAt,
28188
28452
  state: joined.state,
28189
- contacts: viaLink ? {} : { [group.invitation.admin]: linkId }
28453
+ contacts: viaLink ? {} : { [group.invitation.admin]: linkId },
28454
+ ...group.owedBye ? { owedBye: group.owedBye } : {},
28455
+ ...group.declined ? { declined: group.declined } : {}
28190
28456
  };
28191
28457
  this.stored.set(g, member);
28192
28458
  this.acceptSaid.delete(g);
@@ -28392,9 +28658,12 @@ var Groups = class {
28392
28658
  } catch {
28393
28659
  return;
28394
28660
  }
28395
- if (peerKey === session.admin) try {
28396
- for (const bye of session.byesHeld()) this.host.sendOnLink(linkId, bye);
28397
- } catch {}
28661
+ if (peerKey === session.admin) {
28662
+ const owed = this.owedBye(group, session, this.now());
28663
+ try {
28664
+ for (const bye of [...session.byesHeld(), ...owed ? [owed] : []]) this.host.sendOnLink(linkId, bye);
28665
+ } catch {}
28666
+ }
28398
28667
  const kept = this.lingering.get(groupId);
28399
28668
  if (kept?.admin === peerKey) {
28400
28669
  if (this.signals.keptEntry(groupId) === kept.linkId) setTimeout(() => {
@@ -29876,9 +30145,17 @@ var GroupEdits = class {
29876
30145
  });
29877
30146
  }
29878
30147
  }
29879
- /** A group is forgotten, or the app stops: what was known of its members' edges goes with it. */
29880
- dropResends(groupId) {
29881
- const of = (key) => groupId === void 0 || key.startsWith(`${groupId}\n`);
30148
+ /**
30149
+ * A group's roster changed: what was known of the edges of members no longer in it goes (their last edge with it,
30150
+ * which `resentOn` would keep in memory for as long as the app runs). Out of the group: all of it.
30151
+ */
30152
+ membersChanged(groupId) {
30153
+ const members = this.host.membership(groupId)?.members;
30154
+ this.dropResends(groupId, members && ((key) => !members.has(key.slice(groupId.length + 1))));
30155
+ }
30156
+ /** A group is forgotten, or the app stops: what was known of its members' edges goes with it. `gone`: those keys alone. */
30157
+ dropResends(groupId, gone) {
30158
+ const of = (key) => groupId === void 0 || key.startsWith(`${groupId}\n`) && (!gone || gone(key));
29882
30159
  for (const [key, timer] of this.resendTimers) if (of(key)) {
29883
30160
  clearTimeout(timer);
29884
30161
  this.resendTimers.delete(key);
@@ -32415,10 +32692,11 @@ var CashuWallet = class CashuWallet {
32415
32692
  static STOP_WAIT_MS = 3e4;
32416
32693
  /**
32417
32694
  * The Cashu wallet of one network: its mints, their balance, and the network's newest movements (every network's when
32418
- * none is named) with the fees they paid. Only those movements are read, however long the history is.
32695
+ * none is named) with the fees they paid. Only those movements are read, however long the history is. `read` is the
32696
+ * proofs and swaps as `readStored` read them, shared by the views of several networks.
32419
32697
  */
32420
- async view(network) {
32421
- const proofs = await this.allProofs();
32698
+ async view(network, read) {
32699
+ const { proofs, swaps: allSwaps } = read ?? await this.readStored();
32422
32700
  const mints = this.getMints(network).map((url) => ({
32423
32701
  url,
32424
32702
  name: this.names.get(url) ?? new URL(url).hostname,
@@ -32427,7 +32705,7 @@ var CashuWallet = class CashuWallet {
32427
32705
  }));
32428
32706
  const history = await newestWalletTx((mint) => !network || mintNetwork(mint) === network, HISTORY_SHOWN);
32429
32707
  const here = new Set(mints.map((m) => m.url));
32430
- const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => here.has(s.mint) && !s.released && !s.finished);
32708
+ const swaps = allSwaps.filter((s) => here.has(s.mint) && !s.released && !s.finished);
32431
32709
  const about = (s) => s.kind === "send" ? swapOf(s).inputs.reduce((sum, p) => sum + Number(p.amount), 0) : s.tx?.amount ?? 0;
32432
32710
  const spentAway = new Set(swaps.filter((s) => s.stuck && s.kind === "send").flatMap((s) => swapOf(s).inputs.map((p) => p.secret)));
32433
32711
  return {
@@ -32441,6 +32719,13 @@ var CashuWallet = class CashuWallet {
32441
32719
  feesPaid: history.reduce((sum, tx) => sum + tx.fee, 0)
32442
32720
  };
32443
32721
  }
32722
+ /** Every proof and swap stored, read once for the views of every network: each read is the whole store. */
32723
+ async readStored() {
32724
+ return {
32725
+ proofs: await this.allProofs(),
32726
+ swaps: await wrap((await store(STORES$1.swaps, "readonly")).getAll())
32727
+ };
32728
+ }
32444
32729
  /**
32445
32730
  * Ecash a profile restore brought back (`unchecked`) is a copy from when the backup was made. What was spent since
32446
32731
  * (by the profile it was copied from, or by this one before it was restored) still counted in the balance, for good,
@@ -32511,6 +32796,11 @@ var CashuWallet = class CashuWallet {
32511
32796
  name
32512
32797
  };
32513
32798
  }
32799
+ /** What `view(network).balance` says, from the proofs alone: no swaps, no history. */
32800
+ async balance(network) {
32801
+ const here = new Set(this.getMints(network));
32802
+ return total((await this.allProofs()).filter((p) => here.has(p.mint) && !p.reserved));
32803
+ }
32514
32804
  async balanceAt(mint) {
32515
32805
  return total((await this.allProofs()).filter((p) => p.mint === mint && !p.reserved));
32516
32806
  }
@@ -32790,6 +33080,7 @@ var CashuWallet = class CashuWallet {
32790
33080
  tx.oncomplete = () => resolve();
32791
33081
  tx.onabort = tx.onerror = () => reject(new PaymentPreflightError(engineText("reviewedSatsGone")));
32792
33082
  });
33083
+ this.events.onChange();
32793
33084
  const { keep, send } = await (await this.wallet(prepared.mint)).completeSwap(preview);
32794
33085
  return this.finishReviewedCashu(review, prepared, keep, send);
32795
33086
  });
@@ -33489,6 +33780,8 @@ var CashuWallet = class CashuWallet {
33489
33780
  async quoteInvoice(invoice, network) {
33490
33781
  let lastError = /* @__PURE__ */ new Error("Add a mint in Settings first");
33491
33782
  let mints = this.getMints(network);
33783
+ /** The most any mint asked could pay with its fee on top: a Max comes down to it. */
33784
+ let room = 0;
33492
33785
  const decoded = decodeBolt11(invoice);
33493
33786
  if (!decoded) throw new Error("That is not an invoice this wallet can pay");
33494
33787
  if (decoded.amountSat === null) throw new Error("Invoices without an amount are not supported");
@@ -33501,8 +33794,10 @@ var CashuWallet = class CashuWallet {
33501
33794
  const amount = quote.amount.toNumber();
33502
33795
  const feeReserve = quote.fee_reserve.toNumber();
33503
33796
  if (quoteMismatch(quote, decoded.invoice, decoded.amountSat)) throw new Error(MINT_QUOTE_MISMATCH);
33504
- if (await this.balanceAt(mint) < amount + feeReserve) {
33505
- lastError = engineError("notEnoughSats");
33797
+ const balance = await this.balanceAt(mint);
33798
+ if (balance < amount + feeReserve) {
33799
+ room = Math.max(room, balance - feeReserve);
33800
+ lastError = room > 0 ? engineError("notEnoughForFee", { amount: room }) : engineError("notEnoughSats");
33506
33801
  continue;
33507
33802
  }
33508
33803
  this.shownQuotes.set(quote.quote, {
@@ -33993,6 +34288,11 @@ var PaymentBook = class extends Map {
33993
34288
  return this.shown ??= Object.fromEntries([...this].map(([id, { token: _token, ...view }]) => [id, view]));
33994
34289
  }
33995
34290
  };
34291
+ /**
34292
+ * How often a contact's "I paid it from another wallet" makes an on-chain, Ark, Bark or Spark wallet look
34293
+ * (`receiveCheck`): no more often than the wallet's own refresh, which runs the same look.
34294
+ */
34295
+ var RAIL_LOOK_MS = 1e4;
33996
34296
  var PaymentDesk = class {
33997
34297
  wallet;
33998
34298
  host;
@@ -35263,7 +35563,8 @@ var PaymentDesk = class {
35263
35563
  /**
35264
35564
  * The contact says it paid one of our requests from another wallet: our wallet is asked now, and it alone
35265
35565
  * decides. A request already paid is said so again (the first answer may have been lost). Bounded: one
35266
- * look every 3 seconds per request.
35566
+ * look every 3 seconds per Lightning request, and one every `RAIL_LOOK_MS` per other rail: 300 frames a minute
35567
+ * about 5 Bark requests made 100 Bark server syncs and 500 history reads.
35267
35568
  */
35268
35569
  async receiveCheck(linkId, payment) {
35269
35570
  const link = this.host.getLink(linkId);
@@ -35280,8 +35581,9 @@ var PaymentDesk = class {
35280
35581
  return;
35281
35582
  }
35282
35583
  const now = Date.now();
35283
- if (now - (this.lastCheckFrom.get(request.id) ?? 0) < 3e3) return;
35284
- this.lastCheckFrom.set(request.id, now);
35584
+ const [key, every] = rail === "lightning" ? [request.id, 3e3] : [rail, RAIL_LOOK_MS];
35585
+ if (now - (this.lastCheckFrom.get(key) ?? 0) < every) return;
35586
+ this.lastCheckFrom.set(key, now);
35285
35587
  try {
35286
35588
  if (rail === "lightning") await this.lightning[paymentNetwork(request)].check?.(payment.endpoint[1].trim().toLowerCase() === request.invoice?.toLowerCase() ? request.invoice : void 0);
35287
35589
  else if (rail === "bitcoin") await this.reconcileBitcoinReceipts();
@@ -35458,13 +35760,20 @@ var PaymentDesk = class {
35458
35760
  if (!this.host.getLink(linkId)?.supportsUsdtPayments || request?.target?.method !== "usdt" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request" || payment.amount.asset !== request.unit || payment.amount.value !== String(request.amount)) return;
35459
35761
  const existing = this.payments.get(payment.id);
35460
35762
  if (existing && (existing.direction !== "in" || existing.linkId !== linkId || existing.requestId !== request.id)) return;
35763
+ if (existing) {
35764
+ if (request.state === "settled") this.host.getLink(linkId)?.sendPaymentResult({
35765
+ id: request.id,
35766
+ ok: true
35767
+ });
35768
+ return;
35769
+ }
35461
35770
  let txid;
35462
35771
  try {
35463
35772
  txid = JSON.parse(payment.endpoint[1]).txid;
35464
35773
  } catch {
35465
35774
  return;
35466
35775
  }
35467
- if (typeof txid !== "string" || !/^0x[a-fA-F0-9]{64}$/.test(txid) || existing?.state === "settled") return;
35776
+ if (typeof txid !== "string" || !/^0x[a-fA-F0-9]{64}$/.test(txid)) return;
35468
35777
  if (this.repeatedReceipt(this.host.getLink(linkId), request, payment.id)) return;
35469
35778
  txid = txid.toLowerCase();
35470
35779
  if ([...this.payments.values()].some((p) => p.txid?.toLowerCase() === txid && (p.linkId !== linkId || (p.kind === "request" ? p.id !== request.id : p.requestId !== request.id)))) return;
@@ -35624,6 +35933,13 @@ var PaymentDesk = class {
35624
35933
  if (!link?.supportsArkPayments || !request?.target || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
35625
35934
  const existing = this.payments.get(payment.id);
35626
35935
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
35936
+ if (existing) {
35937
+ if (request.state === "settled") link.sendPaymentResult({
35938
+ id: request.id,
35939
+ ok: true
35940
+ });
35941
+ return;
35942
+ }
35627
35943
  if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
35628
35944
  let txid;
35629
35945
  try {
@@ -35632,7 +35948,7 @@ var PaymentDesk = class {
35632
35948
  return;
35633
35949
  }
35634
35950
  if ([...this.payments.values()].some((p) => p.txid === txid && (p.linkId !== linkId || (p.kind === "request" ? p.id !== request.id : p.requestId !== request.id)))) return;
35635
- if (typeof txid !== "string" || !/^[a-f0-9]{64}$/.test(txid) || existing?.state === "settled") return;
35951
+ if (typeof txid !== "string" || !/^[a-f0-9]{64}$/.test(txid)) return;
35636
35952
  if (this.repeatedReceipt(link, request, payment.id)) return;
35637
35953
  await this.save({
35638
35954
  id: payment.id,
@@ -35786,13 +36102,18 @@ var PaymentDesk = class {
35786
36102
  try {
35787
36103
  const open = [...this.payments.values()].filter((r) => r.kind === "request" && r.direction === "out" && r.state === "pending" && r.target?.method === "bark");
35788
36104
  const bark = this.bark;
35789
- for (const wallet of new Set(open.map((r) => bark[walletNetworkOf(r.target.network)]))) await wallet.adapter?.sync().catch(() => {});
36105
+ const receipts = /* @__PURE__ */ new Map();
36106
+ for (const wallet of new Set(open.map((r) => bark[walletNetworkOf(r.target.network)]))) {
36107
+ if (!wallet.adapter) continue;
36108
+ await wallet.adapter.sync().catch(() => {});
36109
+ receipts.set(wallet.adapter, await wallet.adapter.receipts().catch(() => void 0));
36110
+ }
35790
36111
  for (const request of open) {
35791
36112
  if (request.kind !== "request" || request.direction !== "out" || request.state !== "pending" || request.target?.method !== "bark") continue;
35792
36113
  const adapter = this.bark[walletNetworkOf(request.target.network)].adapter;
35793
36114
  if (!adapter || request.target.provider !== adapter.config.provider || request.target.network !== adapter.config.network) continue;
35794
36115
  const claimed = new Set([...this.payments.values()].filter((p) => p.target?.method === "bark" && p.kind === "request" && p.txid).map((p) => p.txid));
35795
- const txid = await adapter.received(request.target.address, request.amount, request.createdAt, claimed).catch(() => void 0);
36116
+ const txid = receipts.get(adapter)?.(request.target.address, request.amount, request.createdAt, claimed);
35796
36117
  if (!txid) continue;
35797
36118
  await this.settleRequest(request, { txid });
35798
36119
  for (const payment of this.payments.values()) if (payment.kind === "payment" && payment.direction === "in" && payment.requestId === request.id && payment.state === "pending") await this.save({
@@ -37044,6 +37365,8 @@ var SPARE_INVITE_WARM_AFTER_TAKE_MS = 3e4;
37044
37365
  var STARTUP_QUIET_MS = 15e3;
37045
37366
  /** At start, how long links start in one task before the page gets the thread back (`startNow`). */
37046
37367
  var START_SLICE_MS = 10;
37368
+ /** How long the wallets' changes gather into one view of them (`walletChanged`). */
37369
+ var WALLET_CHANGE_MS = 50;
37047
37370
  var SPARE_INVITE_MAX_AGE_MS = 9e5;
37048
37371
  /** How far before this clock a warm packet is dated (`warmKey`): further than a contact's clock is ever behind. */
37049
37372
  var WARM_DATED_BACK_MS = 864e5;
@@ -37196,6 +37519,8 @@ var GhostlyNode = class GhostlyNode {
37196
37519
  get networkOn() {
37197
37520
  return !!this.settings.online && !this.limitedMode && !this.options.offline;
37198
37521
  }
37522
+ /** The chats found saved at start that this run leaves unstarted (`NodeOptions.deferChats`). */
37523
+ deferredChats = /* @__PURE__ */ new Set();
37199
37524
  transport;
37200
37525
  /** The same, for groups' requests: a relay budget keeps a chat's share from them (`CHAT_RESERVE`). */
37201
37526
  groupTransport;
@@ -37456,23 +37781,23 @@ var GhostlyNode = class GhostlyNode {
37456
37781
  * goes through the wallet of its own network, and a wallet of one network never pays for the other.
37457
37782
  */
37458
37783
  usdtWallets = perNetwork((network) => new UsdtWallet(network, (viewChanged = true) => {
37459
- if (viewChanged) this.refreshWallet();
37784
+ if (viewChanged) this.walletChanged();
37460
37785
  this.desk.reconcileUsdtReceipts().catch(() => {});
37461
37786
  }));
37462
37787
  arkWallets = perNetwork((network) => new ArkWallet(network, (viewChanged = true) => {
37463
- if (viewChanged) this.refreshWallet();
37788
+ if (viewChanged) this.walletChanged();
37464
37789
  this.desk.reconcileArkReceipts().catch(() => {});
37465
37790
  }));
37466
37791
  barkWallets = perNetwork((network) => new BarkWallet(network, (viewChanged = true) => {
37467
- if (viewChanged) this.refreshWallet();
37792
+ if (viewChanged) this.walletChanged();
37468
37793
  this.desk.reconcileBarkReceipts().catch(() => {});
37469
37794
  }));
37470
37795
  fedimintWallets = perNetwork((network) => new FedimintWallet(network, {
37471
- changed: () => void this.refreshWallet(),
37796
+ changed: () => this.walletChanged(),
37472
37797
  received: (paymentId) => void this.desk.onLightningPaid({ paymentId })
37473
37798
  }, () => (this.options.fedimintSdk ?? loadFedimintSdk)()));
37474
37799
  sparkWallets = perNetwork((network) => new SparkWallet(network, (viewChanged = true) => {
37475
- if (viewChanged) this.refreshWallet();
37800
+ if (viewChanged) this.walletChanged();
37476
37801
  this.desk.reconcileSparkReceipts().catch(() => {});
37477
37802
  }));
37478
37803
  /** What a call naming no network acts on (a caller from before wallets had their own): Mainnet. */
@@ -37558,7 +37883,7 @@ var GhostlyNode = class GhostlyNode {
37558
37883
  return this.settings.mints.filter((mint) => mintNetwork(mint) === wanted);
37559
37884
  }
37560
37885
  wallet = new CashuWallet((network) => this.networkMints(network), {
37561
- onChange: () => void this.refreshWallet(),
37886
+ onChange: () => this.walletChanged(),
37562
37887
  onQuotePaid: (quote) => void this.lightnings[mintNetwork(quote.mint)].reportInvoicePaid(quote.invoice, {
37563
37888
  paymentId: quote.paymentId,
37564
37889
  mint: quote.mint
@@ -37580,6 +37905,7 @@ var GhostlyNode = class GhostlyNode {
37580
37905
  providerHost = (network) => ({
37581
37906
  platform: this.options.platform ?? "web",
37582
37907
  cashu: this.wallet,
37908
+ cashuBalance: () => this.walletView.networks?.[network].balance,
37583
37909
  fedimint: this.fedimintWallets[network],
37584
37910
  invoke: this.options.invoke
37585
37911
  });
@@ -37593,14 +37919,14 @@ var GhostlyNode = class GhostlyNode {
37593
37919
  hasMints: () => this.networkMints(network).length > 0,
37594
37920
  fetch: (...request) => (this.options.lnurlFetch ?? globalThis.fetch)(...request),
37595
37921
  events: {
37596
- changed: () => void this.refreshWallet(),
37922
+ changed: () => this.walletChanged(),
37597
37923
  received: (op) => void this.desk.onLightningPaid(op),
37598
37924
  resolved: (op, paid) => void this.desk.onLightningResolved(op, paid)
37599
37925
  }
37600
37926
  }));
37601
37927
  /** On-chain Bitcoin of each network, through its active source: none until the person sets one up. */
37602
37928
  bitcoins = perNetwork((network) => new BitcoinService(network, () => this.providers().onchain, () => this.providerHost(network), () => {
37603
- this.refreshWallet();
37929
+ this.walletChanged();
37604
37930
  this.desk.reconcileBitcoinReceipts().catch(() => {});
37605
37931
  }));
37606
37932
  desk = new PaymentDesk(this.wallet, {
@@ -37729,16 +38055,21 @@ var GhostlyNode = class GhostlyNode {
37729
38055
  await db.updateDelivery(linkId, messageId, state, error);
37730
38056
  await this.noteHold(linkId, messageId, state, error);
37731
38057
  const message = await db.getMessage(linkId, messageId);
37732
- if (message?.file) this.transfers.set(message.file.id, state === "failed" ? {
37733
- state: "failed",
37734
- transferred: 0,
37735
- size: message.file.size,
37736
- error
37737
- } : {
37738
- state: "done",
37739
- transferred: message.file.size,
37740
- size: message.file.size
37741
- });
38058
+ if (message?.file) {
38059
+ const transfer = state === "failed" ? {
38060
+ state: "failed",
38061
+ transferred: 0,
38062
+ size: message.file.size,
38063
+ error
38064
+ } : {
38065
+ state: "done",
38066
+ transferred: message.file.size,
38067
+ size: message.file.size
38068
+ };
38069
+ await fileStore.updateTransfer(message.file.id, transfer).catch(() => {});
38070
+ this.transfers.set(message.file.id, transfer);
38071
+ if (transfer.state === "done") this.brief(message.file.id);
38072
+ }
37742
38073
  if (message && state !== "failed") this.messageFeedback("sent", message);
37743
38074
  await this.messagesChanged(linkId, [messageId]);
37744
38075
  this.emitState();
@@ -37836,6 +38167,7 @@ var GhostlyNode = class GhostlyNode {
37836
38167
  transferred: wire.size,
37837
38168
  size: wire.size
37838
38169
  });
38170
+ this.brief(file.id);
37839
38171
  await this.storeMessage({
37840
38172
  linkId,
37841
38173
  id: `peer_${wire.wireId}`,
@@ -38140,6 +38472,14 @@ var GhostlyNode = class GhostlyNode {
38140
38472
  this.emitState();
38141
38473
  },
38142
38474
  notify: (chat, key) => this.feedback("reaction", `${chat}:${key}`, chat),
38475
+ keep: async (chat, reactionsWaiting) => {
38476
+ const live = this.links.get(chat);
38477
+ if (live) live.stored = {
38478
+ ...live.stored,
38479
+ reactionsWaiting
38480
+ };
38481
+ await db.patchLink(chat, { reactionsWaiting });
38482
+ },
38143
38483
  believed: (chat, by) => {
38144
38484
  const membership = this.membership(chat.slice(6));
38145
38485
  return !!membership?.members.has(by) && by !== membership.me;
@@ -38265,10 +38605,7 @@ var GhostlyNode = class GhostlyNode {
38265
38605
  groupFiles: {
38266
38606
  store: storedGroupFiles,
38267
38607
  transfers: this.transfers,
38268
- brief: (id) => {
38269
- const view = this.transfers.get(id);
38270
- if (view) this.briefViews.set(id, view);
38271
- },
38608
+ brief: (id) => this.brief(id),
38272
38609
  settings: () => ({
38273
38610
  autoDownloads: this.settings.autoDownloads !== false,
38274
38611
  serveFiles: this.settings.serveFiles !== false
@@ -38540,12 +38877,48 @@ var GhostlyNode = class GhostlyNode {
38540
38877
  this.emitState();
38541
38878
  }).catch(() => {}), 250);
38542
38879
  }
38543
- async refreshWallet() {
38880
+ /** The wallets' view being made, and the one more run asked for while it is (see `refreshWallet`). */
38881
+ walletRefresh;
38882
+ walletRefreshAgain;
38883
+ /**
38884
+ * The wallets' view made again. Every wallet that changes asks for it: a start asked 11 times in its first seconds,
38885
+ * each run reading every Cashu proof and every payment review ever made. A run in flight may have read
38886
+ * before what the caller changed, so callers meanwhile share one more run after it: each still waits for a view made
38887
+ * after it asked.
38888
+ */
38889
+ refreshWallet() {
38890
+ if (!this.walletRefresh) {
38891
+ const run = this.walletRefresh = this.refreshWalletNow().finally(() => {
38892
+ if (this.walletRefresh === run) this.walletRefresh = void 0;
38893
+ });
38894
+ return run;
38895
+ }
38896
+ return this.walletRefreshAgain ??= this.walletRefresh.catch(() => {}).then(() => {
38897
+ this.walletRefreshAgain = void 0;
38898
+ return this.refreshWallet();
38899
+ });
38900
+ }
38901
+ /** While `startWallets` opens the wallets: what they say changed is in the view it makes once they are open. */
38902
+ walletsOpening = false;
38903
+ walletChangeTimer;
38904
+ /**
38905
+ * A wallet says what it shows changed, and nobody waits for the view: the changes said within `WALLET_CHANGE_MS`
38906
+ * make one view. Opening, the wallets and their sources say so a dozen times within 150 ms.
38907
+ */
38908
+ walletChanged() {
38909
+ if (this.walletsOpening || this.walletChangeTimer) return;
38910
+ this.walletChangeTimer = setTimeout(() => {
38911
+ this.walletChangeTimer = void 0;
38912
+ if (!this.shuttingDown) this.refreshWallet().catch(() => {});
38913
+ }, WALLET_CHANGE_MS);
38914
+ }
38915
+ async refreshWalletNow() {
38544
38916
  const networks = {};
38545
38917
  let everything = [];
38546
38918
  const awaiting = await this.readAwaiting();
38919
+ const stored = await this.wallet.readStored();
38547
38920
  for (const network of WALLET_NETWORKS) {
38548
- const view = await this.wallet.view(network);
38921
+ const view = await this.wallet.view(network, stored);
38549
38922
  everything = everything.concat(view.history);
38550
38923
  const history = view.history.filter((tx) => !tx.mint || mintNetwork(tx.mint) === network);
38551
38924
  networks[network] = {
@@ -38699,6 +39072,9 @@ var GhostlyNode = class GhostlyNode {
38699
39072
  await this.publicProfiles.load();
38700
39073
  if (!this.limitedMode) await this.startWallets();
38701
39074
  const links = await db.getLinks();
39075
+ if (this.options.deferChats) {
39076
+ for (const stored of links) if (!stored.group) this.deferredChats.add(stored.id);
39077
+ }
38702
39078
  for (const stored of links) if (stored.group) this.links.set(stored.id, newLiveLink(stored, 0, linkFilesFrom(stored.id, [], [])));
38703
39079
  for (const group of await db.getGroups()) await this.settleHistory(`group:${group.id}`);
38704
39080
  await this.groups.load(this.limitedMode);
@@ -38710,13 +39086,14 @@ var GhostlyNode = class GhostlyNode {
38710
39086
  await this.settleHistory(stored.id);
38711
39087
  const messages = await db.getMessages(stored.id);
38712
39088
  const storedFiles = await fileStore.listForLink(stored.id);
38713
- const waiting = new Set(messages.flatMap((m) => m.sender === "me" && m.delivery === "waiting" && m.file ? [m.file.id] : []));
38714
- for (const file of storedFiles) if (file.transfer && file.transfer.state !== "done" && !file.wire3 && !waiting.has(file.id)) this.transfers.set(file.id, file.transfer.state === "transferring" ? {
39089
+ const notInterrupted = new Set(messages.flatMap((m) => m.sender === "me" && m.file && (m.delivery === "waiting" || m.via === "hold" && (m.delivery === "held" || m.delivery === "delivered")) ? [m.file.id] : []));
39090
+ for (const file of storedFiles) if (file.transfer && file.transfer.state !== "done" && !file.wire3 && !notInterrupted.has(file.id)) this.transfers.set(file.id, file.transfer.state === "transferring" ? {
38715
39091
  ...file.transfer,
38716
39092
  state: "failed",
38717
39093
  error: "Transfer interrupted. Retry when connected."
38718
39094
  } : file.transfer);
38719
- this.fileDesk.restore(stored.id, storedFiles);
39095
+ const unreceipted = new Set(messages.flatMap((m) => m.sender === "me" && m.file && m.delivery !== "delivered" ? [m.file.id] : []));
39096
+ this.fileDesk.restore(stored.id, storedFiles, unreceipted);
38720
39097
  const files = linkFilesFrom(stored.id, storedFiles, messages);
38721
39098
  this.links.set(stored.id, newLiveLink(stored, messages[messages.length - 1]?.timestamp ?? 0, files));
38722
39099
  this.links.get(stored.id).waitingSends = Promise.resolve(new Set(messages.filter(waitsForLive).map((m) => m.id)));
@@ -38724,6 +39101,7 @@ var GhostlyNode = class GhostlyNode {
38724
39101
  for (const message of messages.slice(-20)) this.clockSample(message);
38725
39102
  const note = latestReaction(messages);
38726
39103
  if (note) this.reactionNotes.set(stored.id, note);
39104
+ if (stored.reactionsWaiting?.length) await this.reactions.restore(stored.id, stored.reactionsWaiting, messages);
38727
39105
  if (stored.profile) await this.outboxFor(stored.id).recover(messages);
38728
39106
  }
38729
39107
  this.transfersRestored = true;
@@ -38921,16 +39299,21 @@ var GhostlyNode = class GhostlyNode {
38921
39299
  setSingleWriterGate(() => this.singleWriterTurn());
38922
39300
  const migrated = await migrateWalletNetworks();
38923
39301
  if (migrated.moved.length || migrated.unreadable.length) console.info("[wallet] wallets moved to their network's key:", migrated.moved.map((m) => m.key).join(", ") || "none", migrated.unreadable.length ? `; left as they were: ${migrated.unreadable.join(", ")}` : "");
38924
- for (const network of WALLET_NETWORKS) {
38925
- await this.arkWallets[network].start();
38926
- await this.barkWallets[network].start();
38927
- await this.fedimintWallets[network].start();
38928
- await this.sparkWallets[network].start();
38929
- await this.usdtWallets[network].start();
38930
- await this.lightnings[network].start();
38931
- await this.bitcoins[network].start();
38932
- }
38933
- await this.desk.start();
39302
+ this.walletsOpening = true;
39303
+ try {
39304
+ for (const network of WALLET_NETWORKS) {
39305
+ await this.arkWallets[network].start();
39306
+ await this.barkWallets[network].start();
39307
+ await this.fedimintWallets[network].start();
39308
+ await this.sparkWallets[network].start();
39309
+ await this.usdtWallets[network].start();
39310
+ await this.lightnings[network].start();
39311
+ await this.bitcoins[network].start();
39312
+ }
39313
+ await this.desk.start();
39314
+ } finally {
39315
+ this.walletsOpening = false;
39316
+ }
38934
39317
  await this.refreshWallet();
38935
39318
  this.wallet.start();
38936
39319
  this.dropStaleReviews();
@@ -39169,6 +39552,7 @@ var GhostlyNode = class GhostlyNode {
39169
39552
  this.resumeTimers.clear();
39170
39553
  if (this.paymentTimer) clearTimeout(this.paymentTimer);
39171
39554
  clearTimeout(this.awaitingTimer);
39555
+ clearTimeout(this.walletChangeTimer);
39172
39556
  clearInterval(this.staleReviewTimer);
39173
39557
  if (this.spareTimer) clearTimeout(this.spareTimer);
39174
39558
  for (const timer of this.reactionTimers.values()) clearTimeout(timer);
@@ -39328,6 +39712,7 @@ var GhostlyNode = class GhostlyNode {
39328
39712
  }
39329
39713
  getState() {
39330
39714
  const groups = this.groups.views();
39715
+ const edges = this.edgesByMember();
39331
39716
  return {
39332
39717
  settings: this.settings,
39333
39718
  ...this.limitedMode && { limited: true },
@@ -39370,7 +39755,7 @@ var GhostlyNode = class GhostlyNode {
39370
39755
  ...this.reactionNotes.has(`group:${group.id}`) && { lastReaction: this.reactionNotes.get(`group:${group.id}`) },
39371
39756
  ...this.groupWakeView(group),
39372
39757
  members: group.members.map((member) => {
39373
- const edge = member.me ? void 0 : this.edgeView(group.id, member.key);
39758
+ const edge = member.me ? void 0 : this.edgeView(group.id, member.key, edges);
39374
39759
  return edge ? {
39375
39760
  ...member,
39376
39761
  edge
@@ -39416,9 +39801,25 @@ var GhostlyNode = class GhostlyNode {
39416
39801
  if (!this.groups.isCommunityGroup(groupId) || !this.membership(groupId)?.members.has(member)) return;
39417
39802
  await this.communityPay.hello(groupId, member).catch(() => {});
39418
39803
  }
39804
+ /**
39805
+ * The groups' edges by group, then member: one pass over the links per state, not one per member of every group
39806
+ * (communities' members, who have no edge, included).
39807
+ */
39808
+ edgesByMember() {
39809
+ const edges = /* @__PURE__ */ new Map();
39810
+ for (const live of this.links.values()) {
39811
+ const { group, groupPeer, groupEntry } = live.stored;
39812
+ if (!group || !groupPeer || groupEntry) continue;
39813
+ const members = edges.get(group) ?? /* @__PURE__ */ new Map();
39814
+ if (!members.has(groupPeer)) members.set(groupPeer, live);
39815
+ edges.set(group, members);
39816
+ }
39817
+ return edges;
39818
+ }
39419
39819
  /** The edge of a group toward one member, as the group page shows it: what carries it and when the member was last heard. */
39420
- edgeView(groupId, member) {
39421
- for (const live of this.links.values()) if (live.stored.group === groupId && live.stored.groupPeer === member && !live.stored.groupEntry) return edgeView(live, Date.now(), this.groupNativeWaiting.has(live.stored.id));
39820
+ edgeView(groupId, member, edges = this.edgesByMember()) {
39821
+ const live = edges.get(groupId)?.get(member);
39822
+ return live && edgeView(live, Date.now(), this.groupNativeWaiting.has(live.stored.id));
39422
39823
  }
39423
39824
  /** A chat's or a group's history, as a page gets it (`withoutFrame`). */
39424
39825
  async getMessages(linkId) {
@@ -39568,6 +39969,7 @@ var GhostlyNode = class GhostlyNode {
39568
39969
  const existing = [...this.links.values()].find((l) => l.stored.seedB64 === params.seedB64);
39569
39970
  if (existing) {
39570
39971
  if (existing.stored.profile !== params.profile) throw new Error("Invitation profile does not match the stored link");
39972
+ if (this.deferredChats.delete(existing.stored.id) && this.networkOn) this.startLink(existing.stored.id);
39571
39973
  return { linkId: await this.existingLink(existing.stored.id) };
39572
39974
  }
39573
39975
  this.refuseOwnInvite(params);
@@ -40040,6 +40442,7 @@ var GhostlyNode = class GhostlyNode {
40040
40442
  */
40041
40443
  groupMembersChanged(groupId) {
40042
40444
  this.quietOutsideEdges(groupId);
40445
+ this.groupEdits.membersChanged(groupId);
40043
40446
  const holders = this.settings.wakeHeldBy?.[groupId];
40044
40447
  if (!holders?.length) return;
40045
40448
  const members = this.membership(groupId)?.members;
@@ -40053,6 +40456,7 @@ var GhostlyNode = class GhostlyNode {
40053
40456
  */
40054
40457
  groupHistoryGone(groupId) {
40055
40458
  const linkId = `group:${groupId}`;
40459
+ this.groupEdits.forget(groupId);
40056
40460
  this.newestAt.delete(linkId);
40057
40461
  this.lateAt.delete(linkId);
40058
40462
  for (const clock of this.clockLeads.keys()) if (clock.startsWith(`${linkId} `)) this.clockLeads.delete(clock);
@@ -42048,6 +42452,7 @@ var GhostlyNode = class GhostlyNode {
42048
42452
  });
42049
42453
  const state = this.transfers.get(fileId);
42050
42454
  fileStore.updateTransfer(fileId, state).catch(() => {});
42455
+ if (!error) this.brief(fileId);
42051
42456
  this.emitState();
42052
42457
  }
42053
42458
  async setDeliveryMode({ linkId, mode }) {
@@ -44176,21 +44581,25 @@ var GhostlyNode = class GhostlyNode {
44176
44581
  await db.putSettings(this.settings);
44177
44582
  this.hold.storageChanged();
44178
44583
  }
44179
- if (wasOnline && !this.networkOn) await Promise.allSettled([...this.links.values()].map(async (live) => {
44180
- live.carried?.stop();
44181
- await live.link?.stop(true);
44182
- await live.caps?.stop();
44183
- live.caps = void 0;
44184
- live.link = null;
44185
- live.status = "offline";
44186
- live.dataLink = "idle";
44187
- }));
44188
- else if (!wasOnline && this.networkOn && await this.turnBeforeOnline()) {
44584
+ if (wasOnline && !this.networkOn) {
44585
+ this.enrollment?.cancel("offline").catch(() => {});
44586
+ await Promise.allSettled([...this.links.values()].map(async (live) => {
44587
+ live.carried?.stop();
44588
+ await live.link?.stop(true);
44589
+ await live.caps?.stop();
44590
+ live.caps = void 0;
44591
+ live.link = null;
44592
+ live.status = "offline";
44593
+ live.dataLink = "idle";
44594
+ }));
44595
+ await this.stopDeviceSet();
44596
+ } else if (!wasOnline && this.networkOn && await this.turnBeforeOnline()) {
44189
44597
  await this.startLinks([...this.links.keys()]);
44190
44598
  this.hold.start();
44191
44599
  this.startGroupEntries();
44192
44600
  this.prepareSpare(STARTUP_QUIET_MS);
44193
44601
  this.did.publishNow().catch(() => {});
44602
+ if (!this.options.singleDevice && knownDeviceGate()?.state === "active") this.startDeviceSet({ justRead: true }).catch(() => {});
44194
44603
  } else if (wasOnline && this.networkOn && relayOnlyChanged) await this.restartLinksForRelayOnly();
44195
44604
  if (wasOnline && !this.networkOn) this.stopGroupEntries();
44196
44605
  if (wasOnline && !this.networkOn) await this.hold.stop();
@@ -44332,7 +44741,7 @@ var GhostlyNode = class GhostlyNode {
44332
44741
  * turn read made a moment before (the read at start, or limited mode's), which counts while it is fresh.
44333
44742
  */
44334
44743
  async startDeviceSet({ justRead = false } = {}) {
44335
- if (this.shuttingDown) return;
44744
+ if (this.shuttingDown || !this.networkOn) return;
44336
44745
  const own = await readDeviceRecord(databaseName()).catch(() => null);
44337
44746
  this.ownDeviceKey = own?.ownSlot !== void 0 ? own.deviceSet[own.ownSlot]?.key ?? null : null;
44338
44747
  if (!this.deviceLinks) {
@@ -44379,6 +44788,21 @@ var GhostlyNode = class GhostlyNode {
44379
44788
  this.watchTombstones();
44380
44789
  await this.rotateIfDue().catch(() => {});
44381
44790
  }
44791
+ /**
44792
+ * The network turned off: the links to the other devices stop as every other link does, and ask nothing more of a
44793
+ * relay or the DHT. `startDeviceSet` makes them again when it comes back, with the handoff (which resumes a stopped move).
44794
+ */
44795
+ async stopDeviceSet() {
44796
+ const links = this.deviceLinks;
44797
+ if (!links) return;
44798
+ this.deviceLinks = null;
44799
+ this.handoffGiver = null;
44800
+ if (this.activeTurnTimer) clearTimeout(this.activeTurnTimer);
44801
+ this.activeTurnTimer = null;
44802
+ this.sentTokens.clear();
44803
+ this.renewAsked.clear();
44804
+ await links.stop().catch(() => {});
44805
+ }
44382
44806
  /** How often a running active device reads the turn (WISP 06 § When a device checks: every 10 minutes, with jitter). */
44383
44807
  static ACTIVE_TURN_EVERY_MS = 6e5;
44384
44808
  static ACTIVE_TURN_JITTER_MS = 6e4;
@@ -45480,7 +45904,7 @@ var GhostlyNode = class GhostlyNode {
45480
45904
  }
45481
45905
  startLink(linkId) {
45482
45906
  const live = this.links.get(linkId);
45483
- if (!live || live.link) return;
45907
+ if (!live || live.link || this.deferredChats.has(linkId)) return;
45484
45908
  const { stored } = live;
45485
45909
  if (stored.group) return this.startEdge(linkId);
45486
45910
  if (stored.profile) live.pairing = { status: "connecting" };
@@ -46017,7 +46441,7 @@ var GhostlyNode = class GhostlyNode {
46017
46441
  nativeFactoriesFor(relayOnly) {
46018
46442
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
46019
46443
  return {
46020
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-B2v8eqRd.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46444
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-D1rj84v2.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46021
46445
  ...relayOnly ? {} : this.options.nativeTransports,
46022
46446
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
46023
46447
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -46034,7 +46458,7 @@ var GhostlyNode = class GhostlyNode {
46034
46458
  /** New Iroh relays: idle endpoints move now; one carrying a chat keeps its relay until that session ends. */
46035
46459
  async rehomeIroh() {
46036
46460
  if (!this.options.irohWeb && !this.ownIrohRelays) return;
46037
- this.deviceLinks?.nativeChanged();
46461
+ this.deviceLinks?.nativeChanged(["iroh/1"]);
46038
46462
  for (const [linkId, live] of this.links) {
46039
46463
  const link = live.link;
46040
46464
  if (!link?.availableTransports.includes("iroh/1") || !link.canReleaseEndpoint("iroh/1")) continue;
@@ -46078,7 +46502,7 @@ var GhostlyNode = class GhostlyNode {
46078
46502
  /** A new relay (or none): chats give up their endpoints on the old one, as soon as none of them carries a session. */
46079
46503
  async relayChanged() {
46080
46504
  if (!this.relaysHyperdht) return;
46081
- this.deviceLinks?.nativeChanged();
46505
+ this.deviceLinks?.nativeChanged(["hyperdht/1"]);
46082
46506
  for (const [linkId, live] of this.links) {
46083
46507
  const link = live.link;
46084
46508
  if (!link?.availableTransports.includes("hyperdht/1")) {
@@ -46386,7 +46810,7 @@ var GhostlyNode = class GhostlyNode {
46386
46810
  }
46387
46811
  /**
46388
46812
  * The order saved chats start in, which is the order they take native listeners in (`NATIVE_SLOTS` per transport):
46389
- * the 1:1 chats written in, or live, most recently first; group links keep their places. In the order they were
46813
+ * the 1:1 chats written in, or live, most recently first, then the group links in the order given. In the order they were
46390
46814
  * stored, an app with more paired chats than slots left a chat that was live a moment before with no listener, and a
46391
46815
  * contact with no WebRTC (the Linux Desktop) never reached it again (Omarchy, 2026-09-30: "On DHT · retrying live" for
46392
46816
  * minutes after both apps restarted). Not "live when this app last ran" first: a chat that heard its contact leave as
@@ -46395,6 +46819,10 @@ var GhostlyNode = class GhostlyNode {
46395
46819
  * On an app with WebRTC, the chats whose contact has none (its capability record lists no `webrtc/1`: a Linux Desktop,
46396
46820
  * a CLI with WebRTC off) come first, each class in that order: they reach this app over a native transport or not
46397
46821
  * live at all, while a contact with WebRTC still has it when no listener is left here.
46822
+ *
46823
+ * The chats before every group link, whatever order they come in: leaving limited mode, the network back on and
46824
+ * "Hide my IP" switched start the links in the engine's order, every private group's edges first, and with 10 mesh
46825
+ * groups of 32 the chat about to be opened waited for 310 edges to derive their keys and seal their records.
46398
46826
  */
46399
46827
  nativeStartOrder(linkIds) {
46400
46828
  const isChat = (id) => {
@@ -46418,8 +46846,7 @@ var GhostlyNode = class GhostlyNode {
46418
46846
  place,
46419
46847
  ...rank.get(id)
46420
46848
  }));
46421
- let next = 0;
46422
- return linkIds.map((id) => rank.has(id) ? chats[next++] : id);
46849
+ return [...chats, ...linkIds.filter((id) => !rank.has(id))];
46423
46850
  }
46424
46851
  /**
46425
46852
  * A chat started as "live when this app last ran" (it resumes, and knocks): if this run is not live in it within
@@ -46817,6 +47244,11 @@ var GhostlyNode = class GhostlyNode {
46817
47244
  this.events.onState(this.getState());
46818
47245
  this.dropBriefViews();
46819
47246
  }
47247
+ /** `id`'s view goes in the next state sent, and then away (`briefViews`). */
47248
+ brief(id) {
47249
+ const view = this.transfers.get(id);
47250
+ if (view) this.briefViews.set(id, view);
47251
+ }
46820
47252
  /** A state went with the brief views: they go, so the next states do not carry them (`briefViews`). */
46821
47253
  dropBriefViews() {
46822
47254
  for (const [id, view] of this.briefViews) if (this.transfers.get(id) === view) this.transfers.delete(id);
@@ -47103,4 +47535,4 @@ function signalKind(signal) {
47103
47535
  //#endregion
47104
47536
  export { EngineServer };
47105
47537
 
47106
- //# sourceMappingURL=server-CB9_JuWZ.js.map
47538
+ //# sourceMappingURL=server-CnPj9wWh.js.map