@ghostlytools/cli 1.9.0 → 1.10.1

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 (118) hide show
  1. package/README.md +35 -27
  2. package/SKILL.md +7 -3
  3. package/dist/assets/api-BOWLZYXM.js +3 -0
  4. package/dist/assets/{api-DFCgr6RH.js → api-Bi6hCcwG.js} +100 -47
  5. package/dist/assets/api-Bi6hCcwG.js.map +1 -0
  6. package/dist/assets/{apiKit-CCavJJcl.js → apiKit-DzXHZojD.js} +26 -9
  7. package/dist/assets/apiKit-DzXHZojD.js.map +1 -0
  8. package/dist/assets/{apps-B7o2BPj6.js → apps-0Ks6KjqS.js} +1 -1
  9. package/dist/assets/{apps-DmxEG147.js → apps-DIQbzG08.js} +33 -10
  10. package/dist/assets/apps-DIQbzG08.js.map +1 -0
  11. package/dist/assets/{arkade-DtYR9H0c.js → arkade-zozCldAE.js} +2 -2
  12. package/dist/assets/{arkade-DtYR9H0c.js.map → arkade-zozCldAE.js.map} +1 -1
  13. package/dist/assets/{backup-YIB2XIES.js → backup-BL49Kt-T.js} +7 -6
  14. package/dist/assets/{backup-YIB2XIES.js.map → backup-BL49Kt-T.js.map} +1 -1
  15. package/dist/assets/{backup-BserdrNk.js → backup-BvIFcZM7.js} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{blobFiles-DOQDRdDI.js → blobFiles-BnjN_Vrz.js} +3 -3
  19. package/dist/assets/{blobFiles-DOQDRdDI.js.map → blobFiles-BnjN_Vrz.js.map} +1 -1
  20. package/dist/assets/buttons-CAW5v5EE.js +332 -0
  21. package/dist/assets/buttons-CAW5v5EE.js.map +1 -0
  22. package/dist/assets/buttons-oJI5mHSL.js +2 -0
  23. package/dist/assets/childEnv-BVOQK9EA.js +21 -0
  24. package/dist/assets/childEnv-BVOQK9EA.js.map +1 -0
  25. package/dist/assets/client-CyApKBEw.js +473 -0
  26. package/dist/assets/client-CyApKBEw.js.map +1 -0
  27. package/dist/assets/codec-DqFxxB_q.js +13 -0
  28. package/dist/assets/codec-DqFxxB_q.js.map +1 -0
  29. package/dist/assets/{endpoint-BdaeBw2L.js → endpoint-DWHkXWVM.js} +101 -16
  30. package/dist/assets/endpoint-DWHkXWVM.js.map +1 -0
  31. package/dist/assets/{envelope-Dt75vrmY.js → envelope-CMUgz31I.js} +3 -12
  32. package/dist/assets/envelope-CMUgz31I.js.map +1 -0
  33. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js.map +1 -1
  34. package/dist/assets/{fileBytes-BPDKufla.js → fileBytes-DMzrIdCu.js} +1 -1
  35. package/dist/assets/{fileBytes-DNgrRL0R.js → fileBytes-DjBYYyXT.js} +3 -3
  36. package/dist/assets/{fileBytes-DNgrRL0R.js.map → fileBytes-DjBYYyXT.js.map} +1 -1
  37. package/dist/assets/{fileBytes-Q3ehcEr8.js → fileBytes-Douk1yOp.js} +2 -2
  38. package/dist/assets/{fileBytes-Q3ehcEr8.js.map → fileBytes-Douk1yOp.js.map} +1 -1
  39. package/dist/assets/fileBytesIdb-CD5Uv490.js +2 -0
  40. package/dist/assets/{fileBytesIdb-Dm1EyEbT.js → fileBytesIdb-CkClu9YI.js} +3 -3
  41. package/dist/assets/{fileBytesIdb-Dm1EyEbT.js.map → fileBytesIdb-CkClu9YI.js.map} +1 -1
  42. package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js → fileBytesOpfs-WryQuOgK.js} +3 -3
  43. package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js.map → fileBytesOpfs-WryQuOgK.js.map} +1 -1
  44. package/dist/assets/{fixedHosts-B598JzbC.js → fixedHosts-C2hdCfzK.js} +4 -4
  45. package/dist/assets/{fixedHosts-B598JzbC.js.map → fixedHosts-C2hdCfzK.js.map} +1 -1
  46. package/dist/assets/{groupFiles-FXel6zIc.js → groupFiles-BAQIt_bJ.js} +404 -161
  47. package/dist/assets/groupFiles-BAQIt_bJ.js.map +1 -0
  48. package/dist/assets/{host-DIBeK_c_.js → host-CaRlDMTd.js} +206 -49
  49. package/dist/assets/host-CaRlDMTd.js.map +1 -0
  50. package/dist/assets/{hyperdhtRelay-D185dETu.js → hyperdhtRelay-BxADl3SG.js} +2 -2
  51. package/dist/assets/{hyperdhtRelay-D185dETu.js.map → hyperdhtRelay-BxADl3SG.js.map} +1 -1
  52. package/dist/assets/{idb-BkOJES5_.js → idb-BHsAqENE.js} +37 -6
  53. package/dist/assets/idb-BHsAqENE.js.map +1 -0
  54. package/dist/assets/{irohWeb-BSv_BWyG.js → irohWeb-D2sh6EWp.js} +65 -7
  55. package/dist/assets/irohWeb-D2sh6EWp.js.map +1 -0
  56. package/dist/assets/{main-BbhfMTt8.js → main-Bc4Ow56Z.js} +221 -287
  57. package/dist/assets/main-Bc4Ow56Z.js.map +1 -0
  58. package/dist/assets/{mainline-9Vc3c3SA.js → mainline-DWh4Ccri.js} +2 -2
  59. package/dist/assets/{mainline-9Vc3c3SA.js.map → mainline-DWh4Ccri.js.map} +1 -1
  60. package/dist/assets/networkReason-DT_D_Wpc.js +474 -0
  61. package/dist/assets/networkReason-DT_D_Wpc.js.map +1 -0
  62. package/dist/assets/{nwc-QX3Yt1Sb.js → nwc-DoSEhUKb.js} +3 -3
  63. package/dist/assets/{nwc-QX3Yt1Sb.js.map → nwc-DoSEhUKb.js.map} +1 -1
  64. package/dist/assets/{nwcProvider-CzX3xH47.js → nwcProvider-CGWqUjpB.js} +2 -2
  65. package/dist/assets/{nwcProvider-CzX3xH47.js.map → nwcProvider-CGWqUjpB.js.map} +1 -1
  66. package/dist/assets/{ownDid-D8z5gwGI.js → ownDid-CbGjRLBn.js} +3 -3
  67. package/dist/assets/ownDid-CbGjRLBn.js.map +1 -0
  68. package/dist/assets/{profiles-MFtCmJwK.js → profiles-DgIfvBeN.js} +47 -4
  69. package/dist/assets/profiles-DgIfvBeN.js.map +1 -0
  70. package/dist/assets/{registry-B2Dtnibo.js → registry-BSyxGjN6.js} +11 -9
  71. package/dist/assets/registry-BSyxGjN6.js.map +1 -0
  72. package/dist/assets/{registry-PTtBMaYZ.js → registry-C5cn80Rw.js} +1 -1
  73. package/dist/assets/{resolve-ZxVzwFNA.js → resolve-D-9YRFhl.js} +2 -2
  74. package/dist/assets/{resolve-ZxVzwFNA.js.map → resolve-D-9YRFhl.js.map} +1 -1
  75. package/dist/assets/{restoredRows-BCRCjhdF.js → restoredRows-CRYwIx3g.js} +2 -2
  76. package/dist/assets/{restoredRows-BCRCjhdF.js.map → restoredRows-CRYwIx3g.js.map} +1 -1
  77. package/dist/assets/{buttons-CuRfKnPI.js → secretGuard-CSVNxXVW.js} +80 -330
  78. package/dist/assets/secretGuard-CSVNxXVW.js.map +1 -0
  79. package/dist/assets/secretGuard-Q2BKq0q0.js +2 -0
  80. package/dist/assets/{server-Dw1o8z1o.js → server-BufntkX8.js} +1734 -369
  81. package/dist/assets/server-BufntkX8.js.map +1 -0
  82. package/dist/assets/{src-BD8RBVEp.js → src-CCt5s4DK.js} +3073 -1890
  83. package/dist/assets/src-CCt5s4DK.js.map +1 -0
  84. package/dist/assets/{sshForges-DWrESWkK.js → sshForges-D8CPaIbR.js} +16 -9
  85. package/dist/assets/{sshForges-DWrESWkK.js.map → sshForges-D8CPaIbR.js.map} +1 -1
  86. package/dist/assets/{translate-D1uP0q32.js → translate-Cb-6hMhD.js} +17 -12
  87. package/dist/assets/translate-Cb-6hMhD.js.map +1 -0
  88. package/dist/assets/{usdt-DhVN8geQ.js → usdt-ds461mzA.js} +3 -3
  89. package/dist/assets/{usdt-DhVN8geQ.js.map → usdt-ds461mzA.js.map} +1 -1
  90. package/dist/assets/{words-DdXPkB3n.js → words-B1ylON2h.js} +4 -2
  91. package/dist/assets/words-B1ylON2h.js.map +1 -0
  92. package/dist/ghostly.mjs +1 -1
  93. package/package.json +1 -1
  94. package/dist/assets/api-DFCgr6RH.js.map +0 -1
  95. package/dist/assets/api-raWw9j_m.js +0 -3
  96. package/dist/assets/apiKit-CCavJJcl.js.map +0 -1
  97. package/dist/assets/apps-DmxEG147.js.map +0 -1
  98. package/dist/assets/buttons-CuRfKnPI.js.map +0 -1
  99. package/dist/assets/buttons-De3LPdSG.js +0 -2
  100. package/dist/assets/daemonProof-DtrL5lE5.js +0 -236
  101. package/dist/assets/daemonProof-DtrL5lE5.js.map +0 -1
  102. package/dist/assets/endpoint-BdaeBw2L.js.map +0 -1
  103. package/dist/assets/envelope-Dt75vrmY.js.map +0 -1
  104. package/dist/assets/fileBytesIdb-DZcESfTt.js +0 -2
  105. package/dist/assets/groupFiles-FXel6zIc.js.map +0 -1
  106. package/dist/assets/host-DIBeK_c_.js.map +0 -1
  107. package/dist/assets/idb-BkOJES5_.js.map +0 -1
  108. package/dist/assets/irohWeb-BSv_BWyG.js.map +0 -1
  109. package/dist/assets/main-BbhfMTt8.js.map +0 -1
  110. package/dist/assets/networkReason-BncJ9KSM.js +0 -154
  111. package/dist/assets/networkReason-BncJ9KSM.js.map +0 -1
  112. package/dist/assets/ownDid-D8z5gwGI.js.map +0 -1
  113. package/dist/assets/profiles-MFtCmJwK.js.map +0 -1
  114. package/dist/assets/registry-B2Dtnibo.js.map +0 -1
  115. package/dist/assets/server-Dw1o8z1o.js.map +0 -1
  116. package/dist/assets/src-BD8RBVEp.js.map +0 -1
  117. package/dist/assets/translate-D1uP0q32.js.map +0 -1
  118. package/dist/assets/words-DdXPkB3n.js.map +0 -1
@@ -1,17 +1,17 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $a as replySnippet, $l as readTurnPacket, $r as readPin, $s as sealHandoffPiece, $t as SEPOLIA_TEST_USDT, A as knockIdentity, Aa as EDIT_RATE_WINDOW_MS, Ac as REQUEST_LIFETIME_MS, Al as inviteLink, An as fedimintRequestPayload, Ao as rosterAdmin, Ar as pickHubs, As as handoffCancelFrame, Au as verify, Ba as COMMUNITY_REACTION_FRAME, Bc as readLinkRecord, Bl as devicePingFrame, Bn as stripPictureMetadata, Bo as DHT_POLL_INTERVALS, Br as transferEnded, Bs as handoffReleaseFrame, Bu as utf8Decode, C as communityHasFrame, Cc as inboxRecord, Ci as HoldRefusedError, Cl as createDeviceInvite, Co as shownTime, Cr as doorHubs, Cs as HANDOFF_VERIFIED, D as decodeGroupEntryLink, Dc as takeRequest, Dl as createChatInvite, Dn as decodeBolt11, Do as MEMBER_KEY, Dr as mergeBeacon, Ds as handoffAttemptFailed, Du as identityFromSeed, Ec as settleRequest, Ei as readManifest, El as OwnInviteError, Er as lobbyRecords, Es as handoffAttemptAllowed, Eu as createIdentity, F as GroupWakeLimiter, Fc as linkRecords, Fl as HANDOFF_CAPABILITY, Fo as RatchetBox, Fr as shouldBeHub, Fs as handoffEphemeral, Fu as fromBase64Url, Ga as queueReaction, Gc as APP_ICON_PATH, Gl as TURN_RAISE_READ_TIMEOUT_MS, Gn as PAIRED_FRAME_TOO_LARGE, Go as presenceSeenAt, Gs as readHandoffAck, Gt as encodeDidDhtDeactivated, H as GroupSession, Ha as REACTION_LIMITS, Hc as seenEntry, Hi as DHT_TEXT_CAPABILITY, Hl as seedSigner, Hn as GhostLink, Ho as PRESENCE_WINDOW, Hs as handoffStreamKey, I as groupWakeFrame, Ic as makeStampPaced, Il as deviceEchoFrame, Io as emptyRatchetState, Ir as ChatFiles, Is as handoffHelloFrame, J as parseCommunityEdit, Ja as readReaction, Jc as appViewOf, Jl as turnPutSummary, Jn as EngineError, Jo as parseLocalTarget, Jr as PIN_LIMITS, Js as readHandoffHave, Jt as signDidDhtPacket, K as GROUP_EDIT_TEXT_BYTES, Ka as reactionEmoji, Kl as TURN_SETTLE_MS, Kn as pairedMessageFits, Ko as GhostlyHttpError, Kr as typingActivity, Ks as readHandoffCancel, Kt as encodeDidDhtPacket, L as groupWakes, La as parseLinkPreview, Lc as mergeContactKnocks, Ll as deviceEchoNonce, Ln as NO_PICTURE_METADATA, Lo as ratchetSessionOf, Lr as FILE_LIMITS, Ls as handoffManifestFrames, Lu as randomBytes, M as mergeKnocks, Ma as REMOVED_TEXT, Mc as knockSlotIdentity, Mn as isFederationId, Mo as verifyCommitSignature, Mr as readBeacon, Ms as handoffContextProof, Mu as sanitizeAvatar, N as readKnocks, Na as RateWindow, Nc as knockSlotOf, Nl as DEVICES_CAPABILITY, Nn as parseCashuRequestPayload, No as edgeParams, Nr as readBeaconHead, Ns as handoffDataFrame, Nu as sanitizeDisplayText, O as encodeGroupEntryLink, Oa as parseVideoMeta, Oc as turnOff, Ol as decodeInviteCode, On as ENDPOINT, Oo as commitHash, Or as mergeLobby, Os as handoffAttemptSucceeded, Ou as identityFromSeedB64, Pa as dhtEditId, Pc as knockSlotRecords, Pl as ENROLL_CAPABILITY, Pn as parseFedimintRequestPayload, Po as RATCHET_CAPABILITY, Pr as readLobby, Ps as handoffDigest, Pu as bytesEqual, Qa as readReply, Qc as pacer, Ql as nextTurnPosition, Qn as GROUP_FILE_LIMITS, Qo as encodeControl, Qr as pinNumberHolds, Qs as readHandoffVerified, Qt as PaymentPreflightError, R as parseGroupWakeFrame, Ra as forwardedAgain, Rc as openRequest, Rl as deviceKeyZ32, Rn as PICTURE_METADATA_LIMITS, Ro as DirectPathWatch, Rs as handoffOfferFrame, Ru as toBase64Url, S as GROUP_READ_NOTE_COMMUNITY, Sc as endedRequests, Si as HoldKeys, Sl as readContactLink, So as receivedTimestamp, Sr as beaconRecords, Ss as HANDOFF_TIMINGS, Su as createRelayPayload, T as encodeCommunityLink, Ta as parseVoiceMeta, Tc as planKnocks, Ti as newMailbox, Tl as readDeviceInvite, To as GROUP_MEMBER_CAP, Tr as lobbyKeys, Ts as filePartName, U as frameBytes, Ua as ReactionWindow, Uc as APP_BUNDLE_LIMITS, Ui as capsDescriptors, Ul as webCryptoSigner, Un as INVITE_TAKEN, Uo as RELAY_POLL_INTERVALS, Us as handoffVersions, Ut as didDhtDocument, V as GROUP_READ_NOTE, Va as GROUP_REACTION_FRAME, Vc as requestRecords, Vi as CapsExchange, Vl as newDeviceSetSecret, Vr as transferStalled, Vs as handoffRetryAfter, Vu as utf8Encode, Wa as nextReactionNumber, Wc as APP_BUNDLE_MAGIC, Wi as dialDescriptors, Wn as LIVENESS_PING_MS, Wo as WATCH_PEER_MS, Wr as TypingSender, Ws as newHandoffId, Wt as didDhtFromPublicKey, X as groupName, Xa as wireReaction, Xl as TURN_MAX, Xn as engineText, Xo as LIMITS, Xr as nextPinNumber, Xs as readHandoffPake, Xt as EVM_TEST_CHAINS, Y as mentionsMember, Ya as validReactionNumber, Yl as TURN_LAST_SEQUENCE, Yn as engineError, Yo as webLocalFetch, Yr as mayPin, Ys as readHandoffHello, Yt as ETHEREUM_USDT, Za as pairedReplyAuthor, Zc as isAppUrl, Zi as emptyIdentityLedger, Zl as firstDeviceSetSecret, Zn as parseEngineError, Zo as decodeControl, Zr as pinIsNewer, Zs as readHandoffTurnFrame, Zt as ONCHAIN_PROVIDER, _ as groupTypingEpoch, _a as sanitizeFileName, _c as enrollProofFrame, _i as STATUS_CARD_CAPABILITY, _l as canonicalJson, _r as mayBeHub, _s as HANDOFF_HELLO, _t as normalizeAtprotoHandle, _u as budgetRetryMs, a as appRevocationFor, aa as emptyProofLedger, ac as signTombstone, ai as relayRequest, al as appRef, an as assertTokenUnits, ar as readGroupFileMeta, as as contactRtcConfig, au as turnStatedVerifier, b as COMMUNITY_LIMITS, bc as verifyEnrollProof, bi as HOLD_DATED_BACK_MS, bl as createContactLink, bo as claimedTime, br as COMMUNITY_TOPOLOGY, bs as HANDOFF_PIECE_BYTES, bu as PacketTooLargeError, c as checkAppBeforeRun, ca as automaticTransport, ci as vapidKeysMatch, cl as isAppKey, cn as validatePaymentTarget, co as STATUS_CARD_LIMITS, dc as enrollCancelFrame, dn as SPARK_PROVIDER, ds as LEGACY_SERVICES, ei as WAKE_CALL_INTERVAL_MS, el as readAppBundleAsync, eo as BUTTON_ID, es as RTC_CONFIG, eu as signTurnPacket, fa as DHT_MESSAGE_TTL, fc as enrollCancelReason, fi as chatAppId, fn as sparkAddressKind, fs as serviceIdFromName, g as GroupTypingBoard, ga as formatFileSize, gc as enrollHelloFrame, gi as EDIT_CAPABILITY, gn as isPubkyKey, go as sameButtonText, gr as MESH_HUBS, gs as HANDOFF_HAVE, gt as isAtprotoDid, gu as traceLink, ha as dhtFileId, hc as enrollGrantFrame, hi as BUTTONS_CAPABILITY, hl as parseImageMeta, ho as checkStatusCard, hr as readGroupSignal, hs as HANDOFF_DONE, i as addedAppPermissions, ia as PeerProofs, ic as setUpdateFrame, ii as parseWakeFrame, il as appFingerprint, in as arkAddressPrefix, iu as turnName, j as knockRecords, ja as MAX_REMOVAL_NUMBER, jc as contactDay, jl as inviteOwnership, jn as findEndpoint, jo as rosterHas, jr as rankHubs, js as handoffContext, k as entryParams, ka as EDIT_BUFFER_MS, kc as ContactRequestError, kl as encodeInviteCode, kn as cashuRequestPayload, ko as parseGroupCommit, kr as newerHead, ks as handoffBusyFrame, ku as publicKeyFromZ32, l as planAppUpdate, li as APP_RANGE_LIMITS, ll as isAppRef, ln as walletNetworkOf, lr as CarriedTransport, ls as emptyLinkRecords, ma as DHT_FILE_CAPABILITY, mc as enrollDoneFrame, mi as APPS_CAPABILITY, mn as isBitcoinAddress, mr as groupSignalFrame, ms as HANDOFF_CANCEL, mu as normalizeRelayUrl, n as readX401SdJwtVc, nc as readSetUpdate, ni as deviceWakeRequest, nn as USDT_PUBLIC_RPC, nu as turnInstance, o as appStoreDecision, oa as validExternalKey, oc as verifySetUpdate, oi as wakeRequest, on as assertWholeSats, ou as turnVerifierMark, p as readAppStoreSteps, pa as peekDhtMailbox, pc as enrollDigits, pi as isAppVersion, pn as sparkInvoiceDetails, ps as HANDOFF_ACK, pu as currentRelays, q as carryMentions, qa as reactionIsNewer, qc as appDigest, ql as classifyTurnRead, qn as pairedMessageFrame, qo as formatLocalTarget, qs as readHandoffDone, r as sameX401HolderJwk, ra as lastSharedWithMe, rc as setAckFrame, ri as newWakeToken, rl as APP_STATEMENT_LIMITS, rn as WALLET_NETWORKS, rr as groupFileFallback, ru as turnKeys, s as appUpdateDecision, sa as TRANSPORTS, si as checkPushEndpoint, sl as isAppHash, sn as formatPaymentAmount, ss as parseCallSignal, su as DEFAULT_RELAYS, t as newX401HolderKey, ta as receivedIdentityStatus, ti as WakeLimiter, tl as sha256Paced, tn as TEST_USDT_FAUCET_AMOUNT, tu as signTurnRelease, u as APP_STORE_LIMITS, ui as isServeId, ul as readAppRevocation, un as SPARK_NETWORKS, us as HTTP_SERVICE_PROTO, uu as RelayTransport, v as openGroupTyping, va as sanitizeMime, vc as readEnrollGrant, vi as UPGRADE_CAPABILITY, vo as statusCardText, vr as meshHubs, vs as HANDOFF_OFFER, vu as isDiscoveryBudgetError, w as decodeCommunityLink, wa as fileMessageText, wc as newInbox, wi as isHoldUrl, wl as deviceInviteJoinerParams, wo as GROUP_ADMIN_OFF_ERROR, wr as freshHubs, ws as NO_ATTEMPTS, x as CommunitySession, xc as clearMissed, xi as HOLD_LIMITS, xl as encodeContactLink, xo as heardTime, xr as beaconKeys, xs as HANDOFF_REQUEST, y as sealGroupTyping, yc as readEnrollHello, yi as HOLD_CAPABILITY, yl as readCanonicalJson, yo as arrivalKey, yr as pickMeshHubs, ys as HANDOFF_PAKE, yu as withRequestOptions, z as GROUP_LIMITS, za as readForwarded, zc as readKnockSlot, zl as deviceLinkPairing, zn as isStrippedPicture, zr as sentWhole, zs as handoffPakeFrame, zu as toZ32 } from "./src-BD8RBVEp.js";
2
+ import { $a as validReactionNumber, $c as APP_BUNDLE_MAGIC, $i as newMailbox, $l as seedSigner, $n as parseEngineError, $o as parseLocalTarget, $r as pinIsNewer, $s as readHandoffCancel, $t as PaymentPreflightError, A as knockIdentity, Ac as inboxRecord, Al as readCanonicalJson, An as cashuRequestPayload, Ar as mergeLobby, As as HANDOFF_VERIFIED, Au as withRequestOptions, Bc as contactDay, Bi as emptyProofLedger, Bl as encodeInviteCode, Bn as PICTURE_METADATA_LIMITS, Bo as emptyRatchetState, Bs as handoffDataFrame, Bu as publicKeyFromZ32, C as communityHasFrame, Cc as enrollHelloFrame, Ci as capsDescriptors, Co as arrivalKey, Cr as beaconKeys, Cs as HANDOFF_HAVE, D as decodeGroupEntryLink, Dc as verifyEnrollProof, Do as shownTime, Dr as lobbyKeys, Ds as HANDOFF_PIECE_BYTES, Du as traceLink, Ec as readEnrollHello, El as parseImageMeta, Eo as receivedTimestamp, Er as freshHubs, Es as HANDOFF_PAKE, F as GroupWakeLimiter, Fa as MAX_REMOVAL_NUMBER, Fc as turnOff, Fl as deviceInviteJoinerParams, Fn as parseFedimintRequestPayload, Fo as rosterHas, Fr as readBeaconHead, Fs as handoffAttemptSucceeded, Ga as GROUP_REACTION_FRAME, Gc as makeStampPaced, Gl as ENROLL_CAPABILITY, Gn as INVITE_TAKEN, Go as DHT_POLL_INTERVALS, Gs as handoffOfferFrame, Gt as didDhtFromPublicKey, Gu as bytesEqual, H as GroupSession, Ha as forwardedAgain, Hc as knockSlotOf, Hi as TRANSPORTS, Hl as inviteOwnership, Hn as stripPictureMetadata, Ho as DirectPathWatch, Hr as transferEnded, Hs as handoffEphemeral, I as groupWakeFrame, Ia as REMOVED_TEXT, Ic as ContactRequestError, Ii as receivedIdentityStatus, Il as readDeviceInvite, Io as verifyCommitSignature, Ir as readLobby, Is as handoffBusyFrame, J as meshMessageRef, Ja as nextReactionNumber, Jc as readKnockSlot, Ji as HOLD_DATED_BACK_MS, Jl as deviceEchoNonce, Jn as pairedMessageFits, Jo as RELAY_POLL_INTERVALS, Jr as typingActivity, Js as handoffRetryAfter, Ju as randomBytes, K as GROUP_EDIT_TEXT_BYTES, Ka as REACTION_LIMITS, Kc as mergeContactKnocks, Kl as HANDOFF_CAPABILITY, Kn as LIVENESS_PING_MS, Kr as TypingSender, Ks as handoffPakeFrame, Kt as encodeDidDhtDeactivated, Ku as fromBase64Url, L as groupWakes, La as RateWindow, Lc as REQUEST_LIFETIME_MS, Ll as OwnInviteError, Ln as videoMetadataPatches, Lo as edgeParams, Lr as shouldBeHub, Ls as handoffCancelFrame, Lu as createIdentity, M as mergeKnocks, Ma as parseVideoMeta, Mc as planKnocks, Ml as encodeContactLink, Mn as findEndpoint, Mo as commitHash, Mr as pickHubs, Ms as filePartName, N as readKnocks, Na as EDIT_BUFFER_MS, Nc as settleRequest, Nl as readContactLink, Nn as isFederationId, No as parseGroupCommit, Nr as rankHubs, Ns as handoffAttemptAllowed, Nu as createRelayPayload, O as encodeGroupEntryLink, Oa as fileMessageText, Oc as clearMissed, Ol as canonicalJson, On as decodeBolt11, Oo as GROUP_ADMIN_OFF_ERROR, Or as lobbyRecords, Os as HANDOFF_REQUEST, Ou as budgetRetryMs, Pa as EDIT_RATE_WINDOW_MS, Pc as takeRequest, Pl as createDeviceInvite, Pn as parseCashuRequestPayload, Po as rosterAdmin, Pr as readBeacon, Ps as handoffAttemptFailed, Qa as readReaction, Qc as APP_BUNDLE_LIMITS, Qi as isHoldUrl, Ql as newDeviceSetSecret, Qn as engineText, Qo as formatLocalTarget, Qr as nextPinNumber, Qs as readHandoffAck, Qt as ONCHAIN_PROVIDER, Qu as utf8Encode, R as parseGroupWakeFrame, Ra as dhtEditId, Rc as contactAskerFrame, Ri as lastSharedWithMe, Rl as createChatInvite, Rn as withoutVideoMetadata, Ro as RATCHET_CAPABILITY, Rr as ChatFiles, Rs as handoffContext, Ru as identityFromSeed, S as GROUP_READ_NOTE_COMMUNITY, Sa as sanitizeMime, Sc as enrollGrantFrame, Si as DHT_TEXT_CAPABILITY, So as statusCardText, Sr as COMMUNITY_TOPOLOGY, Ss as HANDOFF_DONE, T as encodeCommunityLink, Tc as readEnrollGrant, To as heardTime, Tr as doorHubs, Ts as HANDOFF_OFFER, Tu as normalizeRelayUrl, U as frameBytes, Ua as readForwarded, Uc as knockSlotRecords, Ui as automaticTransport, Ur as transferStalled, Us as handoffHelloFrame, Uu as sanitizeAvatar, V as GROUP_READ_NOTE, Va as parseLinkPreview, Vc as knockSlotIdentity, Vi as validExternalKey, Vl as inviteLink, Vn as isStrippedPicture, Vo as ratchetSessionOf, Vr as sentWhole, Vs as handoffDigest, Vu as verify, Wa as COMMUNITY_REACTION_FRAME, Wc as linkRecords, Wl as DEVICES_CAPABILITY, Wn as GhostLink, Ws as handoffManifestFrames, Wt as didDhtDocument, Wu as sanitizeDisplayText, X as mentionsMember, Xa as reactionEmoji, Xc as requestRecords, Xi as HoldKeys, Xl as deviceLinkPairing, Xn as EngineError, Xo as presenceSeenAt, Xr as PIN_LIMITS, Xs as handoffVersions, Xt as ETHEREUM_USDT, Xu as toZ32, Y as parseCommunityEdit, Ya as queueReaction, Yc as readLinkRecord, Yi as HOLD_LIMITS, Yl as deviceKeyZ32, Yn as pairedMessageFrame, Yo as WATCH_PEER_MS, Ys as handoffStreamKey, Yt as signDidDhtPacket, Yu as toBase64Url, Z as groupName, Za as reactionIsNewer, Zc as seenEntry, Zi as HoldRefusedError, Zl as devicePingFrame, Zn as engineError, Zo as GhostlyHttpError, Zr as mayPin, Zs as newHandoffId, Zt as EVM_TEST_CHAINS, Zu as utf8Decode, _ as groupTypingEpoch, _a as peekDhtMailbox, _i as BUTTONS_CAPABILITY, _l as isAppHash, _n as isPubkyKey, _r as readGroupSignal, _s as HTTP_SERVICE_PROTO, _t as isAtprotoDid, _u as turnVerifierMark, a as appRevocationFor, ac as readHandoffVerified, ai as newWakeToken, an as arkAddressPrefix, ar as groupFileFallback, au as turnPutSummary, b as COMMUNITY_LIMITS, ba as formatFileSize, bc as enrollDigits, bi as UPGRADE_CAPABILITY, bl as readAppRevocation, bo as sameButtonText, br as meshHubs, bs as HANDOFF_ACK, c as checkAppBeforeRun, ci as wakeRequest, cn as formatPaymentAmount, cu as firstDeviceSetSecret, dc as setUpdateFrame, di as APP_RANGE_LIMITS, dn as SPARK_NETWORKS, dr as CarriedTransport, du as signTurnPacket, ea as readManifest, ec as readHandoffDone, ei as pinNumberHolds, el as APP_ICON_PATH, en as SEPOLIA_TEST_USDT, eo as wireReaction, er as GROUP_FILE_LIMITS, es as webLocalFetch, eu as webCryptoSigner, fc as signTombstone, fi as isServeId, fl as APP_STATEMENT_LIMITS, fn as SPARK_PROVIDER, fo as STATUS_CARD_LIMITS, fs as contactRtcConfig, fu as signTurnRelease, g as GroupTypingBoard, ga as DHT_MESSAGE_TTL, gi as APPS_CAPABILITY, gr as groupSignalFrame, gs as emptyLinkRecords, gu as turnStatedVerifier, hi as isAppVersion, hl as appRefPublisher, hn as isBitcoinAddress, hu as turnName, i as addedAppPermissions, ic as readHandoffTurnFrame, ii as deviceWakeRequest, in as WALLET_NETWORKS, io as BUTTON_ID, iu as classifyTurnRead, j as knockRecords, jc as newInbox, ji as emptyIdentityLedger, jl as createContactLink, jn as fedimintRequestPayload, jo as MEMBER_KEY, jr as newerHead, js as NO_ATTEMPTS, ju as PacketTooLargeError, k as entryParams, ka as parseVoiceMeta, kc as endedRequests, kn as ENDPOINT, ko as GROUP_MEMBER_CAP, kr as mergeBeacon, ks as HANDOFF_TIMINGS, ku as isDiscoveryBudgetError, l as planAppUpdate, lc as readSetUpdate, li as checkPushEndpoint, ll as readAppBundleAsync, ln as validatePaymentTarget, lu as nextTurnPosition, mi as chatAppId, ml as appRef, mn as sparkInvoiceDetails, ms as parseCallSignal, mu as turnKeys, n as readX401SdJwtVc, nc as readHandoffHello, ni as WAKE_CALL_INTERVAL_MS, nl as appDigest, nn as TEST_USDT_FAUCET_AMOUNT, no as readReply, ns as decodeControl, nu as TURN_RAISE_READ_TIMEOUT_MS, o as appStoreDecision, oc as sealHandoffPiece, oi as parseWakeFrame, ol as isAppUrl, on as assertTokenUnits, ou as TURN_LAST_SEQUENCE, p as readAppStoreSteps, pc as verifySetUpdate, pl as appFingerprint, pn as sparkAddressKind, pu as turnInstance, q as carryMentions, qa as ReactionWindow, qc as openRequest, qi as HOLD_CAPABILITY, ql as deviceEchoFrame, qn as PAIRED_FRAME_TOO_LARGE, qo as PRESENCE_WINDOW, qs as handoffReleaseFrame, qt as encodeDidDhtPacket, r as sameX401HolderJwk, rc as readHandoffPake, ri as WakeLimiter, rl as appViewOf, rn as USDT_PUBLIC_RPC, ro as replySnippet, rs as encodeControl, ru as TURN_SETTLE_MS, s as appUpdateDecision, si as relayRequest, sl as pacer, sn as assertWholeSats, sr as readGroupFileMeta, ss as RTC_CONFIG, su as TURN_MAX, t as newX401HolderKey, tc as readHandoffHave, ti as readPin, to as pairedReplyAuthor, tr as GROUP_HAVE_FRAME, ts as LIMITS, u as APP_STORE_LIMITS, uc as setAckFrame, ui as vapidKeysMatch, ul as sha256Paced, un as walletNetworkOf, uu as readTurnPacket, v as openGroupTyping, va as DHT_FILE_CAPABILITY, vc as enrollCancelFrame, vi as EDIT_CAPABILITY, vl as isAppKey, vr as MESH_HUBS, vs as LEGACY_SERVICES, vt as normalizeAtprotoHandle, vu as DEFAULT_RELAYS, w as decodeCommunityLink, wc as enrollProofFrame, wi as dialDescriptors, wo as claimedTime, wr as beaconRecords, ws as HANDOFF_HELLO, wu as currentRelays, x as CommunitySession, xa as sanitizeFileName, xc as enrollDoneFrame, xi as CapsExchange, xl as readAppRevocationShape, xr as pickMeshHubs, xs as HANDOFF_CANCEL, xu as RelayTransport, y as sealGroupTyping, ya as dhtFileId, yc as enrollCancelReason, yi as STATUS_CARD_CAPABILITY, yl as isAppRef, yo as checkStatusCard, yr as mayBeHub, ys as serviceIdFromName, z as GROUP_LIMITS, zc as contactAskerHolds, zi as PeerProofs, zl as decodeInviteCode, zn as NO_PICTURE_METADATA, zo as RatchetBox, zr as FILE_LIMITS, zs as handoffContextProof, zu as identityFromSeedB64 } from "./src-CCt5s4DK.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-CzX3xH47.js";
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-BkOJES5_.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-BncJ9KSM.js";
8
- import { $ as ModeChanged, A as IdentityProofs, B as INVOICE_PACE, C as FileAppender, D as streamStored, E as storedSize, F as LightningCards, G as cashuMint, H as ProviderSources, I as cardsKey, J as breezDatabasesFor, K as breezDatabase, L as isRecoveryPhrase, M as sealSecret, N as whenDataKeyDropped, P as CASHU_CARD, Q as relayOnlyProblem, R as normalizePhrase, S as WALLET_TYPES, T as removeStored, U as sourceKey, V as nextInvoiceAsk, W as CASHU_MINT_SOURCE, X as iceServerProblem, Y as dropBreezDatabase, Z as iceServerSetting, _ as crossNetwork, a as storedGroupFiles, at as requireTurn, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as ModeGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as refuseAway, j as openSecret, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as networkLabel, o as groupReply, ot as setAwayWallets, p as WALLET_NAMES, q as breezDatabaseInUse, r as groupFileText, rt as awayFrom, s as pairedWireReply, st as setSingleWriterGate, t as GroupFileDesk, tt as WrongNetworkError, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as lightningPaying } from "./groupFiles-FXel6zIc.js";
9
- import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-BSv_BWyG.js";
5
+ import { t as nwc } from "./nwcProvider-CGWqUjpB.js";
6
+ import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BHsAqENE.js";
7
+ import { a as sealSeed, c as openRow, d as sealedStore, f as openSecret, i as newDeviceKey, l as openRows, m as whenDataKeyDropped, o as unsealSeed, p as sealSecret, r as intentRepository, s as RowSeals, u as sealRow } from "./networkReason-DT_D_Wpc.js";
8
+ import { $ as WrongNetworkError, A as IdentityProofs, B as ProviderSources, C as FileAppender, D as streamStored, E as storedSize, F as normalizePhrase, G as breezDatabaseInUse, H as CASHU_MINT_SOURCE, I as journaledPayment, J as iceServerProblem, K as breezDatabasesFor, L as lightningPaying, M as LightningCards, N as cardsKey, P as isRecoveryPhrase, Q as ModeGate, R as INVOICE_PACE, S as WALLET_TYPES, T as removeStored, U as cashuMint, V as sourceKey, W as breezDatabase, X as relayOnlyProblem, Y as iceServerSetting, Z as ModeChanged, _ as crossNetwork, a as storedGroupFiles, at as setSingleWriterGate, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as networkLabel, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as setAwayWallets, j as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as refuseAway, o as groupReply, p as WALLET_NAMES, q as dropBreezDatabase, r as groupFileText, rt as requireTurn, s as pairedWireReply, t as GroupFileDesk, tt as awayFrom, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as nextInvoiceAsk } from "./groupFiles-BAQIt_bJ.js";
9
+ import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-D2sh6EWp.js";
10
10
  import { c as isTestMint, d as mintUrlSpelling, f as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
11
- import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-D8z5gwGI.js";
12
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-Dt75vrmY.js";
13
- import { d as chosenResolver, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-ZxVzwFNA.js";
14
- import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-DNgrRL0R.js";
11
+ import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-CbGjRLBn.js";
12
+ import { d as chosenResolver, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-D-9YRFhl.js";
13
+ import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-DjBYYyXT.js";
14
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-CMUgz31I.js";
15
15
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-1wzya_0L.js";
16
16
  import { sha256 } from "@noble/hashes/sha2.js";
17
17
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -199,7 +199,7 @@ function viewNews(before, after) {
199
199
  //#endregion
200
200
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
201
201
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
202
- var loadUsdt = () => import("./usdt-DhVN8geQ.js");
202
+ var loadUsdt = () => import("./usdt-ds461mzA.js");
203
203
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
204
204
  var DEFAULT_USDT = {
205
205
  network: "ethereum",
@@ -686,7 +686,7 @@ async function restoreArkDatabase(walletId, snapshot) {
686
686
  //#endregion
687
687
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
688
688
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
689
- var loadArkade = () => import("./arkade-DtYR9H0c.js");
689
+ var loadArkade = () => import("./arkade-zozCldAE.js");
690
690
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
691
691
  var RETIRE_READ_MS = 1e4;
692
692
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -2414,15 +2414,25 @@ var FedimintWallet = class {
2414
2414
  }
2415
2415
  return null;
2416
2416
  }
2417
- /** Redeems notes into the federation that issued them. `done` once the ecash is ours; `failed` when they were spent. */
2417
+ /**
2418
+ * Redeems notes into the federation that issued them. `done` once the ecash is ours; `failed` when they were spent.
2419
+ * `error`: the redeem was asked for, but the client could not say how it stands (its operation is kept, to ask again).
2420
+ */
2418
2421
  async redeemNotes(federationId, notes, ghostly, waitMs = 6e4) {
2419
2422
  const client = this.client(federationId);
2420
2423
  const operationId = await client.redeem(notes.trim(), ghostly);
2421
- const state = await client.redeemState(operationId, waitMs);
2424
+ const { state, error } = await client.redeemState(operationId, waitMs).then((state) => ({
2425
+ state,
2426
+ error: void 0
2427
+ }), (e) => ({
2428
+ state: void 0,
2429
+ error: e instanceof Error ? e.message : String(e)
2430
+ }));
2422
2431
  this.refresh();
2423
2432
  return {
2424
2433
  operationId,
2425
- state
2434
+ state,
2435
+ error
2426
2436
  };
2427
2437
  }
2428
2438
  async redeemState(federationId, operationId, waitMs) {
@@ -2432,7 +2442,8 @@ var FedimintWallet = class {
2432
2442
  async receiveNotes(notes) {
2433
2443
  const found = await this.inspectNotes(notes);
2434
2444
  if (!found) throw new Error(this.clients.size ? "These notes are not from a federation you joined in this wallet" : "Join the federation these notes are from first");
2435
- const { state } = await this.redeemNotes(found.federation, notes, `wallet-${crypto.randomUUID()}`);
2445
+ const { state, error } = await this.redeemNotes(found.federation, notes, `wallet-${crypto.randomUUID()}`);
2446
+ if (error !== void 0) throw engineError("fedimintRedeemUnheard");
2436
2447
  if (state === "failed") throw new Error("These notes were already redeemed by someone");
2437
2448
  if (state !== "done") throw new Error("The federation is still redeeming these notes: they will show in the balance");
2438
2449
  return {
@@ -6265,7 +6276,7 @@ function networkNamed(name) {
6265
6276
  /** Mutinynet is a signet: its invoices say `lntbs`, like any signet's. */
6266
6277
  var sameChain = (a, b) => a === b || a === "mutinynet" && b === "signet";
6267
6278
  /** Calls the wallet, bounded in time and ended by the source's signal. A wallet that throws at once rejects too. */
6268
- function within$2(call, ms, what, signal) {
6279
+ function within$3(call, ms, what, signal) {
6269
6280
  return new Promise((resolve, reject) => {
6270
6281
  const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`The browser wallet did not answer (${what})`)), ms);
6271
6282
  const abort = () => reject(/* @__PURE__ */ new Error("The browser wallet was disconnected"));
@@ -6318,17 +6329,17 @@ var WeblnLightning = class WeblnLightning {
6318
6329
  static async connect(webln, mode, signal) {
6319
6330
  if (!webln) throw new Error("No WebLN wallet in this browser. Install or unlock one (Alby, for example), then connect again");
6320
6331
  try {
6321
- const answer = await within$2(() => webln.enable(), PROMPT_MS, "connect", signal);
6332
+ const answer = await within$3(() => webln.enable(), PROMPT_MS, "connect", signal);
6322
6333
  if (answer && typeof answer === "object" && answer.enabled === false) throw new Error("not enabled");
6323
6334
  } catch (error) {
6324
6335
  if (signal?.aborted) throw error;
6325
6336
  throw Object.assign(/* @__PURE__ */ new Error(`The browser wallet refused the connection (${message$1(error)})`), { cause: error });
6326
6337
  }
6327
- const info = typeof webln.getInfo === "function" ? await within$2(() => webln.getInfo(), CALL_MS, "info", signal).catch(() => void 0) : void 0;
6338
+ const info = typeof webln.getInfo === "function" ? await within$3(() => webln.getInfo(), CALL_MS, "info", signal).catch(() => void 0) : void 0;
6328
6339
  const methods = Array.isArray(info?.methods) ? info.methods : void 0;
6329
6340
  const has = (method) => typeof webln[method] === "function" && (!methods || methods.includes(method));
6330
6341
  let balance = false;
6331
- if (has("getBalance")) balance = await within$2(() => webln.getBalance(), CALL_MS, "balance", signal).then((b) => sats$1(b) !== void 0, () => false);
6342
+ if (has("getBalance")) balance = await within$3(() => webln.getBalance(), CALL_MS, "balance", signal).then((b) => sats$1(b) !== void 0, () => false);
6332
6343
  const capabilities = {
6333
6344
  receive: has("makeInvoice"),
6334
6345
  send: has("sendPayment"),
@@ -6338,7 +6349,7 @@ var WeblnLightning = class WeblnLightning {
6338
6349
  if (!capabilities.receive && !capabilities.send) throw new Error("This browser wallet can neither make nor pay invoices");
6339
6350
  let network = networkNamed(info?.network) ?? networkNamed(info?.chain) ?? networkNamed(info?.node?.network);
6340
6351
  if (!network && capabilities.receive) {
6341
- const probe = await within$2(() => webln.makeInvoice({
6352
+ const probe = await within$3(() => webln.makeInvoice({
6342
6353
  amount: 1,
6343
6354
  defaultMemo: "Ghostly: which network is this wallet on?"
6344
6355
  }), CALL_MS, "invoice", signal);
@@ -6360,13 +6371,13 @@ var WeblnLightning = class WeblnLightning {
6360
6371
  return {
6361
6372
  network: this.network,
6362
6373
  alias: this.alias,
6363
- ...this.capabilities.balance ? { balance: sats$1(await within$2(() => this.webln.getBalance(), CALL_MS, "balance", this.signal)) ?? 0 } : {}
6374
+ ...this.capabilities.balance ? { balance: sats$1(await within$3(() => this.webln.getBalance(), CALL_MS, "balance", this.signal)) ?? 0 } : {}
6364
6375
  };
6365
6376
  }
6366
6377
  async createInvoice(amount, memo) {
6367
6378
  this.ready();
6368
6379
  if (!this.capabilities.receive) throw new Error("This browser wallet cannot make invoices");
6369
- const made = await within$2(() => this.webln.makeInvoice({
6380
+ const made = await within$3(() => this.webln.makeInvoice({
6370
6381
  amount,
6371
6382
  defaultMemo: memo?.slice(0, 140)
6372
6383
  }), CALL_MS, "invoice", this.signal);
@@ -6403,7 +6414,7 @@ var WeblnLightning = class WeblnLightning {
6403
6414
  if (!decoded?.paymentHash || decoded.amountSat === null) throw new Error("That is not an invoice this wallet can pay");
6404
6415
  if (!sameChain(this.network, decoded.network)) throw new Error(`That invoice is for ${decoded.network}, and this browser wallet is on ${this.network}`);
6405
6416
  if (this.capabilities.balance) {
6406
- const balance = sats$1(await within$2(() => this.webln.getBalance(), CALL_MS, "balance", this.signal));
6417
+ const balance = sats$1(await within$3(() => this.webln.getBalance(), CALL_MS, "balance", this.signal));
6407
6418
  if (balance !== void 0 && balance < decoded.amountSat) throw new Error(`Not enough in the browser wallet (${balance} sats)`);
6408
6419
  }
6409
6420
  } catch (error) {
@@ -6411,7 +6422,7 @@ var WeblnLightning = class WeblnLightning {
6411
6422
  }
6412
6423
  let answer;
6413
6424
  try {
6414
- answer = await within$2(() => this.webln.sendPayment(decoded.invoice), PROMPT_MS, "payment", this.signal);
6425
+ answer = await within$3(() => this.webln.sendPayment(decoded.invoice), PROMPT_MS, "payment", this.signal);
6415
6426
  } catch (error) {
6416
6427
  if (!this.signal?.aborted && error instanceof Error && (REFUSED_NAMES.has(error.name) || REFUSED.test(error.message) || NOT_SENT.test(error.message))) throw new NothingSpentError(`The browser wallet did not pay: ${message$1(error)}`);
6417
6428
  throw Object.assign(/* @__PURE__ */ new Error(`The browser wallet did not say whether it paid (${message$1(error)})`), { cause: error });
@@ -6438,7 +6449,7 @@ var WeblnLightning = class WeblnLightning {
6438
6449
  }
6439
6450
  async lookup(what) {
6440
6451
  if (!this.capabilities.lookup) throw new Error("This browser wallet cannot look up invoices");
6441
- const found = await within$2(() => this.webln.lookupInvoice({
6452
+ const found = await within$3(() => this.webln.lookupInvoice({
6442
6453
  paymentHash: what.paymentHash,
6443
6454
  paymentRequest: what.invoice
6444
6455
  }), CALL_MS, "lookup", this.signal);
@@ -7270,7 +7281,7 @@ var ContactLinks = class {
7270
7281
  */
7271
7282
  shown() {
7272
7283
  this.shownAt = Date.now();
7273
- this.schedulePoll(0);
7284
+ this.schedulePoll(this.pollDue());
7274
7285
  }
7275
7286
  /** Whether a link key is one of this profile's, current or turned off. */
7276
7287
  owns(linkKeyZ32) {
@@ -7292,10 +7303,14 @@ var ContactLinks = class {
7292
7303
  */
7293
7304
  accept(id) {
7294
7305
  return this.serial(async () => {
7295
- const request = this.stored.current?.requests?.find((r) => r.key === id);
7296
- if (!request) throw new Error("This request is no longer waiting");
7306
+ const current = this.stored.current;
7307
+ const request = current?.requests?.find((r) => r.key === id);
7308
+ if (!current || !request) throw new Error("This request is no longer waiting");
7297
7309
  if (request.expires <= Date.now()) throw new Error("This request expired");
7298
- const linkId = await this.host.accept(request);
7310
+ const linkId = await this.host.accept({
7311
+ ...request,
7312
+ link: request.link ?? current.linkKeyZ32
7313
+ });
7299
7314
  await this.settle(id);
7300
7315
  return { linkId };
7301
7316
  });
@@ -7304,9 +7319,19 @@ var ContactLinks = class {
7304
7319
  decline(id) {
7305
7320
  return this.serial(() => this.settle(id));
7306
7321
  }
7307
- /** Reads the knock slots once and takes what is new into Requests. */
7322
+ /**
7323
+ * Reads the knock slots once and takes what is new into Requests. Never faster than the link's fastest pace: within
7324
+ * `POLL_SHOWN_MS` of the last read, what that read took is the answer.
7325
+ */
7308
7326
  poll() {
7309
- return this.serial(() => this.take());
7327
+ return this.serial(async () => {
7328
+ if (this.pollDue() === 0) await this.take();
7329
+ });
7330
+ }
7331
+ /** How long until the knock slots may be read again. */
7332
+ pollDue() {
7333
+ const since = Date.now() - (this.stored.current?.polled ?? -Infinity);
7334
+ return since >= 0 && since < 15e3 ? POLL_SHOWN_MS - since : 0;
7310
7335
  }
7311
7336
  /** Undefined while the profile has no link. */
7312
7337
  view() {
@@ -7422,7 +7447,8 @@ var ContactLinks = class {
7422
7447
  taken.push({
7423
7448
  ...request,
7424
7449
  key,
7425
- receivedAt: now
7450
+ receivedAt: now,
7451
+ link: linkKey
7426
7452
  });
7427
7453
  }
7428
7454
  }
@@ -7435,7 +7461,8 @@ var ContactLinks = class {
7435
7461
  current: {
7436
7462
  ...latest,
7437
7463
  inbox,
7438
- requests
7464
+ requests,
7465
+ polled: now
7439
7466
  }
7440
7467
  });
7441
7468
  this.host.emit();
@@ -7593,6 +7620,15 @@ var ContactAsks = class {
7593
7620
  } catch {}
7594
7621
  });
7595
7622
  }
7623
+ /**
7624
+ * The proof that this profile asked, for the chat a request of its started (WISP 8xx § Accept): said on each live
7625
+ * session of that chat, so the owner's app shows the request's text as confirmed. Undefined for any other chat.
7626
+ */
7627
+ async proof(chatId, chat) {
7628
+ const ask = this.asks.find((a) => a.chatId === chatId);
7629
+ if (!ask) return void 0;
7630
+ return contactAskerFrame((await this.identity(ask)).seedB64, ask.link, chat);
7631
+ }
7596
7632
  /** Looks after every request not yet seen once (the timer does this at its pace). */
7597
7633
  tick() {
7598
7634
  return this.serial(() => this.look());
@@ -9186,7 +9222,7 @@ var HostNotContacted = class extends Error {};
9186
9222
  */
9187
9223
  function fixedHostsFetch(fetch) {
9188
9224
  return async (url, options) => {
9189
- const { fixedIdentityHosts } = await import("./fixedHosts-B598JzbC.js");
9225
+ const { fixedIdentityHosts } = await import("./fixedHosts-C2hdCfzK.js");
9190
9226
  const host = hostOf$1(url);
9191
9227
  if (!fixedIdentityHosts().has(host) && host !== hostOf$1("https://public.api.bsky.app") && host !== hostOf$1("https://nexus.pubky.app")) throw new HostNotContacted(`Hide my IP from contacts is on: ${host}, a server your contact chose, was not contacted`);
9192
9228
  return fetch(url, options);
@@ -9414,6 +9450,8 @@ var PublicProfiles = class {
9414
9450
  timer;
9415
9451
  /** Before the chats are loaded every contact's identity would look ineligible: nothing is pruned until then. */
9416
9452
  started = false;
9453
+ /** The engine stopped ("Clear all data" empties the stores next): an answer still on its way writes nothing. */
9454
+ stopped = false;
9417
9455
  fetch;
9418
9456
  constructor(host) {
9419
9457
  this.host = host;
@@ -9433,6 +9471,7 @@ var PublicProfiles = class {
9433
9471
  /** Starts the periodic clean-up; call once the chats are loaded, so `eligible` sees them. */
9434
9472
  start() {
9435
9473
  this.started = true;
9474
+ this.stopped = false;
9436
9475
  this.prune().catch(() => {});
9437
9476
  this.timer ??= setInterval(() => {
9438
9477
  this.prune().catch(() => {});
@@ -9441,8 +9480,10 @@ var PublicProfiles = class {
9441
9480
  stop() {
9442
9481
  if (this.timer) clearInterval(this.timer);
9443
9482
  this.timer = void 0;
9483
+ this.stopped = true;
9444
9484
  }
9445
9485
  async save() {
9486
+ if (this.stopped) return;
9446
9487
  await transact([STORES$1.settings], (stores) => {
9447
9488
  stores[STORES$1.settings].put(this.cache, KEY);
9448
9489
  });
@@ -10403,14 +10444,46 @@ async function bytesHere(file) {
10403
10444
  if (file.blob) return file.blob.size;
10404
10445
  return await (file.bytes ? await fileBytesOf(file.bytes) : null)?.size(file.id) ?? 0;
10405
10446
  }
10447
+ /** `read` with the parts `patches` replace (zeros where a patch has no bytes). */
10448
+ function patchedRead(read, patches) {
10449
+ return async (offset, length) => {
10450
+ const part = (await read(offset, length)).slice();
10451
+ const end = offset + part.length;
10452
+ for (const { start, end: until, bytes } of patches) {
10453
+ if (until <= offset || start >= end) continue;
10454
+ const from = Math.max(start, offset), to = Math.min(until, end);
10455
+ if (bytes) part.set(bytes.subarray(from - start, to - start), from - offset);
10456
+ else part.fill(0, from - offset, to - offset);
10457
+ }
10458
+ return part;
10459
+ };
10460
+ }
10406
10461
  /**
10407
- * A received picture as it goes on: without its metadata (one from an app that sent it with them keeps where its author
10408
- * took it, the device, the time), read whole; undefined for any other file, copied as it is. Refused with
10409
- * `NO_PICTURE_METADATA` when its metadata cannot be removed, as a picture sent from here is.
10462
+ * A received picture or video as it goes on: without its metadata (one from an app that sent it with them keeps where
10463
+ * its author took it, the device, the time), as one sent from here; undefined for any other file, copied as it is. A
10464
+ * picture is read whole; a video's stripped bytes are a Blob when it is kept in one, else read through the parts
10465
+ * changed. Refused with `NO_PICTURE_METADATA` or `NO_VIDEO_METADATA` when its metadata cannot be removed.
10410
10466
  */
10411
10467
  async function withoutMetadata(source, size, file, read) {
10412
- if (file.voice || file.video || !size) return void 0;
10413
- if (!isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) return void 0;
10468
+ if (file.voice || !size) return void 0;
10469
+ if (file.video || !isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) {
10470
+ if (source.blob) return withoutVideoMetadata(source.blob, file.mime);
10471
+ const readFully = async (offset, length) => {
10472
+ const whole = new Uint8Array(Math.max(0, Math.min(length, size - offset)));
10473
+ for (let at = 0; at < whole.length;) {
10474
+ const part = await read(offset + at, whole.length - at);
10475
+ if (!part.length) break;
10476
+ whole.set(part, at);
10477
+ at += part.length;
10478
+ }
10479
+ return whole;
10480
+ };
10481
+ const patches = await videoMetadataPatches({
10482
+ size,
10483
+ read: readFully
10484
+ }, file.mime);
10485
+ return patches && patchedRead(read, patches);
10486
+ }
10414
10487
  if (size > PICTURE_METADATA_LIMITS.maxBytes) throw new Error(NO_PICTURE_METADATA);
10415
10488
  const whole = new Uint8Array(size);
10416
10489
  for (let offset = 0; offset < size;) {
@@ -10423,8 +10496,9 @@ async function withoutMetadata(source, size, file, read) {
10423
10496
  }
10424
10497
  /**
10425
10498
  * A copy of a file on this device, for sending in another chat under `file.id`: a small one whole, a larger one a
10426
- * step at a time, never whole in memory; a picture without its metadata, read whole. Refused while it is still
10427
- * arriving, or when its bytes are gone. Resolves to `file` as it goes: a stripped picture's size is its copy's.
10499
+ * step at a time, never whole in memory; a picture without its metadata, read whole, and a video without its. Refused
10500
+ * while it is still arriving, or when its bytes are gone. Resolves to `file` as it goes: a stripped file's size is its
10501
+ * copy's.
10428
10502
  */
10429
10503
  async function copyForForward(sourceId, target) {
10430
10504
  const source = await fileStore.get(sourceId);
@@ -10435,7 +10509,8 @@ async function copyForForward(sourceId, target) {
10435
10509
  const from = source.bytes ? await fileBytesOf(source.bytes) : null;
10436
10510
  const read = async (offset, length) => source.blob ? new Uint8Array(await source.blob.slice(offset, offset + length).arrayBuffer()) : from.read(source.id, offset, length);
10437
10511
  const stripped = await withoutMetadata(source, stored, target.file, read);
10438
- const blob = stripped ?? source.blob, size = stripped?.size ?? stored;
10512
+ const blob = typeof stripped === "function" ? void 0 : stripped ?? source.blob, size = blob && stripped ? blob.size : stored;
10513
+ const readCopy = typeof stripped === "function" ? stripped : read;
10439
10514
  const known = stripped ? void 0 : source.digest;
10440
10515
  const { linkId, wireId, timestamp } = target, file = stripped ? {
10441
10516
  ...target.file,
@@ -10477,7 +10552,7 @@ async function copyForForward(sourceId, target) {
10477
10552
  try {
10478
10553
  const appender = new FileAppender(bytes, file.id);
10479
10554
  for (let offset = 0; offset < size;) {
10480
- const part = blob ? new Uint8Array(await blob.slice(offset, offset + 1048576).arrayBuffer()) : await read(offset, Math.min(1048576, size - offset));
10555
+ const part = blob ? new Uint8Array(await blob.slice(offset, offset + 1048576).arrayBuffer()) : await readCopy(offset, Math.min(1048576, size - offset));
10481
10556
  if (!part.length) throw new Error("The file is shorter than it says");
10482
10557
  await appender.append(part);
10483
10558
  offset += part.length;
@@ -10934,6 +11009,11 @@ var APP_CHECK_TIMINGS = {
10934
11009
  };
10935
11010
  /** Apps the update check reads at once (their publishers' files, their sources' peeks): all on the same two hosts. */
10936
11011
  var APP_CHECK_PARALLEL = 6;
11012
+ /**
11013
+ * Stores a refresh reads at once: each read is two requests (its index and `.sig`), and a store behind the copy the
11014
+ * person took reads that copy beside them, so about as many requests as the update check's apps.
11015
+ */
11016
+ var STORE_READ_PARALLEL = 4;
10937
11017
  /** Revocations are checked this long at a time before the page's thread is let go. */
10938
11018
  var REVOCATIONS_SLICE_MS = 10;
10939
11019
  /**
@@ -11008,6 +11088,32 @@ function readCount(value) {
11008
11088
  }
11009
11089
  }
11010
11090
  /**
11091
+ * `run` on every item, at most `limit` at a time (the next one starts when one ends): one promise per item, in the
11092
+ * items' order, whatever order they end in.
11093
+ */
11094
+ function pooled(items, limit, run) {
11095
+ const ends = [];
11096
+ const out = items.map((_, i) => new Promise((resolve, reject) => {
11097
+ ends[i] = {
11098
+ resolve,
11099
+ reject
11100
+ };
11101
+ }));
11102
+ let next = 0;
11103
+ const worker = async () => {
11104
+ while (next < items.length) {
11105
+ const i = next++;
11106
+ try {
11107
+ ends[i].resolve(await run(items[i]));
11108
+ } catch (error) {
11109
+ ends[i].reject(error);
11110
+ }
11111
+ }
11112
+ };
11113
+ for (let w = 0; w < Math.min(limit, items.length); w++) worker();
11114
+ return out;
11115
+ }
11116
+ /**
11011
11117
  * A listing's URLs this client reads, in order, a jsDelivr copy first: one this client reads names a full commit, so it
11012
11118
  * holds exactly the version the store reviewed, where a raw `HEAD` may have moved on to one it has not (WISP 1200 §
11013
11119
  * Stores), and a 16 MiB bundle is not downloaded only to be skipped.
@@ -11068,6 +11174,63 @@ async function noteBundles(change) {
11068
11174
  };
11069
11175
  await done(tx);
11070
11176
  }
11177
+ /**
11178
+ * The key, in `STORES.settings`, of the revocations this profile verified, by app reference (one of
11179
+ * `PROFILE_SETTINGS_KEYS`: only "Clear all data" drops them). A client keeps every revocation it verified (WISP 1200 §
11180
+ * Publisher keys): kept beside the app's record, not in it, so Uninstall leaves them and the same version from a copy at
11181
+ * another URL, with no `ghostly-revoke.json` beside it, is still refused.
11182
+ */
11183
+ var APP_REVOCATIONS_KEY = "appRevocations";
11184
+ /**
11185
+ * Revocations kept there: at most `each` of one app and `all` in all, the ones kept longest ago dropped first. A
11186
+ * revocation is at most about 3.5 KiB (64 digests and a reason).
11187
+ */
11188
+ var REVOCATIONS_KEPT = {
11189
+ each: 64,
11190
+ all: 1024
11191
+ };
11192
+ /**
11193
+ * The revocations as kept, by reference, in the order they were last added to: read with nothing taken on trust but
11194
+ * their signatures (checked before they were kept), so an entry that is not one of that app's publisher is none.
11195
+ */
11196
+ function keptRevocations(kept) {
11197
+ const out = /* @__PURE__ */ new Map();
11198
+ if (!Array.isArray(kept)) return out;
11199
+ for (const entry of kept) {
11200
+ if (!Array.isArray(entry) || !isAppRef(entry[0]) || !Array.isArray(entry[1])) continue;
11201
+ const ref = entry[0];
11202
+ const list = entry[1].flatMap((r) => {
11203
+ const read = readAppRevocationShape(r);
11204
+ return read.ok && read.revocation.statement.app === ref && read.revocation.signature.key === appRefPublisher(ref) ? [read.revocation] : [];
11205
+ });
11206
+ if (list.length) out.set(ref, list);
11207
+ }
11208
+ return out;
11209
+ }
11210
+ /** Queues, on the settings store of an open transaction, these revocations of `ref` kept with the others (each once). */
11211
+ function keepRevocations(settings, ref, add) {
11212
+ if (!add.length) return;
11213
+ const read = settings.get(APP_REVOCATIONS_KEY);
11214
+ read.onsuccess = () => {
11215
+ const kept = keptRevocations(read.result);
11216
+ const before = kept.get(ref) ?? [];
11217
+ const merged = new Map(before.map((r) => [canonicalJson(r), r]));
11218
+ for (const r of add) if (r.statement.app === ref) merged.set(canonicalJson(r), r);
11219
+ if (merged.size === before.length) return;
11220
+ kept.delete(ref);
11221
+ kept.set(ref, [...merged.values()].slice(-REVOCATIONS_KEPT.each));
11222
+ let all = 0;
11223
+ for (const list of kept.values()) all += list.length;
11224
+ for (const [other, list] of kept) {
11225
+ if (all <= REVOCATIONS_KEPT.all || other === ref) break;
11226
+ const drop = Math.min(list.length, all - REVOCATIONS_KEPT.all);
11227
+ all -= drop;
11228
+ if (drop === list.length) kept.delete(other);
11229
+ else kept.set(other, list.slice(drop));
11230
+ }
11231
+ settings.put([...kept], APP_REVOCATIONS_KEY);
11232
+ };
11233
+ }
11071
11234
  var builtInRef = (app) => appRef(app.publisher, app.name);
11072
11235
  /**
11073
11236
  * The entries of the built-in list this profile is offered (WISP 1200 § Built-in apps): each reference once, not
@@ -11262,6 +11425,11 @@ var Apps = class {
11262
11425
  * index listing the same is not peeked again at every check.
11263
11426
  */
11264
11427
  listingMisses = /* @__PURE__ */ new Map();
11428
+ /**
11429
+ * The index a store's own URL served at its last read when it was not taken (behind the copy the person took, at a
11430
+ * commit): by store key, with that URL. The same bytes there again are not checked whole at every refresh.
11431
+ */
11432
+ behindReads = /* @__PURE__ */ new Map();
11265
11433
  /** `ghostly-revoke.json` files checked, by the SHA-256 of their bytes: their revocations, or null when refused, and the bytes the held list counts for. */
11266
11434
  revocationFiles = /* @__PURE__ */ new Map();
11267
11435
  /** Revocations read in a store's index and verified, by `appRevocationId`: at most `STORE_REVOCATIONS_KEPT`. */
@@ -11291,6 +11459,11 @@ var Apps = class {
11291
11459
  nowS() {
11292
11460
  return Math.floor(this.now() / 1e3);
11293
11461
  }
11462
+ /** Checked less than `ms` ago. A mark ahead of the clock (the clock went back since) is not recent: it would stay so until the clock caught up. */
11463
+ checkedWithin(at, ms) {
11464
+ const age = at === void 0 ? -1 : this.now() - at;
11465
+ return age >= 0 && age < ms;
11466
+ }
11294
11467
  /**
11295
11468
  * Preloads the default stores (no request) and removes the bundles no record names (`sweepBundles`), then checks for
11296
11469
  * updates soon after start and every 24 hours.
@@ -11321,7 +11494,7 @@ var Apps = class {
11321
11494
  if (this.stopped) return;
11322
11495
  if (this.host.online()) {
11323
11496
  const apps = await this.installed();
11324
- const fresh = atStart && apps.length > 0 && apps.every((a) => a.checkedAt !== void 0 && this.now() - a.checkedAt < APP_CHECK_TIMINGS.freshMs);
11497
+ const fresh = atStart && apps.length > 0 && apps.every((a) => this.checkedWithin(a.checkedAt, APP_CHECK_TIMINGS.freshMs));
11325
11498
  if (apps.length && !fresh) await this.checkUpdates().catch(() => {});
11326
11499
  }
11327
11500
  if (!this.stopped) this.schedule(APP_CHECK_TIMINGS.everyMs);
@@ -11371,6 +11544,10 @@ var Apps = class {
11371
11544
  async builtInMarks() {
11372
11545
  return builtInMarks(await wrap((await store(STORES$1.settings, "readonly")).get(BUILT_IN_APPS_KEY)));
11373
11546
  }
11547
+ /** The revocations of this app this profile verified and keeps (`APP_REVOCATIONS_KEY`), installed or not. */
11548
+ async keptRevocationsOf(ref) {
11549
+ return keptRevocations(await wrap((await store(STORES$1.settings, "readonly")).get("appRevocations"))).get(ref) ?? [];
11550
+ }
11374
11551
  /**
11375
11552
  * The built-in apps this profile is offered (WISP 1200 § Built-in apps): shown with the installed ones, with nothing
11376
11553
  * stored and nothing granted. Opening one is an install like any other, from the bundle the build carries.
@@ -11484,14 +11661,18 @@ var Apps = class {
11484
11661
  * Writes an app's record back only while it is still the record `was` (`sameRecord`), read and written in one
11485
11662
  * transaction: an app uninstalled (or installed again) while the update check was reading is not put back, nor is the
11486
11663
  * version it read over an update the person accepted meanwhile. `was` undefined: only while the app has no record.
11664
+ * A store removed since the caller read the stores pins nothing: it is judged at the write, as `removeStore` unpins
11665
+ * only the records written before it.
11487
11666
  */
11488
11667
  async putAppIfUnchanged(app, was) {
11668
+ const stores = await this.records();
11489
11669
  const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
11490
11670
  let put = false;
11491
11671
  const read = tx.objectStore(STORES$1.apps).get(app.ref);
11492
11672
  read.onsuccess = () => {
11493
11673
  if (!sameRecord(read.result, was)) return;
11494
- tx.objectStore(STORES$1.apps).put(app);
11674
+ const { store: pin, ...unpinned } = app;
11675
+ tx.objectStore(STORES$1.apps).put(pin !== void 0 && stores.get(pin)?.removed ? unpinned : app);
11495
11676
  put = true;
11496
11677
  };
11497
11678
  try {
@@ -11745,13 +11926,18 @@ var Apps = class {
11745
11926
  }
11746
11927
  /**
11747
11928
  * Reads the index at `url`. With the index held for this store, bytes equal to it (by digest) are the held index: its
11748
- * signature and every revocation in it were checked when it was read, so only its expiry is taken again. Any other
11929
+ * signature and every revocation in it were checked when it was read, so only its expiry is taken again; the same for
11930
+ * `behind`, the index this URL served at its last read when it was not taken (`behindReads`). Any other
11749
11931
  * index is read with a pause every few ms (the engine shares the page's thread, and an index holds up to 4096
11750
11932
  * listings and 4096 revocations, each of these a signature check), and a revocation checked in an earlier read, of
11751
11933
  * this store or another, a preview included, is not checked again.
11752
11934
  */
11753
- async readStoreAt(url, heldKey, held) {
11935
+ async readStoreAt(url, heldKey, held, behind, unneeded) {
11754
11936
  const stop = new AbortController();
11937
+ if (unneeded?.aborted) stop.abort();
11938
+ unneeded?.addEventListener("abort", () => {
11939
+ stop.abort();
11940
+ }, { once: true });
11755
11941
  const read = (at, maxBytes) => this.host.fetch(at, {
11756
11942
  maxBytes,
11757
11943
  revalidate: true,
@@ -11761,14 +11947,22 @@ var Apps = class {
11761
11947
  throw error;
11762
11948
  });
11763
11949
  const [indexBytes, sigBytes] = await Promise.all([read(url, APP_FETCH_LIMITS.storeIndexBytes), read(besideUrl(url, "ghostly-store.sig"), APP_FETCH_LIMITS.sigBytes)]);
11764
- if (held?.index && held.digest !== void 0 && toBase64Url(await sha256Paced(indexBytes)) === held.digest) return {
11765
- ok: true,
11766
- store: {
11767
- index: held.index,
11768
- digest: held.digest,
11769
- expired: held.index.expires < this.nowS()
11770
- }
11771
- };
11950
+ const known = held?.index && held.digest !== void 0 ? [{
11951
+ index: held.index,
11952
+ digest: held.digest
11953
+ }, ...behind ? [behind] : []] : [];
11954
+ if (known.length) {
11955
+ const digest = toBase64Url(await sha256Paced(indexBytes));
11956
+ const same = known.find((k) => k.digest === digest);
11957
+ if (same) return {
11958
+ ok: true,
11959
+ store: {
11960
+ index: same.index,
11961
+ digest,
11962
+ expired: same.index.expires < this.nowS()
11963
+ }
11964
+ };
11965
+ }
11772
11966
  const steps = readAppStoreSteps(indexBytes, sigBytes, this.nowS(), heldKey, this.checkedRevocations);
11773
11967
  const pause = pacer(REVOCATIONS_SLICE_MS);
11774
11968
  for (;;) {
@@ -11871,7 +12065,10 @@ var Apps = class {
11871
12065
  this.previewedSweep = previewed ? setTimeout(() => this.keepPreviewed(null), STAGED.ms) : null;
11872
12066
  this.previewed = previewed;
11873
12067
  }
11874
- /** Reads a store at a URL for the person to see before adding it. Nothing is stored: the checked index waits in memory for `addStore`. */
12068
+ /**
12069
+ * Reads a store at a URL for the person to see before adding it. Nothing is added: the checked index waits in memory
12070
+ * for `addStore`. Only another index under the held one's sequence is kept, on the held store (its proof).
12071
+ */
11875
12072
  async previewStore({ url }) {
11876
12073
  const at = this.storeUrl(url);
11877
12074
  this.keepPreviewed(null);
@@ -11885,6 +12082,16 @@ var Apps = class {
11885
12082
  at: this.now()
11886
12083
  });
11887
12084
  const held = await this.storeRecord(index.key);
12085
+ const other = !!held && !held.removed && !!held.index && appStoreDecision({
12086
+ key: held.key,
12087
+ sequence: held.index.sequence,
12088
+ digest: held.digest ?? ""
12089
+ }, {
12090
+ key: index.key,
12091
+ sequence: index.sequence,
12092
+ digest
12093
+ }) === "equivocation";
12094
+ if (other && held.equivocation?.digest !== digest) await this.putStore(this.withIndex(held, index, digest));
11888
12095
  return {
11889
12096
  url: at,
11890
12097
  key: index.key,
@@ -11896,16 +12103,21 @@ var Apps = class {
11896
12103
  expired: read.store.expired,
11897
12104
  apps: index.apps.length,
11898
12105
  ...index.description !== void 0 && { description: index.description },
11899
- ...held && !held.removed && { held: held.index ? { sequence: held.index.sequence } : {} }
12106
+ ...held && !held.removed && { held: held.index ? {
12107
+ sequence: held.index.sequence,
12108
+ ...other && { equivocation: true }
12109
+ } : {} }
11900
12110
  };
11901
12111
  }
11902
12112
  /**
11903
12113
  * Adds a store the person chose: read at its URL and pinned to its key (`key`, when given, is the key the person saw,
11904
12114
  * and another one is refused). A store already added under that key keeps the URL it is read from and takes only a newer
11905
12115
  * index: a copy of its signed index at another URL, the same one or an older one, never moves it there (it would be
11906
- * read only there from then on, frozen). The same index is nothing to do, and an older one is refused with the held
11907
- * store left as it was: a copy the person chose is not a read of the store, so it marks no problem on it. The index the
11908
- * preview just read at that URL, under that key, is taken as it is (only its expiry again), not downloaded again.
12116
+ * read only there from then on, frozen). A newer one's URL is read too while the store's own URL is behind it (a URL at
12117
+ * a commit always is), so that URL's later indexes still arrive. The same index is nothing to do, and an older one is
12118
+ * refused with the held store left as it was: a copy the person chose is not a read of the store, so it marks no problem
12119
+ * on it. The index the preview just read at that URL, under that key, is taken as it is (only its expiry again), not
12120
+ * downloaded again.
11909
12121
  */
11910
12122
  async addStore({ url, key }) {
11911
12123
  if (key !== void 0 && !isAppKey(key)) fail("store-key", "Not a store key");
@@ -11945,7 +12157,14 @@ var Apps = class {
11945
12157
  if (decision === "same") return this.summary(held);
11946
12158
  if (decision === "rollback") fail("rollback", `This store's index is older than the one you have (sequence ${held.index.sequence})`);
11947
12159
  }
11948
- const record = held && !held.removed ? held : {
12160
+ let record;
12161
+ if (held && !held.removed) {
12162
+ const { copyUrl: _c, ...own } = held;
12163
+ record = at === held.url ? own : {
12164
+ ...own,
12165
+ copyUrl: at
12166
+ };
12167
+ } else record = {
11949
12168
  key: index.key,
11950
12169
  url: at,
11951
12170
  addedAt: this.now(),
@@ -11986,15 +12205,19 @@ var Apps = class {
11986
12205
  ...rest,
11987
12206
  problem: "rollback"
11988
12207
  };
11989
- case "equivocation": return {
11990
- ...rest,
11991
- equivocation: {
12208
+ case "equivocation": {
12209
+ const was = rest.equivocation;
12210
+ const equivocation = was?.sequence === index.sequence && was.digest === digest ? was : {
11992
12211
  sequence: index.sequence,
11993
12212
  digest,
11994
12213
  at: this.now()
11995
- },
11996
- problem: "equivocation"
11997
- };
12214
+ };
12215
+ return {
12216
+ ...rest,
12217
+ equivocation,
12218
+ problem: "equivocation"
12219
+ };
12220
+ }
11998
12221
  default: return {
11999
12222
  ...rest,
12000
12223
  problem: "store-key"
@@ -12004,6 +12227,7 @@ var Apps = class {
12004
12227
  async removeStore({ key }) {
12005
12228
  const held = await this.storeRecord(key);
12006
12229
  if (!held) return;
12230
+ this.behindReads.delete(key);
12007
12231
  await this.keepStoreRevocations(held);
12008
12232
  const seen = held.index ? {
12009
12233
  sequence: held.index.sequence,
@@ -12017,40 +12241,87 @@ var Apps = class {
12017
12241
  removed: true,
12018
12242
  ...seen && { seen }
12019
12243
  });
12020
- for (const app of await this.installed()) {
12021
- if (app.store !== key) continue;
12022
- const { store: _s, ...unpinned } = app;
12023
- await this.putApp(unpinned);
12244
+ for (const app of await this.installed()) if (app.store === key) await this.unpinApp(app.ref, key);
12245
+ }
12246
+ /**
12247
+ * Unpins an app from a store removed, read and written in one transaction: the record as it is now, not one read
12248
+ * before (an uninstall, or the update check's write, meanwhile is not undone). Gone, or pinned elsewhere: nothing.
12249
+ */
12250
+ async unpinApp(ref, key) {
12251
+ const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
12252
+ const read = tx.objectStore(STORES$1.apps).get(ref);
12253
+ read.onsuccess = () => {
12254
+ const now = read.result;
12255
+ if (now?.store !== key) return;
12256
+ const { store: _s, ...unpinned } = now;
12257
+ tx.objectStore(STORES$1.apps).put(unpinned);
12258
+ };
12259
+ try {
12260
+ await done(tx);
12261
+ } finally {
12262
+ this.held.delete(ref);
12024
12263
  }
12025
12264
  }
12026
12265
  /** Reads one store again, or every store (the person opened the Apps page, or the update check). */
12027
12266
  async refreshStores({ key } = {}) {
12028
12267
  const stores = (await this.stores()).filter((s) => key === void 0 || s.key === key);
12029
12268
  if (key !== void 0 && !stores.length) fail("no-store", "No such store");
12269
+ const reads = pooled(stores, STORE_READ_PARALLEL, (s) => this.readStore(s));
12030
12270
  const out = [];
12031
- for (const s of stores) {
12032
- let read;
12033
- try {
12034
- read = await this.readStoreAt(s.url, s.key, s);
12035
- } catch (error) {
12036
- read = {
12037
- ok: false,
12038
- reason: error instanceof AppFetchError ? error.code : "network"
12039
- };
12040
- }
12271
+ for (const [i, s] of stores.entries()) {
12272
+ const { read, copy } = await reads[i];
12041
12273
  const now = await this.storeRecord(s.key);
12042
12274
  if (!now || now.removed) continue;
12043
- const next = read.ok ? this.withIndex(now, read.store.index, read.store.digest) : {
12275
+ let next = read.ok ? this.withIndex(now, read.store.index, read.store.digest) : {
12044
12276
  ...now,
12045
12277
  problem: read.reason
12046
12278
  };
12047
- if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation) (await this.records()).set(s.key, next);
12279
+ const fromCopy = copy?.ok ? this.withIndex(now, copy.store.index, copy.store.digest) : null;
12280
+ if (next.copyUrl !== void 0 && !next.problem) {
12281
+ const { copyUrl: _c, ...own } = next;
12282
+ next = own;
12283
+ } else if (fromCopy && fromCopy.problem !== "rollback" && next.problem !== "equivocation") next = fromCopy;
12284
+ if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation && next.copyUrl === s.copyUrl) (await this.records()).set(s.key, next);
12048
12285
  else await this.putStore(next);
12049
12286
  out.push(this.summary(next));
12050
12287
  }
12051
12288
  return out;
12052
12289
  }
12053
12290
  /**
12291
+ * One store's reads for `refreshStores`; never throws. Its own URL, and the copy its index was taken from (`copyUrl`)
12292
+ * when the own URL is behind it (or not answering). That copy is read beside the own URL when that URL was behind at
12293
+ * its last read (`behindReads`: one at a commit stays so), and stopped when it turns out not to be; otherwise only
12294
+ * once the own URL showed it.
12295
+ */
12296
+ async readStore(s) {
12297
+ const last = this.behindReads.get(s.key);
12298
+ const lastBehind = last?.url === s.url ? last : void 0;
12299
+ const unneeded = new AbortController();
12300
+ const readCopy = (at) => this.readStoreAt(at, s.key, s, void 0, unneeded.signal).catch(() => null);
12301
+ const early = s.copyUrl !== void 0 && lastBehind ? readCopy(s.copyUrl) : null;
12302
+ let read;
12303
+ try {
12304
+ read = await this.readStoreAt(s.url, s.key, s, lastBehind);
12305
+ } catch (error) {
12306
+ read = {
12307
+ ok: false,
12308
+ reason: error instanceof AppFetchError ? error.code : "network"
12309
+ };
12310
+ }
12311
+ const behind = !read.ok || !!this.withIndex(s, read.store.index, read.store.digest).problem;
12312
+ if (read.ok && behind) this.behindReads.set(s.key, {
12313
+ url: s.url,
12314
+ index: read.store.index,
12315
+ digest: read.store.digest
12316
+ });
12317
+ else this.behindReads.delete(s.key);
12318
+ if (!behind) unneeded.abort();
12319
+ return {
12320
+ read,
12321
+ copy: behind && s.copyUrl !== void 0 ? await (early ?? readCopy(s.copyUrl)) : null
12322
+ };
12323
+ }
12324
+ /**
12054
12325
  * Fetches an app and checks it, for the install screen: from a pasted URL, a store's listing (its URLs in order) or a
12055
12326
  * chat card's pointer. A card's `sequence` and digest must hold: the same app, and that version or a newer one. A
12056
12327
  * store's listing must hold exactly: the version it lists, by digest, so a URL that already holds a newer version the
@@ -12099,9 +12370,10 @@ var Apps = class {
12099
12370
  };
12100
12371
  } else fail("bad-source", "No app to fetch");
12101
12372
  if (!urls.length) fail("host", "This listing has no URL Ghostly reads from");
12373
+ const kept = expect?.digest !== void 0 ? this.staged.get(expect.digest) : void 0;
12102
12374
  let last = null;
12103
12375
  for (const url of urls) try {
12104
- const { bundle, bytes } = await this.fetchBundle(url);
12376
+ const { bundle, bytes } = kept && kept.from === url && this.now() - kept.at <= STAGED.ms ? kept : await this.fetchBundle(url);
12105
12377
  const version = versionOf(bundle.manifest, bundle.digest);
12106
12378
  if (expect) {
12107
12379
  if (version.ref !== expect.ref) fail("other-app", "The URL holds another app");
@@ -12125,7 +12397,14 @@ var Apps = class {
12125
12397
  async stage(bundle, bytes, from, fromStore, carried = false) {
12126
12398
  const { manifest, digest } = bundle;
12127
12399
  const version = versionOf(manifest, digest);
12128
- const revocations = carried ? [] : await this.readRevocations(version.ref, [from, ...manifest.sources ?? []]) ?? [];
12400
+ const read = carried ? [] : await this.readRevocations(version.ref, [from, ...manifest.sources ?? []]) ?? [];
12401
+ const stops = stopping([version], read);
12402
+ if (stops.length) {
12403
+ const tx = (await openDb()).transaction(STORES$1.settings, "readwrite");
12404
+ keepRevocations(tx.objectStore(STORES$1.settings), version.ref, stops);
12405
+ await done(tx);
12406
+ }
12407
+ const revocations = [...await this.keptRevocationsOf(version.ref), ...read];
12129
12408
  for (const [d, s] of this.staged) if (this.now() - s.at > STAGED.ms) this.staged.delete(d);
12130
12409
  this.staged.delete(digest);
12131
12410
  while (this.staged.size >= STAGED.max) this.staged.delete(this.staged.keys().next().value);
@@ -12176,9 +12455,17 @@ var Apps = class {
12176
12455
  const version = versionOf(manifest, digest);
12177
12456
  let wrote;
12178
12457
  try {
12458
+ let read = false;
12179
12459
  for (;;) {
12180
- const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
12181
- const run = this.runStatus(version, this.storeViews(stores), [...installed?.revocations ?? [], ...revocations]);
12460
+ const [installed, stores, kept] = await Promise.all([
12461
+ this.app(version.ref),
12462
+ this.stores(),
12463
+ this.keptRevocationsOf(version.ref)
12464
+ ]);
12465
+ if (read && !installed) fail("not-installed", "This app is not installed");
12466
+ read = installed !== void 0;
12467
+ const known = [...kept, ...revocations];
12468
+ const run = this.runStatus(version, this.storeViews(stores), [...installed?.revocations ?? [], ...known]);
12182
12469
  if (run.status === "revoked") fail("revoked", "Its publisher revoked this version");
12183
12470
  if (run.status === "removed") fail("removed", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
12184
12471
  const decision = installDecision(installed, version);
@@ -12210,7 +12497,7 @@ var Apps = class {
12210
12497
  return this.view(await this.app(version.ref), stores);
12211
12498
  }
12212
12499
  const kind = wrote = await this.writeBundle(digest, bytes);
12213
- const next = withRevocations(this.versionRecord(installed, bundle, kind, from, fromStore), revocations);
12500
+ const next = withRevocations(this.versionRecord(installed, bundle, kind, from, fromStore), known);
12214
12501
  if (!await this.putAppIfUnchanged(next, installed)) continue;
12215
12502
  if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
12216
12503
  if (installed && installed.digest !== digest) await this.removeBundle(installed.bytes, installed.digest);
@@ -12325,16 +12612,7 @@ var Apps = class {
12325
12612
  if (!apps.length) return [];
12326
12613
  await this.refreshStores();
12327
12614
  const stores = await this.stores();
12328
- const out = [];
12329
- let next = 0;
12330
- const worker = async () => {
12331
- while (next < apps.length) {
12332
- const i = next++;
12333
- out[i] = await this.checkApp(apps[i], stores);
12334
- }
12335
- };
12336
- await Promise.all(Array.from({ length: Math.min(APP_CHECK_PARALLEL, apps.length) }, worker));
12337
- return out.filter((r) => r !== null);
12615
+ return (await Promise.all(pooled(apps, APP_CHECK_PARALLEL, (app) => this.checkApp(app, stores).catch(() => null)))).filter((r) => r !== null);
12338
12616
  }
12339
12617
  /** One app's part of the update check (`checkNow`); null when it is not installed any more. */
12340
12618
  async checkApp(listed, stores) {
@@ -12506,7 +12784,7 @@ var Apps = class {
12506
12784
  ...merged.size && { revocations: [...merged.values()] },
12507
12785
  checkedAt: this.now()
12508
12786
  };
12509
- const put = stored.checkedAt !== void 0 && this.now() - stored.checkedAt < APP_CHECK_TIMINGS.freshMs / 2 && sameExceptChecked(app, stored) ? sameRecord(current, stored) : await this.putAppIfUnchanged(app, stored);
12787
+ const put = this.checkedWithin(stored.checkedAt, APP_CHECK_TIMINGS.freshMs / 2) && sameExceptChecked(app, stored) ? sameRecord(current, stored) : await this.putAppIfUnchanged(app, stored);
12510
12788
  for (const files of [...dropped, ...!put && wrote ? [wrote] : []]) await this.removeUnusedBundle(app.ref, files.bytes, files.digest);
12511
12789
  if (!put) return null;
12512
12790
  return {
@@ -12715,10 +12993,12 @@ var Apps = class {
12715
12993
  const tx = (await openDb()).transaction([
12716
12994
  STORES$1.apps,
12717
12995
  STORES$1.appStorage,
12718
- ...builtIn ? [STORES$1.settings] : []
12996
+ STORES$1.settings
12719
12997
  ], "readwrite");
12720
12998
  this.uninstalls.set(ref, (this.uninstalls.get(ref) ?? 0) + 1);
12721
12999
  this.held.delete(ref);
13000
+ const record = tx.objectStore(STORES$1.apps).get(ref);
13001
+ record.onsuccess = () => keepRevocations(tx.objectStore(STORES$1.settings), ref, record.result?.revocations ?? []);
12722
13002
  tx.objectStore(STORES$1.apps).delete(ref);
12723
13003
  tx.objectStore(STORES$1.appStorage).delete(rowsOf(ref));
12724
13004
  if (builtIn) markBuiltIns(tx.objectStore(STORES$1.settings), (marks) => {
@@ -13260,7 +13540,7 @@ function parseDeviceRecord(value) {
13260
13540
  if (!optional(r.tombstone, bytes)) return bad("tombstone");
13261
13541
  if (r.secretOffer !== void 0) {
13262
13542
  const o = r.secretOffer;
13263
- if (!o || typeof o !== "object" || o.why !== "takeover" || !count(o.at, Number.MAX_SAFE_INTEGER) || !optional(o.device, text) || o.lost !== void 0 && o.lost !== true) return bad("secretOffer");
13543
+ if (!o || typeof o !== "object" || o.why !== "takeover" || !count(o.at, Number.MAX_SAFE_INTEGER) || !optional(o.key, bytes) || !optional(o.device, text) || o.lost !== void 0 && o.lost !== true) return bad("secretOffer");
13264
13544
  }
13265
13545
  if (r.push !== void 0 && !isPush(r.push)) return bad("push");
13266
13546
  if (r.ownSet !== void 0) {
@@ -13554,7 +13834,7 @@ var DeviceReadTimeout = class extends Error {
13554
13834
  this.name = "DeviceReadTimeout";
13555
13835
  }
13556
13836
  };
13557
- function within$1(work, ms, what) {
13837
+ function within$2(work, ms, what) {
13558
13838
  return new Promise((resolve, reject) => {
13559
13839
  const timer = setTimeout(() => reject(new DeviceReadTimeout(what)), ms);
13560
13840
  work.then((value) => {
@@ -13626,7 +13906,7 @@ async function devicesDbExists() {
13626
13906
  });
13627
13907
  };
13628
13908
  try {
13629
- return await within$1(probe(), DEVICE_READ_TIMINGS.existsMs, "The list of databases");
13909
+ return await within$2(probe(), DEVICE_READ_TIMINGS.existsMs, "The list of databases");
13630
13910
  } catch {
13631
13911
  return false;
13632
13912
  }
@@ -13643,7 +13923,7 @@ async function readLocal(profile) {
13643
13923
  request.onerror = () => reject(request.error);
13644
13924
  });
13645
13925
  };
13646
- const stored = await within$1(read(), DEVICE_READ_TIMINGS.readMs, "The device state database");
13926
+ const stored = await within$2(read(), DEVICE_READ_TIMINGS.readMs, "The device state database");
13647
13927
  return stored === void 0 ? null : parseDeviceRecord(stored);
13648
13928
  }
13649
13929
  /**
@@ -13689,7 +13969,7 @@ async function swapMany(writes) {
13689
13969
  var DeviceFileInvalid = class extends Error {};
13690
13970
  /** The file's record: null when it holds none. */
13691
13971
  async function readMirror(profile) {
13692
- const text = await within$1(mirror.read(profile), DEVICE_READ_TIMINGS.readMs, "The device state file");
13972
+ const text = await within$2(mirror.read(profile), DEVICE_READ_TIMINGS.readMs, "The device state file");
13693
13973
  if (text === null) return null;
13694
13974
  let filed;
13695
13975
  try {
@@ -13883,7 +14163,8 @@ function turnRow(state, atStart) {
13883
14163
  if (state === "active") return atStart ? "active-start" : "active-running";
13884
14164
  return state;
13885
14165
  }
13886
- var tombstone = (facts) => facts.listed ? "moving" : "removed";
14166
+ /** Only a tombstone the device it believes signed ends a device that it does not list; any other leaves it waiting. */
14167
+ var tombstone = (facts) => facts.listed || facts.believed === false ? "moving" : "removed";
13887
14168
  var STAY = {
13888
14169
  do: "stay",
13889
14170
  offers: []
@@ -14044,7 +14325,7 @@ function cell(row, column, facts) {
14044
14325
  break;
14045
14326
  case "moving":
14046
14327
  switch (column) {
14047
- case "tombstone": return facts.listed ? {
14328
+ case "tombstone": return tombstone(facts) === "moving" ? {
14048
14329
  do: "stay",
14049
14330
  offers: [],
14050
14331
  awaits: "set-update"
@@ -14398,11 +14679,11 @@ function checkSetUpdate(record, frame, now) {
14398
14679
  const read = readTurnPacket(oldKeys, update.tomb);
14399
14680
  if (read.kind !== "valid" || !read.record.tombstone) return refuse("tombstone");
14400
14681
  const tomb = read.record;
14401
- if (!tomb.slots.some((slot) => !!slot && toBase64Url(slot.key) === own)) return refuse("removed");
14402
14682
  if (!verifySetUpdate(update, oldKeys.address)) return refuse("signature");
14403
14683
  const by = toBase64Url(update.by);
14404
14684
  const active = believed(record, oldKeys, by, update.rec);
14405
- if (!active || by !== active) return refuse("signer", true);
14685
+ if (!listedIn(tomb, own)) return active && by === active ? refuse("removed") : refuse("signer");
14686
+ if (!active || by !== active) return refuse("signer", record.activeSlot !== record.ownSlot);
14406
14687
  if (!listedIn(tomb, active)) return refuse("unlisted", true);
14407
14688
  if (record.tombstone) {
14408
14689
  const kept = readTurnPacket(oldKeys, fromBase64Url(record.tombstone));
@@ -14508,6 +14789,18 @@ function latestKnown(read, stored) {
14508
14789
  if (!news) return stored;
14509
14790
  return !stored || news.sequence >= stored.sequence ? news : stored;
14510
14791
  }
14792
+ /**
14793
+ * Whether a tombstone was signed by the device this one believes active: the one its record names (itself, on the
14794
+ * active device), or the other device of a handoff under way (the one it releases the turn to, or takes it from). Any
14795
+ * slot's key and `D` make a valid tombstone, so a stolen standby or a removed device can sign one too; only the believed
14796
+ * device's ends this device (WISP 06 § Removing a device).
14797
+ */
14798
+ function tombstoneBelieved(record, tombstone) {
14799
+ const author = tombstone.slots[tombstone.author];
14800
+ if (!author) return false;
14801
+ const key = toBase64Url(author.key);
14802
+ return key === (record.activeSlot === void 0 ? void 0 : record.deviceSet[record.activeSlot]?.key) || key === record.handoff?.release?.to || key === record.handoff?.peer;
14803
+ }
14511
14804
  /** The record's slots as the device state keeps them. */
14512
14805
  function deviceSetOf(record) {
14513
14806
  return record.slots.map((slot) => slot && {
@@ -14515,6 +14808,23 @@ function deviceSetOf(record) {
14515
14808
  name: slot.name
14516
14809
  });
14517
14810
  }
14811
+ /**
14812
+ * The slots of the first record of a turn this device raises (WISP 06 § Who may raise the turn): those of the newest
14813
+ * record of the set it knows. The read the raise acts on may return a record above the one it stored (a device added or
14814
+ * renamed since its last read); when that record still lists this device in its own slot, its slots are written, with
14815
+ * any device of the stored set in a slot that record leaves empty (within one `D` a slot is never emptied). Undefined:
14816
+ * the stored set is the newest. Written as stored, the set would drop the device added, which keeps `D` and is listed
14817
+ * nowhere, and undo the rename.
14818
+ */
14819
+ function newestSlots(held, read) {
14820
+ const news = read.record;
14821
+ if (!news || news.tombstone || read.result === "clone") return void 0;
14822
+ if (held.storedRecord && news.sequence <= held.storedRecord.sequence) return void 0;
14823
+ const listed = news.slots[held.ownSlot];
14824
+ if (!listed || !bytesEqual(listed.key, held.ownKey)) return void 0;
14825
+ const set = deviceSetOf(news);
14826
+ return set.map((slot, i) => slot ?? (held.record.deviceSet[i] && !set.some((s) => s?.key === held.record.deviceSet[i].key) ? held.record.deviceSet[i] : null));
14827
+ }
14518
14828
  var TurnKeeper = class {
14519
14829
  options;
14520
14830
  store;
@@ -14770,10 +15080,11 @@ var TurnKeeper = class {
14770
15080
  step: `${TAKEOVER}${prior}`,
14771
15081
  ...stopping ? { peer: stopping } : {}
14772
15082
  } });
15083
+ const slots = options.slots ?? newestSlots(held, read);
14773
15084
  try {
14774
15085
  await this.writeWith(held, read.conditions, {
14775
15086
  turn,
14776
- ...options.slots ? { slots: options.slots } : {}
15087
+ ...slots ? { slots } : {}
14777
15088
  }, true);
14778
15089
  } catch (error) {
14779
15090
  if (!held.wroteNow) held.record = await this.store.move(this.options.profile, prior, {
@@ -14827,10 +15138,12 @@ var TurnKeeper = class {
14827
15138
  return this.settle(held, await this.readWith(held), true);
14828
15139
  }
14829
15140
  if (!fresh) return this.settle(held, read, true);
15141
+ const slots = newestSlots(held, read);
14830
15142
  try {
14831
15143
  await this.writeWith(held, read.conditions, {
14832
15144
  turn,
14833
- release
15145
+ release,
15146
+ ...slots ? { slots } : {}
14834
15147
  }, true);
14835
15148
  } catch (error) {
14836
15149
  if (error instanceof TurnClosedError) return this.exhausted(held, "taking", read);
@@ -14905,8 +15218,12 @@ var TurnKeeper = class {
14905
15218
  continue;
14906
15219
  }
14907
15220
  let outcome;
15221
+ const facts = read.result === "tombstone" && read.record ? {
15222
+ ...read,
15223
+ believed: tombstoneBelieved(held.record, read.record)
15224
+ } : read;
14908
15225
  try {
14909
- outcome = await this.carryOut(held, row, turnAction(row, read, behind), read);
15226
+ outcome = await this.carryOut(held, row, turnAction(row, facts, behind), read);
14910
15227
  } catch (error) {
14911
15228
  if (error instanceof TurnClosedError) return this.exhausted(held, row, read);
14912
15229
  if (!(error instanceof TurnStaleReadError)) throw error;
@@ -14978,7 +15295,9 @@ var TurnKeeper = class {
14978
15295
  const won = !!takeover && state === "active";
14979
15296
  const takeovers = held.record.takeovers + 1;
14980
15297
  const was = held.record.state;
14981
- const copy = state === "active" ? { copy: void 0 } : state === "superseded" && (was === "active" || was === "releasing") ? { copy: "frozen" } : {};
15298
+ const ran = was === "active" || was === "releasing";
15299
+ const foreign = state === "moving" && read.result === "tombstone" && !!read.record && !tombstoneBelieved(held.record, read.record);
15300
+ const copy = state === "active" ? { copy: void 0 } : (state === "superseded" || foreign) && ran ? { copy: "frozen" } : {};
14982
15301
  const listed = read.record?.slots[held.ownSlot];
14983
15302
  const replacedBy = state === "superseded" && read.result === "other" && read.record && !!listed && toBase64Url(listed.key) === toBase64Url(held.ownKey) ? {
14984
15303
  activeSlot: read.record.active,
@@ -14986,9 +15305,9 @@ var TurnKeeper = class {
14986
15305
  } : {};
14987
15306
  const tombstoned = state === "moving" && read.result === "tombstone" && read.record && read.payload ? {
14988
15307
  tombstone: toBase64Url(read.payload),
14989
- ...storedActiveListed(held.record, read.record) ? {} : { reenroll: true }
15308
+ ...storedActiveListed(held.record, read.record) || foreign && ran ? {} : { reenroll: true }
14990
15309
  } : {};
14991
- const stopped = won && held.record.handoff?.peer ? held.record.deviceSet.find((slot) => slot?.key === held.record.handoff.peer)?.name : void 0;
15310
+ const stopped = won && held.record.handoff?.peer ? held.record.deviceSet.find((slot) => slot?.key === held.record.handoff.peer) : void 0;
14992
15311
  held.record = await this.store.move(this.options.profile, state, {
14993
15312
  ...takeover ? { handoff: void 0 } : {},
14994
15313
  ...held.record.settle ? { settle: void 0 } : {},
@@ -15001,7 +15320,10 @@ var TurnKeeper = class {
15001
15320
  secretOffer: {
15002
15321
  why: "takeover",
15003
15322
  at: this.now(),
15004
- ...stopped ? { device: stopped } : {}
15323
+ ...stopped ? {
15324
+ key: stopped.key,
15325
+ device: stopped.name
15326
+ } : {}
15005
15327
  }
15006
15328
  } : {}
15007
15329
  });
@@ -16260,7 +16582,8 @@ function wakeOwnerOf(current, self) {
16260
16582
  }
16261
16583
  /**
16262
16584
  * Posts a push: the host's way (Desktop and the CLI post it themselves), or `fetch`, then the person's push relay when
16263
- * a page may not post it (the push services answer without CORS). Answers the push service's HTTP status.
16585
+ * a page may not post it (the push services answer without CORS). Answers the push service's HTTP status; throws when
16586
+ * the relay does not answer with it.
16264
16587
  */
16265
16588
  async function postPush(request, options) {
16266
16589
  if (options.pushSend) return options.pushSend(request);
@@ -16286,8 +16609,9 @@ async function postPush(request, options) {
16286
16609
  signal: AbortSignal.timeout(15e3),
16287
16610
  ...quiet
16288
16611
  });
16289
- const answer = await response.json().catch(() => null);
16290
- return typeof answer?.status === "number" ? answer.status : response.status;
16612
+ const answer = response.ok ? await response.json().catch(() => null) : null;
16613
+ if (typeof answer?.status !== "number") throw Object.assign(/* @__PURE__ */ new Error(`The push relay did not forward it (HTTP ${response.status})`), { cause: error });
16614
+ return answer.status;
16291
16615
  }
16292
16616
  }
16293
16617
  /** One device wake-up per device per `DEVICE_WAKE_INTERVAL_MS`. */
@@ -16629,7 +16953,9 @@ function verifierStands(record, latest) {
16629
16953
  const stated = turnStatedVerifier(latest.instance);
16630
16954
  return !stated || bytesEqual(stated, turnVerifierMark(record.verifier));
16631
16955
  }
16632
- var sameName = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16956
+ /** A name as it is seen and typed: nobody types a joiner, a variation selector or a filler, which draw nothing. */
16957
+ var typedName = (name) => name.normalize("NFC").replace(/\p{Default_Ignorable_Code_Point}/gu, "").trim().toLocaleLowerCase();
16958
+ var sameName = (a, b) => typedName(a) === typedName(b);
16633
16959
  /** One try at a time on this device, whoever asks: tries sent at once would all be checked against the same count. */
16634
16960
  var tries = Promise.resolve();
16635
16961
  function oneTry(work) {
@@ -16682,6 +17008,13 @@ async function forceTakeover(ports, request) {
16682
17008
  }
16683
17009
  //#endregion
16684
17010
  //#region ../browser/src/devices/ownSet.ts
17011
+ /**
17012
+ * Whether another valid tombstone that does not list this device ends it here. A device that was the active one
17013
+ * believes no other device, so another slot's tombstone (a stolen device's, which needs only `D` and a slot's key)
17014
+ * leaves it `moving`, and it may try again. Any other device yields: that is how two `moving` devices of one remover
17015
+ * settle which of them goes on.
17016
+ */
17017
+ var yieldsTo = (record) => record.activeSlot !== record.ownSlot;
16685
17018
  /** Whether this device may offer it: `moving`, a copy here, and a remover it still believes (not one it can only be added back from). */
16686
17019
  function canStartOwnSet(record) {
16687
17020
  return !!record && record.state === "moving" && !!record.copy && !record.reenroll;
@@ -16715,7 +17048,7 @@ async function startOwnSet(ports, request) {
16715
17048
  stored: null
16716
17049
  }, await ports.network.turnRead(keys.identity.pubKeyZ32));
16717
17050
  if (!standing.good) return "wait";
16718
- if (standing.result === "tombstone" && !standing.listed) {
17051
+ if (standing.result === "tombstone" && !standing.listed && yieldsTo(record)) {
16719
17052
  await ports.move("removed", {});
16720
17053
  return "removed";
16721
17054
  }
@@ -16822,7 +17155,7 @@ async function resumeOwnSet(ports) {
16822
17155
  await won(ports, record, plan, now());
16823
17156
  return "start";
16824
17157
  }
16825
- if (!read.listed) {
17158
+ if (!read.listed && yieldsTo(record)) {
16826
17159
  await ports.move("removed", { ownSet: void 0 });
16827
17160
  return "removed";
16828
17161
  }
@@ -17139,6 +17472,7 @@ function deviceSetView(record, links) {
17139
17472
  name: slot.name
17140
17473
  }] : [];
17141
17474
  });
17475
+ const stopped = record.secretOffer ? offeredDevice(record, record.secretOffer) : void 0;
17142
17476
  return {
17143
17477
  state: record.state,
17144
17478
  devices,
@@ -17146,7 +17480,10 @@ function deviceSetView(record, links) {
17146
17480
  ...enrollmentUnfinished(record) ? { unfinished: true } : {},
17147
17481
  ...due?.why === "unfinished-grant" ? { newSecretDue: true } : {},
17148
17482
  ...record.state === "active" && record.secretOffer ? { secretOffer: {
17149
- ...record.secretOffer.device ? { device: record.secretOffer.device } : {},
17483
+ ...stopped ? {
17484
+ key: stopped.key,
17485
+ device: stopped.name
17486
+ } : {},
17150
17487
  ...record.secretOffer.lost ? { lost: true } : {}
17151
17488
  } } : {},
17152
17489
  ...record.state === "active" && waiting.length ? { waiting } : {},
@@ -17160,6 +17497,16 @@ function deviceSetView(record, links) {
17160
17497
  };
17161
17498
  }
17162
17499
  /**
17500
+ * The device a takeover's offer is about, as the set lists it now: found by its key, never this device. An offer an older
17501
+ * build stored has only the name, which a rename there may have moved to another device: it is trusted only when the
17502
+ * set has one other device and the name is that device's.
17503
+ */
17504
+ function offeredDevice(record, offer) {
17505
+ const others = record.deviceSet.filter((slot, index) => !!slot && index !== record.ownSlot);
17506
+ if (offer.key) return others.find((slot) => slot.key === offer.key);
17507
+ return others.length === 1 && others[0].name === offer.device ? others[0] : void 0;
17508
+ }
17509
+ /**
17163
17510
  * What the handoff hears when the capabilities agreed on a device link change (WISP 06 § Frames): `handoff/1` agreed
17164
17511
  * (true) or no longer (false). Agreed again on a new session that replaced the open one (the other device dialled in
17165
17512
  * again), the data link never closed and nothing else says so: the old session ended and this one opened. A frame sent
@@ -17184,6 +17531,8 @@ var NATIVE_RETRY_MS$1 = 1e4;
17184
17531
  var NATIVE_RETRY_MAX_MS = 12e4;
17185
17532
  /** The other device is there and no session opened over WebRTC in this long: the link goes on without it (`withoutRtc`). */
17186
17533
  var DEVICE_RTC_MS = 2e4;
17534
+ /** The other device is there and no session opened over a link's native endpoints in this long: it starts again with WebRTC (`withRtc`). */
17535
+ var DEVICE_NATIVE_MS = 6e4;
17187
17536
  /** The longest that wait grows to, for a link that went back to WebRTC again and again (`withRtc`). */
17188
17537
  var DEVICE_RTC_MAX_MS = 3e5;
17189
17538
  /** How often a standby reads the turn while its screen shows (WISP 06 § When a device checks), and the jitter on it. */
@@ -17502,6 +17851,10 @@ var DeviceLinks = class {
17502
17851
  * and a transport that does not start is tried again (`retryNative`), as a chat's listeners are.
17503
17852
  */
17504
17853
  startNative(running) {
17854
+ if (!running.native && running.rtcWait) {
17855
+ clearTimeout(running.rtcWait);
17856
+ running.rtcWait = void 0;
17857
+ }
17505
17858
  running.native = true;
17506
17859
  const factories = this.nativeFactories();
17507
17860
  for (const transport of this.missingNative(running)) {
@@ -17937,22 +18290,33 @@ var DeviceLinks = class {
17937
18290
  });
17938
18291
  this.queue = run;
17939
18292
  }
17940
- /** `withoutRtc` once `DEVICE_RTC_MS` passed with no session open, twice as long for each time it went back (`rtcBacks`). */
18293
+ /**
18294
+ * `withoutRtc` once `DEVICE_RTC_MS` passed with no session open, twice as long for each time it went back (`rtcBacks`).
18295
+ * A link that runs its native endpoints (`native`) waits `DEVICE_NATIVE_MS` so instead, then goes back to WebRTC
18296
+ * (`withRtc`): one device's endpoint may start where the other's never does, so nothing opens over them.
18297
+ */
17941
18298
  waitForRtc(running) {
17942
- if (running.rtcOff || running.rtcWait || running.link.isDataLinkOpen) return;
18299
+ if (running.rtcOff && !running.native || running.rtcWait || running.link.isDataLinkOpen) return;
18300
+ const wait = (running.native ? DEVICE_NATIVE_MS : DEVICE_RTC_MS) * 2 ** (this.rtcBacks.get(running.id) ?? 0);
17943
18301
  running.rtcWait = setTimeout(() => {
17944
18302
  running.rtcWait = void 0;
17945
- if (!running.link.isDataLinkOpen) this.withoutRtc(running, true);
17946
- }, Math.min(DEVICE_RTC_MS * 2 ** (this.rtcBacks.get(running.id) ?? 0), DEVICE_RTC_MAX_MS));
18303
+ if (running.link.isDataLinkOpen) return;
18304
+ if (running.native) this.withRtc(running);
18305
+ else this.withoutRtc(running, true);
18306
+ }, Math.min(wait, DEVICE_RTC_MAX_MS));
17947
18307
  }
17948
18308
  /**
17949
18309
  * The link that went on without WebRTC (`withoutRtc`) started none of its native transports: an Iroh relay neither
17950
18310
  * device reaches, and no HyperDHT relay. With nothing to go through it starts again with WebRTC, which may connect
17951
18311
  * now, or only after `DEVICE_RTC_MS` (a device that just reloaded dials at its own pace). The wait before it goes
17952
18312
  * without WebRTC again doubles each time (`rtcBacks`), so a native transport that comes back is still tried.
18313
+ * The same where its native transports started and no session opened over them by `DEVICE_NATIVE_MS` while the other
18314
+ * device is there (its own endpoint never started, or is on another Iroh relay), and on the other device's link
18315
+ * that runs native for it: the new link forgets the transports the other device's packet said, which a device link
18316
+ * keeps although the packet no longer says any (the other device went back to WebRTC), and offers WebRTC again.
17953
18317
  */
17954
18318
  withRtc(running) {
17955
- if (this.stopped || !running.rtcOff || running.link.isDataLinkOpen || this.running.get(running.id) !== running) return;
18319
+ if (this.stopped || !this.createPeerConnection || !running.native || running.link.isDataLinkOpen || this.running.get(running.id) !== running) return;
17956
18320
  this.rtcBacks.set(running.id, (this.rtcBacks.get(running.id) ?? 0) + 1);
17957
18321
  const run = this.queue.catch(() => {}).then(async () => {
17958
18322
  if (this.stopped || this.running.get(running.id) !== running || running.link.isDataLinkOpen) return;
@@ -19325,7 +19689,6 @@ async function renameDevice(options) {
19325
19689
  if (!record || record.state !== "active") throw new RenameRefusal("state", "Only the active device renames a device.");
19326
19690
  const at = record.deviceSet.findIndex((slot) => slot?.key === options.key);
19327
19691
  if (at < 0) throw new RenameRefusal("device", "That device is not in this profile.");
19328
- const old = record.deviceSet[at].name;
19329
19692
  const slots = Array.from({ length: 4 }, (_, i) => {
19330
19693
  const slot = record.deviceSet[i] ?? null;
19331
19694
  return slot && i === at ? {
@@ -19333,14 +19696,7 @@ async function renameDevice(options) {
19333
19696
  name
19334
19697
  } : slot;
19335
19698
  });
19336
- const offer = record.secretOffer?.device === old ? { secretOffer: {
19337
- ...record.secretOffer,
19338
- device: name
19339
- } } : {};
19340
- await options.keeper.write(turn.conditions, {
19341
- slots,
19342
- patch: offer
19343
- });
19699
+ await options.keeper.write(turn.conditions, { slots });
19344
19700
  return true;
19345
19701
  }
19346
19702
  //#endregion
@@ -21159,7 +21515,7 @@ var RESEND_POLICY = {
21159
21515
  };
21160
21516
  /** How long one turn of an outbox may hold the next one back: a send that never returns must not stop the chat. */
21161
21517
  var TURN_MS = 3e4;
21162
- /** The most rows a new message's look reads one by one (`Outbox.look`). */
21518
+ /** The most rows a new message's look reads one by one (`Outbox.look`), where the store cannot read them in one go. */
21163
21519
  var KNOWN_ROWS = 16;
21164
21520
  /**
21165
21521
  * A text of mine, not handed to store-and-forward, and still to go: queued, or waiting for the chat to carry it. (A
@@ -21367,17 +21723,18 @@ var Outbox = class {
21367
21723
  * The rows a new message's look needs, itself among them: those this outbox holds, by id, where it knows them all.
21368
21724
  * A text sent before the last one's receipt came, or while one waits for an away contact, read the chat's whole
21369
21725
  * history on the page's thread (20,000 rows per send at 20,000 messages), and so did each of the texts a bot asked
21370
- * for at the same time. Past `KNOWN_ROWS`, the history costs less.
21726
+ * for at the same time. Read one by one, past `KNOWN_ROWS` the history costs less; read in one go (`getMany`), they
21727
+ * are never more than the history.
21371
21728
  */
21372
21729
  async look(id) {
21373
- if (!this.store.get || !this.known || this.waiting.size + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
21730
+ if (!this.store.get || !this.known || !this.store.getMany && this.waiting.size + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
21374
21731
  const ids = /* @__PURE__ */ new Set([
21375
21732
  ...id === void 0 ? [] : [id],
21376
21733
  ...this.waiting.keys(),
21377
21734
  ...this.receipts.keys(),
21378
21735
  ...this.onTheirWay.keys()
21379
21736
  ]);
21380
- return (await Promise.all([...ids].map((known) => this.store.get(known)))).filter((row) => !!row);
21737
+ return (this.store.getMany ? await this.store.getMany([...ids]) : await Promise.all([...ids].map((known) => this.store.get(known)))).filter((row) => !!row);
21381
21738
  }
21382
21739
  /**
21383
21740
  * What a look at the chat takes up comes from: the rows this outbox holds, by id, where it knows them all (`look`);
@@ -21600,7 +21957,7 @@ var Outbox = class {
21600
21957
  */
21601
21958
  async check(id) {
21602
21959
  if (this.stopped) return;
21603
- if (this.waiting.get(id)?.timer || this.receipts.has(id)) return;
21960
+ if (!this.waiting.has(id) || this.waiting.get(id)?.timer || this.receipts.has(id)) return;
21604
21961
  const messages = await this.store.read(), message = messages.find((m) => m.id === id);
21605
21962
  if (!message || !(toGo(message) || this.file(message))) {
21606
21963
  await this.attempt(id);
@@ -22582,6 +22939,34 @@ function newestMessages(index, query, count) {
22582
22939
  }
22583
22940
  /** A write that waits for no disk sync of its own (in a browser, the engine's default already; on Node, the CLI's store). */
22584
22941
  var RELAXED = { durability: "relaxed" };
22942
+ var CHANGED = Symbol("changed");
22943
+ /**
22944
+ * A chat's pinned key, for the transaction that checks and changes it, and the seals of the keys that change writes.
22945
+ * Sealed (the data key is set), it is opened before the transaction, and holds inside it only while the row still has
22946
+ * the sealed value that was opened: `CHANGED` otherwise.
22947
+ */
22948
+ async function pinnedKey(linkId, key) {
22949
+ const seals = new RowSeals();
22950
+ if (!seals.on) return {
22951
+ seals,
22952
+ pinned: (link) => link?.pairedPeerKey
22953
+ };
22954
+ const seen = await wrap((await store(STORES$1.links, "readonly")).get(linkId));
22955
+ const opened = await openRow(STORES$1.links, seen);
22956
+ await seals.prepare(STORES$1.links, [{
22957
+ id: linkId,
22958
+ pairedPeerKey: key,
22959
+ peerTrust: { verifiedKey: key }
22960
+ }, {
22961
+ id: linkId,
22962
+ peerTrust: { verifiedKey: opened?.pairedPeerKey }
22963
+ }]);
22964
+ const then = JSON.stringify(seen?.pairedPeerKey);
22965
+ return {
22966
+ seals,
22967
+ pinned: (link) => JSON.stringify(link?.pairedPeerKey) === then ? opened?.pairedPeerKey : CHANGED
22968
+ };
22969
+ }
22585
22970
  /**
22586
22971
  * Durable local state of the browser peer. Identity seeds live here the same
22587
22972
  * way Desktop keeps them in its WebView storage: local to this profile, never
@@ -22589,11 +22974,12 @@ var RELAXED = { durability: "relaxed" };
22589
22974
  */
22590
22975
  var db = {
22591
22976
  async getLinks() {
22592
- return wrap((await store(STORES$1.links, "readonly")).getAll());
22977
+ return openRows(STORES$1.links, await wrap((await store(STORES$1.links, "readonly")).getAll()));
22593
22978
  },
22594
22979
  async putLink(link) {
22980
+ const row = await sealRow(STORES$1.links, link);
22595
22981
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
22596
- tx.objectStore(STORES$1.links).put(link);
22982
+ tx.objectStore(STORES$1.links).put(row);
22597
22983
  await new Promise((resolve, reject) => {
22598
22984
  tx.oncomplete = () => resolve();
22599
22985
  tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Link storage failed"));
@@ -22601,6 +22987,10 @@ var db = {
22601
22987
  },
22602
22988
  /** `relaxed`: for what a power cut may cost (a round trip, a note made again later), no disk sync of its own. */
22603
22989
  async patchLink(linkId, patch, relaxed = false) {
22990
+ const sealed = await sealRow(STORES$1.links, {
22991
+ ...patch,
22992
+ id: linkId
22993
+ });
22604
22994
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite", relaxed ? RELAXED : void 0);
22605
22995
  const links = tx.objectStore(STORES$1.links);
22606
22996
  const request = links.get(linkId);
@@ -22611,8 +23001,7 @@ var db = {
22611
23001
  }
22612
23002
  links.put({
22613
23003
  ...request.result,
22614
- ...patch,
22615
- id: linkId
23004
+ ...sealed
22616
23005
  });
22617
23006
  };
22618
23007
  await new Promise((resolve, reject) => {
@@ -22674,25 +23063,27 @@ var db = {
22674
23063
  return result;
22675
23064
  },
22676
23065
  async pinPeer(linkId, key, signedSignals = false) {
23066
+ const { seals, pinned } = await pinnedKey(linkId, key);
22677
23067
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
22678
23068
  const links = tx.objectStore(STORES$1.links);
22679
23069
  const request = links.get(linkId);
22680
23070
  request.onsuccess = () => {
22681
23071
  const link = request.result;
22682
- if (!link?.participationSeed || link.pairedPeerKey && link.pairedPeerKey !== key) {
23072
+ const before = pinned(link);
23073
+ if (!link?.participationSeed || before === CHANGED || before && before !== key) {
22683
23074
  tx.abort();
22684
23075
  return;
22685
23076
  }
22686
- links.put({
23077
+ links.put(seals.row(STORES$1.links, {
22687
23078
  ...link,
22688
23079
  peerTrust: link.peerTrust ?? {
22689
23080
  version: 1,
22690
- verifiedKey: link.pairedPeerKey
23081
+ verifiedKey: before
22691
23082
  },
22692
23083
  pairedPeerKey: key,
22693
23084
  requireSignedSignals: link.requireSignedSignals || signedSignals,
22694
23085
  inviteCode: void 0
22695
- });
23086
+ }));
22696
23087
  };
22697
23088
  await new Promise((resolve, reject) => {
22698
23089
  tx.oncomplete = () => resolve();
@@ -22700,23 +23091,24 @@ var db = {
22700
23091
  });
22701
23092
  },
22702
23093
  async verifyPeer(linkId, key) {
23094
+ const { seals, pinned } = await pinnedKey(linkId, key);
22703
23095
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
22704
23096
  const links = tx.objectStore(STORES$1.links);
22705
23097
  const request = links.get(linkId);
22706
23098
  request.onsuccess = () => {
22707
23099
  const link = request.result;
22708
- if (!link?.pairedPeerKey || link.pairedPeerKey !== key) {
23100
+ if (!link?.pairedPeerKey || pinned(link) !== key) {
22709
23101
  tx.abort();
22710
23102
  return;
22711
23103
  }
22712
- links.put({
23104
+ links.put(seals.row(STORES$1.links, {
22713
23105
  ...link,
22714
23106
  peerTrust: {
22715
23107
  version: 1,
22716
23108
  verifiedKey: key,
22717
23109
  verifiedAt: Date.now()
22718
23110
  }
22719
- });
23111
+ }));
22720
23112
  };
22721
23113
  await new Promise((resolve, reject) => {
22722
23114
  tx.oncomplete = () => resolve();
@@ -22924,10 +23316,11 @@ var db = {
22924
23316
  await committed((await store(STORES$1.messages, "readwrite")).delete([linkId, messageId]));
22925
23317
  },
22926
23318
  async getGroups() {
22927
- return wrap((await store(STORES$1.groups, "readonly")).getAll());
23319
+ return openRows(STORES$1.groups, await wrap((await store(STORES$1.groups, "readonly")).getAll()));
22928
23320
  },
22929
23321
  async putGroup(group) {
22930
- await committed((await store(STORES$1.groups, "readwrite")).put(group));
23322
+ const row = await sealRow(STORES$1.groups, group);
23323
+ await committed((await store(STORES$1.groups, "readwrite")).put(row));
22931
23324
  },
22932
23325
  /** The group and its history. */
22933
23326
  async deleteGroup(groupId) {
@@ -23363,10 +23756,22 @@ function pinView(pin) {
23363
23756
  }
23364
23757
  /**
23365
23758
  * Whether a private group's pin was made by someone no longer in its roster (`inRoster`): it goes when they do, so a
23366
- * member removed leaves nothing of theirs at the top of the chat.
23759
+ * member removed leaves nothing of theirs at the top of the chat. Their unpin shows nothing already: it stays.
23367
23760
  */
23368
23761
  function pinOfFormerMember(pin, inRoster) {
23369
- return !!pin && pin.by !== "me" && !inRoster(pin.by);
23762
+ return !!pin?.id && pin.by !== "me" && !inRoster(pin.by);
23763
+ }
23764
+ /**
23765
+ * What a former member's pin is dropped to: an unpin at its number, so only a pin numbered past it shows. Dropped to
23766
+ * none, an older pin a member kept while away (and says again when its edges open) would come back.
23767
+ */
23768
+ function droppedPin(pin, now = Date.now()) {
23769
+ return {
23770
+ id: "",
23771
+ n: pin.n,
23772
+ by: pin.by,
23773
+ at: now
23774
+ };
23370
23775
  }
23371
23776
  /** Whether I may pin in this group now: the rule (`mayPin`) with my key and its admin's. */
23372
23777
  function mayPinIn(group) {
@@ -23374,7 +23779,8 @@ function mayPinIn(group) {
23374
23779
  }
23375
23780
  /**
23376
23781
  * The row a pin names, when it is here: the row of that id (a group's), or of `peer_`/`me_` and that id, or one the host
23377
- * knows that id names (a file of mine, a payment), each read alone; else any other of a chat's.
23782
+ * knows that id names (a file of mine, a payment), each read alone; else any other of a chat's, from the rows the host
23783
+ * knows by another id (`unkeyed`) or, without those, the whole chat.
23378
23784
  */
23379
23785
  async function pinnedRow(host, chat, id) {
23380
23786
  if (!id) return void 0;
@@ -23389,6 +23795,11 @@ async function pinnedRow(host, chat, id) {
23389
23795
  if (row && replyRef(row, group) === id) return row;
23390
23796
  }
23391
23797
  if (group) return void 0;
23798
+ const unkeyed = host.unkeyed?.(chat);
23799
+ if (unkeyed) {
23800
+ const rowId = (await unkeyed).get(id), row = rowId === void 0 ? void 0 : await host.message(chat, rowId);
23801
+ return row && replyRef(row, false) === id ? row : void 0;
23802
+ }
23392
23803
  }
23393
23804
  return reactionTarget(await host.messages(chat), id, group);
23394
23805
  }
@@ -23837,6 +24248,16 @@ var MAX_PENDING_ENTRIES$1 = 8;
23837
24248
  var ENTRY_TIMEOUT_MS$1 = 18e4;
23838
24249
  var ENTRY_UNANSWERED_MS = 9e4;
23839
24250
  /**
24251
+ * Knock records are written by anyone with the link: filled again and again with keys that have no app behind them,
24252
+ * they take every entry session the door opens, each for `ENTRY_UNANSWERED_MS`, and nobody real gets in (8 at a time,
24253
+ * a lone admin's door gave 64 such keys their session in 12 minutes while a real joiner waited the whole time). The
24254
+ * admin is told once this many keys went unanswered within `UNANSWERED_WINDOW_MS` (about 3 minutes of that), and
24255
+ * offered a new link. A busy link stays well under: a joiner whose session never comes up closed its app within
24256
+ * seconds of opening the link and did not open it again.
24257
+ */
24258
+ var UNANSWERED_TELL = 16;
24259
+ var UNANSWERED_WINDOW_MS = 6e5;
24260
+ /**
23840
24261
  * Each attempt to let one joiner in belongs to one hub for this long (see `answerKnocks`): it opens
23841
24262
  * the entry session in the first `KNOCK_SLOT_OPEN_MS` and gives up after `ENTRY_UNANSWERED_MS`,
23842
24263
  * before the turn ends. A paired session over Pkarr can take the better part of a minute to come up.
@@ -24152,7 +24573,8 @@ var Communities = class {
24152
24573
  community: {
24153
24574
  hub: live.hub,
24154
24575
  hubs: hubs.length,
24155
- connected: [...edges.keys()].filter(ready).length
24576
+ connected: [...edges.keys()].filter(ready).length,
24577
+ ...s.isAdmin && live.unansweredTold && { unansweredKnocks: live.unanswered.size }
24156
24578
  },
24157
24579
  members: roster.map(([key, role]) => ({
24158
24580
  key,
@@ -24223,6 +24645,7 @@ var Communities = class {
24223
24645
  await this.startJoining(link, door ? s.state.seedB64 : dialedKey(link), this.now());
24224
24646
  return link.g;
24225
24647
  }
24648
+ 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.");
24226
24649
  }
24227
24650
  if (existing) await this.forget(link.g);
24228
24651
  await this.startJoining(link, dialedKey(link), this.now());
@@ -24438,6 +24861,11 @@ var Communities = class {
24438
24861
  const s = this.require(groupId);
24439
24862
  if (!s.isAdmin) throw new Error("Only the admin can replace or turn off the group's link");
24440
24863
  await this.closeEntries(groupId);
24864
+ const live = this.live.get(groupId);
24865
+ if (live) {
24866
+ live.unanswered = void 0;
24867
+ live.unansweredTold = false;
24868
+ }
24441
24869
  const key = await s.replaceLink(off);
24442
24870
  return key ? encodeCommunityLink({
24443
24871
  g: groupId,
@@ -24728,18 +25156,29 @@ var Communities = class {
24728
25156
  for (const [key, since] of live.pendingEntries) {
24729
25157
  const linkId = this.host.entries(groupId).get(key), up = !!linkId && this.host.linkReady(linkId, 2);
24730
25158
  const elsewhere = rosterHas(s.roster, key) && since < this.addedAt(s, key) + this.timings.knockFallbackMs;
24731
- if (!up && (elsewhere || now - since > ENTRY_UNANSWERED_MS)) live.pendingEntries.delete(key);
24732
- else if (now - since > ENTRY_TIMEOUT_MS$1) {
25159
+ if (!up && (elsewhere || now - since > ENTRY_UNANSWERED_MS)) {
25160
+ live.pendingEntries.delete(key);
25161
+ if (!elsewhere) (live.unanswered ??= /* @__PURE__ */ new Map()).set(key, now);
25162
+ } else if (now - since > ENTRY_TIMEOUT_MS$1) {
24733
25163
  live.pendingEntries.delete(key);
24734
25164
  this.refused.set(key, now + REFUSED_FOR_MS$1);
24735
25165
  } else continue;
24736
25166
  if (linkId) await this.host.closeEdge(linkId);
24737
25167
  }
25168
+ if (live.unanswered) {
25169
+ for (const [key, at] of live.unanswered) if (now - at > UNANSWERED_WINDOW_MS) live.unanswered.delete(key);
25170
+ const tell = live.unanswered.size >= UNANSWERED_TELL;
25171
+ if (tell !== !!live.unansweredTold) {
25172
+ live.unansweredTold = tell;
25173
+ this.host.emit();
25174
+ }
25175
+ }
24738
25176
  if ((s.needsCatchUp || live.tipCheck?.upAt) && now - (live.lastCatchUp ?? 0) >= 5e3 || now - (live.lastCatchUp ?? 0) >= 3e4) {
24739
25177
  live.lastCatchUp = now;
24740
25178
  const ready = [...this.host.edges(groupId)].filter(([key, id]) => this.host.linkReady(id, 2) && !s.wasRemoved(key)).map(([key]) => key);
24741
25179
  for (const key of ready.slice(0, 3)) s.catchUp(key);
24742
25180
  }
25181
+ await s.resume().catch(() => {});
24743
25182
  await s.reseal().catch(() => {});
24744
25183
  await this.reconcile(groupId, live, now);
24745
25184
  }
@@ -24948,7 +25387,7 @@ var Communities = class {
24948
25387
  ts: now,
24949
25388
  load: this.beaconLoad(groupId, live, now),
24950
25389
  since: live.hubSince || now
24951
- } : null, now, (key) => !this.gone(live, key));
25390
+ } : null, now, (key) => !this.gone(live, key), (key) => rosterHas(live.session.roster, key));
24952
25391
  const newest = newerHead(head, this.newestFrame(live), now);
24953
25392
  await this.host.publish(keys.identity, beaconRecords(keys, live.hubClocks.asWritten(hubs), newest), !back, live.hub && !back, back);
24954
25393
  live.beacon = hubs;
@@ -24961,12 +25400,14 @@ var Communities = class {
24961
25400
  }
24962
25401
  /**
24963
25402
  * The beacon's hubs, less those the chain took out: hubs are members. Someone removed while its app was closed lists
24964
- * itself there when it comes back, believing it is a member, until it is told (`wantFarewell`).
25403
+ * itself there when it comes back, believing it is a member, until it is told (`wantFarewell`). A key my roster does
25404
+ * not have is nobody's hub here either (anyone holding the rendezvous secret can write one in), though it stays in the
25405
+ * beacon I write: a member behind on the roster must not erase the newest hubs.
24965
25406
  */
24966
25407
  hubs(live) {
24967
25408
  const top = live.session.top, leaves = live.session.state.pendingLeaves, memo = live.hubsMemo;
24968
25409
  if (memo && memo.beacon === live.beacon && memo.top === top && memo.leaves === leaves) return memo.hubs;
24969
- const hubs = live.beacon.filter((h) => !this.gone(live, h.key));
25410
+ const hubs = live.beacon.filter((h) => !this.gone(live, h.key) && rosterHas(live.session.roster, h.key));
24970
25411
  live.hubsMemo = {
24971
25412
  beacon: live.beacon,
24972
25413
  top,
@@ -25667,7 +26108,8 @@ var Communities = class {
25667
26108
  return;
25668
26109
  }
25669
26110
  if (!await live.session.handle(peerKey, frame) || !live.hub) return;
25670
- for (const [key, id] of this.hearers(groupId, f)) if (key !== peerKey) this.sendTo(id, f);
26111
+ const out = live.session.passOn(f);
26112
+ for (const [key, id] of this.hearers(groupId, f)) if (key !== peerKey) this.sendTo(id, out);
25671
26113
  }
25672
26114
  peerIsHub(live, key) {
25673
26115
  return this.recentHub(live, key) && !live.members.has(key) && !live.session.wasRemoved(key);
@@ -25743,7 +26185,6 @@ var Communities = class {
25743
26185
  const file = m.file && this.files && !this.stored.get(id)?.removedIds?.includes(m.id) ? await this.files.announced(id, {
25744
26186
  id: m.id,
25745
26187
  sender: m.sender,
25746
- ts: m.timestamp,
25747
26188
  file: m.file
25748
26189
  }, session.myKey) : void 0;
25749
26190
  const placing = this.lineOrder.placing(MESSAGE_LINK$1(id), {
@@ -25765,7 +26206,7 @@ var Communities = class {
25765
26206
  ...m.card && { card: m.card },
25766
26207
  ...file && { file },
25767
26208
  ...m.frame && { frame: m.frame }
25768
- });
26209
+ }, m.live);
25769
26210
  placing(stored !== false);
25770
26211
  if (stored === false && this.stored.get(id)?.removedIds?.includes(m.id)) return false;
25771
26212
  const came = m.sender === session.myKey ? timestamp : cameAt(timestamp, stored, arrivalNow(this.now()));
@@ -25778,6 +26219,7 @@ var Communities = class {
25778
26219
  },
25779
26220
  app: (m) => this.deliver(id, () => m.frame.t === "group-have" ? this.files?.communityApp(id, m.sender, m.frame) : this.host.communityApp?.(id, m.sender, m.frame)),
25780
26221
  lasting: (m) => m.frame.t === "pin" && m.sender === session.admin ? "pin" : void 0,
26222
+ fleeting: (frame) => frame.t === GROUP_HAVE_FRAME,
25781
26223
  pair: (m) => this.deliver(id, () => this.host.communityPair?.(id, m.sender, m.payload)),
25782
26224
  changed: () => {
25783
26225
  this.membershipChanged(id);
@@ -26585,7 +27027,8 @@ var MeshHubs = class {
26585
27027
  }
26586
27028
  /**
26587
27029
  * As a hub, what the session took for the first time goes on to every other edge that is up: not back where it came
26588
- * from, nor to its author. Everyone else takes it as a frame handed on (WISP 902 § Catch-up).
27030
+ * from, nor to its author. Everyone else takes it as a frame handed on (WISP 902 § Catch-up); a member, a commit with
27031
+ * the epoch's secret sealed for it when I hold it (`GroupSession.handOnTo`), so it can write at once.
26589
27032
  */
26590
27033
  passOn(groupId, session, from, frames) {
26591
27034
  if (!this.live.get(groupId)?.hub || !frames.length) return 0;
@@ -26597,7 +27040,7 @@ var MeshHubs = class {
26597
27040
  for (const frame of frames) {
26598
27041
  if (authorOf(frame) === key || !member && (frame.t !== "group-commit" || frame.commit.e > until)) continue;
26599
27042
  try {
26600
- this.host.sendOnLink(id, frame);
27043
+ this.host.sendOnLink(id, member ? session.handOnTo(key, frame) : frame);
26601
27044
  sent++;
26602
27045
  } catch {
26603
27046
  break;
@@ -26619,7 +27062,8 @@ function authorOf(frame) {
26619
27062
  switch (frame.t) {
26620
27063
  case "group-msg":
26621
27064
  case "group-edit": return frame.s;
26622
- case "group-bye": return frame.k;
27065
+ case "group-bye":
27066
+ case "group-name": return frame.k;
26623
27067
  case "group-commit": return frame.commit.by;
26624
27068
  case "group-meta": return frame.by;
26625
27069
  default: return;
@@ -27166,6 +27610,14 @@ var KNOCK_VERIFY_SPREAD_MS = 700;
27166
27610
  /** Entry sessions the admin runs at once; a joiner who does not finish in time is not answered again for a while. */
27167
27611
  var MAX_PENDING_ENTRIES = 4;
27168
27612
  var ENTRY_TIMEOUT_MS = 18e4;
27613
+ /**
27614
+ * A link whose entry sessions keep timing out with nobody ever on the other side lets nobody in: anyone holding it can
27615
+ * write the knock record with keys no app holds, fresh each time, and they take the `MAX_PENDING_ENTRIES` places a
27616
+ * joiner is answered in. This many such sessions within `JAMMED_WINDOW_MS` tell the admin (`GroupView.entryJammed`),
27617
+ * whose new link reaches none of them; joiners who knock and close their app are a few.
27618
+ */
27619
+ var JAMMED_ENTRIES = 8;
27620
+ var JAMMED_WINDOW_MS = 9e5;
27169
27621
  /** A joiner refused (its app cannot follow the group) is not answered again for this long. */
27170
27622
  var REFUSED_FOR_MS = 6e5;
27171
27623
  /**
@@ -27199,6 +27651,13 @@ var ENTRY_RELEASE_MS = 2e3;
27199
27651
  var REMOVED_LINGER_MS = 15e3;
27200
27652
  /** How long the tombstone of a group I left waits for the admin to hear it. */
27201
27653
  var LEFT_KEPT_MS = 6048e5;
27654
+ /**
27655
+ * A tombstone the role reached (a hand-over that crossed my leave) hands it on this long after: a leave its giver said
27656
+ * right after its `role` commit (an admin's leave does) is heard first, so the role does not go back to a leaver.
27657
+ */
27658
+ var LEFT_HAND_ON_MS = 1e3;
27659
+ /** The commits of my chain since my leave said to the admin my leave follows, before the leave (it may lack them). */
27660
+ var LEFT_COMMITS = 16;
27202
27661
  /** Admin side: how long a contact invited over its chat is waited for. After, it holds no place and may be invited again. */
27203
27662
  var INVITED_KEPT_MS = LEFT_KEPT_MS;
27204
27663
  /**
@@ -27214,6 +27673,8 @@ var ACCEPT_AGAINS = 5;
27214
27673
  var REWELCOME_MS = ACCEPT_AGAIN_MS / 2;
27215
27674
  /** Invitee side: the invitations one contact chat may have waiting here at a time. More are answered as declined. */
27216
27675
  var MAX_INVITATIONS_PER_CHAT = 4;
27676
+ /** Other groups kept beside one under its id (`StoredGroup.others`), at most; an invitation past them is declined. */
27677
+ var MAX_OTHER_GROUPS = 4;
27217
27678
  /** Invitee side, removed and invited again: the chat that let me into the group I kept, if it is its admin's. */
27218
27679
  var keptAdminChat = (kept) => {
27219
27680
  const admin = kept?.state && rosterAdmin(kept.state.chain[kept.state.chain.length - 1].m);
@@ -27325,6 +27786,10 @@ var Groups = class {
27325
27786
  reconciling = Promise.resolve();
27326
27787
  /** Admin side: joiners with an entry session open, per group: member key → since when. */
27327
27788
  pendingEntries = /* @__PURE__ */ new Map();
27789
+ /** Admin side: of those, the ones whose other side was seen, once and for as long as they are open, per group. */
27790
+ entriesSeen = /* @__PURE__ */ new Map();
27791
+ /** Admin side: when entry sessions nobody was ever on the other side of timed out, per group (`JAMMED_ENTRIES`). */
27792
+ unansweredEntries = /* @__PURE__ */ new Map();
27328
27793
  /** Admin side: member keys whose entry did not finish, not answered again until then. */
27329
27794
  refused = /* @__PURE__ */ new Map();
27330
27795
  /** Admin side: entry sessions of a member key that timed out in a row, and when the last did. */
@@ -27332,6 +27797,8 @@ var Groups = class {
27332
27797
  lastPoll = /* @__PURE__ */ new Map();
27333
27798
  /** Admin side: when a link nobody is using was last read. Those links share one `pollMs` between them, read in turn. */
27334
27799
  lastQuietPoll = 0;
27800
+ /** Admin side: until when the relays' budget holds back reads of a group's link (`pollKnocks`). */
27801
+ knocksHeldUntil = /* @__PURE__ */ new Map();
27335
27802
  /** Admin side: until when a group's link is looked at the warm pace. */
27336
27803
  warmUntil = /* @__PURE__ */ new Map();
27337
27804
  lastKnock = /* @__PURE__ */ new Map();
@@ -27355,6 +27822,8 @@ var Groups = class {
27355
27822
  lingering = /* @__PURE__ */ new Map();
27356
27823
  /** Joiner side: groups whose knock is published, for the stage the joiner is shown. */
27357
27824
  knocked = /* @__PURE__ */ new Set();
27825
+ /** Joiner side: groups whose knock record held others' fresh knocks when I last read it (`othersKnocked`). */
27826
+ othersKnocked = /* @__PURE__ */ new Set();
27358
27827
  /**
27359
27828
  * Per mesh group, the member each unreachable member's messages were asked of (in a sync): asked of one member at a
27360
27829
  * time, not of everyone whose edge opens, so a member coming back is not sent the same messages by every other.
@@ -27520,6 +27989,7 @@ var Groups = class {
27520
27989
  bytes: frameBytes(m.frame)
27521
27990
  })));
27522
27991
  if (group.state) this.attach(group.state, framed.map((m) => m.frame));
27992
+ this.ownRows(group.id, history);
27523
27993
  if (group.invited) this.invited.set(group.id, new Set(Object.keys(group.invited)));
27524
27994
  loadMarks(this.marks, group, history);
27525
27995
  this.host.loaded?.(group.id, history);
@@ -27591,7 +28061,8 @@ var Groups = class {
27591
28061
  ...peerMessageAt(this.lastPeerMessageAt, group.id),
27592
28062
  ...mentionAt(this.lastMentionAt, group.id),
27593
28063
  invited: [...this.invited.get(group.id) ?? []],
27594
- memberLinks: Object.fromEntries(contacts.map(([key, linkId]) => [linkId, key]))
28064
+ memberLinks: Object.fromEntries(contacts.map(([key, linkId]) => [linkId, key])),
28065
+ ...group.others?.length ? { others: group.others.map((other) => this.otherView(other)) } : {}
27595
28066
  };
27596
28067
  if (!session) {
27597
28068
  const invitation = group.invitation;
@@ -27613,7 +28084,8 @@ var Groups = class {
27613
28084
  ...invitation.entry ? {
27614
28085
  viaLink: true,
27615
28086
  stage: this.joinStage(group),
27616
- ...this.gaveUp.has(group.id) && { unanswered: true }
28087
+ ...this.gaveUp.has(group.id) && { unanswered: true },
28088
+ ...this.othersKnocked.has(group.id) && { othersKnocked: true }
27617
28089
  } : {}
27618
28090
  }
27619
28091
  };
@@ -27635,6 +28107,7 @@ var Groups = class {
27635
28107
  myKey: session.myKey,
27636
28108
  isAdmin: session.isAdmin,
27637
28109
  ...entry ? { entryLink: encodeGroupEntryLink(entry.link) } : {},
28110
+ ...entry && (this.unansweredEntries.get(group.id)?.length ?? 0) >= JAMMED_ENTRIES ? { entryJammed: true } : {},
27638
28111
  ...session.picture ? { picture: session.picture } : {},
27639
28112
  canSend: session.status === "active" && session.readableEpochs.includes(session.epoch),
27640
28113
  ...onHubs ? { hubs: { hub: this.hubs.isHub(group.id) } } : {},
@@ -27657,6 +28130,15 @@ var Groups = class {
27657
28130
  })
27658
28131
  };
27659
28132
  }
28133
+ otherView(other) {
28134
+ if ("link" in other) return { link: other.link };
28135
+ return {
28136
+ linkId: other.linkId,
28137
+ contact: this.host.contactName(other.linkId) ?? "",
28138
+ name: groupName(other.name) ?? "",
28139
+ members: Math.min(Math.max(other.n, 0), GROUP_MEMBER_CAP.max)
28140
+ };
28141
+ }
27660
28142
  messages(groupId) {
27661
28143
  return this.store.getMessages(MESSAGE_LINK(groupId));
27662
28144
  }
@@ -27823,12 +28305,80 @@ var Groups = class {
27823
28305
  if (!group.previous) return this.forget(groupId);
27824
28306
  await this.dropInvitation(group, this.sayDecline(groupId, group.invitation.linkId));
27825
28307
  }
28308
+ /**
28309
+ * Another group under the id of one held (`StoredGroup.others`): kept beside it and shown, for the person to pick. One
28310
+ * per contact chat (said again, it replaces its own) and one link; past `MAX_OTHER_GROUPS` a contact's is declined, so
28311
+ * its inviter is told rather than left counting me as invited.
28312
+ */
28313
+ async noteOther(group, other) {
28314
+ const kept = (group.others ?? []).filter((o) => "link" in other ? !("link" in o) : !("linkId" in o) || o.linkId !== other.linkId);
28315
+ if (kept.length >= MAX_OTHER_GROUPS) {
28316
+ if ("linkId" in other) this.sayDecline(group.id, other.linkId);
28317
+ return;
28318
+ }
28319
+ group.others = [...kept, other];
28320
+ await this.store.putGroup(group);
28321
+ this.host.emit();
28322
+ }
28323
+ /** The others under a group's id go, each contact who invited told no (best effort: its invitation ages out otherwise). */
28324
+ declineOthers(group) {
28325
+ for (const other of group.others ?? []) if ("linkId" in other) this.sayDecline(group.id, other.linkId);
28326
+ delete group.others;
28327
+ }
28328
+ /** The group held under this id is the real one: the others that came under it go, their inviters told no. */
28329
+ async keepGroup(groupId) {
28330
+ const group = this.stored.get(groupId);
28331
+ if (!group?.others) return;
28332
+ this.declineOthers(group);
28333
+ await this.store.putGroup(group);
28334
+ this.host.emit();
28335
+ }
28336
+ /**
28337
+ * Another group under this id is the real one (`to`: its contact chat, or its link): the group held goes as Delete
28338
+ * takes it (left, or its invitation declined), the rest of the others are told no, and the one picked takes its place:
28339
+ * a contact's invitation waits for Accept, a link is joined.
28340
+ */
28341
+ async switchGroup(groupId, to) {
28342
+ const group = this.stored.get(groupId);
28343
+ const other = group?.others?.find((o) => "link" in o ? o.link === to : o.linkId === to);
28344
+ if (!group || !other) throw new Error("No other group under this id");
28345
+ const others = group.others;
28346
+ group.others = others.filter((o) => o !== other);
28347
+ try {
28348
+ await this.forget(groupId);
28349
+ } catch (error) {
28350
+ group.others = others;
28351
+ throw error;
28352
+ }
28353
+ if ("link" in other) {
28354
+ await this.joinByLink(other.link);
28355
+ return;
28356
+ }
28357
+ const declined = this.stored.get(groupId)?.declined;
28358
+ const invitation = {
28359
+ id: groupId,
28360
+ createdAt: Date.now(),
28361
+ invitation: {
28362
+ name: other.name,
28363
+ admin: other.admin,
28364
+ linkId: other.linkId,
28365
+ e: other.e,
28366
+ n: other.n,
28367
+ pieces: []
28368
+ },
28369
+ ...declined ? { declined } : {}
28370
+ };
28371
+ this.stored.set(groupId, invitation);
28372
+ await this.store.putGroup(invitation);
28373
+ this.host.emit();
28374
+ }
27826
28375
  /** An invitation goes from the list: declined here (`owed`: the answer, when it could not be sent), or taken back by who sent it. */
27827
28376
  async dropInvitation(group, owed) {
27828
28377
  const previous = group.previous;
27829
28378
  if (!previous) return this.forget(group.id, false);
27830
28379
  if (owed) previous.declined = owed;
27831
28380
  else if (previous.declined?.linkId === group.invitation?.linkId) delete previous.declined;
28381
+ if (group.others) previous.others = group.others;
27832
28382
  this.acceptSaid.delete(group.id);
27833
28383
  this.stored.set(group.id, previous);
27834
28384
  if (previous.state) this.attach(previous.state);
@@ -28010,6 +28560,26 @@ var Groups = class {
28010
28560
  });
28011
28561
  }
28012
28562
  /**
28563
+ * Whom the role goes on to from a member it reached while its leave was under way (WISP 902 § Admission and
28564
+ * departure, "A role that reaches a leave"): `by`, who handed it to me, while it stays; else the first other member
28565
+ * whose edge is up, else the first in the roster. Never one whose leave I heard, nor one I handed the role to
28566
+ * myself (an admin who left): with two leavers the role would go back and forth between them.
28567
+ */
28568
+ nextAdmin(groupId, session, by) {
28569
+ const heard = this.leavesHeard.get(groupId), handed = new Set(session.state.chain.filter((c) => c.k === "role" && c.by === session.myKey).map((c) => c.s));
28570
+ const eligible = session.others.filter((key) => !heard?.has(key) && !handed.has(key));
28571
+ if (by && eligible.includes(by)) return by;
28572
+ const edges = this.host.edges(groupId);
28573
+ return eligible.find((key) => {
28574
+ const edge = edges.get(key);
28575
+ return !!edge && this.host.linkReady(edge);
28576
+ }) ?? eligible[0];
28577
+ }
28578
+ /** Members whose leave reached my tombstone of their group: the role a hand-over gave me does not go on to them. */
28579
+ leavesHeard = /* @__PURE__ */ new Map();
28580
+ /** Tombstones the role reached, and when they hand it on (`LEFT_HAND_ON_MS`). */
28581
+ handOnAt = /* @__PURE__ */ new Map();
28582
+ /**
28013
28583
  * Leaves, and the group is gone from this device at once: its row, its history, its files and every
28014
28584
  * edge but the one to the admin, which stays until the admin's commit removing me comes back (or a
28015
28585
  * week passes), so a leave said while the admin was away still reaches it. An admin with other
@@ -28045,8 +28615,11 @@ var Groups = class {
28045
28615
  bye: bye ?? session.byeFrame()
28046
28616
  };
28047
28617
  delete group.entry;
28618
+ this.declineOthers(group);
28048
28619
  this.takeBack(groupId, group);
28049
28620
  this.pendingEntries.delete(groupId);
28621
+ this.entriesSeen.delete(groupId);
28622
+ this.unansweredEntries.delete(groupId);
28050
28623
  this.welcomed.delete(groupId);
28051
28624
  this.lingering.delete(groupId);
28052
28625
  dropMarks(this.marks, groupId);
@@ -28066,14 +28639,22 @@ var Groups = class {
28066
28639
  } catch {}
28067
28640
  }
28068
28641
  }
28069
- await session.leave();
28642
+ await session.leave(() => this.nextAdmin(groupId, session, session.top.k === "role" && session.top.s === session.myKey ? session.top.by : void 0));
28643
+ const holder = session.admin, handed = !next && session.top.k === "role" && session.top.by === session.myKey ? holder : void 0;
28644
+ if (holder && holder !== admin && holder !== session.myKey && group.left) {
28645
+ group.left = {
28646
+ ...group.left,
28647
+ admin: holder
28648
+ };
28649
+ await this.store.putGroup(group);
28650
+ }
28070
28651
  if (bye) for (const key of hubs) {
28071
28652
  const edge = this.host.edges(groupId).get(key);
28072
28653
  if (edge && this.host.linkReady(edge)) try {
28073
28654
  this.host.sendOnLink(edge, bye);
28074
28655
  } catch {}
28075
28656
  }
28076
- const contact = group.contacts?.[admin];
28657
+ const contact = group.contacts?.[group.left?.admin ?? admin];
28077
28658
  if (contact) try {
28078
28659
  this.host.sendOnLink(contact, {
28079
28660
  t: "group-leave",
@@ -28082,7 +28663,7 @@ var Groups = class {
28082
28663
  } catch {}
28083
28664
  this.reconcileEdges(groupId);
28084
28665
  this.host.emit();
28085
- return next;
28666
+ return next ?? handed;
28086
28667
  }
28087
28668
  /**
28088
28669
  * The signed leave of my old key the admin has still to hear (`StoredGroup.owedBye`): none once the old key is out of
@@ -28298,16 +28879,22 @@ var Groups = class {
28298
28879
  }
28299
28880
  const gone = this.stored.get(groupId), invitation = answer && gone?.invitation && !gone.invitation.entry && !gone.invitation.takenBack ? gone.invitation : void 0;
28300
28881
  const owed = invitation && this.sayDecline(groupId, invitation.linkId);
28882
+ if (gone) this.declineOthers(gone);
28301
28883
  this.sessions.delete(groupId);
28302
28884
  this.stored.delete(groupId);
28885
+ this.leavesHeard.delete(groupId);
28886
+ this.handOnAt.delete(groupId);
28303
28887
  this.takeBack(groupId);
28304
28888
  this.acceptSaid.delete(groupId);
28305
28889
  this.entryHosts.delete(groupId);
28306
28890
  this.lastRoster.delete(groupId);
28307
28891
  this.lastTold.delete(groupId);
28308
28892
  this.pendingEntries.delete(groupId);
28893
+ this.entriesSeen.delete(groupId);
28894
+ this.unansweredEntries.delete(groupId);
28309
28895
  this.framesKept.delete(groupId);
28310
28896
  this.knocked.delete(groupId);
28897
+ this.othersKnocked.delete(groupId);
28311
28898
  this.knockCheckAt.delete(groupId);
28312
28899
  this.knockRewrites.delete(groupId);
28313
28900
  this.knockingSince.delete(groupId);
@@ -28368,6 +28955,7 @@ var Groups = class {
28368
28955
  };
28369
28956
  await this.store.putGroup(group);
28370
28957
  this.lastPoll.delete(groupId);
28958
+ this.knocksHeldUntil.delete(groupId);
28371
28959
  }
28372
28960
  this.warmUntil.set(groupId, Date.now() + this.timings.warmMs);
28373
28961
  this.host.emit();
@@ -28402,12 +28990,24 @@ var Groups = class {
28402
28990
  if (!link) throw new Error("This is not a link to a group");
28403
28991
  if (this.isCommunity(link.g)) throw new Error("This group is joined with its current link");
28404
28992
  const existing = this.stored.get(link.g);
28405
- if (existing?.state?.status === "active") return link.g;
28993
+ if (existing?.state?.status === "active") {
28994
+ if (!(this.sessions.get(link.g)?.isAdmin && this.entryOf(existing)?.link.host === link.host)) await this.noteOther(existing, {
28995
+ at: Date.now(),
28996
+ link: encodeGroupEntryLink(link)
28997
+ });
28998
+ return link.g;
28999
+ }
28406
29000
  if (existing?.invitation?.entry === link.host) {
28407
29001
  if (!existing.state) await this.knockAgain(existing);
28408
29002
  return link.g;
28409
29003
  }
28410
- if (existing?.invitation?.seedB64 && !existing.invitation.entry) throw new Error("You are already joining this group");
29004
+ if (existing?.invitation && !existing.invitation.entry && !existing.invitation.takenBack) {
29005
+ await this.noteOther(existing, {
29006
+ at: Date.now(),
29007
+ link: encodeGroupEntryLink(link)
29008
+ });
29009
+ return link.g;
29010
+ }
28411
29011
  if (existing?.invitation && !existing.invitation.entry) throw new Error("You have an invitation to this group. Answer it first.");
28412
29012
  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.");
28413
29013
  const owedBye = existing?.left?.bye ?? existing?.owedBye, declined = existing?.declined;
@@ -28447,7 +29047,12 @@ var Groups = class {
28447
29047
  const quiet = [];
28448
29048
  for (const group of [...this.stored.values()]) {
28449
29049
  if (group.left) {
28450
- if (now - group.left.at > LEFT_KEPT_MS) await this.forget(group.id);
29050
+ if (now - group.left.at > LEFT_KEPT_MS) {
29051
+ await this.forget(group.id);
29052
+ continue;
29053
+ }
29054
+ const session = this.sessions.get(group.id);
29055
+ if (session?.status === "left" && session.admin === session.myKey && now >= (this.handOnAt.get(group.id) ?? 0)) await this.handOn(group.id);
28451
29056
  continue;
28452
29057
  }
28453
29058
  if (group.declined) {
@@ -28485,9 +29090,11 @@ var Groups = class {
28485
29090
  await this.disableLink(group.id);
28486
29091
  continue;
28487
29092
  }
28488
- const pending = this.pendingEntries.get(group.id);
29093
+ const pending = this.pendingEntries.get(group.id), seen = this.seenEntries(group.id);
29094
+ let unanswered = 0;
28489
29095
  for (const [key, since] of pending ?? []) if (now - since > ENTRY_TIMEOUT_MS) {
28490
29096
  pending.delete(key);
29097
+ if (!seen.delete(key)) unanswered++;
28491
29098
  const timeouts = (this.entryTimeouts.get(key)?.count ?? 0) + 1;
28492
29099
  this.entryTimeouts.set(key, {
28493
29100
  count: timeouts,
@@ -28497,23 +29104,22 @@ var Groups = class {
28497
29104
  const linkId = this.host.entries(group.id).get(key);
28498
29105
  if (linkId) await this.host.closeEdge(linkId);
28499
29106
  }
29107
+ this.noteUnanswered(group.id, now, unanswered);
28500
29108
  const busy = (pending?.size ?? 0) >= MAX_PENDING_ENTRIES || session.roster.length + (pending?.size ?? 0) >= GROUP_MEMBER_CAP.max;
28501
29109
  const since = now - (this.lastPoll.get(group.id) ?? 0);
28502
29110
  if (busy) continue;
29111
+ const held = this.knocksHeldUntil.get(group.id);
29112
+ if (held !== void 0 && now < held) continue;
28503
29113
  if (now >= (this.warmUntil.get(group.id) ?? 0)) {
28504
- if (since >= this.timings.pollMs) quiet.push(group.id);
28505
- } else if (since >= this.timings.warmPollMs) {
28506
- this.lastPoll.set(group.id, now);
28507
- await this.answerKnocks(group, session, now).catch(() => {});
28508
- }
29114
+ if (since >= this.timings.pollMs || held !== void 0) quiet.push(group.id);
29115
+ } else if (since >= this.timings.warmPollMs || held !== void 0) await this.pollKnocks(group, session, now);
28509
29116
  }
28510
29117
  if (quiet.length && now - this.lastQuietPoll >= this.timings.pollMs) {
28511
29118
  const groupId = quiet.reduce((a, b) => (this.lastPoll.get(b) ?? 0) < (this.lastPoll.get(a) ?? 0) ? b : a);
28512
29119
  const group = this.stored.get(groupId), session = this.sessions.get(groupId);
28513
29120
  if (group?.entry && !group.left && session?.isAdmin) {
28514
29121
  this.lastQuietPoll = now;
28515
- this.lastPoll.set(groupId, now);
28516
- await this.answerKnocks(group, session, now).catch(() => {});
29122
+ await this.pollKnocks(group, session, now);
28517
29123
  }
28518
29124
  }
28519
29125
  for (const [key, until] of this.refused) if (until <= now) this.refused.delete(key);
@@ -28686,6 +29292,8 @@ var Groups = class {
28686
29292
  }
28687
29293
  async closeEntries(groupId) {
28688
29294
  this.pendingEntries.delete(groupId);
29295
+ this.entriesSeen.delete(groupId);
29296
+ this.unansweredEntries.delete(groupId);
28689
29297
  this.welcomed.delete(groupId);
28690
29298
  const invited = this.invited.get(groupId);
28691
29299
  for (const linkId of this.host.entries(groupId).values()) {
@@ -28707,6 +29315,7 @@ var Groups = class {
28707
29315
  this.knockingSince.set(group.id, now);
28708
29316
  this.lastKnock.delete(group.id);
28709
29317
  this.knocked.delete(group.id);
29318
+ this.othersKnocked.delete(group.id);
28710
29319
  this.knockRewrites.delete(group.id);
28711
29320
  await this.reopenEntry(group);
28712
29321
  this.host.emit();
@@ -28737,6 +29346,12 @@ var Groups = class {
28737
29346
  others: existing.length,
28738
29347
  ...mine ? { mine: now - mine.ts } : {}
28739
29348
  });
29349
+ const crowd = existing.some((k) => k.key !== key && now - k.ts < 3e4 + this.timings.knockMs);
29350
+ if (crowd !== this.othersKnocked.has(group.id)) {
29351
+ if (crowd) this.othersKnocked.add(group.id);
29352
+ else this.othersKnocked.delete(group.id);
29353
+ this.host.emit();
29354
+ }
28740
29355
  if (mine && now - mine.ts >= 0 && now - mine.ts < 3e4) {
28741
29356
  this.knockRewrites.delete(group.id);
28742
29357
  if (!this.knocked.has(group.id)) {
@@ -28758,13 +29373,45 @@ var Groups = class {
28758
29373
  this.host.emit();
28759
29374
  }
28760
29375
  }
29376
+ /**
29377
+ * Let in: my knock leaves the link's record. Left there until it aged out, the next joiner read it as someone still
29378
+ * waiting, and was told the admin's app may be busy letting them in. Once, in the background; if it fails, it ages out.
29379
+ */
29380
+ async unknock(link, seedB64) {
29381
+ const me = identityFromSeedB64(seedB64).pubKeyZ32, identity = knockIdentity(link);
29382
+ const knocks = readKnocks(link, await this.host.resolve(identity.pubKeyZ32, true) ?? []);
29383
+ if (!knocks.some((k) => k.key === me)) return;
29384
+ await this.host.publish(identity, knockRecords(link, knocks.filter((k) => k.key !== me)), true);
29385
+ }
29386
+ /**
29387
+ * Reads the link's knocks, and counts the read only if the relays answered it. One their budget held back answered
29388
+ * the record as last read: taken for a reading, the knock that came meanwhile waited for the next turn, and a burst's
29389
+ * tenth joiner waited ~40 s with the admin's app open. The link keeps its place and is read once the hold ends.
29390
+ */
29391
+ async pollKnocks(group, session, now) {
29392
+ const before = this.lastPoll.get(group.id);
29393
+ this.lastPoll.set(group.id, now);
29394
+ const held = await this.answerKnocks(group, session, now).catch(() => void 0);
29395
+ if (held === void 0) {
29396
+ this.knocksHeldUntil.delete(group.id);
29397
+ return;
29398
+ }
29399
+ this.knocksHeldUntil.set(group.id, now + held);
29400
+ if (before === void 0) this.lastPoll.delete(group.id);
29401
+ else this.lastPoll.set(group.id, before);
29402
+ }
29403
+ /** Answers the knocks in the link's record; how long the relays' budget still holds its reads back, if it held this one. */
28761
29404
  async answerKnocks(group, session, now) {
28762
29405
  const entry = this.entryOf(group);
28763
29406
  const started = Date.now();
28764
- const knocks = readKnocks(entry.link, await this.host.resolve(knockIdentity(entry.link).pubKeyZ32) ?? []);
29407
+ const knockKey = knockIdentity(entry.link).pubKeyZ32;
29408
+ const records = await this.host.resolve(knockKey).catch(() => null);
29409
+ const held = this.host.readHeldBackFor?.(knockKey);
29410
+ const knocks = readKnocks(entry.link, records ?? []);
28765
29411
  traceJoin(group.id, "knocks.read", {
28766
29412
  ms: Date.now() - started,
28767
- knocks: knocks.length
29413
+ knocks: knocks.length,
29414
+ ...held !== void 0 && { held }
28768
29415
  });
28769
29416
  let pending = this.pendingEntries.get(group.id);
28770
29417
  let ever;
@@ -28787,6 +29434,27 @@ var Groups = class {
28787
29434
  pending.delete(key);
28788
29435
  }
28789
29436
  }
29437
+ return held;
29438
+ }
29439
+ /** The admin's entry sessions of this group whose other side was seen, once and for as long as they are open. */
29440
+ seenEntries(groupId) {
29441
+ let seen = this.entriesSeen.get(groupId);
29442
+ if (!seen) this.entriesSeen.set(groupId, seen = /* @__PURE__ */ new Set());
29443
+ const pending = this.pendingEntries.get(groupId), entries = this.host.entries(groupId);
29444
+ for (const key of seen) if (!pending?.has(key)) seen.delete(key);
29445
+ for (const key of pending?.keys() ?? []) {
29446
+ const linkId = entries.get(key);
29447
+ if (linkId && (this.host.linkReady(linkId) || this.host.linkSeen?.(linkId))) seen.add(key);
29448
+ }
29449
+ return seen;
29450
+ }
29451
+ /** Entry sessions that timed out with nobody ever on the other side, kept for `JAMMED_WINDOW_MS`: the admin is told past `JAMMED_ENTRIES`. */
29452
+ noteUnanswered(groupId, now, count) {
29453
+ const before = this.unansweredEntries.get(groupId) ?? [];
29454
+ const times = [...before.filter((at) => now - at <= JAMMED_WINDOW_MS), ...Array(count).fill(now)];
29455
+ if (times.length) this.unansweredEntries.set(groupId, times);
29456
+ else this.unansweredEntries.delete(groupId);
29457
+ if (before.length >= JAMMED_ENTRIES !== times.length >= JAMMED_ENTRIES) this.host.emit();
28790
29458
  }
28791
29459
  /** The admin's entry session this link is, and whom it is pinned to. */
28792
29460
  hostEntry(groupId, linkId) {
@@ -28808,8 +29476,15 @@ var Groups = class {
28808
29476
  case "group-invite": {
28809
29477
  if (typeof frame.admin !== "string" || !MEMBER_KEY.test(frame.admin) || typeof frame.name !== "string") return;
28810
29478
  const existing = this.stored.get(g);
29479
+ const other = () => this.noteOther(existing, {
29480
+ at: Date.now(),
29481
+ linkId,
29482
+ name: groupName(frame.name) ?? "Group",
29483
+ admin: frame.admin,
29484
+ ...invitationClaims(frame)
29485
+ });
28811
29486
  if (existing?.invitation?.entry && !existing.state) {
28812
- if (existing.invitation.linkId !== linkId) return;
29487
+ if (existing.invitation.linkId !== linkId) return other();
28813
29488
  existing.invitation = {
28814
29489
  ...existing.invitation,
28815
29490
  name: groupName(frame.name) ?? "Group",
@@ -28832,11 +29507,14 @@ var Groups = class {
28832
29507
  t: "group-decline",
28833
29508
  g
28834
29509
  });
29510
+ const session = this.sessions.get(g);
29511
+ if (session && !rosterHas(session.roster, frame.admin)) await other();
28835
29512
  return;
28836
29513
  }
28837
- if (existing?.invitation?.seedB64 && (existing.invitation.linkId !== linkId || existing.invitation.admin !== frame.admin)) return;
29514
+ if (existing?.invitation?.seedB64 && existing.invitation.linkId !== linkId) return other();
29515
+ if (existing?.invitation?.seedB64 && existing.invitation.admin !== frame.admin) return;
28838
29516
  if (existing?.left && (existing.left.admin !== frame.admin || existing.contacts?.[existing.left.admin] !== linkId)) return;
28839
- if (existing?.invitation && !existing.state && existing.invitation.linkId !== linkId && !(existing.invitation.genesis && linkId === keptAdminChat(existing.previous)) && !existing.invitation.takenBack) return;
29517
+ if (existing?.invitation && !existing.state && existing.invitation.linkId !== linkId && !(existing.invitation.genesis && linkId === keptAdminChat(existing.previous)) && !existing.invitation.takenBack) return other();
28840
29518
  if ([...this.stored.values()].filter((x) => x.invitation && !x.invitation.takenBack).length >= 32) return;
28841
29519
  if (!(existing?.invitation && !existing.invitation.takenBack && existing.invitation.linkId === linkId) && [...this.stored.values()].filter((x) => x.invitation?.linkId === linkId && !x.invitation.takenBack).length >= MAX_INVITATIONS_PER_CHAT) {
28842
29520
  try {
@@ -28853,6 +29531,7 @@ var Groups = class {
28853
29531
  };
28854
29532
  const previous = existing?.state ? existing : existing?.previous;
28855
29533
  const genesis = existing?.state ? commitHash(existing.state.chain[0]) : existing?.invitation?.genesis;
29534
+ const others = existing?.others?.filter((o) => !("linkId" in o) || o.linkId !== linkId);
28856
29535
  const invitation = {
28857
29536
  id: g,
28858
29537
  createdAt: Date.now(),
@@ -28865,7 +29544,8 @@ var Groups = class {
28865
29544
  ...genesis ? { genesis } : {}
28866
29545
  },
28867
29546
  ...Object.keys(known).length ? { formerNames: known } : {},
28868
- ...previous ? { previous } : {}
29547
+ ...previous ? { previous } : {},
29548
+ ...others?.length ? { others } : {}
28869
29549
  };
28870
29550
  if (existing) {
28871
29551
  this.sessions.delete(g);
@@ -28954,6 +29634,12 @@ var Groups = class {
28954
29634
  await this.takeBackFrom(mine);
28955
29635
  return;
28956
29636
  }
29637
+ if (mine?.others?.some((o) => "linkId" in o && o.linkId === linkId)) {
29638
+ mine.others = mine.others.filter((o) => !("linkId" in o) || o.linkId !== linkId);
29639
+ if (!mine.others.length) delete mine.others;
29640
+ await this.store.putGroup(mine);
29641
+ this.host.emit();
29642
+ }
28957
29643
  const entryPeer = this.hostEntry(g, linkId);
28958
29644
  if (entryPeer) {
28959
29645
  this.pendingEntries.get(g)?.delete(entryPeer);
@@ -29012,7 +29698,8 @@ var Groups = class {
29012
29698
  state: joined.state,
29013
29699
  contacts: viaLink ? {} : { [group.invitation.admin]: linkId },
29014
29700
  ...group.owedBye ? { owedBye: group.owedBye } : {},
29015
- ...group.declined ? { declined: group.declined } : {}
29701
+ ...group.declined ? { declined: group.declined } : {},
29702
+ ...group.others ? { others: group.others } : {}
29016
29703
  };
29017
29704
  this.stored.set(g, member);
29018
29705
  this.acceptSaid.delete(g);
@@ -29029,8 +29716,13 @@ var Groups = class {
29029
29716
  await this.event(g, "joined", group.invitation.genesis ? "You joined again" : `You joined. ${GROUP_READ_NOTE}`, Date.now(), joined.state.chain.length - 1);
29030
29717
  if (viaLink) traceJoin(g, "welcome.received");
29031
29718
  if (viaLink) {
29719
+ if (this.lastKnock.has(g)) this.unknock({
29720
+ g,
29721
+ host: group.invitation.entry
29722
+ }, group.invitation.seedB64).catch(() => {});
29032
29723
  this.lastKnock.delete(g);
29033
29724
  this.knocked.delete(g);
29725
+ this.othersKnocked.delete(g);
29034
29726
  this.knockingSince.delete(g);
29035
29727
  if (this.host.linkReady(linkId, 5)) this.signals.keep(g, linkId);
29036
29728
  }
@@ -29086,6 +29778,7 @@ var Groups = class {
29086
29778
  if (this.isCommunity(groupId)) return this.communities.handleEdgeFrame(groupId, peerKey, frame);
29087
29779
  if (this.stored.get(groupId)?.left) {
29088
29780
  if (this.removesMe(groupId, peerKey, frame)) await this.leaveConfirmed(groupId);
29781
+ else await this.afterLeave(groupId, peerKey, frame);
29089
29782
  return;
29090
29783
  }
29091
29784
  const session = this.sessions.get(groupId);
@@ -29168,6 +29861,84 @@ var Groups = class {
29168
29861
  const session = this.sessions.get(groupId);
29169
29862
  return session?.status === "active" && this.hubs.enabled ? session.signReaction(reaction) : {};
29170
29863
  }
29864
+ /**
29865
+ * A group I left, and a frame from the admin my leave is owed to, or a hub carrying my leave (WISP 902 § Admission and
29866
+ * departure, "A role that reaches a leave"). A member's leave: the role does not go on to it. The next commit of my
29867
+ * chain, while it keeps me: kept, so my leave follows the role to whoever holds it now, and said to that admin; one
29868
+ * that makes me the admin goes on at the next tick (`handOn`). Taken in full while my leave is still under way: the
29869
+ * leave then hands the role on itself.
29870
+ */
29871
+ async afterLeave(groupId, from, raw) {
29872
+ const group = this.stored.get(groupId), left = group?.left, session = this.sessions.get(groupId);
29873
+ if (!group || !left || !session || from !== left.admin && !left.hubs?.includes(from) || !raw || typeof raw !== "object") return;
29874
+ const t = raw.t;
29875
+ if (t === "group-leave" && from !== session.myKey) {
29876
+ let heard = this.leavesHeard.get(groupId);
29877
+ if (!heard) this.leavesHeard.set(groupId, heard = /* @__PURE__ */ new Set());
29878
+ heard.add(from);
29879
+ return;
29880
+ }
29881
+ if (t !== "group-commit") return;
29882
+ if (session.status === "active") await session.handle(from, raw);
29883
+ if (session.status !== "left" || !await session.followAfterLeave(raw)) return;
29884
+ if (session.admin === session.myKey) {
29885
+ this.handOnAt.set(groupId, this.now() + LEFT_HAND_ON_MS);
29886
+ return;
29887
+ }
29888
+ await this.leaveFollows(groupId);
29889
+ }
29890
+ /** My tombstone's chain moved: my leave goes to the admin it names now, over our edge when it is up (and when it opens). */
29891
+ async leaveFollows(groupId) {
29892
+ const group = this.stored.get(groupId), left = group?.left, session = this.sessions.get(groupId);
29893
+ const admin = session?.admin;
29894
+ if (!group || !left || !session || !admin || admin === session.myKey) return;
29895
+ if (admin !== left.admin) {
29896
+ group.left = {
29897
+ ...left,
29898
+ admin
29899
+ };
29900
+ await this.store.putGroup(group);
29901
+ this.reconcileEdges(groupId);
29902
+ }
29903
+ const edge = this.host.edges(groupId).get(admin);
29904
+ if (edge && this.host.linkReady(edge)) try {
29905
+ this.sayLeave(groupId, session, group, edge);
29906
+ } catch {}
29907
+ const contact = group.contacts?.[admin];
29908
+ if (contact) try {
29909
+ this.host.sendOnLink(contact, {
29910
+ t: "group-leave",
29911
+ g: groupId
29912
+ });
29913
+ } catch {}
29914
+ }
29915
+ /**
29916
+ * My leave, to the admin it is owed to: first the commits of my chain since I left, which that admin may lack (the
29917
+ * role came to it from a leaver, whose edge with it is the only one up), then the leave.
29918
+ */
29919
+ sayLeave(groupId, session, group, linkId) {
29920
+ const since = group.left?.bye?.e ?? session.epoch;
29921
+ for (let e = Math.max(since + 1, session.epoch - LEFT_COMMITS + 1); e <= session.epoch; e++) this.host.sendOnLink(linkId, farewellCommit(groupId, session, e));
29922
+ this.host.sendOnLink(linkId, {
29923
+ t: "group-leave",
29924
+ g: groupId
29925
+ });
29926
+ }
29927
+ /** A tombstone the role reached: it goes on (`nextAdmin`), and my leave with it. */
29928
+ async handOn(groupId) {
29929
+ const session = this.sessions.get(groupId);
29930
+ if (!session || session.status !== "left" || session.admin !== session.myKey) {
29931
+ this.handOnAt.delete(groupId);
29932
+ return;
29933
+ }
29934
+ try {
29935
+ if (!await session.handOnAfterLeave((by) => this.nextAdmin(groupId, session, by))) return;
29936
+ } catch {
29937
+ return;
29938
+ }
29939
+ this.handOnAt.delete(groupId);
29940
+ await this.leaveFollows(groupId);
29941
+ }
29171
29942
  /** A validly signed commit, by the admin I told, that takes me out of the roster. */
29172
29943
  removesMe(groupId, from, raw) {
29173
29944
  const group = this.stored.get(groupId), session = this.sessions.get(groupId);
@@ -29184,8 +29955,10 @@ var Groups = class {
29184
29955
  }
29185
29956
  const left = this.stored.get(groupId)?.left;
29186
29957
  if (left) {
29958
+ const session = this.sessions.get(groupId), group = this.stored.get(groupId);
29187
29959
  if (peerKey === left.admin) try {
29188
- this.host.sendOnLink(linkId, {
29960
+ if (session) this.sayLeave(groupId, session, group, linkId);
29961
+ else this.host.sendOnLink(linkId, {
29189
29962
  t: "group-leave",
29190
29963
  g: groupId
29191
29964
  });
@@ -29217,6 +29990,12 @@ var Groups = class {
29217
29990
  } catch {
29218
29991
  return;
29219
29992
  }
29993
+ const name = session.nameFrame();
29994
+ if (name) try {
29995
+ this.host.sendOnLink(linkId, name);
29996
+ } catch {
29997
+ return;
29998
+ }
29220
29999
  if (peerKey === session.admin) {
29221
30000
  const owed = this.owedBye(group, session, this.now());
29222
30001
  try {
@@ -29639,6 +30418,8 @@ var Groups = class {
29639
30418
  for (const [groupId, session] of this.sessions) {
29640
30419
  if (session.status !== "active" || this.stored.get(groupId)?.left) continue;
29641
30420
  session.reseal().catch(() => {});
30421
+ session.resume().catch(() => {});
30422
+ session.sayName().catch(() => {});
29642
30423
  this.farewellsTick(groupId, session, now);
29643
30424
  this.heldSyncs(groupId, session, now);
29644
30425
  if (reconcile) {
@@ -29716,6 +30497,20 @@ var Groups = class {
29716
30497
  if (!session) throw new Error("Group not found");
29717
30498
  return session;
29718
30499
  }
30500
+ /** Tells a group's session the numbers its own rows hold (`GroupSession.ownRows`). */
30501
+ ownRows(groupId, history) {
30502
+ const session = this.sessions.get(groupId);
30503
+ if (!session) return;
30504
+ const rows = [];
30505
+ for (const m of history) {
30506
+ const ref = m.sender === "me" ? meshMessageRef(m.id) : null;
30507
+ if (ref && ref.s === session.myKey) rows.push({
30508
+ epoch: ref.e,
30509
+ seq: ref.n
30510
+ });
30511
+ }
30512
+ session.ownRows(rows);
30513
+ }
29719
30514
  /** `frames`: what the group's rows hold to hand on, oldest first (none yet for a group just made, joined or given back). */
29720
30515
  attach(state, frames = []) {
29721
30516
  const session = new GroupSession(state, {
@@ -29755,7 +30550,7 @@ var Groups = class {
29755
30550
  const file = m.file && this.files && !this.isRemoved(state.id, m.id) ? await this.files.announced(state.id, {
29756
30551
  id: m.id,
29757
30552
  sender: m.sender,
29758
- ts: m.timestamp,
30553
+ epoch: m.epoch,
29759
30554
  file: m.file
29760
30555
  }, session.myKey) : void 0;
29761
30556
  const message = {
@@ -29807,6 +30602,7 @@ var Groups = class {
29807
30602
  kept: async (id, frame) => {
29808
30603
  await this.host.keepFrame?.(MESSAGE_LINK(state.id), id, frame).catch(() => {});
29809
30604
  await this.frameKept(state.id, id, frame);
30605
+ this.files?.arrivedAgain(state.id, id, frame.e);
29810
30606
  },
29811
30607
  edit: (e) => this.host.groupEdit?.(state.id, e),
29812
30608
  changed: () => {
@@ -29864,8 +30660,8 @@ var Groups = class {
29864
30660
  if (top.k === "rotate") await this.event(groupId, "rotated", "Keys rotated: a fresh epoch", when, top.e);
29865
30661
  }
29866
30662
  const group = this.stored.get(groupId);
29867
- if (session.status === "active" && group && pinOfFormerMember(group.pin, (key) => rosterHas(after, key))) {
29868
- group.pin = void 0;
30663
+ if (session.status === "active" && group?.pin && pinOfFormerMember(group.pin, (key) => rosterHas(after, key))) {
30664
+ group.pin = droppedPin(group.pin, this.now());
29869
30665
  await this.store.putGroup(group);
29870
30666
  }
29871
30667
  this.reconcileEdges(groupId);
@@ -33253,6 +34049,8 @@ function amountlessUnderOptions(info) {
33253
34049
  }
33254
34050
  /** A Lightning payment can stay in flight for minutes or hours; the mint is asked again this often. */
33255
34051
  var MELT_POLL_MS = 3e4;
34052
+ /** Once its request can no longer land, a payment still pending is asked twice as late each time, up to this. */
34053
+ var MELT_SLOW_POLL_MS = 18e5;
33256
34054
  var MAX_AMOUNT = 1e6;
33257
34055
  /** How long "Get test coins" waits for the test mint to mark its invoice paid before saying the coins come later. */
33258
34056
  var TEST_COINS_WAIT_MS = 3e4;
@@ -33269,8 +34067,15 @@ var SWAP_WATCH_MS = 36e5;
33269
34067
  var SPENT_KEPT = 1e3;
33270
34068
  /** The most coins `sendCoins` makes for one token. */
33271
34069
  var MAX_SEND_COINS = 64;
33272
- /** Cashu's library (174 KiB) loads with the wallet's first use of a mint or a token, not with the app's start. */
33273
- var loadCashu = () => import("@cashu/cashu-ts");
34070
+ /**
34071
+ * Cashu's library (174 KiB) loads with the wallet's first use of a mint or a token, not with the app's start. A mint's
34072
+ * redirect is refused on every request, not only on those with a body as the library does: `normalizeMintUrl` alone
34073
+ * says where the wallet's requests go.
34074
+ */
34075
+ var loadCashu = () => import("@cashu/cashu-ts").then((cashu) => {
34076
+ cashu.setGlobalRequestOptions({ redirect: "error" });
34077
+ return cashu;
34078
+ });
33274
34079
  async function reviewedCashuFee(preview) {
33275
34080
  const { Amount } = await loadCashu();
33276
34081
  const fee = preview.inputs.reduce((sum, proof) => sum + Amount.from(proof.amount).toNumber(), 0) - (preview.keepOutputs ?? []).reduce((sum, output) => sum + Amount.from(output.blindedMessage.amount).toNumber(), 0) - preview.amount.toNumber();
@@ -33427,7 +34232,7 @@ var mintReason = (error) => (error instanceof Error ? error.message : String(err
33427
34232
  * that is down can hold a request for minutes; the next mint should get its turn well before that.
33428
34233
  */
33429
34234
  var MINT_TIMEOUT_MS = 12e3;
33430
- function within(ms, work, mint) {
34235
+ function within$1(ms, work, mint) {
33431
34236
  let timer;
33432
34237
  const late = new Promise((_, reject) => {
33433
34238
  timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${new URL(mint).host} did not answer`)), ms);
@@ -33450,6 +34255,8 @@ var CashuWallet = class CashuWallet {
33450
34255
  /** Per quote the screen shows: until when (`watch`). */
33451
34256
  quoteWatched = /* @__PURE__ */ new Map();
33452
34257
  meltTimer = null;
34258
+ /** Per pending melt: when it is asked about next and the wait before that, in this run (a restart asks at once). */
34259
+ meltAsk = /* @__PURE__ */ new Map();
33453
34260
  restoredTimer = null;
33454
34261
  swapTimer = null;
33455
34262
  swapTimerAt = 0;
@@ -33539,7 +34346,7 @@ var CashuWallet = class CashuWallet {
33539
34346
  async readStored() {
33540
34347
  return {
33541
34348
  proofs: await this.allProofs(),
33542
- swaps: await wrap((await store(STORES$1.swaps, "readonly")).getAll())
34349
+ swaps: await this.readSwaps()
33543
34350
  };
33544
34351
  }
33545
34352
  /**
@@ -33561,7 +34368,7 @@ var CashuWallet = class CashuWallet {
33561
34368
  if (!proofs.length) return;
33562
34369
  const states = await (await this.wallet(mint)).checkProofsStates(proofs);
33563
34370
  if (states.length !== proofs.length) throw new Error("The mint answered for another number of proofs");
33564
- await transact([STORES$1.proofs], (stores) => {
34371
+ await this.sealedTransact([STORES$1.proofs], { [STORES$1.proofs]: proofs }, (stores) => {
33565
34372
  proofs.forEach((proof, i) => {
33566
34373
  const state = states[i]?.state;
33567
34374
  if (state === "SPENT") stores[STORES$1.proofs].delete(proof.secret);
@@ -33627,7 +34434,7 @@ var CashuWallet = class CashuWallet {
33627
34434
  for (const candidate of this.getMints(network)) try {
33628
34435
  created = {
33629
34436
  mint: candidate,
33630
- response: await within(MINT_TIMEOUT_MS, (await this.wallet(candidate)).createMintQuoteBolt11(amount, "Ghostly"), candidate)
34437
+ response: await within$1(MINT_TIMEOUT_MS, (await this.wallet(candidate)).createMintQuoteBolt11(amount, "Ghostly"), candidate)
33631
34438
  };
33632
34439
  break;
33633
34440
  } catch (error) {
@@ -33645,7 +34452,7 @@ var CashuWallet = class CashuWallet {
33645
34452
  paymentId,
33646
34453
  ...paysItsOwnInvoices(mint) ? { held: true } : {}
33647
34454
  };
33648
- await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
34455
+ await this.putQuote(quote);
33649
34456
  this.quoteAsked.set(quote.quote, Date.now());
33650
34457
  this.pollQuotes();
33651
34458
  return quote;
@@ -33665,18 +34472,22 @@ var CashuWallet = class CashuWallet {
33665
34472
  /**
33666
34473
  * A payer says it paid this invoice of ours (a contact's app, once its payment went through). A held quote (a test
33667
34474
  * mint's, which reads paid by itself) is minted from now on; on any other mint the mint's own answer decides, as
33668
- * always. Returns whether the invoice is one of ours.
34475
+ * always. Returns whether the invoice is one of ours. `said` false: the payer spoke of another invoice, so this one is
34476
+ * only asked about, and a held one stays held. Only this invoice is asked about now: the others keep their pace.
33669
34477
  */
33670
- async vouch(invoice) {
34478
+ async vouch(invoice, said = true) {
33671
34479
  const wanted = invoice.trim().toLowerCase();
33672
- const quote = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).find((q) => q.invoice.toLowerCase() === wanted);
34480
+ let quote = (await this.quotes()).find((q) => q.invoice.toLowerCase() === wanted);
33673
34481
  if (!quote) return false;
33674
- if (quote.held) await committed((await store(STORES$1.quotes, "readwrite")).put({
33675
- ...quote,
33676
- held: void 0
33677
- }));
34482
+ if (quote.held && said) {
34483
+ quote = {
34484
+ ...quote,
34485
+ held: void 0
34486
+ };
34487
+ await this.putQuote(quote);
34488
+ }
33678
34489
  this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);
33679
- await this.pollQuotes(true);
34490
+ if (!(await this.settleQuotes([quote])).length && !quote.held && !quote.issuedUnclaimed) this.scheduleQuotes(this.nextAsk(quote, Date.now()));
33680
34491
  return true;
33681
34492
  }
33682
34493
  /** True while an invoice of ours waits for a payer's word (see `vouch`): whatever its mint says, it is not paid. */
@@ -33692,7 +34503,7 @@ var CashuWallet = class CashuWallet {
33692
34503
  assertAmount(amount);
33693
34504
  const mint = this.getMints(network).find(paysItsOwnInvoices);
33694
34505
  if (!mint) throw new Error("This wallet has no test mint to ask for test coins");
33695
- const response = await within(MINT_TIMEOUT_MS, (await this.wallet(mint)).createMintQuoteBolt11(amount, "Ghostly test coins"), mint);
34506
+ const response = await within$1(MINT_TIMEOUT_MS, (await this.wallet(mint)).createMintQuoteBolt11(amount, "Ghostly test coins"), mint);
33696
34507
  const quote = {
33697
34508
  quote: response.quote,
33698
34509
  mint,
@@ -33702,7 +34513,7 @@ var CashuWallet = class CashuWallet {
33702
34513
  expiresAt: response.expiry ? response.expiry * 1e3 : null,
33703
34514
  testCoins: true
33704
34515
  };
33705
- await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
34516
+ await this.putQuote(quote);
33706
34517
  const deadline = Date.now() + TEST_COINS_WAIT_MS;
33707
34518
  for (;;) {
33708
34519
  if (await this.locked(mint, () => this.settleQuote(quote.quote))) {
@@ -33730,7 +34541,12 @@ var CashuWallet = class CashuWallet {
33730
34541
  }
33731
34542
  /** Every invoice of ours the mints have not settled yet, held, paid-unclaimed and issued-unclaimed ones included. */
33732
34543
  async quotes() {
33733
- return wrap((await store(STORES$1.quotes, "readonly")).getAll());
34544
+ return openRows(STORES$1.quotes, await wrap((await store(STORES$1.quotes, "readonly")).getAll()));
34545
+ }
34546
+ /** Sealed before its transaction opens, when the profile is encrypted: a paid quote's outputs can be minted from. */
34547
+ async putQuote(quote) {
34548
+ const row = await sealRow(STORES$1.quotes, quote);
34549
+ await committed((await store(STORES$1.quotes, "readwrite")).put(row));
33734
34550
  }
33735
34551
  /**
33736
34552
  * Invoices are paid by someone else, somewhere else; all we can do is ask the mint. A quote is the only
@@ -33795,7 +34611,7 @@ var CashuWallet = class CashuWallet {
33795
34611
  }
33796
34612
  /** Runs under the mint's lock, so two rounds never mint one quote twice. Returns the quote once its ecash is in. */
33797
34613
  async settleQuote(id) {
33798
- const quote = await wrap((await store(STORES$1.quotes, "readonly")).get(id));
34614
+ const quote = await openRow(STORES$1.quotes, await wrap((await store(STORES$1.quotes, "readonly")).get(id)));
33799
34615
  if (!quote || quote.issuedUnclaimed || quote.held) return null;
33800
34616
  const wallet = await this.wallet(quote.mint);
33801
34617
  const { OutputData } = await loadCashu();
@@ -33810,10 +34626,10 @@ var CashuWallet = class CashuWallet {
33810
34626
  const issued = saved?.length ? await this.signedOutputs(wallet, saved) : void 0;
33811
34627
  if (Array.isArray(issued)) return this.storeMinted(quote, issued);
33812
34628
  console.warn(`[wallet] ${quote.mint} issued quote ${quote.quote} (${quote.amount} sats) but this wallet holds no ecash for it`);
33813
- await committed((await store(STORES$1.quotes, "readwrite")).put({
34629
+ await this.putQuote({
33814
34630
  ...quote,
33815
34631
  issuedUnclaimed: true
33816
- }));
34632
+ });
33817
34633
  return null;
33818
34634
  }
33819
34635
  const preview = await wallet.prepareMint("bolt11", quote.amount, {
@@ -33826,14 +34642,14 @@ var CashuWallet = class CashuWallet {
33826
34642
  paid: true,
33827
34643
  outputs: saved ? quote.outputs : preview.outputData.map((o) => OutputData.serialize(o))
33828
34644
  };
33829
- if (!quote.paid || !saved) await committed((await store(STORES$1.quotes, "readwrite")).put(written));
34645
+ if (!quote.paid || !saved) await this.putQuote(written);
33830
34646
  let proofs;
33831
34647
  try {
33832
34648
  proofs = await wallet.completeMint(preview);
33833
34649
  } catch (error) {
33834
34650
  if (mintRefused(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
33835
34651
  const { outputs: _refused, ...fresh } = written;
33836
- await committed((await store(STORES$1.quotes, "readwrite")).put(fresh));
34652
+ await this.putQuote(fresh);
33837
34653
  }
33838
34654
  throw error;
33839
34655
  }
@@ -33846,11 +34662,11 @@ var CashuWallet = class CashuWallet {
33846
34662
  ...walletTx(quote.mint, "lightning-in", minted, quote.amount - minted, quote.paymentId ? "Request paid over Lightning" : quote.testCoins ? TEST_COINS_NOTE : void 0),
33847
34663
  quote: quote.quote
33848
34664
  };
33849
- await transact([
34665
+ await this.sealedTransact([
33850
34666
  STORES$1.proofs,
33851
34667
  STORES$1.walletTx,
33852
34668
  STORES$1.quotes
33853
- ], (stores) => {
34669
+ ], { [STORES$1.proofs]: proofs }, (stores) => {
33854
34670
  for (const p of proofs) stores[STORES$1.proofs].put(toStored(quote.mint, p));
33855
34671
  stores[STORES$1.walletTx].put(tx);
33856
34672
  stores[STORES$1.quotes].delete(quote.quote);
@@ -33901,12 +34717,15 @@ var CashuWallet = class CashuWallet {
33901
34717
  const spent = total(inputs) - sats(keep);
33902
34718
  const tx = walletTx(mint, "ecash-out", amount, spent - amount, note);
33903
34719
  const kept = outbox?.(token, mint);
33904
- await transact([
34720
+ await this.sealedTransact([
33905
34721
  STORES$1.proofs,
33906
34722
  STORES$1.walletTx,
33907
34723
  STORES$1.swaps,
33908
34724
  ...kept ? [STORES$1.payments] : []
33909
- ], (stores) => {
34725
+ ], {
34726
+ [STORES$1.proofs]: keep,
34727
+ [STORES$1.payments]: kept ? [kept] : []
34728
+ }, (stores) => {
33910
34729
  this.queueReplace(stores[STORES$1.proofs], mint, inputs, keep);
33911
34730
  stores[STORES$1.walletTx].put(tx);
33912
34731
  if (swap) stores[STORES$1.swaps].delete(swap.id);
@@ -33942,9 +34761,9 @@ var CashuWallet = class CashuWallet {
33942
34761
  return this.locked(prepared.mint, async () => {
33943
34762
  const preview = (await loadCashu()).deserializeSwapPreview(prepared.swap);
33944
34763
  if (prepared.mint !== review.provider || preview.amount.toNumber() !== review.amount || await reviewedCashuFee(preview) !== review.fee) throw new PaymentPreflightError("Cashu preview does not match review");
33945
- const tx = (await openDb()).transaction(STORES$1.proofs, "readwrite");
34764
+ const seals = new RowSeals(), tx = (await openDb()).transaction(STORES$1.proofs, "readwrite");
33946
34765
  await new Promise((resolve, reject) => {
33947
- const proofs = tx.objectStore(STORES$1.proofs);
34766
+ const proofs = sealedStore(tx.objectStore(STORES$1.proofs), seals);
33948
34767
  for (const input of preview.inputs) {
33949
34768
  const request = proofs.get(input.secret);
33950
34769
  request.onsuccess = () => {
@@ -33969,7 +34788,7 @@ var CashuWallet = class CashuWallet {
33969
34788
  }
33970
34789
  /** NUT-09 retrieves signatures for the exact saved outputs; it never creates another swap. */
33971
34790
  async recoverReviewedCashu(review, prepared) {
33972
- const stored = await wrap((await store(STORES$1.payments, "readonly")).get(review.id));
34791
+ const stored = await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
33973
34792
  if (stored?.token) return stored.token;
33974
34793
  const wallet = await this.wallet(prepared.mint);
33975
34794
  const { OutputData } = await loadCashu();
@@ -34036,11 +34855,14 @@ var CashuWallet = class CashuWallet {
34036
34855
  requestId: review.requestId,
34037
34856
  target: review
34038
34857
  };
34039
- await transact([
34858
+ await this.sealedTransact([
34040
34859
  STORES$1.proofs,
34041
34860
  STORES$1.payments,
34042
34861
  STORES$1.walletTx
34043
- ], (stores) => {
34862
+ ], {
34863
+ [STORES$1.proofs]: keep,
34864
+ [STORES$1.payments]: [record]
34865
+ }, (stores) => {
34044
34866
  this.queueReplace(stores[STORES$1.proofs], prepared.mint, preview.inputs.map((p) => toStored(prepared.mint, p)), keep);
34045
34867
  stores[STORES$1.payments].put(record);
34046
34868
  stores[STORES$1.walletTx].put({
@@ -34102,7 +34924,7 @@ var CashuWallet = class CashuWallet {
34102
34924
  })));
34103
34925
  if (states.length !== preview.inputs.length) throw new Error("The mint answered for another number of proofs");
34104
34926
  const spent = new Set(preview.inputs.filter((_, i) => states[i]?.state === "SPENT").map((p) => p.secret));
34105
- await transact([STORES$1.proofs], (stores) => {
34927
+ await this.sealedTransact([STORES$1.proofs], {}, (stores) => {
34106
34928
  const proofs = stores[STORES$1.proofs];
34107
34929
  for (const input of preview.inputs) {
34108
34930
  const request = proofs.get(input.secret);
@@ -34129,7 +34951,7 @@ var CashuWallet = class CashuWallet {
34129
34951
  */
34130
34952
  async recheck(mint) {
34131
34953
  const free = (await this.allProofs()).filter((p) => p.mint === mint && !p.reserved && !p.unchecked);
34132
- if (free.length > 0) await transact([STORES$1.proofs], (stores) => {
34954
+ if (free.length > 0) await this.sealedTransact([STORES$1.proofs], { [STORES$1.proofs]: free }, (stores) => {
34133
34955
  for (const p of free) stores[STORES$1.proofs].put({
34134
34956
  ...p,
34135
34957
  unchecked: true
@@ -34141,7 +34963,7 @@ var CashuWallet = class CashuWallet {
34141
34963
  async releaseReviewedCashu(prepared) {
34142
34964
  const preview = (await loadCashu()).deserializeSwapPreview(prepared.swap);
34143
34965
  await this.locked(prepared.mint, async () => {
34144
- await transact([STORES$1.proofs], (stores) => {
34966
+ await this.sealedTransact([STORES$1.proofs], {}, (stores) => {
34145
34967
  const proofs = stores[STORES$1.proofs];
34146
34968
  for (const input of preview.inputs) {
34147
34969
  const request = proofs.get(input.secret);
@@ -34252,7 +35074,7 @@ var CashuWallet = class CashuWallet {
34252
35074
  token,
34253
35075
  ...records(preview.amount.toNumber())
34254
35076
  };
34255
- await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
35077
+ await this.putSwap(swap);
34256
35078
  }
34257
35079
  const { keep } = await this.completeSwap(swap);
34258
35080
  const credited = sats(keep);
@@ -34312,7 +35134,10 @@ var CashuWallet = class CashuWallet {
34312
35134
  createdAt: Date.now()
34313
35135
  };
34314
35136
  const inputs = among(preview.inputs);
34315
- await transact([STORES$1.proofs, STORES$1.swaps], (stores) => {
35137
+ await this.sealedTransact([STORES$1.proofs, STORES$1.swaps], {
35138
+ [STORES$1.proofs]: inputs,
35139
+ [STORES$1.swaps]: [swap]
35140
+ }, (stores) => {
34316
35141
  for (const p of inputs) stores[STORES$1.proofs].put({
34317
35142
  ...p,
34318
35143
  reserved: true
@@ -34344,7 +35169,7 @@ var CashuWallet = class CashuWallet {
34344
35169
  ...swap,
34345
35170
  attemptEndedAt: Date.now()
34346
35171
  };
34347
- await (async () => committed((await store(STORES$1.swaps, "readwrite")).put(ended)))().catch(() => {});
35172
+ await this.putSwap(ended).catch(() => {});
34348
35173
  const outcome = await this.swapOutcome(ended, refused).catch(() => ({ state: "open" }));
34349
35174
  if (outcome.state === "done") return outcome;
34350
35175
  if (outcome.state === "never" && outcome.final) {
@@ -34435,12 +35260,15 @@ var CashuWallet = class CashuWallet {
34435
35260
  const inputs = (await this.allProofs()).filter((p) => p.mint === swap.mint && secrets.has(p.secret));
34436
35261
  const lost = swap.kind === "send" ? swapOf(swap).inputs.reduce((sum, p) => sum + Number(p.amount), 0) - sats(keep) - sats(send) : 0;
34437
35262
  let stored = false;
34438
- await transact([
35263
+ await this.sealedTransact([
34439
35264
  STORES$1.proofs,
34440
35265
  STORES$1.swaps,
34441
35266
  STORES$1.walletTx,
34442
35267
  ...swap.payment ? [STORES$1.payments] : []
34443
- ], (stores) => {
35268
+ ], {
35269
+ [STORES$1.proofs]: [...keep, ...send],
35270
+ [STORES$1.payments]: swap.payment ? [swap.payment] : []
35271
+ }, (stores) => {
34444
35272
  const current = stores[STORES$1.swaps].get(swap.id);
34445
35273
  current.onsuccess = () => {
34446
35274
  const kept = current.result;
@@ -34475,7 +35303,10 @@ var CashuWallet = class CashuWallet {
34475
35303
  async dropSwap(swap, gone, watch = false) {
34476
35304
  const inputs = swap.kind === "send" && !swap.released ? await this.storedInputs(swap) : [];
34477
35305
  if (gone.size > 0 && inputs.length > 0) console.warn(`[wallet] ${gone.size} proofs of a swap at ${swap.mint} that never happened are spent`);
34478
- await transact([STORES$1.proofs, STORES$1.swaps], (stores) => {
35306
+ await this.sealedTransact([STORES$1.proofs, STORES$1.swaps], {
35307
+ [STORES$1.proofs]: inputs,
35308
+ [STORES$1.swaps]: [swap]
35309
+ }, (stores) => {
34479
35310
  for (const p of inputs) if (gone.has(p.secret)) stores[STORES$1.proofs].delete(p.secret);
34480
35311
  else {
34481
35312
  const { reserved: _released, ...free } = p;
@@ -34506,7 +35337,7 @@ var CashuWallet = class CashuWallet {
34506
35337
  return (await this.allProofs()).filter((p) => p.mint === swap.mint && p.reserved && secrets.has(p.secret));
34507
35338
  }
34508
35339
  async swapsAt(mint) {
34509
- return (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => s.mint === mint);
35340
+ return (await this.readSwaps()).filter((s) => s.mint === mint);
34510
35341
  }
34511
35342
  /** Says what became of a swap to whoever follows it (the chat its payment is in), and waits for it to be taken in. */
34512
35343
  async tellSwap(swap, done) {
@@ -34541,7 +35372,7 @@ var CashuWallet = class CashuWallet {
34541
35372
  * pay the request, which another member may pay.
34542
35373
  */
34543
35374
  async redeemingFor(requestId) {
34544
- return (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).some((s) => s.kind === "receive" && !s.released && s.payment?.requestId === requestId && !(s.stuck && Date.now() >= s.createdAt + SWAP_WATCH_MS));
35375
+ return (await this.readSwaps()).some((s) => s.kind === "receive" && !s.released && s.payment?.requestId === requestId && !(s.stuck && Date.now() >= s.createdAt + SWAP_WATCH_MS));
34545
35376
  }
34546
35377
  async pollSwaps(mints) {
34547
35378
  if (!mints) {
@@ -34549,13 +35380,13 @@ var CashuWallet = class CashuWallet {
34549
35380
  this.swapTimer = null;
34550
35381
  if (this.stopped) return;
34551
35382
  }
34552
- const open = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => !mints || mints.includes(s.mint));
35383
+ const open = (await this.readSwaps()).filter((s) => !mints || mints.includes(s.mint));
34553
35384
  let again = 0;
34554
35385
  const later = (ms) => {
34555
35386
  again = again ? Math.min(again, ms) : ms;
34556
35387
  };
34557
35388
  for (const { id, mint } of open) await this.locked(mint, async () => {
34558
- let swap = await wrap((await store(STORES$1.swaps, "readonly")).get(id));
35389
+ let swap = await openRow(STORES$1.swaps, await wrap((await store(STORES$1.swaps, "readonly")).get(id)));
34559
35390
  if (!swap) return;
34560
35391
  try {
34561
35392
  if (swap.finished) {
@@ -34572,7 +35403,7 @@ var CashuWallet = class CashuWallet {
34572
35403
  ...swap,
34573
35404
  attemptEndedAt: Date.now()
34574
35405
  };
34575
- await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
35406
+ await this.putSwap(swap);
34576
35407
  }
34577
35408
  const outcome = await this.swapOutcome(swap);
34578
35409
  if (outcome.state === "open") {
@@ -34583,11 +35414,11 @@ var CashuWallet = class CashuWallet {
34583
35414
  if (outcome.slow) {
34584
35415
  const stuck = (swap.stuck ?? 0) + 1;
34585
35416
  const wait = stuck <= 6 ? SWAP_SLOW_POLL_MS : stuck <= 30 ? 36e5 : 864e5;
34586
- await committed((await store(STORES$1.swaps, "readwrite")).put({
35417
+ await this.putSwap({
34587
35418
  ...swap,
34588
35419
  stuck,
34589
35420
  askAt: Date.now() + wait
34590
- }));
35421
+ });
34591
35422
  if (stuck === 1) this.events.onChange();
34592
35423
  later(wait);
34593
35424
  } else if (outcome.idle && swap.kind === "receive" && !swap.released) {
@@ -34605,7 +35436,7 @@ var CashuWallet = class CashuWallet {
34605
35436
  ...swap,
34606
35437
  attemptEndedAt: Date.now()
34607
35438
  };
34608
- await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
35439
+ await this.putSwap(swap);
34609
35440
  const refusal = mintRefused(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
34610
35441
  if (refusal?.state === "done") {
34611
35442
  if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
@@ -34621,10 +35452,10 @@ var CashuWallet = class CashuWallet {
34621
35452
  }
34622
35453
  } else if (outcome.pending && swap.kind === "receive" && !swap.released && Date.now() >= swapOverdueAt(swap)) {
34623
35454
  if (Date.now() < swap.createdAt + SWAP_WATCH_MS) {
34624
- await committed((await store(STORES$1.swaps, "readwrite")).put({
35455
+ await this.putSwap({
34625
35456
  ...swap,
34626
35457
  askAt: Date.now() + SWAP_SLOW_POLL_MS
34627
- }));
35458
+ });
34628
35459
  later(SWAP_SLOW_POLL_MS);
34629
35460
  } else {
34630
35461
  await this.dropSwap(swap, /* @__PURE__ */ new Set());
@@ -34730,7 +35561,7 @@ var CashuWallet = class CashuWallet {
34730
35561
  const wallet = await this.wallet(mint);
34731
35562
  const { MeltChangeError, OutputData, getEncodedToken } = await loadCashu();
34732
35563
  const quote = await wallet.checkMeltQuoteBolt11(quoteId);
34733
- if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => m.quote === quote.quote || m.request === quote.request)) throw new Error("This invoice is already being paid");
35564
+ if ((await this.readMelts()).some((m) => m.quote === quote.quote || m.request === quote.request)) throw new Error("This invoice is already being paid");
34734
35565
  const shown = this.shownQuotes.get(quoteId);
34735
35566
  const needed = quote.amount.toNumber() + quote.fee_reserve.toNumber();
34736
35567
  const proofs = await this.proofsAt(mint);
@@ -34745,7 +35576,7 @@ var CashuWallet = class CashuWallet {
34745
35576
  try {
34746
35577
  preview = await wallet.prepareMelt("bolt11", quote, send);
34747
35578
  } catch (error) {
34748
- await transact([STORES$1.proofs, STORES$1.swaps], (stores) => {
35579
+ await this.sealedTransact([STORES$1.proofs, STORES$1.swaps], { [STORES$1.proofs]: [...keep, ...send] }, (stores) => {
34749
35580
  this.queueReplace(stores[STORES$1.proofs], mint, inputs, [...keep, ...send]);
34750
35581
  if (swap) stores[STORES$1.swaps].delete(swap.id);
34751
35582
  });
@@ -34763,11 +35594,14 @@ var CashuWallet = class CashuWallet {
34763
35594
  paymentId,
34764
35595
  createdAt: Date.now()
34765
35596
  };
34766
- await transact([
35597
+ await this.sealedTransact([
34767
35598
  STORES$1.proofs,
34768
35599
  STORES$1.melts,
34769
35600
  STORES$1.swaps
34770
- ], (stores) => {
35601
+ ], {
35602
+ [STORES$1.proofs]: [...keep, ...send],
35603
+ [STORES$1.melts]: [melt]
35604
+ }, (stores) => {
34771
35605
  this.queueReplace(stores[STORES$1.proofs], mint, inputs, keep);
34772
35606
  for (const p of send) stores[STORES$1.proofs].put(toStored(mint, p, true));
34773
35607
  stores[STORES$1.melts].put(melt);
@@ -34799,27 +35633,44 @@ var CashuWallet = class CashuWallet {
34799
35633
  * its proofs, and `pollMelts` settles and reports it: an invoice with none never reached the mint's melt, or is done.
34800
35634
  */
34801
35635
  async meltInFlight(invoice) {
34802
- return (await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => m.request === invoice);
35636
+ return (await this.readMelts()).some((m) => m.request === invoice);
34803
35637
  }
34804
- /** Lightning payments left pending, asked about again until the mint settles each one. */
35638
+ /**
35639
+ * Lightning payments left pending, asked about again until the mint settles each one: every MELT_POLL_MS while its
35640
+ * request may still land, then each at its own pace, twice as late every time up to MELT_SLOW_POLL_MS.
35641
+ */
34805
35642
  async pollMelts() {
34806
35643
  if (this.meltTimer) clearTimeout(this.meltTimer);
34807
35644
  this.meltTimer = null;
34808
35645
  if (this.stopped) return;
34809
- const melts = await wrap((await store(STORES$1.melts, "readonly")).getAll());
34810
- for (const melt of melts) try {
34811
- const outcome = await this.locked(melt.mint, async () => {
34812
- const current = await wrap((await store(STORES$1.melts, "readonly")).get(melt.quote));
34813
- return current ? this.settleMelt(current) : null;
34814
- });
34815
- if (outcome === "paid" || outcome === "unpaid") {
34816
- this.takeFailedFee(melt.quote);
34817
- this.spentAway.delete(melt.quote);
34818
- this.events.onMeltResolved(melt, outcome === "paid");
34819
- this.events.onChange();
34820
- }
34821
- } catch {}
34822
- if (await wrap((await store(STORES$1.melts, "readonly")).count()) > 0 && !this.stopped) this.meltTimer = setTimeout(() => void this.pollMelts(), MELT_POLL_MS);
35646
+ const melts = await this.readMelts();
35647
+ for (const melt of melts) {
35648
+ const pace = this.meltAsk.get(melt.quote);
35649
+ if (pace && Date.now() < pace.at) continue;
35650
+ try {
35651
+ const outcome = await this.locked(melt.mint, async () => {
35652
+ const current = await openRow(STORES$1.melts, await wrap((await store(STORES$1.melts, "readonly")).get(melt.quote)));
35653
+ return current ? this.settleMelt(current) : null;
35654
+ });
35655
+ if (outcome === "paid" || outcome === "unpaid") {
35656
+ this.takeFailedFee(melt.quote);
35657
+ this.spentAway.delete(melt.quote);
35658
+ this.events.onMeltResolved(melt, outcome === "paid");
35659
+ this.events.onChange();
35660
+ }
35661
+ } catch {}
35662
+ const wait = Date.now() < meltOverdueAt(melt) ? MELT_POLL_MS : Math.min((pace?.wait ?? MELT_POLL_MS) * 2, MELT_SLOW_POLL_MS);
35663
+ this.meltAsk.set(melt.quote, {
35664
+ at: Date.now() + wait,
35665
+ wait
35666
+ });
35667
+ }
35668
+ const remaining = new Set((await this.readMelts()).map((m) => m.quote));
35669
+ for (const quote of this.meltAsk.keys()) if (!remaining.has(quote)) this.meltAsk.delete(quote);
35670
+ if (remaining.size === 0 || this.stopped) return;
35671
+ const next = Math.min(...[...remaining].map((quote) => this.meltAsk.get(quote)?.at ?? 0));
35672
+ if (this.meltTimer) clearTimeout(this.meltTimer);
35673
+ this.meltTimer = setTimeout(() => void this.pollMelts(), Math.max(0, next - Date.now()));
34823
35674
  }
34824
35675
  /**
34825
35676
  * Asks the mint where a recorded melt stands and books the answer. Paid: the reserved proofs are gone and
@@ -34853,11 +35704,11 @@ var CashuWallet = class CashuWallet {
34853
35704
  const spent = new Set(inputs.filter((_, i) => states[i]?.state === "SPENT").map((p) => p.secret));
34854
35705
  if (spent.size > 0) console.warn(`[wallet] melt ${melt.quote} is unpaid, yet ${spent.size} of its proofs are spent`);
34855
35706
  const lost = melt.outlay - inputs.reduce((sum, p) => sum + p.amount, 0);
34856
- await transact([
35707
+ await this.sealedTransact([
34857
35708
  STORES$1.proofs,
34858
35709
  STORES$1.melts,
34859
35710
  ...lost > 0 ? [STORES$1.walletTx] : []
34860
- ], (stores) => {
35711
+ ], { [STORES$1.proofs]: inputs }, (stores) => {
34861
35712
  for (const p of inputs) if (spent.has(p.secret)) stores[STORES$1.proofs].delete(p.secret);
34862
35713
  else stores[STORES$1.proofs].put({
34863
35714
  ...p,
@@ -34882,11 +35733,11 @@ var CashuWallet = class CashuWallet {
34882
35733
  /** The invoice is paid: the reserved proofs are spent, the change is ours, and the payment goes in the history. */
34883
35734
  async finishMelt(melt, change) {
34884
35735
  const tx = walletTx(melt.mint, "lightning-out", melt.amount, melt.outlay - sats(change) - melt.amount, melt.note);
34885
- await transact([
35736
+ await this.sealedTransact([
34886
35737
  STORES$1.proofs,
34887
35738
  STORES$1.melts,
34888
35739
  STORES$1.walletTx
34889
- ], (stores) => {
35740
+ ], { [STORES$1.proofs]: change }, (stores) => {
34890
35741
  for (const secret of melt.secrets) stores[STORES$1.proofs].delete(secret);
34891
35742
  for (const p of change) stores[STORES$1.proofs].put(toStored(melt.mint, p));
34892
35743
  stores[STORES$1.melts].delete(melt.quote);
@@ -34902,21 +35753,21 @@ var CashuWallet = class CashuWallet {
34902
35753
  async forget(mints, acceptLoss = false) {
34903
35754
  const at = new Set(mints);
34904
35755
  const inFlight = async () => {
34905
- if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
35756
+ if ((await this.readMelts()).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
34906
35757
  };
34907
35758
  await inFlight();
34908
35759
  await this.pollSwaps(mints).catch(() => {});
34909
35760
  await this.lockedAll(mints, async () => {
34910
35761
  await inFlight();
34911
- if ((await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
35762
+ if ((await this.readSwaps()).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
34912
35763
  const proofs = (await this.allProofs()).filter((p) => at.has(p.mint));
34913
35764
  const quotes = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).filter((q) => at.has(q.mint));
34914
- const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint));
34915
- await transact([
35765
+ const swaps = (await this.readSwaps()).filter((s) => at.has(s.mint));
35766
+ await this.sealedTransact([
34916
35767
  STORES$1.proofs,
34917
35768
  STORES$1.quotes,
34918
35769
  STORES$1.swaps
34919
- ], (stores) => {
35770
+ ], {}, (stores) => {
34920
35771
  for (const p of proofs) stores[STORES$1.proofs].delete(p.secret);
34921
35772
  for (const q of quotes) stores[STORES$1.quotes].delete(q.quote);
34922
35773
  for (const s of swaps) stores[STORES$1.swaps].delete(s.id);
@@ -34956,7 +35807,7 @@ var CashuWallet = class CashuWallet {
34956
35807
  if (!wallet) {
34957
35808
  wallet = (async () => {
34958
35809
  const instance = new (await (loadCashu())).Wallet(mint, { unit: UNIT$1 });
34959
- await within(MINT_TIMEOUT_MS, instance.loadMint(), mint);
35810
+ await within$1(MINT_TIMEOUT_MS, instance.loadMint(), mint);
34960
35811
  const info = instance.getMintInfo();
34961
35812
  if (info.isSupported(5).params.some(saysAmountlessBeside)) instance.loadMintFromCache(amountlessUnderOptions(info.cache), instance.keyChain.cache);
34962
35813
  return instance;
@@ -34989,7 +35840,28 @@ var CashuWallet = class CashuWallet {
34989
35840
  return [...new Set(mints)].sort().reduceRight((inner, mint) => () => this.locked(mint, inner), task)();
34990
35841
  }
34991
35842
  async allProofs() {
34992
- return wrap((await store(STORES$1.proofs, "readonly")).getAll());
35843
+ return openRows(STORES$1.proofs, await wrap((await store(STORES$1.proofs, "readonly")).getAll()));
35844
+ }
35845
+ async readSwaps() {
35846
+ return openRows(STORES$1.swaps, await wrap((await store(STORES$1.swaps, "readonly")).getAll()));
35847
+ }
35848
+ async readMelts() {
35849
+ return openRows(STORES$1.melts, await wrap((await store(STORES$1.melts, "readonly")).getAll()));
35850
+ }
35851
+ /** Sealed before its transaction opens (one that waits for WebCrypto commits early), when the profile is encrypted. */
35852
+ async putSwap(swap) {
35853
+ const row = await sealRow(STORES$1.swaps, swap);
35854
+ await committed((await store(STORES$1.swaps, "readwrite")).put(row));
35855
+ }
35856
+ /**
35857
+ * `transact`, with the wallet's secrets sealed as they are written when the profile is encrypted (WISP 04): `rows`,
35858
+ * the proofs, swaps, melts and payments the work may put, are sealed before the transaction opens, and the work finds
35859
+ * a proof by its secret. Without the data key, `transact` itself.
35860
+ */
35861
+ async sealedTransact(names, rows, work) {
35862
+ const seals = new RowSeals();
35863
+ for (const [name, list] of Object.entries(rows)) await seals.prepare(name, list ?? []);
35864
+ return transact(names, (stores) => work(seals.on ? Object.fromEntries(names.map((name) => [name, sealedStore(stores[name], seals)])) : stores));
34993
35865
  }
34994
35866
  async proofsAt(mint) {
34995
35867
  return (await this.allProofs()).filter((p) => p.mint === mint && !p.reserved);
@@ -35058,6 +35930,13 @@ var ENDPOINT_OF = {
35058
35930
  bitcoin: ENDPOINT.bitcoin,
35059
35931
  spark: ENDPOINT.spark
35060
35932
  };
35933
+ /**
35934
+ * Every USDT request carries the wallet's one address: a transfer to it says which request it pays only by its amount.
35935
+ * So each asks for a little more than typed, 1 to USDT_TAG_SPAN-1 base units (under a thousandth of a USDT), an amount
35936
+ * no other open request of that network asks for; a transfer settles only the request of its exact amount.
35937
+ */
35938
+ var USDT_TAG_SPAN = 1e3;
35939
+ var USDT_TX_USED = "This transaction already paid another request";
35061
35940
  /** A `pay` frame that carries no receipt, only "I paid this from another wallet: look now". */
35062
35941
  var CHECK_PAYLOAD = JSON.stringify({ check: true });
35063
35942
  var isCheck = (payload) => {
@@ -35217,6 +36096,11 @@ var PaymentBook = class extends Map {
35217
36096
  * (`receiveCheck`): no more often than the wallet's own refresh, which runs the same look.
35218
36097
  */
35219
36098
  var RAIL_LOOK_MS = 1e4;
36099
+ /**
36100
+ * Whether `at` was less than `ms` ago, for the desk's paces. A time later than now (the device clock went back) is long
36101
+ * ago: otherwise a pace stays shut for as long as the clock went back.
36102
+ */
36103
+ var within = (now, at, ms) => at !== void 0 && at <= now && now - at < ms;
35220
36104
  var PaymentDesk = class {
35221
36105
  wallet;
35222
36106
  host;
@@ -35224,6 +36108,8 @@ var PaymentDesk = class {
35224
36108
  paying = /* @__PURE__ */ new Map();
35225
36109
  receiving = /* @__PURE__ */ new Map();
35226
36110
  reclaims = /* @__PURE__ */ new Map();
36111
+ /** Receipts older than `RECEIPT_FRESH_MS` said again in this run of the app, by payment id (`receiptOwed`). */
36112
+ receiptsSaid = /* @__PURE__ */ new Set();
35227
36113
  checkingArk = false;
35228
36114
  checkingUsdt = false;
35229
36115
  checkingBark = false;
@@ -35275,8 +36161,9 @@ var PaymentDesk = class {
35275
36161
  return federation && this.fedimint ? distinct(this.fedimint).find((w) => w.federation(federation)) : void 0;
35276
36162
  }
35277
36163
  async start() {
35278
- const stored = await wrap((await store(STORES$1.payments, "readonly")).getAll());
36164
+ const stored = await openRows(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).getAll()));
35279
36165
  for (const payment of stored) this.payments.set(payment.id, payment);
36166
+ for (const payment of stored) if (payment.kind === "request" && payment.direction === "in" && payment.lightningPending) await this.settleInterrupted(payment);
35280
36167
  const claims = await wrap((await store(STORES$1.settings, "readonly")).get(INVOICE_CLAIMS_KEY));
35281
36168
  this.claims = [...(claims ?? []).filter((c) => !this.claims.some((d) => sameClaim(c, d))), ...this.claims];
35282
36169
  }
@@ -35338,12 +36225,13 @@ var PaymentDesk = class {
35338
36225
  if (usdt.configured === false) throw new Error(mine("USDT"));
35339
36226
  const target = await usdt.target();
35340
36227
  const unit = target.asset === "USDT" ? "usdt" : "testusdt";
36228
+ const amount = this.uniqueUsdtAmount(params.amount, target.network);
35341
36229
  await this.save({
35342
36230
  id,
35343
36231
  linkId: params.linkId,
35344
36232
  kind: "request",
35345
36233
  direction: "out",
35346
- amount: params.amount,
36234
+ amount,
35347
36235
  unit,
35348
36236
  memo,
35349
36237
  state: "pending",
@@ -35355,7 +36243,7 @@ var PaymentDesk = class {
35355
36243
  await this.host.storeMessage({
35356
36244
  linkId: params.linkId,
35357
36245
  id: `me_${params.timestamp}`,
35358
- text: `Requested ${formatPaymentAmount(params.amount, target.decimals)} ${target.asset}`,
36246
+ text: `Requested ${formatPaymentAmount(amount, target.decimals)} ${target.asset}`,
35359
36247
  sender: "me",
35360
36248
  timestamp: params.timestamp,
35361
36249
  via: "datalink",
@@ -35365,7 +36253,7 @@ var PaymentDesk = class {
35365
36253
  id,
35366
36254
  timestamp: params.timestamp,
35367
36255
  amount: {
35368
- value: String(params.amount),
36256
+ value: String(amount),
35369
36257
  asset: unit
35370
36258
  },
35371
36259
  memo,
@@ -35965,7 +36853,8 @@ var PaymentDesk = class {
35965
36853
  */
35966
36854
  answering(linkId, request, method, amount, network) {
35967
36855
  const ask = request.ask ? this.asks.get(request.ask) : void 0;
35968
- if (!ask || ask.linkId !== linkId || ask.method !== method || ask.amount !== amount || ask.expiresAt < Date.now() || network !== ask.network) return void 0;
36856
+ if (!ask || ask.linkId !== linkId || ask.method !== method || ask.expiresAt < Date.now() || network !== ask.network) return void 0;
36857
+ if (method === "usdt" ? amount < ask.amount || amount >= ask.amount + USDT_TAG_SPAN : amount !== ask.amount) return void 0;
35969
36858
  this.asks.delete(request.ask);
35970
36859
  return request.ask;
35971
36860
  }
@@ -35977,7 +36866,7 @@ var PaymentDesk = class {
35977
36866
  const link = this.host.getLink(linkId);
35978
36867
  if (!link) return;
35979
36868
  const now = Date.now();
35980
- if (now - (this.lastAskFrom.get(linkId) ?? 0) < 3e3) return;
36869
+ if (within(now, this.lastAskFrom.get(linkId), 3e3)) return;
35981
36870
  this.lastAskFrom.set(linkId, now);
35982
36871
  if ([...this.payments.values()].filter((p) => p.linkId === linkId && p.kind === "request" && p.direction === "out" && p.state === "pending" && p.ask).length >= 5 || !/^[1-9]\d{0,15}$/.test(ask.amount.value)) return;
35983
36872
  if (ask.method === "bitcoin" && [...this.payments.values()].filter((p) => p.kind === "request" && p.direction === "out" && p.ask && p.target?.method === "bitcoin" && now - p.createdAt < 36e5).length >= 10) return;
@@ -36402,14 +37291,21 @@ var PaymentDesk = class {
36402
37291
  Promise.resolve(this.host.onReviewedPaymentResult?.(payment.id)).catch(() => {});
36403
37292
  return;
36404
37293
  }
36405
- if (!payment || payment.linkId !== linkId || payment.state !== "pending") return;
36406
- if (payment.kind === "request") {
36407
- if (payment.direction === "in" && result.ok) await this.save({
37294
+ if (result.ok && payment?.kind === "request" && payment.direction === "in" && payment.linkId === linkId) {
37295
+ const settles = payment.state === "pending";
37296
+ if (settles || !payment.payeeConfirmed) await this.save({
36408
37297
  ...payment,
36409
- state: "settled",
36410
- lightningPending: void 0
37298
+ ...settles && {
37299
+ state: "settled",
37300
+ lightningPending: void 0
37301
+ },
37302
+ payeeConfirmed: true
36411
37303
  });
36412
- else if (payment.direction === "in" && result.closed && !payment.lightningPending) await this.save({
37304
+ return;
37305
+ }
37306
+ if (!payment || payment.linkId !== linkId || payment.state !== "pending") return;
37307
+ if (payment.kind === "request") {
37308
+ if (payment.direction === "in" && result.closed && !payment.lightningPending) await this.save({
36413
37309
  ...payment,
36414
37310
  state: "failed",
36415
37311
  closed: true,
@@ -36481,7 +37377,7 @@ var PaymentDesk = class {
36481
37377
  const endpoint = request.target ? request.target.method === "fedimint" ? request.invoice ? [ENDPOINT.bolt11, request.invoice] : void 0 : request.target.method === "usdt" || request.target.method === "cashu" ? void 0 : [ENDPOINT_OF[request.target.method], CHECK_PAYLOAD] : request.invoice ? [ENDPOINT.bolt11, request.invoice] : void 0;
36482
37378
  if (!endpoint) throw new Error("This request cannot be paid from another wallet");
36483
37379
  const now = Date.now();
36484
- if (now - (this.lastCheck.get(request.id) ?? 0) < 5e3) return;
37380
+ if (within(now, this.lastCheck.get(request.id), 5e3)) return;
36485
37381
  this.lastCheck.set(request.id, now);
36486
37382
  const link = this.requireLink(params.linkId);
36487
37383
  await this.sendTo(link, {
@@ -36503,7 +37399,7 @@ var PaymentDesk = class {
36503
37399
  */
36504
37400
  async receiveCheck(linkId, payment) {
36505
37401
  const link = this.host.getLink(linkId);
36506
- if (link && !payment.requestId && payment.endpoint[0] === ENDPOINT.bolt11) return this.receiveInvoicePaid(linkId, link, payment.endpoint[1]);
37402
+ if (link && !payment.requestId && payment.endpoint[0] === ENDPOINT.bolt11) return this.receiveInvoicePaid(linkId, payment.endpoint[1]);
36507
37403
  const request = payment.requestId ? this.payments.get(payment.requestId) : void 0;
36508
37404
  if (!link || !request || request.kind !== "request" || request.direction !== "out" || !this.owns(request, linkId)) return;
36509
37405
  const rail = request.target ? request.target.method : request.invoice ? "lightning" : void 0;
@@ -36517,11 +37413,12 @@ var PaymentDesk = class {
36517
37413
  }
36518
37414
  const now = Date.now();
36519
37415
  const [key, every] = rail === "lightning" ? [request.id, 3e3] : [rail, RAIL_LOOK_MS];
36520
- if (now - (this.lastCheckFrom.get(key) ?? 0) < every) return;
37416
+ if (within(now, this.lastCheckFrom.get(key), every)) return;
36521
37417
  this.lastCheckFrom.set(key, now);
36522
37418
  try {
36523
- if (rail === "lightning") await this.lightning[paymentNetwork(request)].check?.(payment.endpoint[1].trim().toLowerCase() === request.invoice?.toLowerCase() ? request.invoice : void 0);
36524
- else if (rail === "bitcoin") await this.reconcileBitcoinReceipts();
37419
+ if (rail === "lightning") {
37420
+ if (request.invoice) await this.lightning[paymentNetwork(request)].check?.(request.invoice, payment.endpoint[1].trim().toLowerCase() === request.invoice.toLowerCase());
37421
+ } else if (rail === "bitcoin") await this.reconcileBitcoinReceipts();
36525
37422
  else if (rail === "bark") await this.reconcileBarkReceipts();
36526
37423
  else if (rail === "spark") await this.reconcileSparkReceipts();
36527
37424
  else await this.reconcileArkReceipts();
@@ -36533,27 +37430,27 @@ var PaymentDesk = class {
36533
37430
  * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per invoice of a chat, so two
36534
37431
  * invoices paid one right after the other are both let go, and `INVOICE_LOOKS_PER_CHAT` looks every 3 seconds per
36535
37432
  * chat: the invoice is the contact's text, and a frame per text made each one a read of every invoice of the wallet
36536
- * (2,000 frames, 2,000 reads), each also walking every key of the last 3 s (agents#1586).
37433
+ * (2,000 frames, 2,000 reads), each also walking every key of the last 3 s (agents#1586). Taken whatever the chat's
37434
+ * Lightning choice: a group's card tells the writer through their 1:1 chat, and the word lets go of our own invoice only.
36537
37435
  */
36538
- async receiveInvoicePaid(linkId, link, invoice) {
36539
- if (!link.allowsPayment("lightning")) return;
37436
+ async receiveInvoicePaid(linkId, invoice) {
36540
37437
  const now = Date.now();
36541
37438
  const wanted = invoice.trim().toLowerCase();
36542
37439
  const key = `${linkId}:${wanted}`;
36543
- if (now - (this.lastInvoiceCheck.get(key) ?? 0) < 3e3) return;
36544
- const looks = (this.invoiceLooks.get(linkId) ?? []).filter((at) => now - at < 3e3);
37440
+ if (within(now, this.lastInvoiceCheck.get(key), 3e3)) return;
37441
+ const looks = (this.invoiceLooks.get(linkId) ?? []).filter((at) => within(now, at, 3e3));
36545
37442
  if (looks.length >= 5) {
36546
37443
  this.invoiceLooks.set(linkId, looks);
36547
37444
  return;
36548
37445
  }
36549
37446
  this.invoiceLooks.set(linkId, [...looks, now]);
36550
37447
  for (const [seen, at] of this.lastInvoiceCheck) {
36551
- if (now - at < 3e3) break;
37448
+ if (within(now, at, 3e3)) break;
36552
37449
  this.lastInvoiceCheck.delete(seen);
36553
37450
  }
36554
37451
  this.lastInvoiceCheck.delete(key);
36555
37452
  this.lastInvoiceCheck.set(key, now);
36556
- for (const [chat, times] of this.invoiceLooks) if (chat !== linkId && times.every((at) => now - at >= 3e3)) this.invoiceLooks.delete(chat);
37453
+ for (const [chat, times] of this.invoiceLooks) if (chat !== linkId && times.every((at) => !within(now, at, 3e3))) this.invoiceLooks.delete(chat);
36557
37454
  try {
36558
37455
  const quote = (await this.wallet.quotes()).find((q) => q.held && !q.paymentId && q.invoice.toLowerCase() === wanted);
36559
37456
  if (quote) await this.wallet.vouch(quote.invoice);
@@ -36580,6 +37477,20 @@ var PaymentDesk = class {
36580
37477
  error: "The Lightning payment did not go through"
36581
37478
  });
36582
37479
  }
37480
+ /**
37481
+ * A contact's request marked as being paid over Lightning when the app was closed: the mark is written before the
37482
+ * source is asked, and only that run's answer cleared it. What the source and the mints wrote down decides: nothing
37483
+ * left the wallet and it can be paid again (and the group is not told it was sent), or it went through.
37484
+ */
37485
+ async settleInterrupted(request) {
37486
+ const lightning = this.lightning[paymentNetwork(request)];
37487
+ if (!lightning.interrupted || this.paying.has(`${request.linkId}:${request.id}`)) return;
37488
+ try {
37489
+ if (request.invoice && await this.wallet.meltInFlight?.(request.invoice)) return;
37490
+ const outcome = await lightning.interrupted(request.id);
37491
+ if (outcome !== "pending") await this.onLightningResolved({ paymentId: request.id }, outcome === "paid");
37492
+ } catch {}
37493
+ }
36583
37494
  onQuotePaid(quote) {
36584
37495
  return this.onLightningPaid(quote);
36585
37496
  }
@@ -36711,7 +37622,8 @@ var PaymentDesk = class {
36711
37622
  if (typeof txid !== "string" || !/^0x[a-fA-F0-9]{64}$/.test(txid)) return;
36712
37623
  if (this.repeatedReceipt(this.host.getLink(linkId), request, payment.id)) return;
36713
37624
  txid = txid.toLowerCase();
36714
- 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;
37625
+ const used = this.usdtTxUsed(txid, request.id);
37626
+ const paid = request.state === "settled";
36715
37627
  await this.save({
36716
37628
  id: payment.id,
36717
37629
  linkId,
@@ -36719,7 +37631,8 @@ var PaymentDesk = class {
36719
37631
  direction: "in",
36720
37632
  amount: request.amount,
36721
37633
  unit: request.unit,
36722
- state: "pending",
37634
+ state: used ? "failed" : "pending",
37635
+ error: used ? USDT_TX_USED : void 0,
36723
37636
  createdAt: payment.timestamp,
36724
37637
  target: request.target,
36725
37638
  requestId: request.id,
@@ -36728,13 +37641,32 @@ var PaymentDesk = class {
36728
37641
  await this.host.storeMessage({
36729
37642
  linkId,
36730
37643
  id: `peer_${payment.timestamp}`,
36731
- text: `${formatPaymentAmount(request.amount, request.target.decimals)} ${request.target.asset} — checking chain`,
37644
+ text: `${formatPaymentAmount(request.amount, request.target.decimals)} ${request.target.asset} — ${used ? USDT_TX_USED.toLowerCase() : "checking chain"}`,
36732
37645
  sender: "peer",
36733
37646
  timestamp: payment.timestamp,
36734
37647
  via: "datalink",
36735
37648
  paymentId: payment.id
36736
37649
  });
36737
- await this.reconcileUsdtReceipts();
37650
+ if (!used) await this.reconcileUsdtReceipts();
37651
+ if (paid) this.host.getLink(linkId)?.sendPaymentResult({
37652
+ id: request.id,
37653
+ ok: true
37654
+ });
37655
+ }
37656
+ /** Whether a USDT transaction already paid a request other than `requestId`. */
37657
+ usdtTxUsed(txid, requestId) {
37658
+ return [...this.payments.values()].some((p) => p.state === "settled" && p.txid?.toLowerCase() === txid.toLowerCase() && (p.kind === "request" ? p.id !== requestId : p.requestId !== requestId));
37659
+ }
37660
+ /** An amount of `amount` plus 1 to USDT_TAG_SPAN-1 base units that no open USDT request of `network` asks for. */
37661
+ uniqueUsdtAmount(amount, network) {
37662
+ const taken = /* @__PURE__ */ new Set();
37663
+ for (const p of this.payments.values()) if (p.kind === "request" && p.direction === "out" && p.state === "pending" && p.target?.method === "usdt" && p.target.network === network) taken.add(p.amount);
37664
+ const free = [];
37665
+ for (let tag = 1; tag < USDT_TAG_SPAN; tag++) if (!taken.has(amount + tag)) free.push(amount + tag);
37666
+ if (!free.length) throw new Error("Too many open USDT requests of this amount: wait for one to be paid");
37667
+ const unique = free[randomBytes(4).reduce((n, b) => n * 256 + b, 0) % free.length];
37668
+ assertTokenUnits(unique);
37669
+ return unique;
36738
37670
  }
36739
37671
  async reconcileUsdtReceipts() {
36740
37672
  if (this.checkingUsdt || !this.usdt) return;
@@ -36749,6 +37681,14 @@ var PaymentDesk = class {
36749
37681
  amount: payment.amount
36750
37682
  }).catch(() => null);
36751
37683
  if (!result?.settled && !result?.failed) continue;
37684
+ if (result.settled && this.usdtTxUsed(payment.txid, payment.requestId)) {
37685
+ await this.save({
37686
+ ...payment,
37687
+ state: "failed",
37688
+ error: USDT_TX_USED
37689
+ });
37690
+ continue;
37691
+ }
36752
37692
  await this.save({
36753
37693
  ...payment,
36754
37694
  state: result.settled ? "settled" : "failed",
@@ -36819,7 +37759,7 @@ var PaymentDesk = class {
36819
37759
  if (!review.linkId || review.method !== "cashu") throw new Error("Cashu chat recipient missing");
36820
37760
  const link = this.requireLink(review.linkId);
36821
37761
  await link.requirePaymentSupport();
36822
- const existing = await wrap((await store(STORES$1.payments, "readonly")).get(review.id));
37762
+ const existing = await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
36823
37763
  if (!existing || existing.linkId !== review.linkId || existing.requestId !== review.requestId) throw new Error("Cashu outbox does not match the reviewed payment");
36824
37764
  this.payments.set(existing.id, existing);
36825
37765
  this.host.onChange();
@@ -36846,7 +37786,7 @@ var PaymentDesk = class {
36846
37786
  }
36847
37787
  async confirmReviewedCashu(review) {
36848
37788
  if (review.method !== "cashu" || review.state !== "settled") return;
36849
- const payment = this.payments.get(review.id) ?? await wrap((await store(STORES$1.payments, "readonly")).get(review.id));
37789
+ const payment = this.payments.get(review.id) ?? await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
36850
37790
  if (!payment || payment.linkId !== review.linkId || payment.state === "reclaimed") return;
36851
37791
  await this.save({
36852
37792
  ...payment,
@@ -36885,6 +37825,7 @@ var PaymentDesk = class {
36885
37825
  if ([...this.payments.values()].some((p) => p.txid === txid && (p.linkId !== linkId || (p.kind === "request" ? p.id !== request.id : p.requestId !== request.id)))) return;
36886
37826
  if (typeof txid !== "string" || !/^[a-f0-9]{64}$/.test(txid)) return;
36887
37827
  if (this.repeatedReceipt(link, request, payment.id)) return;
37828
+ const paid = request.state === "settled";
36888
37829
  await this.save({
36889
37830
  id: payment.id,
36890
37831
  linkId,
@@ -36908,6 +37849,10 @@ var PaymentDesk = class {
36908
37849
  paymentId: payment.id
36909
37850
  });
36910
37851
  await this.reconcileArkReceipts();
37852
+ if (paid) link.sendPaymentResult({
37853
+ id: request.id,
37854
+ ok: true
37855
+ });
36911
37856
  }
36912
37857
  /**
36913
37858
  * An Ark request is paid when a virtual output of at least the amount reached the address made for it,
@@ -37001,8 +37946,16 @@ var PaymentDesk = class {
37001
37946
  if (!link?.supportsBarkPayments || request?.target?.method !== "bark" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
37002
37947
  const existing = this.payments.get(payment.id);
37003
37948
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
37004
- if (existing || parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
37949
+ if (existing) {
37950
+ if (request.state === "settled") link.sendPaymentResult({
37951
+ id: request.id,
37952
+ ok: true
37953
+ });
37954
+ return;
37955
+ }
37956
+ if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
37005
37957
  if (this.repeatedReceipt(link, request, payment.id)) return;
37958
+ const settled = request.state === "settled";
37006
37959
  await this.save({
37007
37960
  id: payment.id,
37008
37961
  linkId,
@@ -37010,7 +37963,7 @@ var PaymentDesk = class {
37010
37963
  direction: "in",
37011
37964
  amount: request.amount,
37012
37965
  unit: UNIT,
37013
- state: request.state === "settled" ? "settled" : "pending",
37966
+ state: settled ? "settled" : "pending",
37014
37967
  createdAt: payment.timestamp,
37015
37968
  target: request.target,
37016
37969
  requestId: request.id,
@@ -37019,13 +37972,17 @@ var PaymentDesk = class {
37019
37972
  await this.host.storeMessage({
37020
37973
  linkId,
37021
37974
  id: `peer_${payment.timestamp}`,
37022
- text: `${request.amount} ${arkSats(request.target.network)} on Bark${request.state === "settled" ? "" : " — checking wallet"}`,
37975
+ text: `${request.amount} ${arkSats(request.target.network)} on Bark${settled ? "" : " — checking wallet"}`,
37023
37976
  sender: "peer",
37024
37977
  timestamp: payment.timestamp,
37025
37978
  via: "datalink",
37026
37979
  paymentId: payment.id
37027
37980
  });
37028
37981
  await this.reconcileBarkReceipts();
37982
+ if (settled) link.sendPaymentResult({
37983
+ id: request.id,
37984
+ ok: true
37985
+ });
37029
37986
  }
37030
37987
  /**
37031
37988
  * A Bark request is paid when this wallet received, on the address made for it, at least the amount asked,
@@ -37136,7 +38093,14 @@ var PaymentDesk = class {
37136
38093
  if (!link?.supportsBitcoinPayments || request?.target?.method !== "bitcoin" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
37137
38094
  const existing = this.payments.get(payment.id);
37138
38095
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
37139
- if (existing || parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
38096
+ if (existing) {
38097
+ if (request.state === "settled") link.sendPaymentResult({
38098
+ id: request.id,
38099
+ ok: true
38100
+ });
38101
+ return;
38102
+ }
38103
+ if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
37140
38104
  let hint;
37141
38105
  try {
37142
38106
  hint = JSON.parse(payment.endpoint[1]).txid;
@@ -37169,6 +38133,10 @@ var PaymentDesk = class {
37169
38133
  paymentId: payment.id
37170
38134
  });
37171
38135
  await this.reconcileBitcoinReceipts();
38136
+ if (settled) link.sendPaymentResult({
38137
+ id: request.id,
38138
+ ok: true
38139
+ });
37172
38140
  }
37173
38141
  /**
37174
38142
  * An on-chain request is paid when this wallet's source has a confirmed transaction paying the address made
@@ -37396,7 +38364,8 @@ var PaymentDesk = class {
37396
38364
  const redeemed = await fedimint.redeemNotes(payment.federation, payment.token, payment.id);
37397
38365
  await this.save({
37398
38366
  ...this.current(payment),
37399
- fedimintOp: redeemed.operationId
38367
+ fedimintOp: redeemed.operationId,
38368
+ ...redeemed.error !== void 0 ? { error: redeemed.error } : {}
37400
38369
  });
37401
38370
  state = redeemed.state;
37402
38371
  }
@@ -37540,7 +38509,14 @@ var PaymentDesk = class {
37540
38509
  if (!link?.supportsSparkPayments || request?.target?.method !== "spark" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
37541
38510
  const existing = this.payments.get(payment.id);
37542
38511
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
37543
- if (existing || parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
38512
+ if (existing) {
38513
+ if (request.state === "settled") link.sendPaymentResult({
38514
+ id: request.id,
38515
+ ok: true
38516
+ });
38517
+ return;
38518
+ }
38519
+ if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
37544
38520
  if (this.repeatedReceipt(link, request, payment.id)) return;
37545
38521
  const settled = request.state === "settled";
37546
38522
  await this.save({
@@ -37566,6 +38542,10 @@ var PaymentDesk = class {
37566
38542
  paymentId: payment.id
37567
38543
  });
37568
38544
  await this.reconcileSparkReceipts();
38545
+ if (settled) link.sendPaymentResult({
38546
+ id: request.id,
38547
+ ok: true
38548
+ });
37569
38549
  }
37570
38550
  /**
37571
38551
  * A Spark request is paid when this wallet completed a receive on the invoice made for it, of at least the amount
@@ -37735,7 +38715,7 @@ var PaymentDesk = class {
37735
38715
  endpoints: [[ENDPOINT.usdt, JSON.stringify(payment.target)]],
37736
38716
  ask: payment.ask
37737
38717
  });
37738
- else if (payment.kind === "payment" && payment.txid && payment.state !== "failed") await this.sendTo(link, {
38718
+ else if (payment.kind === "payment" && payment.txid && payment.state !== "failed" && this.receiptOwed(payment)) await this.sendTo(link, {
37739
38719
  id: payment.id,
37740
38720
  timestamp: payment.createdAt,
37741
38721
  requestId: payment.requestId,
@@ -37760,7 +38740,7 @@ var PaymentDesk = class {
37760
38740
  endpoints: [[ENDPOINT.bark, JSON.stringify(payment.target)]],
37761
38741
  ask: payment.ask
37762
38742
  });
37763
- else if (payment.kind === "payment" && payment.state === "settled") await this.sendTo(link, {
38743
+ else if (payment.kind === "payment" && payment.state === "settled" && this.receiptOwed(payment)) await this.sendTo(link, {
37764
38744
  id: payment.id,
37765
38745
  timestamp: payment.createdAt,
37766
38746
  requestId: payment.requestId,
@@ -37801,7 +38781,7 @@ var PaymentDesk = class {
37801
38781
  endpoints: [[ENDPOINT.spark, JSON.stringify(payment.target)]],
37802
38782
  ask: payment.ask
37803
38783
  });
37804
- else if (payment.kind === "payment" && payment.state === "settled") await this.sendTo(link, {
38784
+ else if (payment.kind === "payment" && payment.state === "settled" && this.receiptOwed(payment)) await this.sendTo(link, {
37805
38785
  id: payment.id,
37806
38786
  timestamp: payment.createdAt,
37807
38787
  requestId: payment.requestId,
@@ -37826,7 +38806,7 @@ var PaymentDesk = class {
37826
38806
  endpoints: [[ENDPOINT.bitcoin, JSON.stringify(payment.target)]],
37827
38807
  ask: payment.ask
37828
38808
  });
37829
- else if (payment.kind === "payment" && payment.txid && payment.state !== "failed") await this.sendTo(link, {
38809
+ else if (payment.kind === "payment" && payment.txid && payment.state !== "failed" && this.receiptOwed(payment)) await this.sendTo(link, {
37830
38810
  id: payment.id,
37831
38811
  timestamp: payment.createdAt,
37832
38812
  requestId: payment.requestId,
@@ -37851,7 +38831,7 @@ var PaymentDesk = class {
37851
38831
  endpoints: [[ENDPOINT.arkade, JSON.stringify(payment.target)]],
37852
38832
  ask: payment.ask
37853
38833
  });
37854
- else if (payment.kind === "payment" && payment.txid && payment.state === "settled") await this.sendTo(link, {
38834
+ else if (payment.kind === "payment" && payment.txid && payment.state === "settled" && this.receiptOwed(payment)) await this.sendTo(link, {
37855
38835
  id: payment.id,
37856
38836
  timestamp: payment.createdAt,
37857
38837
  requestId: payment.requestId,
@@ -37863,6 +38843,13 @@ var PaymentDesk = class {
37863
38843
  });
37864
38844
  continue;
37865
38845
  }
38846
+ if (payment.kind === "request" && payment.state === "settled" && payment.invoice && !payment.group && Date.now() - payment.createdAt < 6048e5) {
38847
+ link.sendPaymentResult({
38848
+ id: payment.id,
38849
+ ok: true
38850
+ });
38851
+ continue;
38852
+ }
37866
38853
  if (payment.state !== "pending") continue;
37867
38854
  if (payment.kind === "payment" && payment.token) await this.sendTo(link, {
37868
38855
  id: payment.id,
@@ -37888,6 +38875,22 @@ var PaymentDesk = class {
37888
38875
  });
37889
38876
  }
37890
38877
  }
38878
+ /**
38879
+ * Whether a receipt of ours (an on-chain, Ark, Bark, Spark or USDT payment already made) is said again on this
38880
+ * reconnect. Never once the payee said the request it answers is paid (`payeeConfirmed`): its own wallet saw the
38881
+ * money, and the receipt is only a hint. Otherwise at every reconnect while it is under `RECEIPT_FRESH_MS` old, so a
38882
+ * frame lost with a link that went down goes again, and once per run of the app after that: a payee that was away
38883
+ * when we paid still gets it the first time its chat opens, and a long history of payments made before the payee's
38884
+ * app answered them no longer goes out at every reconnect and transport switch. Call it last: it counts a send.
38885
+ */
38886
+ receiptOwed(payment) {
38887
+ const request = payment.requestId ? this.payments.get(payment.requestId) : void 0;
38888
+ if (request?.payeeConfirmed && request.kind === "request" && request.direction === "in" && request.linkId === payment.linkId) return false;
38889
+ if (Date.now() - payment.createdAt < 6048e5) return true;
38890
+ if (this.receiptsSaid.has(payment.id)) return false;
38891
+ this.receiptsSaid.add(payment.id);
38892
+ return true;
38893
+ }
37891
38894
  requireLink(linkId) {
37892
38895
  const link = this.host.getLink(linkId);
37893
38896
  if (!link) throw new Error("You are offline");
@@ -37899,7 +38902,8 @@ var PaymentDesk = class {
37899
38902
  }
37900
38903
  async save(payment) {
37901
38904
  this.payments.set(payment.id, payment);
37902
- await committed((await store(STORES$1.payments, "readwrite")).put(payment));
38905
+ const row = await sealRow(STORES$1.payments, payment);
38906
+ await committed((await store(STORES$1.payments, "readwrite")).put(row));
37903
38907
  this.host.onChange();
37904
38908
  }
37905
38909
  /**
@@ -38036,9 +39040,14 @@ function writtenAt(message, leads) {
38036
39040
  return Math.min(message.timestamp, message.sentAt - behind);
38037
39041
  }
38038
39042
  var JOIN_NOTICE = /^👋 (?:.+ )?joined$/;
39043
+ /**
39044
+ * The quiet "joined" line: a 1:1 contact's only when the engine took it as the chat's joined line (`joinLine`), since
39045
+ * any later row of theirs in those words is a message like the rest; mine and a group's by their words.
39046
+ */
39047
+ var joinLine = (type, message) => type === "message" && !message.linkId.startsWith("group:") ? !!message.joinLine : JOIN_NOTICE.test(message.text);
38039
39048
  /** What a newly stored row says, or null when it is quiet. `type`: "message" for the contact's, "sent" for mine. */
38040
39049
  function messageAttention(type, message, { startedAt, newest, now, lateAt }) {
38041
- if (message.timestamp < startedAt || message.file || message.paymentId || JOIN_NOTICE.test(message.text)) return null;
39050
+ if (message.timestamp < startedAt || message.file || message.paymentId || joinLine(type, message)) return null;
38042
39051
  if (message.event) {
38043
39052
  const cue = groupCue(message);
38044
39053
  return cue && type === "message" ? {
@@ -38201,6 +39210,17 @@ var WalletSetup = class {
38201
39210
  * they all came back in the same instant, more listens than its one HyperDHT node sends out in time.
38202
39211
  */
38203
39212
  var RELAY_RETRY_MS = 3e4;
39213
+ /**
39214
+ * A chat's relayed HyperDHT listener went with the relay connection (`relayHolds`): for this long the chat keeps first
39215
+ * claim on a listener, and another chat does not take the slot it held. A socket closed with no close reaching the relay
39216
+ * (a network switch, a NAT that forgot it) leaves the old connection holding the chat's key until the relay's ping drops
39217
+ * it, 30 to 60 s (55 s measured), and the relay refuses the key to the new connection meanwhile: chats with free keys
39218
+ * took every slot, and the chats used most stayed without a listener until each was used again. The relay's worst ping
39219
+ * drop plus a margin.
39220
+ */
39221
+ var RELAY_HOLD_MS = 9e4;
39222
+ /** How often such a chat tries to listen again within that time, while the relay still refuses its key. */
39223
+ var RELAY_HOLD_RETRY_MS = 1e4;
38204
39224
  /** Native listeners an app may hold per transport (the Desktop's Rust Iroh allows eight, `paired_transport.rs`). */
38205
39225
  var NATIVE_SLOTS = 8;
38206
39226
  /**
@@ -38209,7 +39229,7 @@ var NATIVE_SLOTS = 8;
38209
39229
  * relays took sixteen started one after another, as the queue here starts them (six of sixteen started at once were
38210
39230
  * refused). 1:1 chats hold eight of them at most, as before: the rest is room for group links. HyperDHT keeps eight
38211
39231
  * there too: a page's listeners share one WebSocket to its relay, which drops a client past sixteen listens (device
38212
- * links listen there as well), and each of the CLI's is a whole DHT node.
39232
+ * links listen there as well).
38213
39233
  */
38214
39234
  var IROH_WEB_SLOTS = 16;
38215
39235
  /**
@@ -38233,6 +39253,20 @@ var CLEAR_WITHDRAW_MS = 6e3;
38233
39253
  * session): a dial to a contact that is not there ends within its 20 s timeout, and leaves its slot free until the next.
38234
39254
  */
38235
39255
  var ACTIVE_SLOT_RETRY_MS = 3e3;
39256
+ /**
39257
+ * A 1:1 chat whose contact has not been seen this long (no packet that says it is online, no session, no text either
39258
+ * way, not on screen) lets its HyperDHT listener go: hyperdht keeps an announced listener reachable by pinging three DHT
39259
+ * nodes every 3 s, about 62 requests a minute, for a contact who is not there to dial it. It listens again as soon as
39260
+ * the contact is seen online (its next packet read: half a minute at most at the background pace), a text goes either
39261
+ * way, the chat is opened, or the contact's packet cannot be read (the relays out of reach: no read would say it is
39262
+ * back); its transport key is kept. A contact gone a little while (an app restarted, a laptop asleep for a few
39263
+ * minutes) finds it as before.
39264
+ */
39265
+ var NATIVE_GONE_MS = 6e5;
39266
+ /** How often the chats are looked at for that (`releaseGoneListeners`). */
39267
+ var NATIVE_GONE_CHECK_MS = 15e3;
39268
+ /** The transport that lets a gone contact's listener go: the one whose waiting costs the network (`NATIVE_GONE_MS`). */
39269
+ var GONE_TRANSPORT = "hyperdht/1";
38236
39270
  /** How long an edge passed over that way ranks after the others, before the group tries it again. */
38237
39271
  var GROUP_ANCHOR_PASSED_MS = 3e5;
38238
39272
  /** How often the edges groups keep are looked at for that (`groupAnchorsAnswered`). */
@@ -38252,9 +39286,25 @@ var DEFAULT_SETTINGS = {
38252
39286
  mints: [],
38253
39287
  mintsInitialized: false
38254
39288
  };
39289
+ /** How many deleted ids a link remembers: enough to outlast what a peer republishes. */
39290
+ var MAX_DELETED_IDS = 500;
38255
39291
  /** A link's `removedRefs` with `ref`, the newest `MAX_DELETED_IDS`. */
38256
39292
  var withRemovedRef = (refs, ref) => [...(refs ?? []).filter((r) => r !== ref), ref].slice(-500);
38257
39293
  /**
39294
+ * A 1:1 chat's `deletedIds` with `id`. Full (`MAX_DELETED_IDS`), the oldest of the side that has the most goes (the one
39295
+ * just noted's own on a tie), as a group's removed ids by author (`withRemovedId`): my deletions, as many as I make,
39296
+ * never push out an id of the contact's, so a copy of theirs that comes again stays deleted, nor theirs one of mine.
39297
+ */
39298
+ var withDeletedId = (ids, id) => {
39299
+ const next = [...ids ?? [], id];
39300
+ if (next.length <= MAX_DELETED_IDS) return next;
39301
+ const theirs = (row) => row.startsWith("peer_");
39302
+ const peer = next.filter(theirs).length;
39303
+ const side = peer * 2 === next.length ? theirs(id) : peer * 2 > next.length;
39304
+ next.splice(next.findIndex((row) => theirs(row) === side), 1);
39305
+ return next;
39306
+ };
39307
+ /**
38258
39308
  * A card that went on the DHT floor or into a hold goes again live (`restoreCards`) only for the newest this many
38259
39309
  * messages of a chat, sent within this long: an old chat's cards are not worth a burst of edits.
38260
39310
  */
@@ -38279,6 +39329,32 @@ var pkarrSeenAt = (messages) => messages.reduce((max, m) => m.sender === "peer"
38279
39329
  var waitsForLive = (m) => m.sender === "me" && m.delivery === "waiting" && (!!m.file || !!m.paymentId);
38280
39330
  /** A message of mine whose card went as its text alone and is due to go again live (`restoreCards`). */
38281
39331
  var cardDue = (m) => m.sender === "me" && (m.cardRestore ?? m.buttonsRestore) === "due";
39332
+ /**
39333
+ * A row id of the contact's own in a 1:1 chat: not the note a contact request carried (the chat's first row on the side
39334
+ * that accepted it, before the contact's joined line), nor a line of this app's about their payment (`shared/refusals.ts`).
39335
+ */
39336
+ var contactRowId = (id) => id.startsWith("peer_") && !id.startsWith("peer_contact_") && !isRefusalId(id);
39337
+ /** A row of the contact's own (`contactRowId`) in the words of the chat's joined line. */
39338
+ var contactJoinRow = (m) => m.sender === "peer" && contactRowId(m.id) && isJoinNotice(m.text);
39339
+ /**
39340
+ * Whether a 1:1 chat holds a row of the contact's in the joined line's words (`contactJoinRow`) other than `except`:
39341
+ * oldest first, a page at a time.
39342
+ */
39343
+ async function contactJoinRowStored(linkId, except) {
39344
+ for (let after = { timestamp: -Infinity };;) {
39345
+ const page = await db.getMessagePageAfter(linkId, {
39346
+ limit: 64,
39347
+ after
39348
+ });
39349
+ if (page.messages.some((m) => m.id !== except && contactJoinRow(m))) return true;
39350
+ const last = page.messages[page.messages.length - 1];
39351
+ if (!page.more || !last) return false;
39352
+ after = {
39353
+ timestamp: last.timestamp,
39354
+ id: last.id
39355
+ };
39356
+ }
39357
+ }
38282
39358
  /** The id a 1:1 chat's row goes by on both sides when its own row is not `peer_`/`me_` and that id (`resolveReply`). */
38283
39359
  var unkeyedRef = (m) => {
38284
39360
  const ref = replyRef(m, false);
@@ -38360,6 +39436,7 @@ function newLiveLink(stored, lastMessageAt, files = emptyLinkFiles()) {
38360
39436
  lastPacketAt: 0,
38361
39437
  services: null
38362
39438
  },
39439
+ onlineSeenAt: Date.now(),
38363
39440
  lastMessageAt,
38364
39441
  peerAck: 0,
38365
39442
  lastSyncAt: 0,
@@ -38576,6 +39653,8 @@ var GhostlyNode = class GhostlyNode {
38576
39653
  }
38577
39654
  /** The newest time written in each chat while this engine runs: a message written well before it is a catch-up. */
38578
39655
  newestAt = /* @__PURE__ */ new Map();
39656
+ /** The chats whose contact's joined line came while this engine runs (`firstContactRow`), whatever `stored` says. */
39657
+ contactSpoke = /* @__PURE__ */ new WeakSet();
38579
39658
  /** Per group: when the last message written well before it came, came. What comes after it, as old, is its catch-up. */
38580
39659
  lateAt = /* @__PURE__ */ new Map();
38581
39660
  /** The last place given in each chat while this engine runs (`arrivalKey`). */
@@ -38590,8 +39669,8 @@ var GhostlyNode = class GhostlyNode {
38590
39669
  return message.linkId.startsWith("group:") ? `${message.linkId} ${message.member ?? ""}` : message.linkId;
38591
39670
  }
38592
39671
  /**
38593
- * A contact's row came on the live session of a 1:1 chat, or a member's straight from its author (`live`, never one
38594
- * handed on or caught up): what it says of that clock is kept.
39672
+ * A contact's row came on the live session of a 1:1 chat, or a member's as it was written (`live`: straight from its
39673
+ * author, or in a community handed on at once by a hub that says so; never one caught up): what it says of that clock is kept.
38595
39674
  */
38596
39675
  clockSample(message, live = false) {
38597
39676
  if (message.sender !== "peer" || message.sentAt === void 0 || message.event || message.via !== "datalink") return;
@@ -38974,13 +40053,14 @@ var GhostlyNode = class GhostlyNode {
38974
40053
  note,
38975
40054
  paymentId
38976
40055
  }),
38977
- check: async (paid) => {
40056
+ check: async (invoice, named) => {
38978
40057
  await Promise.all([
38979
- this.lightnings[network].reconcile(),
38980
- paid ? this.wallet.vouch(paid) : this.wallet.checkQuotes(),
40058
+ this.lightnings[network].check(invoice),
40059
+ this.wallet.vouch(invoice, named),
38981
40060
  this.fedimintWallets[network].checkReceives()
38982
40061
  ]);
38983
- }
40062
+ },
40063
+ interrupted: journaledPayment
38984
40064
  })), this.bitcoins, this.fedimintWallets, perNetwork((network) => ({
38985
40065
  ready: () => !!this.sparkWallets[network].adapter,
38986
40066
  requestTarget: (amount, memo) => this.sparkWallets[network].target(amount, memo),
@@ -39277,22 +40357,87 @@ var GhostlyNode = class GhostlyNode {
39277
40357
  accept: async (request) => {
39278
40358
  const params = decodeInviteCode(request.invite);
39279
40359
  if (!params || inviteOwnership(params, [...this.links.values()].map((l) => l.stored)).kind !== "new") throw new Error("This request's invite is for a chat you already have.");
39280
- const { linkId } = await this.joinLink({ inviteCode: request.invite });
39281
- this.renameLink({
39282
- linkId,
39283
- label: request.name
39284
- });
39285
- await this.storeMessage({
39286
- linkId,
39287
- id: `peer_contact_${request.key.slice(0, 32)}`,
39288
- text: request.text,
39289
- sender: "peer",
39290
- timestamp: Math.min(request.issued, request.receivedAt),
39291
- via: "pkarr"
39292
- });
39293
- return linkId;
40360
+ this.accepting = true;
40361
+ try {
40362
+ const { linkId } = await this.joinLink({ inviteCode: request.invite });
40363
+ this.renameLink({
40364
+ linkId,
40365
+ label: request.name
40366
+ });
40367
+ const message = `peer_contact_${request.key.slice(0, 32)}`;
40368
+ const contactAsker = {
40369
+ link: request.link,
40370
+ key: request.key,
40371
+ message
40372
+ };
40373
+ const live = this.links.get(linkId);
40374
+ if (live) live.stored = {
40375
+ ...live.stored,
40376
+ contactAsker
40377
+ };
40378
+ await db.patchLink(linkId, { contactAsker });
40379
+ await this.storeMessage({
40380
+ linkId,
40381
+ id: message,
40382
+ text: request.text,
40383
+ sender: "peer",
40384
+ timestamp: Math.min(request.issued, request.receivedAt),
40385
+ via: "pkarr",
40386
+ unconfirmed: true
40387
+ });
40388
+ const heard = this.askerHeard.get(linkId);
40389
+ if (heard) await this.contactAskerHeard(linkId, heard.frame, heard.keys);
40390
+ return linkId;
40391
+ } finally {
40392
+ this.accepting = false;
40393
+ this.askerHeard.clear();
40394
+ }
39294
40395
  }
39295
40396
  });
40397
+ /** An accept of a contact request is under way, and the last asker's proof each chat said meanwhile. */
40398
+ accepting = false;
40399
+ askerHeard = /* @__PURE__ */ new Map();
40400
+ /**
40401
+ * The contact said it asked through this profile's link (WISP 8xx § Accept). The chat's request text is confirmed
40402
+ * when the proof is the asker key's for this chat; anything else changes nothing.
40403
+ */
40404
+ async contactAskerHeard(linkId, frame, keys) {
40405
+ const live = this.links.get(linkId);
40406
+ if (!live) return;
40407
+ const expected = live.stored.contactAsker;
40408
+ if (!expected) {
40409
+ if (this.accepting) this.askerHeard.set(linkId, {
40410
+ frame,
40411
+ keys
40412
+ });
40413
+ return;
40414
+ }
40415
+ if (!contactAskerHolds(frame, expected, {
40416
+ inviter: keys.peer,
40417
+ joiner: keys.mine
40418
+ })) return;
40419
+ live.stored = {
40420
+ ...live.stored,
40421
+ contactAsker: void 0
40422
+ };
40423
+ await db.patchLink(linkId, { contactAsker: void 0 });
40424
+ if (await db.patchMessage(linkId, expected.message, (m) => m.unconfirmed ? { unconfirmed: void 0 } : null)) await this.messagesChanged(linkId, [expected.message]);
40425
+ }
40426
+ /**
40427
+ * A chat a request of this profile's started is live: its proof that this side asked goes to the contact, on each
40428
+ * session (WISP 8xx § Accept). Nothing for any other chat.
40429
+ */
40430
+ sayContactAsker(linkId) {
40431
+ const link = this.links.get(linkId)?.link;
40432
+ const keys = link?.participationKeys;
40433
+ if (!link || !keys) return;
40434
+ this.contactAsks.proof(linkId, {
40435
+ inviter: keys.mine,
40436
+ joiner: keys.peer
40437
+ }).then((frame) => {
40438
+ if (frame) link.sendContactAsker(frame);
40439
+ }).catch(() => {});
40440
+ }
39296
40441
  /** Requests this profile sends through others' contact links (WISP 8xx). */
39297
40442
  contactAsks = new ContactAsks({
39298
40443
  online: () => this.networkOn,
@@ -39322,7 +40467,7 @@ var GhostlyNode = class GhostlyNode {
39322
40467
  settings: () => this.settings.nostr,
39323
40468
  online: () => this.networkOn,
39324
40469
  emit: () => this.emitState(),
39325
- ownSubjects: () => this.identities.views().filter((p) => p.provider === "nostr").map((p) => p.subject),
40470
+ ownSubjects: () => this.identities.subjects("nostr"),
39326
40471
  contactSubjects: (linkId) => {
39327
40472
  const live = this.links.get(linkId), stored = live?.stored;
39328
40473
  if (!stored?.profile || !stored.identities) return [];
@@ -39452,7 +40597,11 @@ var GhostlyNode = class GhostlyNode {
39452
40597
  pinsHost = {
39453
40598
  messages: (chat) => db.getMessages(chat),
39454
40599
  message: (chat, id) => db.getMessage(chat, id),
39455
- rows: (chat, id) => this.rowsNamed(chat, id)
40600
+ rows: (chat, id) => this.rowsNamed(chat, id),
40601
+ unkeyed: (chat) => {
40602
+ const live = this.links.get(chat);
40603
+ return live && !live.stored.group ? this.unkeyedRowsOf(live) : void 0;
40604
+ }
39456
40605
  };
39457
40606
  reactions = new Reactions({
39458
40607
  messages: (chat) => db.getMessages(chat),
@@ -40083,10 +41232,11 @@ var GhostlyNode = class GhostlyNode {
40083
41232
  this.groupsLoaded = true;
40084
41233
  this.groupsLoadedNow();
40085
41234
  this.emitState();
40086
- for (const stored of links) {
41235
+ for (let stored of links) {
40087
41236
  if (stored.group) continue;
40088
41237
  await this.settleHistory(stored.id);
40089
41238
  const messages = await db.getMessages(stored.id);
41239
+ stored = await this.settleJoinLine(stored, messages);
40090
41240
  const storedFiles = await fileStore.listForLink(stored.id);
40091
41241
  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] : []));
40092
41242
  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" ? {
@@ -40367,6 +41517,7 @@ var GhostlyNode = class GhostlyNode {
40367
41517
  this.startGroupEntries();
40368
41518
  this.prepareSpare(STARTUP_QUIET_MS);
40369
41519
  this.did.publishNow().catch(() => {});
41520
+ this.identities.networkBack();
40370
41521
  }
40371
41522
  this.emitState();
40372
41523
  if (failure) throw failure;
@@ -42229,6 +43380,7 @@ var GhostlyNode = class GhostlyNode {
42229
43380
  ...live.stored,
42230
43381
  removedRefs: withRemovedRef(live.stored.removedRefs, edit.id)
42231
43382
  };
43383
+ this.pinRemoved(linkId, edit.id);
42232
43384
  await this.writeDeletions(linkId, { removedRefs: live.stored.removedRefs });
42233
43385
  this.emitState();
42234
43386
  }
@@ -42502,6 +43654,7 @@ var GhostlyNode = class GhostlyNode {
42502
43654
  outbox = new Outbox({
42503
43655
  read: () => db.getMessages(linkId),
42504
43656
  get: (id) => db.getMessage(linkId, id),
43657
+ getMany: (ids) => db.getMessagesById(linkId, ids),
42505
43658
  update: async (id, delivery, error, extra) => {
42506
43659
  if (delivery === "delivered") await db.patchMessage(linkId, id, (message) => message.delivery === "delivered" ? null : {
42507
43660
  ...message.delivery && {
@@ -42789,9 +43942,13 @@ var GhostlyNode = class GhostlyNode {
42789
43942
  /**
42790
43943
  * The message of mine that carries a payment or a request, read by its id: `me_<the time the desk keeps for it>`.
42791
43944
  * The chat's history is read only when that row does not carry it, so it costs the same in a long chat as in a short one.
43945
+ * A contact's request or payment is never on a message of mine: nothing is read for it (the payee says a paid request
43946
+ * is paid again at each reconnect, `PaymentDesk.replay`).
42792
43947
  */
42793
43948
  async paymentMessage(linkId, paymentId) {
42794
- const at = this.desk.payment(paymentId)?.createdAt;
43949
+ const payment = this.desk.payment(paymentId);
43950
+ if (payment?.direction === "in") return void 0;
43951
+ const at = payment?.createdAt;
42795
43952
  const message = at === void 0 ? void 0 : await db.getMessage(linkId, `me_${at}`);
42796
43953
  if (message?.sender === "me" && message.paymentId === paymentId) return message;
42797
43954
  return (await db.getMessages(linkId)).find((m) => m.sender === "me" && m.paymentId === paymentId);
@@ -42896,6 +44053,23 @@ var GhostlyNode = class GhostlyNode {
42896
44053
  });
42897
44054
  return entry.done;
42898
44055
  }
44056
+ /**
44057
+ * A 1:1 chat's message `ref` was deleted for everyone: its pin is marked so (`StoredPin.removed`), shown as unpinned
44058
+ * however many removals come after and push `ref` out of `removedRefs`. Written at once, not merged with a burst's
44059
+ * write: a newer pin taken meanwhile writes after it.
44060
+ */
44061
+ pinRemoved(linkId, ref) {
44062
+ const live = this.links.get(linkId), pin = live?.stored.pin;
44063
+ if (!live || pin?.id !== ref || pin.removed) return;
44064
+ live.stored = {
44065
+ ...live.stored,
44066
+ pin: {
44067
+ ...pin,
44068
+ removed: true
44069
+ }
44070
+ };
44071
+ db.patchLink(linkId, { pin: live.stored.pin }).catch(() => {});
44072
+ }
42899
44073
  /** Whether a 1:1 chat's wire id names a message of mine: here, deleted here, removed, or a file or payment of mine. */
42900
44074
  async namesMine(linkId, wireId) {
42901
44075
  const stored = this.links.get(linkId)?.stored, row = `me_${wireId}`;
@@ -42907,7 +44081,7 @@ var GhostlyNode = class GhostlyNode {
42907
44081
  * Forgets one message of a chat on this device, the bytes of its file and any transfer of it, and keeps its id so a
42908
44082
  * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
42909
44083
  * also of a message not here yet. `removed`: deleted for everyone (its row, when the caller read it), so the replies
42910
- * here that quote it lose its line too, and a pin of it goes (`removedRefs`).
44084
+ * here that quote it lose its line too, and a pin of it goes (`removedRefs`, and marked on the pin for good).
42911
44085
  */
42912
44086
  async forgetMessage(linkId, messageId, removed = false) {
42913
44087
  const live = this.links.get(linkId);
@@ -42918,15 +44092,24 @@ var GhostlyNode = class GhostlyNode {
42918
44092
  } : removed) : void 0;
42919
44093
  live.stored = {
42920
44094
  ...live.stored,
42921
- deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500),
44095
+ deletedIds: withDeletedId(live.stored.deletedIds, messageId),
42922
44096
  ...ref && { removedRefs: withRemovedRef(live.stored.removedRefs, ref) }
42923
44097
  };
44098
+ if (ref) this.pinRemoved(linkId, ref);
42924
44099
  this.writeDeletions(linkId, {
42925
44100
  deletedIds: live.stored.deletedIds,
42926
44101
  ...ref && { removedRefs: live.stored.removedRefs }
42927
44102
  }).catch(() => {});
42928
44103
  this.hold.forget(linkId, messageId).catch(() => {});
42929
44104
  const message = await db.getMessage(linkId, messageId);
44105
+ if (message && contactJoinRow(message) && !live.stored.group && !live.stored.peerSpoke) {
44106
+ this.contactSpoke.add(live);
44107
+ live.stored = {
44108
+ ...live.stored,
44109
+ peerSpoke: true
44110
+ };
44111
+ await db.patchLink(linkId, { peerSpoke: true }).catch(() => {});
44112
+ }
42930
44113
  if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
42931
44114
  if (message?.paymentId && message.sender === "peer") await this.desk.dropReceipt(message.paymentId).catch(() => {});
42932
44115
  if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) {
@@ -43877,6 +45060,13 @@ var GhostlyNode = class GhostlyNode {
43877
45060
  declineGroupInvitation({ groupId }) {
43878
45061
  return this.groups.decline(groupId);
43879
45062
  }
45063
+ keepGroup({ groupId }) {
45064
+ return this.groups.keepGroup(groupId);
45065
+ }
45066
+ switchGroup({ groupId, to }) {
45067
+ if (typeof to !== "string") throw new Error("No other group under this id");
45068
+ return this.groups.switchGroup(groupId, to);
45069
+ }
43880
45070
  async enableGroupLink({ groupId, reset }) {
43881
45071
  return { link: await this.groups.enableLink(groupId, reset === true) };
43882
45072
  }
@@ -44464,6 +45654,11 @@ var GhostlyNode = class GhostlyNode {
44464
45654
  }
44465
45655
  /** Ranges the contact's apps asked, by chat, app and this engine's number for the ask, until a page answers them. */
44466
45656
  appRanges = /* @__PURE__ */ new Map();
45657
+ /**
45658
+ * Asks the session no longer serves (cancelled, the contact's app closed, the session ended) that a page may still be
45659
+ * reading: its answer sends nothing, and only gives the place back. At most 4 per chat app, the places they hold.
45660
+ */
45661
+ appRangesStopped = /* @__PURE__ */ new Map();
44467
45662
  nextAppRangeAsk = 0;
44468
45663
  /**
44469
45664
  * Every task stays until a page answers it, live or not: until the link settles it, it holds one of its app's places
@@ -44473,7 +45668,11 @@ var GhostlyNode = class GhostlyNode {
44473
45668
  */
44474
45669
  appRangeAsked(linkId, task) {
44475
45670
  const link = this.links.get(linkId)?.link;
44476
- for (const [key, held] of this.appRanges) if (key.startsWith(`${linkId} `) && (!link || !link.holdsAppRange(held))) this.appRanges.delete(key);
45671
+ for (const [key, held] of this.appRanges) if (key.startsWith(`${linkId} `) && !(held.live && link?.holdsAppRange(held))) {
45672
+ this.appRanges.delete(key);
45673
+ if (link?.holdsAppRange(held)) this.appRangesStopped.set(key, held);
45674
+ }
45675
+ for (const [key, held] of this.appRangesStopped) if (key.startsWith(`${linkId} `) && !link?.holdsAppRange(held)) this.appRangesStopped.delete(key);
44477
45676
  const request = ++this.nextAppRangeAsk;
44478
45677
  this.appRanges.set(`${linkId} ${task.app} ${request}`, task);
44479
45678
  const { app, serve, file, offset, length } = task;
@@ -44508,8 +45707,9 @@ var GhostlyNode = class GhostlyNode {
44508
45707
  /** A page's answer to an `app-range` it served: the bytes and the file's size go to the contact, or why they cannot. */
44509
45708
  async appRangeAnswer({ linkId, app, request, bytes, size, error }) {
44510
45709
  if (!this.appsOn) throw this.appsOff();
44511
- const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key);
45710
+ const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key) ?? this.appRangesStopped.get(key);
44512
45711
  this.appRanges.delete(key);
45712
+ this.appRangesStopped.delete(key);
44513
45713
  if (!task) return;
44514
45714
  const serving = this.appServing.get(`${linkId} ${app}`);
44515
45715
  const stopped = serving && await this.appChatRunnable(serving.ref, serving.digest).then(() => false, () => true);
@@ -44552,11 +45752,14 @@ var GhostlyNode = class GhostlyNode {
44552
45752
  }
44553
45753
  }
44554
45754
  /** Keeps a pin of a 1:1 chat when it is newer than the chat's; `out`: mine, to say until the contact confirms it. */
44555
- async keepLinkPin(linkId, pin, out) {
45755
+ async keepLinkPin(linkId, came, out) {
44556
45756
  const live = this.links.get(linkId);
44557
- if (!live || !pinIsNewer(live.stored.pin, pin)) return;
45757
+ if (!live || !pinIsNewer(live.stored.pin, came)) return;
44558
45758
  const patch = {
44559
- pin,
45759
+ pin: came.id && live.stored.removedRefs?.includes(came.id) ? {
45760
+ ...came,
45761
+ removed: true
45762
+ } : came,
44560
45763
  ...out && { pinOut: out }
44561
45764
  };
44562
45765
  live.stored = {
@@ -44596,7 +45799,7 @@ var GhostlyNode = class GhostlyNode {
44596
45799
  */
44597
45800
  async pinnedRowCame(linkId, ids) {
44598
45801
  const live = this.links.get(linkId), pin = live?.stored.pin;
44599
- if (!live || live.stored.group || !pin?.id || pin.messageId) return;
45802
+ if (!live || live.stored.group || !pin?.id || pin.messageId || pin.removed) return;
44600
45803
  for (const id of new Set(ids)) {
44601
45804
  const row = await db.getMessage(linkId, id);
44602
45805
  if (!row || replyRef(row) !== pin.id) continue;
@@ -45864,6 +47067,7 @@ var GhostlyNode = class GhostlyNode {
45864
47067
  this.startGroupEntries();
45865
47068
  this.prepareSpare(STARTUP_QUIET_MS);
45866
47069
  this.did.publishNow().catch(() => {});
47070
+ this.identities.networkBack();
45867
47071
  if (!this.options.singleDevice && knownDeviceGate()?.state === "active") this.startDeviceSet({ justRead: true }).catch(() => {});
45868
47072
  } else if (wasOnline && this.networkOn && relayOnlyChanged) await this.restartLinksForRelayOnly();
45869
47073
  if (relayOnlyChanged && this.settings.relayOnly !== true) this.hold.wake();
@@ -47263,6 +48467,14 @@ var GhostlyNode = class GhostlyNode {
47263
48467
  await pause();
47264
48468
  }
47265
48469
  }
48470
+ /**
48471
+ * Starts a chat this run left unstarted (`NodeOptions.deferChats`): the one a one-shot names, once the command has
48472
+ * found it. Any other chat, or one already started, is left as it is.
48473
+ */
48474
+ startDeferredChat(linkId) {
48475
+ if (!this.deferredChats.delete(linkId)) return;
48476
+ if (this.networkOn && !this.shuttingDown) this.startLink(linkId);
48477
+ }
47266
48478
  startLink(linkId) {
47267
48479
  const live = this.links.get(linkId);
47268
48480
  if (!live || live.link || this.deferredChats.has(linkId)) return;
@@ -47392,6 +48604,7 @@ var GhostlyNode = class GhostlyNode {
47392
48604
  avatar: this.sharedAvatar,
47393
48605
  lastSeenTimestamp,
47394
48606
  pollIntervals: this.pollIntervals,
48607
+ ...this.options.watchPeerIdleMs ? { watchPeerIdleMs: this.options.watchPeerIdleMs } : {},
47395
48608
  autoConnect: true,
47396
48609
  createPeerConnection: () => this.chatPeer(new RTCPeerConnection(this.contactRtcConfig())),
47397
48610
  localFetch: this.localFetch,
@@ -47434,6 +48647,9 @@ var GhostlyNode = class GhostlyNode {
47434
48647
  onHold: (state) => this.hold.peerSaid(linkId, state),
47435
48648
  onPeerProof: void 0,
47436
48649
  onIdentityProof: stored.profile ? (frame) => this.identities.frame(linkId, frame) : void 0,
48650
+ onContactAsker: stored.profile ? (frame, keys) => {
48651
+ this.contactAskerHeard(linkId, frame, keys).catch(() => {});
48652
+ } : void 0,
47437
48653
  onTransportsChanged: () => {
47438
48654
  if (live.link && !live.link.availableTransports.includes("hyperdht/1")) this.retryRelayLater();
47439
48655
  this.capsChanged(linkId);
@@ -47463,10 +48679,10 @@ var GhostlyNode = class GhostlyNode {
47463
48679
  onLiveAttempt: () => this.emitState(),
47464
48680
  onRtt: (ms) => this.noteRtt(live, ms),
47465
48681
  onDiscoveryError: (error) => {
47466
- if ((error ?? void 0) !== live.discoveryError) {
47467
- live.discoveryError = error ?? void 0;
47468
- this.emitState();
47469
- }
48682
+ if ((error ?? void 0) === live.discoveryError) return;
48683
+ live.discoveryError = error ?? void 0;
48684
+ if (live.goneListener && this.contactUnread(live)) this.listenAgain(live);
48685
+ this.emitState();
47470
48686
  },
47471
48687
  onTransportDiscovery: async (peerDescriptors, peerTransports, peerFallback) => {
47472
48688
  const patch = {
@@ -47483,8 +48699,10 @@ var GhostlyNode = class GhostlyNode {
47483
48699
  },
47484
48700
  onPairingState: (state) => {
47485
48701
  live.pairing = state;
47486
- if (state.status === "ready") this.identities.ready(linkId);
47487
- else this.identities.closed(linkId);
48702
+ if (state.status === "ready") {
48703
+ this.identities.ready(linkId);
48704
+ this.sayContactAsker(linkId);
48705
+ } else this.identities.closed(linkId);
47488
48706
  if (state.status === "ready" && live.link) this.hold.rememberPeerMethods(linkId, PAYMENT_METHODS.filter((m) => live.link.peerChoosesPayment(m))).catch(() => {});
47489
48707
  live.proofs?.stop();
47490
48708
  this.observeTransport(linkId);
@@ -47551,6 +48769,7 @@ var GhostlyNode = class GhostlyNode {
47551
48769
  this.wakeLimiter.reset(linkId);
47552
48770
  this.desk.replay(linkId).catch(() => {}).then(() => this.sendWaiting(linkId)).catch(() => {});
47553
48771
  this.identities.ready(linkId);
48772
+ this.sayContactAsker(linkId);
47554
48773
  }
47555
48774
  if (state !== "open") {
47556
48775
  live.proofs?.stop();
@@ -47587,6 +48806,10 @@ var GhostlyNode = class GhostlyNode {
47587
48806
  onPresence: (presence) => {
47588
48807
  let same = samePresence(live.presence, presence);
47589
48808
  live.presence = presence;
48809
+ if (presence.online) {
48810
+ live.onlineSeenAt = Date.now();
48811
+ if (live.goneListener) this.listenAgain(live);
48812
+ }
47590
48813
  if (!stored.profile && presence.nick && presence.nick !== live.stored.peerNick) {
47591
48814
  live.stored = {
47592
48815
  ...live.stored,
@@ -47631,7 +48854,7 @@ var GhostlyNode = class GhostlyNode {
47631
48854
  if (supported) this.flushReactions(linkId);
47632
48855
  },
47633
48856
  onPin: async (pin) => {
47634
- await this.keepLinkPin(linkId, await this.pinCame(linkId, "peer", pin));
48857
+ if (pinIsNewer(this.links.get(linkId)?.stored.pin, pin)) await this.keepLinkPin(linkId, await this.pinCame(linkId, "peer", pin));
47635
48858
  return true;
47636
48859
  },
47637
48860
  onPinReceipt: (n) => this.pinReceipt(linkId, n),
@@ -47807,7 +49030,7 @@ var GhostlyNode = class GhostlyNode {
47807
49030
  nativeFactoriesFor(relayOnly) {
47808
49031
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
47809
49032
  return {
47810
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-D185dETu.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
49033
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-BxADl3SG.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
47811
49034
  ...relayOnly ? {} : this.options.nativeTransports,
47812
49035
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
47813
49036
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -47903,9 +49126,21 @@ var GhostlyNode = class GhostlyNode {
47903
49126
  if (!this.relaysHyperdht || !this.hyperdhtRelay || this.relayRetry || this.shuttingDown) return;
47904
49127
  this.relayRetry = setTimeout(() => {
47905
49128
  this.relayRetry = null;
47906
- for (const [linkId, live] of this.links) if (live.link && live.stored.profile && (!live.stored.group || this.keepsGroupNative(live.stored)) && live.stored.deliveryMode !== "dht" && !live.link.availableTransports.includes("hyperdht/1") && this.keepsNativeEndpoints(linkId, live.stored)) this.ensureNativeEndpoints(linkId);
49129
+ const held = (linkId) => this.relayHeld(linkId, Date.now());
49130
+ const ids = [...this.links.keys()].sort((a, b) => Number(held(b)) - Number(held(a)));
49131
+ for (const linkId of ids) {
49132
+ const live = this.links.get(linkId);
49133
+ if (live.link && live.stored.profile && (!live.stored.group || this.keepsGroupNative(live.stored)) && live.stored.deliveryMode !== "dht" && !live.link.availableTransports.includes("hyperdht/1") && this.keepsNativeEndpoints(linkId, live.stored)) this.ensureNativeEndpoints(linkId);
49134
+ }
47907
49135
  }, RELAY_RETRY_MS / 2 + Math.random() * RELAY_RETRY_MS);
47908
49136
  }
49137
+ /** Chats whose relayed HyperDHT listener went with the relay connection, by link id: until when they keep first claim on a slot. */
49138
+ relayHolds = /* @__PURE__ */ new Map();
49139
+ relayHeld(linkId, now) {
49140
+ const until = this.relayHolds.get(linkId);
49141
+ if (until !== void 0 && now >= until) this.relayHolds.delete(linkId);
49142
+ return until !== void 0 && now < until;
49143
+ }
47909
49144
  /** A new relay (or none): chats give up their endpoints on the old one, as soon as none of them carries a session. */
47910
49145
  async relayChanged() {
47911
49146
  if (!this.relaysHyperdht) return;
@@ -48086,7 +49321,7 @@ var GhostlyNode = class GhostlyNode {
48086
49321
  else this.groupNativeWaiting.delete(linkId);
48087
49322
  }
48088
49323
  if ((group ? this.keepsGroupNative(live.stored) : this.keepsNativeEndpoints(linkId, live.stored)) && full.includes("failed")) {
48089
- const wait = Math.min(Math.max(NATIVE_RETRY_MS, (this.nativeFailed.get(linkId)?.wait ?? 0) * 2), NATIVE_FAILED_MAX_MS);
49324
+ const wait = this.relayHeld(linkId, Date.now()) ? RELAY_HOLD_RETRY_MS : Math.min(Math.max(NATIVE_RETRY_MS, (this.nativeFailed.get(linkId)?.wait ?? 0) * 2), NATIVE_FAILED_MAX_MS);
48090
49325
  this.nativeFailed.set(linkId, {
48091
49326
  at: Date.now() + wait,
48092
49327
  wait
@@ -48168,6 +49403,10 @@ var GhostlyNode = class GhostlyNode {
48168
49403
  if (group && !this.keepsGroupNative(live.stored)) return false;
48169
49404
  if (group && !this.groupNatives(live.stored).includes(key)) return false;
48170
49405
  if (link.availableTransports.includes(key)) return false;
49406
+ if (key === GONE_TRANSPORT && !inUse && this.contactGone(live, Date.now())) {
49407
+ live.goneListener = true;
49408
+ return false;
49409
+ }
48171
49410
  live.transportErrors ??= {};
48172
49411
  try {
48173
49412
  const owners = [...this.links.values()].filter((other) => other.link?.availableTransports.includes(key));
@@ -48187,7 +49426,23 @@ var GhostlyNode = class GhostlyNode {
48187
49426
  const used = (other) => this.lastUsed(other, viewOf);
48188
49427
  const extra = (other) => !!other.stored.group && !other.stored.groupEntry && !onScreen(other) && anchorOf(other.stored.group) !== other && !this.chosenByPeer(other, key);
48189
49428
  const full = owners.length >= slots, entry = !!live.stored.groupEntry;
48190
- if (group && (entry || extra(live)) && (full || groups >= this.groupNativeSlots(key) || !entry && !anchorOf(live.stored.group)?.link?.availableTransports.includes(key))) return "no-slot";
49429
+ const claiming = key === "hyperdht/1" && this.relayHeld(linkId, now);
49430
+ const reserved = key !== "hyperdht/1" || inUse || this.activeLinkId === linkId ? 0 : [...this.relayHolds.keys()].filter((id) => {
49431
+ const other = this.links.get(id)?.link;
49432
+ return id !== linkId && this.relayHeld(id, now) && !!other && !other.availableTransports.includes(key);
49433
+ }).length;
49434
+ const free = slots - owners.length, chatFree = this.chatNativeSlots(key) - (owners.length - groups);
49435
+ if (reserved && free > 0 && (group || chatFree > 0) && (free <= reserved || !group && chatFree <= reserved)) {
49436
+ traceLink(live.myPubKeyZ32, "native-held-for-relay", {
49437
+ transport: key,
49438
+ reserved,
49439
+ group
49440
+ });
49441
+ if (group) return "no-slot";
49442
+ throw new Error("All native connection slots are in use. This chat takes one once a chat live over one has been quiet for 2 minutes. Disconnect a native connection in another chat to free one now.");
49443
+ }
49444
+ if (group && extra(live) && (full || groups >= this.groupNativeSlots(key) || !anchorOf(live.stored.group)?.link?.availableTransports.includes(key))) return "no-slot";
49445
+ if (entry && full && !owners.some((other) => extra(other) && other.link?.canReleaseEndpoint(key))) return "no-slot";
48191
49446
  if (full || !group && owners.length - groups >= this.chatNativeSlots(key)) {
48192
49447
  const paired = !group && live.pairedAt !== void 0 && now - live.pairedAt < 6e5 ? live.pairedAt : void 0;
48193
49448
  const taking = group || this.activeLinkId === linkId || inUse || paired !== void 0;
@@ -48214,6 +49469,7 @@ var GhostlyNode = class GhostlyNode {
48214
49469
  group
48215
49470
  });
48216
49471
  if (group) return "no-slot";
49472
+ if (claiming) return "failed";
48217
49473
  if (this.activeLinkId === linkId) this.retryActiveSlot(linkId);
48218
49474
  throw new Error("All native connection slots are in use. This chat takes one once a chat live over one has been quiet for 2 minutes. Disconnect a native connection in another chat to free one now.");
48219
49475
  } else {
@@ -48249,6 +49505,18 @@ var GhostlyNode = class GhostlyNode {
48249
49505
  return false;
48250
49506
  }
48251
49507
  link.registerEndpoint(endpoint);
49508
+ this.relayHolds.delete(linkId);
49509
+ if (key === "hyperdht/1" && this.relaysHyperdht) {
49510
+ const gone = endpoint.onUnavailable;
49511
+ endpoint.onUnavailable = () => {
49512
+ if (this.links.get(linkId)?.link === link) this.relayHolds.set(linkId, Date.now() + RELAY_HOLD_MS);
49513
+ gone?.();
49514
+ };
49515
+ }
49516
+ if (key === GONE_TRANSPORT && live.goneListener) {
49517
+ live.goneListener = false;
49518
+ link.knockOnReturn(key);
49519
+ }
48252
49520
  if (group) live.nativeUpAt = {
48253
49521
  ...live.nativeUpAt,
48254
49522
  [key]: Date.now()
@@ -48331,6 +49599,53 @@ var GhostlyNode = class GhostlyNode {
48331
49599
  }
48332
49600
  /** Group links waiting for a free native slot (`ensureNativeEndpoints`), by link id. */
48333
49601
  groupNativeWaiting = /* @__PURE__ */ new Set();
49602
+ /**
49603
+ * Whether a 1:1 chat's contact is gone: no packet read in this run that says it is online for `NATIVE_GONE_MS` (since
49604
+ * the chat started, before the first), and the chat neither live, nor on screen, nor used in that time (a text either
49605
+ * way, opened), nor paired in this run and not live yet. Nor while its packet cannot be read (`contactUnread`): the
49606
+ * contact may be back and only out of sight. With the Pkarr relays down, a contact back on the HyperDHT dialled a
49607
+ * listener let go here, and no read said it was online: the chat stayed offline for the whole outage, both apps up.
49608
+ */
49609
+ contactGone(live, now) {
49610
+ if (live.stored.group || live.presence.online || live.link?.isDataLinkOpen || live.pairedAt !== void 0) return false;
49611
+ if (this.contactUnread(live)) return false;
49612
+ if (live.stored.id === this.activeLinkId) return false;
49613
+ return now - Math.max(live.onlineSeenAt ?? 0, this.openedAt.get(live.stored.id) ?? 0, live.lastMessageAt) >= NATIVE_GONE_MS;
49614
+ }
49615
+ /** The last read of the contact's packet failed (the Pkarr relays out of reach), as its link says (`onDiscoveryError`). */
49616
+ contactUnread(live) {
49617
+ return !!live.discoveryError?.includes("Could not read discovery");
49618
+ }
49619
+ goneCheckAt = 0;
49620
+ /**
49621
+ * Every `NATIVE_GONE_CHECK_MS`, the 1:1 chats whose contact is gone (`contactGone`) let their HyperDHT listener go, as
49622
+ * one whose slot another chat takes does (its record then says it runs none). Not one dialling or switching
49623
+ * (`canReleaseEndpoint`).
49624
+ */
49625
+ releaseGoneListeners() {
49626
+ const now = Date.now();
49627
+ if (!this.nativeFactories[GONE_TRANSPORT] || now < this.goneCheckAt) return;
49628
+ this.goneCheckAt = now + NATIVE_GONE_CHECK_MS;
49629
+ for (const live of this.links.values()) {
49630
+ const link = live.link;
49631
+ if (!link || !link.availableTransports.includes(GONE_TRANSPORT) || !this.contactGone(live, now) || !link.canReleaseEndpoint(GONE_TRANSPORT)) continue;
49632
+ live.goneListener = true;
49633
+ traceLink(live.myPubKeyZ32, "native-gone", {
49634
+ transport: GONE_TRANSPORT,
49635
+ seen: now - (live.onlineSeenAt ?? 0)
49636
+ });
49637
+ link.releaseEndpoint(GONE_TRANSPORT).then(() => this.emitState(), () => {});
49638
+ }
49639
+ }
49640
+ /**
49641
+ * The contact of a chat whose HyperDHT listener was let go is back (`releaseGoneListeners`): it listens again (and
49642
+ * dials the contact once it does, `startNativeEndpoint`).
49643
+ */
49644
+ listenAgain(live) {
49645
+ const link = live.link;
49646
+ if (this.shuttingDown || !link || link.availableTransports.includes(GONE_TRANSPORT) || !this.keepsNativeEndpoints(live.stored.id, live.stored)) return;
49647
+ this.ensureNativeEndpoints(live.stored.id);
49648
+ }
48334
49649
  groupNativeRetryAt = 0;
48335
49650
  /** Chats and group links whose native listener failed to start, by link id: when each tries again, and how long it waited last. */
48336
49651
  nativeFailed = /* @__PURE__ */ new Map();
@@ -48343,6 +49658,7 @@ var GhostlyNode = class GhostlyNode {
48343
49658
  retryNative() {
48344
49659
  this.groupAnchorsAnswered();
48345
49660
  this.moveNative();
49661
+ this.releaseGoneListeners();
48346
49662
  const now = Date.now();
48347
49663
  for (const [linkId, failed] of this.nativeFailed) {
48348
49664
  if (now < failed.at || this.nativeRetrying.has(linkId)) continue;
@@ -48512,6 +49828,50 @@ var GhostlyNode = class GhostlyNode {
48512
49828
  await this.storeNewMessage(message);
48513
49829
  }
48514
49830
  /**
49831
+ * Whether this row is the contact's first in a 1:1 chat in the joined line's words, the only one of theirs that may be
49832
+ * drawn as that line (`StoredMessage.joinLine`). Not their first row: they say it once the chat first goes live (WISP
49833
+ * 1100), and what they wrote before that may come first. False at once for any later row in those words: the chat is
49834
+ * marked (`peerSpoke`) as the first one comes, before anything is awaited, so of two stored together only the first
49835
+ * is. A chat not marked yet is looked at once, for rows of the contact's this engine did not see come (a history
49836
+ * brought in while it runs).
49837
+ */
49838
+ firstContactRow(live, message) {
49839
+ const { stored } = live;
49840
+ if (stored.group || message.linkId !== stored.id || message.linkId.startsWith("group:") || !contactJoinRow(message)) return false;
49841
+ if (stored.peerSpoke || this.contactSpoke.has(live)) return false;
49842
+ this.contactSpoke.add(live);
49843
+ live.stored = {
49844
+ ...stored,
49845
+ peerSpoke: true
49846
+ };
49847
+ const marked = db.patchLink(stored.id, { peerSpoke: true }).catch(() => {});
49848
+ return Promise.all([contactJoinRowStored(stored.id, message.id), marked]).then(([had]) => !had, () => false);
49849
+ }
49850
+ /**
49851
+ * A chat stored before `peerSpoke` was kept, as the engine starts: the contact's oldest row left there in the joined
49852
+ * line's words is that line (as it was drawn before), and no later row of theirs is. Done once: the chat is marked.
49853
+ * One with no such row waits for it, whatever else of theirs was deleted: a deleted id does not say what its row said,
49854
+ * and one in those words deleted since `peerSpoke` was kept marked the chat as it went (`forgetMessage`).
49855
+ */
49856
+ async settleJoinLine(stored, messages) {
49857
+ if (stored.peerSpoke || stored.group) return stored;
49858
+ const at = messages.findIndex(contactJoinRow);
49859
+ if (at < 0) return stored;
49860
+ const first = messages[at];
49861
+ if (!first.joinLine) {
49862
+ await db.patchMessage(stored.id, first.id, () => ({ joinLine: true }));
49863
+ messages[at] = {
49864
+ ...first,
49865
+ joinLine: true
49866
+ };
49867
+ }
49868
+ await db.patchLink(stored.id, { peerSpoke: true });
49869
+ return {
49870
+ ...stored,
49871
+ peerSpoke: true
49872
+ };
49873
+ }
49874
+ /**
48515
49875
  * Stores a message; false when it was there already (or deleted here): nothing new came. `straight`: a group's,
48516
49876
  * straight from its author (`clockSample`). `place`: as `placed`.
48517
49877
  */
@@ -48535,7 +49895,12 @@ var GhostlyNode = class GhostlyNode {
48535
49895
  const live = this.links.get(message.linkId);
48536
49896
  if (live?.stored.deletedIds?.includes(message.id)) return false;
48537
49897
  if (message.linkId.startsWith("group:") && this.groups.isRemoved(message.linkId.slice(6), message.id)) return false;
49898
+ const first = live ? this.firstContactRow(live, message) : false;
48538
49899
  message = await this.resolveReply(message);
49900
+ if (first && isJoinNotice(message.text) && await first) message = {
49901
+ ...message,
49902
+ joinLine: true
49903
+ };
48539
49904
  if (message.sender === "peer" && live && !message.details?.received) message = {
48540
49905
  ...message,
48541
49906
  details: {
@@ -48612,7 +49977,7 @@ var GhostlyNode = class GhostlyNode {
48612
49977
  ...stored.wakeMuted && { wakeMuted: true }
48613
49978
  },
48614
49979
  ...this.reactionNotes.has(stored.id) && { lastReaction: this.reactionNotes.get(stored.id) },
48615
- ...stored.pin && { pin: pinView(stored.pin.id && stored.removedRefs?.includes(stored.pin.id) ? {
49980
+ ...stored.pin && { pin: pinView(stored.pin.id && (stored.pin.removed || stored.removedRefs?.includes(stored.pin.id)) ? {
48616
49981
  ...stored.pin,
48617
49982
  id: "",
48618
49983
  messageId: void 0
@@ -49032,4 +50397,4 @@ function signalKind(signal) {
49032
50397
  //#endregion
49033
50398
  export { EngineServer };
49034
50399
 
49035
- //# sourceMappingURL=server-Dw1o8z1o.js.map
50400
+ //# sourceMappingURL=server-BufntkX8.js.map