@ghostlytools/cli 1.11.1 → 1.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +24 -16
  2. package/dist/assets/{api-DL0Uazf6.js → api-BM3PsXbB.js} +359 -114
  3. package/dist/assets/api-BM3PsXbB.js.map +1 -0
  4. package/dist/assets/{api-D89ubgas.js → api-CtXgscmK.js} +2 -2
  5. package/dist/assets/{apiKit-D78MXTrk.js → apiKit-lCTQ0EBG.js} +17 -7
  6. package/dist/assets/apiKit-lCTQ0EBG.js.map +1 -0
  7. package/dist/assets/appFetch-BKHy5H8J.js +194 -0
  8. package/dist/assets/appFetch-BKHy5H8J.js.map +1 -0
  9. package/dist/assets/{apps-BlSl1nGn.js → apps-DO_gAZgm.js} +1 -1
  10. package/dist/assets/{apps--pAqmfgQ.js → apps-Do26w3c7.js} +44 -40
  11. package/dist/assets/apps-Do26w3c7.js.map +1 -0
  12. package/dist/assets/{arkade-DxB-MR43.js → arkade-CZrLbz-M.js} +2 -2
  13. package/dist/assets/{arkade-DxB-MR43.js.map → arkade-CZrLbz-M.js.map} +1 -1
  14. package/dist/assets/{backup-T7gFpU80.js → backup-D21x1f5P.js} +1 -1
  15. package/dist/assets/{backup-B3JJd75o.js → backup-j47AzDvG.js} +84 -33
  16. package/dist/assets/backup-j47AzDvG.js.map +1 -0
  17. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  18. package/dist/assets/{bitcoind-CZchoh43.js → bitcoind-CdSmvy2y.js} +3 -3
  19. package/dist/assets/{bitcoind-CZchoh43.js.map → bitcoind-CdSmvy2y.js.map} +1 -1
  20. package/dist/assets/{bitcoindProvider-DGw3xBSa.js → bitcoindProvider-BvoRh0D5.js} +2 -2
  21. package/dist/assets/{bitcoindProvider-DGw3xBSa.js.map → bitcoindProvider-BvoRh0D5.js.map} +1 -1
  22. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  23. package/dist/assets/{buttons-C1VbDihe.js → buttons-CiGlBVBT.js} +18 -7
  24. package/dist/assets/buttons-CiGlBVBT.js.map +1 -0
  25. package/dist/assets/buttons-D2l2bVCG.js +2 -0
  26. package/dist/assets/{childEnv-BVOQK9EA.js → childEnv-K_IzUqQx.js} +4 -3
  27. package/dist/assets/childEnv-K_IzUqQx.js.map +1 -0
  28. package/dist/assets/{client-CGLuWFRV.js → client-raIncVtF.js} +31 -3
  29. package/dist/assets/client-raIncVtF.js.map +1 -0
  30. package/dist/assets/{codec-YGJDr7uH.js → codec-DcG2AeyE.js} +2 -2
  31. package/dist/assets/{codec-YGJDr7uH.js.map → codec-DcG2AeyE.js.map} +1 -1
  32. package/dist/assets/endpoint-DarqblYE.js +5052 -0
  33. package/dist/assets/endpoint-DarqblYE.js.map +1 -0
  34. package/dist/assets/{envelope-Dwq8EN8x.js → envelope-Dud6lntA.js} +2 -2
  35. package/dist/assets/{envelope-Dwq8EN8x.js.map → envelope-Dud6lntA.js.map} +1 -1
  36. package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-DRKRSw14.js} +6 -3
  37. package/dist/assets/fedimintSdk-DRKRSw14.js.map +1 -0
  38. package/dist/assets/{fixedHosts-CINXidpd.js → fixedHosts-CNX7QiUD.js} +3 -3
  39. package/dist/assets/{fixedHosts-CINXidpd.js.map → fixedHosts-CNX7QiUD.js.map} +1 -1
  40. package/dist/assets/{host-CGlHkiQv.js → host-8RskzQgB.js} +306 -84
  41. package/dist/assets/host-8RskzQgB.js.map +1 -0
  42. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js → hyperdhtRelay-uAThbFub.js} +2 -2
  43. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js.map → hyperdhtRelay-uAThbFub.js.map} +1 -1
  44. package/dist/assets/{irohWeb-CYn0uB_A.js → irohWeb-DGelfgDJ.js} +693 -38
  45. package/dist/assets/irohWeb-DGelfgDJ.js.map +1 -0
  46. package/dist/assets/jsonOut-POtMBS_V.js +16 -0
  47. package/dist/assets/jsonOut-POtMBS_V.js.map +1 -0
  48. package/dist/assets/{main-CgLW_Gyx.js → main-BC33ooYg.js} +175 -107
  49. package/dist/assets/main-BC33ooYg.js.map +1 -0
  50. package/dist/assets/{mainline-B0h8RchD.js → mainline-DYrjsS1t.js} +27 -8
  51. package/dist/assets/mainline-DYrjsS1t.js.map +1 -0
  52. package/dist/assets/{networkReason-BBosp2KG.js → networkReason-n2oBs4by.js} +3 -3
  53. package/dist/assets/{networkReason-BBosp2KG.js.map → networkReason-n2oBs4by.js.map} +1 -1
  54. package/dist/assets/{nwc-SSNS1aJ-.js → nwc-Do3VSlIS.js} +6 -5
  55. package/dist/assets/nwc-Do3VSlIS.js.map +1 -0
  56. package/dist/assets/{nwcProvider-BXqJmM98.js → nwcProvider-Du5aWNIn.js} +6 -3
  57. package/dist/assets/{nwcProvider-BXqJmM98.js.map → nwcProvider-Du5aWNIn.js.map} +1 -1
  58. package/dist/assets/{ownDid--DtH_Jdi.js → ownDid-CwwYu8s2.js} +3 -3
  59. package/dist/assets/{ownDid--DtH_Jdi.js.map → ownDid-CwwYu8s2.js.map} +1 -1
  60. package/dist/assets/{ownStatus-CQPGjCUR.js → ownStatus-D7dB4zJB.js} +4 -3
  61. package/dist/assets/{ownStatus-CQPGjCUR.js.map → ownStatus-D7dB4zJB.js.map} +1 -1
  62. package/dist/assets/{profiles-4UQ1Hsds.js → profiles-NyF5FnYF.js} +82 -6
  63. package/dist/assets/profiles-NyF5FnYF.js.map +1 -0
  64. package/dist/assets/{registry-B6BXKv6Q.js → registry-C734VrO9.js} +1 -1
  65. package/dist/assets/{registry-BKCFTEYp.js → registry-DKDInr0A.js} +75 -23
  66. package/dist/assets/registry-DKDInr0A.js.map +1 -0
  67. package/dist/assets/{resolve-MFeFljsN.js → resolve-3Tqh9AWQ.js} +4 -3
  68. package/dist/assets/resolve-3Tqh9AWQ.js.map +1 -0
  69. package/dist/assets/{server-rHKhnog1.js → server-B6PQ6iae.js} +401 -852
  70. package/dist/assets/server-B6PQ6iae.js.map +1 -0
  71. package/dist/assets/{src-BzsyAvPf.js → src-ChJijTlM.js} +395 -129
  72. package/dist/assets/src-ChJijTlM.js.map +1 -0
  73. package/dist/assets/{sshForges-qITn-RoV.js → sshForges-Brf0fslM.js} +2 -2
  74. package/dist/assets/{sshForges-qITn-RoV.js.map → sshForges-Brf0fslM.js.map} +1 -1
  75. package/dist/assets/{translate-Bkr_iDgp.js → translate-xLme9Rdh.js} +3 -3
  76. package/dist/assets/{translate-Bkr_iDgp.js.map → translate-xLme9Rdh.js.map} +1 -1
  77. package/dist/assets/{types-C4_KafL_.js → types-Clyb52K2.js} +2 -1
  78. package/dist/assets/types-Clyb52K2.js.map +1 -0
  79. package/dist/assets/{usdt-Bp7T2iqt.js → usdt-CSU5KzTV.js} +3 -3
  80. package/dist/assets/{usdt-Bp7T2iqt.js.map → usdt-CSU5KzTV.js.map} +1 -1
  81. package/dist/ghostly.mjs +1 -1
  82. package/npm-shrinkwrap.json +3592 -0
  83. package/package.json +5 -3
  84. package/dist/assets/api-DL0Uazf6.js.map +0 -1
  85. package/dist/assets/apiKit-D78MXTrk.js.map +0 -1
  86. package/dist/assets/apps--pAqmfgQ.js.map +0 -1
  87. package/dist/assets/backup-B3JJd75o.js.map +0 -1
  88. package/dist/assets/buttons-C1VbDihe.js.map +0 -1
  89. package/dist/assets/buttons-DwWuK_uN.js +0 -2
  90. package/dist/assets/childEnv-BVOQK9EA.js.map +0 -1
  91. package/dist/assets/client-CGLuWFRV.js.map +0 -1
  92. package/dist/assets/endpoint-DWHkXWVM.js +0 -419
  93. package/dist/assets/endpoint-DWHkXWVM.js.map +0 -1
  94. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +0 -1
  95. package/dist/assets/host-CGlHkiQv.js.map +0 -1
  96. package/dist/assets/irohWeb-CYn0uB_A.js.map +0 -1
  97. package/dist/assets/main-CgLW_Gyx.js.map +0 -1
  98. package/dist/assets/mainline-B0h8RchD.js.map +0 -1
  99. package/dist/assets/nwc-SSNS1aJ-.js.map +0 -1
  100. package/dist/assets/profiles-4UQ1Hsds.js.map +0 -1
  101. package/dist/assets/registry-BKCFTEYp.js.map +0 -1
  102. package/dist/assets/resolve-MFeFljsN.js.map +0 -1
  103. package/dist/assets/server-rHKhnog1.js.map +0 -1
  104. package/dist/assets/src-BzsyAvPf.js.map +0 -1
  105. package/dist/assets/types-C4_KafL_.js.map +0 -1
@@ -1,22 +1,22 @@
1
- import { Ba as PLAYABLE_AUDIO, Bo as MESSAGE_CLOCK_SKEW_MS, Di as APP_DATA_MAX_BYTES, Gu as relayUrlProblem, Ha as VOICE_METER, Hn as withoutVideoMetadata, Ho as claimedTime, Io as checkStatusCard, Ja as voiceLevel, Ka as parseVoiceMeta, Kl as readImageMeta, Kn as stripPictureMetadata, Ml as appRef, Mo as appCardUrl, Po as cardLine, Ra as sanitizeFileName, Rl as isAppRef, Ro as statusCardBytes, Ua as baseMime, Un as NO_PICTURE_METADATA, Va as VOICE_LIMITS, Wa as downsamplePeaks, Wu as normalizeRelayUrl, Yi as identityStatement, _d as randomBytes$1, _s as parseLocalTarget, ar as GROUP_FILE_LIMITS, bo as replySnippet, cu as ownInviteRefusal, hs as GhostlyHttpError, ii as sanitizeTypingStatus, jo as appCardId, ko as STATUS_CARD_LIMITS, ld as MAX_AVATAR_LENGTH, ni as TYPING_REFRESH_MS, ou as inviteLink, qa as voiceDownloadName, qn as withoutPictureMetadata, ss as AWAITING_PEER_MS, ti as TYPING_KINDS, ud as sanitizeAvatar, vd as toBase64Url, wl as isAppUrl, yl as APP_PERMISSIONS, ys as LIMITS, za as sanitizeMime, zn as withoutAudioMetadata } from "./src-BzsyAvPf.js";
1
+ import { Ao as STATUS_CARD_LIMITS, Ba as sanitizeMime, Bn as withoutAudioMetadata, Fo as cardLine, Ga as downsamplePeaks, Gu as normalizeRelayUrl, Ha as VOICE_LIMITS, Ja as voiceDownloadName, Jn as withoutPictureMetadata, Ku as relayUrlProblem, Lo as checkStatusCard, Mo as appCardId, Nl as appRef, No as appCardUrl, Oi as APP_DATA_MAX_BYTES, Tl as isAppUrl, Ua as VOICE_METER, Un as withoutVideoMetadata, Uo as claimedTime, Va as PLAYABLE_AUDIO, Vo as MESSAGE_CLOCK_SKEW_MS, Wa as baseMime, Wn as NO_PICTURE_METADATA, Xi as identityStatement, Ya as voiceLevel, ai as sanitizeTypingStatus, bd as toBase64Url, bl as APP_PERMISSIONS, bs as LIMITS, cs as AWAITING_PEER_MS, dd as sanitizeAvatar, gs as GhostlyHttpError, lu as ownInviteRefusal, ni as TYPING_KINDS, or as GROUP_FILE_LIMITS, qa as parseVoiceMeta, ql as readImageMeta, qn as stripPictureMetadata, ri as TYPING_REFRESH_MS, su as inviteLink, ud as MAX_AVATAR_LENGTH, vs as parseLocalTarget, xo as replySnippet, yd as randomBytes$1, za as sanitizeFileName, zl as isAppRef, zo as statusCardBytes } from "./src-ChJijTlM.js";
2
2
  import { p as fileStore } from "./idb-CEuoNsTv.js";
3
3
  import { f as FILE_BYTES_STEP, o as fileBytes, s as fileBytesOf } from "./fileBytes-BLPZq9YU.js";
4
- import { $ as iceServerProblem, M as waitingGroupFile, N as IDENTITY_DRAFT_TTL_MS, S as paymentNetwork, c as groupOfFile, et as iceServerSetting, k as removeStored, o as groupFileId, p as replyRef, t as DEFAULT_IROH_RELAYS } from "./irohWeb-CYn0uB_A.js";
5
- import { t as IDENTITY_PROVIDERS } from "./registry-BKCFTEYp.js";
4
+ import { B as removeStored, U as waitingGroupFile, W as IDENTITY_DRAFT_TTL_MS, a as groupMemberOfLink, b as replyRef, c as groupPayTwin, ft as iceServerProblem, h as groupOfFile, k as paymentNetwork, o as groupPayLineId, p as groupFileId, pt as iceServerSetting, s as groupPayNoteId, t as DEFAULT_IROH_RELAYS } from "./irohWeb-DGelfgDJ.js";
5
+ import { t as IDENTITY_PROVIDERS } from "./registry-DKDInr0A.js";
6
6
  import { n as secretWords, r as findSecret, t as guardText } from "./secretGuard-B7Hj0Kvz.js";
7
7
  import { i as localFileError, r as asCliError, t as CliError } from "./errors-Dt-ZnyOX.js";
8
- import { a as PAY_METHODS, d as ENGINE_METHODS, f as ENGINE_PARAMS, g as engineParamsProblem, i as CHAT_METHODS, l as withStoredIds, m as READ_PARAMS, n as statusJson, o as TRANSPORT_NAMES, p as ENGINE_READS, r as ADDRESS_TYPES, s as WALLET_TYPES, t as checkOwnStatus, u as DESTRUCTIVE_CALLS } from "./ownStatus-CQPGjCUR.js";
9
- import { A as sinceSeq, D as oneShotWaits, E as oneOf, F as transportOffered, I as waitForState, N as state, O as sentAt, P as str, S as nobodyJoined, T as num, _ as messageOf, b as noFile, c as findChatOrGroup, d as groupNameOf, f as groupOf, g as list, h as keptForJoin, i as chatOrGroup, j as somebodyJoined, k as shownName, l as findGroup, m as inviteTaken, n as bool, o as dhtOnly, p as groupPrefixed, r as chatOf, s as findChat, u as findOwnNamedChat, w as node, x as noMessage } from "./apiKit-D78MXTrk.js";
10
- import { t as childEnv } from "./childEnv-BVOQK9EA.js";
8
+ import { a as PAY_METHODS, d as ENGINE_METHODS, f as ENGINE_PARAMS, g as engineParamsProblem, i as CHAT_METHODS, l as withStoredIds, m as READ_PARAMS, n as statusJson, o as TRANSPORT_NAMES, p as ENGINE_READS, r as ADDRESS_TYPES, s as WALLET_TYPES, t as checkOwnStatus, u as DESTRUCTIVE_CALLS } from "./ownStatus-D7dB4zJB.js";
9
+ import { A as sinceSeq, D as oneShotWaits, E as oneOf, F as transportOffered, I as waitForState, N as state, O as sentAt, P as str, S as nobodyJoined, T as num, _ as messageOf, a as contactKeyOf, b as noFile, c as findChatOrGroup, d as groupNameOf, f as groupOf, g as list, h as keptForJoin, j as somebodyJoined, k as shownName, l as findGroup, m as inviteTaken, n as chatOf, o as dhtOnly, p as groupPrefixed, r as chatOrGroup, s as findChat, t as bool, u as findOwnNamedChat, w as node, x as noMessage } from "./apiKit-lCTQ0EBG.js";
10
+ import { t as childEnv } from "./childEnv-K_IzUqQx.js";
11
11
  import { t as chatState } from "./waitNotice-Cn0WJ-He.js";
12
- import { a as goesOn, c as waitForGroupFrame, i as pressable, l as waitForMessage, n as buttonsCard, o as waitForConfirmed, s as waitForEdit, t as BUTTON_METHODS, u as waitForRemoval } from "./buttons-C1VbDihe.js";
13
- import { a as checkShownName } from "./profiles-4UQ1Hsds.js";
14
- import { t as BACKUP_METHODS } from "./backup-B3JJd75o.js";
15
- import { o as checkedBundle } from "./apps--pAqmfgQ.js";
12
+ import { a as goesOn, c as waitForEdit, d as waitForRemoval, i as pressable, l as waitForGroupFrame, n as buttonsCard, o as nobodyElseIn, s as waitForConfirmed, t as BUTTON_METHODS, u as waitForMessage } from "./buttons-CiGlBVBT.js";
13
+ import { a as checkShownName } from "./profiles-NyF5FnYF.js";
14
+ import { t as BACKUP_METHODS } from "./backup-j47AzDvG.js";
15
+ import { o as checkedBundle } from "./apps-Do26w3c7.js";
16
16
  import { generateMnemonic } from "@scure/bip39";
17
17
  import { wordlist } from "@scure/bip39/wordlists/english.js";
18
18
  import { execFile, spawn } from "node:child_process";
19
- import { openAsBlob, readFileSync, renameSync, writeFileSync } from "node:fs";
19
+ import { openAsBlob, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
20
20
  import { access, constants as constants$1, copyFile, link, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
21
21
  import { basename, dirname, extname, join, resolve, sep } from "node:path";
22
22
  import { randomBytes, timingSafeEqual } from "node:crypto";
@@ -373,6 +373,12 @@ function pushWavFrames(view, from, to, channels, width, read, sink) {
373
373
  more: true
374
374
  };
375
375
  }
376
+ /**
377
+ * Opus packets a demuxer keeps: as many as the longest voice note read past its limit can have, at 2.5 ms (Opus's
378
+ * shortest packet) each. Past it a file is longer than a voice note anyway. Before, a 1 MB WebM of blocks each lacing
379
+ * 256 empty frames held ~8 KB of heap per byte read, and took the daemon down out of memory.
380
+ */
381
+ var MAX_OPUS_PACKETS = Math.ceil((VOICE_LIMITS.maxDurationMs + PAST_LIMIT_MS) / 2.5);
376
382
  /** A variable-length number in EBML: its length in bytes and value (the marker bit kept for ids, dropped for sizes). */
377
383
  function vint(bytes, at, keepMarker) {
378
384
  const first = bytes[at];
@@ -408,7 +414,7 @@ function demuxWebm(bytes) {
408
414
  const tracks = [];
409
415
  const blocks = [];
410
416
  let at = 0;
411
- while (at < bytes.length) {
417
+ while (at < bytes.length && blocks.length < MAX_OPUS_PACKETS) {
412
418
  const id = vint(bytes, at, true);
413
419
  if (!id) break;
414
420
  const size = vint(bytes, at + id.length, false);
@@ -434,7 +440,7 @@ function demuxWebm(bytes) {
434
440
  else if (id.value === 159 && track) track.channels = uint(data);
435
441
  else if (id.value === 163 || id.value === 161) {
436
442
  const number = vint(data, 0, false);
437
- if (number) for (const frame of laced(data, number.length)) blocks.push({
443
+ if (number) for (const frame of laced(data, number.length).slice(0, MAX_OPUS_PACKETS - blocks.length)) blocks.push({
438
444
  track: number.value,
439
445
  data: frame
440
446
  });
@@ -497,7 +503,7 @@ function demuxOgg(bytes) {
497
503
  let packet = [];
498
504
  let endGranule;
499
505
  let at = 0;
500
- while (at + 27 <= bytes.length && ascii(bytes, at, 4) === "OggS") {
506
+ while (at + 27 <= bytes.length && ascii(bytes, at, 4) === "OggS" && frames.length < MAX_OPUS_PACKETS) {
501
507
  const segments = bytes[at + 26];
502
508
  const table = bytes.subarray(at + 27, at + 27 + segments);
503
509
  let pos = at + 27 + segments;
@@ -507,6 +513,7 @@ function demuxOgg(bytes) {
507
513
  serial = pageSerial;
508
514
  if (granule >= 0) endGranule = granule;
509
515
  for (const size of table) {
516
+ if (frames.length >= MAX_OPUS_PACKETS) break;
510
517
  packet.push(bytes.subarray(pos, pos + size));
511
518
  pos += size;
512
519
  if (size < 255) {
@@ -1864,6 +1871,37 @@ function writeHolds(ctx, holds) {
1864
1871
  writeFileSync(file + ".tmp", JSON.stringify(holds) + "\n", { mode: 384 });
1865
1872
  renameSync(file + ".tmp", file);
1866
1873
  }
1874
+ /**
1875
+ * Changes one chat's entry: the file is read again right here and written back in the same step, with no wait in
1876
+ * between, so what another chat's hold, expiry or release wrote meanwhile stays. Each call read the file before its
1877
+ * engine call and wrote that copy back after it: two holds at once on a daemon (which serves its connections at once)
1878
+ * kept only one, and the other chat stayed on DHT only for good; an expiry meanwhile brought an ended hold back.
1879
+ * Only one process writes the file: a command goes through the profile's daemon when one runs, and otherwise holds
1880
+ * the profile itself.
1881
+ */
1882
+ function editHold(ctx, linkId, hold) {
1883
+ const holds = readHolds(ctx);
1884
+ if (hold) holds[linkId] = hold;
1885
+ else if (holds[linkId]) delete holds[linkId];
1886
+ else return;
1887
+ writeHolds(ctx, holds);
1888
+ }
1889
+ /** Per profile folder and chat, the last change to its hold under way: changes to one chat's hold go one after another. */
1890
+ var queues = /* @__PURE__ */ new Map();
1891
+ /**
1892
+ * Runs `task` once the changes to this chat's hold started before it are done (failed or not). A hold and an expiry,
1893
+ * a release or a removal of the same chat no longer run into each other; other chats' run meanwhile.
1894
+ */
1895
+ function inTurn(ctx, linkId, task) {
1896
+ const key = `${ctx.runtime.paths.dir}\0${linkId}`;
1897
+ const run = (queues.get(key) ?? Promise.resolve()).then(task, task);
1898
+ const settled = run.then(() => {}, () => {});
1899
+ queues.set(key, settled);
1900
+ settled.then(() => {
1901
+ if (queues.get(key) === settled) queues.delete(key);
1902
+ });
1903
+ return run;
1904
+ }
1867
1905
  function timersOf(ctx) {
1868
1906
  let map = timers.get(ctx);
1869
1907
  if (!map) timers.set(ctx, map = /* @__PURE__ */ new Map());
@@ -1912,56 +1950,78 @@ function holdOf(ctx, linkId) {
1912
1950
  return until !== void 0 && until > Date.now() ? until : null;
1913
1951
  }
1914
1952
  /** Keeps the chat off its direct link for `minutes` (again: from now). */
1915
- async function holdChat(ctx, link, minutes) {
1916
- const holds = readHolds(ctx);
1917
- if (link.deliveryMode === "dht" && !holds[link.id]) throw new CliError("refused", "This chat is on DHT only already, by its own choice: chat transport auto leaves it");
1918
- if (!link.profile) throw new CliError("unavailable", "A chat of the older protocol has no DHT only");
1919
- const until = Date.now() + minutes * 6e4;
1920
- if (link.deliveryMode !== "dht") try {
1921
- await node(ctx).setChatTransport({
1922
- linkId: link.id,
1923
- transport: "dht"
1953
+ function holdChat(ctx, link, minutes) {
1954
+ return inTurn(ctx, link.id, async () => {
1955
+ const now = state(ctx).links.find((l) => l.id === link.id) ?? link;
1956
+ const held = readHolds(ctx)[link.id];
1957
+ if (now.deliveryMode === "dht" && !held) throw new CliError("refused", "This chat is on DHT only already, by its own choice: chat transport auto leaves it");
1958
+ if (!now.profile) throw new CliError("unavailable", "A chat of the older protocol has no DHT only");
1959
+ const until = Date.now() + minutes * 6e4;
1960
+ editHold(ctx, link.id, {
1961
+ until,
1962
+ since: held?.since ?? Date.now()
1924
1963
  });
1925
- } catch (error) {
1926
- throw new CliError("unavailable", error instanceof Error ? error.message : String(error));
1927
- }
1928
- holds[link.id] = {
1929
- until,
1930
- since: holds[link.id]?.since ?? Date.now()
1931
- };
1932
- writeHolds(ctx, holds);
1933
- schedule(ctx, link.id, until);
1934
- ctx.hub.emit("chat.held", `chat.held:${link.id}:${until}`, {
1935
- chat: link.id,
1936
- until
1964
+ if (now.deliveryMode !== "dht") try {
1965
+ await node(ctx).setChatTransport({
1966
+ linkId: link.id,
1967
+ transport: "dht"
1968
+ });
1969
+ } catch (error) {
1970
+ editHold(ctx, link.id, held ?? null);
1971
+ throw new CliError("unavailable", error instanceof Error ? error.message : String(error));
1972
+ }
1973
+ schedule(ctx, link.id, until);
1974
+ ctx.hub.emit("chat.held", `chat.held:${link.id}:${until}`, {
1975
+ chat: link.id,
1976
+ until
1977
+ });
1978
+ return until;
1937
1979
  });
1938
- return until;
1939
1980
  }
1940
1981
  /**
1941
1982
  * Ends a hold: the chat leaves DHT only, unless someone chose otherwise meanwhile. Whether there was one. `reason`:
1942
1983
  * expired, connect (`chat connect`) or lifted (`--hold 0`, or `chat transport`: `chosen`, the chat's transport was
1943
1984
  * just chosen, and stays as chosen).
1944
1985
  */
1945
- async function releaseHold(ctx, linkId, reason, chosen = false) {
1946
- const holds = readHolds(ctx);
1947
- if (!holds[linkId]) return false;
1948
- stopWait(ctx, linkId);
1949
- const link = state(ctx).links.find((l) => l.id === linkId);
1950
- if (!chosen && link?.deliveryMode === "dht") await node(ctx).setDeliveryMode({
1951
- linkId,
1952
- mode: "stream"
1986
+ function releaseHold(ctx, linkId, reason, chosen = false) {
1987
+ return inTurn(ctx, linkId, async () => {
1988
+ if (!readHolds(ctx)[linkId]) return false;
1989
+ stopWait(ctx, linkId);
1990
+ const link = state(ctx).links.find((l) => l.id === linkId);
1991
+ if (!chosen && link?.deliveryMode === "dht") await node(ctx).setDeliveryMode({
1992
+ linkId,
1993
+ mode: "stream"
1994
+ });
1995
+ editHold(ctx, linkId, null);
1996
+ ctx.hub.emit("chat.released", `chat.released:${linkId}:${Date.now()}`, {
1997
+ chat: linkId,
1998
+ reason
1999
+ });
2000
+ return true;
1953
2001
  });
1954
- delete holds[linkId];
1955
- writeHolds(ctx, holds);
1956
- ctx.hub.emit("chat.released", `chat.released:${linkId}:${Date.now()}`, {
1957
- chat: linkId,
1958
- reason
2002
+ }
2003
+ /**
2004
+ * A removed chat's hold goes with it, with no release said: it stayed in the folder until its time was up (and in a
2005
+ * backup made meanwhile), a chat joined again from the same invite showed its `heldUntil`, and its end said
2006
+ * `chat.released` for a chat that was gone.
2007
+ */
2008
+ function forgetHold(ctx, linkId) {
2009
+ return inTurn(ctx, linkId, async () => {
2010
+ stopWait(ctx, linkId);
2011
+ editHold(ctx, linkId, null);
1959
2012
  });
1960
- return true;
1961
2013
  }
1962
- /** At start: holds whose time is up end now, the others are timed again. */
2014
+ /**
2015
+ * At start: holds whose time is up end now, the others are timed again. A hold whose chat the store does not have is
2016
+ * dropped, with no release said: a profile restored from a backup taken while that chat was removed (the backup reads
2017
+ * holds.json before and after its store) had it, and its end said `chat.released` for a chat it never had.
2018
+ */
1963
2019
  function resumeHolds(ctx) {
1964
- for (const [linkId, hold] of Object.entries(readHolds(ctx))) schedule(ctx, linkId, hold.until);
2020
+ const chats = new Set(state(ctx).links.map((link) => link.id));
2021
+ const holds = readHolds(ctx), gone = Object.keys(holds).filter((linkId) => !chats.has(linkId));
2022
+ for (const linkId of gone) delete holds[linkId];
2023
+ if (gone.length) writeHolds(ctx, holds);
2024
+ for (const [linkId, hold] of Object.entries(holds)) schedule(ctx, linkId, hold.until);
1965
2025
  }
1966
2026
  //#endregion
1967
2027
  //#region src/views.ts
@@ -2058,6 +2118,23 @@ function chatDetailsJson(link, showSecret) {
2058
2118
  pin: pinJson(link.pin)
2059
2119
  };
2060
2120
  }
2121
+ function groupPayJson(note) {
2122
+ const by = note.from === "*" && note.rail === "lightning" ? null : note.by ?? null;
2123
+ return {
2124
+ id: note.id,
2125
+ kind: note.kind,
2126
+ from: note.from,
2127
+ to: note.to,
2128
+ by,
2129
+ claims: [...note.claims ?? []],
2130
+ amount: note.amount,
2131
+ decimals: note.decimals,
2132
+ unit: note.unit,
2133
+ rail: note.rail,
2134
+ state: note.state,
2135
+ test: !!note.test
2136
+ };
2137
+ }
2061
2138
  function messageJson(message) {
2062
2139
  return {
2063
2140
  id: message.id,
@@ -2101,7 +2178,8 @@ function messageJson(message) {
2101
2178
  button: message.press.button,
2102
2179
  label: message.press.label,
2103
2180
  ...message.press.inferred ? { inferred: true } : {}
2104
- } } : {}
2181
+ } } : {},
2182
+ ...message.groupPay ? { groupPay: groupPayJson(message.groupPay) } : {}
2105
2183
  };
2106
2184
  }
2107
2185
  /**
@@ -2151,9 +2229,13 @@ function chatMessageJson(message, link) {
2151
2229
  * name rides on the edge or the roster), so the roster fills `nick` when the message has none, and for an author no
2152
2230
  * longer in it (removed, or back with a new member key) the name the group knew them by. A group's own line written
2153
2231
  * before that name came ("Member a4w9nb5y joined") says it, as the app draws it; before, it kept the key for good.
2232
+ * `twinOf`: the line of the payment note this message is the twin of (`groupPayTwins`).
2154
2233
  */
2155
- function groupMessageJson(message, group) {
2156
- const json = messageJson(message);
2234
+ function groupMessageJson(message, group, twinOf) {
2235
+ const json = twinOf ? {
2236
+ ...messageJson(message),
2237
+ twinOf
2238
+ } : messageJson(message);
2157
2239
  if (!message.member) return json;
2158
2240
  const nick = json.nick ?? group?.members.find((m) => m.key === message.member)?.nick ?? group?.formerNames?.[message.member];
2159
2241
  if (!nick) return json;
@@ -2166,6 +2248,20 @@ function groupMessageJson(message, group) {
2166
2248
  };
2167
2249
  }
2168
2250
  /**
2251
+ * Which payment lines of a group's history are twins of a payment note's line, by message id, as the app's group page
2252
+ * tells them (`groupPayTwin`): the requester's own request, the request as it came over the edge, a payment answering
2253
+ * it. Only for a note whose line is in `notes` (the group's, by note id): a twin of nothing is no twin.
2254
+ */
2255
+ function groupPayTwins(messages, notes, payments, group) {
2256
+ const twins = /* @__PURE__ */ new Map();
2257
+ for (const m of messages) {
2258
+ if (!m.paymentId || m.groupPay) continue;
2259
+ const note = groupPayTwin(m, payments[m.paymentId], (id) => notes.get(id), group?.myKey, (linkId) => groupMemberOfLink(group, linkId));
2260
+ if (note && notes.has(note)) twins.set(m.id, groupPayLineId(note));
2261
+ }
2262
+ return twins;
2263
+ }
2264
+ /**
2169
2265
  * A group as the CLI prints it. The entry link lets anyone who reads it join, so it is `<hidden>` unless asked for
2170
2266
  * (`--show-secret`, or `group link`); null when the group has none.
2171
2267
  */
@@ -2217,14 +2313,28 @@ function groupJson(group, showSecret = false) {
2217
2313
  /**
2218
2314
  * A member by key, unique key prefix or name; never this profile itself (`myName`: its name, which its own row lacks).
2219
2315
  * A whole key is that member, whatever another member calls itself; a prefix and a name stand side by side (two
2220
- * members is an error, not a guess).
2316
+ * members is an error, not a guess). For a grant (`byKeyOnly`: admin, a pinned hub) a member found only by the name it
2317
+ * gave itself is refused, with its key: another member could call itself that name while the one meant is away, as
2318
+ * `findOwnNamedChat` refuses a contact's own name.
2221
2319
  */
2222
- function findMember(group, ref, myName) {
2320
+ function findMember(group, ref, myName, byKeyOnly = false) {
2223
2321
  const lower = ref.toLowerCase();
2322
+ const asKey = contactKeyOf(ref);
2323
+ if (asKey !== void 0) {
2324
+ const member = group.members.find((m) => !m.me && m.key === asKey);
2325
+ if (member) return member;
2326
+ throw noMember(group, asKey, myName);
2327
+ }
2224
2328
  const others = group.members.filter((m) => !m.me);
2225
2329
  const byKey = others.filter((m) => m.key === ref);
2226
2330
  const matches = byKey.length ? byKey : others.filter((m) => m.key.startsWith(ref) || m.nick?.trim().toLowerCase() === lower);
2227
- if (matches.length === 1) return matches[0];
2331
+ if (matches.length === 1) {
2332
+ if (byKeyOnly && !matches[0].key.startsWith(ref)) throw new CliError("bad_request", `${JSON.stringify(ref)} names a member only by the name it gave itself: use its key`, {
2333
+ member: matches[0].key,
2334
+ name: matches[0].nick ?? null
2335
+ });
2336
+ return matches[0];
2337
+ }
2228
2338
  throw matches.length ? new CliError("bad_request", `${JSON.stringify(ref)} names more than one member`) : noMember(group, ref, myName);
2229
2339
  }
2230
2340
  /**
@@ -2266,12 +2376,23 @@ async function picture(params) {
2266
2376
  if (bool(params, "clear")) return null;
2267
2377
  return pictureFrom(str(params, "path", true));
2268
2378
  }
2269
- /** The member `params.member` names in `group`, this profile's own name said to be it. */
2270
- var member = (ctx, group, params) => findMember(group, str(params, "member", true), state(ctx).settings.nick);
2379
+ /**
2380
+ * A group this profile administers or is in, not only an invitation: before, the engine answered `group rename`,
2381
+ * `picture`, `link`, `rotate` and `invite` on an invitation not yet joined with "Group not found" (engine, exit 1),
2382
+ * while `group show` listed it, and `remove`/`admin` said "No member" of a member list it had not received yet.
2383
+ */
2384
+ function joined(ctx, params, twin) {
2385
+ const group = groupOf(ctx, params, twin);
2386
+ if (group.status || !group.invitation) return group;
2387
+ const ref = str(params, "group", true), shown = /^[\w.:-]+$/.test(ref) ? ref : JSON.stringify(ref);
2388
+ throw new CliError("refused", group.invitation.accepted ? `You are not in ${group.name} yet: you accepted its invitation, and its admin has not let you in` : `You are not in ${group.name} yet: ghostly group accept ${shown} joins it`);
2389
+ }
2390
+ /** The member `params.member` names in `group`, this profile's own name said to be it; by its key only for a grant. */
2391
+ var member = (ctx, group, params, grant = false) => findMember(group, str(params, "member", true), state(ctx).settings.nick, grant);
2271
2392
  var view = (ctx, id, params) => groupJson(state(ctx).groups.find((g) => g.id === id) ?? groupOf(ctx, { group: id }), bool(params, "showSecret"));
2272
2393
  var GROUP_ADMIN_METHODS = {
2273
2394
  async "group.invite"(ctx, params) {
2274
- const group = groupOf(ctx, params);
2395
+ const group = joined(ctx, params);
2275
2396
  const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2276
2397
  await node(ctx).inviteToGroup({
2277
2398
  groupId: group.id,
@@ -2280,23 +2401,28 @@ var GROUP_ADMIN_METHODS = {
2280
2401
  return view(ctx, group.id, params);
2281
2402
  },
2282
2403
  async "group.remove"(ctx, params) {
2283
- const group = groupOf(ctx, params);
2404
+ const group = joined(ctx, params);
2405
+ const removed = member(ctx, group, params);
2284
2406
  await node(ctx).removeGroupMember({
2285
2407
  groupId: group.id,
2286
- key: member(ctx, group, params).key
2408
+ key: removed.key
2287
2409
  });
2288
- return view(ctx, group.id, params);
2410
+ const linkOn = !!(state(ctx).groups.find((g) => g.id === group.id) ?? group).entryLink;
2411
+ return {
2412
+ ...view(ctx, group.id, params),
2413
+ ...linkOn && { warning: `${removed.nick ?? "They"} can still join again with the group's link: ghostly group link ${group.id} --reset gives it a new one and keeps them out` }
2414
+ };
2289
2415
  },
2290
2416
  async "group.admin"(ctx, params) {
2291
- const group = groupOf(ctx, params);
2417
+ const group = joined(ctx, params);
2292
2418
  await node(ctx).makeGroupAdmin({
2293
2419
  groupId: group.id,
2294
- key: member(ctx, group, params).key
2420
+ key: member(ctx, group, params, true).key
2295
2421
  });
2296
2422
  return view(ctx, group.id, params);
2297
2423
  },
2298
2424
  async "group.hub"(ctx, params) {
2299
- const group = groupOf(ctx, params);
2425
+ const group = joined(ctx, params);
2300
2426
  const role = str(params, "role") ?? "auto";
2301
2427
  if (![
2302
2428
  "pin",
@@ -2305,13 +2431,13 @@ var GROUP_ADMIN_METHODS = {
2305
2431
  ].includes(role)) throw new CliError("bad_request", "role is pin, exclude or auto");
2306
2432
  await node(ctx).setGroupHub({
2307
2433
  groupId: group.id,
2308
- key: member(ctx, group, params).key,
2434
+ key: member(ctx, group, params, role === "pin").key,
2309
2435
  role: role === "auto" ? null : role
2310
2436
  });
2311
2437
  return view(ctx, group.id, params);
2312
2438
  },
2313
2439
  async "group.rename"(ctx, params) {
2314
- const group = groupOf(ctx, params, "chat rename <chat> <name...>");
2440
+ const group = joined(ctx, params, "chat rename <chat> <name...>");
2315
2441
  const name = groupNameOf(params);
2316
2442
  guardText(name, bool(params, "force"), "group's name", "rename it");
2317
2443
  await node(ctx).renameGroup({
@@ -2321,12 +2447,12 @@ var GROUP_ADMIN_METHODS = {
2321
2447
  return view(ctx, group.id, params);
2322
2448
  },
2323
2449
  async "group.rotate"(ctx, params) {
2324
- const group = groupOf(ctx, params);
2450
+ const group = joined(ctx, params);
2325
2451
  await node(ctx).rotateGroup({ groupId: group.id });
2326
2452
  return view(ctx, group.id, params);
2327
2453
  },
2328
2454
  async "group.link"(ctx, params) {
2329
- const group = groupOf(ctx, params);
2455
+ const group = joined(ctx, params);
2330
2456
  if (params.on === false) {
2331
2457
  await node(ctx).disableGroupLink({ groupId: group.id });
2332
2458
  return {
@@ -2344,7 +2470,7 @@ var GROUP_ADMIN_METHODS = {
2344
2470
  };
2345
2471
  },
2346
2472
  async "group.picture"(ctx, params) {
2347
- const group = groupOf(ctx, params);
2473
+ const group = joined(ctx, params);
2348
2474
  await node(ctx).setGroupPicture({
2349
2475
  groupId: group.id,
2350
2476
  picture: await picture(params)
@@ -3160,10 +3286,26 @@ function servedApps(dir) {
3160
3286
  return [];
3161
3287
  }
3162
3288
  }
3289
+ /** Writes of the list by this process: a stamp taken before one never matches one taken after, whatever the clock. */
3290
+ var writes = 0;
3291
+ /**
3292
+ * What changes whenever `apps.json` does, for a reader that keeps what it learned from the list until then: this
3293
+ * process's writes, and the file's inode, size and change times (a one-shot `app serve` writes it from another process).
3294
+ * Cheaper than a read: no parse.
3295
+ */
3296
+ function servedStamp(dir) {
3297
+ try {
3298
+ const s = statSync(servedFile(dir), { bigint: true });
3299
+ return `${writes} ${s.ino} ${s.size} ${s.mtimeNs} ${s.ctimeNs}`;
3300
+ } catch {
3301
+ return `${writes} none`;
3302
+ }
3303
+ }
3163
3304
  function writeServed(dir, apps) {
3164
3305
  const file = servedFile(dir);
3165
3306
  writeFileSync(file + ".tmp", JSON.stringify(apps, null, 2) + "\n", { mode: 384 });
3166
3307
  renameSync(file + ".tmp", file);
3308
+ writes++;
3167
3309
  }
3168
3310
  /** A served app by its reference or, when only one has it, its name. */
3169
3311
  function servedApp(apps, ref) {
@@ -3251,23 +3393,49 @@ function peerVersion(hub, chat, ref) {
3251
3393
  function reportAppFrames(hub, node, profileDir) {
3252
3394
  const open = /* @__PURE__ */ new Map();
3253
3395
  peers.set(hub, open);
3254
- /** Per chat: chat app id to reference, of the apps served when the contact last opened one there. */
3396
+ /**
3397
+ * Per chat: chat app id to reference, of the apps served when they were learned there; the list's stamp then
3398
+ * (undefined when an id could not be derived, so the next open tries again); and the version of each served app's
3399
+ * last open since.
3400
+ */
3255
3401
  const known = /* @__PURE__ */ new Map();
3256
3402
  let count = 0;
3257
3403
  const learn = (chat) => {
3404
+ let stamp = servedStamp(profileDir);
3258
3405
  const ids = /* @__PURE__ */ new Map();
3259
3406
  for (const { ref } of servedApps(profileDir)) try {
3260
3407
  ids.set(node.appId({
3261
3408
  linkId: chat,
3262
3409
  ref
3263
3410
  }).app, ref);
3264
- } catch {}
3265
- known.set(chat, ids);
3266
- return ids;
3411
+ } catch {
3412
+ stamp = void 0;
3413
+ }
3414
+ const learnt = {
3415
+ ids,
3416
+ stamp,
3417
+ versions: /* @__PURE__ */ new Map()
3418
+ };
3419
+ known.set(chat, learnt);
3420
+ return learnt;
3421
+ };
3422
+ /**
3423
+ * An open learns the served list again only when it changed since (a stat, no read), or names another version of a
3424
+ * served app than its last open did: an app served or unserved since is taken or left from its next open, and a
3425
+ * contact repeating opens (up to 50 a second for each of 16 apps) costs no read of the list nor derivation of ids.
3426
+ */
3427
+ const current = (chat, frame) => {
3428
+ const learnt = known.get(chat);
3429
+ if (!learnt) return learn(chat);
3430
+ if (!("o" in frame) || frame.o !== "open") return learnt;
3431
+ const was = learnt.versions.get(frame.app);
3432
+ return learnt.stamp === void 0 || learnt.stamp !== servedStamp(profileDir) || was !== void 0 && was !== frame.v ? learn(chat) : learnt;
3267
3433
  };
3268
3434
  return hub.onAppFrame((chat, frame) => {
3269
- const app = ("o" in frame && frame.o === "open" ? learn(chat) : known.get(chat) ?? learn(chat)).get(frame.app);
3435
+ const learnt = current(chat, frame);
3436
+ const app = learnt.ids.get(frame.app);
3270
3437
  if (!app) return;
3438
+ if ("o" in frame && frame.o === "open") learnt.versions.set(frame.app, frame.v);
3271
3439
  const id = `${chat}:${app}:${Date.now()}-${++count}`;
3272
3440
  if ("o" in frame) {
3273
3441
  if (frame.o === "open") open.set(`${chat} ${app}`, frame.v);
@@ -3323,6 +3491,7 @@ var APP_CHAT_METHODS = {
3323
3491
  }));
3324
3492
  let card = null;
3325
3493
  if (!bool(params, "noCard") && peer === null) {
3494
+ const version = app.version.length <= STATUS_CARD_LIMITS.appVersion ? { version: app.version } : {};
3326
3495
  const sent = {
3327
3496
  kind: "app",
3328
3497
  id: appCardId(app.ref),
@@ -3330,7 +3499,7 @@ var APP_CHAT_METHODS = {
3330
3499
  digest: app.digest,
3331
3500
  sequence: app.sequence,
3332
3501
  title: app.title,
3333
- version: app.version,
3502
+ ...version,
3334
3503
  ...app.url !== void 0 && { url: app.url },
3335
3504
  opened: true
3336
3505
  };
@@ -3481,7 +3650,32 @@ async function federationsOpen(ctx, ms = 3e4) {
3481
3650
  const connecting = () => NETWORKS.some((n) => (netView(state(ctx), n)?.fedimint?.federations ?? []).some((f) => f.status === "connecting"));
3482
3651
  while (connecting() && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 250));
3483
3652
  }
3484
- /** One wallet of the deck with its balance, in its own unit. Never a key, a phrase or a token. */
3653
+ /**
3654
+ * An Arkade, Bark, Spark or USDT balance, known only once the wallet is open and read it: until then the view holds 0
3655
+ * (USDT "0", also offline for good), which the app's total shows as "?" (walletTotals). `null` with `status` `locked` or
3656
+ * `reading`, never a 0 a script takes for the balance.
3657
+ */
3658
+ function readBalance(view) {
3659
+ if (!view) return {
3660
+ balance: null,
3661
+ status: null
3662
+ };
3663
+ if (view.locked) return {
3664
+ balance: null,
3665
+ status: "locked"
3666
+ };
3667
+ return view.read ? {
3668
+ balance: view.balance,
3669
+ status: null
3670
+ } : {
3671
+ balance: null,
3672
+ status: "reading"
3673
+ };
3674
+ }
3675
+ /**
3676
+ * One wallet of the deck with its balance, in its own unit. Never a key, a phrase or a token. A balance not read yet
3677
+ * is `null`, with `status` saying why (`locked`, `reading`, `error`).
3678
+ */
3485
3679
  function walletJson(instance, s) {
3486
3680
  const view = netView(s, instance.network);
3487
3681
  let balance = null, unit = "sat", address = null, status = null, error = null;
@@ -3497,16 +3691,16 @@ function walletJson(instance, s) {
3497
3691
  break;
3498
3692
  }
3499
3693
  case "arkade":
3500
- balance = view?.ark?.balance ?? null;
3694
+ ({balance, status} = readBalance(view?.ark));
3501
3695
  address = view?.ark?.address ?? null;
3502
3696
  error = view?.ark?.error ?? null;
3503
3697
  break;
3504
3698
  case "bark":
3505
- balance = view?.bark?.balance ?? null;
3699
+ ({balance, status} = readBalance(view?.bark));
3506
3700
  error = view?.bark?.error ?? null;
3507
3701
  break;
3508
3702
  case "spark":
3509
- balance = view?.spark?.balance ?? null;
3703
+ ({balance, status} = readBalance(view?.spark));
3510
3704
  address = view?.spark?.address ?? null;
3511
3705
  error = view?.spark?.error ?? null;
3512
3706
  break;
@@ -3516,12 +3710,16 @@ function walletJson(instance, s) {
3516
3710
  status = view?.bitcoin?.status ?? null;
3517
3711
  error = view?.bitcoin?.error ?? null;
3518
3712
  break;
3519
- case "fedimint":
3520
- balance = view?.fedimint?.balance ?? null;
3521
- error = view?.fedimint?.error ?? null;
3713
+ case "fedimint": {
3714
+ const federations = view?.fedimint?.federations ?? [];
3715
+ const known = federations.every((f) => f.read && f.status === "ready");
3716
+ balance = known ? view?.fedimint?.balance ?? null : null;
3717
+ status = known ? null : federations.some((f) => f.status === "error") ? "error" : "reading";
3718
+ error = view?.fedimint?.error ?? federations.find((f) => f.error)?.error ?? null;
3522
3719
  break;
3720
+ }
3523
3721
  case "usdt":
3524
- balance = view?.usdt?.balance ?? null;
3722
+ ({balance, status} = readBalance(view?.usdt));
3525
3723
  unit = "token-base";
3526
3724
  address = view?.usdt?.address ?? null;
3527
3725
  error = view?.usdt?.error ?? null;
@@ -3846,6 +4044,8 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
3846
4044
  network: n,
3847
4045
  ...card ? { card } : {}
3848
4046
  });
4047
+ const expected = isInvoice(text) ? num(params, "amount", 0, { min: 1 }) : 0;
4048
+ if (expected && quote.amount !== expected) throw new CliError("refused", `The invoice asks ${quote.amount} sats, not the ${expected} given with --amount`);
3849
4049
  const maxFee = params.maxFee === void 0 ? null : num(params, "maxFee", 0);
3850
4050
  if (maxFee !== null && quote.feeReserve > maxFee) throw new CliError("refused", `The fee may reach ${quote.feeReserve} sats, more than the ${maxFee} allowed`);
3851
4051
  const paid = await node(ctx).walletPayQuote({
@@ -4012,21 +4212,28 @@ function checkTextSize(text) {
4012
4212
  }
4013
4213
  /**
4014
4214
  * The engine's state as `engine getState` prints it without `--show-secret`: the settings' credentials, a group's
4015
- * entry link (anyone who reads it can join) and a pending chat's invite code (whoever reads it can take the chat)
4016
- * are `<hidden>`.
4215
+ * entry link and the link of another group kept under its id (anyone who reads one can join), a pending chat's
4216
+ * invite code (whoever reads it can take the chat) and this side's wake-up tokens are `<hidden>`.
4017
4217
  */
4018
4218
  function hideStateSecrets(state) {
4219
+ const hideOther = (o) => o && typeof o === "object" && "link" in o ? {
4220
+ ...o,
4221
+ link: "<hidden>"
4222
+ } : o;
4019
4223
  return {
4020
4224
  ...state,
4021
4225
  settings: redactSettings(state.settings),
4022
- ...state.groups ? { groups: state.groups.map((g) => g.entryLink ? {
4226
+ ...state.groups ? { groups: state.groups.map((g) => ({
4023
4227
  ...g,
4024
- entryLink: "<hidden>"
4025
- } : g) } : {},
4026
- ...state.links ? { links: state.links.map((l) => l.inviteCode ? {
4228
+ ...g.entryLink ? { entryLink: "<hidden>" } : {},
4229
+ ...g.others ? { others: g.others.map(hideOther) } : {},
4230
+ ...g.wakeTokens ? { wakeTokens: g.wakeTokens.map(() => "<hidden>") } : {}
4231
+ })) } : {},
4232
+ ...state.links ? { links: state.links.map((l) => ({
4027
4233
  ...l,
4028
- inviteCode: "<hidden>"
4029
- } : l) } : {}
4234
+ ...l.inviteCode ? { inviteCode: "<hidden>" } : {},
4235
+ ...l.wakeToken ? { wakeToken: "<hidden>" } : {}
4236
+ })) } : {}
4030
4237
  };
4031
4238
  }
4032
4239
  /** Settings as a bot may read them: storage credentials and other secrets masked unless asked for. */
@@ -4057,7 +4264,8 @@ var SETTABLE_KINDS = {
4057
4264
  sendTyping: "boolean",
4058
4265
  nick: "string",
4059
4266
  autoDownloads: "boolean",
4060
- serveFiles: "boolean"
4267
+ serveFiles: "boolean",
4268
+ daemonPresence: "boolean"
4061
4269
  };
4062
4270
  var SETTABLE = SETTABLE_KINDS;
4063
4271
  /**
@@ -4072,7 +4280,8 @@ var SETTING_DEFAULTS = {
4072
4280
  shareProfile: () => true,
4073
4281
  sendTyping: () => true,
4074
4282
  autoDownloads: () => true,
4075
- serveFiles: () => true
4283
+ serveFiles: () => true,
4284
+ daemonPresence: () => false
4076
4285
  };
4077
4286
  /**
4078
4287
  * The settings as `settings get` and `settings set` answer them: each key `settings set` takes, with its value in
@@ -4209,6 +4418,8 @@ function inviteNotOut(detail) {
4209
4418
  }
4210
4419
  /** V8's words for reading what a value does not have: an `engine.call` given a parameter of the wrong kind. */
4211
4420
  var BAD_VALUE = /^Cannot (destructure|read properties of (undefined|null))|is not (a function|iterable)/;
4421
+ /** A one-shot's typing without `--for` (it opens the profile offline, `offlineCall`): said on no live session. */
4422
+ var ONE_SHOT_TYPING = "Typing is said on a live session only, and a one-shot has none: it reached nobody. Keep the profile online (`ghostly daemon --detach`), or give --for to wait until it is live";
4212
4423
  var METHODS = {
4213
4424
  ...WALLET_METHODS,
4214
4425
  ...FILE_METHODS,
@@ -4394,7 +4605,7 @@ var METHODS = {
4394
4605
  },
4395
4606
  async "chat.history"(ctx, params) {
4396
4607
  const link = chatNotGroup(ctx, params, "group history");
4397
- return historyOf(ctx, link.id, params, (m) => chatMessageJson(m, link));
4608
+ return historyOf(ctx, link.id, params, async () => (m) => chatMessageJson(m, link));
4398
4609
  },
4399
4610
  async "chat.send"(ctx, params) {
4400
4611
  const link = chatNotGroup(ctx, params, "group send", "[text...]");
@@ -4450,6 +4661,7 @@ var METHODS = {
4450
4661
  const link = chatNotGroup(ctx, params, "group edit", "<message> <text...>");
4451
4662
  const messageId = str(params, "message", true);
4452
4663
  const text = str(params, "text", true);
4664
+ checkTextSize(text);
4453
4665
  if (!bool(params, "force")) {
4454
4666
  const secret = findSecret(text);
4455
4667
  if (secret) throw new CliError("confirm", `The text looks like ${secretWords(secret)}; edit with --force if you mean to`, { kind: secret.kind });
@@ -4513,7 +4725,8 @@ var METHODS = {
4513
4725
  ...status ? { status } : {},
4514
4726
  live: open(state(ctx)),
4515
4727
  sendTyping: state(ctx).settings.sendTyping !== false,
4516
- ...until ? { until } : {}
4728
+ ...until ? { until } : {},
4729
+ ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
4517
4730
  };
4518
4731
  },
4519
4732
  /**
@@ -4631,9 +4844,16 @@ var METHODS = {
4631
4844
  */
4632
4845
  async "chat.forward"(ctx, params) {
4633
4846
  const from = chatOrGroup(ctx, str(params, "chat", true));
4634
- const messageIds = list(params, "messages");
4847
+ const messageIds = [...new Set(list(params, "messages"))];
4635
4848
  if (!messageIds.length) throw new CliError("bad_request", "Name the messages to forward (their ids, from history or an event)");
4636
- const to = list(params, "to").map((ref) => chatOrGroup(ctx, ref));
4849
+ if (messageIds.length > 30) throw new CliError("bad_request", `Forward at most 30 messages at once, not ${messageIds.length}`);
4850
+ const to = [];
4851
+ for (const ref of new Set(list(params, "to"))) {
4852
+ const target = chatOrGroup(ctx, ref);
4853
+ if (to.some((t) => t.linkId === target.linkId)) continue;
4854
+ if (to.length === 5) throw new CliError("bad_request", `Forward to at most 5 chats and groups at once`);
4855
+ to.push(target);
4856
+ }
4637
4857
  if (!to.length) throw new CliError("bad_request", "Forward to which chat? Name one or more with --to");
4638
4858
  const chosen = [];
4639
4859
  for (const id of messageIds) {
@@ -4831,6 +5051,7 @@ var METHODS = {
4831
5051
  await node(ctx).removeLink({ linkId: link.id });
4832
5052
  ctx.calls.forgetChat(link.id);
4833
5053
  ctx.groupAuto.forgetChat(link.id);
5054
+ await forgetHold(ctx, link.id);
4834
5055
  return { removed: link.id };
4835
5056
  },
4836
5057
  async "chat.transport"(ctx, params) {
@@ -4956,7 +5177,10 @@ var METHODS = {
4956
5177
  },
4957
5178
  async "group.history"(ctx, params) {
4958
5179
  const group = groupOf(ctx, params, "chat history <chat>");
4959
- return historyOf(ctx, `group:${group.id}`, params, (m) => groupMessageJson(m, group));
5180
+ return historyOf(ctx, `group:${group.id}`, params, async (page) => {
5181
+ const twins = await groupPayTwinsOf(ctx, group, page);
5182
+ return (m) => groupMessageJson(m, group, twins.get(m.id));
5183
+ });
4960
5184
  },
4961
5185
  async "group.send"(ctx, params) {
4962
5186
  const group = groupOf(ctx, params, "send <chat> [text...]");
@@ -4964,7 +5188,7 @@ var METHODS = {
4964
5188
  checkTextSize(text);
4965
5189
  if (!bool(params, "force")) {
4966
5190
  const secret = findSecret(text);
4967
- if (secret) throw new CliError("confirm", "The text looks like a secret or a Cashu token; send it with --force if you mean to", { kind: secret.kind });
5191
+ if (secret) throw new CliError("confirm", `The text looks like ${secretWords(secret)}; send it with --force if you mean to`, { kind: secret.kind });
4968
5192
  }
4969
5193
  const mentions = mentionsFor(text, list(params, "mentions"), group);
4970
5194
  const replyTo = str(params, "reply");
@@ -4999,7 +5223,8 @@ var METHODS = {
4999
5223
  ...card ? {
5000
5224
  buttons: card.id,
5001
5225
  card
5002
- } : {}
5226
+ } : {},
5227
+ ...messageId && nobodyElseIn(ctx, group.id) ? { note: "Nobody else is in this group: nobody gets this message, not even someone who joins later" } : {}
5003
5228
  };
5004
5229
  },
5005
5230
  /**
@@ -5011,6 +5236,7 @@ var METHODS = {
5011
5236
  const group = groupOf(ctx, params, "edit <chat> <message> <text...>");
5012
5237
  const messageId = str(params, "message", true);
5013
5238
  const text = str(params, "text", true);
5239
+ checkTextSize(text);
5014
5240
  if (!bool(params, "force")) {
5015
5241
  const secret = findSecret(text);
5016
5242
  if (secret) throw new CliError("confirm", `The text looks like ${secretWords(secret)}; edit with --force if you mean to`, { kind: secret.kind });
@@ -5115,7 +5341,8 @@ var METHODS = {
5115
5341
  ...status ? { status } : {},
5116
5342
  reached: reached(state(ctx)),
5117
5343
  sendTyping: state(ctx).settings.sendTyping !== false,
5118
- ...until ? { until } : {}
5344
+ ...until ? { until } : {},
5345
+ ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
5119
5346
  };
5120
5347
  },
5121
5348
  async "group.leave"(ctx, params) {
@@ -5245,7 +5472,8 @@ var ENGINE_SENDS = /* @__PURE__ */ new Set([
5245
5472
  "createGroup",
5246
5473
  "renameGroup",
5247
5474
  "updateSettings",
5248
- "sendFile"
5475
+ "sendFile",
5476
+ "setOwnStatus"
5249
5477
  ]);
5250
5478
  async function guardEngineSend(ctx, method, args) {
5251
5479
  const of = (value, key) => value && typeof value === "object" ? value[key] : void 0;
@@ -5257,7 +5485,8 @@ async function guardEngineSend(ctx, method, args) {
5257
5485
  args.comment,
5258
5486
  args.name,
5259
5487
  of(args.settings, "nick"),
5260
- of(args.file, "name")
5488
+ of(args.file, "name"),
5489
+ of(args.status, "text")
5261
5490
  ];
5262
5491
  if (method === "forwardMessages") {
5263
5492
  const ids = Array.isArray(args.messageIds) ? args.messageIds.filter((id) => typeof id === "string") : [];
@@ -5398,7 +5627,10 @@ async function connectWithin(ctx, link, ms) {
5398
5627
  try {
5399
5628
  if (await Promise.race([dial, late]) !== "late") return;
5400
5629
  } catch (error) {
5401
- if (asCliError(error).code !== "timeout") throw error;
5630
+ if (asCliError(error).code !== "timeout") {
5631
+ dhtOnly(findChat(state(ctx).links, link.id));
5632
+ throw error;
5633
+ }
5402
5634
  } finally {
5403
5635
  clearTimeout(timer);
5404
5636
  }
@@ -5424,11 +5656,7 @@ async function saveMark(ctx, params, remove) {
5424
5656
  saved: !remove
5425
5657
  };
5426
5658
  }
5427
- /**
5428
- * A page of a chat's or a group's history: only that page is read from the store (the newest, those before `before`,
5429
- * or the oldest after `after`), so a long chat's is as quick as a short one's.
5430
- */
5431
- async function historyOf(ctx, chat, params, json = messageJson) {
5659
+ async function historyOf(ctx, chat, params, linesOf = async () => messageJson) {
5432
5660
  const limit = num(params, "limit", 50, {
5433
5661
  min: 1,
5434
5662
  max: 1e4,
@@ -5455,11 +5683,28 @@ async function historyOf(ctx, chat, params, json = messageJson) {
5455
5683
  });
5456
5684
  });
5457
5685
  const originals = await originalsNow(ctx, chat, page.messages);
5686
+ const json = await linesOf(page.messages);
5458
5687
  return {
5459
5688
  messages: page.messages.map((m) => quoteChecked(json(m), m, originals)),
5460
5689
  more: page.more
5461
5690
  };
5462
5691
  }
5692
+ /**
5693
+ * The payment lines of a group's history page that are twins of a payment note's line (`groupPayTwins`), as the app
5694
+ * tells them. A note whose line is not on the page is read as its one row, as the originals of replies are.
5695
+ */
5696
+ async function groupPayTwinsOf(ctx, group, page) {
5697
+ const rows = page.filter((m) => m.paymentId && !m.groupPay);
5698
+ if (!rows.length) return /* @__PURE__ */ new Map();
5699
+ const payments = state(ctx).payments ?? {};
5700
+ const notes = new Map(page.flatMap((m) => m.groupPay ? [[m.groupPay.id, m.groupPay]] : []));
5701
+ for (const id of new Set(rows.map((m) => groupPayNoteId(m.paymentId, payments[m.paymentId])))) {
5702
+ if (notes.has(id)) continue;
5703
+ const note = (await node(ctx).getMessage(`group:${group.id}`, groupPayLineId(id)))?.groupPay;
5704
+ if (note) notes.set(note.id, note);
5705
+ }
5706
+ return groupPayTwins(rows, notes, payments, group);
5707
+ }
5463
5708
  /** Past this many originals outside a page, its history is read once instead of row by row. */
5464
5709
  var ORIGINAL_READS = 32;
5465
5710
  /**
@@ -5513,6 +5758,6 @@ async function callApi(ctx, method, params = {}) {
5513
5758
  return run(ctx, await withStoredIds(ctx, params));
5514
5759
  }
5515
5760
  //#endregion
5516
- export { resumeHolds as _, hideStateSecrets as a, settingsInEffect as c, servedApps as d, nodeLocalFetch as f, groupMessageJson as g, groupJson as h, groupSendRefused as i, paymentJson as l, chatMessageJson as m, SETTABLE as n, mentionsFor as o, chatJson as p, callApi as r, redactSettings as s, API_METHODS as t, reportAppFrames as u, flushCardUpdates as v };
5761
+ export { groupPayTwins as _, hideStateSecrets as a, settingsInEffect as c, servedApps as d, nodeLocalFetch as f, groupMessageJson as g, groupJson as h, groupSendRefused as i, paymentJson as l, chatMessageJson as m, SETTABLE as n, mentionsFor as o, chatJson as p, callApi as r, redactSettings as s, API_METHODS as t, reportAppFrames as u, resumeHolds as v, flushCardUpdates as y };
5517
5762
 
5518
- //# sourceMappingURL=api-DL0Uazf6.js.map
5763
+ //# sourceMappingURL=api-BM3PsXbB.js.map