@ghostlytools/cli 1.9.0 → 1.10.0

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 +28 -20
  2. package/SKILL.md +5 -1
  3. package/dist/assets/{api-DFCgr6RH.js → api-BF_KwecF.js} +84 -38
  4. package/dist/assets/api-BF_KwecF.js.map +1 -0
  5. package/dist/assets/{api-raWw9j_m.js → api-DdrA86Ur.js} +2 -2
  6. package/dist/assets/{apiKit-CCavJJcl.js → apiKit-Du1u2l4x.js} +8 -8
  7. package/dist/assets/apiKit-Du1u2l4x.js.map +1 -0
  8. package/dist/assets/{apps-B7o2BPj6.js → apps-Bti9fDoW.js} +1 -1
  9. package/dist/assets/{apps-DmxEG147.js → apps-DwPfp54I.js} +5 -3
  10. package/dist/assets/apps-DwPfp54I.js.map +1 -0
  11. package/dist/assets/{arkade-DtYR9H0c.js → arkade-DOWpA2Kr.js} +2 -2
  12. package/dist/assets/{arkade-DtYR9H0c.js.map → arkade-DOWpA2Kr.js.map} +1 -1
  13. package/dist/assets/{backup-BserdrNk.js → backup-CeRckyl2.js} +1 -1
  14. package/dist/assets/{backup-YIB2XIES.js → backup-DZ_Q1eSu.js} +6 -6
  15. package/dist/assets/{backup-YIB2XIES.js.map → backup-DZ_Q1eSu.js.map} +1 -1
  16. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  17. package/dist/assets/{blobFiles-DOQDRdDI.js → blobFiles-BnjN_Vrz.js} +3 -3
  18. package/dist/assets/{blobFiles-DOQDRdDI.js.map → blobFiles-BnjN_Vrz.js.map} +1 -1
  19. package/dist/assets/buttons-BxIThdg9.js +332 -0
  20. package/dist/assets/buttons-BxIThdg9.js.map +1 -0
  21. package/dist/assets/buttons-D9QBHS9Y.js +2 -0
  22. package/dist/assets/client-D5E1RQYB.js +473 -0
  23. package/dist/assets/client-D5E1RQYB.js.map +1 -0
  24. package/dist/assets/{endpoint-BdaeBw2L.js → endpoint-DWHkXWVM.js} +101 -16
  25. package/dist/assets/endpoint-DWHkXWVM.js.map +1 -0
  26. package/dist/assets/{envelope-Dt75vrmY.js → envelope-CugS9qwQ.js} +2 -2
  27. package/dist/assets/{envelope-Dt75vrmY.js.map → envelope-CugS9qwQ.js.map} +1 -1
  28. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js.map +1 -1
  29. package/dist/assets/{fileBytes-BPDKufla.js → fileBytes-DMzrIdCu.js} +1 -1
  30. package/dist/assets/{fileBytes-DNgrRL0R.js → fileBytes-DjBYYyXT.js} +3 -3
  31. package/dist/assets/{fileBytes-DNgrRL0R.js.map → fileBytes-DjBYYyXT.js.map} +1 -1
  32. package/dist/assets/{fileBytes-Q3ehcEr8.js → fileBytes-Douk1yOp.js} +2 -2
  33. package/dist/assets/{fileBytes-Q3ehcEr8.js.map → fileBytes-Douk1yOp.js.map} +1 -1
  34. package/dist/assets/fileBytesIdb-CD5Uv490.js +2 -0
  35. package/dist/assets/{fileBytesIdb-Dm1EyEbT.js → fileBytesIdb-CkClu9YI.js} +3 -3
  36. package/dist/assets/{fileBytesIdb-Dm1EyEbT.js.map → fileBytesIdb-CkClu9YI.js.map} +1 -1
  37. package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js → fileBytesOpfs-WryQuOgK.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js.map → fileBytesOpfs-WryQuOgK.js.map} +1 -1
  39. package/dist/assets/{fixedHosts-B598JzbC.js → fixedHosts-B4E4VrYE.js} +4 -4
  40. package/dist/assets/{fixedHosts-B598JzbC.js.map → fixedHosts-B4E4VrYE.js.map} +1 -1
  41. package/dist/assets/{groupFiles-FXel6zIc.js → groupFiles-NonOYBKN.js} +378 -59
  42. package/dist/assets/groupFiles-NonOYBKN.js.map +1 -0
  43. package/dist/assets/{host-DIBeK_c_.js → host-DvcVt5YI.js} +79 -23
  44. package/dist/assets/{host-DIBeK_c_.js.map → host-DvcVt5YI.js.map} +1 -1
  45. package/dist/assets/{hyperdhtRelay-D185dETu.js → hyperdhtRelay-Ce42sR8x.js} +2 -2
  46. package/dist/assets/{hyperdhtRelay-D185dETu.js.map → hyperdhtRelay-Ce42sR8x.js.map} +1 -1
  47. package/dist/assets/{idb-BkOJES5_.js → idb-BHsAqENE.js} +37 -6
  48. package/dist/assets/idb-BHsAqENE.js.map +1 -0
  49. package/dist/assets/{irohWeb-BSv_BWyG.js → irohWeb-C9ChbD-c.js} +57 -3
  50. package/dist/assets/{irohWeb-BSv_BWyG.js.map → irohWeb-C9ChbD-c.js.map} +1 -1
  51. package/dist/assets/{main-BbhfMTt8.js → main-4qE381KM.js} +194 -276
  52. package/dist/assets/main-4qE381KM.js.map +1 -0
  53. package/dist/assets/{mainline-9Vc3c3SA.js → mainline-DOwZDHVy.js} +2 -2
  54. package/dist/assets/{mainline-9Vc3c3SA.js.map → mainline-DOwZDHVy.js.map} +1 -1
  55. package/dist/assets/{networkReason-BncJ9KSM.js → networkReason-MInk1Y63.js} +3 -3
  56. package/dist/assets/{networkReason-BncJ9KSM.js.map → networkReason-MInk1Y63.js.map} +1 -1
  57. package/dist/assets/{nwc-QX3Yt1Sb.js → nwc-CHLWFV1R.js} +3 -3
  58. package/dist/assets/{nwc-QX3Yt1Sb.js.map → nwc-CHLWFV1R.js.map} +1 -1
  59. package/dist/assets/{nwcProvider-CzX3xH47.js → nwcProvider-BlkPOJen.js} +2 -2
  60. package/dist/assets/{nwcProvider-CzX3xH47.js.map → nwcProvider-BlkPOJen.js.map} +1 -1
  61. package/dist/assets/{ownDid-D8z5gwGI.js → ownDid-yXtY_1B5.js} +3 -3
  62. package/dist/assets/ownDid-yXtY_1B5.js.map +1 -0
  63. package/dist/assets/{profiles-MFtCmJwK.js → profiles-vbXHs0Mq.js} +40 -3
  64. package/dist/assets/profiles-vbXHs0Mq.js.map +1 -0
  65. package/dist/assets/{registry-PTtBMaYZ.js → registry-BN9r2pR4.js} +1 -1
  66. package/dist/assets/{registry-B2Dtnibo.js → registry-chCD0KWS.js} +5 -5
  67. package/dist/assets/registry-chCD0KWS.js.map +1 -0
  68. package/dist/assets/{resolve-ZxVzwFNA.js → resolve-Dtzogt2W.js} +2 -2
  69. package/dist/assets/{resolve-ZxVzwFNA.js.map → resolve-Dtzogt2W.js.map} +1 -1
  70. package/dist/assets/{restoredRows-BCRCjhdF.js → restoredRows-CRYwIx3g.js} +2 -2
  71. package/dist/assets/{restoredRows-BCRCjhdF.js.map → restoredRows-CRYwIx3g.js.map} +1 -1
  72. package/dist/assets/{buttons-CuRfKnPI.js → secretGuard-CSVNxXVW.js} +80 -330
  73. package/dist/assets/secretGuard-CSVNxXVW.js.map +1 -0
  74. package/dist/assets/secretGuard-Q2BKq0q0.js +2 -0
  75. package/dist/assets/{server-Dw1o8z1o.js → server-BZnsm5X5.js} +1749 -335
  76. package/dist/assets/server-BZnsm5X5.js.map +1 -0
  77. package/dist/assets/{src-BD8RBVEp.js → src-DZagapGt.js} +1043 -197
  78. package/dist/assets/src-DZagapGt.js.map +1 -0
  79. package/dist/assets/{sshForges-DWrESWkK.js → sshForges-BkTgy5rx.js} +16 -9
  80. package/dist/assets/{sshForges-DWrESWkK.js.map → sshForges-BkTgy5rx.js.map} +1 -1
  81. package/dist/assets/{translate-D1uP0q32.js → translate-B9SMd6uf.js} +8 -7
  82. package/dist/assets/translate-B9SMd6uf.js.map +1 -0
  83. package/dist/assets/{usdt-DhVN8geQ.js → usdt-BU4ezonh.js} +3 -3
  84. package/dist/assets/{usdt-DhVN8geQ.js.map → usdt-BU4ezonh.js.map} +1 -1
  85. package/dist/assets/{words-DdXPkB3n.js → words-jYy7lTcb.js} +4 -2
  86. package/dist/assets/words-jYy7lTcb.js.map +1 -0
  87. package/dist/ghostly.mjs +1 -1
  88. package/package.json +1 -1
  89. package/dist/assets/api-DFCgr6RH.js.map +0 -1
  90. package/dist/assets/apiKit-CCavJJcl.js.map +0 -1
  91. package/dist/assets/apps-DmxEG147.js.map +0 -1
  92. package/dist/assets/buttons-CuRfKnPI.js.map +0 -1
  93. package/dist/assets/buttons-De3LPdSG.js +0 -2
  94. package/dist/assets/daemonProof-DtrL5lE5.js +0 -236
  95. package/dist/assets/daemonProof-DtrL5lE5.js.map +0 -1
  96. package/dist/assets/endpoint-BdaeBw2L.js.map +0 -1
  97. package/dist/assets/fileBytesIdb-DZcESfTt.js +0 -2
  98. package/dist/assets/groupFiles-FXel6zIc.js.map +0 -1
  99. package/dist/assets/idb-BkOJES5_.js.map +0 -1
  100. package/dist/assets/main-BbhfMTt8.js.map +0 -1
  101. package/dist/assets/ownDid-D8z5gwGI.js.map +0 -1
  102. package/dist/assets/profiles-MFtCmJwK.js.map +0 -1
  103. package/dist/assets/registry-B2Dtnibo.js.map +0 -1
  104. package/dist/assets/server-Dw1o8z1o.js.map +0 -1
  105. package/dist/assets/src-BD8RBVEp.js.map +0 -1
  106. package/dist/assets/translate-D1uP0q32.js.map +0 -1
  107. package/dist/assets/words-DdXPkB3n.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buttons-BxIThdg9.js","names":["goesOnIn"],"sources":["../../src/waits.ts","../../src/buttons.ts"],"sourcesContent":["import type { StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { node, type ApiContext } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { goesOn as goesOnIn } from \"./waitNotice\";\n\n/*\n * Waiting on what a command sent (WISP 1100): a message's delivery, an edit's confirmation, a group frame taken by an\n * edge. Shared by the chat, group and status card methods.\n */\n\nconst DELIVERY_RANK: Record<string, number> = { sending: 0, waiting: 1, queued: 1, held: 2, sent: 2, delivered: 3 };\n\n/**\n * What a timed-out wait says of what happens next: a daemon goes on, a one-shot's profile closes now. A one-shot's\n * `edit` and `group edit` said \"while this profile is online\" too, as it was about to leave. Ctrl-C says the same.\n */\nconst goesOn = (ctx: ApiContext) => goesOnIn(ctx.mode);\n\n/** Waits until the contact confirmed the latest edit of one of my messages (it is no longer pending). */\nexport async function waitForEdit(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<StoredMessage> {\n const until = Date.now() + ms;\n for (;;) {\n const message = await node(ctx).getMessage(chat, messageId);\n if (!message) throw new CliError(\"not_found\", `No message ${messageId} in this chat`);\n if (!message.edit?.pending) return message;\n if (Date.now() >= until) throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: the contact has not confirmed the edit yet (it needs a live chat and a contact's app that shows edits). It ${goesOn(ctx)}`, { messageId, edits: message.edit.seq });\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/** Waits until the contact confirmed my removal of a message, which is already gone here. */\nexport async function waitForRemoval(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<void> {\n const until = Date.now() + ms;\n while (node(ctx).removalPending({ linkId: chat, messageId })) {\n if (Date.now() >= until) throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: the message is gone here and the contact has not confirmed yet. Its removal ${goesOn(ctx)}`, { messageId });\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * Waits until an edge took my group message, or its edit number `edit` (WISP 902: a group has no receipts, so this is\n * as far as the author sees): a member's edge in a private group, an edge to one of my hubs in a community.\n */\nexport async function waitForGroupFrame(ctx: ApiContext, groupId: string, messageId: string, edit: number | undefined, ms: number): Promise<number> {\n const until = Date.now() + ms;\n for (;;) {\n const taken = node(ctx).groupTaken({ groupId, messageId, ...(edit ? { edit } : {}) });\n if (taken > 0) return taken;\n if (Date.now() >= until) throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: no member's edge took it yet (it stays in the group and goes when one opens). It ${goesOn(ctx)}`, { messageId, ...(edit ? { edits: edit } : {}) });\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * A one-shot whose text went over the live link waits this long for its receipt before it leaves (`waitForMessage`).\n * Left at `sent`, the engine stopping took the text for unconfirmed, the next start sent it again on the DHT, and that\n * copy took the chat's one DHT text awaiting a receipt: a script's next one-shot send waited 30 s behind it, every 5-8\n * messages, and the last text showed \"Connection closed before receipt\" though the contact had it (agents#1640).\n */\nexport const ONE_SHOT_RECEIPT_MS = 2_000;\n\n/**\n * Waits until the contact confirmed my reaction or pin in a 1:1 chat (WISP 401): until `pending` no longer finds it in\n * what the contact has not confirmed (`chatUnconfirmed`). It goes on the live session, a reaction also on the DHT\n * envelopes; one not confirmed in time is kept and said again.\n */\nexport async function waitForConfirmed(ctx: ApiContext, chat: string, what: \"reaction\" | \"pin\", pending: (left: { reactions: number[]; pin: number | null }) => boolean, ms: number): Promise<void> {\n const until = Date.now() + ms;\n while (pending(node(ctx).chatUnconfirmed({ linkId: chat }))) {\n if (Date.now() >= until) throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: the contact has not confirmed the ${what} yet. It is kept here and ${goesOn(ctx)}`, { chat });\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * Waits until a message of mine reached `target` (`sent`: on its way to the contact; `delivered`: acknowledged). A\n * one-shot's text sent over the live link waits a moment more for its receipt (`ONE_SHOT_RECEIPT_MS`).\n */\nexport async function waitForMessage(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const reached = await waitForDelivery(ctx, chat, messageId, target, ms);\n if (ctx.mode !== \"one-shot\" || target !== \"sent\" || reached.delivery !== \"sent\" || reached.via !== \"datalink\") return reached;\n return waitForDelivery(ctx, chat, messageId, \"delivered\", ONE_SHOT_RECEIPT_MS).catch(async () => (await node(ctx).getMessage(chat, messageId)) ?? reached);\n}\n\nasync function waitForDelivery(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const want = DELIVERY_RANK[target];\n const look = (message: StoredMessage | undefined) => {\n if (!message) return undefined;\n const delivery = message.delivery ?? \"sent\";\n if (delivery === \"failed\") throw new CliError(\"engine\", message.deliveryError ?? \"The message could not be sent\", { messageId, delivery });\n return (DELIVERY_RANK[delivery] ?? 0) >= want ? message : undefined;\n };\n return new Promise<StoredMessage>((resolve, reject) => {\n let settled = false;\n const finish = (error: unknown, message?: StoredMessage) => {\n if (settled) return;\n settled = true; clearTimeout(timer); off();\n if (error) reject(error); else resolve(message!);\n };\n const check = (last = false) => void node(ctx).getMessage(chat, messageId).then((message) => {\n try {\n const done = look(message);\n if (done) finish(null, done);\n else if (last) finish(new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: the message is ${message?.delivery ?? \"not sent yet\"} and ${goesOn(ctx)}`, { messageId, delivery: message?.delivery ?? null }));\n } catch (error) { finish(error); }\n }, finish);\n const timer = setTimeout(() => check(true), ms);\n // Any event naming the message: a message first seen already delivered comes as `message.sent`, never as\n // `message.delivery`. Listening before the first read leaves no gap for a change to slip through.\n const off = ctx.hub.onEvent((event: GhostlyEvent) => {\n if (event.chat === chat && (event.messageId === messageId || (event.message as { id?: string } | undefined)?.id === messageId)) check();\n });\n check();\n });\n}\n","import { BUTTONS_CAPABILITY, BUTTON_STYLES, STATUS_CARD_LIMITS, buttonLabelClash, checkStatusCard, randomBytes, toBase64Url, type ButtonsCard } from \"@ghostly/core\";\nimport type { LinkView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport type { Parsed } from \"./args\";\nimport { bool, chatOrGroup, messageOf, node, num, oneOf, str, type Method, type Params } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport { findSecret, secretWords } from \"./secretGuard\";\nimport { waitForEdit, waitForGroupFrame, waitForMessage } from \"./waits\";\n\n/*\n * Message buttons (WISP 406 · Message Buttons), the bot's side: a message whose text is the question, with up to six\n * buttons under it (`send --button yes:Yes`). A press comes back as a reply whose text is the button's label; the\n * engine marks it (`press`) and `listen` says `button.pressed`. `button update` then shows the answer (`chosen`) and\n * closes the buttons, by editing the message with the same buttons.\n */\n\n/**\n * `--button id:Label` (again for each, 1 to 6), `--style id=primary|neutral|danger`, `--once` and `--id`, as the\n * method's parameters: `buttons` and `buttonsId`. Nothing when no `--button` is given. The label may hold colons: the\n * id ends at the first one. An id given twice, two labels that read the same (ignoring case and spaces at the ends), a\n * label that is another button's id, or a style not listed are a usage error here, before the profile opens; other\n * bounds (ids, labels, how many) are the card's, checked when it is sent.\n */\nexport function buttonsOf(options: Parsed[\"options\"]): { buttons: Record<string, unknown>[]; buttonsId?: string } | undefined {\n const given = Array.isArray(options.button) ? options.button as string[] : [];\n if (!given.length) {\n for (const flag of [\"style\", \"once\", \"id\"] as const)\n if (options[flag] !== undefined) throw new CliError(\"usage\", `--${flag} goes with --button id:Label`);\n return undefined;\n }\n const buttons: Record<string, unknown>[] = given.map((value) => {\n const colon = value.indexOf(\":\");\n if (colon < 1 || colon === value.length - 1) throw new CliError(\"usage\", `--button takes id:Label, like yes:Yes, not ${JSON.stringify(value)}`);\n return { id: value.slice(0, colon), label: value.slice(colon + 1).trim() };\n });\n const twice = buttons.findIndex((button, at) => buttons.findIndex((other) => other.id === button.id) !== at);\n if (twice !== -1) throw new CliError(\"usage\", `--button ${JSON.stringify(given[twice])} repeats the id ${JSON.stringify(buttons[twice].id)}: each button takes its own`);\n // Two buttons a typed answer could not tell apart: the same label, or a label that is another's id (ignoring case).\n const clash = buttonLabelClash(buttons);\n if (clash) {\n const [at, other] = [JSON.stringify(given[clash.at]), JSON.stringify(given[clash.with])];\n throw new CliError(\"usage\", clash.kind === \"label\"\n ? `--button ${at} repeats the label of --button ${other} (ignoring case and spaces): a typed answer could not tell them apart`\n : `--button ${at} has a label that is the id of --button ${other}: a typed answer could not tell them apart`);\n }\n for (const value of Array.isArray(options.style) ? options.style as string[] : []) {\n const eq = value.indexOf(\"=\");\n const button = eq > 0 ? buttons.find((b) => b.id === value.slice(0, eq)) : undefined;\n if (!button) throw new CliError(\"usage\", `--style takes id=primary|neutral|danger for one of the buttons, not ${JSON.stringify(value)}`);\n const style = value.slice(eq + 1);\n if (!(BUTTON_STYLES as readonly string[]).includes(style)) throw new CliError(\"usage\", `--style ${JSON.stringify(value)}: a button's style is ${BUTTON_STYLES.join(\", \")}`);\n button.style = style;\n }\n if (options.once === true) for (const button of buttons) button.once = true;\n return { buttons, ...(options.id !== undefined && { buttonsId: String(options.id) }) };\n}\n\n/** A buttons card checked by the sender's rule, or a `bad_request` that says what is wrong. */\nfunction checked(card: Record<string, unknown>): ButtonsCard {\n const result = checkStatusCard(card);\n if (\"error\" in result) throw new CliError(\"bad_request\", `Buttons: ${result.error}`, { card });\n return result.card as ButtonsCard;\n}\n\n/**\n * The card a send's `buttons` (and `buttonsId`) make, or undefined when it names none. `buttons` is a list of\n * `{id, label, style?, once?}`; the id of the question is made up (`ask-…`) unless given.\n */\nexport function buttonsCard(params: Params): ButtonsCard | undefined {\n const buttons = params.buttons;\n if (buttons === undefined || buttons === null) {\n if (params.buttonsId !== undefined) throw new CliError(\"bad_request\", \"buttonsId goes with buttons\");\n return undefined;\n }\n if (!Array.isArray(buttons)) throw new CliError(\"bad_request\", \"buttons must be a list of {id, label, style?, once?}\");\n const id = str(params, \"buttonsId\") ?? `ask-${toBase64Url(randomBytes(6))}`;\n return checked({ kind: \"buttons\", id, buttons });\n}\n\n/** Whether a 1:1 contact's app shows and presses buttons: null until its app said what it offers. */\nexport function pressable(link: LinkView): boolean | null {\n const peer = link.sessionOffers?.peer;\n return peer ? peer.includes(BUTTONS_CAPABILITY) : null;\n}\n\n/** The message of mine with buttons that `button update` names, by its id here (or the id both sides know). */\nfunction buttonsMessage(message: StoredMessage | undefined, ref: string, group: boolean): StoredMessage & { card: ButtonsCard } {\n if (!message) throw new CliError(\"not_found\", `No message ${JSON.stringify(ref)} of yours in this ${group ? \"group\" : \"chat\"}: the messageId send gave`);\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons: send one with send --button id:Label\");\n return message as StoredMessage & { card: ButtonsCard };\n}\n\n/**\n * `button update`: the answer shown on a question's buttons (`chosen`), the buttons closed (`close`), or a new text\n * (`text`), by editing the message with the same buttons. What is not given stays as it was.\n */\nasync function updateButtons(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const chosen = str(params, \"chosen\");\n const close = bool(params, \"close\");\n const newText = str(params, \"text\");\n if (chosen === undefined && !close && newText === undefined) throw new CliError(\"bad_request\", \"Nothing to update: give chosen, close or text\");\n // A new text is a message like any other: the same guard as `send` and `edit`.\n if (newText !== undefined && !bool(params, \"force\")) {\n const secret = findSecret(newText);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; update with --force if you mean to`, { kind: secret.kind });\n }\n const message = buttonsMessage(await messageOf(ctx, target.linkId, ref, (m) => m.sender === \"me\"), ref, target.group);\n if ((message.edit?.seq ?? 0) >= STATUS_CARD_LIMITS.edits)\n throw new CliError(\"refused\", `This message took ${STATUS_CARD_LIMITS.edits} updates, the most one takes: ask again with a new send`, { messageId: message.id, edits: message.edit!.seq });\n const before = message.card;\n // Said here, with the buttons it has, as a press says it: the card's own check names only the field.\n if (chosen !== undefined && !before.buttons.some((b) => b.id === chosen))\n throw new CliError(\"bad_request\", `That message has no button ${JSON.stringify(chosen)}; its buttons: ${before.buttons.map((b) => b.id).join(\", \")}`, { card: before });\n const card = checked({ ...before, ...(chosen !== undefined && { chosen }), ...((close || before.closed) && { closed: true }) });\n const text = newText ?? message.text;\n const wait = oneOf(params, \"wait\", target.group ? [\"none\", \"sent\"] as const : [\"none\", \"confirmed\"] as const, \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).editMessage({ linkId: target.linkId, messageId: message.id, text, card });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n let edited = await node(ctx).getMessage(target.linkId, message.id);\n if (wait === \"confirmed\" && edited?.edit?.pending) edited = await waitForEdit(ctx, target.linkId, message.id, ms);\n const edges = wait === \"sent\" && edited?.edit ? await waitForGroupFrame(ctx, target.id, message.id, edited.edit.seq, ms) : undefined;\n return {\n [target.group ? \"group\" : \"chat\"]: target.id, buttons: card.id, messageId: message.id, card, edits: edited?.edit?.seq ?? 0,\n ...(target.group ? { ...(edges !== undefined && { edges }) } : { confirmed: !!edited && !edited.edit?.pending }),\n };\n}\n\n/**\n * `button press`: the other side of a question, as the app's tap: a press on a button of someone else's message, by\n * its id here (or the id both sides know). The engine sends a reply whose text is the button's label, and refuses what\n * an app would: a button the message does not have, closed buttons, a second answer past `once`, a second press\n * within a second. A one-shot in a chat waits until the press went out, as `send` does.\n */\nasync function pressButton(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const buttonId = str(params, \"button\", true);\n const where = target.group ? \"group\" : \"chat\";\n const message = await messageOf(ctx, target.linkId, ref, (m) => m.sender !== \"me\");\n if (!message) throw new CliError(\"not_found\", `No message ${JSON.stringify(ref)} from someone else in this ${where}: the id its event or history gave`);\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons\");\n const button = message.card.buttons.find((b) => b.id === buttonId);\n if (!button) throw new CliError(\"not_found\", `That message has no button ${JSON.stringify(buttonId)}; its buttons: ${message.card.buttons.map((b) => b.id).join(\", \")}`);\n const wait = target.group\n ? oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\")\n : oneOf(params, \"wait\", [\"none\", \"sent\", \"delivered\"] as const, ctx.mode === \"one-shot\" ? \"sent\" : \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).pressButton({ linkId: target.linkId, messageId: message.id, buttonId });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error, result.paced ? { paced: true } : undefined);\n const replyId = result.messageId ?? null;\n const answer = { [where]: target.id, messageId: message.id, button: button.id, label: button.label, replyId };\n if (!replyId) return answer;\n if (target.group) {\n const edges = wait === \"sent\" ? await waitForGroupFrame(ctx, target.id, replyId, undefined, ms) : node(ctx).groupTaken({ groupId: target.id, messageId: replyId });\n return { ...answer, edges };\n }\n const reply = wait === \"none\" ? await node(ctx).getMessage(target.linkId, replyId) : await waitForMessage(ctx, target.linkId, replyId, wait, ms);\n return { ...answer, delivery: reply?.delivery ?? null };\n}\n\nexport const BUTTON_METHODS: Record<string, Method> = {\n /** WISP 406 · Message Buttons: a press on a button of someone else's message, as the app's tap. */\n \"button.press\": pressButton,\n /** WISP 406 · Message Buttons: the answer chosen on a question of mine, its buttons closed, or its text changed. */\n \"button.update\": updateButtons,\n};\n"],"mappings":";;;;;;AAWA,IAAM,gBAAwC;CAAE,SAAS;CAAG,SAAS;CAAG,QAAQ;CAAG,MAAM;CAAG,MAAM;CAAG,WAAW;AAAE;;;;;AAMlH,IAAM,UAAU,QAAoBA,SAAS,IAAI,IAAI;;AAGrD,eAAsB,YAAY,KAAiB,MAAc,WAAmB,IAAoC;CACtH,MAAM,QAAQ,KAAK,IAAI,IAAI;CAC3B,SAAS;EACP,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,CAAC,WAAW,MAAM,SAAS;EAC1D,IAAI,CAAC,SAAS,MAAM,IAAI,SAAS,aAAa,cAAc,UAAU,cAAc;EACpF,IAAI,CAAC,QAAQ,MAAM,SAAS,OAAO;EACnC,IAAI,KAAK,IAAI,KAAK,OAAO,MAAM,IAAI,SAAS,WAAW,mBAAmB,KAAK,MAAM,KAAK,GAAI,EAAE,iHAAiH,OAAO,GAAG,KAAK;GAAE;GAAW,OAAO,QAAQ,KAAK;EAAI,CAAC;EACtQ,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;CACzD;AACF;;AAGA,eAAsB,eAAe,KAAiB,MAAc,WAAmB,IAA2B;CAChH,MAAM,QAAQ,KAAK,IAAI,IAAI;CAC3B,OAAO,KAAK,GAAG,CAAC,CAAC,eAAe;EAAE,QAAQ;EAAM;CAAU,CAAC,GAAG;EAC5D,IAAI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AK,GAAG,CAAC,CAAC,YAAY;EAAE,QAAQ,OAAO;EAAQ,WAAW,QAAQ;EAAI;CAAS,CAAC;CACrG,IAAI,OAAO,OAAO,MAAM,IAAI,SAAS,OAAO,UAAU,YAAY,eAAe,OAAO,OAAO,OAAO,QAAQ,EAAE,OAAO,KAAK,IAAI,KAAA,CAAS;CACzI,MAAM,UAAU,OAAO,aAAa;CACpC,MAAM,SAAS;GAAG,QAAQ,OAAO;EAAI,WAAW,QAAQ;EAAI,QAAQ,OAAO;EAAI,OAAO,OAAO;EAAO;CAAQ;CAC5G,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI,OAAO,OAAO;EAChB,MAAM,QAAQ,SAAS,SAAS,MAAM,kBAAkB,KAAK,OAAO,IAAI,SAAS,KAAA,GAAW,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC,WAAW;GAAE,SAAS,OAAO;GAAI,WAAW;EAAQ,CAAC;EACjK,OAAO;GAAE,GAAG;GAAQ;EAAM;CAC5B;CACA,MAAM,QAAQ,SAAS,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,WAAW,OAAO,QAAQ,OAAO,IAAI,MAAM,eAAe,KAAK,OAAO,QAAQ,SAAS,MAAM,EAAE;CAC/I,OAAO;EAAE,GAAG;EAAQ,UAAU,OAAO,YAAY;CAAK;AACxD;AAEA,IAAa,iBAAyC;;CAEpD,gBAAgB;;CAEhB,iBAAiB;AACnB"}
@@ -0,0 +1,2 @@
1
+ import { r as buttonsOf } from "./buttons-BxIThdg9.js";
2
+ export { buttonsOf };
@@ -0,0 +1,473 @@
1
+ import { t as CliError } from "./errors-R4S2SAEM.js";
2
+ import { b as ownSocket, d as lockPath } from "./profiles-vbXHs0Mq.js";
3
+ import { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
6
+ import { connect } from "node:net";
7
+ import { createInterface } from "node:readline";
8
+ var CALL_RATES = [
9
+ 8e3,
10
+ 12e3,
11
+ 16e3,
12
+ 24e3,
13
+ 48e3
14
+ ];
15
+ var DEFAULT_RATE = 48e3;
16
+ var frameSamples = (rate) => rate * 20 / 1e3;
17
+ var frameBytes = (rate) => frameSamples(rate) * 2;
18
+ var bytesToMs = (rate, bytes) => Math.round(bytes / 2 / rate * 1e3);
19
+ function isCallRate(value) {
20
+ return CALL_RATES.includes(value);
21
+ }
22
+ /** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */
23
+ var MAX_QUEUE_MS = 3e5;
24
+ /**
25
+ * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and
26
+ * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.
27
+ */
28
+ var PlaybackQueue = class {
29
+ rate;
30
+ now;
31
+ chunks = [];
32
+ head = 0;
33
+ length = 0;
34
+ lastPush = 0;
35
+ frame;
36
+ max;
37
+ silence;
38
+ /** Bytes dropped because the queue was full, since the start. */
39
+ dropped = 0;
40
+ constructor(rate, now = Date.now, maxMs = MAX_QUEUE_MS) {
41
+ this.rate = rate;
42
+ this.now = now;
43
+ this.frame = frameBytes(rate);
44
+ this.max = Math.floor(rate * maxMs / 1e3) * 2;
45
+ this.silence = Buffer.alloc(this.frame);
46
+ }
47
+ /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */
48
+ push(chunk) {
49
+ if (!chunk.length) return 0;
50
+ this.lastPush = this.now();
51
+ const room = this.max - this.length;
52
+ const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));
53
+ const lost = chunk.length - kept.length;
54
+ this.dropped += lost;
55
+ if (kept.length) {
56
+ this.chunks.push(Buffer.from(kept));
57
+ this.length += kept.length;
58
+ }
59
+ return lost;
60
+ }
61
+ /** Queued audio, in milliseconds (whole frames and a partial one). */
62
+ get queuedMs() {
63
+ return bytesToMs(this.rate, this.length - this.length % 2);
64
+ }
65
+ /** One frame to send now, and whether it is the program's audio or silence. */
66
+ next() {
67
+ if (this.length >= this.frame) return {
68
+ frame: this.take(this.frame),
69
+ silent: false
70
+ };
71
+ const whole = this.length - this.length % 2;
72
+ if (whole > 0 && this.now() - this.lastPush >= 60) {
73
+ const frame = Buffer.alloc(this.frame);
74
+ this.take(whole).copy(frame);
75
+ return {
76
+ frame,
77
+ silent: false
78
+ };
79
+ }
80
+ return {
81
+ frame: this.silence,
82
+ silent: true
83
+ };
84
+ }
85
+ /** Drops everything queued; returns how much, in milliseconds. */
86
+ flush() {
87
+ const ms = this.queuedMs;
88
+ this.chunks = [];
89
+ this.head = 0;
90
+ this.length = 0;
91
+ return ms;
92
+ }
93
+ /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */
94
+ skip(ms) {
95
+ const frames = Math.min(Math.floor(ms / 20), Math.floor(this.length / this.frame));
96
+ if (frames > 0) this.take(frames * this.frame);
97
+ return Math.max(0, frames) * 20;
98
+ }
99
+ take(bytes) {
100
+ const out = Buffer.allocUnsafe(bytes);
101
+ let filled = 0;
102
+ while (filled < bytes) {
103
+ const chunk = this.chunks[0];
104
+ const n = Math.min(bytes - filled, chunk.length - this.head);
105
+ chunk.copy(out, filled, this.head, this.head + n);
106
+ filled += n;
107
+ this.head += n;
108
+ if (this.head === chunk.length) {
109
+ this.chunks.shift();
110
+ this.head = 0;
111
+ }
112
+ }
113
+ this.length -= bytes;
114
+ return out;
115
+ }
116
+ };
117
+ //#endregion
118
+ //#region src/daemonProof.ts
119
+ /**
120
+ * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).
121
+ * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine
122
+ * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random
123
+ * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a
124
+ * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.
125
+ *
126
+ * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the
127
+ * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process
128
+ * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first
129
+ * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),
130
+ * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):
131
+ * a client that writes nothing to it cannot be impersonated.
132
+ */
133
+ var HELLO = "daemon.hello";
134
+ function daemonSecretPath(dir) {
135
+ return join(dir, "daemon.secret");
136
+ }
137
+ /** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */
138
+ function proof(secret, role, nonce) {
139
+ return createHmac("sha256", secret).update(`ghostly-${role}:${nonce}`).digest("hex");
140
+ }
141
+ function newNonce() {
142
+ return randomBytes(16).toString("hex");
143
+ }
144
+ /**
145
+ * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is
146
+ * an error, not something written through). The one a daemon before it left is removed first: whoever could have
147
+ * read that one learns nothing about this one.
148
+ */
149
+ function newDaemonSecret(dir) {
150
+ const file = daemonSecretPath(dir);
151
+ rmSync(file, { force: true });
152
+ const secret = randomBytes(32);
153
+ const fd = openSync(file, "wx", 384);
154
+ try {
155
+ writeSync(fd, secret.toString("hex") + "\n");
156
+ } finally {
157
+ closeSync(fd);
158
+ }
159
+ return secret;
160
+ }
161
+ /** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */
162
+ function removeDaemonSecret(dir) {
163
+ rmSync(daemonSecretPath(dir), { force: true });
164
+ }
165
+ /** The daemon's first line on every connection, before it has read anything. */
166
+ function greeting(secret, pid = process.pid, at = Date.now()) {
167
+ return { greeting: {
168
+ pid,
169
+ at,
170
+ proof: proof(secret, "greeting", `${pid}:${at}`)
171
+ } };
172
+ }
173
+ /**
174
+ * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made
175
+ * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may
176
+ * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate
177
+ * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,
178
+ * unless a process this user may signal took that pid within the window.
179
+ */
180
+ function provesGreeting(secret, dir, message, now = Date.now()) {
181
+ const given = message?.greeting;
182
+ if (!given || !Number.isSafeInteger(given.pid) || given.pid <= 0 || !Number.isSafeInteger(given.at)) return false;
183
+ if (typeof given.proof !== "string" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;
184
+ const { pid, at } = given;
185
+ if (Math.abs(now - at) > 1e4) return false;
186
+ if (!timingSafeEqual(Buffer.from(given.proof, "hex"), Buffer.from(proof(secret, "greeting", `${pid}:${at}`), "hex"))) return false;
187
+ return holdsProfile(dir, pid);
188
+ }
189
+ /**
190
+ * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a
191
+ * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is
192
+ * busy (its event loop held by one long task), not something else on its socket: the client waits for it.
193
+ */
194
+ function daemonOfThisRelease(dir) {
195
+ if (!readDaemonSecret(dir)) return false;
196
+ let pid;
197
+ try {
198
+ pid = Number(readFileSync(lockPath(dir), "utf8").trim());
199
+ } catch {
200
+ return false;
201
+ }
202
+ return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);
203
+ }
204
+ function holdsProfile(dir, pid) {
205
+ try {
206
+ if (readFileSync(lockPath(dir), "utf8").trim() !== String(pid)) return false;
207
+ process.kill(pid, 0);
208
+ return true;
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+ /**
214
+ * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's
215
+ * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the
216
+ * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.
217
+ */
218
+ function readDaemonSecret(dir) {
219
+ const file = daemonSecretPath(dir);
220
+ try {
221
+ const info = lstatSync(file);
222
+ if (!info.isFile()) return null;
223
+ if (process.platform !== "win32" && (process.getuid && info.uid !== process.getuid() || (info.mode & 63) !== 0)) return null;
224
+ const text = readFileSync(file, "utf8").trim();
225
+ return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, "hex") : null;
226
+ } catch {
227
+ return null;
228
+ }
229
+ }
230
+ /** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */
231
+ function provesDaemon(secret, nonce, answer) {
232
+ const given = answer?.proof;
233
+ if (typeof given !== "string" || !/^[0-9a-f]{64}$/.test(given)) return false;
234
+ return timingSafeEqual(Buffer.from(given, "hex"), Buffer.from(proof(secret, "daemon", nonce), "hex"));
235
+ }
236
+ //#endregion
237
+ //#region src/client.ts
238
+ /** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */
239
+ var HELLO_ID = "hello";
240
+ /**
241
+ * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it
242
+ * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release
243
+ * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything
244
+ * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an
245
+ * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.
246
+ */
247
+ var GREETING_MS = 2e3;
248
+ /** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */
249
+ var MAX_LINE = 16777216;
250
+ /** The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). */
251
+ function notTheDaemon(socket) {
252
+ return new CliError("refused", `What answers on ${socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \`ghostly daemon restart\` starts this one's`, { reason: "not-the-daemon" });
253
+ }
254
+ function isNotTheDaemon(error) {
255
+ return error instanceof CliError && error.code === "refused" && error.details?.reason === "not-the-daemon";
256
+ }
257
+ /**
258
+ * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`
259
+ * means no daemon answers there: a one-shot command runs the profile itself.
260
+ *
261
+ * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the
262
+ * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read
263
+ * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a
264
+ * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then
265
+ * every call waits, under its own deadline, and a listener that does not prove both gets every call refused
266
+ * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.
267
+ */
268
+ var DaemonClient = class {
269
+ socket;
270
+ address;
271
+ nextId = 1;
272
+ pending = /* @__PURE__ */ new Map();
273
+ eventListener = null;
274
+ closedListener = null;
275
+ /** While paused: the events of the chunk already read, given to the listener on resume. */
276
+ held = null;
277
+ greeted = false;
278
+ verified = false;
279
+ refusal = null;
280
+ ready;
281
+ settle;
282
+ constructor(socket, address, greetingMs = GREETING_MS) {
283
+ this.socket = socket;
284
+ this.address = address;
285
+ this.ready = new Promise((resolve, reject) => {
286
+ this.settle = {
287
+ resolve,
288
+ reject
289
+ };
290
+ });
291
+ this.ready.catch(() => {});
292
+ const nonce = newNonce();
293
+ const waitedTooLong = setTimeout(() => {
294
+ if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse();
295
+ }, greetingMs);
296
+ waitedTooLong.unref?.();
297
+ const lines = createInterface({
298
+ input: socket,
299
+ crlfDelay: Infinity
300
+ });
301
+ lines.on("error", () => {});
302
+ lines.on("line", (line) => {
303
+ let message;
304
+ try {
305
+ message = JSON.parse(line);
306
+ } catch {
307
+ if (!this.greeted && !this.refusal) this.refuse();
308
+ return;
309
+ }
310
+ if (this.refusal) return;
311
+ if (!this.greeted) {
312
+ clearTimeout(waitedTooLong);
313
+ const secret = readDaemonSecret(this.address.dir);
314
+ if (!secret || !provesGreeting(secret, this.address.dir, message)) {
315
+ this.refuse();
316
+ return;
317
+ }
318
+ this.greeted = true;
319
+ if (socket.writableEnded || socket.destroyed) return;
320
+ socket.write(JSON.stringify({
321
+ id: HELLO_ID,
322
+ method: HELLO,
323
+ params: { nonce }
324
+ }) + "\n");
325
+ return;
326
+ }
327
+ if (!this.verified) {
328
+ if (message?.id !== HELLO_ID) return;
329
+ const secret = readDaemonSecret(this.address.dir);
330
+ if (!message.error && secret && provesDaemon(secret, nonce, message.result)) {
331
+ this.verified = true;
332
+ this.settle.resolve();
333
+ return;
334
+ }
335
+ this.refuse();
336
+ return;
337
+ }
338
+ if (message.event) {
339
+ if (this.held) this.held.push(message.event);
340
+ else this.eventListener?.(message.event);
341
+ return;
342
+ }
343
+ const waiting = typeof message.id === "number" ? this.pending.get(message.id) : void 0;
344
+ if (!waiting) return;
345
+ this.pending.delete(message.id);
346
+ if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));
347
+ else waiting.resolve(message.result);
348
+ });
349
+ socket.on("close", () => {
350
+ clearTimeout(waitedTooLong);
351
+ const why = this.refusal ?? new CliError("unavailable", "The daemon went away");
352
+ if (!this.verified) this.settle.reject(why);
353
+ for (const waiting of this.pending.values()) waiting.reject(why);
354
+ this.pending.clear();
355
+ this.closedListener?.();
356
+ });
357
+ socket.on("error", () => {});
358
+ }
359
+ refuse() {
360
+ this.refusal = notTheDaemon(this.address.socket);
361
+ this.settle.reject(this.refusal);
362
+ this.socket.destroy();
363
+ }
364
+ /**
365
+ * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits
366
+ * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,
367
+ * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).
368
+ *
369
+ * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,
370
+ * and the command answered "The daemon went away" (`unavailable`, read as try later) while the daemon ran on.
371
+ */
372
+ call(method, params = {}, { timeoutMs } = {}) {
373
+ if (this.socket.destroyed) return Promise.reject(this.refusal ?? new CliError("unavailable", "The daemon went away"));
374
+ const id = this.nextId++;
375
+ const line = JSON.stringify({
376
+ id,
377
+ method,
378
+ params
379
+ }) + "\n";
380
+ const bytes = Buffer.byteLength(line);
381
+ if (bytes > 16777216) return Promise.reject(new CliError("bad_request", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));
382
+ return new Promise((resolve, reject) => {
383
+ let timer;
384
+ if (timeoutMs !== void 0) {
385
+ timer = setTimeout(() => {
386
+ if (!this.pending.delete(id)) return;
387
+ reject(new CliError("timeout", `The daemon did not answer ${method} in ${timeoutMs / 1e3} s: \`ghostly daemon restart\` starts a fresh one`, { method }));
388
+ this.destroy();
389
+ }, timeoutMs);
390
+ timer.unref?.();
391
+ }
392
+ const settle = {
393
+ resolve: (value) => {
394
+ if (timer) clearTimeout(timer);
395
+ resolve(value);
396
+ },
397
+ reject: (error) => {
398
+ if (timer) clearTimeout(timer);
399
+ reject(error);
400
+ }
401
+ };
402
+ this.pending.set(id, settle);
403
+ this.ready.then(() => {
404
+ if (this.pending.has(id) && !this.socket.destroyed) this.socket.write(line);
405
+ }, (error) => {
406
+ if (this.pending.delete(id)) settle.reject(error);
407
+ });
408
+ });
409
+ }
410
+ /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */
411
+ async subscribe(since, listener, onClosed) {
412
+ this.eventListener = listener;
413
+ this.closedListener = onClosed ?? null;
414
+ return this.call("events.subscribe", since === void 0 ? {} : { since });
415
+ }
416
+ /**
417
+ * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no
418
+ * event reaches the listener until `resume`.
419
+ */
420
+ pause() {
421
+ if (this.held) return;
422
+ this.held = [];
423
+ this.socket.pause();
424
+ }
425
+ /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */
426
+ resume() {
427
+ const held = this.held;
428
+ if (!held) return;
429
+ this.held = null;
430
+ for (let i = 0; i < held.length; i++) {
431
+ this.eventListener?.(held[i]);
432
+ if (this.held) {
433
+ this.held.unshift(...held.slice(i + 1));
434
+ return;
435
+ }
436
+ }
437
+ this.socket.resume();
438
+ }
439
+ close() {
440
+ this.socket.end();
441
+ }
442
+ /** Closes at once: what the daemon still sends is not read. */
443
+ destroy() {
444
+ this.socket.destroy();
445
+ }
446
+ };
447
+ /**
448
+ * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives
449
+ * has written nothing yet; whether the listener is the daemon is known at the first call.
450
+ */
451
+ function connectDaemon(address, timeoutMs = 2e3, { greetingMs = GREETING_MS } = {}) {
452
+ const path = address.socket;
453
+ if (!ownSocket(path)) return Promise.resolve(null);
454
+ return new Promise((resolve) => {
455
+ const socket = connect(path);
456
+ const timer = setTimeout(() => {
457
+ socket.destroy();
458
+ resolve(null);
459
+ }, timeoutMs);
460
+ socket.once("connect", () => {
461
+ clearTimeout(timer);
462
+ resolve(new DaemonClient(socket, address, greetingMs));
463
+ });
464
+ socket.once("error", () => {
465
+ clearTimeout(timer);
466
+ resolve(null);
467
+ });
468
+ });
469
+ }
470
+ //#endregion
471
+ export { HELLO as a, proof as c, DEFAULT_RATE as d, PlaybackQueue as f, isCallRate as g, frameSamples as h, isNotTheDaemon as i, removeDaemonSecret as l, frameBytes as m, MAX_LINE as n, greeting as o, bytesToMs as p, connectDaemon as r, newDaemonSecret as s, DaemonClient as t, CALL_RATES as u };
472
+
473
+ //# sourceMappingURL=client-D5E1RQYB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-D5E1RQYB.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = Date.now, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n","import { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/** The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). */\nfunction notTheDaemon(socket: string): CliError {\n return new CliError(\"refused\", `What answers on ${socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n private readonly pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse();\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? new CliError(\"unavailable\", \"The daemon went away\");\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n private refuse(): void {\n this.refusal = notTheDaemon(this.address.socket);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? new CliError(\"unavailable\", \"The daemon went away\"));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => { if (this.pending.has(id) && !this.socket.destroyed) this.socket.write(line); },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OAAQ,GAAI;AAExG,SAAgB,WAAW,OAAmC;CAC5D,OAAO,WAAW,SAAS,KAAiB;AAC9C;;AAGA,IAAa,eAAe;;;;;AAY5B,IAAa,gBAAb,MAA2B;CAWJ;CAAiC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