@ghostlytools/cli 1.11.1 → 1.11.3

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 (107) hide show
  1. package/README.md +32 -23
  2. package/dist/assets/{api-DL0Uazf6.js → api-DBlaoz8i.js} +478 -141
  3. package/dist/assets/api-DBlaoz8i.js.map +1 -0
  4. package/dist/assets/{api-D89ubgas.js → api-DgU4MZPD.js} +2 -2
  5. package/dist/assets/{apiKit-D78MXTrk.js → apiKit-DesObIDf.js} +19 -9
  6. package/dist/assets/apiKit-DesObIDf.js.map +1 -0
  7. package/dist/assets/appFetch-C8yZIq1e.js +194 -0
  8. package/dist/assets/appFetch-C8yZIq1e.js.map +1 -0
  9. package/dist/assets/{apps--pAqmfgQ.js → apps-DkMjDHML.js} +142 -67
  10. package/dist/assets/apps-DkMjDHML.js.map +1 -0
  11. package/dist/assets/{apps-BlSl1nGn.js → apps-rzxsjfBV.js} +1 -1
  12. package/dist/assets/{arkade-DxB-MR43.js → arkade-CarKONmH.js} +2 -2
  13. package/dist/assets/{arkade-DxB-MR43.js.map → arkade-CarKONmH.js.map} +1 -1
  14. package/dist/assets/{backup-B3JJd75o.js → backup-C0OJCJlM.js} +90 -47
  15. package/dist/assets/backup-C0OJCJlM.js.map +1 -0
  16. package/dist/assets/{backup-T7gFpU80.js → backup-CgWU7x0T.js} +1 -1
  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-Cco0Agfa.js +2 -0
  24. package/dist/assets/{buttons-C1VbDihe.js → buttons-fZTEa_2i.js} +47 -7
  25. package/dist/assets/buttons-fZTEa_2i.js.map +1 -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-Ibk3-e60.js} +31 -3
  29. package/dist/assets/client-Ibk3-e60.js.map +1 -0
  30. package/dist/assets/{codec-YGJDr7uH.js → codec-DMpQqVSt.js} +2 -2
  31. package/dist/assets/{codec-YGJDr7uH.js.map → codec-DMpQqVSt.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-CvQVCGdf.js} +2 -2
  35. package/dist/assets/{envelope-Dwq8EN8x.js.map → envelope-CvQVCGdf.js.map} +1 -1
  36. package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-zV_5Qdqz.js} +6 -3
  37. package/dist/assets/fedimintSdk-zV_5Qdqz.js.map +1 -0
  38. package/dist/assets/{fixedHosts-CINXidpd.js → fixedHosts-6gKn8dp2.js} +3 -3
  39. package/dist/assets/{fixedHosts-CINXidpd.js.map → fixedHosts-6gKn8dp2.js.map} +1 -1
  40. package/dist/assets/{host-CGlHkiQv.js → host-CYlIiY3r.js} +455 -104
  41. package/dist/assets/host-CYlIiY3r.js.map +1 -0
  42. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js → hyperdhtRelay-CdsLcAhY.js} +2 -2
  43. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js.map → hyperdhtRelay-CdsLcAhY.js.map} +1 -1
  44. package/dist/assets/{irohWeb-CYn0uB_A.js → irohWeb-D2IuloLL.js} +705 -43
  45. package/dist/assets/irohWeb-D2IuloLL.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-C0PfjKTe.js} +263 -128
  49. package/dist/assets/main-C0PfjKTe.js.map +1 -0
  50. package/dist/assets/{mainline-B0h8RchD.js → mainline-Cu61qcPS.js} +60 -24
  51. package/dist/assets/mainline-Cu61qcPS.js.map +1 -0
  52. package/dist/assets/{networkReason-BBosp2KG.js → networkReason-Dt7Yx_n4.js} +3 -3
  53. package/dist/assets/{networkReason-BBosp2KG.js.map → networkReason-Dt7Yx_n4.js.map} +1 -1
  54. package/dist/assets/{nwc-SSNS1aJ-.js → nwc-CtZypDcv.js} +6 -5
  55. package/dist/assets/nwc-CtZypDcv.js.map +1 -0
  56. package/dist/assets/{nwcProvider-BXqJmM98.js → nwcProvider-DYHkd0iu.js} +6 -3
  57. package/dist/assets/{nwcProvider-BXqJmM98.js.map → nwcProvider-DYHkd0iu.js.map} +1 -1
  58. package/dist/assets/{ownDid--DtH_Jdi.js → ownDid-CJ0ta8CL.js} +3 -3
  59. package/dist/assets/{ownDid--DtH_Jdi.js.map → ownDid-CJ0ta8CL.js.map} +1 -1
  60. package/dist/assets/{ownStatus-CQPGjCUR.js → ownStatus-D4HC6tNR.js} +12 -6
  61. package/dist/assets/{ownStatus-CQPGjCUR.js.map → ownStatus-D4HC6tNR.js.map} +1 -1
  62. package/dist/assets/{profiles-4UQ1Hsds.js → profiles-Ccdq6Xf6.js} +82 -6
  63. package/dist/assets/profiles-Ccdq6Xf6.js.map +1 -0
  64. package/dist/assets/{registry-B6BXKv6Q.js → registry-CE0PpQAE.js} +1 -1
  65. package/dist/assets/{registry-BKCFTEYp.js → registry-LvxsLJ5S.js} +88 -25
  66. package/dist/assets/registry-LvxsLJ5S.js.map +1 -0
  67. package/dist/assets/{resolve-MFeFljsN.js → resolve-6kVu2DE5.js} +4 -3
  68. package/dist/assets/resolve-6kVu2DE5.js.map +1 -0
  69. package/dist/assets/{server-rHKhnog1.js → server-Q3VcNqGt.js} +630 -933
  70. package/dist/assets/server-Q3VcNqGt.js.map +1 -0
  71. package/dist/assets/{src-BzsyAvPf.js → src-DjVj2ynY.js} +580 -168
  72. package/dist/assets/src-DjVj2ynY.js.map +1 -0
  73. package/dist/assets/{sshForges-qITn-RoV.js → sshForges-DeZ9cN9Q.js} +4 -3
  74. package/dist/assets/sshForges-DeZ9cN9Q.js.map +1 -0
  75. package/dist/assets/{translate-Bkr_iDgp.js → translate-iQZq4TnY.js} +36 -15
  76. package/dist/assets/translate-iQZq4TnY.js.map +1 -0
  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-DnyTGdTX.js} +3 -3
  80. package/dist/assets/{usdt-Bp7T2iqt.js.map → usdt-DnyTGdTX.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/sshForges-qITn-RoV.js.map +0 -1
  106. package/dist/assets/translate-Bkr_iDgp.js.map +0 -1
  107. 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 { Ba as sanitizeFileName, Cd as toBase64Url, Co as replySnippet, Dl as isAppUrl, Fl as appRef, Fo as appCardUrl, Ga as baseMime, Gn as NO_PICTURE_METADATA, Go as claimedTime, Ha as PLAYABLE_AUDIO, Ja as parseVoiceMeta, Jn as stripPictureMetadata, Ju as relayUrlProblem, Ka as downsamplePeaks, Lo as cardLine, Mo as STATUS_CARD_LIMITS, Po as appCardId, Sd as randomBytes$1, Sl as APP_PERMISSIONS, Ss as LIMITS, Ua as VOICE_LIMITS, Uo as MESSAGE_CLOCK_SKEW_MS, Va as sanitizeMime, Vl as isAppRef, Vn as withoutAudioMetadata, Vo as statusCardBytes, Wa as VOICE_METER, Wn as withoutVideoMetadata, Xa as voiceLevel, Ya as voiceDownloadName, Yl as readImageMeta, Yn as withoutPictureMetadata, Zi as identityStatement, bs as parseLocalTarget, du as ownInviteRefusal, ii as TYPING_REFRESH_MS, ki as APP_DATA_MAX_BYTES, lu as inviteLink, md as sanitizeAvatar, oi as sanitizeTypingStatus, pd as MAX_AVATAR_LENGTH, qu as normalizeRelayUrl, ri as TYPING_KINDS, sr as GROUP_FILE_LIMITS, us as AWAITING_PEER_MS, vs as GhostlyHttpError, zo as checkStatusCard } from "./src-DjVj2ynY.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-D2IuloLL.js";
5
+ import { t as IDENTITY_PROVIDERS } from "./registry-LvxsLJ5S.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-D4HC6tNR.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-DesObIDf.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 checkTextSize$1, c as waitForConfirmed, d as waitForMessage, f as waitForRemoval, i as pressable, l as waitForEdit, n as buttonsCard, o as goesOn, s as nobodyElseIn, t as BUTTON_METHODS, u as waitForGroupFrame } from "./buttons-fZTEa_2i.js";
13
+ import { a as checkShownName } from "./profiles-Ccdq6Xf6.js";
14
+ import { t as BACKUP_METHODS } from "./backup-C0OJCJlM.js";
15
+ import { o as checkedBundle } from "./apps-DkMjDHML.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) {
@@ -722,19 +729,22 @@ function mimeOf(path, given) {
722
729
  * a date can hold it; else when it was stored here.
723
730
  */
724
731
  async function voiceTime(ctx, stored) {
725
- return (await findMessage(ctx, stored.linkId, (m) => m.file?.id === stored.id))?.timestamp ?? claimedTime(stored.metadata?.timestamp) ?? stored.createdAt;
732
+ const older = (linkId) => node(ctx).fileMessages(linkId);
733
+ return (await findMessage(ctx, stored.linkId, (m) => m.file?.id === stored.id, older))?.timestamp ?? claimedTime(stored.metadata?.timestamp) ?? stored.createdAt;
726
734
  }
727
735
  /**
728
736
  * The message of a chat or a group (`group:<id>`) that `test` picks: looked for among its newest first, where the one a
729
- * command names almost always is, then in all of them only when there are more. A whole history costs a read of every row.
737
+ * command names almost always is, then in all of them only when there are more. A whole history costs a read of every row;
738
+ * `older` reads fewer, where the message is known to be among them.
730
739
  */
731
- async function findMessage(ctx, linkId, test) {
740
+ async function findMessage(ctx, linkId, test, older) {
732
741
  const page = await node(ctx).messagePage({
733
742
  linkId,
734
743
  limit: 200
735
744
  });
736
745
  const newest = page.messages.find(test);
737
746
  if (newest || !page.more) return newest;
747
+ if (older) return (await older(linkId)).find(test);
738
748
  const group = linkId.startsWith("group:") ? linkId.slice(6) : void 0;
739
749
  return (group ? await node(ctx).groupMessages({ groupId: group }) : await node(ctx).getMessages(linkId)).find(test);
740
750
  }
@@ -887,7 +897,7 @@ async function whileUnchanged(path, read) {
887
897
  * A file announced in a group (WISP 503): its bytes staged under a group file id with their digest, as a chat's are, then
888
898
  * the announcement. This device is its first holder and serves the members who ask.
889
899
  */
890
- async function sendToGroup(ctx, params, group, path, picked) {
900
+ async function sendToGroup(ctx, params, group, path, name, picked) {
891
901
  if (picked > GROUP_FILE_LIMITS.maxBytes) throw new CliError("refused", `Too large for a group (at most ${GROUP_FILE_LIMITS.maxBytes} bytes)`);
892
902
  if (!picked) throw new CliError("refused", "An empty file cannot go to a group");
893
903
  const mime = mimeOf(path, str(params, "mime"));
@@ -907,7 +917,7 @@ async function sendToGroup(ctx, params, group, path, picked) {
907
917
  const fileId = groupFileId(group.id, "out");
908
918
  const file = {
909
919
  id: fileId,
910
- name: sanitizeFileName(str(params, "name") ?? basename(path)),
920
+ name,
911
921
  size,
912
922
  mime,
913
923
  ...voice ? { voice } : {},
@@ -1083,9 +1093,10 @@ async function waitForFile(ctx, params, stopping) {
1083
1093
  }
1084
1094
  var FILE_METHODS = {
1085
1095
  async "file.send"(ctx, params) {
1086
- guardText(str(params, "name"), bool(params, "force"), "file's name", "send it");
1087
- const target = chatOrGroupOf(ctx, params);
1088
1096
  const path = resolve(str(params, "path", true));
1097
+ const name = sanitizeFileName(str(params, "name") ?? basename(path));
1098
+ guardText(name, bool(params, "force"), "file's name", "send it");
1099
+ const target = chatOrGroupOf(ctx, params);
1089
1100
  let info;
1090
1101
  try {
1091
1102
  info = await stat(path);
@@ -1099,10 +1110,10 @@ var FILE_METHODS = {
1099
1110
  min: 1,
1100
1111
  max: 86400
1101
1112
  });
1102
- if ("group" in target) return sendToGroup(ctx, params, target.group, path, info.size);
1113
+ if ("group" in target) return sendToGroup(ctx, params, target.group, path, name, info.size);
1103
1114
  const { link } = target;
1104
1115
  if (link.profile && link.dataLink === "open" && !link.capabilities?.files) throw new CliError("unavailable", "The contact's app takes no files");
1105
- if (!link.capabilities?.largeFiles && info.size > LIMITS.maxFileBytes) throw new CliError("refused", `Too large for the contact's app (at most ${LIMITS.maxFileBytes} bytes)`);
1116
+ if (link.dataLink === "open" && !link.capabilities?.largeFiles && info.size > LIMITS.maxFileBytes) throw new CliError("refused", `Too large for the contact's app (at most ${LIMITS.maxFileBytes} bytes)`);
1106
1117
  if (typeof link.peerFileRoom === "number" && info.size > link.peerFileRoom) throw new CliError("refused", `Not enough space on the contact's device (${link.peerFileRoom} bytes free)`);
1107
1118
  const mime = mimeOf(path, str(params, "mime"));
1108
1119
  const replyTo = str(params, "reply");
@@ -1118,7 +1129,7 @@ var FILE_METHODS = {
1118
1129
  const wireId = toBase64Url(randomBytes$1(12));
1119
1130
  const file = {
1120
1131
  id: `${link.id}-out-${wireId}`,
1121
- name: sanitizeFileName(str(params, "name") ?? basename(path)),
1132
+ name,
1122
1133
  size: source.size,
1123
1134
  mime,
1124
1135
  ...voice ? { voice } : {},
@@ -1265,6 +1276,8 @@ var FILE_METHODS = {
1265
1276
  if (whole && action === "cancel") throw new CliError("refused", "Too late to cancel: it arrived whole, and the contact keeps it");
1266
1277
  if (whole && action === "pause") throw new CliError("refused", "Too late to pause: it arrived whole, and the contact keeps it");
1267
1278
  }
1279
+ const view = state(ctx).transfers[fileId];
1280
+ if ((action === "resume" || action === "request" || action === "resend") && view?.stage === "paused" && view.pausedBy === "peer") throw new CliError("refused", "Paused by the contact: it goes on when they resume it");
1268
1281
  await node(ctx).fileAction({
1269
1282
  linkId,
1270
1283
  fileId,
@@ -1288,7 +1301,7 @@ var FILE_METHODS = {
1288
1301
  async "file.save"(ctx, params) {
1289
1302
  const fileId = str(params, "file", true);
1290
1303
  if (params.chat !== void 0) fileChat(ctx, params, fileId);
1291
- if (bool(params, "wait")) await FILE_METHODS["file.wait"](ctx, {
1304
+ if (bool(params, "wait") && (await fileStore.get(fileId))?.direction !== "out") await FILE_METHODS["file.wait"](ctx, {
1292
1305
  file: fileId,
1293
1306
  timeout: params.timeout
1294
1307
  });
@@ -1490,9 +1503,11 @@ function secretIn(value) {
1490
1503
  * The secret guard `send` has (docs/CLI.md § Safety): a card whose text looks like a seed, a private key or a Cashu
1491
1504
  * token goes only with `--force`. `fields` are what this command gives (an update's own, not the card it merges over).
1492
1505
  * A card's text is read as given and as the card carries it (`cardLine`): a line loses its invisible characters on the
1493
- * way, so a key one of them broke in two is whole again on the card. The fallback text goes as it is, as `send`'s.
1506
+ * way, so a key one of them broke in two is whole again on the card. The fallback text goes as it is, as `send`'s, and
1507
+ * one past 16 KiB is refused first, with its size, `--force` or not (`checkTextSize`).
1494
1508
  */
1495
1509
  function guardSecrets(fields, params, verb) {
1510
+ if (typeof params.text === "string") checkTextSize$1(params.text);
1496
1511
  if (bool(params, "force")) return;
1497
1512
  const check = (text) => {
1498
1513
  const secret = findSecret(text);
@@ -1688,16 +1703,18 @@ async function updateCard(ctx, params, kind) {
1688
1703
  let queued = false;
1689
1704
  if (due > 0 && ctx.mode === "daemon") {
1690
1705
  pace.next = card;
1706
+ pace.text = text;
1691
1707
  queued = true;
1692
1708
  if (!pace.timer) pace.flushed = new Promise((resolve) => {
1693
1709
  const send = () => {
1694
- const next = pace.next;
1710
+ const next = pace.next, nextText = pace.text ?? "";
1695
1711
  clearTimeout(pace.timer);
1696
1712
  pace.timer = void 0;
1697
1713
  pace.next = void 0;
1714
+ pace.text = void 0;
1698
1715
  pace.flush = void 0;
1699
1716
  pace.last = Date.now();
1700
- (next ? editCard(ctx, target, message.id, next, text) : Promise.resolve()).catch(() => {}).finally(resolve);
1717
+ (next ? editCard(ctx, target, message.id, next, nextText) : Promise.resolve()).catch(() => {}).finally(resolve);
1701
1718
  };
1702
1719
  pace.flush = send;
1703
1720
  pace.timer = setTimeout(send, due);
@@ -1798,6 +1815,7 @@ async function sendUsage(ctx, params) {
1798
1815
  kind: "usage",
1799
1816
  id: typeof fields.id === "string" && fields.id ? fields.id : USAGE_CARD_ID
1800
1817
  });
1818
+ if (typeof params.text === "string") checkTextSize$1(params.text);
1801
1819
  oneOf(params, "wait", ["none", "sent"], "none");
1802
1820
  num(params, "timeout", 30, {
1803
1821
  min: 1,
@@ -1864,6 +1882,37 @@ function writeHolds(ctx, holds) {
1864
1882
  writeFileSync(file + ".tmp", JSON.stringify(holds) + "\n", { mode: 384 });
1865
1883
  renameSync(file + ".tmp", file);
1866
1884
  }
1885
+ /**
1886
+ * Changes one chat's entry: the file is read again right here and written back in the same step, with no wait in
1887
+ * between, so what another chat's hold, expiry or release wrote meanwhile stays. Each call read the file before its
1888
+ * engine call and wrote that copy back after it: two holds at once on a daemon (which serves its connections at once)
1889
+ * kept only one, and the other chat stayed on DHT only for good; an expiry meanwhile brought an ended hold back.
1890
+ * Only one process writes the file: a command goes through the profile's daemon when one runs, and otherwise holds
1891
+ * the profile itself.
1892
+ */
1893
+ function editHold(ctx, linkId, hold) {
1894
+ const holds = readHolds(ctx);
1895
+ if (hold) holds[linkId] = hold;
1896
+ else if (holds[linkId]) delete holds[linkId];
1897
+ else return;
1898
+ writeHolds(ctx, holds);
1899
+ }
1900
+ /** Per profile folder and chat, the last change to its hold under way: changes to one chat's hold go one after another. */
1901
+ var queues = /* @__PURE__ */ new Map();
1902
+ /**
1903
+ * Runs `task` once the changes to this chat's hold started before it are done (failed or not). A hold and an expiry,
1904
+ * a release or a removal of the same chat no longer run into each other; other chats' run meanwhile.
1905
+ */
1906
+ function inTurn(ctx, linkId, task) {
1907
+ const key = `${ctx.runtime.paths.dir}\0${linkId}`;
1908
+ const run = (queues.get(key) ?? Promise.resolve()).then(task, task);
1909
+ const settled = run.then(() => {}, () => {});
1910
+ queues.set(key, settled);
1911
+ settled.then(() => {
1912
+ if (queues.get(key) === settled) queues.delete(key);
1913
+ });
1914
+ return run;
1915
+ }
1867
1916
  function timersOf(ctx) {
1868
1917
  let map = timers.get(ctx);
1869
1918
  if (!map) timers.set(ctx, map = /* @__PURE__ */ new Map());
@@ -1873,12 +1922,19 @@ function stopWait(ctx, linkId) {
1873
1922
  timersOf(ctx).get(linkId)?.();
1874
1923
  timersOf(ctx).delete(linkId);
1875
1924
  }
1925
+ /**
1926
+ * The longest a hold's timer waits before it reads the wall clock again. Timers run on a clock that stops while the
1927
+ * machine sleeps: one timer for the whole hold, after a sleep past its end, kept the chat on DHT only for as long again
1928
+ * as the hold had left when the machine went to sleep, while `holdOf` no longer reported it.
1929
+ */
1930
+ var HOLD_CHECK_MS = 6e4;
1876
1931
  function schedule(ctx, linkId, until) {
1877
1932
  stopWait(ctx, linkId);
1878
1933
  const timer = setTimeout(() => {
1879
1934
  timersOf(ctx).delete(linkId);
1880
- expire(ctx, linkId);
1881
- }, Math.max(0, until - Date.now()));
1935
+ if (until > Date.now()) schedule(ctx, linkId, until);
1936
+ else expire(ctx, linkId);
1937
+ }, Math.min(HOLD_CHECK_MS, Math.max(0, until - Date.now())));
1882
1938
  timer.unref?.();
1883
1939
  timersOf(ctx).set(linkId, () => clearTimeout(timer));
1884
1940
  }
@@ -1912,56 +1968,78 @@ function holdOf(ctx, linkId) {
1912
1968
  return until !== void 0 && until > Date.now() ? until : null;
1913
1969
  }
1914
1970
  /** 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"
1971
+ function holdChat(ctx, link, minutes) {
1972
+ return inTurn(ctx, link.id, async () => {
1973
+ const now = state(ctx).links.find((l) => l.id === link.id) ?? link;
1974
+ const held = readHolds(ctx)[link.id];
1975
+ 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");
1976
+ if (!now.profile) throw new CliError("unavailable", "A chat of the older protocol has no DHT only");
1977
+ const until = Date.now() + minutes * 6e4;
1978
+ editHold(ctx, link.id, {
1979
+ until,
1980
+ since: held?.since ?? Date.now()
1924
1981
  });
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
1982
+ if (now.deliveryMode !== "dht") try {
1983
+ await node(ctx).setChatTransport({
1984
+ linkId: link.id,
1985
+ transport: "dht"
1986
+ });
1987
+ } catch (error) {
1988
+ editHold(ctx, link.id, held ?? null);
1989
+ throw new CliError("unavailable", error instanceof Error ? error.message : String(error));
1990
+ }
1991
+ schedule(ctx, link.id, until);
1992
+ ctx.hub.emit("chat.held", `chat.held:${link.id}:${until}`, {
1993
+ chat: link.id,
1994
+ until
1995
+ });
1996
+ return until;
1937
1997
  });
1938
- return until;
1939
1998
  }
1940
1999
  /**
1941
2000
  * Ends a hold: the chat leaves DHT only, unless someone chose otherwise meanwhile. Whether there was one. `reason`:
1942
2001
  * expired, connect (`chat connect`) or lifted (`--hold 0`, or `chat transport`: `chosen`, the chat's transport was
1943
2002
  * just chosen, and stays as chosen).
1944
2003
  */
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"
2004
+ function releaseHold(ctx, linkId, reason, chosen = false) {
2005
+ return inTurn(ctx, linkId, async () => {
2006
+ if (!readHolds(ctx)[linkId]) return false;
2007
+ stopWait(ctx, linkId);
2008
+ const link = state(ctx).links.find((l) => l.id === linkId);
2009
+ if (!chosen && link?.deliveryMode === "dht") await node(ctx).setDeliveryMode({
2010
+ linkId,
2011
+ mode: "stream"
2012
+ });
2013
+ editHold(ctx, linkId, null);
2014
+ ctx.hub.emit("chat.released", `chat.released:${linkId}:${Date.now()}`, {
2015
+ chat: linkId,
2016
+ reason
2017
+ });
2018
+ return true;
1953
2019
  });
1954
- delete holds[linkId];
1955
- writeHolds(ctx, holds);
1956
- ctx.hub.emit("chat.released", `chat.released:${linkId}:${Date.now()}`, {
1957
- chat: linkId,
1958
- reason
2020
+ }
2021
+ /**
2022
+ * 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
2023
+ * backup made meanwhile), a chat joined again from the same invite showed its `heldUntil`, and its end said
2024
+ * `chat.released` for a chat that was gone.
2025
+ */
2026
+ function forgetHold(ctx, linkId) {
2027
+ return inTurn(ctx, linkId, async () => {
2028
+ stopWait(ctx, linkId);
2029
+ editHold(ctx, linkId, null);
1959
2030
  });
1960
- return true;
1961
2031
  }
1962
- /** At start: holds whose time is up end now, the others are timed again. */
2032
+ /**
2033
+ * At start: holds whose time is up end now, the others are timed again. A hold whose chat the store does not have is
2034
+ * dropped, with no release said: a profile restored from a backup taken while that chat was removed (the backup reads
2035
+ * holds.json before and after its store) had it, and its end said `chat.released` for a chat it never had.
2036
+ */
1963
2037
  function resumeHolds(ctx) {
1964
- for (const [linkId, hold] of Object.entries(readHolds(ctx))) schedule(ctx, linkId, hold.until);
2038
+ const chats = new Set(state(ctx).links.map((link) => link.id));
2039
+ const holds = readHolds(ctx), gone = Object.keys(holds).filter((linkId) => !chats.has(linkId));
2040
+ for (const linkId of gone) delete holds[linkId];
2041
+ if (gone.length) writeHolds(ctx, holds);
2042
+ for (const [linkId, hold] of Object.entries(holds)) schedule(ctx, linkId, hold.until);
1965
2043
  }
1966
2044
  //#endregion
1967
2045
  //#region src/views.ts
@@ -2058,6 +2136,23 @@ function chatDetailsJson(link, showSecret) {
2058
2136
  pin: pinJson(link.pin)
2059
2137
  };
2060
2138
  }
2139
+ function groupPayJson(note) {
2140
+ const by = note.from === "*" && note.rail === "lightning" ? null : note.by ?? null;
2141
+ return {
2142
+ id: note.id,
2143
+ kind: note.kind,
2144
+ from: note.from,
2145
+ to: note.to,
2146
+ by,
2147
+ claims: [...note.claims ?? []],
2148
+ amount: note.amount,
2149
+ decimals: note.decimals,
2150
+ unit: note.unit,
2151
+ rail: note.rail,
2152
+ state: note.state,
2153
+ test: !!note.test
2154
+ };
2155
+ }
2061
2156
  function messageJson(message) {
2062
2157
  return {
2063
2158
  id: message.id,
@@ -2101,7 +2196,8 @@ function messageJson(message) {
2101
2196
  button: message.press.button,
2102
2197
  label: message.press.label,
2103
2198
  ...message.press.inferred ? { inferred: true } : {}
2104
- } } : {}
2199
+ } } : {},
2200
+ ...message.groupPay ? { groupPay: groupPayJson(message.groupPay) } : {}
2105
2201
  };
2106
2202
  }
2107
2203
  /**
@@ -2151,9 +2247,13 @@ function chatMessageJson(message, link) {
2151
2247
  * name rides on the edge or the roster), so the roster fills `nick` when the message has none, and for an author no
2152
2248
  * 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
2249
  * before that name came ("Member a4w9nb5y joined") says it, as the app draws it; before, it kept the key for good.
2250
+ * `twinOf`: the line of the payment note this message is the twin of (`groupPayTwins`).
2154
2251
  */
2155
- function groupMessageJson(message, group) {
2156
- const json = messageJson(message);
2252
+ function groupMessageJson(message, group, twinOf) {
2253
+ const json = twinOf ? {
2254
+ ...messageJson(message),
2255
+ twinOf
2256
+ } : messageJson(message);
2157
2257
  if (!message.member) return json;
2158
2258
  const nick = json.nick ?? group?.members.find((m) => m.key === message.member)?.nick ?? group?.formerNames?.[message.member];
2159
2259
  if (!nick) return json;
@@ -2166,6 +2266,20 @@ function groupMessageJson(message, group) {
2166
2266
  };
2167
2267
  }
2168
2268
  /**
2269
+ * 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
2270
+ * tells them (`groupPayTwin`): the requester's own request, the request as it came over the edge, a payment answering
2271
+ * it. Only for a note whose line is in `notes` (the group's, by note id): a twin of nothing is no twin.
2272
+ */
2273
+ function groupPayTwins(messages, notes, payments, group) {
2274
+ const twins = /* @__PURE__ */ new Map();
2275
+ for (const m of messages) {
2276
+ if (!m.paymentId || m.groupPay) continue;
2277
+ const note = groupPayTwin(m, payments[m.paymentId], (id) => notes.get(id), group?.myKey, (linkId) => groupMemberOfLink(group, linkId));
2278
+ if (note && notes.has(note)) twins.set(m.id, groupPayLineId(note));
2279
+ }
2280
+ return twins;
2281
+ }
2282
+ /**
2169
2283
  * A group as the CLI prints it. The entry link lets anyone who reads it join, so it is `<hidden>` unless asked for
2170
2284
  * (`--show-secret`, or `group link`); null when the group has none.
2171
2285
  */
@@ -2217,14 +2331,28 @@ function groupJson(group, showSecret = false) {
2217
2331
  /**
2218
2332
  * A member by key, unique key prefix or name; never this profile itself (`myName`: its name, which its own row lacks).
2219
2333
  * 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).
2334
+ * members is an error, not a guess). For a grant (`byKeyOnly`: admin, a pinned hub) a member found only by the name it
2335
+ * gave itself is refused, with its key: another member could call itself that name while the one meant is away, as
2336
+ * `findOwnNamedChat` refuses a contact's own name.
2221
2337
  */
2222
- function findMember(group, ref, myName) {
2338
+ function findMember(group, ref, myName, byKeyOnly = false) {
2223
2339
  const lower = ref.toLowerCase();
2340
+ const asKey = contactKeyOf(ref);
2341
+ if (asKey !== void 0) {
2342
+ const member = group.members.find((m) => !m.me && m.key === asKey);
2343
+ if (member) return member;
2344
+ throw noMember(group, asKey, myName);
2345
+ }
2224
2346
  const others = group.members.filter((m) => !m.me);
2225
2347
  const byKey = others.filter((m) => m.key === ref);
2226
2348
  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];
2349
+ if (matches.length === 1) {
2350
+ 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`, {
2351
+ member: matches[0].key,
2352
+ name: matches[0].nick ?? null
2353
+ });
2354
+ return matches[0];
2355
+ }
2228
2356
  throw matches.length ? new CliError("bad_request", `${JSON.stringify(ref)} names more than one member`) : noMember(group, ref, myName);
2229
2357
  }
2230
2358
  /**
@@ -2266,12 +2394,23 @@ async function picture(params) {
2266
2394
  if (bool(params, "clear")) return null;
2267
2395
  return pictureFrom(str(params, "path", true));
2268
2396
  }
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);
2397
+ /**
2398
+ * A group this profile administers or is in, not only an invitation: before, the engine answered `group rename`,
2399
+ * `picture`, `link`, `rotate` and `invite` on an invitation not yet joined with "Group not found" (engine, exit 1),
2400
+ * while `group show` listed it, and `remove`/`admin` said "No member" of a member list it had not received yet.
2401
+ */
2402
+ function joined(ctx, params, twin) {
2403
+ const group = groupOf(ctx, params, twin);
2404
+ if (group.status || !group.invitation) return group;
2405
+ const ref = str(params, "group", true), shown = /^[\w.:-]+$/.test(ref) ? ref : JSON.stringify(ref);
2406
+ 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`);
2407
+ }
2408
+ /** The member `params.member` names in `group`, this profile's own name said to be it; by its key only for a grant. */
2409
+ var member = (ctx, group, params, grant = false) => findMember(group, str(params, "member", true), state(ctx).settings.nick, grant);
2271
2410
  var view = (ctx, id, params) => groupJson(state(ctx).groups.find((g) => g.id === id) ?? groupOf(ctx, { group: id }), bool(params, "showSecret"));
2272
2411
  var GROUP_ADMIN_METHODS = {
2273
2412
  async "group.invite"(ctx, params) {
2274
- const group = groupOf(ctx, params);
2413
+ const group = joined(ctx, params);
2275
2414
  const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2276
2415
  await node(ctx).inviteToGroup({
2277
2416
  groupId: group.id,
@@ -2280,23 +2419,28 @@ var GROUP_ADMIN_METHODS = {
2280
2419
  return view(ctx, group.id, params);
2281
2420
  },
2282
2421
  async "group.remove"(ctx, params) {
2283
- const group = groupOf(ctx, params);
2422
+ const group = joined(ctx, params);
2423
+ const removed = member(ctx, group, params);
2284
2424
  await node(ctx).removeGroupMember({
2285
2425
  groupId: group.id,
2286
- key: member(ctx, group, params).key
2426
+ key: removed.key
2287
2427
  });
2288
- return view(ctx, group.id, params);
2428
+ const linkOn = !!(state(ctx).groups.find((g) => g.id === group.id) ?? group).entryLink;
2429
+ return {
2430
+ ...view(ctx, group.id, params),
2431
+ ...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` }
2432
+ };
2289
2433
  },
2290
2434
  async "group.admin"(ctx, params) {
2291
- const group = groupOf(ctx, params);
2435
+ const group = joined(ctx, params);
2292
2436
  await node(ctx).makeGroupAdmin({
2293
2437
  groupId: group.id,
2294
- key: member(ctx, group, params).key
2438
+ key: member(ctx, group, params, true).key
2295
2439
  });
2296
2440
  return view(ctx, group.id, params);
2297
2441
  },
2298
2442
  async "group.hub"(ctx, params) {
2299
- const group = groupOf(ctx, params);
2443
+ const group = joined(ctx, params);
2300
2444
  const role = str(params, "role") ?? "auto";
2301
2445
  if (![
2302
2446
  "pin",
@@ -2305,13 +2449,13 @@ var GROUP_ADMIN_METHODS = {
2305
2449
  ].includes(role)) throw new CliError("bad_request", "role is pin, exclude or auto");
2306
2450
  await node(ctx).setGroupHub({
2307
2451
  groupId: group.id,
2308
- key: member(ctx, group, params).key,
2452
+ key: member(ctx, group, params, role === "pin").key,
2309
2453
  role: role === "auto" ? null : role
2310
2454
  });
2311
2455
  return view(ctx, group.id, params);
2312
2456
  },
2313
2457
  async "group.rename"(ctx, params) {
2314
- const group = groupOf(ctx, params, "chat rename <chat> <name...>");
2458
+ const group = joined(ctx, params, "chat rename <chat> <name...>");
2315
2459
  const name = groupNameOf(params);
2316
2460
  guardText(name, bool(params, "force"), "group's name", "rename it");
2317
2461
  await node(ctx).renameGroup({
@@ -2321,13 +2465,15 @@ var GROUP_ADMIN_METHODS = {
2321
2465
  return view(ctx, group.id, params);
2322
2466
  },
2323
2467
  async "group.rotate"(ctx, params) {
2324
- const group = groupOf(ctx, params);
2468
+ const group = joined(ctx, params);
2325
2469
  await node(ctx).rotateGroup({ groupId: group.id });
2326
2470
  return view(ctx, group.id, params);
2327
2471
  },
2328
2472
  async "group.link"(ctx, params) {
2329
- const group = groupOf(ctx, params);
2330
- if (params.on === false) {
2473
+ const group = joined(ctx, params);
2474
+ const on = params.on === void 0 || bool(params, "on"), reset = bool(params, "reset");
2475
+ if (!on && reset) throw new CliError("bad_request", "on: false turns the link off: not with reset");
2476
+ if (!on) {
2331
2477
  await node(ctx).disableGroupLink({ groupId: group.id });
2332
2478
  return {
2333
2479
  group: group.id,
@@ -2336,7 +2482,7 @@ var GROUP_ADMIN_METHODS = {
2336
2482
  }
2337
2483
  const { link } = await node(ctx).enableGroupLink({
2338
2484
  groupId: group.id,
2339
- ...bool(params, "reset") ? { reset: true } : {}
2485
+ ...reset ? { reset: true } : {}
2340
2486
  });
2341
2487
  return {
2342
2488
  group: group.id,
@@ -2344,7 +2490,7 @@ var GROUP_ADMIN_METHODS = {
2344
2490
  };
2345
2491
  },
2346
2492
  async "group.picture"(ctx, params) {
2347
- const group = groupOf(ctx, params);
2493
+ const group = joined(ctx, params);
2348
2494
  await node(ctx).setGroupPicture({
2349
2495
  groupId: group.id,
2350
2496
  picture: await picture(params)
@@ -3103,13 +3249,34 @@ var SERVICE_METHODS = {
3103
3249
  open$1.delete(key);
3104
3250
  const entry = await pending?.catch(() => void 0);
3105
3251
  if (!entry) throw new CliError("not_found", "That service is not open here");
3106
- await new Promise((resolve) => {
3107
- entry.server.close(() => resolve());
3108
- entry.server.closeAllConnections();
3109
- });
3252
+ await closeOpened(entry);
3110
3253
  return { closed: key };
3111
3254
  }
3112
3255
  };
3256
+ /**
3257
+ * Closed means closed: an answer still streaming (a page's EventSource) kept `close` waiting for good, and kept coming.
3258
+ * Each connection's end stops the contact's answer too (`proxy`).
3259
+ */
3260
+ function closeOpened(entry) {
3261
+ return new Promise((resolve) => {
3262
+ entry.server.close(() => resolve());
3263
+ entry.server.closeAllConnections();
3264
+ });
3265
+ }
3266
+ /**
3267
+ * `chat remove`: the services opened from a contact no chat here has any more. Before, they stayed on their ports, each
3268
+ * request a 503, and `service close` answered `No chat` for good.
3269
+ */
3270
+ async function closeServicesOf(ctx, peer) {
3271
+ if (state(ctx).links.some((link) => link.peerPubKeyZ32 === peer)) return;
3272
+ const keys = [...open$1.keys()].filter((key) => key.startsWith(`${peer}/`));
3273
+ await Promise.all(keys.map(async (key) => {
3274
+ const pending = open$1.get(key);
3275
+ open$1.delete(key);
3276
+ const entry = await pending?.catch(() => void 0);
3277
+ if (entry) await closeOpened(entry);
3278
+ }));
3279
+ }
3113
3280
  //#endregion
3114
3281
  //#region src/calls/api.ts
3115
3282
  /** Voice calls (WISP 1100 § Calls): the API methods. The audio itself goes over each call's own socket. */
@@ -3160,10 +3327,26 @@ function servedApps(dir) {
3160
3327
  return [];
3161
3328
  }
3162
3329
  }
3330
+ /** Writes of the list by this process: a stamp taken before one never matches one taken after, whatever the clock. */
3331
+ var writes = 0;
3332
+ /**
3333
+ * What changes whenever `apps.json` does, for a reader that keeps what it learned from the list until then: this
3334
+ * process's writes, and the file's inode, size and change times (a one-shot `app serve` writes it from another process).
3335
+ * Cheaper than a read: no parse.
3336
+ */
3337
+ function servedStamp(dir) {
3338
+ try {
3339
+ const s = statSync(servedFile(dir), { bigint: true });
3340
+ return `${writes} ${s.ino} ${s.size} ${s.mtimeNs} ${s.ctimeNs}`;
3341
+ } catch {
3342
+ return `${writes} none`;
3343
+ }
3344
+ }
3163
3345
  function writeServed(dir, apps) {
3164
3346
  const file = servedFile(dir);
3165
3347
  writeFileSync(file + ".tmp", JSON.stringify(apps, null, 2) + "\n", { mode: 384 });
3166
3348
  renameSync(file + ".tmp", file);
3349
+ writes++;
3167
3350
  }
3168
3351
  /** A served app by its reference or, when only one has it, its name. */
3169
3352
  function servedApp(apps, ref) {
@@ -3251,23 +3434,49 @@ function peerVersion(hub, chat, ref) {
3251
3434
  function reportAppFrames(hub, node, profileDir) {
3252
3435
  const open = /* @__PURE__ */ new Map();
3253
3436
  peers.set(hub, open);
3254
- /** Per chat: chat app id to reference, of the apps served when the contact last opened one there. */
3437
+ /**
3438
+ * Per chat: chat app id to reference, of the apps served when they were learned there; the list's stamp then
3439
+ * (undefined when an id could not be derived, so the next open tries again); and the version of each served app's
3440
+ * last open since.
3441
+ */
3255
3442
  const known = /* @__PURE__ */ new Map();
3256
3443
  let count = 0;
3257
3444
  const learn = (chat) => {
3445
+ let stamp = servedStamp(profileDir);
3258
3446
  const ids = /* @__PURE__ */ new Map();
3259
3447
  for (const { ref } of servedApps(profileDir)) try {
3260
3448
  ids.set(node.appId({
3261
3449
  linkId: chat,
3262
3450
  ref
3263
3451
  }).app, ref);
3264
- } catch {}
3265
- known.set(chat, ids);
3266
- return ids;
3452
+ } catch {
3453
+ stamp = void 0;
3454
+ }
3455
+ const learnt = {
3456
+ ids,
3457
+ stamp,
3458
+ versions: /* @__PURE__ */ new Map()
3459
+ };
3460
+ known.set(chat, learnt);
3461
+ return learnt;
3462
+ };
3463
+ /**
3464
+ * An open learns the served list again only when it changed since (a stat, no read), or names another version of a
3465
+ * served app than its last open did: an app served or unserved since is taken or left from its next open, and a
3466
+ * contact repeating opens (up to 50 a second for each of 16 apps) costs no read of the list nor derivation of ids.
3467
+ */
3468
+ const current = (chat, frame) => {
3469
+ const learnt = known.get(chat);
3470
+ if (!learnt) return learn(chat);
3471
+ if (!("o" in frame) || frame.o !== "open") return learnt;
3472
+ const was = learnt.versions.get(frame.app);
3473
+ return learnt.stamp === void 0 || learnt.stamp !== servedStamp(profileDir) || was !== void 0 && was !== frame.v ? learn(chat) : learnt;
3267
3474
  };
3268
3475
  return hub.onAppFrame((chat, frame) => {
3269
- const app = ("o" in frame && frame.o === "open" ? learn(chat) : known.get(chat) ?? learn(chat)).get(frame.app);
3476
+ const learnt = current(chat, frame);
3477
+ const app = learnt.ids.get(frame.app);
3270
3478
  if (!app) return;
3479
+ if ("o" in frame && frame.o === "open") learnt.versions.set(frame.app, frame.v);
3271
3480
  const id = `${chat}:${app}:${Date.now()}-${++count}`;
3272
3481
  if ("o" in frame) {
3273
3482
  if (frame.o === "open") open.set(`${chat} ${app}`, frame.v);
@@ -3323,6 +3532,7 @@ var APP_CHAT_METHODS = {
3323
3532
  }));
3324
3533
  let card = null;
3325
3534
  if (!bool(params, "noCard") && peer === null) {
3535
+ const version = app.version.length <= STATUS_CARD_LIMITS.appVersion ? { version: app.version } : {};
3326
3536
  const sent = {
3327
3537
  kind: "app",
3328
3538
  id: appCardId(app.ref),
@@ -3330,7 +3540,7 @@ var APP_CHAT_METHODS = {
3330
3540
  digest: app.digest,
3331
3541
  sequence: app.sequence,
3332
3542
  title: app.title,
3333
- version: app.version,
3543
+ ...version,
3334
3544
  ...app.url !== void 0 && { url: app.url },
3335
3545
  opened: true
3336
3546
  };
@@ -3481,7 +3691,32 @@ async function federationsOpen(ctx, ms = 3e4) {
3481
3691
  const connecting = () => NETWORKS.some((n) => (netView(state(ctx), n)?.fedimint?.federations ?? []).some((f) => f.status === "connecting"));
3482
3692
  while (connecting() && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 250));
3483
3693
  }
3484
- /** One wallet of the deck with its balance, in its own unit. Never a key, a phrase or a token. */
3694
+ /**
3695
+ * An Arkade, Bark, Spark or USDT balance, known only once the wallet is open and read it: until then the view holds 0
3696
+ * (USDT "0", also offline for good), which the app's total shows as "?" (walletTotals). `null` with `status` `locked` or
3697
+ * `reading`, never a 0 a script takes for the balance.
3698
+ */
3699
+ function readBalance(view) {
3700
+ if (!view) return {
3701
+ balance: null,
3702
+ status: null
3703
+ };
3704
+ if (view.locked) return {
3705
+ balance: null,
3706
+ status: "locked"
3707
+ };
3708
+ return view.read ? {
3709
+ balance: view.balance,
3710
+ status: null
3711
+ } : {
3712
+ balance: null,
3713
+ status: "reading"
3714
+ };
3715
+ }
3716
+ /**
3717
+ * 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
3718
+ * is `null`, with `status` saying why (`locked`, `reading`, `error`).
3719
+ */
3485
3720
  function walletJson(instance, s) {
3486
3721
  const view = netView(s, instance.network);
3487
3722
  let balance = null, unit = "sat", address = null, status = null, error = null;
@@ -3497,16 +3732,16 @@ function walletJson(instance, s) {
3497
3732
  break;
3498
3733
  }
3499
3734
  case "arkade":
3500
- balance = view?.ark?.balance ?? null;
3735
+ ({balance, status} = readBalance(view?.ark));
3501
3736
  address = view?.ark?.address ?? null;
3502
3737
  error = view?.ark?.error ?? null;
3503
3738
  break;
3504
3739
  case "bark":
3505
- balance = view?.bark?.balance ?? null;
3740
+ ({balance, status} = readBalance(view?.bark));
3506
3741
  error = view?.bark?.error ?? null;
3507
3742
  break;
3508
3743
  case "spark":
3509
- balance = view?.spark?.balance ?? null;
3744
+ ({balance, status} = readBalance(view?.spark));
3510
3745
  address = view?.spark?.address ?? null;
3511
3746
  error = view?.spark?.error ?? null;
3512
3747
  break;
@@ -3516,12 +3751,16 @@ function walletJson(instance, s) {
3516
3751
  status = view?.bitcoin?.status ?? null;
3517
3752
  error = view?.bitcoin?.error ?? null;
3518
3753
  break;
3519
- case "fedimint":
3520
- balance = view?.fedimint?.balance ?? null;
3521
- error = view?.fedimint?.error ?? null;
3754
+ case "fedimint": {
3755
+ const federations = view?.fedimint?.federations ?? [];
3756
+ const known = federations.every((f) => f.read && f.status === "ready");
3757
+ balance = known ? view?.fedimint?.balance ?? null : null;
3758
+ status = known ? null : federations.some((f) => f.status === "error") ? "error" : "reading";
3759
+ error = view?.fedimint?.error ?? federations.find((f) => f.error)?.error ?? null;
3522
3760
  break;
3761
+ }
3523
3762
  case "usdt":
3524
- balance = view?.usdt?.balance ?? null;
3763
+ ({balance, status} = readBalance(view?.usdt));
3525
3764
  unit = "token-base";
3526
3765
  address = view?.usdt?.address ?? null;
3527
3766
  error = view?.usdt?.error ?? null;
@@ -3846,6 +4085,8 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
3846
4085
  network: n,
3847
4086
  ...card ? { card } : {}
3848
4087
  });
4088
+ const expected = isInvoice(text) ? num(params, "amount", 0, { min: 1 }) : 0;
4089
+ if (expected && quote.amount !== expected) throw new CliError("refused", `The invoice asks ${quote.amount} sats, not the ${expected} given with --amount`);
3849
4090
  const maxFee = params.maxFee === void 0 ? null : num(params, "maxFee", 0);
3850
4091
  if (maxFee !== null && quote.feeReserve > maxFee) throw new CliError("refused", `The fee may reach ${quote.feeReserve} sats, more than the ${maxFee} allowed`);
3851
4092
  const paid = await node(ctx).walletPayQuote({
@@ -4012,21 +4253,28 @@ function checkTextSize(text) {
4012
4253
  }
4013
4254
  /**
4014
4255
  * 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>`.
4256
+ * entry link and the link of another group kept under its id (anyone who reads one can join), a pending chat's
4257
+ * invite code (whoever reads it can take the chat) and this side's wake-up tokens are `<hidden>`.
4017
4258
  */
4018
4259
  function hideStateSecrets(state) {
4260
+ const hideOther = (o) => o && typeof o === "object" && "link" in o ? {
4261
+ ...o,
4262
+ link: "<hidden>"
4263
+ } : o;
4019
4264
  return {
4020
4265
  ...state,
4021
4266
  settings: redactSettings(state.settings),
4022
- ...state.groups ? { groups: state.groups.map((g) => g.entryLink ? {
4267
+ ...state.groups ? { groups: state.groups.map((g) => ({
4023
4268
  ...g,
4024
- entryLink: "<hidden>"
4025
- } : g) } : {},
4026
- ...state.links ? { links: state.links.map((l) => l.inviteCode ? {
4269
+ ...g.entryLink ? { entryLink: "<hidden>" } : {},
4270
+ ...g.others ? { others: g.others.map(hideOther) } : {},
4271
+ ...g.wakeTokens ? { wakeTokens: g.wakeTokens.map(() => "<hidden>") } : {}
4272
+ })) } : {},
4273
+ ...state.links ? { links: state.links.map((l) => ({
4027
4274
  ...l,
4028
- inviteCode: "<hidden>"
4029
- } : l) } : {}
4275
+ ...l.inviteCode ? { inviteCode: "<hidden>" } : {},
4276
+ ...l.wakeToken ? { wakeToken: "<hidden>" } : {}
4277
+ })) } : {}
4030
4278
  };
4031
4279
  }
4032
4280
  /** Settings as a bot may read them: storage credentials and other secrets masked unless asked for. */
@@ -4057,7 +4305,8 @@ var SETTABLE_KINDS = {
4057
4305
  sendTyping: "boolean",
4058
4306
  nick: "string",
4059
4307
  autoDownloads: "boolean",
4060
- serveFiles: "boolean"
4308
+ serveFiles: "boolean",
4309
+ daemonPresence: "boolean"
4061
4310
  };
4062
4311
  var SETTABLE = SETTABLE_KINDS;
4063
4312
  /**
@@ -4072,7 +4321,8 @@ var SETTING_DEFAULTS = {
4072
4321
  shareProfile: () => true,
4073
4322
  sendTyping: () => true,
4074
4323
  autoDownloads: () => true,
4075
- serveFiles: () => true
4324
+ serveFiles: () => true,
4325
+ daemonPresence: () => false
4076
4326
  };
4077
4327
  /**
4078
4328
  * The settings as `settings get` and `settings set` answer them: each key `settings set` takes, with its value in
@@ -4209,6 +4459,28 @@ function inviteNotOut(detail) {
4209
4459
  }
4210
4460
  /** V8's words for reading what a value does not have: an `engine.call` given a parameter of the wrong kind. */
4211
4461
  var BAD_VALUE = /^Cannot (destructure|read properties of (undefined|null))|is not (a function|iterable)/;
4462
+ /** A one-shot's typing without `--for` (it opens the profile offline, `offlineCall`): said on no live session. */
4463
+ 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";
4464
+ /**
4465
+ * A removal on its way goes with the chat's row, and the contact kept the message for good, though `message delete
4466
+ * --everyone` had said its removal goes on: `chat remove`, the engine's `removeLink` and `clearProfileData` (every
4467
+ * chat's row at once) are refused until `--force`.
4468
+ */
4469
+ function noRemovalOnItsWay(ctx, linkIds, clearing = false) {
4470
+ const pending = linkIds.flatMap((linkId) => node(ctx).removalsPending({ linkId }));
4471
+ if (!pending.length) return;
4472
+ const n = pending.length, one = n === 1;
4473
+ const [now, then, go] = clearing ? [
4474
+ "clearing the profile",
4475
+ "clear it then",
4476
+ "clear it"
4477
+ ] : [
4478
+ "removing the chat",
4479
+ "remove the chat then",
4480
+ "remove it"
4481
+ ];
4482
+ throw new CliError("confirm", `${one ? "A message you deleted for everyone has" : `${n} messages you deleted for everyone have`} not reached the contact yet: ${now} now leaves ${one ? "it" : "them"} on their device. Keep this profile online until the contact is reachable (ghostly daemon --detach) and ${then}, or pass --force (force: true over the socket) to ${go} now`, { messages: pending });
4483
+ }
4212
4484
  var METHODS = {
4213
4485
  ...WALLET_METHODS,
4214
4486
  ...FILE_METHODS,
@@ -4394,7 +4666,7 @@ var METHODS = {
4394
4666
  },
4395
4667
  async "chat.history"(ctx, params) {
4396
4668
  const link = chatNotGroup(ctx, params, "group history");
4397
- return historyOf(ctx, link.id, params, (m) => chatMessageJson(m, link));
4669
+ return historyOf(ctx, link.id, params, async () => (m) => chatMessageJson(m, link));
4398
4670
  },
4399
4671
  async "chat.send"(ctx, params) {
4400
4672
  const link = chatNotGroup(ctx, params, "group send", "[text...]");
@@ -4450,6 +4722,7 @@ var METHODS = {
4450
4722
  const link = chatNotGroup(ctx, params, "group edit", "<message> <text...>");
4451
4723
  const messageId = str(params, "message", true);
4452
4724
  const text = str(params, "text", true);
4725
+ checkTextSize(text);
4453
4726
  if (!bool(params, "force")) {
4454
4727
  const secret = findSecret(text);
4455
4728
  if (secret) throw new CliError("confirm", `The text looks like ${secretWords(secret)}; edit with --force if you mean to`, { kind: secret.kind });
@@ -4513,7 +4786,8 @@ var METHODS = {
4513
4786
  ...status ? { status } : {},
4514
4787
  live: open(state(ctx)),
4515
4788
  sendTyping: state(ctx).settings.sendTyping !== false,
4516
- ...until ? { until } : {}
4789
+ ...until ? { until } : {},
4790
+ ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
4517
4791
  };
4518
4792
  },
4519
4793
  /**
@@ -4631,9 +4905,16 @@ var METHODS = {
4631
4905
  */
4632
4906
  async "chat.forward"(ctx, params) {
4633
4907
  const from = chatOrGroup(ctx, str(params, "chat", true));
4634
- const messageIds = list(params, "messages");
4908
+ const messageIds = [...new Set(list(params, "messages"))];
4635
4909
  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));
4910
+ if (messageIds.length > 30) throw new CliError("bad_request", `Forward at most 30 messages at once, not ${messageIds.length}`);
4911
+ const to = [];
4912
+ for (const ref of new Set(list(params, "to"))) {
4913
+ const target = chatOrGroup(ctx, ref);
4914
+ if (to.some((t) => t.linkId === target.linkId)) continue;
4915
+ if (to.length === 5) throw new CliError("bad_request", `Forward to at most 5 chats and groups at once`);
4916
+ to.push(target);
4917
+ }
4637
4918
  if (!to.length) throw new CliError("bad_request", "Forward to which chat? Name one or more with --to");
4638
4919
  const chosen = [];
4639
4920
  for (const id of messageIds) {
@@ -4828,9 +5109,12 @@ var METHODS = {
4828
5109
  const link = chatNotGroup(ctx, params, "group forget", "--yes");
4829
5110
  if (!bool(params, "yes")) throw new CliError("confirm", "Removing a chat deletes its keys and history on this device; pass --yes (yes: true over the socket) to go on");
4830
5111
  noCallOn(ctx, link.id, "remove the chat");
5112
+ if (!bool(params, "force")) noRemovalOnItsWay(ctx, [link.id]);
4831
5113
  await node(ctx).removeLink({ linkId: link.id });
4832
5114
  ctx.calls.forgetChat(link.id);
4833
5115
  ctx.groupAuto.forgetChat(link.id);
5116
+ await forgetHold(ctx, link.id);
5117
+ await closeServicesOf(ctx, link.peerPubKeyZ32);
4834
5118
  return { removed: link.id };
4835
5119
  },
4836
5120
  async "chat.transport"(ctx, params) {
@@ -4956,7 +5240,10 @@ var METHODS = {
4956
5240
  },
4957
5241
  async "group.history"(ctx, params) {
4958
5242
  const group = groupOf(ctx, params, "chat history <chat>");
4959
- return historyOf(ctx, `group:${group.id}`, params, (m) => groupMessageJson(m, group));
5243
+ return historyOf(ctx, `group:${group.id}`, params, async (page) => {
5244
+ const twins = await groupPayTwinsOf(ctx, group, page);
5245
+ return (m) => groupMessageJson(m, group, twins.get(m.id));
5246
+ });
4960
5247
  },
4961
5248
  async "group.send"(ctx, params) {
4962
5249
  const group = groupOf(ctx, params, "send <chat> [text...]");
@@ -4964,7 +5251,7 @@ var METHODS = {
4964
5251
  checkTextSize(text);
4965
5252
  if (!bool(params, "force")) {
4966
5253
  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 });
5254
+ if (secret) throw new CliError("confirm", `The text looks like ${secretWords(secret)}; send it with --force if you mean to`, { kind: secret.kind });
4968
5255
  }
4969
5256
  const mentions = mentionsFor(text, list(params, "mentions"), group);
4970
5257
  const replyTo = str(params, "reply");
@@ -4999,7 +5286,8 @@ var METHODS = {
4999
5286
  ...card ? {
5000
5287
  buttons: card.id,
5001
5288
  card
5002
- } : {}
5289
+ } : {},
5290
+ ...messageId && nobodyElseIn(ctx, group.id) ? { note: "Nobody else is in this group: nobody gets this message, not even someone who joins later" } : {}
5003
5291
  };
5004
5292
  },
5005
5293
  /**
@@ -5011,6 +5299,7 @@ var METHODS = {
5011
5299
  const group = groupOf(ctx, params, "edit <chat> <message> <text...>");
5012
5300
  const messageId = str(params, "message", true);
5013
5301
  const text = str(params, "text", true);
5302
+ checkTextSize(text);
5014
5303
  if (!bool(params, "force")) {
5015
5304
  const secret = findSecret(text);
5016
5305
  if (secret) throw new CliError("confirm", `The text looks like ${secretWords(secret)}; edit with --force if you mean to`, { kind: secret.kind });
@@ -5115,7 +5404,8 @@ var METHODS = {
5115
5404
  ...status ? { status } : {},
5116
5405
  reached: reached(state(ctx)),
5117
5406
  sendTyping: state(ctx).settings.sendTyping !== false,
5118
- ...until ? { until } : {}
5407
+ ...until ? { until } : {},
5408
+ ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
5119
5409
  };
5120
5410
  },
5121
5411
  async "group.leave"(ctx, params) {
@@ -5172,7 +5462,7 @@ var METHODS = {
5172
5462
  if (args && "confirmedReal" in args && !bool(params, "confirmReal")) throw new CliError("confirm", `${method} spends real money: pass --confirm-real (confirmReal: true over the socket) to confirm it`);
5173
5463
  const deletes = DESTRUCTIVE_CALLS.get(method);
5174
5464
  if (deletes && !bool(params, "yes")) throw new CliError("confirm", `${method} ${deletes}; pass --yes (yes: true over the socket) to go on`);
5175
- if (method === "clearProfileData") return clearProfile(ctx);
5465
+ if (method === "clearProfileData") return clearProfile(ctx, bool(params, "force"));
5176
5466
  const takes = ENGINE_PARAMS[method] ?? READ_PARAMS[method];
5177
5467
  const wrong = (why, rawError) => new CliError("bad_request", `${method} takes ${takes || "no parameters"}: ${why} (ghostly engine --list --verbose)`, {
5178
5468
  takes,
@@ -5181,8 +5471,10 @@ var METHODS = {
5181
5471
  const problem = engineParamsProblem(method, args);
5182
5472
  if (problem) throw wrong(problem);
5183
5473
  if (typeof args?.linkId === "string") {
5184
- if (method === "removeLink") noCallOn(ctx, args.linkId, "remove the chat");
5185
- else if (method === "setChatTransport" && args.transport === "dht" || method === "setDeliveryMode" && args.mode === "dht") noCallOn(ctx, args.linkId, "put the chat on DHT only");
5474
+ if (method === "removeLink") {
5475
+ noCallOn(ctx, args.linkId, "remove the chat");
5476
+ if (!bool(params, "force")) noRemovalOnItsWay(ctx, [args.linkId]);
5477
+ } else if (method === "setChatTransport" && args.transport === "dht" || method === "setDeliveryMode" && args.mode === "dht") noCallOn(ctx, args.linkId, "put the chat on DHT only");
5186
5478
  }
5187
5479
  if (args && ENGINE_SENDS.has(method) && !bool(params, "force")) await guardEngineSend(ctx, method, args);
5188
5480
  if (method === "getMessages") return node(ctx).getMessages(str(args ?? {}, "linkId", true));
@@ -5190,12 +5482,16 @@ var METHODS = {
5190
5482
  if (method === "setActiveLink") inviteShown.get(ctx)?.();
5191
5483
  const target = node(ctx)[method];
5192
5484
  if (typeof target !== "function") throw new CliError("not_found", `The engine has no call ${method}`);
5485
+ const removedPeer = method === "removeLink" ? state(ctx).links.find((link) => link.id === args?.linkId)?.peerPubKeyZ32 : void 0;
5193
5486
  try {
5194
5487
  const result = await target.call(node(ctx), args) ?? null;
5195
5488
  if (method === "removeLink") {
5196
5489
  ctx.calls.forgetChat(str(args ?? {}, "linkId", true));
5197
5490
  ctx.groupAuto.forgetChat(str(args ?? {}, "linkId", true));
5491
+ await forgetHold(ctx, str(args ?? {}, "linkId", true));
5492
+ if (removedPeer) await closeServicesOf(ctx, removedPeer);
5198
5493
  }
5494
+ if ((method === "setChatTransport" || method === "setDeliveryMode") && typeof args?.linkId === "string") await releaseHold(ctx, args.linkId, "lifted", true);
5199
5495
  return result;
5200
5496
  } catch (error) {
5201
5497
  if (error instanceof TypeError && BAD_VALUE.test(error.message)) throw wrong("a parameter of the wrong kind", error.message);
@@ -5208,10 +5504,11 @@ var METHODS = {
5208
5504
  * A daemon would go on serving the stopped engine's memory (chats and groups that are gone, new ones that are not
5209
5505
  * kept): it stops once it has answered, and the next command starts on the emptied profile.
5210
5506
  */
5211
- async function clearProfile(ctx) {
5507
+ async function clearProfile(ctx, force) {
5212
5508
  const call = ctx.calls.list()[0];
5213
5509
  if (call) throw new CliError("busy", `A call is on in a chat: hang it up first (ghostly call hangup ${call.chat}), then clear the profile`, { call: call.call });
5214
5510
  const { links, groups } = state(ctx);
5511
+ if (!force) noRemovalOnItsWay(ctx, links.map((link) => link.id), true);
5215
5512
  await node(ctx).clearProfileData();
5216
5513
  const cleared = {
5217
5514
  chats: links.length,
@@ -5245,7 +5542,8 @@ var ENGINE_SENDS = /* @__PURE__ */ new Set([
5245
5542
  "createGroup",
5246
5543
  "renameGroup",
5247
5544
  "updateSettings",
5248
- "sendFile"
5545
+ "sendFile",
5546
+ "setOwnStatus"
5249
5547
  ]);
5250
5548
  async function guardEngineSend(ctx, method, args) {
5251
5549
  const of = (value, key) => value && typeof value === "object" ? value[key] : void 0;
@@ -5257,7 +5555,8 @@ async function guardEngineSend(ctx, method, args) {
5257
5555
  args.comment,
5258
5556
  args.name,
5259
5557
  of(args.settings, "nick"),
5260
- of(args.file, "name")
5558
+ of(args.file, "name"),
5559
+ of(args.status, "text")
5261
5560
  ];
5262
5561
  if (method === "forwardMessages") {
5263
5562
  const ids = Array.isArray(args.messageIds) ? args.messageIds.filter((id) => typeof id === "string") : [];
@@ -5398,12 +5697,37 @@ async function connectWithin(ctx, link, ms) {
5398
5697
  try {
5399
5698
  if (await Promise.race([dial, late]) !== "late") return;
5400
5699
  } catch (error) {
5401
- if (asCliError(error).code !== "timeout") throw error;
5700
+ if (asCliError(error).code !== "timeout") {
5701
+ dhtOnly(findChat(state(ctx).links, link.id));
5702
+ const away = contactAway(error);
5703
+ if (away) throw new CliError("unavailable", `${away}. ${connectNext(ctx, link)}`, {
5704
+ chat: link.id,
5705
+ reason: error.message
5706
+ });
5707
+ throw error;
5708
+ }
5402
5709
  } finally {
5403
5710
  clearTimeout(timer);
5404
5711
  }
5712
+ throw new CliError("timeout", `Timed out after ${Math.round(ms / 1e3)} s: the contact did not answer. ${connectNext(ctx, link)}`, { chat: link.id });
5713
+ }
5714
+ /** What happens after a `chat connect` the contact did not answer: the daemon dials again by itself, a one-shot does not. */
5715
+ function connectNext(ctx, link) {
5405
5716
  const shown = /^[\w.:-]+$/.test(link.label ?? "") ? link.label : link.id;
5406
- throw new CliError("timeout", `Timed out after ${Math.round(ms / 1e3)} s: the contact did not answer. ${ctx.mode === "one-shot" ? "Try again later, or keep this profile online with `ghostly daemon --detach`: it reconnects by itself" : `It reconnects by itself while this profile is online; ghostly chat wait ${shown} --until live waits for it`}`, { chat: link.id });
5717
+ return ctx.mode === "one-shot" ? "Try again later, or keep this profile online with `ghostly daemon --detach`: it reconnects by itself" : `It reconnects by itself while this profile is online; ghostly chat wait ${shown} --until live waits for it`;
5718
+ }
5719
+ /**
5720
+ * A dial that ended because the contact's app is not there: the link's own "Could not connect to the peer", or
5721
+ * HyperDHT's errors as the app's errorText says them (closed, or asleep or frozen). They answered as they came, without
5722
+ * the next step; HyperDHT's as `engine`, "PEER_NOT_FOUND: Peer not found", as if this side had failed.
5723
+ */
5724
+ function contactAway(error) {
5725
+ const message = error instanceof Error ? error.message : "";
5726
+ const reason = /^Could not connect to the peer(?:: ([\s\S]*))?$/.exec(message);
5727
+ const native = reason ? reason[1] ?? "" : message;
5728
+ if (/^PEER_NOT_FOUND: /.test(native)) return "Your contact's app isn't reachable on HyperDHT: it may be closed";
5729
+ if (/^(?:PEER_CONNECTION_FAILED|BAD_HOLEPUNCH_REPLY|HOLEPUNCH_[A-Z_]+): /.test(native)) return "Your contact's app isn't answering on HyperDHT: it may be asleep or frozen";
5730
+ return reason ? "The contact did not answer" : void 0;
5407
5731
  }
5408
5732
  async function saveMark(ctx, params, remove) {
5409
5733
  const target = chatOrGroup(ctx, str(params, "chat", true)), messageId = str(params, "message", true);
@@ -5424,11 +5748,7 @@ async function saveMark(ctx, params, remove) {
5424
5748
  saved: !remove
5425
5749
  };
5426
5750
  }
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) {
5751
+ async function historyOf(ctx, chat, params, linesOf = async () => messageJson) {
5432
5752
  const limit = num(params, "limit", 50, {
5433
5753
  min: 1,
5434
5754
  max: 1e4,
@@ -5455,11 +5775,28 @@ async function historyOf(ctx, chat, params, json = messageJson) {
5455
5775
  });
5456
5776
  });
5457
5777
  const originals = await originalsNow(ctx, chat, page.messages);
5778
+ const json = await linesOf(page.messages);
5458
5779
  return {
5459
5780
  messages: page.messages.map((m) => quoteChecked(json(m), m, originals)),
5460
5781
  more: page.more
5461
5782
  };
5462
5783
  }
5784
+ /**
5785
+ * The payment lines of a group's history page that are twins of a payment note's line (`groupPayTwins`), as the app
5786
+ * tells them. A note whose line is not on the page is read as its one row, as the originals of replies are.
5787
+ */
5788
+ async function groupPayTwinsOf(ctx, group, page) {
5789
+ const rows = page.filter((m) => m.paymentId && !m.groupPay);
5790
+ if (!rows.length) return /* @__PURE__ */ new Map();
5791
+ const payments = state(ctx).payments ?? {};
5792
+ const notes = new Map(page.flatMap((m) => m.groupPay ? [[m.groupPay.id, m.groupPay]] : []));
5793
+ for (const id of new Set(rows.map((m) => groupPayNoteId(m.paymentId, payments[m.paymentId])))) {
5794
+ if (notes.has(id)) continue;
5795
+ const note = (await node(ctx).getMessage(`group:${group.id}`, groupPayLineId(id)))?.groupPay;
5796
+ if (note) notes.set(note.id, note);
5797
+ }
5798
+ return groupPayTwins(rows, notes, payments, group);
5799
+ }
5463
5800
  /** Past this many originals outside a page, its history is read once instead of row by row. */
5464
5801
  var ORIGINAL_READS = 32;
5465
5802
  /**
@@ -5513,6 +5850,6 @@ async function callApi(ctx, method, params = {}) {
5513
5850
  return run(ctx, await withStoredIds(ctx, params));
5514
5851
  }
5515
5852
  //#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 };
5853
+ 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
5854
 
5518
- //# sourceMappingURL=api-DL0Uazf6.js.map
5855
+ //# sourceMappingURL=api-DBlaoz8i.js.map