@ghostlytools/cli 1.11.2 → 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 (83) hide show
  1. package/README.md +11 -10
  2. package/dist/assets/{api-BM3PsXbB.js → api-DBlaoz8i.js} +129 -37
  3. package/dist/assets/api-DBlaoz8i.js.map +1 -0
  4. package/dist/assets/{api-CtXgscmK.js → api-DgU4MZPD.js} +2 -2
  5. package/dist/assets/{apiKit-lCTQ0EBG.js → apiKit-DesObIDf.js} +4 -4
  6. package/dist/assets/{apiKit-lCTQ0EBG.js.map → apiKit-DesObIDf.js.map} +1 -1
  7. package/dist/assets/{appFetch-BKHy5H8J.js → appFetch-C8yZIq1e.js} +3 -3
  8. package/dist/assets/{appFetch-BKHy5H8J.js.map → appFetch-C8yZIq1e.js.map} +1 -1
  9. package/dist/assets/{apps-Do26w3c7.js → apps-DkMjDHML.js} +104 -33
  10. package/dist/assets/apps-DkMjDHML.js.map +1 -0
  11. package/dist/assets/{apps-DO_gAZgm.js → apps-rzxsjfBV.js} +1 -1
  12. package/dist/assets/{arkade-CZrLbz-M.js → arkade-CarKONmH.js} +2 -2
  13. package/dist/assets/{arkade-CZrLbz-M.js.map → arkade-CarKONmH.js.map} +1 -1
  14. package/dist/assets/{backup-j47AzDvG.js → backup-C0OJCJlM.js} +17 -25
  15. package/dist/assets/backup-C0OJCJlM.js.map +1 -0
  16. package/dist/assets/{backup-D21x1f5P.js → backup-CgWU7x0T.js} +1 -1
  17. package/dist/assets/buttons-Cco0Agfa.js +2 -0
  18. package/dist/assets/{buttons-CiGlBVBT.js → buttons-fZTEa_2i.js} +34 -5
  19. package/dist/assets/buttons-fZTEa_2i.js.map +1 -0
  20. package/dist/assets/{client-raIncVtF.js → client-Ibk3-e60.js} +2 -2
  21. package/dist/assets/{client-raIncVtF.js.map → client-Ibk3-e60.js.map} +1 -1
  22. package/dist/assets/{codec-DcG2AeyE.js → codec-DMpQqVSt.js} +2 -2
  23. package/dist/assets/{codec-DcG2AeyE.js.map → codec-DMpQqVSt.js.map} +1 -1
  24. package/dist/assets/{envelope-Dud6lntA.js → envelope-CvQVCGdf.js} +2 -2
  25. package/dist/assets/{envelope-Dud6lntA.js.map → envelope-CvQVCGdf.js.map} +1 -1
  26. package/dist/assets/{fedimintSdk-DRKRSw14.js → fedimintSdk-zV_5Qdqz.js} +2 -2
  27. package/dist/assets/{fedimintSdk-DRKRSw14.js.map → fedimintSdk-zV_5Qdqz.js.map} +1 -1
  28. package/dist/assets/{fixedHosts-CNX7QiUD.js → fixedHosts-6gKn8dp2.js} +3 -3
  29. package/dist/assets/{fixedHosts-CNX7QiUD.js.map → fixedHosts-6gKn8dp2.js.map} +1 -1
  30. package/dist/assets/{host-8RskzQgB.js → host-CYlIiY3r.js} +161 -32
  31. package/dist/assets/host-CYlIiY3r.js.map +1 -0
  32. package/dist/assets/{hyperdhtRelay-uAThbFub.js → hyperdhtRelay-CdsLcAhY.js} +2 -2
  33. package/dist/assets/{hyperdhtRelay-uAThbFub.js.map → hyperdhtRelay-CdsLcAhY.js.map} +1 -1
  34. package/dist/assets/{irohWeb-DGelfgDJ.js → irohWeb-D2IuloLL.js} +19 -12
  35. package/dist/assets/irohWeb-D2IuloLL.js.map +1 -0
  36. package/dist/assets/{main-BC33ooYg.js → main-C0PfjKTe.js} +109 -42
  37. package/dist/assets/main-C0PfjKTe.js.map +1 -0
  38. package/dist/assets/{mainline-DYrjsS1t.js → mainline-Cu61qcPS.js} +35 -18
  39. package/dist/assets/mainline-Cu61qcPS.js.map +1 -0
  40. package/dist/assets/{networkReason-n2oBs4by.js → networkReason-Dt7Yx_n4.js} +3 -3
  41. package/dist/assets/{networkReason-n2oBs4by.js.map → networkReason-Dt7Yx_n4.js.map} +1 -1
  42. package/dist/assets/{nwc-Do3VSlIS.js → nwc-CtZypDcv.js} +3 -3
  43. package/dist/assets/{nwc-Do3VSlIS.js.map → nwc-CtZypDcv.js.map} +1 -1
  44. package/dist/assets/{nwcProvider-Du5aWNIn.js → nwcProvider-DYHkd0iu.js} +2 -2
  45. package/dist/assets/{nwcProvider-Du5aWNIn.js.map → nwcProvider-DYHkd0iu.js.map} +1 -1
  46. package/dist/assets/{ownDid-CwwYu8s2.js → ownDid-CJ0ta8CL.js} +2 -2
  47. package/dist/assets/{ownDid-CwwYu8s2.js.map → ownDid-CJ0ta8CL.js.map} +1 -1
  48. package/dist/assets/{ownStatus-D7dB4zJB.js → ownStatus-D4HC6tNR.js} +11 -6
  49. package/dist/assets/{ownStatus-D7dB4zJB.js.map → ownStatus-D4HC6tNR.js.map} +1 -1
  50. package/dist/assets/{profiles-NyF5FnYF.js → profiles-Ccdq6Xf6.js} +3 -3
  51. package/dist/assets/{profiles-NyF5FnYF.js.map → profiles-Ccdq6Xf6.js.map} +1 -1
  52. package/dist/assets/{registry-C734VrO9.js → registry-CE0PpQAE.js} +1 -1
  53. package/dist/assets/{registry-DKDInr0A.js → registry-LvxsLJ5S.js} +18 -7
  54. package/dist/assets/registry-LvxsLJ5S.js.map +1 -0
  55. package/dist/assets/{resolve-3Tqh9AWQ.js → resolve-6kVu2DE5.js} +2 -2
  56. package/dist/assets/{resolve-3Tqh9AWQ.js.map → resolve-6kVu2DE5.js.map} +1 -1
  57. package/dist/assets/{server-B6PQ6iae.js → server-Q3VcNqGt.js} +245 -97
  58. package/dist/assets/server-Q3VcNqGt.js.map +1 -0
  59. package/dist/assets/{src-ChJijTlM.js → src-DjVj2ynY.js} +188 -42
  60. package/dist/assets/src-DjVj2ynY.js.map +1 -0
  61. package/dist/assets/{sshForges-Brf0fslM.js → sshForges-DeZ9cN9Q.js} +4 -3
  62. package/dist/assets/sshForges-DeZ9cN9Q.js.map +1 -0
  63. package/dist/assets/{translate-xLme9Rdh.js → translate-iQZq4TnY.js} +35 -14
  64. package/dist/assets/translate-iQZq4TnY.js.map +1 -0
  65. package/dist/assets/{usdt-CSU5KzTV.js → usdt-DnyTGdTX.js} +3 -3
  66. package/dist/assets/{usdt-CSU5KzTV.js.map → usdt-DnyTGdTX.js.map} +1 -1
  67. package/dist/ghostly.mjs +1 -1
  68. package/npm-shrinkwrap.json +2 -2
  69. package/package.json +1 -1
  70. package/dist/assets/api-BM3PsXbB.js.map +0 -1
  71. package/dist/assets/apps-Do26w3c7.js.map +0 -1
  72. package/dist/assets/backup-j47AzDvG.js.map +0 -1
  73. package/dist/assets/buttons-CiGlBVBT.js.map +0 -1
  74. package/dist/assets/buttons-D2l2bVCG.js +0 -2
  75. package/dist/assets/host-8RskzQgB.js.map +0 -1
  76. package/dist/assets/irohWeb-DGelfgDJ.js.map +0 -1
  77. package/dist/assets/main-BC33ooYg.js.map +0 -1
  78. package/dist/assets/mainline-DYrjsS1t.js.map +0 -1
  79. package/dist/assets/registry-DKDInr0A.js.map +0 -1
  80. package/dist/assets/server-B6PQ6iae.js.map +0 -1
  81. package/dist/assets/src-ChJijTlM.js.map +0 -1
  82. package/dist/assets/sshForges-Brf0fslM.js.map +0 -1
  83. package/dist/assets/translate-xLme9Rdh.js.map +0 -1
@@ -1,3 +1,3 @@
1
- import { M as startNamedChats, l as findGroup, s as findChat } from "./apiKit-lCTQ0EBG.js";
2
- import { a as hideStateSecrets, c as settingsInEffect, i as groupSendRefused, n as SETTABLE, o as mentionsFor, r as callApi, s as redactSettings, t as API_METHODS } from "./api-BM3PsXbB.js";
1
+ import { M as startNamedChats, l as findGroup, s as findChat } from "./apiKit-DesObIDf.js";
2
+ import { a as hideStateSecrets, c as settingsInEffect, i as groupSendRefused, n as SETTABLE, o as mentionsFor, r as callApi, s as redactSettings, t as API_METHODS } from "./api-DBlaoz8i.js";
3
3
  export { API_METHODS, SETTABLE, callApi, findChat, findGroup, groupSendRefused, hideStateSecrets, mentionsFor, redactSettings, settingsInEffect, startNamedChats };
@@ -1,4 +1,4 @@
1
- import { Q as groupName, Xn as INVITE_TAKEN, md as sanitizeDisplayText, vd as isZ32Key } from "./src-ChJijTlM.js";
1
+ import { $ as groupName, Zn as INVITE_TAKEN, _d as sanitizeDisplayText, xd as isZ32Key } from "./src-DjVj2ynY.js";
2
2
  import { t as CliError } from "./errors-Dt-ZnyOX.js";
3
3
  //#region src/apiKit.ts
4
4
  var node = (ctx) => ctx.runtime.server.node;
@@ -300,7 +300,7 @@ function findChatOrGroup(links, groups, ref) {
300
300
  * Starts the chats a call names (its `chat`, a forward's `to`) in a runtime that left the saved chats unstarted
301
301
  * (`RuntimeOptions.deferChats`). A ref that names no chat, or names a group, starts nothing: the call says so itself.
302
302
  */
303
- function startNamedChats(ctx, params) {
303
+ async function startNamedChats(ctx, params) {
304
304
  const { links, groups } = state(ctx);
305
305
  for (const ref of [params.chat, ...Array.isArray(params.to) ? params.to : []]) {
306
306
  if (typeof ref !== "string") continue;
@@ -310,7 +310,7 @@ function startNamedChats(ctx, params) {
310
310
  } catch {
311
311
  continue;
312
312
  }
313
- if ("link" in found) node(ctx).startDeferredChat(found.link.id);
313
+ if ("link" in found) await node(ctx).startDeferredChat(found.link.id);
314
314
  }
315
315
  }
316
316
  var chatOf = (ctx, params) => findChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
@@ -463,4 +463,4 @@ function waitForState(ctx, check, ms, what, stopping) {
463
463
  //#endregion
464
464
  export { sinceSeq as A, nobodyJoinedChat as C, oneShotWaits as D, oneOf as E, transportOffered as F, waitForState as I, startNamedChats as M, state as N, sentAt as O, str as P, nobodyJoined as S, num as T, messageOf as _, contactKeyOf as a, noFile as b, findChatOrGroup as c, groupNameOf as d, groupOf as f, list as g, keptForJoin as h, cleanName as i, somebodyJoined as j, shownName as k, findGroup as l, inviteTaken as m, chatOf as n, dhtOnly as o, groupPrefixed as p, chatOrGroup as r, findChat as s, bool as t, findOwnNamedChat as u, nameKey as v, node as w, noMessage as x, namedByThem as y };
465
465
 
466
- //# sourceMappingURL=apiKit-lCTQ0EBG.js.map
466
+ //# sourceMappingURL=apiKit-DesObIDf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"apiKit-lCTQ0EBG.js","names":[],"sources":["../../src/apiKit.ts"],"sourcesContent":["import { groupName, INVITE_TAKEN, isZ32Key, MAX_GROUP_NAME_BYTES, MAX_GROUP_NAME_LENGTH, sanitizeDisplayText, type PairedTransport } from \"@ghostly/core\";\nimport type { GhostlyNode } from \"@ghostly/browser/engine/node\";\nimport type { EngineState, GroupView, LinkView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { CliError } from \"./errors\";\nimport type { CallManager } from \"./calls/manager\";\nimport type { EventHub } from \"./events\";\nimport type { GroupAutoJoin } from \"./groupAuto\";\nimport type { Runtime } from \"./runtime/engine\";\n\n/**\n * The methods of the local control API (WISP 1100): the daemon answers them over its socket, and a one-shot\n * command calls them in its own process. Parameters come from JSON: every one is checked here.\n */\nexport interface ApiContext {\n runtime: Runtime;\n hub: EventHub;\n /** Voice calls (WISP 1100 § Calls). */\n calls: CallManager;\n /** Group invitations accepted by themselves (`group auto`). */\n groupAuto: GroupAutoJoin;\n /** How the host runs: a daemon stays; a one-shot leaves when its command is done. */\n mode: \"daemon\" | \"one-shot\";\n version: string;\n /** The daemon asks to stop (answered first). */\n stop?: () => void;\n /**\n * Aborted when the daemon stops (`serve().close`): a wait still open answers with what it knows (`waits.ts`), as a\n * timeout with `details.reason: \"daemon-stopped\"`, before the connections end.\n */\n stopping?: AbortSignal;\n /** The daemon is a `listen` that found none and runs the profile itself: a stop ends that listen too. */\n listen?: true;\n}\n\nexport type Params = Record<string, unknown>;\nexport type Method = (ctx: ApiContext, params: Params) => Promise<unknown>;\n\nexport const node = (ctx: ApiContext): GhostlyNode => ctx.runtime.server.node;\nexport const state = (ctx: ApiContext): EngineState => node(ctx).getState();\n\n/**\n * The time of a send the engine names its row after (`me_<timestamp>`: a file, a payment, a request), its own even\n * within one millisecond (a bot paying or sending several times at once over the socket, `file send` run in\n * parallel), or the chat keeps only one. One clock for all of them: they share the row names. A file's resend after a\n * drop finds its row by it, as a forward does.\n */\nlet lastSentAt = 0;\nexport const sentAt = () => (lastSentAt = Math.max(Date.now(), lastSentAt + 1));\n\n// ---------- parameters ----------\n\nexport function str(params: Params, name: string, required: true): string;\nexport function str(params: Params, name: string, required?: false): string | undefined;\nexport function str(params: Params, name: string, required = false): string | undefined {\n const value = params[name];\n if (value === undefined || value === null || value === \"\") {\n if (required) throw new CliError(\"bad_request\", `${name} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") throw new CliError(\"bad_request\", `${name} must be a string`);\n return value;\n}\n/** A number in `[min, max]`; `whole` takes only whole ones (a count of messages), as the engine needs them. */\nexport function num(params: Params, name: string, fallback: number, { min = 0, max = Number.MAX_SAFE_INTEGER, whole = false } = {}): number {\n const value = params[name];\n if (value === undefined || value === null) return fallback;\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) throw new CliError(\"bad_request\", `${name} must be a ${whole ? \"whole \" : \"\"}number from ${min} to ${max}`);\n if (whole && !Number.isSafeInteger(value)) throw new CliError(\"bad_request\", `${name} must be a whole number from ${min} to ${max}`);\n return value;\n}\n/**\n * The seq `events.replay` and `events.subscribe` start after: whole, from 0; `fallback` when left out. A cursor sent as\n * text (\"412\") was a stream from now on the socket with no error, and a negative one a gap of seqs that never were.\n */\nexport function sinceSeq(params: Params, fallback: number): number {\n return num(params, \"since\", fallback, { whole: true });\n}\nexport function bool(params: Params, name: string): boolean {\n const value = params[name];\n if (value === undefined || value === null) return false;\n if (typeof value !== \"boolean\") throw new CliError(\"bad_request\", `${name} must be true or false`);\n return value;\n}\nexport function list(params: Params, name: string): string[] {\n const value = params[name];\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) throw new CliError(\"bad_request\", `${name} must be a list of strings`);\n return value as string[];\n}\n/**\n * One of `values`; `fallback` when it was left out. Given empty (an unset variable in a script: `wallet remove \"\"`), it\n * is refused like any other wrong choice, never read as left out: that acted on the default (the Cashu wallet).\n */\nexport function oneOf<T extends string>(params: Params, name: string, values: readonly T[], fallback: T): T {\n const value = params[name] === \"\" ? \"\" : str(params, name) ?? fallback;\n if (!values.includes(value as T)) throw new CliError(\"bad_request\", `${name} must be one of ${values.join(\", \")}`);\n return value as T;\n}\n\n// ---------- finding things ----------\n\nconst KEY_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\n/**\n * A chat's id as the engine makes it (the first 16 characters of a z-base-32 key) and the CLI prints it as `chat`. A ref\n * so shaped is only ever an id: tested on its `nameKey`, so that a case, a space or an invisible character more is too.\n */\nconst CHAT_ID_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{16}$/;\n/**\n * A contact key as chats show it (`peer`): 52 characters of z-base-32, in its one canonical spelling. The same 52\n * characters with the last one respelled decode to the same bytes but are no key (WISP 02): refused here, so that\n * they never fall through to a chat's name, which its contact chooses.\n */\nexport const CONTACT_KEY = {\n test(ref: string): boolean {\n if (isZ32Key(ref)) return true;\n if (KEY_SHAPED.test(ref)) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} is not a contact key: a key has one spelling, and its last character is not this one`);\n return false;\n },\n};\n\n/**\n * The contact key `ref` is once read as a name is (`nameKey`: trimmed, invisible characters dropped, one case), or\n * undefined for a ref not shaped as one. A key a script or a paste left a line break, a space or capitals on is still\n * that key, and only ever names by key: never a chat, a group or a member by a name someone else chose. Every ref that\n * may be a key is read here, so no caller tests the raw string.\n */\nexport function contactKeyOf(ref: string): string | undefined {\n const key = nameKey(ref);\n return CONTACT_KEY.test(key) ? key : undefined;\n}\n\n/**\n * A chat's label, its contact's name or a group's name as a ref is compared with it: cleaned as the engine cleans a name\n * it stores (`renameLink`, `groupName`: any run of whitespace one space, invisible and direction-changing characters\n * dropped, trimmed), in one Unicode form (NFC) and one case. The string given to `chat rename` or `group create` finds\n * what it named, though what was stored is the cleaned one. Empty when nothing visible is left: that names nothing.\n */\nexport function nameKey(name: string | null | undefined): string {\n if (!name) return \"\";\n return (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\").toLowerCase();\n}\n\n/**\n * A name this side writes (a chat's label, the profile's name, a group's name) cleaned as the engine stores a name\n * (`renameLink`, `groupName`): any run of whitespace (a tab, a line break) one space, invisible and direction-changing\n * characters dropped, trimmed, in NFC: `nameKey` without the case. Counted after that, in code points as the engine\n * counts: undefined past `max`, \"\" when nothing visible is left. Every command that writes a name checks it here, so a\n * tab is a space and not a second line, and a name is never refused at a length it does not have once stored.\n */\nexport function cleanName(name: string, max: number): string | undefined {\n const clean = (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\");\n return [...clean].length > max ? undefined : clean;\n}\n\n/**\n * `name` as `cleanName` stores it, or the one refusal every name kind gives (`bad_request`), so a chat's, the profile's\n * and a group's name read alike. `subject` starts the sentence (\"A chat's name\", \"nick\"); `empty` follows \"needs a\n * character that shows\" (what an empty name does instead, when it does something). Too long says the count as stored,\n * in code points as the engine counts, and the largest character of several code points in it (a joined emoji or a\n * flag counts as several): the person sees what to cut, and a bot reads `details.length` and `details.max`.\n */\nexport function shownName(name: string, max: number, subject: string, empty = \"\"): string {\n const clean = cleanName(name, Infinity) ?? \"\";\n const length = [...clean].length;\n if (length > max) {\n const widest = [...new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(clean)]\n .map(({ segment }) => segment).reduce((a, b) => ([...b].length > [...a].length ? b : a), \"\");\n const several = [...widest].length > 1 ? `: ${widest} counts as ${[...widest].length}` : \"\";\n throw new CliError(\"bad_request\", `${subject} is up to ${max} characters as stored (this one is ${length}${several})`, { length, max });\n }\n if (!clean) throw new CliError(\"bad_request\", `${subject} needs a character that shows${empty}`);\n return clean;\n}\n\n/**\n * The `name` param of `group create` and `group rename`, refused as a chat's or the profile's name is (`shownName`),\n * then as the engine takes it (`groupName`: the same cleaning, 64 code points, 256 bytes; 64 code points never pass\n * 256 bytes, so its refusal is only a guard). Said here, before anything is made.\n */\nexport function groupNameOf(params: Params): string {\n const name = groupName(shownName(str(params, \"name\", true), MAX_GROUP_NAME_LENGTH, \"A group's name\"));\n if (!name) throw new CliError(\"bad_request\", `A group's name is up to ${MAX_GROUP_NAME_BYTES} bytes as stored`);\n return name;\n}\n\n/** Whether `name` is the one `key` (a ref's `nameKey`) names. */\nconst namedAs = (key: string, name: string | null | undefined) => key !== \"\" && nameKey(name) === key;\n\n/**\n * A chat by its id; by its contact's key (only by the key: a name is never taken for one); by the label this side gave\n * it; and only when no label matches, by a unique prefix of its id or the name the contact gave itself. The contact\n * controls both of those (a joiner's chat id is made from the inviter's code), so neither wins over a label, and a ref\n * that fits one chat's prefix and another's name is refused. A ref shaped as a chat's id is only ever an id, or a label\n * given here. `group:<ref>` is never a chat (a group, as everywhere). A ref\n * that names no chat but one of `groups` says it is a group (see `noChat`).\n */\nexport function findChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n return chatBy(links, ref, groups).link;\n}\n\n/**\n * No chat by `ref`. A group's id, prefix or name (or `group:<id>`) says it is a group, as `groupOf` says a chat is one:\n * `chat connect`, `identity share`, `call start` and the other commands that take only a 1:1 chat read `No chat \"Crew\"`,\n * as if nothing had that name.\n */\nfunction noChat(ref: string, groups: readonly GroupView[]): CliError {\n const group = groupNamed(ref, groups);\n if (group) return new CliError(\"not_found\", `${JSON.stringify(ref)} is a group, not a chat (ghostly chat list)`, { group: group.id });\n return new CliError(\"not_found\", `No chat ${JSON.stringify(ref)} (ghostly chat list)`);\n}\n\n/** A chat or group ref as a next step shows it: as given, quoted only when it holds more than a word. */\nconst shownRef = (ref: string) => (/^[\\w.:-]+$/.test(ref) ? ref : JSON.stringify(ref));\n\n/** The chat or the group a message or a file was looked for in, as the command was given it (`ref`). */\nexport type RefPlace = { group: boolean; ref: string };\n\n/**\n * No message by `id` in a chat or a group, said one way by every command that takes one, as `noChat` says a chat: the id\n * quoted as given, and where the ids are. `whose` (\"of yours\", \"from someone else\") is what it had to be; `tail` what\n * else it may have failed for (\", or it takes no reaction\", \": only your own messages are sent again\").\n */\nexport function noMessage(id: string, place: RefPlace, { whose, tail }: { whose?: string; tail?: string } = {}): CliError {\n const history = `ghostly ${place.group ? \"group\" : \"chat\"} history ${shownRef(place.ref)}`;\n return new CliError(\"not_found\", `No message ${JSON.stringify(id)}${whose ? ` ${whose}` : \"\"} in this ${place.group ? \"group\" : \"chat\"}${tail ?? \"\"} (${history})`);\n}\n\n/** No file by `id`, as `noMessage` says a message: in the chat or group named (`place`), or in none when none was. */\nexport function noFile(id: string, place?: RefPlace): CliError {\n const where = place ? ` in this ${place.group ? \"group\" : \"chat\"}` : \"\";\n return new CliError(\"not_found\", `No file ${JSON.stringify(id)}${where} (ghostly file list ${place ? shownRef(place.ref) : \"<chat|group>\"})`);\n}\n\n/** The one group `ref` names, if any (none, or more than one: undefined). */\nfunction groupNamed(ref: string, groups: readonly GroupView[]): GroupView | undefined {\n try { return findGroup(groups, ref); } catch { return undefined; }\n}\n\n/** `findChat`, and whether only what the contact controls (`theirName`: a prefix of the id, its own name) found the chat. */\nfunction chatBy(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): { link: LinkView; theirName: boolean } {\n // \"\" (an unset variable in a script) is a prefix of every id: it took the only chat.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names no chat`);\n const exact = links.find((link) => link.id === ref);\n if (exact) return { link: exact, theirName: false };\n const contact = contactKeyOf(ref);\n if (contact !== undefined) {\n const byKey = links.filter((link) => link.peerPubKeyZ32 === contact);\n if (byKey.length === 1) return { link: byKey[0], theirName: false };\n if (byKey.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: byKey.map((link) => link.id) });\n throw new CliError(\"not_found\", `No chat with ${JSON.stringify(ref)} (ghostly chat list)`);\n }\n const key = nameKey(ref);\n const named = (name: string | null | undefined) => namedAs(key, name);\n const byLabel = links.filter((link) => named(link.label));\n // `group:<ref>` names a group (`groupPrefixed`), never a chat: not by a name its contact chose, nor by a label given\n // here (a chat labelled `group:Crew` was that chat for `chat show` and the group Crew for `send`). A chat labelled so\n // before labels were refused (`chatName`) is named by its id.\n if (groupPrefixed(ref) !== null) {\n if (byLabel.length && !groupNamed(ref, groups)) throw new CliError(\"not_found\", `${JSON.stringify(ref)} names a group, never a chat: name the chat labelled so by its id, and give it another name (ghostly chat rename <chat> <name>)`, { matches: byLabel.map((link) => link.id) });\n throw noChat(ref, groups);\n }\n // A chat's id no chat has (one removed since: a bot kept it from an event) is no chat. Its contact and whoever saw its\n // invite know it, so another contact could call itself that and take every later command sent by it. A label given\n // here still names the chat: only this side chooses it.\n if (!byLabel.length && CHAT_ID_SHAPED.test(key)) throw noChat(ref, groups);\n const found = byLabel.length ? byLabel : [...new Set([...links.filter((link) => link.id.startsWith(ref)), ...links.filter((link) => named(link.peerNick))])];\n if (found.length === 1) return { link: found[0], theirName: !byLabel.length };\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: found.map((link) => link.id) });\n throw noChat(ref, groups);\n}\n\n/**\n * `findChat` for a grant the daemon keeps acting on (`call auto on --from`): only the chat's id, its contact's key or the\n * label this side gave it name the chat. A prefix of its id or the name its contact gave itself is refused, with the\n * chat it found: the contact chose those, so another contact could take the grant by calling itself that name.\n */\nexport function findOwnNamedChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n const chat = chatBy(links, ref, groups);\n if (chat.theirName) throw namedByThem(ref, { chat: chat.link.id, name: chat.link.peerNick ?? null, contact: chat.link.peerPubKeyZ32 });\n return chat.link;\n}\n\n/** `findOwnNamedChat`'s refusal: `ref` found `chat` only by what its contact chose. */\nexport function namedByThem(ref: string, chat: { chat: string; name: string | null; contact: string | undefined }): CliError {\n return new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat only by what its contact chose (a prefix of its id, its own name): use the chat's id, its contact's key or a label given here (ghostly chat rename <chat> <name>)`, chat);\n}\n\n/**\n * `group:<ref>`, the form that names a group wherever a group is taken (docs/CLI.md § What it does): `<ref>`, read as any\n * other ref (`findGroup`: an id, a prefix of it or a name). Null for a ref without it. `findGroup` and `findChatOrGroup`\n * both read the prefix here, so a group command and a command that takes a chat or a group never read it apart.\n */\nexport const groupPrefixed = (ref: string): string | null => (ref.startsWith(\"group:\") ? ref.slice(\"group:\".length) : null);\n\n/** Only an invitation so far: this profile is not in the group (yet), and whoever invited chose its name. */\nconst invitedOnly = (group: GroupView) => group.status === undefined && !!group.invitation;\n\n/**\n * A group by its id, by its name, or by a unique prefix of its id. Whoever created a group chose its id and its admin\n * chooses its name, so neither wins over the other: a ref that is one group's name and another's prefix is refused,\n * with both ids, as `chatBy` does for chats. A group this profile is in wins over an invitation with the same name or\n * prefix (the one who invites chooses those); an invitation is still found by its id, and by name or prefix where no\n * group of this profile has it. `group:<ref>` is `<ref>` (`groupPrefixed`); before, only the commands that take a chat\n * or a group read it, and every group command and `listen --group` answered it `No group`.\n */\nexport function findGroup(groups: readonly GroupView[], given: string): GroupView {\n const ref = groupPrefixed(given) ?? given;\n // Each refusal echoes the ref as given (`\"group:k86q\"`), not the part after `group:`: what the person typed.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names no group`);\n const exact = groups.find((group) => group.id === ref);\n if (exact) return exact;\n const key = nameKey(ref);\n for (const among of [groups.filter((group) => !invitedOnly(group)), groups.filter(invitedOnly)]) {\n const found = among.filter((group) => namedAs(key, group.name) || group.id.startsWith(ref));\n if (found.length === 1) return found[0];\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names more than one group: use its id`, { matches: found.map((group) => group.id) });\n }\n throw new CliError(\"not_found\", `No group ${JSON.stringify(given)} (ghostly group list)`);\n}\n\n/**\n * A chat or a group, where a command takes either: `group:<id>` is a group; anything else a chat first (`findChat`),\n * then a group. A chat found only by what its contact chose (a prefix of its id, its own name) never takes what also\n * names a group: a group's\n * own id is that group, and a prefix or the name of a group this profile is in is refused, with both ids. With neither,\n * one `not_found` names both and where to look (a contact's key: no chat with it); a name that matches more than one\n * chat or group stays that error.\n */\nexport function findChatOrGroup(links: readonly LinkView[], groups: readonly GroupView[], ref: string): { link: LinkView } | { group: GroupView } {\n if (groupPrefixed(ref) !== null) return { group: findGroup(groups, ref) };\n let chat: ReturnType<typeof chatBy>;\n try {\n chat = chatBy(links, ref);\n } catch (error) {\n if (!(error instanceof CliError) || error.code !== \"not_found\") throw error;\n // Nor is it a group's name or a prefix of a group's id (its admin and its creator chose those; a group's own id is\n // longer), nor is a contact's key with no chat: `group:<ref>` names a group.\n if (CHAT_ID_SHAPED.test(nameKey(ref)) || contactKeyOf(ref) !== undefined) throw error;\n try { return { group: findGroup(groups, ref) }; } catch (inner) {\n if (!(inner instanceof CliError) || inner.code !== \"not_found\") throw inner;\n throw new CliError(\"not_found\", `No chat or group ${JSON.stringify(ref)} (ghostly chat list, ghostly group list)`);\n }\n }\n if (!chat.theirName) return { link: chat.link };\n const exact = groups.find((group) => group.id === ref);\n if (exact) return { group: exact };\n const key = nameKey(ref);\n const also = groups.filter((group) => !invitedOnly(group) && (group.id.startsWith(ref) || namedAs(key, group.name)));\n if (also.length) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat (by what its contact chose) and a group: use the chat's id or group:<id>`, { chat: chat.link.id, groups: also.map((group) => group.id) });\n return { link: chat.link };\n}\n\n/**\n * Starts the chats a call names (its `chat`, a forward's `to`) in a runtime that left the saved chats unstarted\n * (`RuntimeOptions.deferChats`). A ref that names no chat, or names a group, starts nothing: the call says so itself.\n */\nexport function startNamedChats(ctx: ApiContext, params: Params): void {\n const { links, groups } = state(ctx);\n for (const ref of [params.chat, ...(Array.isArray(params.to) ? params.to : [])]) {\n if (typeof ref !== \"string\") continue;\n let found: ReturnType<typeof findChatOrGroup>;\n try { found = findChatOrGroup(links, groups, ref); } catch { continue; }\n if (\"link\" in found) node(ctx).startDeferredChat(found.link.id);\n }\n}\n\nexport const chatOf = (ctx: ApiContext, params: Params) => findChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\n\n/** A chat of mine whose invite nobody took yet: no contact's key, so nothing goes out until they join. */\nexport const nobodyJoined = (link: LinkView): boolean => !!(link.profile && link.inviteCode && !link.peerParticipationKey);\n\n/** `nobodyJoined` by the chat's id: a group's (`group:<id>`) is never one. */\nexport const nobodyJoinedChat = (ctx: ApiContext, chat: string): boolean => {\n const link = state(ctx).links.find((l) => l.id === chat);\n return !!link && nobodyJoined(link);\n};\n\n/**\n * Whether a one-shot waits by default on what it did in a 1:1 chat: it leaves with its process, so it stays until that\n * went out or the contact confirmed it. Not on a chat nobody joined yet: there is no one to wait for, and `edit`, `react`,\n * `pin`, a card or a file sat their whole wait (a file 300 s), then failed `timeout`, exit 4, which a bot retries: one\n * more card or file each time. What was done is kept and goes once they join; the answer says so (`keptForJoin`).\n */\nexport const oneShotWaits = (ctx: ApiContext, chat: string): boolean => ctx.mode === \"one-shot\" && !nobodyJoinedChat(ctx, chat);\n\n/** An answer's `note` on a chat nobody joined yet: `what` is kept and goes once they join. Nothing on any other chat. */\nexport const keptForJoin = (ctx: ApiContext, chat: string, what: string): { note?: string } => nobodyJoinedChat(ctx, chat)\n ? { note: `Nobody joined this chat yet: ${what} goes once they join${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}` }\n : {};\n\n/**\n * A chat whose invite nobody took yet has no session to close either: `chat disconnect` answered done with the chat at\n * `connecting`, and `--hold` put the waiting invite on DHT only (a one-shot answered `pairing: error`).\n */\nexport function somebodyJoined(link: LinkView): void {\n if (nobodyJoined(link)) throw new CliError(\"unavailable\", \"Nobody joined this chat yet: its invite is still waiting to be taken\");\n}\n\n/**\n * A chat whose invite nobody took yet: nobody is there to pay or to dial, and its stage says so. Before, `chat pay`\n * waited 15 s and `chat connect` 25 s for the contact, then answered `engine`. A chat whose invite someone else used\n * first is refused too, with the sentence `send` gives: its contact seals everything to them (`connect` waited 120 s,\n * then answered `timeout`, a code a bot retries).\n */\nexport function inviteTaken(link: LinkView): void {\n somebodyJoined(link);\n if (link.dhtDelivery?.inviteTaken && link.textDelivery !== \"stream\") throw new CliError(\"refused\", INVITE_TAKEN);\n}\n\n/**\n * A chat on DHT only opens no live session: the engine refused `chat connect` as `engine`, \"Both peers must choose a\n * live method first\", which read as if this side had to change something. Refused instead, naming whose choice it is\n * (`details.reason`): the contact's (`peer-dht-only`, nothing to do here but wait), or this side's (`dht-only`).\n */\nexport function dhtOnly(link: LinkView): void {\n if (link.deliveryMode === \"dht\") throw new CliError(\"refused\", \"This chat is on DHT only on this side: choose a live method first (chat transport auto)\", { reason: \"dht-only\" });\n if (link.dhtDelivery?.peerMode === \"dht\") throw new CliError(\"refused\", \"Your contact keeps this chat on DHT only: it goes live once they choose a live method. Short texts still go on the DHT\", { reason: \"peer-dht-only\" });\n}\n\nconst TRANSPORT_TITLES: Record<PairedTransport, string> = { \"webrtc/1\": \"WebRTC\", \"iroh/1\": \"Iroh\", \"hyperdht/1\": \"HyperDHT\" };\n\n/**\n * A transport the chat's Connection menu offers: one this app runs (on DHT only, one it can start), and the contact's\n * app too, by its last word. `chat transport` took any: toward a contact with no WebRTC (`GHOSTLY_WEBRTC=0`) the choice\n * was kept and the chat stayed where it was, saying nothing; for one this app lacks, the engine answered `engine`,\n * \"Transport unavailable\". Refused instead, saying whose app lacks it (`details.reason`, as a chat's wait says it).\n */\nexport function transportOffered(link: LinkView, transport: PairedTransport): void {\n const mine = (link.deliveryMode === \"dht\" ? link.runnableTransports : undefined) ?? link.availableTransports;\n const title = TRANSPORT_TITLES[transport], error = link.transportErrors?.[transport];\n if (mine && !mine.includes(transport)) throw new CliError(\"refused\", `This app has no ${title} running${error ? `: ${error}` : \"\"}`, { reason: \"app-lacks\", transport });\n if (link.peerTransports?.length && !link.peerTransports.includes(transport)) throw new CliError(\"refused\", `Your contact's app doesn't have ${title}: choose another, or auto`, { reason: \"contact-lacks\", transport });\n}\n\n/** A chat or a group as `findChatOrGroup` reads it. `linkId` is what the engine calls it. */\nexport function chatOrGroup(ctx: ApiContext, ref: string): { id: string; linkId: string; group: boolean } {\n const found = findChatOrGroup(state(ctx).links, state(ctx).groups, ref);\n return \"group\" in found ? { id: found.group.id, linkId: `group:${found.group.id}`, group: true } : { id: found.link.id, linkId: found.link.id, group: false };\n}\n\n/**\n * The group a group command names. A chat's id, key or name says it is a chat, with `twin`, the chat command that takes\n * it (`group send` on a chat, where `send` is meant; `<chat>` stands for the ref), else where the groups are listed.\n * It read \"No group\" before. A name nothing has stays that error.\n */\nexport function groupOf(ctx: ApiContext, params: Params, twin?: string): GroupView {\n const ref = str(params, \"group\", true);\n try { return findGroup(state(ctx).groups, ref); } catch (error) {\n // `group:<ref>` names a group only: never a chat, as in `findChatOrGroup`.\n if (!(error instanceof CliError) || error.code !== \"not_found\" || groupPrefixed(ref) !== null) throw error;\n let chat: LinkView;\n try { chat = findChat(state(ctx).links, ref); } catch { throw error; }\n const shown = /^[\\w.:-]+$/.test(ref) ? ref : JSON.stringify(ref);\n throw new CliError(\"not_found\", `${JSON.stringify(ref)} is a chat, not a group${twin ? `: ghostly ${twin.replace(\"<chat>\", shown)}` : \" (ghostly group list)\"}`, { chat: chat.id });\n }\n}\n\n/**\n * A message of a chat or a group (`group:<id>`) named by its id here, read as one row; only a name that is no such\n * row's key (the id both sides know, `wireId`) reads the whole history. `keep`: only a message it accepts (mine, or\n * someone else's). The history is synchronous work on the daemon's one thread, about 120 ms at 10,000 messages.\n */\nexport async function messageOf(ctx: ApiContext, linkId: string, ref: string, keep: (message: StoredMessage) => boolean = () => true): Promise<StoredMessage | undefined> {\n const found = await node(ctx).getMessage(linkId, ref);\n if (found && keep(found)) return found;\n const all = linkId.startsWith(\"group:\") ? await node(ctx).groupMessages({ groupId: linkId.slice(\"group:\".length) }) : await node(ctx).getMessages(linkId);\n return all.find((m) => keep(m) && m.wireId === ref);\n}\n\n// ---------- waiting ----------\n\n/**\n * Resolves with `check`'s first defined answer: now, or on a later state; `timeout` error after `ms`. A check that\n * throws on a later state (`chat wait`'s chat removed) ends the wait with its error: the hub swallows what its\n * listeners throw, and the wait went on to its timeout.\n *\n * `stopping` (a daemon's `ctx.stopping`): the daemon's stop ends it too, as a timeout with `details.reason:\n * \"daemon-stopped\"`, for a wait whose command did something (`file send --wait`) and answers with what it knows. A\n * wait that changes nothing is left to its connection's end, and its client asks it again (main.ts `READ_WAITS`).\n */\nexport function waitForState<T>(ctx: ApiContext, check: (state: EngineState) => T | undefined, ms: number, what: string, stopping?: AbortSignal): Promise<T> {\n const now = check(state(ctx));\n if (now !== undefined) return Promise.resolve(now);\n return new Promise<T>((resolve, reject) => {\n const end = (error: unknown) => { clearTimeout(timer); off(); stopping?.removeEventListener(\"abort\", stopped); if (error) reject(error); };\n const stopped = () => end(new CliError(\"timeout\", `The daemon stopped before the wait ended, waiting for ${what}`, { reason: \"daemon-stopped\" }));\n const timer = setTimeout(() => end(new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s waiting for ${what}`)), ms);\n const off = ctx.hub.onState((next) => {\n let value: T | undefined;\n try { value = check(next); } catch (error) { end(error); return; }\n if (value === undefined) return;\n end(null);\n resolve(value);\n });\n if (stopping?.aborted) stopped();\n else stopping?.addEventListener(\"abort\", stopped, { once: true });\n });\n}\n\n"],"mappings":";;;AAqCA,IAAa,QAAQ,QAAiC,IAAI,QAAQ,OAAO;AACzE,IAAa,SAAS,QAAiC,KAAK,GAAG,CAAC,CAAC,SAAS;;;;;;;AAQ1E,IAAI,aAAa;AACjB,IAAa,eAAgB,aAAa,KAAK,IAAI,KAAK,IAAI,GAAG,aAAa,CAAC;AAM7E,SAAgB,IAAI,QAAgB,MAAc,WAAW,OAA2B;CACtF,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,IAAI;EACzD,IAAI,UAAU,MAAM,IAAI,SAAS,eAAe,GAAG,KAAK,aAAa;EACrE;CACF;CACA,IAAI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GACjE,IAAI,UAAU,KAAA,GAAW;GACzB,IAAI,IAAI;GACR,QAAQ,KAAK;EACf,CAAC;EACD,IAAI,UAAU,SAAS,QAAQ;OAC1B,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAClE,CAAC;AACH"}
1
+ {"version":3,"file":"apiKit-DesObIDf.js","names":[],"sources":["../../src/apiKit.ts"],"sourcesContent":["import { groupName, INVITE_TAKEN, isZ32Key, MAX_GROUP_NAME_BYTES, MAX_GROUP_NAME_LENGTH, sanitizeDisplayText, type PairedTransport } from \"@ghostly/core\";\nimport type { GhostlyNode } from \"@ghostly/browser/engine/node\";\nimport type { EngineState, GroupView, LinkView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { CliError } from \"./errors\";\nimport type { CallManager } from \"./calls/manager\";\nimport type { EventHub } from \"./events\";\nimport type { GroupAutoJoin } from \"./groupAuto\";\nimport type { Runtime } from \"./runtime/engine\";\n\n/**\n * The methods of the local control API (WISP 1100): the daemon answers them over its socket, and a one-shot\n * command calls them in its own process. Parameters come from JSON: every one is checked here.\n */\nexport interface ApiContext {\n runtime: Runtime;\n hub: EventHub;\n /** Voice calls (WISP 1100 § Calls). */\n calls: CallManager;\n /** Group invitations accepted by themselves (`group auto`). */\n groupAuto: GroupAutoJoin;\n /** How the host runs: a daemon stays; a one-shot leaves when its command is done. */\n mode: \"daemon\" | \"one-shot\";\n version: string;\n /** The daemon asks to stop (answered first). */\n stop?: () => void;\n /**\n * Aborted when the daemon stops (`serve().close`): a wait still open answers with what it knows (`waits.ts`), as a\n * timeout with `details.reason: \"daemon-stopped\"`, before the connections end.\n */\n stopping?: AbortSignal;\n /** The daemon is a `listen` that found none and runs the profile itself: a stop ends that listen too. */\n listen?: true;\n}\n\nexport type Params = Record<string, unknown>;\nexport type Method = (ctx: ApiContext, params: Params) => Promise<unknown>;\n\nexport const node = (ctx: ApiContext): GhostlyNode => ctx.runtime.server.node;\nexport const state = (ctx: ApiContext): EngineState => node(ctx).getState();\n\n/**\n * The time of a send the engine names its row after (`me_<timestamp>`: a file, a payment, a request), its own even\n * within one millisecond (a bot paying or sending several times at once over the socket, `file send` run in\n * parallel), or the chat keeps only one. One clock for all of them: they share the row names. A file's resend after a\n * drop finds its row by it, as a forward does.\n */\nlet lastSentAt = 0;\nexport const sentAt = () => (lastSentAt = Math.max(Date.now(), lastSentAt + 1));\n\n// ---------- parameters ----------\n\nexport function str(params: Params, name: string, required: true): string;\nexport function str(params: Params, name: string, required?: false): string | undefined;\nexport function str(params: Params, name: string, required = false): string | undefined {\n const value = params[name];\n if (value === undefined || value === null || value === \"\") {\n if (required) throw new CliError(\"bad_request\", `${name} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") throw new CliError(\"bad_request\", `${name} must be a string`);\n return value;\n}\n/** A number in `[min, max]`; `whole` takes only whole ones (a count of messages), as the engine needs them. */\nexport function num(params: Params, name: string, fallback: number, { min = 0, max = Number.MAX_SAFE_INTEGER, whole = false } = {}): number {\n const value = params[name];\n if (value === undefined || value === null) return fallback;\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) throw new CliError(\"bad_request\", `${name} must be a ${whole ? \"whole \" : \"\"}number from ${min} to ${max}`);\n if (whole && !Number.isSafeInteger(value)) throw new CliError(\"bad_request\", `${name} must be a whole number from ${min} to ${max}`);\n return value;\n}\n/**\n * The seq `events.replay` and `events.subscribe` start after: whole, from 0; `fallback` when left out. A cursor sent as\n * text (\"412\") was a stream from now on the socket with no error, and a negative one a gap of seqs that never were.\n */\nexport function sinceSeq(params: Params, fallback: number): number {\n return num(params, \"since\", fallback, { whole: true });\n}\nexport function bool(params: Params, name: string): boolean {\n const value = params[name];\n if (value === undefined || value === null) return false;\n if (typeof value !== \"boolean\") throw new CliError(\"bad_request\", `${name} must be true or false`);\n return value;\n}\nexport function list(params: Params, name: string): string[] {\n const value = params[name];\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) throw new CliError(\"bad_request\", `${name} must be a list of strings`);\n return value as string[];\n}\n/**\n * One of `values`; `fallback` when it was left out. Given empty (an unset variable in a script: `wallet remove \"\"`), it\n * is refused like any other wrong choice, never read as left out: that acted on the default (the Cashu wallet).\n */\nexport function oneOf<T extends string>(params: Params, name: string, values: readonly T[], fallback: T): T {\n const value = params[name] === \"\" ? \"\" : str(params, name) ?? fallback;\n if (!values.includes(value as T)) throw new CliError(\"bad_request\", `${name} must be one of ${values.join(\", \")}`);\n return value as T;\n}\n\n// ---------- finding things ----------\n\nconst KEY_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\n/**\n * A chat's id as the engine makes it (the first 16 characters of a z-base-32 key) and the CLI prints it as `chat`. A ref\n * so shaped is only ever an id: tested on its `nameKey`, so that a case, a space or an invisible character more is too.\n */\nconst CHAT_ID_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{16}$/;\n/**\n * A contact key as chats show it (`peer`): 52 characters of z-base-32, in its one canonical spelling. The same 52\n * characters with the last one respelled decode to the same bytes but are no key (WISP 02): refused here, so that\n * they never fall through to a chat's name, which its contact chooses.\n */\nexport const CONTACT_KEY = {\n test(ref: string): boolean {\n if (isZ32Key(ref)) return true;\n if (KEY_SHAPED.test(ref)) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} is not a contact key: a key has one spelling, and its last character is not this one`);\n return false;\n },\n};\n\n/**\n * The contact key `ref` is once read as a name is (`nameKey`: trimmed, invisible characters dropped, one case), or\n * undefined for a ref not shaped as one. A key a script or a paste left a line break, a space or capitals on is still\n * that key, and only ever names by key: never a chat, a group or a member by a name someone else chose. Every ref that\n * may be a key is read here, so no caller tests the raw string.\n */\nexport function contactKeyOf(ref: string): string | undefined {\n const key = nameKey(ref);\n return CONTACT_KEY.test(key) ? key : undefined;\n}\n\n/**\n * A chat's label, its contact's name or a group's name as a ref is compared with it: cleaned as the engine cleans a name\n * it stores (`renameLink`, `groupName`: any run of whitespace one space, invisible and direction-changing characters\n * dropped, trimmed), in one Unicode form (NFC) and one case. The string given to `chat rename` or `group create` finds\n * what it named, though what was stored is the cleaned one. Empty when nothing visible is left: that names nothing.\n */\nexport function nameKey(name: string | null | undefined): string {\n if (!name) return \"\";\n return (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\").toLowerCase();\n}\n\n/**\n * A name this side writes (a chat's label, the profile's name, a group's name) cleaned as the engine stores a name\n * (`renameLink`, `groupName`): any run of whitespace (a tab, a line break) one space, invisible and direction-changing\n * characters dropped, trimmed, in NFC: `nameKey` without the case. Counted after that, in code points as the engine\n * counts: undefined past `max`, \"\" when nothing visible is left. Every command that writes a name checks it here, so a\n * tab is a space and not a second line, and a name is never refused at a length it does not have once stored.\n */\nexport function cleanName(name: string, max: number): string | undefined {\n const clean = (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\");\n return [...clean].length > max ? undefined : clean;\n}\n\n/**\n * `name` as `cleanName` stores it, or the one refusal every name kind gives (`bad_request`), so a chat's, the profile's\n * and a group's name read alike. `subject` starts the sentence (\"A chat's name\", \"nick\"); `empty` follows \"needs a\n * character that shows\" (what an empty name does instead, when it does something). Too long says the count as stored,\n * in code points as the engine counts, and the largest character of several code points in it (a joined emoji or a\n * flag counts as several): the person sees what to cut, and a bot reads `details.length` and `details.max`.\n */\nexport function shownName(name: string, max: number, subject: string, empty = \"\"): string {\n const clean = cleanName(name, Infinity) ?? \"\";\n const length = [...clean].length;\n if (length > max) {\n const widest = [...new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(clean)]\n .map(({ segment }) => segment).reduce((a, b) => ([...b].length > [...a].length ? b : a), \"\");\n const several = [...widest].length > 1 ? `: ${widest} counts as ${[...widest].length}` : \"\";\n throw new CliError(\"bad_request\", `${subject} is up to ${max} characters as stored (this one is ${length}${several})`, { length, max });\n }\n if (!clean) throw new CliError(\"bad_request\", `${subject} needs a character that shows${empty}`);\n return clean;\n}\n\n/**\n * The `name` param of `group create` and `group rename`, refused as a chat's or the profile's name is (`shownName`),\n * then as the engine takes it (`groupName`: the same cleaning, 64 code points, 256 bytes; 64 code points never pass\n * 256 bytes, so its refusal is only a guard). Said here, before anything is made.\n */\nexport function groupNameOf(params: Params): string {\n const name = groupName(shownName(str(params, \"name\", true), MAX_GROUP_NAME_LENGTH, \"A group's name\"));\n if (!name) throw new CliError(\"bad_request\", `A group's name is up to ${MAX_GROUP_NAME_BYTES} bytes as stored`);\n return name;\n}\n\n/** Whether `name` is the one `key` (a ref's `nameKey`) names. */\nconst namedAs = (key: string, name: string | null | undefined) => key !== \"\" && nameKey(name) === key;\n\n/**\n * A chat by its id; by its contact's key (only by the key: a name is never taken for one); by the label this side gave\n * it; and only when no label matches, by a unique prefix of its id or the name the contact gave itself. The contact\n * controls both of those (a joiner's chat id is made from the inviter's code), so neither wins over a label, and a ref\n * that fits one chat's prefix and another's name is refused. A ref shaped as a chat's id is only ever an id, or a label\n * given here. `group:<ref>` is never a chat (a group, as everywhere). A ref\n * that names no chat but one of `groups` says it is a group (see `noChat`).\n */\nexport function findChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n return chatBy(links, ref, groups).link;\n}\n\n/**\n * No chat by `ref`. A group's id, prefix or name (or `group:<id>`) says it is a group, as `groupOf` says a chat is one:\n * `chat connect`, `identity share`, `call start` and the other commands that take only a 1:1 chat read `No chat \"Crew\"`,\n * as if nothing had that name.\n */\nfunction noChat(ref: string, groups: readonly GroupView[]): CliError {\n const group = groupNamed(ref, groups);\n if (group) return new CliError(\"not_found\", `${JSON.stringify(ref)} is a group, not a chat (ghostly chat list)`, { group: group.id });\n return new CliError(\"not_found\", `No chat ${JSON.stringify(ref)} (ghostly chat list)`);\n}\n\n/** A chat or group ref as a next step shows it: as given, quoted only when it holds more than a word. */\nconst shownRef = (ref: string) => (/^[\\w.:-]+$/.test(ref) ? ref : JSON.stringify(ref));\n\n/** The chat or the group a message or a file was looked for in, as the command was given it (`ref`). */\nexport type RefPlace = { group: boolean; ref: string };\n\n/**\n * No message by `id` in a chat or a group, said one way by every command that takes one, as `noChat` says a chat: the id\n * quoted as given, and where the ids are. `whose` (\"of yours\", \"from someone else\") is what it had to be; `tail` what\n * else it may have failed for (\", or it takes no reaction\", \": only your own messages are sent again\").\n */\nexport function noMessage(id: string, place: RefPlace, { whose, tail }: { whose?: string; tail?: string } = {}): CliError {\n const history = `ghostly ${place.group ? \"group\" : \"chat\"} history ${shownRef(place.ref)}`;\n return new CliError(\"not_found\", `No message ${JSON.stringify(id)}${whose ? ` ${whose}` : \"\"} in this ${place.group ? \"group\" : \"chat\"}${tail ?? \"\"} (${history})`);\n}\n\n/** No file by `id`, as `noMessage` says a message: in the chat or group named (`place`), or in none when none was. */\nexport function noFile(id: string, place?: RefPlace): CliError {\n const where = place ? ` in this ${place.group ? \"group\" : \"chat\"}` : \"\";\n return new CliError(\"not_found\", `No file ${JSON.stringify(id)}${where} (ghostly file list ${place ? shownRef(place.ref) : \"<chat|group>\"})`);\n}\n\n/** The one group `ref` names, if any (none, or more than one: undefined). */\nfunction groupNamed(ref: string, groups: readonly GroupView[]): GroupView | undefined {\n try { return findGroup(groups, ref); } catch { return undefined; }\n}\n\n/** `findChat`, and whether only what the contact controls (`theirName`: a prefix of the id, its own name) found the chat. */\nfunction chatBy(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): { link: LinkView; theirName: boolean } {\n // \"\" (an unset variable in a script) is a prefix of every id: it took the only chat.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names no chat`);\n const exact = links.find((link) => link.id === ref);\n if (exact) return { link: exact, theirName: false };\n const contact = contactKeyOf(ref);\n if (contact !== undefined) {\n const byKey = links.filter((link) => link.peerPubKeyZ32 === contact);\n if (byKey.length === 1) return { link: byKey[0], theirName: false };\n if (byKey.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: byKey.map((link) => link.id) });\n throw new CliError(\"not_found\", `No chat with ${JSON.stringify(ref)} (ghostly chat list)`);\n }\n const key = nameKey(ref);\n const named = (name: string | null | undefined) => namedAs(key, name);\n const byLabel = links.filter((link) => named(link.label));\n // `group:<ref>` names a group (`groupPrefixed`), never a chat: not by a name its contact chose, nor by a label given\n // here (a chat labelled `group:Crew` was that chat for `chat show` and the group Crew for `send`). A chat labelled so\n // before labels were refused (`chatName`) is named by its id.\n if (groupPrefixed(ref) !== null) {\n if (byLabel.length && !groupNamed(ref, groups)) throw new CliError(\"not_found\", `${JSON.stringify(ref)} names a group, never a chat: name the chat labelled so by its id, and give it another name (ghostly chat rename <chat> <name>)`, { matches: byLabel.map((link) => link.id) });\n throw noChat(ref, groups);\n }\n // A chat's id no chat has (one removed since: a bot kept it from an event) is no chat. Its contact and whoever saw its\n // invite know it, so another contact could call itself that and take every later command sent by it. A label given\n // here still names the chat: only this side chooses it.\n if (!byLabel.length && CHAT_ID_SHAPED.test(key)) throw noChat(ref, groups);\n const found = byLabel.length ? byLabel : [...new Set([...links.filter((link) => link.id.startsWith(ref)), ...links.filter((link) => named(link.peerNick))])];\n if (found.length === 1) return { link: found[0], theirName: !byLabel.length };\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: found.map((link) => link.id) });\n throw noChat(ref, groups);\n}\n\n/**\n * `findChat` for a grant the daemon keeps acting on (`call auto on --from`): only the chat's id, its contact's key or the\n * label this side gave it name the chat. A prefix of its id or the name its contact gave itself is refused, with the\n * chat it found: the contact chose those, so another contact could take the grant by calling itself that name.\n */\nexport function findOwnNamedChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n const chat = chatBy(links, ref, groups);\n if (chat.theirName) throw namedByThem(ref, { chat: chat.link.id, name: chat.link.peerNick ?? null, contact: chat.link.peerPubKeyZ32 });\n return chat.link;\n}\n\n/** `findOwnNamedChat`'s refusal: `ref` found `chat` only by what its contact chose. */\nexport function namedByThem(ref: string, chat: { chat: string; name: string | null; contact: string | undefined }): CliError {\n return new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat only by what its contact chose (a prefix of its id, its own name): use the chat's id, its contact's key or a label given here (ghostly chat rename <chat> <name>)`, chat);\n}\n\n/**\n * `group:<ref>`, the form that names a group wherever a group is taken (docs/CLI.md § What it does): `<ref>`, read as any\n * other ref (`findGroup`: an id, a prefix of it or a name). Null for a ref without it. `findGroup` and `findChatOrGroup`\n * both read the prefix here, so a group command and a command that takes a chat or a group never read it apart.\n */\nexport const groupPrefixed = (ref: string): string | null => (ref.startsWith(\"group:\") ? ref.slice(\"group:\".length) : null);\n\n/** Only an invitation so far: this profile is not in the group (yet), and whoever invited chose its name. */\nconst invitedOnly = (group: GroupView) => group.status === undefined && !!group.invitation;\n\n/**\n * A group by its id, by its name, or by a unique prefix of its id. Whoever created a group chose its id and its admin\n * chooses its name, so neither wins over the other: a ref that is one group's name and another's prefix is refused,\n * with both ids, as `chatBy` does for chats. A group this profile is in wins over an invitation with the same name or\n * prefix (the one who invites chooses those); an invitation is still found by its id, and by name or prefix where no\n * group of this profile has it. `group:<ref>` is `<ref>` (`groupPrefixed`); before, only the commands that take a chat\n * or a group read it, and every group command and `listen --group` answered it `No group`.\n */\nexport function findGroup(groups: readonly GroupView[], given: string): GroupView {\n const ref = groupPrefixed(given) ?? given;\n // Each refusal echoes the ref as given (`\"group:k86q\"`), not the part after `group:`: what the person typed.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names no group`);\n const exact = groups.find((group) => group.id === ref);\n if (exact) return exact;\n const key = nameKey(ref);\n for (const among of [groups.filter((group) => !invitedOnly(group)), groups.filter(invitedOnly)]) {\n const found = among.filter((group) => namedAs(key, group.name) || group.id.startsWith(ref));\n if (found.length === 1) return found[0];\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names more than one group: use its id`, { matches: found.map((group) => group.id) });\n }\n throw new CliError(\"not_found\", `No group ${JSON.stringify(given)} (ghostly group list)`);\n}\n\n/**\n * A chat or a group, where a command takes either: `group:<id>` is a group; anything else a chat first (`findChat`),\n * then a group. A chat found only by what its contact chose (a prefix of its id, its own name) never takes what also\n * names a group: a group's\n * own id is that group, and a prefix or the name of a group this profile is in is refused, with both ids. With neither,\n * one `not_found` names both and where to look (a contact's key: no chat with it); a name that matches more than one\n * chat or group stays that error.\n */\nexport function findChatOrGroup(links: readonly LinkView[], groups: readonly GroupView[], ref: string): { link: LinkView } | { group: GroupView } {\n if (groupPrefixed(ref) !== null) return { group: findGroup(groups, ref) };\n let chat: ReturnType<typeof chatBy>;\n try {\n chat = chatBy(links, ref);\n } catch (error) {\n if (!(error instanceof CliError) || error.code !== \"not_found\") throw error;\n // Nor is it a group's name or a prefix of a group's id (its admin and its creator chose those; a group's own id is\n // longer), nor is a contact's key with no chat: `group:<ref>` names a group.\n if (CHAT_ID_SHAPED.test(nameKey(ref)) || contactKeyOf(ref) !== undefined) throw error;\n try { return { group: findGroup(groups, ref) }; } catch (inner) {\n if (!(inner instanceof CliError) || inner.code !== \"not_found\") throw inner;\n throw new CliError(\"not_found\", `No chat or group ${JSON.stringify(ref)} (ghostly chat list, ghostly group list)`);\n }\n }\n if (!chat.theirName) return { link: chat.link };\n const exact = groups.find((group) => group.id === ref);\n if (exact) return { group: exact };\n const key = nameKey(ref);\n const also = groups.filter((group) => !invitedOnly(group) && (group.id.startsWith(ref) || namedAs(key, group.name)));\n if (also.length) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat (by what its contact chose) and a group: use the chat's id or group:<id>`, { chat: chat.link.id, groups: also.map((group) => group.id) });\n return { link: chat.link };\n}\n\n/**\n * Starts the chats a call names (its `chat`, a forward's `to`) in a runtime that left the saved chats unstarted\n * (`RuntimeOptions.deferChats`). A ref that names no chat, or names a group, starts nothing: the call says so itself.\n */\nexport async function startNamedChats(ctx: ApiContext, params: Params): Promise<void> {\n const { links, groups } = state(ctx);\n for (const ref of [params.chat, ...(Array.isArray(params.to) ? params.to : [])]) {\n if (typeof ref !== \"string\") continue;\n let found: ReturnType<typeof findChatOrGroup>;\n try { found = findChatOrGroup(links, groups, ref); } catch { continue; }\n if (\"link\" in found) await node(ctx).startDeferredChat(found.link.id);\n }\n}\n\nexport const chatOf = (ctx: ApiContext, params: Params) => findChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\n\n/** A chat of mine whose invite nobody took yet: no contact's key, so nothing goes out until they join. */\nexport const nobodyJoined = (link: LinkView): boolean => !!(link.profile && link.inviteCode && !link.peerParticipationKey);\n\n/** `nobodyJoined` by the chat's id: a group's (`group:<id>`) is never one. */\nexport const nobodyJoinedChat = (ctx: ApiContext, chat: string): boolean => {\n const link = state(ctx).links.find((l) => l.id === chat);\n return !!link && nobodyJoined(link);\n};\n\n/**\n * Whether a one-shot waits by default on what it did in a 1:1 chat: it leaves with its process, so it stays until that\n * went out or the contact confirmed it. Not on a chat nobody joined yet: there is no one to wait for, and `edit`, `react`,\n * `pin`, a card or a file sat their whole wait (a file 300 s), then failed `timeout`, exit 4, which a bot retries: one\n * more card or file each time. What was done is kept and goes once they join; the answer says so (`keptForJoin`).\n */\nexport const oneShotWaits = (ctx: ApiContext, chat: string): boolean => ctx.mode === \"one-shot\" && !nobodyJoinedChat(ctx, chat);\n\n/** An answer's `note` on a chat nobody joined yet: `what` is kept and goes once they join. Nothing on any other chat. */\nexport const keptForJoin = (ctx: ApiContext, chat: string, what: string): { note?: string } => nobodyJoinedChat(ctx, chat)\n ? { note: `Nobody joined this chat yet: ${what} goes once they join${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}` }\n : {};\n\n/**\n * A chat whose invite nobody took yet has no session to close either: `chat disconnect` answered done with the chat at\n * `connecting`, and `--hold` put the waiting invite on DHT only (a one-shot answered `pairing: error`).\n */\nexport function somebodyJoined(link: LinkView): void {\n if (nobodyJoined(link)) throw new CliError(\"unavailable\", \"Nobody joined this chat yet: its invite is still waiting to be taken\");\n}\n\n/**\n * A chat whose invite nobody took yet: nobody is there to pay or to dial, and its stage says so. Before, `chat pay`\n * waited 15 s and `chat connect` 25 s for the contact, then answered `engine`. A chat whose invite someone else used\n * first is refused too, with the sentence `send` gives: its contact seals everything to them (`connect` waited 120 s,\n * then answered `timeout`, a code a bot retries).\n */\nexport function inviteTaken(link: LinkView): void {\n somebodyJoined(link);\n if (link.dhtDelivery?.inviteTaken && link.textDelivery !== \"stream\") throw new CliError(\"refused\", INVITE_TAKEN);\n}\n\n/**\n * A chat on DHT only opens no live session: the engine refused `chat connect` as `engine`, \"Both peers must choose a\n * live method first\", which read as if this side had to change something. Refused instead, naming whose choice it is\n * (`details.reason`): the contact's (`peer-dht-only`, nothing to do here but wait), or this side's (`dht-only`).\n */\nexport function dhtOnly(link: LinkView): void {\n if (link.deliveryMode === \"dht\") throw new CliError(\"refused\", \"This chat is on DHT only on this side: choose a live method first (chat transport auto)\", { reason: \"dht-only\" });\n if (link.dhtDelivery?.peerMode === \"dht\") throw new CliError(\"refused\", \"Your contact keeps this chat on DHT only: it goes live once they choose a live method. Short texts still go on the DHT\", { reason: \"peer-dht-only\" });\n}\n\nconst TRANSPORT_TITLES: Record<PairedTransport, string> = { \"webrtc/1\": \"WebRTC\", \"iroh/1\": \"Iroh\", \"hyperdht/1\": \"HyperDHT\" };\n\n/**\n * A transport the chat's Connection menu offers: one this app runs (on DHT only, one it can start), and the contact's\n * app too, by its last word. `chat transport` took any: toward a contact with no WebRTC (`GHOSTLY_WEBRTC=0`) the choice\n * was kept and the chat stayed where it was, saying nothing; for one this app lacks, the engine answered `engine`,\n * \"Transport unavailable\". Refused instead, saying whose app lacks it (`details.reason`, as a chat's wait says it).\n */\nexport function transportOffered(link: LinkView, transport: PairedTransport): void {\n const mine = (link.deliveryMode === \"dht\" ? link.runnableTransports : undefined) ?? link.availableTransports;\n const title = TRANSPORT_TITLES[transport], error = link.transportErrors?.[transport];\n if (mine && !mine.includes(transport)) throw new CliError(\"refused\", `This app has no ${title} running${error ? `: ${error}` : \"\"}`, { reason: \"app-lacks\", transport });\n if (link.peerTransports?.length && !link.peerTransports.includes(transport)) throw new CliError(\"refused\", `Your contact's app doesn't have ${title}: choose another, or auto`, { reason: \"contact-lacks\", transport });\n}\n\n/** A chat or a group as `findChatOrGroup` reads it. `linkId` is what the engine calls it. */\nexport function chatOrGroup(ctx: ApiContext, ref: string): { id: string; linkId: string; group: boolean } {\n const found = findChatOrGroup(state(ctx).links, state(ctx).groups, ref);\n return \"group\" in found ? { id: found.group.id, linkId: `group:${found.group.id}`, group: true } : { id: found.link.id, linkId: found.link.id, group: false };\n}\n\n/**\n * The group a group command names. A chat's id, key or name says it is a chat, with `twin`, the chat command that takes\n * it (`group send` on a chat, where `send` is meant; `<chat>` stands for the ref), else where the groups are listed.\n * It read \"No group\" before. A name nothing has stays that error.\n */\nexport function groupOf(ctx: ApiContext, params: Params, twin?: string): GroupView {\n const ref = str(params, \"group\", true);\n try { return findGroup(state(ctx).groups, ref); } catch (error) {\n // `group:<ref>` names a group only: never a chat, as in `findChatOrGroup`.\n if (!(error instanceof CliError) || error.code !== \"not_found\" || groupPrefixed(ref) !== null) throw error;\n let chat: LinkView;\n try { chat = findChat(state(ctx).links, ref); } catch { throw error; }\n const shown = /^[\\w.:-]+$/.test(ref) ? ref : JSON.stringify(ref);\n throw new CliError(\"not_found\", `${JSON.stringify(ref)} is a chat, not a group${twin ? `: ghostly ${twin.replace(\"<chat>\", shown)}` : \" (ghostly group list)\"}`, { chat: chat.id });\n }\n}\n\n/**\n * A message of a chat or a group (`group:<id>`) named by its id here, read as one row; only a name that is no such\n * row's key (the id both sides know, `wireId`) reads the whole history. `keep`: only a message it accepts (mine, or\n * someone else's). The history is synchronous work on the daemon's one thread, about 120 ms at 10,000 messages.\n */\nexport async function messageOf(ctx: ApiContext, linkId: string, ref: string, keep: (message: StoredMessage) => boolean = () => true): Promise<StoredMessage | undefined> {\n const found = await node(ctx).getMessage(linkId, ref);\n if (found && keep(found)) return found;\n const all = linkId.startsWith(\"group:\") ? await node(ctx).groupMessages({ groupId: linkId.slice(\"group:\".length) }) : await node(ctx).getMessages(linkId);\n return all.find((m) => keep(m) && m.wireId === ref);\n}\n\n// ---------- waiting ----------\n\n/**\n * Resolves with `check`'s first defined answer: now, or on a later state; `timeout` error after `ms`. A check that\n * throws on a later state (`chat wait`'s chat removed) ends the wait with its error: the hub swallows what its\n * listeners throw, and the wait went on to its timeout.\n *\n * `stopping` (a daemon's `ctx.stopping`): the daemon's stop ends it too, as a timeout with `details.reason:\n * \"daemon-stopped\"`, for a wait whose command did something (`file send --wait`) and answers with what it knows. A\n * wait that changes nothing is left to its connection's end, and its client asks it again (main.ts `READ_WAITS`).\n */\nexport function waitForState<T>(ctx: ApiContext, check: (state: EngineState) => T | undefined, ms: number, what: string, stopping?: AbortSignal): Promise<T> {\n const now = check(state(ctx));\n if (now !== undefined) return Promise.resolve(now);\n return new Promise<T>((resolve, reject) => {\n const end = (error: unknown) => { clearTimeout(timer); off(); stopping?.removeEventListener(\"abort\", stopped); if (error) reject(error); };\n const stopped = () => end(new CliError(\"timeout\", `The daemon stopped before the wait ended, waiting for ${what}`, { reason: \"daemon-stopped\" }));\n const timer = setTimeout(() => end(new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s waiting for ${what}`)), ms);\n const off = ctx.hub.onState((next) => {\n let value: T | undefined;\n try { value = check(next); } catch (error) { end(error); return; }\n if (value === undefined) return;\n end(null);\n resolve(value);\n });\n if (stopping?.aborted) stopped();\n else stopping?.addEventListener(\"abort\", stopped, { once: true });\n });\n}\n\n"],"mappings":";;;AAqCA,IAAa,QAAQ,QAAiC,IAAI,QAAQ,OAAO;AACzE,IAAa,SAAS,QAAiC,KAAK,GAAG,CAAC,CAAC,SAAS;;;;;;;AAQ1E,IAAI,aAAa;AACjB,IAAa,eAAgB,aAAa,KAAK,IAAI,KAAK,IAAI,GAAG,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I,SAAS,WAAW,mBAAmB,KAAK,MAAM,KAAK,GAAI,EAAE,iBAAiB,MAAM,CAAC,GAAG,EAAE;EACjI,MAAM,MAAM,IAAI,IAAI,SAAS,SAAS;GACpC,IAAI;GACJ,IAAI;IAAE,QAAQ,MAAM,IAAI;GAAG,SAAS,OAAO;IAAE,IAAI,KAAK;IAAG;GAAQ;GACjE,IAAI,UAAU,KAAA,GAAW;GACzB,IAAI,IAAI;GACR,QAAQ,KAAK;EACf,CAAC;EACD,IAAI,UAAU,SAAS,QAAQ;OAC1B,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAClE,CAAC;AACH"}
@@ -1,4 +1,4 @@
1
- import { Tl as isAppUrl } from "./src-ChJijTlM.js";
1
+ import { Dl as isAppUrl } from "./src-DjVj2ynY.js";
2
2
  //#region ../browser/src/engine/appFetch.ts
3
3
  /** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */
4
4
  var APP_FETCH_HOSTS = ["raw.githubusercontent.com", "cdn.jsdelivr.net"];
@@ -189,6 +189,6 @@ function besideUrl(url, name) {
189
189
  return new URL(name, target).href;
190
190
  }
191
191
  //#endregion
192
- export { boundedAppFetch as a, besideUrl as i, AppFetchError as n, isAppFetchUrl as o, appPasteUrl as r, isGitHubPage as s, APP_FETCH_LIMITS as t };
192
+ export { besideUrl as a, isGitHubPage as c, appPasteUrl as i, APP_FETCH_LIMITS as n, boundedAppFetch as o, AppFetchError as r, isAppFetchUrl as s, APP_FETCH_HOSTS as t };
193
193
 
194
- //# sourceMappingURL=appFetch-BKHy5H8J.js.map
194
+ //# sourceMappingURL=appFetch-C8yZIq1e.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"appFetch-BKHy5H8J.js","names":[],"sources":["../../../browser/src/engine/appFetch.ts"],"sourcesContent":["import { isAppUrl } from \"@ghostly/core\";\n\n/*\n * Where mini-apps and stores are read from (WISP 1200 § Stores, § Apps sent in a chat): in phase 1 only two hosts,\n * `raw.githubusercontent.com` and `cdn.jsdelivr.net` pinned to a full commit, both readable from a page (CORS `*`).\n * HTTPS only, no user or password, no port, no redirect (one would walk out of the list), no cookies, no referrer, and a\n * cap on the bytes read while the body streams in. Every read of the apps feature goes through `boundedAppFetch`.\n */\n\n/** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */\nexport const APP_FETCH_HOSTS = [\"raw.githubusercontent.com\", \"cdn.jsdelivr.net\"] as const;\n\nexport const APP_FETCH_LIMITS = {\n /**\n * A store index as read (WISP 1200 § Stores, Privacy): 4 MiB in phase 1, under the format's 16 MiB. Counted on the body\n * as it arrives, after the browser undid any compression, since a page never sees the compressed size.\n */\n storeIndexBytes: 4 * 1024 * 1024,\n /** A store's signature statement, `ghostly-store.sig` (canonical, at most 1 KiB). */\n sigBytes: 1024,\n /** `ghostly-revoke.json`: at most 4096 signed revocations. */\n revocationsBytes: 16 * 1024 * 1024,\n /** How long the host has to answer (the response's headers). */\n timeoutMs: 30_000,\n /** How long the body may go without a byte: a read still arriving is never cut by the clock alone. */\n idleMs: 30_000,\n /** A whole read at most: the 16 MiB cap at about 224 kbit/s. */\n totalMs: 10 * 60_000,\n} as const;\n\n/** A URL this client may read an app, a store or a revocation list from. */\nexport function isAppFetchUrl(value: unknown): value is string {\n if (!isAppUrl(value)) return false;\n const url = new URL(value);\n return url.port === \"\" && (APP_FETCH_HOSTS as readonly string[]).includes(url.hostname.toLowerCase());\n}\n\n/** `slow`: the host did not answer in time, went silent, or the read ran past its whole budget. */\nexport type AppFetchErrorCode = \"host\" | \"offline\" | \"status\" | \"too-large\" | \"network\" | \"slow\";\n\nexport class AppFetchError extends Error {\n constructor(readonly code: AppFetchErrorCode, message: string, readonly status?: number) {\n // Its code first, as every error of the apps calls (`<code>: words`).\n super(`${code}: ${message}`);\n this.name = \"AppFetchError\";\n }\n}\n\n/**\n * Reads a URL of the list: its bytes, at most `maxBytes`. With `peek`, the first `maxBytes` bytes and no more, the rest\n * left unread (a bundle's manifest, to see whether it is newer before reading all of it). `signal` stops a read whose\n * bytes nobody will use any more (`network`). `revalidate`: a file every update check reads again (a store's index and\n * its sig, `ghostly-revoke.json`), kept by the browser and asked again with its ETag every time, so an unchanged one is\n * an empty 304 and never a copy the host was not asked about. Anything else is not kept by the browser (a bundle is\n * kept in file storage, a peek is a range).\n */\nexport type AppFetcher = (url: string, options: { maxBytes: number; peek?: boolean; revalidate?: boolean; signal?: AbortSignal }) => Promise<Uint8Array>;\n\nexport function boundedAppFetch(options: { fetcher?: typeof fetch; online?: () => boolean; timeoutMs?: number; idleMs?: number; totalMs?: number } = {}): AppFetcher {\n return async (url, { maxBytes, peek = false, revalidate = false, signal: stopped }) => {\n if (!isAppFetchUrl(url)) throw new AppFetchError(\"host\", \"Apps are read only from raw.githubusercontent.com, or from cdn.jsdelivr.net at a commit, over HTTPS\");\n if (options.online && !options.online()) throw new AppFetchError(\"offline\", \"Offline\");\n if (stopped?.aborted) throw new AppFetchError(\"network\", \"The read was stopped\");\n const fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);\n // One signal for the request and its body: the host has `timeoutMs` to answer, then the body `idleMs` between two\n // bytes, the whole read `totalMs`. A read still arriving goes on; one cut by the clock is `slow`, not `network`.\n const controller = new AbortController();\n const cut = () => { controller.abort(new DOMException(\"The read took too long\", \"TimeoutError\")); };\n const stop = () => { controller.abort(new DOMException(\"The read was stopped\", \"AbortError\")); };\n stopped?.addEventListener(\"abort\", stop);\n const total = setTimeout(cut, options.totalMs ?? APP_FETCH_LIMITS.totalMs);\n let idle = setTimeout(cut, options.timeoutMs ?? APP_FETCH_LIMITS.timeoutMs);\n const heard = () => { clearTimeout(idle); idle = setTimeout(cut, options.idleMs ?? APP_FETCH_LIMITS.idleMs); };\n const failure = (error: unknown) => stopped?.aborted ? new AppFetchError(\"network\", \"The read was stopped\")\n : controller.signal.aborted ? new AppFetchError(\"slow\", \"That took too long on this connection\")\n : new AppFetchError(\"network\", error instanceof Error ? error.message : String(error));\n const { signal } = controller;\n let response: Response;\n try {\n response = await fetcher(url, {\n signal,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: revalidate && !peek ? \"no-cache\" : \"no-store\", redirect: \"error\",\n ...(peek && { headers: { range: `bytes=0-${maxBytes - 1}` } }),\n });\n } catch (error) {\n clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop);\n throw failure(error);\n }\n heard();\n const parts: Uint8Array[] = [];\n let length = 0;\n try {\n // A redirect a fetcher followed after all (one that ignores `redirect`) still lands only on a host of the list.\n if (response.url && response.url !== url && !isAppFetchUrl(response.url)) throw new AppFetchError(\"host\", \"The host sent the request elsewhere\");\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"status\", `The host answered ${response.status}`, response.status);\n }\n if (!peek && Number(response.headers.get(\"content-length\")) > maxBytes) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"too-large\", \"Too large\");\n }\n const reader = response.body?.getReader();\n if (reader) {\n // A body the signal does not reach (a fetcher of its own) is let go all the same: its pending read ends.\n const letGo = () => { reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", letGo);\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw failure(signal.reason);\n if (done) break;\n heard();\n if (length + value.length > maxBytes) {\n if (!peek) throw new AppFetchError(\"too-large\", \"Too large\");\n parts.push(value.subarray(0, maxBytes - length));\n length = maxBytes;\n break;\n }\n parts.push(value);\n length += value.length;\n }\n } catch (error) {\n if (error instanceof AppFetchError) throw error;\n throw failure(error);\n } finally {\n signal.removeEventListener(\"abort\", letGo);\n await reader.cancel().catch(() => {});\n }\n }\n } finally { clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop); }\n const bytes = new Uint8Array(length);\n let at = 0;\n for (const part of parts) { bytes.set(part, at); at += part.length; }\n return bytes;\n };\n}\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * The URL a pasted address reads `file` from (WISP 1200 § Paste a URL), or null when it is not one this client reads:\n * - `https://github.com/<owner>/<repo>`, or `/tree/<ref>`: `raw.githubusercontent.com/<owner>/<repo>/<ref or HEAD>/<file>`,\n * with no request to `github.com` or `api.github.com`;\n * - a file as GitHub shows it, `https://github.com/<owner>/<repo>/blob/<ref>/<path>` (or `/raw/`), naming a `.ghostlyapp`\n * or `.json` file: `raw.githubusercontent.com/<owner>/<repo>/<ref>/<path>`, again with no request to `github.com`;\n * - a URL of the list that names a file (`….ghostlyapp`, `….json`): itself;\n * - a URL of the list that names a folder: `<file>` in it.\n */\nexport function appPasteUrl(input: string, file: \"app.ghostlyapp\" | \"ghostly-store.json\"): string | null {\n let url: URL;\n try { url = new URL(input.trim()); } catch { return null; }\n if (url.protocol !== \"https:\" || url.username || url.password || url.port) return null;\n const host = url.hostname.toLowerCase();\n if (host === \"github.com\" || host === \"www.github.com\") {\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n const owner = parts[0]!, repo = parts[1]!.replace(/\\.git$/, \"\");\n if (!NAME.test(owner) || !NAME.test(repo)) return null;\n let ref = \"HEAD\";\n if (parts.length > 2) {\n const rest = parts.slice(3);\n if (!rest.length || !rest.every((p) => NAME.test(p) && p !== \".\" && p !== \"..\")) return null;\n if (parts[2] === \"blob\" || parts[2] === \"raw\") {\n // `<ref>/<path>`: raw.githubusercontent.com takes the two joined the same way github.com does.\n if (rest.length < 2 || !/\\.(ghostlyapp|json)$/.test(rest[rest.length - 1]!)) return null;\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${rest.join(\"/\")}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n if (parts[2] !== \"tree\") return null;\n ref = rest.join(\"/\");\n }\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n const last = url.pathname.split(\"/\").pop() ?? \"\";\n const named = /\\.(ghostlyapp|json)$/.test(last) ? url.href : new URL(`${url.pathname.replace(/\\/?$/, \"/\")}${file}`, url).href;\n return isAppFetchUrl(named) ? named : null;\n}\n\n/** A page of github.com (any scheme): a link `appPasteUrl` could not read is still GitHub, and is answered as such. */\nexport function isGitHubPage(input: string): boolean {\n try {\n const host = new URL(input.trim()).hostname.toLowerCase();\n return host === \"github.com\" || host === \"www.github.com\";\n } catch { return false; }\n}\n\n/** A file beside another (`ghostly-store.sig` beside the index, `ghostly-revoke.json` beside a bundle). */\nexport function besideUrl(url: string, name: string): string {\n const target = new URL(url);\n target.search = \"\";\n target.hash = \"\";\n return new URL(name, target).href;\n}\n"],"mappings":";;;AAUA,IAAa,kBAAkB,CAAC,6BAA6B,kBAAkB;AAE/E,IAAa,mBAAmB;;;;;CAK9B,iBAAiB;;CAEjB,UAAU;;CAEV,kBAAkB;;CAElB,WAAW;;CAEX,QAAQ;;CAER,SAAS;AACX;;AAGA,SAAgB,cAAc,OAAiC;CAC7D,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,MAAM,IAAI,IAAI,KAAK;CACzB,OAAO,IAAI,SAAS,MAAO,gBAAsC,SAAS,IAAI,SAAS,YAAY,CAAC;AACtG;AAKA,IAAa,gBAAb,cAAmC,MAAM;CAClB;CAAmD;CAAxE,YAAY,MAAkC,SAAiB,QAA0B;EAEvF,MAAM,GAAG,KAAK,IAAI,SAAS;EAFR,KAAA,OAAA;EAAmD,KAAA,SAAA;EAGtE,KAAK,OAAO;CACd;AACF;AAYA,SAAgB,gBAAgB,UAAqH,CAAC,GAAe;CACnK,OAAO,OAAO,KAAK,EAAE,UAAU,OAAO,OAAO,aAAa,OAAO,QAAQ,cAAc;EACrF,IAAI,CAAC,cAAc,GAAG,GAAG,MAAM,IAAI,cAAc,QAAQ,qGAAqG;EAC9J,IAAI,QAAQ,UAAU,CAAC,QAAQ,OAAO,GAAG,MAAM,IAAI,cAAc,WAAW,SAAS;EACrF,IAAI,SAAS,SAAS,MAAM,IAAI,cAAc,WAAW,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ACA,MAAM,OAAO,IAAI,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC9C,MAAM,QAAQ,uBAAuB,KAAK,IAAI,IAAI,IAAI,OAAO,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,QAAQ,GAAG,IAAI,QAAQ,GAAG,CAAC,CAAC;CACzH,OAAO,cAAc,KAAK,IAAI,QAAQ;AACxC;;AAGA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,MAAM,OAAO,IAAI,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,SAAS,YAAY;EACxD,OAAO,SAAS,gBAAgB,SAAS;CAC3C,QAAQ;EAAE,OAAO;CAAO;AAC1B;;AAGA,SAAgB,UAAU,KAAa,MAAsB;CAC3D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,OAAO,SAAS;CAChB,OAAO,OAAO;CACd,OAAO,IAAI,IAAI,MAAM,MAAM,CAAC,CAAC;AAC/B"}
1
+ {"version":3,"file":"appFetch-C8yZIq1e.js","names":[],"sources":["../../../browser/src/engine/appFetch.ts"],"sourcesContent":["import { isAppUrl } from \"@ghostly/core\";\n\n/*\n * Where mini-apps and stores are read from (WISP 1200 § Stores, § Apps sent in a chat): in phase 1 only two hosts,\n * `raw.githubusercontent.com` and `cdn.jsdelivr.net` pinned to a full commit, both readable from a page (CORS `*`).\n * HTTPS only, no user or password, no port, no redirect (one would walk out of the list), no cookies, no referrer, and a\n * cap on the bytes read while the body streams in. Every read of the apps feature goes through `boundedAppFetch`.\n */\n\n/** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */\nexport const APP_FETCH_HOSTS = [\"raw.githubusercontent.com\", \"cdn.jsdelivr.net\"] as const;\n\nexport const APP_FETCH_LIMITS = {\n /**\n * A store index as read (WISP 1200 § Stores, Privacy): 4 MiB in phase 1, under the format's 16 MiB. Counted on the body\n * as it arrives, after the browser undid any compression, since a page never sees the compressed size.\n */\n storeIndexBytes: 4 * 1024 * 1024,\n /** A store's signature statement, `ghostly-store.sig` (canonical, at most 1 KiB). */\n sigBytes: 1024,\n /** `ghostly-revoke.json`: at most 4096 signed revocations. */\n revocationsBytes: 16 * 1024 * 1024,\n /** How long the host has to answer (the response's headers). */\n timeoutMs: 30_000,\n /** How long the body may go without a byte: a read still arriving is never cut by the clock alone. */\n idleMs: 30_000,\n /** A whole read at most: the 16 MiB cap at about 224 kbit/s. */\n totalMs: 10 * 60_000,\n} as const;\n\n/** A URL this client may read an app, a store or a revocation list from. */\nexport function isAppFetchUrl(value: unknown): value is string {\n if (!isAppUrl(value)) return false;\n const url = new URL(value);\n return url.port === \"\" && (APP_FETCH_HOSTS as readonly string[]).includes(url.hostname.toLowerCase());\n}\n\n/** `slow`: the host did not answer in time, went silent, or the read ran past its whole budget. */\nexport type AppFetchErrorCode = \"host\" | \"offline\" | \"status\" | \"too-large\" | \"network\" | \"slow\";\n\nexport class AppFetchError extends Error {\n constructor(readonly code: AppFetchErrorCode, message: string, readonly status?: number) {\n // Its code first, as every error of the apps calls (`<code>: words`).\n super(`${code}: ${message}`);\n this.name = \"AppFetchError\";\n }\n}\n\n/**\n * Reads a URL of the list: its bytes, at most `maxBytes`. With `peek`, the first `maxBytes` bytes and no more, the rest\n * left unread (a bundle's manifest, to see whether it is newer before reading all of it). `signal` stops a read whose\n * bytes nobody will use any more (`network`). `revalidate`: a file every update check reads again (a store's index and\n * its sig, `ghostly-revoke.json`), kept by the browser and asked again with its ETag every time, so an unchanged one is\n * an empty 304 and never a copy the host was not asked about. Anything else is not kept by the browser (a bundle is\n * kept in file storage, a peek is a range).\n */\nexport type AppFetcher = (url: string, options: { maxBytes: number; peek?: boolean; revalidate?: boolean; signal?: AbortSignal }) => Promise<Uint8Array>;\n\nexport function boundedAppFetch(options: { fetcher?: typeof fetch; online?: () => boolean; timeoutMs?: number; idleMs?: number; totalMs?: number } = {}): AppFetcher {\n return async (url, { maxBytes, peek = false, revalidate = false, signal: stopped }) => {\n if (!isAppFetchUrl(url)) throw new AppFetchError(\"host\", \"Apps are read only from raw.githubusercontent.com, or from cdn.jsdelivr.net at a commit, over HTTPS\");\n if (options.online && !options.online()) throw new AppFetchError(\"offline\", \"Offline\");\n if (stopped?.aborted) throw new AppFetchError(\"network\", \"The read was stopped\");\n const fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);\n // One signal for the request and its body: the host has `timeoutMs` to answer, then the body `idleMs` between two\n // bytes, the whole read `totalMs`. A read still arriving goes on; one cut by the clock is `slow`, not `network`.\n const controller = new AbortController();\n const cut = () => { controller.abort(new DOMException(\"The read took too long\", \"TimeoutError\")); };\n const stop = () => { controller.abort(new DOMException(\"The read was stopped\", \"AbortError\")); };\n stopped?.addEventListener(\"abort\", stop);\n const total = setTimeout(cut, options.totalMs ?? APP_FETCH_LIMITS.totalMs);\n let idle = setTimeout(cut, options.timeoutMs ?? APP_FETCH_LIMITS.timeoutMs);\n const heard = () => { clearTimeout(idle); idle = setTimeout(cut, options.idleMs ?? APP_FETCH_LIMITS.idleMs); };\n const failure = (error: unknown) => stopped?.aborted ? new AppFetchError(\"network\", \"The read was stopped\")\n : controller.signal.aborted ? new AppFetchError(\"slow\", \"That took too long on this connection\")\n : new AppFetchError(\"network\", error instanceof Error ? error.message : String(error));\n const { signal } = controller;\n let response: Response;\n try {\n response = await fetcher(url, {\n signal,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: revalidate && !peek ? \"no-cache\" : \"no-store\", redirect: \"error\",\n ...(peek && { headers: { range: `bytes=0-${maxBytes - 1}` } }),\n });\n } catch (error) {\n clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop);\n throw failure(error);\n }\n heard();\n const parts: Uint8Array[] = [];\n let length = 0;\n try {\n // A redirect a fetcher followed after all (one that ignores `redirect`) still lands only on a host of the list.\n if (response.url && response.url !== url && !isAppFetchUrl(response.url)) throw new AppFetchError(\"host\", \"The host sent the request elsewhere\");\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"status\", `The host answered ${response.status}`, response.status);\n }\n if (!peek && Number(response.headers.get(\"content-length\")) > maxBytes) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"too-large\", \"Too large\");\n }\n const reader = response.body?.getReader();\n if (reader) {\n // A body the signal does not reach (a fetcher of its own) is let go all the same: its pending read ends.\n const letGo = () => { reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", letGo);\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw failure(signal.reason);\n if (done) break;\n heard();\n if (length + value.length > maxBytes) {\n if (!peek) throw new AppFetchError(\"too-large\", \"Too large\");\n parts.push(value.subarray(0, maxBytes - length));\n length = maxBytes;\n break;\n }\n parts.push(value);\n length += value.length;\n }\n } catch (error) {\n if (error instanceof AppFetchError) throw error;\n throw failure(error);\n } finally {\n signal.removeEventListener(\"abort\", letGo);\n await reader.cancel().catch(() => {});\n }\n }\n } finally { clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop); }\n const bytes = new Uint8Array(length);\n let at = 0;\n for (const part of parts) { bytes.set(part, at); at += part.length; }\n return bytes;\n };\n}\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * The URL a pasted address reads `file` from (WISP 1200 § Paste a URL), or null when it is not one this client reads:\n * - `https://github.com/<owner>/<repo>`, or `/tree/<ref>`: `raw.githubusercontent.com/<owner>/<repo>/<ref or HEAD>/<file>`,\n * with no request to `github.com` or `api.github.com`;\n * - a file as GitHub shows it, `https://github.com/<owner>/<repo>/blob/<ref>/<path>` (or `/raw/`), naming a `.ghostlyapp`\n * or `.json` file: `raw.githubusercontent.com/<owner>/<repo>/<ref>/<path>`, again with no request to `github.com`;\n * - a URL of the list that names a file (`….ghostlyapp`, `….json`): itself;\n * - a URL of the list that names a folder: `<file>` in it.\n */\nexport function appPasteUrl(input: string, file: \"app.ghostlyapp\" | \"ghostly-store.json\"): string | null {\n let url: URL;\n try { url = new URL(input.trim()); } catch { return null; }\n if (url.protocol !== \"https:\" || url.username || url.password || url.port) return null;\n const host = url.hostname.toLowerCase();\n if (host === \"github.com\" || host === \"www.github.com\") {\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n const owner = parts[0]!, repo = parts[1]!.replace(/\\.git$/, \"\");\n if (!NAME.test(owner) || !NAME.test(repo)) return null;\n let ref = \"HEAD\";\n if (parts.length > 2) {\n const rest = parts.slice(3);\n if (!rest.length || !rest.every((p) => NAME.test(p) && p !== \".\" && p !== \"..\")) return null;\n if (parts[2] === \"blob\" || parts[2] === \"raw\") {\n // `<ref>/<path>`: raw.githubusercontent.com takes the two joined the same way github.com does.\n if (rest.length < 2 || !/\\.(ghostlyapp|json)$/.test(rest[rest.length - 1]!)) return null;\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${rest.join(\"/\")}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n if (parts[2] !== \"tree\") return null;\n ref = rest.join(\"/\");\n }\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n const last = url.pathname.split(\"/\").pop() ?? \"\";\n const named = /\\.(ghostlyapp|json)$/.test(last) ? url.href : new URL(`${url.pathname.replace(/\\/?$/, \"/\")}${file}`, url).href;\n return isAppFetchUrl(named) ? named : null;\n}\n\n/** A page of github.com (any scheme): a link `appPasteUrl` could not read is still GitHub, and is answered as such. */\nexport function isGitHubPage(input: string): boolean {\n try {\n const host = new URL(input.trim()).hostname.toLowerCase();\n return host === \"github.com\" || host === \"www.github.com\";\n } catch { return false; }\n}\n\n/** A file beside another (`ghostly-store.sig` beside the index, `ghostly-revoke.json` beside a bundle). */\nexport function besideUrl(url: string, name: string): string {\n const target = new URL(url);\n target.search = \"\";\n target.hash = \"\";\n return new URL(name, target).href;\n}\n"],"mappings":";;;AAUA,IAAa,kBAAkB,CAAC,6BAA6B,kBAAkB;AAE/E,IAAa,mBAAmB;;;;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