@ghostlytools/cli 1.13.0 → 1.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -10
- package/dist/assets/api-DV52o7A8.js +3 -0
- package/dist/assets/{api-CjOaoG-v.js → api-O57SNJcb.js} +495 -99
- package/dist/assets/api-O57SNJcb.js.map +1 -0
- package/dist/assets/{apiKit-BAGvlQtm.js → apiKit-CPTFJHA7.js} +40 -8
- package/dist/assets/{apiKit-BAGvlQtm.js.map → apiKit-CPTFJHA7.js.map} +1 -1
- package/dist/assets/{appFetch-BwJd-kNq.js → appFetch-Ca9DNQQ2.js} +2 -2
- package/dist/assets/{appFetch-BwJd-kNq.js.map → appFetch-Ca9DNQQ2.js.map} +1 -1
- package/dist/assets/{apps-Cuk45sz5.js → apps-gXpGFPiv.js} +16 -14
- package/dist/assets/apps-gXpGFPiv.js.map +1 -0
- package/dist/assets/{apps-DjY095Af.js → apps-uZTu5FlR.js} +1 -1
- package/dist/assets/{arkade-DryM-q5n.js → arkade-B6UNf5HI.js} +2 -2
- package/dist/assets/{arkade-DryM-q5n.js.map → arkade-B6UNf5HI.js.map} +1 -1
- package/dist/assets/{backup-DekVCDWv.js → backup-CxH3auHB.js} +9 -7
- package/dist/assets/backup-CxH3auHB.js.map +1 -0
- package/dist/assets/{backup-B56sQqoQ.js → backup-Di2U6QVH.js} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
- package/dist/assets/{bitcoind-B2bbVSzh.js → bitcoind-BpZn3bRN.js} +2 -2
- package/dist/assets/{bitcoind-B2bbVSzh.js.map → bitcoind-BpZn3bRN.js.map} +1 -1
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
- package/dist/assets/{buttons-BGxzOtrq.js → buttons-D4udKEvT.js} +8 -8
- package/dist/assets/buttons-D4udKEvT.js.map +1 -0
- package/dist/assets/buttons-YTYEqvGC.js +1 -0
- package/dist/assets/{client-DcQAfc3h.js → client-DGx7E8b3.js} +3 -3
- package/dist/assets/{client-DcQAfc3h.js.map → client-DGx7E8b3.js.map} +1 -1
- package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
- package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
- package/dist/assets/{engineErrors--9hfgKlK.js → engineErrors-wWlLy54D.js} +11 -3
- package/dist/assets/engineErrors-wWlLy54D.js.map +1 -0
- package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
- package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
- package/dist/assets/{fixedHosts-C3hBliM9.js → fixedHosts-CODN2pTL.js} +3 -3
- package/dist/assets/{fixedHosts-C3hBliM9.js.map → fixedHosts-CODN2pTL.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
- package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
- package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
- package/dist/assets/{groupMeta-goASqzOt.js → groupMeta-CeZpqVVC.js} +174 -37
- package/dist/assets/groupMeta-CeZpqVVC.js.map +1 -0
- package/dist/assets/{host-C2WRKj3g.js → host-CRA7h5A2.js} +270 -64
- package/dist/assets/host-CRA7h5A2.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-B34Zhz4P.js} +2 -2
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-B34Zhz4P.js.map} +1 -1
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-DDwU5b4P.js} +2 -2
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-DDwU5b4P.js.map} +1 -1
- package/dist/assets/{identityProofs-Cksc_K7_.js → identityProofs-B8zCp5_0.js} +140 -27
- package/dist/assets/identityProofs-B8zCp5_0.js.map +1 -0
- package/dist/assets/{irohWeb-NfthOL98.js → irohWeb-mnOi2Jp7.js} +10838 -4837
- package/dist/assets/irohWeb-mnOi2Jp7.js.map +1 -0
- package/dist/assets/{linkPreview-DdMf-YAc.js → linkPreview-5kHmKUTN.js} +20 -8
- package/dist/assets/linkPreview-5kHmKUTN.js.map +1 -0
- package/dist/assets/{main-Dh7fePd8.js → main-Chc871HV.js} +119 -81
- package/dist/assets/main-Chc871HV.js.map +1 -0
- package/dist/assets/{mainline-DY95WbuK.js → mainline-CDUXtV-I.js} +2 -2
- package/dist/assets/{mainline-DY95WbuK.js.map → mainline-CDUXtV-I.js.map} +1 -1
- package/dist/assets/{networkReason-Be-hMghr.js → networkReason-DYlPZS5M.js} +2 -2
- package/dist/assets/{networkReason-Be-hMghr.js.map → networkReason-DYlPZS5M.js.map} +1 -1
- package/dist/assets/{ownDid-BErplN7N.js → ownDid-BOuSlDv-.js} +10 -6
- package/dist/assets/ownDid-BOuSlDv-.js.map +1 -0
- package/dist/assets/{ownStatus-ClrFjd7h.js → ownStatus-CLA1VPkL.js} +6 -6
- package/dist/assets/{ownStatus-ClrFjd7h.js.map → ownStatus-CLA1VPkL.js.map} +1 -1
- package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-DAzupLYo.js} +23 -17
- package/dist/assets/pairedTransports-DAzupLYo.js.map +1 -0
- package/dist/assets/{paymentIntent-DySU3Ajm.js → paymentIntent-Cr3uZa_0.js} +2 -2
- package/dist/assets/{paymentIntent-DySU3Ajm.js.map → paymentIntent-Cr3uZa_0.js.map} +1 -1
- package/dist/assets/{profiles-B8xO8-oj.js → profiles-BH1bH9aE.js} +3 -3
- package/dist/assets/{profiles-B8xO8-oj.js.map → profiles-BH1bH9aE.js.map} +1 -1
- package/dist/assets/{registry--Rg2YvOH.js → registry-DAq16T-V.js} +1 -1
- package/dist/assets/{registry-CU8PevhI.js → registry-DP_-RA-v.js} +11 -7
- package/dist/assets/registry-DP_-RA-v.js.map +1 -0
- package/dist/assets/{relay-CHWg5hpZ.js → relay-gJTOYQJZ.js} +93 -7
- package/dist/assets/relay-gJTOYQJZ.js.map +1 -0
- package/dist/assets/{resolve-B1upovPM.js → resolve-B1eQ4dVQ.js} +10 -5
- package/dist/assets/resolve-B1eQ4dVQ.js.map +1 -0
- package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
- package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
- package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
- package/dist/assets/{server-Dgxx_DaN.js → server-Bd2ofxc1.js} +1283 -6628
- package/dist/assets/server-Bd2ofxc1.js.map +1 -0
- package/dist/assets/{sshForges-BnvwmNj-.js → sshForges-As7dbGXM.js} +2 -2
- package/dist/assets/{sshForges-BnvwmNj-.js.map → sshForges-As7dbGXM.js.map} +1 -1
- package/dist/assets/{translate-BcbSWkuq.js → translate-DnuQMfj0.js} +22 -11
- package/dist/assets/translate-DnuQMfj0.js.map +1 -0
- package/dist/assets/{usdt-CBJ4Q5Ji.js → usdt-DLmtf8F9.js} +4 -4
- package/dist/assets/{usdt-CBJ4Q5Ji.js.map → usdt-DLmtf8F9.js.map} +1 -1
- package/dist/assets/{waitNotice-ylU3XwjO.js → waitNotice-BHuMofaH.js} +57 -3
- package/dist/assets/waitNotice-BHuMofaH.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-CVtg7MpI.js +0 -3
- package/dist/assets/api-CjOaoG-v.js.map +0 -1
- package/dist/assets/apps-Cuk45sz5.js.map +0 -1
- package/dist/assets/backup-DekVCDWv.js.map +0 -1
- package/dist/assets/buttons-BGxzOtrq.js.map +0 -1
- package/dist/assets/buttons-CsN2WJOf.js +0 -1
- package/dist/assets/engineErrors--9hfgKlK.js.map +0 -1
- package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
- package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
- package/dist/assets/groupMeta-goASqzOt.js.map +0 -1
- package/dist/assets/host-C2WRKj3g.js.map +0 -1
- package/dist/assets/identityProofs-Cksc_K7_.js.map +0 -1
- package/dist/assets/irohWeb-NfthOL98.js.map +0 -1
- package/dist/assets/linkPreview-DdMf-YAc.js.map +0 -1
- package/dist/assets/main-Dh7fePd8.js.map +0 -1
- package/dist/assets/ownDid-BErplN7N.js.map +0 -1
- package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
- package/dist/assets/registry-CU8PevhI.js.map +0 -1
- package/dist/assets/relay-CHWg5hpZ.js.map +0 -1
- package/dist/assets/resolve-B1upovPM.js.map +0 -1
- package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
- package/dist/assets/server-Dgxx_DaN.js.map +0 -1
- package/dist/assets/translate-BcbSWkuq.js.map +0 -1
- package/dist/assets/waitNotice-ylU3XwjO.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"translate-BcbSWkuq.js","names":["EMOJI","runtimePackage"],"sources":["../../../../native/translation/package.json","../../../../apps/ui/src/lib/parse/blob.ts","../../../../apps/ui/src/lib/parse/links.ts","../../../../apps/ui/src/lib/parse/inline.ts","../../../../apps/ui/src/lib/parse/mdlink.ts","../../../../apps/ui/src/lib/parse/mentions.ts","../../../../apps/ui/src/lib/parse/time.ts","../../../../apps/ui/src/lib/parse/detectors.ts","../../../../apps/ui/src/lib/parse/json.ts","../../../../apps/ui/src/lib/parse/blocks.ts","../../../../apps/ui/src/lib/translateWhich.ts","../../src/translate.ts"],"sourcesContent":["{\n \"name\": \"ghostly-translation-native\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": { \"@qvac/translation-nmtcpp\": \"0.21.1\", \"bare-process\": \"4.5.1\", \"bare-runtime\": \"1.36.0\" }\n}\n","import type { Atom, Detector } from \"./types\";\n\n/** How long an unbroken key-like run must be before it folds to one line. */\nexport const BLOB_MIN = 80;\n\n/**\n * A long run with no spaces made of base64, base64url or hex characters: a key, a signature, a token pasted in\n * full. It folds to one line with \"Show all\" and Copy. Links and money come first (a link's path is never a blob,\n * and a Cashu token or an invoice has its own card).\n */\nexport const blob: Detector<\"blob\", null> = {\n kind: \"blob\",\n pattern: new RegExp(`(?<![A-Za-z0-9+/=_-])[A-Za-z0-9+/_-]{${BLOB_MIN},}={0,2}(?![A-Za-z0-9+/=_-])`, \"g\"),\n accept: () => ({ data: null }),\n plain: (atom: Atom<\"blob\", null>) => `${atom.text.slice(0, 12)}…`,\n};\n","import { LINK_TRAILING, linkStop, linkTail } from \"@ghostly/core\";\nimport type { Detector } from \"./types\";\n\nconst CLOSERS: Record<string, string> = { \")\": \"(\", \"]\": \"[\", \"}\": \"{\" };\n\n/**\n * A link ends where the sentence around it takes over: trailing punctuation (\"see https://x.example/a.\", \"見て\n * https://x.example/a。\", in any of the app's languages), an emoji or invisible character (\"https://x.example/a🔥\",\n * `linkTail`) and a closing bracket or quote the link did not open (\"(https://x.example/a)\") are left as text, and so\n * is a doubled `~~` or `||` closing the strike or spoiler the link sits in.\n */\nexport function linkEnd(whole: string): string {\n const url = linkStop(whole);\n const count: Record<string, number> = { \"(\": 0, \")\": 0, \"[\": 0, \"]\": 0, \"{\": 0, \"}\": 0 };\n for (const c of url) if (c in count) count[c]++;\n let end = url.length;\n while (end > 0) {\n const last = url[end - 1];\n const opener = CLOSERS[last];\n const tail = linkTail(url, end);\n if (tail) end -= tail;\n else if (LINK_TRAILING.test(last) || (opener && count[last] > count[opener])) {\n if (opener) count[last]--;\n end--;\n } else if ((last === \"~\" || last === \"|\") && url[end - 2] === last) end -= 2;\n else break;\n }\n return url.slice(0, end);\n}\n\n/**\n * Characters that draw as nothing, which can make a link read as another address: format characters (direction\n * marks and overrides, zero-width ones, the soft hyphen, tags, interlinear annotation, shorthand and musical format\n * controls), everything Unicode marks as ignorable by default (the grapheme joiner, the Hangul fillers, variation\n * selectors, the Khmer inherent vowels, the Mongolian free variation selectors), and the line and paragraph\n * separators. Spelled out as well as by property, so none of them depends on the engine's Unicode version.\n */\nexport const INVISIBLE =\n /[\\p{Cf}\\p{Default_Ignorable_Code_Point}\\u115f\\u1160\\u180e\\u2028\\u2029\\u3164\\uffa0\\ufff9-\\ufffb\\u{1bca0}-\\u{1bca3}\\u{1d173}-\\u{1d17a}\\u{e0000}-\\u{e007f}]|\\u034f|[\\u17b4\\u17b5]|[\\u180b-\\u180d]|\\u180f|[\\ufe00-\\ufe0f]|[\\u{e0100}-\\u{e01ef}]/gu;\n\n/**\n * A link as a bubble shows it. Plain ASCII whose host the browser reads as typed shows as typed. Anything else shows\n * as the browser reads it: the host in punycode (a look-alike \"аpple.com\" reads \"xn--pple-43d.com\"), escapes in it\n * decoded (\"paypal.com%2Eevil.example\" opens \"paypal.com.evil.example\") and other characters percent-encoded, so a\n * right-to-left override inside it cannot turn the address around. A user part (\"www.paypal.com@evil.example\")\n * is left out, so what reads as the host is the one the link opens. What no URL parser takes loses its invisible\n * characters.\n */\nexport function shownUrl(url: string): string {\n let parsed: URL;\n try { parsed = new URL(url); } catch { return url.replace(INVISIBLE, \"\"); }\n if (parsed.username || parsed.password) {\n parsed.username = \"\";\n parsed.password = \"\";\n return parsed.href;\n }\n const typedHost = /^[a-z][a-z\\d+.-]*:\\/\\/([^/?#\\\\]*)/i.exec(url)?.[1].replace(/:\\d*$/, \"\").toLowerCase();\n return /^[\\x21-\\x7e]*$/.test(url) && typedHost === parsed.hostname ? url : parsed.href;\n}\n\n/** Web addresses, over http(s) only: `javascript:` and `data:` never become links. */\nexport const link: Detector<\"link\", { url: string }> = {\n kind: \"link\",\n pattern: /https?:\\/\\/\\S+/gi,\n lead: /https?:\\/\\//gi,\n accept(match) {\n const url = linkEnd(match[0]);\n // \"https://\" and nothing else is not a place.\n if (url.length <= match[0].indexOf(\"//\") + 2) return null;\n return { data: { url }, end: match.index + url.length };\n },\n // The chat list reads it as the bubble shows it, not as typed.\n plain: (atom) => shownUrl(atom.text),\n};\n","import type { Detector, ParseContext, Segment, SpanStyle } from \"./types\";\n\n/**\n * The inline tokenizer: a paragraph's text in, segments out. Three passes, each linear in the text:\n *\n * 1. `code`: backtick spans (a run of N backticks up to the next run of exactly N on the same line). What is\n * inside is never read again: no links, no markers.\n * 2. Detectors, over the text between code spans: links, long blobs, times, and whatever other cards register.\n * What they recognise is opaque too, so a `*` or `_` inside a URL stays part of it.\n * 3. Markers, over what is left: `*bold*` (or `**bold**`), `_italic_` (or `__italic__`), `~~strike~~` and\n * `||spoiler||`, paired within a line. A marker opens after a space, a punctuation mark or the start, before\n * something that is not a space, and closes the other way round, so `snake_case_name`, `2*3*4` and\n * `__init__.py` stay text. Openers left unclosed, and closers with no opener, are text too.\n */\n\n/** What a spoiler reads as where it cannot be tapped: nothing of what it hides. */\nexport const SPOILER_PLAIN = \"▒▒▒\";\n\n/** Which runs of marker characters mean something, and what. A run of any other length is text. */\nconst MARKERS: Record<string, SpanStyle> = { \"*\": \"bold\", \"**\": \"bold\", \"_\": \"italic\", \"__\": \"italic\", \"~~\": \"strike\", \"||\": \"spoiler\" };\nconst MARKER_CHARS = new Set([\"*\", \"_\", \"~\", \"|\"]);\n\n/** Punctuation or a symbol: what a marker may lean on besides a space. */\nconst PUNCT = /[\\p{P}\\p{S}]/u;\nconst SPACE = /\\s/u;\nconst WORD = /[\\p{L}\\p{N}]/u;\n\nconst compiled = new WeakMap<RegExp, RegExp>();\nfunction globalOf(pattern: RegExp): RegExp {\n let re = compiled.get(pattern);\n if (!re) {\n const { source, flags } = pattern;\n re = new RegExp(source, flags.includes(\"g\") ? flags : flags + \"g\");\n compiled.set(pattern, re);\n }\n return re;\n}\nconst patternOf = (detector: Detector) => globalOf(detector.pattern);\n\ntype Found = { start: number; end: number; data: unknown };\n/** Where a detector's next match may start (its `lead`), not yet read: none starts before `start`. */\ntype Lead = { start: number; lead: true };\n\n/** The detector's next accepted match in `text` at or after `from`. */\nfunction findNext(detector: Detector, text: string, from: number, ctx: ParseContext): Found | null {\n const re = patternOf(detector);\n let at = from;\n while (at <= text.length) {\n re.lastIndex = at;\n const match = re.exec(text);\n if (!match) return null;\n const accepted = match[0] ? detector.accept(match, text, ctx) : null;\n const matchEnd = match.index + match[0].length;\n if (accepted) {\n const end = Math.min(accepted.end ?? matchEnd, matchEnd);\n if (end > match.index) return { start: match.index, end, data: accepted.data };\n }\n at = Math.max(matchEnd, match.index + 1);\n }\n return null;\n}\n\ntype Item = { t: \"text\"; s: string } | { t: \"seg\"; seg: Segment } | Mark;\ninterface Mark { t: \"mark\"; run: string; canOpen: boolean; canClose: boolean; pair?: \"open\" | \"close\" }\n\n/** The detector's next match at or after `from`, or only where it may start when it has a `lead`. */\nfunction nextFrom(detector: Detector, text: string, from: number, ctx: ParseContext): Found | Lead | null {\n if (!detector.lead) return findNext(detector, text, from, ctx);\n const re = globalOf(detector.lead);\n re.lastIndex = from;\n const hit = re.exec(text);\n return hit ? { start: hit.index, lead: true } : null;\n}\n\n/** Pass 2: the detectors' atoms in a stretch of text outside code, and the text between them. */\nfunction detect(text: string, detectors: readonly Detector[], ctx: ParseContext, out: (string | Segment)[]) {\n const next = detectors.map((d) => nextFrom(d, text, 0, ctx));\n let cursor = 0;\n for (;;) {\n let best = -1;\n for (let i = 0; i < next.length; i++) {\n const found = next[i];\n if (found && (best < 0 || found.start < next[best]!.start)) best = i;\n }\n if (best < 0) break;\n const first = next[best]!;\n // A lead is read only once it comes first: its match starts there or later, and is looked at again.\n if (\"lead\" in first) { next[best] = findNext(detectors[best], text, first.start, ctx); continue; }\n const found = first;\n if (found.start > cursor) out.push(text.slice(cursor, found.start));\n const detector = detectors[best];\n out.push({ type: \"atom\", kind: detector.kind, text: text.slice(found.start, found.end), data: found.data });\n cursor = found.end;\n // Whatever started inside the atom is gone; look again from its end.\n for (let i = 0; i < next.length; i++) if (next[i] && next[i]!.start < cursor) next[i] = nextFrom(detectors[i], text, cursor, ctx);\n }\n if (cursor < text.length) out.push(text.slice(cursor));\n}\n\n/** Pass 1: code spans. Backtick runs pair with the next run of the same length on the same line. */\nfunction codeSpans(text: string): (string | Segment)[] {\n const out: (string | Segment)[] = [];\n const runs: { at: number; len: number }[] = [];\n for (let i = 0; i < text.length; i++) {\n if (text[i] !== \"`\") continue;\n let j = i;\n while (text[j] === \"`\") j++;\n runs.push({ at: i, len: j - i });\n i = j - 1;\n }\n if (!runs.length) return [text];\n // For each run, the next run of the same length (found right to left, so this stays linear).\n const nextSame = new Array<number>(runs.length).fill(-1);\n const seen = new Map<number, number>();\n for (let i = runs.length - 1; i >= 0; i--) {\n nextSame[i] = seen.get(runs[i].len) ?? -1;\n seen.set(runs[i].len, i);\n }\n // Where each line ends, so a span never crosses one.\n const lineEnd = (at: number) => { const n = text.indexOf(\"\\n\", at); return n < 0 ? text.length : n; };\n let cursor = 0;\n let endOfLine = -1;\n for (let i = 0; i < runs.length; i++) {\n const open = runs[i];\n if (open.at < cursor) continue;\n if (open.at > endOfLine) endOfLine = lineEnd(open.at);\n const j = nextSame[i];\n if (j < 0) continue;\n const close = runs[j];\n const inner = text.slice(open.at + open.len, close.at);\n if (close.at > endOfLine || !inner.trim()) continue;\n if (open.at > cursor) out.push(text.slice(cursor, open.at));\n // As in Markdown, one space on each side lets a span start or end with a backtick.\n out.push({ type: \"code\", text: inner.length > 2 && inner[0] === \" \" && inner[inner.length - 1] === \" \" ? inner.slice(1, -1) : inner });\n cursor = close.at + close.len;\n i = j;\n }\n if (cursor < text.length) out.push(text.slice(cursor));\n return out;\n}\n\n/**\n * Pass 3, splitting: text into plain stretches and marker runs that could open or close something. `before` and\n * `after` are the characters around the text in the message (an atom's or a code span's edge counts as a word\n * character there: \"*see https://x.example*\" closes after the link).\n */\nfunction splitMarkers(text: string, prev: string | undefined, nextChar: string | undefined, items: Item[]) {\n let from = 0;\n for (let i = 0; i < text.length; i++) {\n if (!MARKER_CHARS.has(text[i])) continue;\n let j = i;\n while (text[j] === text[i]) j++;\n const run = text.slice(i, j);\n if (MARKERS[run]) {\n if (i > from) items.push({ t: \"text\", s: text.slice(from, i) });\n const before = i > 0 ? text[i - 1] : prev;\n const after = j < text.length ? text[j] : nextChar;\n const afterNext = j + 1 < text.length ? text[j + 1] : undefined;\n const mark: Mark = {\n t: \"mark\",\n run,\n canOpen: after !== undefined && !SPACE.test(after) && (before === undefined || SPACE.test(before) || (PUNCT.test(before) && before !== run[0])),\n canClose:\n before !== undefined && !SPACE.test(before) && (after === undefined || SPACE.test(after) || (PUNCT.test(after) && after !== run[0]))\n // \"__init__.py\": a full stop or colon followed straight by a word is part of a name, not the sentence.\n && !(after !== undefined && /[.,:;]/.test(after) && afterNext !== undefined && WORD.test(afterNext)),\n };\n items.push(mark);\n from = j;\n }\n i = j - 1;\n }\n if (from < text.length) items.push({ t: \"text\", s: text.slice(from) });\n}\n\n/**\n * The most styles open inside one another. Past it a marker stays text: a peer's message cannot nest spans\n * thousands deep, which every recursive reader of the tree (the bubble, the chat list's preview) would follow.\n */\nexport const MAX_SPAN_DEPTH = 8;\n\n/** Pass 3, pairing: per-run stacks, so a closer finds its opener in O(1) and each marker is dropped at most once. */\nfunction pairMarkers(items: Item[]) {\n // Open markers in order, where each one sits in that list, and the same markers per run.\n const stack: number[] = [];\n const depthOf = new Int32Array(items.length);\n const byRun = new Map<string, number[]>();\n const popTo = (depth: number) => {\n while (stack.length > depth) byRun.get((items[stack.pop()!] as Mark).run)!.pop();\n };\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n if (item.t === \"text\") {\n // Markers pair within a line.\n if (item.s.includes(\"\\n\")) popTo(0);\n continue;\n }\n if (item.t !== \"mark\") continue;\n const openers = byRun.get(item.run);\n if (item.canClose && openers?.length) {\n const opener = openers[openers.length - 1];\n // Whatever opened after it and is still open never closes: \"*a _b* c_\" is bold \"a _b\", then text.\n popTo(depthOf[opener]);\n (items[opener] as Mark).pair = \"open\";\n item.pair = \"close\";\n } else if (item.canOpen && stack.length < MAX_SPAN_DEPTH) {\n depthOf[i] = stack.length;\n stack.push(i);\n if (openers) openers.push(i);\n else byRun.set(item.run, [i]);\n }\n }\n}\n\n/** The paired items as a tree; unpaired markers are text, and neighbouring text is joined. */\nfunction build(items: Item[]): Segment[] {\n const root: Segment[] = [];\n const parents: Segment[][] = [root];\n const push = (seg: Segment) => {\n const list = parents[parents.length - 1];\n const last = list[list.length - 1];\n if (seg.type === \"text\" && last?.type === \"text\") last.text += seg.text;\n else list.push(seg);\n };\n for (const item of items) {\n if (item.t === \"text\") push({ type: \"text\", text: item.s });\n else if (item.t === \"seg\") push(item.seg);\n else if (item.pair === \"open\") {\n const span = { type: \"span\" as const, style: MARKERS[item.run], children: [] as Segment[] };\n push(span);\n parents.push(span.children);\n } else if (item.pair === \"close\") {\n parents.pop();\n } else push({ type: \"text\", text: item.run });\n }\n return root;\n}\n\n/** One paragraph's segments. `detectors` is the registry's list unless a test gives its own. */\nexport function tokenizeInline(text: string, detectors: readonly Detector[], ctx: ParseContext = {}): Segment[] {\n const pieces: (string | Segment)[] = [];\n for (const piece of codeSpans(text)) {\n if (typeof piece === \"string\") detect(piece, detectors, ctx, pieces);\n else pieces.push(piece);\n }\n const items: Item[] = [];\n // What sits on either side of a stretch of text: an atom's or a code span's edge reads as a word character.\n const edge = (piece: string | Segment | undefined, first: boolean) =>\n piece === undefined ? undefined : typeof piece === \"string\" ? piece[first ? 0 : piece.length - 1] : \"a\";\n pieces.forEach((piece, i) => {\n if (typeof piece === \"string\") splitMarkers(piece, edge(pieces[i - 1], false), edge(pieces[i + 1], true), items);\n else items.push({ t: \"seg\", seg: piece });\n });\n pairMarkers(items);\n return build(items);\n}\n","import { SPOILER_PLAIN, tokenizeInline } from \"./inline\";\nimport { INVISIBLE, shownUrl } from \"./links\";\nimport type { Atom, Detector, Segment } from \"./types\";\n\nexport interface MdLinkData {\n url: string;\n /** What the author wrote between the brackets, formatting read (no links or other atoms inside). */\n label: Segment[];\n /** True when the label reads as another address than the link's: the bubble shows the address instead. */\n showUrl: boolean;\n}\n\n/** The link's host as a browser reads it: lower case, punycode, without a leading \"www.\". */\nfunction hostOf(url: string): string | null {\n try {\n return new URL(url).hostname.replace(/^www\\./, \"\");\n } catch {\n return null;\n }\n}\n\n/** Something in a label that reads as a web address or a domain: \"ghostly.tools\", \"https://a.example/x\", \"1.2.3.4\". */\nconst ADDRESS = /(?:[a-z][a-z\\d+.-]{0,20}:\\/\\/)?[\\p{L}\\p{N}][\\p{L}\\p{N}-]{0,62}(?:\\.[\\p{L}\\p{N}][\\p{L}\\p{N}-]{0,62}){1,8}/giu;\n/** Ends in a top-level domain (letters), or is an IPv4 address. \"v1.2\", \"3.14\" and \"e.g.\" are not hosts. */\nconst LOOKS_LIKE_HOST = /\\.\\p{L}[\\p{L}\\p{N}-]{1,62}$|^\\d{1,3}(?:\\.\\d{1,3}){3}$/u;\n/** File extensions no top-level domain uses: \"report.pdf\", \"Node.js\" and \"package.json\" are names, not hosts. */\nconst NOT_A_TLD = /\\.(?:[cm]?js|jsx|tsx?|json|css|html?|txt|log|csv|png|jpe?g|gif|svg|webp|toml|ya?ml|lock|wasm|pdf|rb|go)$/i;\n/** Extensions that are country domains too (Moldova, Paraguay…): a file only as a path's last part (\"docs/CHAT.md\"). */\nconst FILE_IN_PATH = /\\.(?:md|py|rs|sh)$/i;\n/**\n * Characters a browser reads as the dot between a host's labels, and ones that only look like it (Unicode's\n * confusables of \".\" and the middle, raised and word-separator dots fonts draw like it). Read before NFKC (\"˙\" would\n * become a space and an accent) and after it (\"・\" becomes \"・\"). The combining dots stand alone, outside the class.\n */\nconst DOTS =\n /[\\u00b7\\u02d9\\u0660\\u06d4\\u06f0\\u0701\\u0702\\u0f0b\\u0f0c\\u1427\\u16eb\\u2022\\u2024\\u2027\\u2219\\u22c5\\u2e30\\u2e31\\u2e33\\u2e3c\\u3002\\u30fb\\u318d\\ua4f8\\ua60e\\ua78f\\uff0e\\uff61\\u{10a50}\\u2981]|\\u0323|\\u{1d16d}/gu;\n\n/**\n * A whole emoji: a keycap (\"1️⃣\"), a flag drawn from tags (🏴 and its tag letters), or pictographs joined by zero-width\n * joiners, each with its variation selector or skin tone (\"❤️\", \"👩🏽💻\"). Their invisible parts are drawn as part of\n * the emoji, so they hide nothing; the same characters anywhere else still count.\n */\nconst EMOJI =\n /[#*0-9]️?⃣|\\u{1f3f4}[\\u{e0020}-\\u{e007e}]+\\u{e007f}|\\p{Extended_Pictographic}(?:[︎️]|\\p{Emoji_Modifier})?(?:\\p{Extended_Pictographic}(?:[︎️]|\\p{Emoji_Modifier})?)*/gu;\n\n/**\n * Whether a link's text would make a reader think it goes somewhere else: it names a host that is not the link's (nor\n * one the link's host sits under), or it holds an invisible or direction character, which can turn \"moc.lapyap\"\n * into \"paypal.com\" on screen. The text is read as a browser would read a host (\"ghostly。tools\" and \"ghostly.tools\"\n * are \"ghostly.tools\"). File names are left alone (\"report.pdf\", \"docs/CHAT.md\"); anything else that reads as a\n * host counts, which errs on the safe side: the bubble shows the address.\n */\nexport function labelMisleads(label: string, url: string): boolean {\n const target = hostOf(url);\n if (!target) return true;\n if (new RegExp(INVISIBLE.source, \"u\").test(label.replace(EMOJI, \"\"))) return true;\n const text = label.replace(DOTS, \".\").normalize(\"NFKC\").replace(DOTS, \".\");\n for (const found of text.matchAll(ADDRESS)) {\n const written = found[0];\n const bare = written.replace(/^[a-z][a-z\\d+.-]*:\\/\\//i, \"\");\n if (bare === written) {\n if (!LOOKS_LIKE_HOST.test(bare) || NOT_A_TLD.test(bare)) continue;\n // \"docs/CHAT.md\": after a path's slash (not the \"//\" of an address).\n const at = found.index;\n if (FILE_IN_PATH.test(bare) && text[at - 1] === \"/\" && at > 1 && !/[/:]/.test(text[at - 2])) continue;\n }\n const host = hostOf(`https://${bare}`);\n if (!host) return true;\n if (host !== target && !target.endsWith(`.${host}`)) return true;\n }\n return false;\n}\n\n/** A label's words without its markers, for the chat list; `revealed` reads a spoiler's words as a tap shows them. */\nfunction labelText(label: Segment[], revealed = false): string {\n return label\n .map((s) => (s.type === \"span\" ? (s.style === \"spoiler\" && !revealed ? SPOILER_PLAIN : labelText(s.children, revealed)) : s.text))\n .join(\"\");\n}\n\n/**\n * `[text](https://…)`: the text as a link, over http(s) only (`[a](javascript:…)` stays text). The address may hold\n * one pair of brackets (\"…/Foo_(bar)\"); both parts are bounded, so the pattern stays linear.\n */\nexport const mdLink: Detector<\"md-link\", MdLinkData> = {\n kind: \"md-link\",\n pattern: /\\[([^[\\]\\n]{1,200})\\]\\((https?:\\/\\/[^\\s()<>]{1,4096}(?:\\([^\\s()<>]{0,256}\\)[^\\s()<>]{0,1024})?)\\)/gi,\n accept(match) {\n const [, text, url] = match;\n if (!text.trim() || !hostOf(url)) return null;\n const label = tokenizeInline(text, []);\n // The written text, and the words the bubble draws: markers can split a host (\"paypal.**com**\") it shows whole.\n const showUrl = labelMisleads(text, url) || labelMisleads(labelText(label, true), url);\n return { data: { url, label, showUrl } };\n },\n plain(atom: Atom<\"md-link\", MdLinkData>) {\n return atom.data.showUrl ? shownUrl(atom.data.url) : labelText(atom.data.label);\n },\n};\n","import { MENTION_EVERYONE, MENTION_LIMITS, type GroupMention } from \"@ghostly/core\";\nimport type { Atom, Detector } from \"./types\";\n\n/*\n * Mentions in a group's composer and bubbles (WISP 902 § Mentions). The composer keeps which member each \"@Name\"\n * it inserted stands for; on send, every place the text still has that token becomes a mention bound to the\n * member's key. A bubble then shows each mention with the member's name as it is now.\n */\n\n/** A member the picker offers: `name` as the group shows them, `tag` a short piece of their key. */\nexport interface MentionCandidate { key: string; name: string; tag: string }\n/**\n * What the composer inserted: `@${label}` for `key` (`MENTION_EVERYONE` for everyone), at `at` (the UTF-16 index of its\n * \"@\" in the field, moved along as the text changes: `moveChosen`). Without `at`, every place the token stands is it.\n */\nexport interface ChosenMention { key: string; label: string; at?: number }\n/** The \"@…\" being typed at the caret: `start` is the \"@\", `end` the caret (UTF-16 indices, as the textarea has them). */\nexport interface MentionQuery { start: number; end: number; query: string }\n/**\n * A mention as a bubble shows it: its place (code points), the name to show, whether it names me, and what the\n * message has at that place (without the \"@\").\n */\nexport interface MentionView { o: number; l: number; key: string; name: string; me: boolean; written?: string }\n\n/** How much of a name the picker is asked about. */\nconst QUERY_CHARS = 32;\n/**\n * A key is matched from this many characters on, by its start or the piece the picker shows: two letters are found\n * somewhere in most 52-character keys, and \"@Bo\" must not offer Carol.\n */\nconst KEY_QUERY_CHARS = 3;\n/** Rows the picker shows. */\nexport const PICKER_ROWS = 8;\n\n/**\n * The \"@…\" the caret is at the end of, or null: an \"@\" at the start of the text or after a space or an opening\n * bracket (so an address like a@b.example is not one), followed by up to 32 characters with no space or \"@\".\n */\nexport function mentionQueryAt(text: string, caret: number): MentionQuery | null {\n const match = /(?:^|[\\s([{\"'])@([^\\s@]{0,32})$/u.exec(text.slice(0, caret));\n if (!match) return null;\n return { start: caret - match[1].length - 1, end: caret, query: match[1].slice(0, QUERY_CHARS) };\n}\n\nconst fold = (s: string) => s.normalize(\"NFD\").replace(/\\p{M}/gu, \"\").toLowerCase();\n\n/**\n * The members that fit what was typed, best first: a name starting with it, then a word of the name starting with\n * it, then a key starting with it or a shown piece of key containing it (three characters or more). An empty query\n * lists everyone, in the order given.\n */\nexport function filterCandidates(candidates: readonly MentionCandidate[], query: string): MentionCandidate[] {\n const q = fold(query);\n if (!q) return candidates.slice(0, PICKER_ROWS);\n const rank = (c: MentionCandidate) => {\n const name = fold(c.name);\n if (name.startsWith(q)) return 0;\n if (name.split(/[\\s._-]+/u).some(word => word.startsWith(q))) return 1;\n return q.length >= KEY_QUERY_CHARS && (c.key.toLowerCase().startsWith(q) || fold(c.tag).includes(q)) ? 2 : 3;\n };\n return candidates.map(c => ({ c, r: rank(c) })).filter(x => x.r < 3).sort((a, b) => a.r - b.r).map(x => x.c).slice(0, PICKER_ROWS);\n}\n\n/** The text with the query replaced by \"@label \" and the caret after the space. */\nexport function insertMention(text: string, query: MentionQuery, label: string): { text: string; caret: number } {\n const token = `@${label} `;\n const after = text.slice(query.end).replace(/^ /, \"\");\n return { text: text.slice(0, query.start) + token + after, caret: query.start + token.length };\n}\n\n/** What a member's token says after the \"@\": their name, with no \"@\" in it and not longer than a mention may be. */\nexport function mentionLabel(name: string): string {\n const clean = name.replace(/@/g, \"\").replace(/\\s+/g, \" \").trim();\n return Array.from(clean).slice(0, MENTION_LIMITS.chars - 1).join(\"\").trim() || \"member\";\n}\n\nconst wordChar = /[\\p{L}\\p{N}_]/u;\n\n/**\n * The chosen mentions of a field whose text went from `before` to `after`, each moved with the text around it: one\n * whose token the change touched is dropped (edited away). `caret`, where the caret is after the change, tells where\n * it was when the same words stand twice (\"@Bob @Bob\" losing one); without it, or when it does not fit, the change is\n * taken as what lies between the text the two have in common at the start and at the end.\n */\nexport function moveChosen(chosen: readonly ChosenMention[], before: string, after: string, caret?: number | null): ChosenMention[] {\n if (before === after || !chosen.some(c => c.at !== undefined)) return [...chosen];\n const grown = after.length - before.length;\n // The change, as [from, to) in `before` replaced by [from, to + grown) in `after`.\n let from: number, to: number;\n const fits = (f: number, t: number) => f >= 0 && t >= f && t <= before.length && t + grown >= f && t + grown <= after.length\n && before.slice(0, f) === after.slice(0, f) && before.slice(t) === after.slice(t + grown);\n const typed = caret ?? -1;\n if (grown >= 0 && fits(typed - grown, typed - grown)) [from, to] = [typed - grown, typed - grown];\n else if (grown < 0 && fits(typed, typed - grown)) [from, to] = [typed, typed - grown];\n else {\n from = 0;\n while (from < before.length && from < after.length && before[from] === after[from]) from++;\n let tail = 0;\n while (tail < before.length - from && tail < after.length - from && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail++;\n to = before.length - tail;\n }\n return chosen.flatMap(c => {\n if (c.at === undefined) return [c];\n const end = c.at + c.label.length + 1;\n if (end <= from) return [c];\n if (c.at >= to) return [{ ...c, at: c.at + grown }];\n return [];\n });\n}\n\n/**\n * The mentions of a text about to be sent (trimmed, as the group sends it), in code points, in order, at most\n * `MENTION_LIMITS.count`: each chosen token that still stands whole at its place (`at`), bound to the member chosen\n * there, so two members who go by one name are each named where they were picked; a choice with no place names every\n * place its token stands that no other choice holds. A token edited away is simply no mention.\n */\nexport function composeMentions(text: string, chosen: readonly ChosenMention[]): GroupMention[] {\n const trimmed = text.trim();\n const lead = text.length - text.trimStart().length;\n const found: { at: number; end: number; key: string }[] = [];\n const whole = (at: number, label: string) => {\n const end = at + label.length + 1;\n return at >= 0 && trimmed.startsWith(`@${label}`, at) && !(end < trimmed.length && wordChar.test(trimmed[end]));\n };\n const take = (at: number, label: string, key: string) => {\n const end = at + label.length + 1;\n if (found.some(f => at < f.end && end > f.at)) return;\n found.push({ at, end, key });\n };\n // Longer tokens first, so \"@Ann Lee\" wins over \"@Ann\" at the same place.\n const byLength = (a: ChosenMention, b: ChosenMention) => b.label.length - a.label.length;\n for (const { key, label, at } of chosen.filter(c => c.at !== undefined).sort(byLength)) {\n if (whole(at! - lead, label)) take(at! - lead, label, key);\n }\n const tokens = [...new Map(chosen.filter(c => c.at === undefined).map(c => [`${c.key}\\n${c.label}`, c])).values()].sort(byLength);\n for (const { key, label } of tokens) {\n const token = `@${label}`;\n for (let at = trimmed.indexOf(token); at !== -1; at = trimmed.indexOf(token, at + 1)) {\n if (whole(at, label)) take(at, label, key);\n }\n }\n const points = (i: number) => Array.from(trimmed.slice(0, i)).length;\n return found.sort((a, b) => a.at - b.at).slice(0, MENTION_LIMITS.count)\n .map(f => ({ k: f.key, o: points(f.at), l: points(f.end) - points(f.at) }));\n}\n\n/*\n * How a bubble draws them, through the rich text parser: a mention is a place in the message (code points), not a\n * pattern in its text, and a detector only sees stretches of text. So before parsing, each mention's place is\n * replaced by a mark of two private-use characters around its index, and the `member-mention` detector turns each mark\n * back into an atom carrying the mention. Formatting around a mention (\"*@Bob*\") still applies.\n */\nconst OPEN = \"\\uE000\", CLOSE = \"\\uE001\";\n\n/** The text with each mention's place marked (the text as it is when it already holds a mark character). */\nexport function markMentions(text: string, mentions: readonly { o: number; l: number }[]): string {\n if (text.includes(OPEN) || text.includes(CLOSE)) return text;\n const points = Array.from(text);\n let out = \"\", at = 0;\n mentions.forEach((m, i) => {\n if (m.o < at || m.o + m.l > points.length) return;\n out += points.slice(at, m.o).join(\"\") + OPEN + i + CLOSE;\n at = m.o + m.l;\n });\n return out + points.slice(at).join(\"\");\n}\n\n/** A marked mention, as an atom carrying how it shows (`ParseContext.mentions`). */\nexport const mention: Detector<\"member-mention\", MentionView> = {\n kind: \"member-mention\",\n pattern: /\\uE000(\\d{1,2})\\uE001/g,\n accept: (match, _text, ctx) => {\n const view = (ctx.mentions as readonly MentionView[] | undefined)?.[Number(match[1])];\n return view ? { data: view } : null;\n },\n plain: (atom: Atom<\"member-mention\", MentionView>) => `@${atom.data.name}`,\n};\n\n/**\n * Whether what a mention covers reads as a name the chip may show instead: the member's name itself, or one word\n * (the name they went by when it was sent). Anything longer stays as written, since the chip would hide it: a\n * mention of \"@Bob - ignore the card, this invoice is fake\" must not read \"@Bob\".\n */\nfunction readsAsName(written: string, name: string): boolean {\n const fold = (s: string) => s.normalize(\"NFC\").toLowerCase();\n return fold(written) === fold(name) || /^[\\p{L}\\p{M}\\p{N}._-]{1,32}$/u.test(written);\n}\n\n/**\n * A message's mentions as its bubble shows them. A member still in the group goes by their name now, where what\n * was written reads as a name (`readsAsName`); one who is gone, or a mention covering more than a name, by what was\n * written. Mine (and everyone, from someone else) are `me`.\n */\nexport function mentionViews(text: string, mentions: readonly GroupMention[] | undefined, members: readonly { key: string; name: string; me: boolean }[], fromMe: boolean): MentionView[] {\n if (!mentions?.length) return [];\n const points = Array.from(text);\n return mentions.map(m => {\n const written = points.slice(m.o + 1, m.o + m.l).join(\"\");\n if (m.k === MENTION_EVERYONE) return { ...m, key: m.k, name: written || \"everyone\", me: !fromMe, written };\n const member = members.find(x => x.key === m.k);\n const name = member?.name && readsAsName(written, member.name) ? member.name : written;\n return { ...m, key: m.k, name, me: !!member?.me, written };\n });\n}\n","import type { Detector } from \"./types\";\n\n/**\n * Times the reader may want in their own zone: an ISO timestamp with its offset (\"2026-09-25T14:00:00Z\",\n * \"2026-09-25 14:00 +02:00\") and a clock time with a named zone (\"at 14:00 UTC\", \"3pm GMT+2\", \"9:30 am EST\").\n * Conservative on purpose: a time with no zone, a bare number, a score (\"3:2\") or a version (\"v1.14:00\") is text.\n * A clock time with no date means that day where the message was written, the day it was sent.\n */\n\n/** Zone abbreviations read the same way everywhere (no CST, IST or BST, which name several zones). Minutes east of UTC. */\nconst ZONES: Record<string, number> = {\n UTC: 0, GMT: 0, Z: 0,\n EST: -300, EDT: -240, MST: -420, MDT: -360, PST: -480, PDT: -420,\n CET: 60, CEST: 120, EET: 120, EEST: 180, BRT: -180, JST: 540, AEST: 600, AEDT: 660,\n};\nconst NAMED = \"UTC|GMT|EST|EDT|MST|MDT|PST|PDT|CET|CEST|EET|EEST|BRT|JST|AEST|AEDT\";\nconst OFFSET = \"[+-]\\\\d{1,2}(?::?\\\\d{2})?\";\n\nconst ISO = `(\\\\d{4})-(\\\\d{2})-(\\\\d{2})[T ](\\\\d{2}):(\\\\d{2})(?::(\\\\d{2})(?:\\\\.\\\\d{1,9})?)?\\\\s?(Z|UTC|GMT|[+-]\\\\d{2}:?\\\\d{2})`;\nconst CLOCK = `(\\\\d{1,2})(?::(\\\\d{2}))?\\\\s?(?:([ap])\\\\.?m\\\\b\\\\.?)?\\\\s?(?:(UTC|GMT)(${OFFSET})?|(${NAMED}))`;\n\nexport interface TimeData {\n /** The moment written, in ms since the epoch. */\n at: number;\n /** Whether the text carried its date; a clock time alone takes the day it was sent. */\n dated: boolean;\n}\n\n/** Whether a moment is one a date can hold (±8.64e15 ms): a peer picks the time a message was sent. */\nconst isMoment = (ms: number) => !Number.isNaN(new Date(ms).getTime());\n\n/** Minutes east of UTC for \"+02:00\", \"-3\", \"+0530\"; null past ±14 h. */\nfunction offsetMinutes(offset: string): number | null {\n const m = /^([+-])(\\d{1,2})(?::?(\\d{2}))?$/.exec(offset);\n if (!m) return null;\n const minutes = Number(m[2]) * 60 + Number(m[3] ?? 0);\n if (Number(m[2]) > 14 || Number(m[3] ?? 0) > 59) return null;\n return m[1] === \"-\" ? -minutes : minutes;\n}\n\nexport const time: Detector<\"time\", TimeData> = {\n kind: \"time\",\n // Not after a word, a digit, a colon, a dot or a slash, and not before one: \"v1.14:00 UTC\" and \"12:00:00:00\" stay text.\n pattern: new RegExp(`(?<![\\\\w:./+-])(?:${ISO}|${CLOCK})(?![\\\\w:+-])`, \"gi\"),\n accept(m, _text, ctx) {\n if (m[1] !== undefined) {\n const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) => Number(m[i] ?? 0));\n const zone = m[7].toUpperCase();\n const offset = zone in ZONES ? ZONES[zone] : offsetMinutes(zone);\n if (offset === null || month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 59) return null;\n const at = Date.UTC(year, month - 1, day, hour, minute, second) - offset * 60_000;\n // February 30th rolls over into March: not a date anyone wrote.\n if (!isMoment(at) || new Date(at + offset * 60_000).getUTCDate() !== day) return null;\n return { data: { at, dated: true } };\n }\n let hour = Number(m[8]);\n const minute = m[9] === undefined ? 0 : Number(m[9]);\n const meridiem = m[10]?.toLowerCase();\n // A bare hour needs am/pm: \"5 UTC\" could be anything.\n if (m[9] === undefined && !meridiem) return null;\n if (minute > 59) return null;\n if (meridiem) {\n if (hour < 1 || hour > 12) return null;\n hour = (hour % 12) + (meridiem === \"p\" ? 12 : 0);\n } else if (hour > 23) return null;\n const offset = m[13] ? ZONES[m[13].toUpperCase()] : m[12] ? offsetMinutes(m[12]) : 0;\n if (offset === null || offset === undefined) return null;\n // The day it was where the message was written. A sending time no date can hold names no day: the time is text.\n const there = new Date((ctx.sentAt ?? Date.now()) + offset * 60_000);\n if (!isMoment(there.getTime())) return null;\n const at = Date.UTC(there.getUTCFullYear(), there.getUTCMonth(), there.getUTCDate(), hour, minute) - offset * 60_000;\n if (!isMoment(at)) return null;\n return { data: { at, dated: false } };\n },\n};\n","import { blob } from \"./blob\";\nimport { link } from \"./links\";\nimport { mdLink } from \"./mdlink\";\nimport { mention } from \"./mentions\";\nimport { time } from \"./time\";\nimport type { Detector } from \"./types\";\n\n/**\n * Every inline detector, in order of precedence: where two match at the same place, the earlier one here wins;\n * otherwise the match that starts first does. A new kind of atom is one line here (its look, if it needs one, is\n * one line in apps/ui/src/components/rich/views.ts; without one it shows as the text it matched).\n */\nexport const DETECTORS: readonly Detector[] = [\n // Before `link`, though it wins by starting first anyway: \"[text](https://…)\" starts at the bracket.\n mdLink,\n link,\n blob,\n time,\n mention,\n];\n","/**\n * What pretty-printing takes on. Re-indenting adds two spaces a level on every line, so deep nesting grows the text\n * with the square of its depth: 8 KiB of `[` and `]` would come out as about 134 million characters. A message past\n * these bounds shows as it was written.\n */\nexport const JSON_LIMITS = {\n /** Characters of the message, trimmed. */\n inputChars: 4 * 1024,\n /** Levels of nesting. */\n depth: 32,\n /** Characters of the pretty-printed text. */\n outputChars: 64 * 1024,\n} as const;\n\n/**\n * A message that is JSON (an object or an array with something in it) shows pretty-printed. The text is\n * re-indented, not parsed and printed again: a number too big for a double, a duplicate key or an escape stays\n * exactly as written. Null for anything else, and for JSON too big or too deep to lay out (`JSON_LIMITS`).\n */\nexport function prettyJson(text: string): string | null {\n const trimmed = text.trim();\n if (trimmed.length > JSON_LIMITS.inputChars) return null;\n const first = trimmed[0];\n const last = trimmed[trimmed.length - 1];\n if (!((first === \"{\" && last === \"}\") || (first === \"[\" && last === \"]\"))) return null;\n // Counted before parsing, so the parser never walks a deep tree either (brackets inside strings count too, which\n // only ever errs towards plain text).\n let depth = 0;\n for (const c of trimmed) {\n if (c === \"{\" || c === \"[\") { if (++depth > JSON_LIMITS.depth) return null; }\n else if (c === \"}\" || c === \"]\") depth--;\n }\n try {\n const value: unknown = JSON.parse(trimmed);\n if (typeof value !== \"object\" || value === null || Object.keys(value).length === 0) return null;\n } catch {\n return null;\n }\n return reindent(trimmed);\n}\n\n/** Valid JSON, one value per line, two spaces a level; strings are copied as they are. Null past the bounds. */\nfunction reindent(json: string): string | null {\n let out = \"\";\n let depth = 0;\n const newline = () => \"\\n\" + \" \".repeat(depth);\n for (let i = 0; i < json.length; i++) {\n const c = json[i];\n if (c === '\"') {\n let j = i + 1;\n while (json[j] !== '\"') j += json[j] === \"\\\\\" ? 2 : 1;\n out += json.slice(i, j + 1);\n i = j;\n } else if (c === \"{\" || c === \"[\") {\n // An empty object or array stays on its line.\n let j = i + 1;\n while (/\\s/.test(json[j])) j++;\n if (json[j] === (c === \"{\" ? \"}\" : \"]\")) { out += c + json[j]; i = j; continue; }\n if (++depth > JSON_LIMITS.depth) return null;\n out += c + newline();\n } else if (c === \"}\" || c === \"]\") {\n depth--;\n out += newline() + c;\n } else if (c === \",\") out += \",\" + newline();\n else if (c === \":\") out += \": \";\n else if (!/\\s/.test(c)) out += c;\n if (out.length > JSON_LIMITS.outputChars) return null;\n }\n return out;\n}\n","import { DETECTORS } from \"./detectors\";\nimport { tokenizeInline } from \"./inline\";\nimport { prettyJson } from \"./json\";\nimport type { Block, Detector, ListBlock, ListItem, ParseContext } from \"./types\";\n\n/** What may follow an opening fence as a language name (\"```ts\", \"```c++\", \"```objective-c\"). */\nconst LANG = /^[A-Za-z][\\w+#.-]{0,19}$/;\n\n/**\n * A list item's line: an indent, then `-`, `*` or `•`, or a number (at most 9 digits) with `.` or `)`, then a space\n * and something. \"1.5 kg\" and \"-5 °C\" are not items: the marker needs the space.\n */\nconst ITEM = /^( {0,6}|\\t)(?:([-*\\u2022])|(\\d{1,9})([.)])) +(?=\\S)/;\n/** How far in an item's line starts for it to sit under the item before it (one level; deeper counts the same). */\nconst NESTED = 2;\n/** A quote's line: `>` then a space, or `>` alone (an empty line of the quote). */\nconst QUOTE = /^ {0,3}>(?: |$)/;\nconst HEADING = /^(#{1,3}) +(?=\\S)/;\nconst BLANK = /^\\s*$/;\n\n/**\n * The lines of text outside code as blocks: lists, quotes and headings where a line starts with one, paragraphs for\n * the rest. Text with none of them is one paragraph, exactly as written. A blank line next to a list, a quote or a\n * heading is the room around it, which the block's own margin gives, so it goes; the line break between them goes\n * too, the way the one before a fence does. Each line is read once here (twice inside a quote), so this stays linear.\n */\nfunction proseBlocks(text: string, detectors: readonly Detector[], ctx: ParseContext, quotes: boolean): Block[] {\n const inline = (s: string) => tokenizeInline(s, detectors, ctx);\n type Unit = { t: \"para\"; lines: string[] } | { t: \"block\"; block: Block } | { t: \"quote\"; lines: string[]; raw: string[] };\n const units: Unit[] = [];\n const lines = text.split(\"\\n\");\n // The list being read, its last item (text still open to continuation lines) and that item's last child.\n let list: ListBlock | null = null;\n let item: { at: ListItem; text: string[] } | null = null;\n let child: { list: ListBlock; at: ListItem; text: string[] } | null = null;\n const closeChild = () => { if (child) { child.at.segments = inline(child.text.join(\"\\n\")); child = null; } };\n const closeItem = () => { closeChild(); if (item) { item.at.segments = inline(item.text.join(\"\\n\")); item = null; } };\n const closeList = () => { closeItem(); list = null; };\n const last = () => units[units.length - 1];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n // One blank line between items of the same list does not end it (\"9. a\", \"\", \"10. b\" is one list).\n if (list && BLANK.test(line)) {\n const next = ITEM.exec(lines[i + 1] ?? \"\");\n if (next && ((next[1] === \"\\t\" ? NESTED : next[1].length) >= NESTED || (next[3] !== undefined) === list.ordered)) continue;\n }\n const m = ITEM.exec(line);\n if (m) {\n const ordered = m[3] !== undefined;\n const at: ListItem = { marker: ordered ? m[3] + m[4] : \"\\u2022\", ...(ordered ? { number: Number(m[3]) } : {}), segments: [], children: [] };\n const body = line.slice(m[0].length);\n const indent = m[1] === \"\\t\" ? NESTED : m[1].length;\n if (list && item && indent >= NESTED) {\n closeChild();\n const kids = item.at.children;\n let under = kids[kids.length - 1];\n if (!under || under.ordered !== ordered) kids.push(under = { type: \"list\", ordered, items: [] });\n under.items.push(at);\n child = { list: under, at, text: [body] };\n continue;\n }\n if (!list || list.ordered !== ordered) {\n closeList();\n list = { type: \"list\", ordered, items: [] };\n units.push({ t: \"block\", block: list });\n }\n closeItem();\n list.items.push(at);\n item = { at, text: [body] };\n continue;\n }\n // An indented line under an item goes on with it, as a line of its own.\n if (item && /^(?: {2}|\\t)/.test(line) && !BLANK.test(line)) {\n (child ?? item).text.push(line.trimStart());\n continue;\n }\n closeList();\n if (quotes && QUOTE.test(line)) {\n const inner = line.replace(/^ {0,3}> ?/, \"\");\n const unit = last();\n if (unit?.t === \"quote\") { unit.lines.push(inner); unit.raw.push(line); }\n else units.push({ t: \"quote\", lines: [inner], raw: [line] });\n continue;\n }\n const h = HEADING.exec(line);\n if (h) {\n units.push({ t: \"block\", block: { type: \"heading\", level: h[1].length as 1 | 2 | 3, segments: inline(line.slice(h[0].length)) } });\n continue;\n }\n const unit = last();\n if (unit?.t === \"para\") unit.lines.push(line);\n else units.push({ t: \"para\", lines: [line] });\n }\n closeList();\n\n // A quote with nothing in it (\">\" alone) is the text it was, one paragraph with the lines around it.\n const merged: Unit[] = [];\n for (const unit of units) {\n const now: Unit = unit.t === \"quote\" && unit.lines.every((l) => BLANK.test(l)) ? { t: \"para\", lines: unit.raw } : unit;\n const before = merged[merged.length - 1];\n if (now.t === \"para\" && before?.t === \"para\") before.lines.push(...now.lines);\n else merged.push(now);\n }\n\n const blocks: Block[] = [];\n merged.forEach((unit, i) => {\n if (unit.t === \"block\") { blocks.push(unit.block); return; }\n if (unit.t === \"quote\") {\n blocks.push({ type: \"quote\", blocks: proseBlocks(unit.lines.join(\"\\n\"), detectors, ctx, false) });\n return;\n }\n let { lines: body } = unit;\n let from = 0;\n let to = body.length;\n if (i > 0) while (from < to && BLANK.test(body[from])) from++;\n if (i < merged.length - 1) while (to > from && BLANK.test(body[to - 1])) to--;\n body = body.slice(from, to);\n const joined = body.join(\"\\n\");\n if (joined) blocks.push({ type: \"paragraph\", segments: inline(joined) });\n });\n return blocks;\n}\n\n/**\n * A message's text as blocks. A message that is JSON is one pretty-printed block. Otherwise a fence (```) at the\n * start of a line opens a code block, with an optional language name after it, and the next ``` closes it; a fence\n * that never closes is text. Everything else is lists, quotes, headings and paragraphs of inline segments\n * (`proseBlocks`, then `tokenizeInline`).\n */\nexport function parseMessage(text: string, ctx: ParseContext = {}, detectors: readonly Detector[] = DETECTORS): Block[] {\n const json = prettyJson(text);\n if (json !== null) return [{ type: \"codeblock\", code: json, lang: \"json\" }];\n\n const blocks: Block[] = [];\n const paragraph = (from: number, to: number) => {\n if (to > from) blocks.push(...proseBlocks(text.slice(from, to), detectors, ctx, true));\n };\n const fence = /(^|\\n)```/g;\n let cursor = 0;\n for (let found = fence.exec(text); found; found = fence.exec(text)) {\n const open = found.index + found[1].length;\n if (open < cursor) continue;\n const lineEnd = text.indexOf(\"\\n\", open);\n // \"```code```\" on one line is inline code, not a block.\n if (lineEnd < 0) break;\n const info = text.slice(open + 3, lineEnd).trim();\n const lang = LANG.test(info) ? info.toLowerCase() : undefined;\n // Without a language name, what follows the fence is the code's first line (the way chat apps write it).\n const start = lang || !info ? lineEnd + 1 : open + 3;\n const close = text.indexOf(\"```\", start);\n // No closing fence anywhere after this one: none of the later ones closes either.\n if (close < 0) break;\n let code = text.slice(start, close);\n if (code.endsWith(\"\\n\")) code = code.slice(0, -1);\n if (!code.trim()) { fence.lastIndex = close; continue; }\n // The line break before the fence belongs to the block.\n paragraph(cursor, found.index);\n blocks.push({ type: \"codeblock\", code, ...(lang ? { lang } : {}) });\n // The next fence may start on the very next line: look from the line break, which the pattern needs.\n fence.lastIndex = close + 3;\n cursor = close + 3;\n if (text[cursor] === \"\\n\") cursor++;\n }\n paragraph(cursor, text.length);\n return blocks;\n}\n","import { parseMessage, prettyJson, type Block, type Segment } from \"./parse\";\nimport type { Language } from \"./settings\";\nimport type { ChatMessage } from \"./types\";\n\n/*\n * Which received messages are translated, and from which language (docs/AUTO-TRANSLATE.md § Source language). Pure:\n * the detector is passed in, so this file decides and never loads it. The detector is unreliable on short or slangy\n * text (\"ok\" is undetermined, \"lol no way 😂\" came out as Volapük), hence the rules: only received text, only what\n * the detector is sure of, never the app's own language, and never a few letters on their own.\n */\n\n/** One of the detector's guesses, best first: `@qvac/langdetect-text`'s `detectMultiple` gives these. */\nexport interface LanguageGuess {\n /** ISO 639-1, or `und` when it cannot tell. */\n code: string;\n probability: number;\n}\n\nexport type DetectLanguages = (text: string) => readonly LanguageGuess[] | Promise<readonly LanguageGuess[]>;\n\nexport interface TranslateWhichOptions {\n /** What received messages are translated into. */\n appLanguage: Language;\n detect: DetectLanguages;\n /** Whether a model exists from `language` (straight into the app's language, or through English). */\n canTranslate: (language: string) => boolean;\n /** The last language the others in this chat wrote with confidence: what a short message is taken to be in. */\n chatLanguage?: string | null;\n}\n\nexport interface TranslateWhich {\n /** The language to translate the message from, or null: it is shown as it was sent. */\n from: string | null;\n /** The message's language when the detector was sure of it, the app's own included: what the chat remembers. */\n detected: string | null;\n}\n\n/** Fewer letters than this, once emoji, links, numbers and mentions are out, and the detector is not asked. */\nexport const MIN_LETTERS = 4;\n/** The detector's top guess below this probability is no answer. */\nexport const MIN_PROBABILITY = 0.5;\n/** How much of a long message the detector reads: its language shows long before, and the cost grows with it. */\nexport const DETECT_CHARS = 2_000;\n\nconst UNDETERMINED = \"und\";\nconst NONE: TranslateWhich = { from: null, detected: null };\n\n/**\n * A run of letters, digits and token characters, or of numbers of any script. One with a digit in it is a number, a\n * token, an invoice, an address, a code (`codeless`). Each run is read whole once: a `[…]*\\d` was tried from each\n * character of a long run with no digit, and a contact's 48,000 held the page for seconds.\n */\nconst CODE_RUN = /[A-Za-z0-9_+/=:.-]+|\\p{N}+/gu;\nconst codeless = (run: string) => /\\d|^\\p{N}/u.test(run) ? \" \" : run;\nconst EMOJI = /\\p{Extended_Pictographic}|\\p{Emoji_Modifier}|\\p{Regional_Indicator}||️/gu;\nconst LETTER = /\\p{L}/gu;\n\nfunction segmentsText(segments: readonly Segment[]): string {\n return segments.map((segment) => {\n if (segment.type === \"text\") return segment.text;\n if (segment.type === \"span\") return segmentsText(segment.children);\n // Code, links and the other atoms (long keys, times, mentions) are never translated, so they say nothing of the language.\n return \" \";\n }).join(\"\");\n}\n\nfunction blockText(block: Block): string {\n switch (block.type) {\n case \"codeblock\": return \" \";\n case \"paragraph\":\n case \"heading\": return segmentsText(block.segments);\n case \"quote\": return block.blocks.map(blockText).join(\" \");\n case \"list\": return block.items.map((item) => [segmentsText(item.segments), ...item.children.map(blockText)].join(\" \")).join(\" \");\n }\n}\n\n/**\n * What of `text` is language, as the detector reads it: without code, links, mentions (`mentions`, by their place in\n * code points), numbers and tokens, and emoji; one space between words. A message that is JSON has none.\n */\nexport function detectableText(text: string, mentions: readonly { o: number; l: number }[] = []): string {\n if (prettyJson(text) !== null) return \"\";\n let unmentioned = text;\n if (mentions.length) {\n const points = Array.from(text);\n for (const { o, l } of mentions) points.fill(\" \", o, Math.min(o + l, points.length));\n unmentioned = points.join(\"\");\n }\n return parseMessage(unmentioned).map(blockText).join(\" \")\n .replace(CODE_RUN, codeless)\n .replace(EMOJI, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nconst baseCode = (code: string) => code.toLowerCase().split(/[-_]/)[0];\n\n/**\n * Whether `message` is translated for reading, and from which language. Only text a contact or member sent: never\n * mine, a system line, a file, a payment, a status card or a call line. A short message (under `MIN_LETTERS`) is\n * taken to be in the chat's language, when it has one; anything else in what the detector is sure of. The app's\n * language and a language with no model are shown as they are.\n */\nexport async function translateFrom(\n message: Pick<ChatMessage, \"sender\" | \"text\" | \"file\" | \"paymentId\" | \"card\" | \"callEvent\" | \"systemEvent\" | \"mentions\">,\n { appLanguage, detect, canTranslate, chatLanguage }: TranslateWhichOptions,\n): Promise<TranslateWhich> {\n if (message.sender !== \"peer\") return NONE;\n if (message.file || message.paymentId || message.card || message.callEvent || message.systemEvent) return NONE;\n\n const text = detectableText(message.text, message.mentions);\n const letters = text.match(LETTER)?.length ?? 0;\n if (letters === 0) return NONE;\n const usable = (language: string | null | undefined) =>\n language && language !== UNDETERMINED && language !== appLanguage && canTranslate(language) ? language : null;\n if (letters < MIN_LETTERS) return { from: usable(chatLanguage && baseCode(chatLanguage)), detected: null };\n\n const top = (await detect(text.slice(0, DETECT_CHARS)))[0];\n if (!top || top.probability < MIN_PROBABILITY) return NONE;\n const detected = baseCode(top.code);\n if (detected === UNDETERMINED) return NONE;\n return { from: usable(detected), detected };\n}\n","import { spawn, type ChildProcessByStdio } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\nimport runtimePackage from \"../../../native/translation/package.json\" with { type: \"json\" };\nimport { translateFrom, type DetectLanguages } from \"../../../apps/ui/src/lib/translateWhich\";\nimport { childEnv } from \"./childEnv\";\nimport { CliError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\n\n/**\n * `--translate <lang>` (docs/AUTO-TRANSLATE.md): received messages get `translation: { from, text }`, made on this machine\n * by the translation runtime (native/translation) the Desktop downloads: `bare runtime.mjs <models>`, one JSON line per\n * request. Which messages, and from which language, is the app's rule (translateWhich.ts): only a contact's or a member's\n * text, never mine, and only what the detector is sure of. Nothing is fetched here. A message's text goes to the runtime\n * only, never to stderr: what is said there is the runtime's own word or a path.\n */\n\n/** The runtime this CLI starts, in `<home>/translation-runtime/<version>/`; models in `<home>/translation-models/<pair>/`, as on Desktop. */\nexport const RUNTIME_VERSION: string = runtimePackage.version;\n\nexport function translationPaths(home: string): { runtime: string; models: string } {\n return { runtime: join(home, \"translation-runtime\", RUNTIME_VERSION), models: join(home, \"translation-models\") };\n}\n\n/** `--translate`'s language, checked before anything starts: an ISO 639 code, as the runtime's pairs take. */\nexport function translateTarget(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\" || !/^[a-z]{2,3}$/.test(value)) throw new CliError(\"usage\", `--translate takes a language code (en, pt, es, ...), not ${JSON.stringify(value)}`);\n return value;\n}\n\n/**\n * The language detector (`@qvac/langdetect-text`'s `detectMultiple`), which the rule takes as a parameter. It is not a\n * dependency of the CLI yet: until it is, `--translate` says so once and prints messages as they are.\n */\nexport async function loadDetector(): Promise<DetectLanguages | null> {\n return null;\n}\n\n/** What the CLI prints of a message, as far as translating it goes (views.ts' MessageJson). */\ninterface ShownMessage {\n chat?: string;\n from?: string;\n text?: unknown;\n file?: unknown;\n paymentId?: unknown;\n card?: unknown;\n event?: unknown;\n mentions?: { offset: number; length: number }[];\n translation?: { from: string; text: string };\n}\n\nexport interface Translator {\n /** The message with `translation` when the rule says so and the runtime answered; else the same object. */\n message<T extends ShownMessage>(message: T): Promise<T & Pick<ShownMessage, \"translation\">>;\n /** The event with its message translated (a join notice is the app's line, not the contact's words). */\n event(event: GhostlyEvent): Promise<GhostlyEvent>;\n /** Ends the runtime's input: it unloads and exits. */\n close(): void;\n}\n\nexport interface TranslatorOptions {\n home: string;\n to: string;\n detect: DetectLanguages | null;\n /** One line to stderr. */\n warn: (line: string) => void;\n}\n\n/** `events` and `chat history` with `--translate`: their events or messages one by one, oldest first, as `listen` takes them. */\nexport async function translateAnswer(answer: Record<string, unknown>, translator: Translator): Promise<Record<string, unknown>> {\n const each = async <T,>(list: T[], one: (item: T) => Promise<T>) => { const out: T[] = []; for (const item of list) out.push(await one(item)); return out; };\n if (Array.isArray(answer.events)) return { ...answer, events: await each(answer.events as GhostlyEvent[], translator.event) };\n if (Array.isArray(answer.messages)) return { ...answer, messages: await each(answer.messages as ShownMessage[], translator.message) };\n return answer;\n}\n\ntype Answer = { id?: unknown; texts?: unknown; error?: unknown } | null;\n\n/** A translator, or null when the detector or the runtime is not there: said once, and messages stay as they are. */\nexport function openTranslator({ home, to, detect, warn }: TranslatorOptions): Translator | null {\n const { runtime, models } = translationPaths(home);\n const bare = join(runtime, process.platform === \"win32\" ? \"bare.exe\" : \"bare\"), script = join(runtime, \"runtime.mjs\");\n // The detector first: without it no runtime or model helps, so nobody is sent to unpack one for nothing.\n if (!detect) {\n warn(\"ghostly: --translate cannot translate in this build of the CLI (it has no language detector yet): messages are printed untranslated\");\n return null;\n }\n if (!existsSync(bare) || !existsSync(script)) {\n warn(`ghostly: no translation runtime in ${runtime}: messages are printed untranslated. Unpack runtime ${RUNTIME_VERSION} there and a model in ${join(models, \"<from>-<to>\")}`);\n return null;\n }\n\n let child: ChildProcessByStdio<Writable, Readable, null> | null = null, next = 0, closed = false, stopped = false;\n const waiting = new Map<number, (answer: Answer) => void>();\n const said = new Set<string>();\n const kill = () => child?.kill();\n\n // Started at the first message to translate, and kept for the ones after it (a model loads once).\n const start = () => {\n const started = spawn(bare, [script, models], { stdio: [\"pipe\", \"pipe\", \"ignore\"], env: childEnv() });\n started.stdin.on(\"error\", () => {});\n createInterface({ input: started.stdout }).on(\"line\", (line) => {\n let answer: Answer;\n try { answer = JSON.parse(line) as Answer; } catch { return; }\n const id = answer?.id as number, done = waiting.get(id);\n waiting.delete(id);\n done?.(answer);\n });\n const gone = (why: string) => {\n if (stopped) return;\n stopped = true;\n child = null;\n if (!closed) warn(`ghostly: the translation runtime stopped (${why}): messages are printed untranslated from here`);\n for (const done of waiting.values()) done(null);\n waiting.clear();\n };\n started.on(\"error\", (error) => gone(error.message));\n started.on(\"exit\", (code, signal) => gone(signal ?? `exit ${code}`));\n process.once(\"exit\", kill);\n return started;\n };\n\n const ask = (pair: string, text: string) => new Promise<string | null>((resolve) => {\n if (closed || stopped) return resolve(null);\n child ??= start();\n const id = ++next;\n waiting.set(id, (answer) => {\n const texts = answer?.texts;\n if (Array.isArray(texts) && typeof texts[0] === \"string\") return resolve(texts[0]);\n // The runtime's errors never carry the text (\"Translation model not downloaded\"): said once per pair.\n if (typeof answer?.error === \"string\" && !said.has(pair)) { said.add(pair); warn(`ghostly: no translation ${pair}: ${answer.error}`); }\n resolve(null);\n });\n child.stdin.write(JSON.stringify({ id, op: \"translate\", pair, texts: [text] }) + \"\\n\");\n });\n\n const has = (pair: string) => existsSync(join(models, pair));\n // Straight into `to`, or through English: the runtime chains es-en and en-pt itself for es-pt.\n const canTranslate = (from: string) => has(`${from}-${to}`) || (from !== \"en\" && to !== \"en\" && has(`${from}-en`) && has(`en-${to}`));\n /** Per chat or group, the last language the others wrote with confidence: a short message is taken to be in it. */\n const languages = new Map<string, string>();\n\n async function message<T extends ShownMessage>(shown: T): Promise<T & Pick<ShownMessage, \"translation\">> {\n if (typeof shown?.text !== \"string\") return shown;\n const place = shown.chat ?? \"\";\n let which: Awaited<ReturnType<typeof translateFrom>>;\n try {\n which = await translateFrom({\n sender: shown.from === \"peer\" ? \"peer\" : \"me\", text: shown.text,\n file: shown.file, paymentId: shown.paymentId, card: shown.card, systemEvent: shown.event,\n mentions: shown.mentions?.map((m) => ({ o: m.offset, l: m.length })),\n } as unknown as Parameters<typeof translateFrom>[0], { appLanguage: to as Parameters<typeof translateFrom>[1][\"appLanguage\"], detect: detect!, canTranslate, chatLanguage: languages.get(place) });\n } catch { return shown; }\n const { from, detected } = which;\n if (detected) languages.set(place, detected);\n if (!from) return shown;\n const text = await ask(`${from}-${to}`, shown.text);\n // The same words back (\"ok\" taken as the chat's Portuguese) are no translation.\n return text === null || text.trim() === shown.text.trim() ? shown : { ...shown, translation: { from, text } };\n }\n\n return {\n message,\n async event(event) {\n const shown = event.message as ShownMessage | undefined;\n if (!shown || typeof shown !== \"object\" || event.type === \"chat.joined\") return event;\n const translated = await message(shown);\n return translated === shown ? event : { ...event, message: translated };\n },\n close() {\n closed = true;\n process.off(\"exit\", kill);\n child?.stdin.end();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;ACUA,IAAa,OAA+B;CAC1C,MAAM;CACN,SAAS,IAAI,OAAO,uEAAgF,GAAG;CACvG,eAAe,EAAE,MAAM,KAAK;CAC5B,QAAQ,SAA6B,GAAG,KAAK,KAAK,MAAM,GAAG,EAAE,EAAE;AACjE;;ACZA,IAAM,UAAkC;CAAE,KAAK;CAAK,KAAK;CAAK,KAAK;AAAI;;;;;;;AAQvE,SAAgB,QAAQ,OAAuB;CAC7C,MAAM,MAAM,SAAS,KAAK;CAC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,IAAI;GACxB,OAAO,MAAM,IAAI;EACnB;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"waitNotice-ylU3XwjO.js","names":[],"sources":["../../src/waitNotice.ts"],"sourcesContent":["/*\n * What a command that waits says while it waits and when Ctrl-C ends it (agents#2354). Kept apart from waits.ts, which\n * runs in the daemon or the one-shot's engine: this is read by the command's own process, which loads no engine module\n * for a command a daemon answers.\n */\n\nimport { basename } from \"node:path\";\nimport { shellWord } from \"./shellWord\";\n\n/** What happens next to what a wait was waiting on: a daemon goes on, a one-shot's profile closes now. */\nexport const goesOn = (mode: \"daemon\" | \"one-shot\"): string => mode === \"one-shot\"\n ? \"goes with this profile's next command, or keep it online with `ghostly daemon --detach`\"\n : \"still goes by itself while this profile is online\";\n\n/**\n * The wait a one-shot does when no `--wait` is given (`ctx.mode === \"one-shot\"` defaults in api.ts, files.ts, buttons.ts\n * and statusCards.ts): what is not out yet leaves with the process, so it stays. A daemon answers those at once. A ref\n * written `group:<id>` is a group's, whose file, card or button press does not wait; a group named otherwise is told\n * only by the engine, and its notice comes only if the call is still going after WAIT_NOTICE_MS.\n */\nfunction oneShotWait(method: string, params: Record<string, unknown>): string | undefined {\n const group = typeof params.group === \"string\" || (typeof params.chat === \"string\" && params.chat.startsWith(\"group:\"));\n switch (method) {\n // On a chat nobody joined yet these answer at once (apiKit `oneShotWaits`); a notice comes only if a call is still\n // going after WAIT_NOTICE_MS.\n case \"chat.send\": return \"sent\";\n case \"chat.edit\": return \"confirmed\";\n case \"file.send\": case \"task.send\": case \"routine.send\": case \"button.press\": return group ? undefined : \"sent\";\n // `--all` reports to each 1:1 chat in turn, each waiting as one named would.\n case \"usage.send\": return group ? undefined : \"sent\";\n case \"task.update\": case \"routine.update\": return group ? undefined : \"confirmed\";\n case \"chat.react\": return \"confirmed\";\n case \"group.react\": return \"sent\";\n case \"chat.pin\": return group ? \"sent\" : \"confirmed\";\n case \"chat.delete\": return params.everyone !== true ? undefined : group ? \"sent\" : \"confirmed\";\n default: return undefined;\n }\n}\n\n/** The call's `wait`: the one given, or the one-shot's own default. */\nfunction waitOf(method: string, params: Record<string, unknown>, mode: \"daemon\" | \"one-shot\"): Record<string, unknown> {\n if (params.wait !== undefined || mode !== \"one-shot\") return params;\n const wait = oneShotWait(method, params);\n return wait === undefined ? params : { ...params, wait };\n}\n\n/**\n * The seconds a call without `--timeout` waits for the contact: the daemon's defaults (`num(params, \"timeout\", …)` in\n * api.ts, files.ts, buttons.ts and statusCards.ts), so that a bot's `chat wait` or `send --wait sent` on a daemon that\n * stopped answering ends when the wait would have (main.ts `answerWithin`). A call that does not wait is none.\n */\nexport function waitsFor(method: string, params: Record<string, unknown>): number | undefined {\n if (method === \"chat.wait\") return 60;\n if (method === \"file.wait\" || (method === \"file.save\" && params.wait === true) || (method === \"file.send\" && params.wait === \"sent\")) return 300;\n // send, edit, forward, a button, a task or routine card: `--wait sent|confirmed|delivered`, 30 s each.\n if (typeof params.wait === \"string\" && params.wait !== \"none\") return 30;\n return undefined;\n}\n\nexport interface WaitNotice {\n /** Said on stderr (a terminal's only) when the wait has gone on for a moment: what it waits for. */\n waiting: string;\n /** Said after \"stopped waiting (Ctrl-C): \" when Ctrl-C ends the wait: what becomes of what it waited on. */\n stopped: string;\n}\n\nconst word = (value: unknown): string | undefined => typeof value === \"string\" && value.trim() ? value : undefined;\n\n/**\n * A state `chat wait --until` waits for, as a sentence says it (`to`: the wait's timeout and notice, `not`: Ctrl-C).\n * The flag's word after \"to be\" read \"to be text\" and \"was not text yet\".\n */\nconst CHAT_STATES: Record<string, { to: string; not: string }> = {\n live: { to: \"to be live\", not: \"was not live yet\" },\n text: { to: \"to carry text\", not: \"could not carry text yet\" },\n paired: { to: \"to be paired\", not: \"was not paired yet\" },\n};\nexport const chatState = (until: string): { to: string; not: string } => CHAT_STATES[until] ?? { to: `to be ${until}`, not: `was not ${until} yet` };\n\n/** What a call waits for, in a person's words, or null for a call that does not wait. */\nexport function waitNotice(method: string, given: Record<string, unknown>, mode: \"daemon\" | \"one-shot\"): WaitNotice | null {\n // A one-shot join by a group's link waits to be let in (api.ts `letIn`); through a daemon it answers at once.\n if (method === \"group.join\") return mode === \"one-shot\"\n ? { waiting: \"waiting for a member's app to let this profile in (up to 60 s; Ctrl-C stops waiting)\", stopped: \"not let in yet: the knock goes on while this profile is running (ghostly daemon --detach)\" }\n : null;\n const params = waitOf(method, given, mode);\n // A daemon's file send answers once it has copied the file into the profile (files.ts `stage`): 6-30 s for 1 GiB, said\n // nothing, and read as a hung daemon. Ctrl-C there stops the send (files.ts `stageWhileAsked`): nothing goes.\n if (method === \"file.send\" && mode === \"daemon\" && params.wait !== \"sent\") {\n const file = word(params.name) ?? (word(params.path) ? basename(params.path as string) : \"the file\");\n const chatRef = word(params.chat) ?? \"the chat\", chat = chatRef.startsWith(\"group:\") ? `group ${chatRef.slice(\"group:\".length)}` : chatRef;\n return { waiting: `copying ${file} into the profile before it goes to ${chat} (Ctrl-C stops the send)`, stopped: `${file} was not sent to ${chat}: send it again when you want it` };\n }\n const waits = waitsFor(method, params);\n if (waits === undefined) return null;\n const seconds = typeof params.timeout === \"number\" ? params.timeout : waits;\n // One that waits for the contact (`--wait sent`, a one-shot's own wait) copies the file in first as well, and Ctrl-C\n // then stops the send (a daemon's `stageWhileAsked`, a one-shot's profile closing under the copy): it said \"it is kept\n // here and still goes\" with nothing in the chat. Which of the two it was, only the chat's file list tells.\n if (method === \"file.send\") {\n const file = word(params.name) ?? (word(params.path) ? basename(params.path as string) : \"the file\");\n const chatRef = word(params.chat), chat = chatRef ?? \"the contact\";\n const list = chatRef ? ` (ghostly file list ${shellWord(chatRef, \"<chat>\")} says which)` : \"\";\n return {\n waiting: `copying ${file} into the profile, then waiting for it to go out to ${chat} (up to ${seconds} s; Ctrl-C stops the send while it is copied in, then only the waiting)`,\n stopped: `${file} was not sent to ${chat} if it was still being copied in; if it was in the chat, it is kept here and ${goesOn(mode)}${list}`,\n };\n }\n const upTo = `up to ${seconds} s; Ctrl-C stops waiting`;\n if (method === \"chat.wait\") {\n const chat = word(params.chat) ?? \"the chat\", state = chatState(word(params.until) ?? \"live\");\n return { waiting: `waiting for chat ${chat} ${state.to} (${upTo})`, stopped: `chat ${chat} ${state.not}` };\n }\n if (method === \"file.wait\" || method === \"file.save\") {\n const file = word(params.file) ?? \"the file\";\n const on = mode === \"one-shot\" ? \"goes on while this profile is online (`ghostly daemon --detach`)\" : \"goes on while this profile is online\";\n return { waiting: `waiting for file ${file}'s transfer to end (${upTo}; the transfer ${on})`, stopped: `file ${file}'s transfer ${on}` };\n }\n const chatRef = word(params.chat);\n // A forward's `chat` is where the messages come from; they go to `to`.\n const group = word(params.group) ?? (method.startsWith(\"group.\") ? chatRef\n : method !== \"chat.forward\" && chatRef?.startsWith(\"group:\") ? chatRef.slice(\"group:\".length) : undefined);\n const to = Array.isArray(params.to) ? params.to.filter((t): t is string => typeof t === \"string\").join(\", \") : undefined;\n const chat = (to || undefined) ?? chatRef ?? (params.all === true ? \"each contact\" : \"the contact\");\n const what = group !== undefined ? `a member's edge in group ${group} to take it`\n : params.wait === \"sent\" ? `it to go out to ${chat}`\n : `${chat}'s app to confirm it`;\n return { waiting: `waiting for ${what} (${upTo}, it still goes)`, stopped: `it is kept here and ${goesOn(mode)}` };\n}\n"],"mappings":";;;;AAUA,IAAa,UAAU,SAAwC,SAAS,aACpE,4FACA;;;;;;;AAQJ,SAAS,YAAY,QAAgB,QAAqD;CACxF,MAAM,QAAQ,OAAO,OAAO,UAAU,YAAa,OAAO,OAAO,SAAS,YAAY,OAAO,KAAK,WAAW,QAAQ;CACrH,QAAQ,QAAR;EAGE,KAAK,aAAa,OAAO;EACzB,KAAK,aAAa,OAAO;EACzB,KAAK;EAAa,KAAK;EAAa,KAAK;EAAgB,KAAK,gBAAgB,OAAO,QAAQ,KAAA,IAAY;EAEzG,KAAK,cAAc,OAAO,QAAQ,KAAA,IAAY;EAC9C,KAAK;EAAe,KAAK,kBAAkB,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