@ghostlytools/cli 1.7.3 → 1.7.4
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 +18 -13
- package/SKILL.md +5 -3
- package/dist/assets/{api-B42F9ytB.js → api-Chhvpwok.js} +2 -2
- package/dist/assets/{api-tf-wAAnB.js → api-D3i2hwy0.js} +142 -84
- package/dist/assets/api-D3i2hwy0.js.map +1 -0
- package/dist/assets/{apiKit-DJb9hulp.js → apiKit-BtsHrnoo.js} +30 -7
- package/dist/assets/apiKit-BtsHrnoo.js.map +1 -0
- package/dist/assets/{apps-BfoDISRg.js → apps-BFJTqvAt.js} +1 -1
- package/dist/assets/{apps-DIrWmLgL.js → apps-BHl97rHs.js} +10 -8
- package/dist/assets/apps-BHl97rHs.js.map +1 -0
- package/dist/assets/{arkade-CJAhhgPQ.js → arkade-BFE8KkEE.js} +2 -2
- package/dist/assets/{arkade-CJAhhgPQ.js.map → arkade-BFE8KkEE.js.map} +1 -1
- package/dist/assets/{backup-BkUeeduy.js → backup-Bbsr6nDi.js} +1 -1
- package/dist/assets/{backup-Bko-AAm0.js → backup-CxACdtQX.js} +7 -7
- package/dist/assets/{backup-Bko-AAm0.js.map → backup-CxACdtQX.js.map} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
- package/dist/assets/{blobFiles-Bckz9fjp.js → blobFiles-DOQDRdDI.js} +3 -3
- package/dist/assets/{blobFiles-Bckz9fjp.js.map → blobFiles-DOQDRdDI.js.map} +1 -1
- package/dist/assets/{buttons-DeA6Yddq.js → buttons-CieBtXEO.js} +4 -4
- package/dist/assets/{buttons-DeA6Yddq.js.map → buttons-CieBtXEO.js.map} +1 -1
- package/dist/assets/buttons-YtAj3R_E.js +2 -0
- package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-QmtwDj-N.js} +2 -2
- package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-QmtwDj-N.js.map} +1 -1
- package/dist/assets/{envelope-Cz5fc7BM.js → envelope-DYiGwzq_.js} +2 -2
- package/dist/assets/{envelope-Cz5fc7BM.js.map → envelope-DYiGwzq_.js.map} +1 -1
- package/dist/assets/{errors-mnjSQlbX.js → errors-QUGP-jIF.js} +2 -2
- package/dist/assets/errors-QUGP-jIF.js.map +1 -0
- package/dist/assets/{fileBytes-OolN5cSY.js → fileBytes-BPDKufla.js} +1 -1
- package/dist/assets/{fileBytes-BD0v3rRG.js → fileBytes-DNgrRL0R.js} +3 -3
- package/dist/assets/{fileBytes-BD0v3rRG.js.map → fileBytes-DNgrRL0R.js.map} +1 -1
- package/dist/assets/{fileBytes-_fd-2JRY.js → fileBytes-Q3ehcEr8.js} +2 -2
- package/dist/assets/{fileBytes-_fd-2JRY.js.map → fileBytes-Q3ehcEr8.js.map} +1 -1
- package/dist/assets/fileBytesIdb-DZcESfTt.js +2 -0
- package/dist/assets/{fileBytesIdb-NtA8r9EM.js → fileBytesIdb-Dm1EyEbT.js} +3 -3
- package/dist/assets/{fileBytesIdb-NtA8r9EM.js.map → fileBytesIdb-Dm1EyEbT.js.map} +1 -1
- package/dist/assets/{fileBytesOpfs-B8fJwkwM.js → fileBytesOpfs-ZGD21c4Q.js} +3 -3
- package/dist/assets/{fileBytesOpfs-B8fJwkwM.js.map → fileBytesOpfs-ZGD21c4Q.js.map} +1 -1
- package/dist/assets/{groupFiles-BlZRBWpt.js → groupFiles-CBJIEvCE.js} +22 -10
- package/dist/assets/groupFiles-CBJIEvCE.js.map +1 -0
- package/dist/assets/{host-BX0DmKW6.js → host-Va-r_KJz.js} +54 -16
- package/dist/assets/host-Va-r_KJz.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-DitYDnXx.js → hyperdhtRelay-B2uK9tJv.js} +2 -2
- package/dist/assets/{hyperdhtRelay-DitYDnXx.js.map → hyperdhtRelay-B2uK9tJv.js.map} +1 -1
- package/dist/assets/{idb-BlH8-O3R.js → idb-BkOJES5_.js} +5 -3
- package/dist/assets/idb-BkOJES5_.js.map +1 -0
- package/dist/assets/{irohWeb-R3bcd34h.js → irohWeb-DxeEgQ-W.js} +2 -2
- package/dist/assets/{irohWeb-R3bcd34h.js.map → irohWeb-DxeEgQ-W.js.map} +1 -1
- package/dist/assets/{main-6QOSvQ8b.js → main-BX4oPWCJ.js} +362 -110
- package/dist/assets/main-BX4oPWCJ.js.map +1 -0
- package/dist/assets/{mainline-BfwezHWi.js → mainline-IfWQOB-J.js} +39 -12
- package/dist/assets/mainline-IfWQOB-J.js.map +1 -0
- package/dist/assets/{networkReason-Ba9415nn.js → networkReason-N2vAaoth.js} +3 -3
- package/dist/assets/{networkReason-Ba9415nn.js.map → networkReason-N2vAaoth.js.map} +1 -1
- package/dist/assets/{nwc-ovXSN2M2.js → nwc-CzyCtNK2.js} +3 -3
- package/dist/assets/{nwc-ovXSN2M2.js.map → nwc-CzyCtNK2.js.map} +1 -1
- package/dist/assets/{nwcProvider-BzZbfFP3.js → nwcProvider-DjWmEn3j.js} +2 -2
- package/dist/assets/{nwcProvider-BzZbfFP3.js.map → nwcProvider-DjWmEn3j.js.map} +1 -1
- package/dist/assets/{profiles-C6XWqre5.js → profiles-DcCeOi7J.js} +104 -10
- package/dist/assets/profiles-DcCeOi7J.js.map +1 -0
- package/dist/assets/{registry-CFtlhWCI.js → registry-BmS02J5h.js} +1 -1
- package/dist/assets/{registry-B0Uv9yL6.js → registry-CeW8XEQc.js} +45 -14
- package/dist/assets/registry-CeW8XEQc.js.map +1 -0
- package/dist/assets/{resolve-BzFG4WDU.js → resolve-BvHkAhDH.js} +66 -29
- package/dist/assets/resolve-BvHkAhDH.js.map +1 -0
- package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-mTTp3XNs.js} +2 -2
- package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-mTTp3XNs.js.map} +1 -1
- package/dist/assets/{server-BGCuHbmQ.js → server-BUcJo4vz.js} +779 -239
- package/dist/assets/server-BUcJo4vz.js.map +1 -0
- package/dist/assets/{src-DWw2hUE5.js → src-BB5-5P3s.js} +540 -159
- package/dist/assets/src-BB5-5P3s.js.map +1 -0
- package/dist/assets/{translate-DObb-1tq.js → translate-2WyaRVCr.js} +11 -9
- package/dist/assets/translate-2WyaRVCr.js.map +1 -0
- package/dist/assets/{usdt-Bkva90Vo.js → usdt-BLazHiaP.js} +3 -3
- package/dist/assets/{usdt-Bkva90Vo.js.map → usdt-BLazHiaP.js.map} +1 -1
- package/dist/assets/{words-odSAoasK.js → words-BaumxjXe.js} +3 -3
- package/dist/assets/words-BaumxjXe.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/package.json +1 -1
- package/dist/assets/api-tf-wAAnB.js.map +0 -1
- package/dist/assets/apiKit-DJb9hulp.js.map +0 -1
- package/dist/assets/apps-DIrWmLgL.js.map +0 -1
- package/dist/assets/buttons-Be7u0V5g.js +0 -2
- package/dist/assets/errors-mnjSQlbX.js.map +0 -1
- package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
- package/dist/assets/groupFiles-BlZRBWpt.js.map +0 -1
- package/dist/assets/host-BX0DmKW6.js.map +0 -1
- package/dist/assets/idb-BlH8-O3R.js.map +0 -1
- package/dist/assets/main-6QOSvQ8b.js.map +0 -1
- package/dist/assets/mainline-BfwezHWi.js.map +0 -1
- package/dist/assets/profiles-C6XWqre5.js.map +0 -1
- package/dist/assets/registry-B0Uv9yL6.js.map +0 -1
- package/dist/assets/resolve-BzFG4WDU.js.map +0 -1
- package/dist/assets/server-BGCuHbmQ.js.map +0 -1
- package/dist/assets/src-DWw2hUE5.js.map +0 -1
- package/dist/assets/translate-DObb-1tq.js.map +0 -1
- package/dist/assets/words-odSAoasK.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import "./src-
|
|
2
|
-
import { t as CliError } from "./errors-
|
|
1
|
+
import { Da as LINK_TRAILING, Oa as linkStop } from "./src-BB5-5P3s.js";
|
|
2
|
+
import { t as CliError } from "./errors-QUGP-jIF.js";
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { spawn } from "node:child_process";
|
|
@@ -33,11 +33,13 @@ var CLOSERS = {
|
|
|
33
33
|
"}": "{"
|
|
34
34
|
};
|
|
35
35
|
/**
|
|
36
|
-
* A link ends where the sentence around it takes over: trailing punctuation ("see https://x.example/a."
|
|
37
|
-
*
|
|
38
|
-
* `~~` or `||` closing the strike or spoiler the link
|
|
36
|
+
* A link ends where the sentence around it takes over: trailing punctuation ("see https://x.example/a.", "見て
|
|
37
|
+
* https://x.example/a。", in any of the app's languages) and a closing bracket or quote the link did not open
|
|
38
|
+
* ("(https://x.example/a)") are left as text, and so is a doubled `~~` or `||` closing the strike or spoiler the link
|
|
39
|
+
* sits in.
|
|
39
40
|
*/
|
|
40
|
-
function linkEnd(
|
|
41
|
+
function linkEnd(whole) {
|
|
42
|
+
const url = linkStop(whole);
|
|
41
43
|
const count = {
|
|
42
44
|
"(": 0,
|
|
43
45
|
")": 0,
|
|
@@ -51,7 +53,7 @@ function linkEnd(url) {
|
|
|
51
53
|
while (end > 0) {
|
|
52
54
|
const last = url[end - 1];
|
|
53
55
|
const opener = CLOSERS[last];
|
|
54
|
-
if (
|
|
56
|
+
if (LINK_TRAILING.test(last) || opener && count[last] > count[opener]) {
|
|
55
57
|
if (opener) count[last]--;
|
|
56
58
|
end--;
|
|
57
59
|
} else if ((last === "~" || last === "|") && url[end - 2] === last) end -= 2;
|
|
@@ -85,7 +87,7 @@ function shownUrl(url) {
|
|
|
85
87
|
/** Web addresses, over http(s) only: `javascript:` and `data:` never become links. */
|
|
86
88
|
var link = {
|
|
87
89
|
kind: "link",
|
|
88
|
-
pattern: /https?:\/\/\S+/
|
|
90
|
+
pattern: /https?:\/\/\S+/gi,
|
|
89
91
|
accept(match) {
|
|
90
92
|
const url = linkEnd(match[0]);
|
|
91
93
|
if (url.length <= match[0].indexOf("//") + 2) return null;
|
|
@@ -1064,4 +1066,4 @@ function openTranslator({ home, to, detect, warn }) {
|
|
|
1064
1066
|
//#endregion
|
|
1065
1067
|
export { loadDetector, openTranslator, translateAnswer, translateTarget };
|
|
1066
1068
|
|
|
1067
|
-
//# sourceMappingURL=translate-
|
|
1069
|
+
//# sourceMappingURL=translate-2WyaRVCr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translate-2WyaRVCr.js","names":["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 } 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) and a closing bracket or quote the link did not open\n * (\"(https://x.example/a)\") are left as text, and so is a doubled `~~` or `||` closing the strike or spoiler the link\n * 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 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/** Direction and other invisible format characters, which can make a link read as another address. */\nexport const INVISIBLE = /[\\u00ad\\u061c\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2069\\ufeff]/g;\n\n/**\n * A link as a bubble shows it. Plain ASCII shows as typed. Anything else shows as the browser reads it: the host\n * in punycode (a look-alike \"аpple.com\" reads \"xn--pple-43d.com\") 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 return /^[\\x21-\\x7e]*$/.test(url) ? 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 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};\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<Detector, RegExp>();\nfunction patternOf(detector: Detector): RegExp {\n let re = compiled.get(detector);\n if (!re) {\n const { source, flags } = detector.pattern;\n re = new RegExp(source, flags.includes(\"g\") ? flags : flags + \"g\");\n compiled.set(detector, re);\n }\n return re;\n}\n\ntype Found = { start: number; end: number; data: unknown };\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/** 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) => findNext(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 found = next[best]!;\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] = findNext(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/** Characters a browser reads as the dot between a host's labels, and ones that only look like it. */\nconst DOTS = /[\\u00b7\\u0701\\u06d4\\u2024\\u2027\\u2e3c\\u3002\\uff0e\\uff61]/g;\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).test(label)) return true;\n const text = label.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. */\nfunction labelText(label: Segment[]): string {\n return label.map((s) => (s.type === \"span\" ? (s.style === \"spoiler\" ? SPOILER_PLAIN : labelText(s.children)) : s.text)).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 return { data: { url, label: tokenizeInline(text, []), showUrl: labelMisleads(text, url) } };\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/** A run of letters, digits and token characters with a digit in it: a number, a token, an invoice, an address, a code. */\nconst CODE_RUN = /[A-Za-z0-9_+/=:.-]*\\d[A-Za-z0-9_+/=:.-]*|\\p{N}+/gu;\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, \" \")\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 { 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\"] });\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;CAC1B,MAAM,QAAgC;EAAE,KAAK;EAAG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CAC9G;CAEA,OAAO;EACL;EACA,MAAM,MAAM,OAAO;GACjB,MAAM,QAAQ,MAAM;GACpB,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,SAAS,eAAe,OAAO;GAChF,MAAM,aAAa,MAAM,QAAQ,KAAK;GACtC,OAAO,eAAe,QAAQ,QAAQ;IAAE,GAAG;IAAO,SAAS;GAAW;EACxE;EACA,QAAQ;GACN,SAAS;GACT,QAAQ,IAAI,QAAQ,IAAI;GACxB,OAAO,MAAM,IAAI;EACnB;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { $t as
|
|
2
|
-
import { a as sealSeed, n as rpcHost, o as unsealSeed, t as networkReason } from "./networkReason-
|
|
1
|
+
import { $t as SEPOLIA_TEST_USDT, Hn as engineError, Qt as PaymentPreflightError, Xt as EVM_TEST_CHAINS, cn as validatePaymentTarget, en as SEPOLIA_TEST_USDT_FAUCET, nn as USDT_PUBLIC_RPC, tn as TEST_USDT_FAUCET_AMOUNT } from "./src-BB5-5P3s.js";
|
|
2
|
+
import { a as sealSeed, n as rpcHost, o as unsealSeed, t as networkReason } from "./networkReason-N2vAaoth.js";
|
|
3
3
|
import { mnemonicToSeedSync } from "@scure/bip39";
|
|
4
4
|
import WalletManagerEvm from "@tetherto/wdk-wallet-evm";
|
|
5
5
|
import { Interface, Transaction, getAddress, keccak256 } from "ethers";
|
|
@@ -407,4 +407,4 @@ var UsdtAdapter = class UsdtAdapter {
|
|
|
407
407
|
//#endregion
|
|
408
408
|
export { UsdtAdapter, wireProvider };
|
|
409
409
|
|
|
410
|
-
//# sourceMappingURL=usdt-
|
|
410
|
+
//# sourceMappingURL=usdt-BLazHiaP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usdt-Bkva90Vo.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/usdt.ts"],"sourcesContent":["import { mnemonicToSeedSync } from '@scure/bip39';\nimport WalletManagerEvm, { type WalletAccountEvm } from '@tetherto/wdk-wallet-evm';\nimport { Interface, Transaction, getAddress, keccak256 } from 'ethers';\nimport { ETHEREUM_USDT, EVM_TEST_CHAINS, USDT_PUBLIC_RPC, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, TEST_USDT_FAUCET_AMOUNT, PaymentPreflightError, engineError, validatePaymentTarget, type PaymentAdapter, type PaymentExecution, type PaymentReview, type PaymentTarget } from '@ghostly/core';\nimport { sealSeed, unsealSeed, type EncryptedSeed } from './persistence';\nimport { networkReason, rpcHost } from './networkReason';\n\nexport interface UsdtConfig {\n network: 'ethereum' | 'sepolia' | 'evm-local';\n provider: string;\n chainId: 1 | 11155111 | 31337;\n token: string;\n decimals: number;\n codeHash: string;\n}\nexport interface UsdtPrepared {\n from: string; to: string; data: string; value: string; chainId: number; nonce: number;\n gasLimit: string; maxFeePerGas: string; maxPriorityFeePerGas: string;\n signed?: EncryptedSeed; hash?: string;\n}\nconst faucet = new Interface(['function mint(address token,address to,uint256 amount) returns (uint256)']);\nconst erc20 = new Interface(['function decimals() view returns(uint8)', 'function balanceOf(address) view returns(uint256)', 'function transfer(address,uint256) returns(bool)', 'event Transfer(address indexed from,address indexed to,uint256 value)']);\nconst same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\nconst CONFIRMATIONS = 2;\n/** The JSON-RPC methods that only read: asked again once when they fail (see `UsdtAdapter.rpc`). */\nconst RETRIED_READS = new Set(['eth_chainId', 'eth_getCode', 'eth_call', 'eth_getBalance', 'eth_blockNumber', 'eth_getLogs', 'eth_getTransactionCount', 'eth_estimateGas', 'eth_getBlockByNumber', 'eth_maxPriorityFeePerGas', 'eth_gasPrice', 'eth_feeHistory', 'eth_getTransactionByHash', 'eth_getTransactionReceipt']);\nconst RETRY_AFTER_MS = 1000;\n/** Failures that would fail the same way again at once: not retried. */\nconst FINAL = new WeakSet<object>();\nconst timedOut = (error: unknown) => error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');\n\n/**\n * The `provider` a request carries to the contact. Which RPC pays is the payer's own choice, so it names none of\n * this wallet's: a typed RPC URL may hold an API key (`/v3/<key>`), and every contact would read it. Older apps\n * require a URL here and pay only when it equals their own RPC, so it is the chain's public RPC (the default both\n * start with), and a local test chain's origin, without its path.\n */\nexport function wireProvider(config: Pick<UsdtConfig, 'network' | 'provider'>): string {\n return config.network === 'evm-local' ? new URL(config.provider).origin : USDT_PUBLIC_RPC[config.network];\n}\n\n/** WDK signs locally. Every network call uses the configured RPC, never a peer-supplied URL. */\nexport class UsdtAdapter implements PaymentAdapter<UsdtPrepared> {\n readonly method = 'usdt' as const;\n private manager?: WalletManagerEvm;\n private account?: WalletAccountEvm;\n private mnemonic = '';\n private nextId = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private constructor(readonly config: UsdtConfig) {}\n\n static async inspect(config: Omit<UsdtConfig, 'decimals' | 'codeHash'>): Promise<UsdtConfig> {\n if (config.network === 'ethereum' ? config.chainId !== 1 || !same(config.token, ETHEREUM_USDT) : !(config.network in EVM_TEST_CHAINS) || config.chainId !== EVM_TEST_CHAINS[config.network]) throw new Error('Unsupported USDT network or contract');\n const token = getAddress(config.token);\n const url = new URL(config.provider);\n if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) throw new Error('Use HTTPS or a loopback test RPC');\n const adapter = new UsdtAdapter({...config, token, decimals: 6, codeHash: ''});\n await adapter.chain();\n const code = await adapter.rpc<string>('eth_getCode', [token, 'latest']);\n if (code === '0x') throw new Error('No token contract exists on this chain');\n const result = await adapter.rpc<string>('eth_call', [{to: token, data: erc20.encodeFunctionData('decimals')}, 'latest']);\n const decimals = Number(erc20.decodeFunctionResult('decimals', result)[0]);\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18 || (config.chainId === 1 && decimals !== 6)) throw new Error('Unexpected token decimals');\n return {...config, token, decimals, codeHash: keccak256(code)};\n }\n static async connect(config: UsdtConfig, mnemonic: string): Promise<UsdtAdapter> {\n const inspected = await UsdtAdapter.inspect(config);\n if (inspected.decimals !== config.decimals || inspected.codeHash !== config.codeHash) throw new Error('Token metadata changed; do not use this wallet configuration');\n const adapter = new UsdtAdapter(config);\n adapter.mnemonic = mnemonic;\n // Pass standard BIP-39 seed bytes: WDK's string helper assumes a Node Buffer global.\n const seed = mnemonicToSeedSync(mnemonic);\n try { adapter.manager = new WalletManagerEvm(seed, {provider: {request: ({method, params}) => adapter.rpc(method, params as unknown[] ?? [])}, chainId: config.chainId}); } finally { seed.fill(0); }\n adapter.account = await adapter.manager.getAccount(0);\n return adapter;\n }\n /**\n * A read that fails is asked again, once, a moment later: a public RPC drops a request now and then, and a chain that\n * just made a block can refuse a read of \"latest\" it no longer holds. Without it a network switch, a restore or New\n * gave up on the first such answer. Never a broadcast or anything else that writes, nor a request that did not answer\n * in time (the person would wait twice as long), nor one the server refused as such (4xx).\n */\n async rpc<T>(method: string, params: unknown[] = []): Promise<T> {\n try { return await this.ask<T>(method, params); }\n catch (error) {\n if (!RETRIED_READS.has(method) || FINAL.has(error as object)) throw error;\n await new Promise((resolve) => setTimeout(resolve, RETRY_AFTER_MS));\n return this.ask<T>(method, params);\n }\n }\n private async ask<T>(method: string, params: unknown[]): Promise<T> {\n let response: Response;\n // The browser's words for a request that got no answer (\"Fetch is aborted\") say nothing: the RPC's host does.\n try { response = await fetch(this.config.provider, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({jsonrpc:'2.0',id:++this.nextId,method,params}), signal:AbortSignal.timeout(15000)}); }\n catch (error) {\n const reason = networkReason(error, rpcHost(this.config.provider));\n const thrown = reason ? Object.assign(new Error(reason), {cause: error}) : error;\n if (timedOut(error) && thrown && typeof thrown === 'object') FINAL.add(thrown);\n throw thrown;\n }\n if (!response.ok) { const error = engineError('usdtRpcUnavailable'); if (response.status !== 429 && response.status < 500) FINAL.add(error); throw error; }\n const result = await response.json();\n if (result.error || !Object.prototype.hasOwnProperty.call(result, 'result')) throw new Error('USDT RPC rejected the operation');\n return result.result as T;\n }\n private async chain() {\n if (BigInt(await this.rpc<string>('eth_chainId')) !== BigInt(this.config.chainId)) throw new Error('RPC chain does not match this wallet');\n }\n private async assertToken() {\n await this.chain();\n const code = await this.rpc<string>('eth_getCode', [this.config.token, 'latest']);\n if (code === '0x' || keccak256(code) !== this.config.codeHash) throw new Error('Token contract changed');\n }\n /**\n * Sepolia only: asks Aave's public faucet for test USDT, to this wallet, paid with its own test ETH.\n * Everything is fixed here (chain, contract, token, amount, recipient): nothing comes from outside.\n */\n mintTestTokens(): Promise<string> { return this.serial(async () => {\n if (this.config.chainId !== EVM_TEST_CHAINS.sepolia || !same(this.config.token, SEPOLIA_TEST_USDT)) throw new Error('Test USDT comes from a faucet on Sepolia only');\n await this.chain();\n const account = this.current(), from = await account.getAddress();\n const data = faucet.encodeFunctionData('mint', [SEPOLIA_TEST_USDT, from, BigInt(TEST_USDT_FAUCET_AMOUNT)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount', [from, 'pending'])));\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas', [{ from, to: SEPOLIA_TEST_USDT_FAUCET, data, value: '0x0' }]));\n const block = await this.rpc<{ baseFeePerGas?: string }>('eth_getBlockByNumber', ['latest', false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFeePerGas = BigInt(block.baseFeePerGas) * 2n + priority, gasLimit = (estimate * 120n + 99n) / 100n;\n if (BigInt((await this.balances()).gasBalance) < gasLimit * maxFeePerGas) throw engineError('usdtNeedsSepoliaGas');\n const raw = await account.signTransaction({ type: 2, to: SEPOLIA_TEST_USDT_FAUCET, data, value: 0n, chainId: this.config.chainId, nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas: priority });\n await account.sendTransaction(raw);\n return Transaction.from(raw).hash!;\n }); }\n private current(): WalletAccountEvm { if (!this.account) throw new Error('Unlock the USDT wallet first'); return this.account; }\n address() { return this.current().getAddress(); }\n async balances() {\n await this.assertToken();\n const address = await this.address();\n const [token, gas] = await Promise.all([this.rpc<string>('eth_call',[{to:this.config.token,data:erc20.encodeFunctionData('balanceOf',[address])},'latest']),this.rpc<string>('eth_getBalance',[address,'pending'])]);\n return {balance:erc20.decodeFunctionResult('balanceOf',token)[0].toString(),gasBalance:BigInt(gas).toString()};\n }\n async target(): Promise<PaymentTarget> {\n const now = Date.now();\n return {method:'usdt',network:this.config.network,provider:wireProvider(this.config),asset:this.config.chainId === 1 ? 'USDT':'TEST-USDT',unit:'token-base',address:await this.address(),chainId:this.config.chainId,token:this.config.token,decimals:this.config.decimals,issuedAt:now,expiresAt:now+15*60*1000};\n }\n /** The request is for this wallet's token on its chain. Its `provider` is not compared: this wallet's own RPC pays. */\n private matches(target: PaymentTarget) {\n validatePaymentTarget(target);\n if (target.method !== 'usdt' || target.network !== this.config.network || target.chainId !== this.config.chainId || !same(target.token!,this.config.token) || target.decimals !== this.config.decimals) throw new Error('Request does not match the configured token and network');\n }\n prepare(target: PaymentTarget, amount: number, feeCap: number) { return this.serial(async () => {\n this.matches(target);\n await this.assertToken();\n const from = await this.address(), to = this.config.token;\n if (same(target.address, from) || same(target.address, to)) throw new Error('Choose a different recipient address');\n const {balance,gasBalance} = await this.balances();\n if (BigInt(balance) < BigInt(amount)) throw engineError('usdtNotEnoughTokens');\n const data = erc20.encodeFunctionData('transfer', [getAddress(target.address),BigInt(amount)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[from,'pending'])));\n if (!Number.isSafeInteger(nonce)) throw new Error('Invalid account nonce');\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas',[{from,to,data,value:'0x0'}]));\n const block = await this.rpc<{baseFeePerGas?:string}>('eth_getBlockByNumber',['latest',false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFee = BigInt(block.baseFeePerGas)*2n + priority;\n const gasLimit = (estimate*120n+99n)/100n;\n const maximum = gasLimit*maxFee;\n if (maximum > BigInt(feeCap) || maximum > BigInt(Number.MAX_SAFE_INTEGER)) throw engineError('usdtGasAboveLimit');\n if (BigInt(gasBalance) < maximum) throw engineError('usdtNotEnoughGas');\n const prepared:UsdtPrepared = {from,to,data,value:'0',chainId:this.config.chainId,nonce,gasLimit:gasLimit.toString(),maxFeePerGas:maxFee.toString(),maxPriorityFeePerGas:priority.toString()};\n return {fee:Number(maximum),prepared,evm:{from,nonce,gasLimit:prepared.gasLimit,maxFeePerGas:prepared.maxFeePerGas,maxPriorityFeePerGas:prepared.maxPriorityFeePerGas,confirmations:CONFIRMATIONS}};\n }); }\n private verifyPrepared(review: PaymentReview, tx: UsdtPrepared) {\n if (tx.chainId !== this.config.chainId || !same(tx.to,this.config.token) || tx.value !== '0' || tx.data !== erc20.encodeFunctionData('transfer',[getAddress(review.address),BigInt(review.amount)]) || BigInt(tx.gasLimit)*BigInt(tx.maxFeePerGas) !== BigInt(review.fee) || review.fee > review.feeCap || tx.nonce !== review.evm?.nonce || !same(tx.from,review.evm?.from ?? '')) throw new Error('Transaction no longer matches the approved review');\n }\n private verifySigned(raw: string, saved: UsdtPrepared) {\n const tx = Transaction.from(raw);\n if (!tx.hash || !tx.from || !same(tx.from,saved.from) || tx.chainId !== BigInt(saved.chainId) || !tx.to || !same(tx.to,saved.to) || tx.data !== saved.data || tx.value !== 0n || tx.nonce !== saved.nonce || tx.gasLimit !== BigInt(saved.gasLimit) || tx.maxFeePerGas !== BigInt(saved.maxFeePerGas) || tx.maxPriorityFeePerGas !== BigInt(saved.maxPriorityFeePerGas)) throw new Error('Signature does not match the approved transaction');\n return tx.hash;\n }\n execute(review: PaymentReview, prepared: UsdtPrepared, persist?:()=>Promise<void>) { return this.serial(async () => {\n let account:WalletAccountEvm;\n try {\n this.matches(review); this.verifyPrepared(review,prepared);\n await this.assertToken(); account=this.current();\n if (!same(await account.getAddress(),prepared.from)) throw new Error('Wrong wallet');\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce !== prepared.nonce) throw new Error('Account nonce changed. Create a new review');\n const balances = await this.balances();\n if (BigInt(balances.balance)<BigInt(review.amount) || BigInt(balances.gasBalance)<BigInt(review.fee)) throw new Error('Token or gas balance changed. Create a new review');\n if (!persist) throw new Error('Durable payment journal required');\n } catch (error) { throw new PaymentPreflightError(error instanceof Error ? error.message : 'Could not validate payment'); }\n const raw = await account.signTransaction({type:2,to:prepared.to,data:prepared.data,value:0n,chainId:prepared.chainId,nonce:prepared.nonce,gasLimit:BigInt(prepared.gasLimit),maxFeePerGas:BigInt(prepared.maxFeePerGas),maxPriorityFeePerGas:BigInt(prepared.maxPriorityFeePerGas)});\n prepared.hash = this.verifySigned(raw,prepared);\n prepared.signed = await sealSeed(raw,this.mnemonic);\n await persist!(); // Nothing may broadcast before the encrypted bytes are durable.\n await account.sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n reconcile(review: PaymentReview, prepared: UsdtPrepared) { return this.serial(async () => {\n await this.assertToken(); this.verifyPrepared(review,prepared);\n if (!prepared.signed || !prepared.hash) return {settled:false,failed:true,error:'No signed transaction was submitted. Create a new review.'};\n const result = await this.receipt(prepared.hash,review,prepared.from);\n if (result.settled || result.failed || result.pending) return result;\n // An uncertain network response permits only replay of exactly the saved bytes.\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce > prepared.nonce) return result;\n const raw = await unsealSeed(prepared.signed,this.mnemonic);\n if (this.verifySigned(raw,prepared) !== prepared.hash || !same(await this.address(),prepared.from)) throw new Error('Recovery wallet mismatch');\n await this.current().sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n async receipt(hash: string, target: PaymentTarget & {amount:number}, expectedFrom?:string): Promise<PaymentExecution> {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash) || target.chainId !== this.config.chainId || !same(target.token ?? '',this.config.token) || target.decimals !== this.config.decimals) throw new Error('Invalid receipt target');\n await this.assertToken();\n const tx = await this.rpc<{from:string;to:string;input:string;value:string;nonce:string}|null>('eth_getTransactionByHash',[hash]);\n if (!tx) return {txid:hash,settled:false};\n if (!same(tx.to,this.config.token) || (expectedFrom && !same(tx.from,expectedFrom)) || BigInt(tx.value)!==0n || tx.input !== erc20.encodeFunctionData('transfer',[getAddress(target.address),BigInt(target.amount)])) throw new Error('Transaction is not the requested token transfer');\n const receipt = await this.rpc<{status:string;blockNumber:string;blockHash:string;logs:Array<{address:string;topics:string[];data:string}>}|null>('eth_getTransactionReceipt',[hash]);\n if (!receipt) return {txid:hash,settled:false,pending:true};\n const block = await this.rpc<{hash:string;timestamp:string}>('eth_getBlockByNumber',[receipt.blockNumber,false]);\n if (!block || block.hash !== receipt.blockHash || BigInt(block.timestamp)*1000n < BigInt((target.issuedAt ?? 0)-1000)) return {txid:hash,settled:false};\n const height = BigInt(await this.rpc<string>('eth_blockNumber'));\n if (height-BigInt(receipt.blockNumber)+1n < BigInt(CONFIRMATIONS)) return {txid:hash,settled:false,pending:true};\n if (BigInt(receipt.status)!==1n) return {txid:hash,settled:false,failed:true,error:'Transaction reverted. Tokens were not sent; gas was spent.'};\n const transfer = receipt.logs.some(log=>{\n if (!same(log.address,this.config.token)) return false;\n try {const event=erc20.parseLog(log);return event?.name==='Transfer' && same(event.args[0],tx.from) && same(event.args[1],target.address) && event.args[2]===BigInt(target.amount);} catch {return false;}\n });\n if (!transfer) throw new Error('Receipt has no matching token Transfer');\n return {txid:hash,settled:true};\n }\n async dispose() { await this.queue.catch(()=>{}); this.account=undefined;this.manager?.dispose();this.manager=undefined;this.mnemonic=''; }\n private serial<T>(work:()=>Promise<T>):Promise<T> { const operation=this.queue.then(work,work);this.queue=operation.catch(()=>{});return operation; }\n}\n"],"mappings":";;;;;;AAoBA,IAAM,SAAS,IA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wC;EACvE,OAAO;GAAC,MAAK;GAAK,SAAQ;EAAI;CAChC;CACA,MAAM,UAAU;EAAE,MAAM,KAAK,MAAM,YAAU,CAAC,CAAC;EAAG,KAAK,UAAQ,KAAA;EAAU,KAAK,SAAS,QAAQ;EAAE,KAAK,UAAQ,KAAA;EAAU,KAAK,WAAS;CAAI;CAC1I,OAAkB,MAAgC;EAAE,MAAM,YAAU,KAAK,MAAM,KAAK,MAAK,IAAI;EAAE,KAAK,QAAM,UAAU,YAAU,CAAC,CAAC;EAAE,OAAO;CAAW;AACtJ"}
|
|
1
|
+
{"version":3,"file":"usdt-BLazHiaP.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/usdt.ts"],"sourcesContent":["import { mnemonicToSeedSync } from '@scure/bip39';\nimport WalletManagerEvm, { type WalletAccountEvm } from '@tetherto/wdk-wallet-evm';\nimport { Interface, Transaction, getAddress, keccak256 } from 'ethers';\nimport { ETHEREUM_USDT, EVM_TEST_CHAINS, USDT_PUBLIC_RPC, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, TEST_USDT_FAUCET_AMOUNT, PaymentPreflightError, engineError, validatePaymentTarget, type PaymentAdapter, type PaymentExecution, type PaymentReview, type PaymentTarget } from '@ghostly/core';\nimport { sealSeed, unsealSeed, type EncryptedSeed } from './persistence';\nimport { networkReason, rpcHost } from './networkReason';\n\nexport interface UsdtConfig {\n network: 'ethereum' | 'sepolia' | 'evm-local';\n provider: string;\n chainId: 1 | 11155111 | 31337;\n token: string;\n decimals: number;\n codeHash: string;\n}\nexport interface UsdtPrepared {\n from: string; to: string; data: string; value: string; chainId: number; nonce: number;\n gasLimit: string; maxFeePerGas: string; maxPriorityFeePerGas: string;\n signed?: EncryptedSeed; hash?: string;\n}\nconst faucet = new Interface(['function mint(address token,address to,uint256 amount) returns (uint256)']);\nconst erc20 = new Interface(['function decimals() view returns(uint8)', 'function balanceOf(address) view returns(uint256)', 'function transfer(address,uint256) returns(bool)', 'event Transfer(address indexed from,address indexed to,uint256 value)']);\nconst same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\nconst CONFIRMATIONS = 2;\n/** The JSON-RPC methods that only read: asked again once when they fail (see `UsdtAdapter.rpc`). */\nconst RETRIED_READS = new Set(['eth_chainId', 'eth_getCode', 'eth_call', 'eth_getBalance', 'eth_blockNumber', 'eth_getLogs', 'eth_getTransactionCount', 'eth_estimateGas', 'eth_getBlockByNumber', 'eth_maxPriorityFeePerGas', 'eth_gasPrice', 'eth_feeHistory', 'eth_getTransactionByHash', 'eth_getTransactionReceipt']);\nconst RETRY_AFTER_MS = 1000;\n/** Failures that would fail the same way again at once: not retried. */\nconst FINAL = new WeakSet<object>();\nconst timedOut = (error: unknown) => error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');\n\n/**\n * The `provider` a request carries to the contact. Which RPC pays is the payer's own choice, so it names none of\n * this wallet's: a typed RPC URL may hold an API key (`/v3/<key>`), and every contact would read it. Older apps\n * require a URL here and pay only when it equals their own RPC, so it is the chain's public RPC (the default both\n * start with), and a local test chain's origin, without its path.\n */\nexport function wireProvider(config: Pick<UsdtConfig, 'network' | 'provider'>): string {\n return config.network === 'evm-local' ? new URL(config.provider).origin : USDT_PUBLIC_RPC[config.network];\n}\n\n/** WDK signs locally. Every network call uses the configured RPC, never a peer-supplied URL. */\nexport class UsdtAdapter implements PaymentAdapter<UsdtPrepared> {\n readonly method = 'usdt' as const;\n private manager?: WalletManagerEvm;\n private account?: WalletAccountEvm;\n private mnemonic = '';\n private nextId = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private constructor(readonly config: UsdtConfig) {}\n\n static async inspect(config: Omit<UsdtConfig, 'decimals' | 'codeHash'>): Promise<UsdtConfig> {\n if (config.network === 'ethereum' ? config.chainId !== 1 || !same(config.token, ETHEREUM_USDT) : !(config.network in EVM_TEST_CHAINS) || config.chainId !== EVM_TEST_CHAINS[config.network]) throw new Error('Unsupported USDT network or contract');\n const token = getAddress(config.token);\n const url = new URL(config.provider);\n if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) throw new Error('Use HTTPS or a loopback test RPC');\n const adapter = new UsdtAdapter({...config, token, decimals: 6, codeHash: ''});\n await adapter.chain();\n const code = await adapter.rpc<string>('eth_getCode', [token, 'latest']);\n if (code === '0x') throw new Error('No token contract exists on this chain');\n const result = await adapter.rpc<string>('eth_call', [{to: token, data: erc20.encodeFunctionData('decimals')}, 'latest']);\n const decimals = Number(erc20.decodeFunctionResult('decimals', result)[0]);\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18 || (config.chainId === 1 && decimals !== 6)) throw new Error('Unexpected token decimals');\n return {...config, token, decimals, codeHash: keccak256(code)};\n }\n static async connect(config: UsdtConfig, mnemonic: string): Promise<UsdtAdapter> {\n const inspected = await UsdtAdapter.inspect(config);\n if (inspected.decimals !== config.decimals || inspected.codeHash !== config.codeHash) throw new Error('Token metadata changed; do not use this wallet configuration');\n const adapter = new UsdtAdapter(config);\n adapter.mnemonic = mnemonic;\n // Pass standard BIP-39 seed bytes: WDK's string helper assumes a Node Buffer global.\n const seed = mnemonicToSeedSync(mnemonic);\n try { adapter.manager = new WalletManagerEvm(seed, {provider: {request: ({method, params}) => adapter.rpc(method, params as unknown[] ?? [])}, chainId: config.chainId}); } finally { seed.fill(0); }\n adapter.account = await adapter.manager.getAccount(0);\n return adapter;\n }\n /**\n * A read that fails is asked again, once, a moment later: a public RPC drops a request now and then, and a chain that\n * just made a block can refuse a read of \"latest\" it no longer holds. Without it a network switch, a restore or New\n * gave up on the first such answer. Never a broadcast or anything else that writes, nor a request that did not answer\n * in time (the person would wait twice as long), nor one the server refused as such (4xx).\n */\n async rpc<T>(method: string, params: unknown[] = []): Promise<T> {\n try { return await this.ask<T>(method, params); }\n catch (error) {\n if (!RETRIED_READS.has(method) || FINAL.has(error as object)) throw error;\n await new Promise((resolve) => setTimeout(resolve, RETRY_AFTER_MS));\n return this.ask<T>(method, params);\n }\n }\n private async ask<T>(method: string, params: unknown[]): Promise<T> {\n let response: Response;\n // The browser's words for a request that got no answer (\"Fetch is aborted\") say nothing: the RPC's host does.\n try { response = await fetch(this.config.provider, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({jsonrpc:'2.0',id:++this.nextId,method,params}), signal:AbortSignal.timeout(15000)}); }\n catch (error) {\n const reason = networkReason(error, rpcHost(this.config.provider));\n const thrown = reason ? Object.assign(new Error(reason), {cause: error}) : error;\n if (timedOut(error) && thrown && typeof thrown === 'object') FINAL.add(thrown);\n throw thrown;\n }\n if (!response.ok) { const error = engineError('usdtRpcUnavailable'); if (response.status !== 429 && response.status < 500) FINAL.add(error); throw error; }\n const result = await response.json();\n if (result.error || !Object.prototype.hasOwnProperty.call(result, 'result')) throw new Error('USDT RPC rejected the operation');\n return result.result as T;\n }\n private async chain() {\n if (BigInt(await this.rpc<string>('eth_chainId')) !== BigInt(this.config.chainId)) throw new Error('RPC chain does not match this wallet');\n }\n private async assertToken() {\n await this.chain();\n const code = await this.rpc<string>('eth_getCode', [this.config.token, 'latest']);\n if (code === '0x' || keccak256(code) !== this.config.codeHash) throw new Error('Token contract changed');\n }\n /**\n * Sepolia only: asks Aave's public faucet for test USDT, to this wallet, paid with its own test ETH.\n * Everything is fixed here (chain, contract, token, amount, recipient): nothing comes from outside.\n */\n mintTestTokens(): Promise<string> { return this.serial(async () => {\n if (this.config.chainId !== EVM_TEST_CHAINS.sepolia || !same(this.config.token, SEPOLIA_TEST_USDT)) throw new Error('Test USDT comes from a faucet on Sepolia only');\n await this.chain();\n const account = this.current(), from = await account.getAddress();\n const data = faucet.encodeFunctionData('mint', [SEPOLIA_TEST_USDT, from, BigInt(TEST_USDT_FAUCET_AMOUNT)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount', [from, 'pending'])));\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas', [{ from, to: SEPOLIA_TEST_USDT_FAUCET, data, value: '0x0' }]));\n const block = await this.rpc<{ baseFeePerGas?: string }>('eth_getBlockByNumber', ['latest', false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFeePerGas = BigInt(block.baseFeePerGas) * 2n + priority, gasLimit = (estimate * 120n + 99n) / 100n;\n if (BigInt((await this.balances()).gasBalance) < gasLimit * maxFeePerGas) throw engineError('usdtNeedsSepoliaGas');\n const raw = await account.signTransaction({ type: 2, to: SEPOLIA_TEST_USDT_FAUCET, data, value: 0n, chainId: this.config.chainId, nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas: priority });\n await account.sendTransaction(raw);\n return Transaction.from(raw).hash!;\n }); }\n private current(): WalletAccountEvm { if (!this.account) throw new Error('Unlock the USDT wallet first'); return this.account; }\n address() { return this.current().getAddress(); }\n async balances() {\n await this.assertToken();\n const address = await this.address();\n const [token, gas] = await Promise.all([this.rpc<string>('eth_call',[{to:this.config.token,data:erc20.encodeFunctionData('balanceOf',[address])},'latest']),this.rpc<string>('eth_getBalance',[address,'pending'])]);\n return {balance:erc20.decodeFunctionResult('balanceOf',token)[0].toString(),gasBalance:BigInt(gas).toString()};\n }\n async target(): Promise<PaymentTarget> {\n const now = Date.now();\n return {method:'usdt',network:this.config.network,provider:wireProvider(this.config),asset:this.config.chainId === 1 ? 'USDT':'TEST-USDT',unit:'token-base',address:await this.address(),chainId:this.config.chainId,token:this.config.token,decimals:this.config.decimals,issuedAt:now,expiresAt:now+15*60*1000};\n }\n /** The request is for this wallet's token on its chain. Its `provider` is not compared: this wallet's own RPC pays. */\n private matches(target: PaymentTarget) {\n validatePaymentTarget(target);\n if (target.method !== 'usdt' || target.network !== this.config.network || target.chainId !== this.config.chainId || !same(target.token!,this.config.token) || target.decimals !== this.config.decimals) throw new Error('Request does not match the configured token and network');\n }\n prepare(target: PaymentTarget, amount: number, feeCap: number) { return this.serial(async () => {\n this.matches(target);\n await this.assertToken();\n const from = await this.address(), to = this.config.token;\n if (same(target.address, from) || same(target.address, to)) throw new Error('Choose a different recipient address');\n const {balance,gasBalance} = await this.balances();\n if (BigInt(balance) < BigInt(amount)) throw engineError('usdtNotEnoughTokens');\n const data = erc20.encodeFunctionData('transfer', [getAddress(target.address),BigInt(amount)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[from,'pending'])));\n if (!Number.isSafeInteger(nonce)) throw new Error('Invalid account nonce');\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas',[{from,to,data,value:'0x0'}]));\n const block = await this.rpc<{baseFeePerGas?:string}>('eth_getBlockByNumber',['latest',false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFee = BigInt(block.baseFeePerGas)*2n + priority;\n const gasLimit = (estimate*120n+99n)/100n;\n const maximum = gasLimit*maxFee;\n if (maximum > BigInt(feeCap) || maximum > BigInt(Number.MAX_SAFE_INTEGER)) throw engineError('usdtGasAboveLimit');\n if (BigInt(gasBalance) < maximum) throw engineError('usdtNotEnoughGas');\n const prepared:UsdtPrepared = {from,to,data,value:'0',chainId:this.config.chainId,nonce,gasLimit:gasLimit.toString(),maxFeePerGas:maxFee.toString(),maxPriorityFeePerGas:priority.toString()};\n return {fee:Number(maximum),prepared,evm:{from,nonce,gasLimit:prepared.gasLimit,maxFeePerGas:prepared.maxFeePerGas,maxPriorityFeePerGas:prepared.maxPriorityFeePerGas,confirmations:CONFIRMATIONS}};\n }); }\n private verifyPrepared(review: PaymentReview, tx: UsdtPrepared) {\n if (tx.chainId !== this.config.chainId || !same(tx.to,this.config.token) || tx.value !== '0' || tx.data !== erc20.encodeFunctionData('transfer',[getAddress(review.address),BigInt(review.amount)]) || BigInt(tx.gasLimit)*BigInt(tx.maxFeePerGas) !== BigInt(review.fee) || review.fee > review.feeCap || tx.nonce !== review.evm?.nonce || !same(tx.from,review.evm?.from ?? '')) throw new Error('Transaction no longer matches the approved review');\n }\n private verifySigned(raw: string, saved: UsdtPrepared) {\n const tx = Transaction.from(raw);\n if (!tx.hash || !tx.from || !same(tx.from,saved.from) || tx.chainId !== BigInt(saved.chainId) || !tx.to || !same(tx.to,saved.to) || tx.data !== saved.data || tx.value !== 0n || tx.nonce !== saved.nonce || tx.gasLimit !== BigInt(saved.gasLimit) || tx.maxFeePerGas !== BigInt(saved.maxFeePerGas) || tx.maxPriorityFeePerGas !== BigInt(saved.maxPriorityFeePerGas)) throw new Error('Signature does not match the approved transaction');\n return tx.hash;\n }\n execute(review: PaymentReview, prepared: UsdtPrepared, persist?:()=>Promise<void>) { return this.serial(async () => {\n let account:WalletAccountEvm;\n try {\n this.matches(review); this.verifyPrepared(review,prepared);\n await this.assertToken(); account=this.current();\n if (!same(await account.getAddress(),prepared.from)) throw new Error('Wrong wallet');\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce !== prepared.nonce) throw new Error('Account nonce changed. Create a new review');\n const balances = await this.balances();\n if (BigInt(balances.balance)<BigInt(review.amount) || BigInt(balances.gasBalance)<BigInt(review.fee)) throw new Error('Token or gas balance changed. Create a new review');\n if (!persist) throw new Error('Durable payment journal required');\n } catch (error) { throw new PaymentPreflightError(error instanceof Error ? error.message : 'Could not validate payment'); }\n const raw = await account.signTransaction({type:2,to:prepared.to,data:prepared.data,value:0n,chainId:prepared.chainId,nonce:prepared.nonce,gasLimit:BigInt(prepared.gasLimit),maxFeePerGas:BigInt(prepared.maxFeePerGas),maxPriorityFeePerGas:BigInt(prepared.maxPriorityFeePerGas)});\n prepared.hash = this.verifySigned(raw,prepared);\n prepared.signed = await sealSeed(raw,this.mnemonic);\n await persist!(); // Nothing may broadcast before the encrypted bytes are durable.\n await account.sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n reconcile(review: PaymentReview, prepared: UsdtPrepared) { return this.serial(async () => {\n await this.assertToken(); this.verifyPrepared(review,prepared);\n if (!prepared.signed || !prepared.hash) return {settled:false,failed:true,error:'No signed transaction was submitted. Create a new review.'};\n const result = await this.receipt(prepared.hash,review,prepared.from);\n if (result.settled || result.failed || result.pending) return result;\n // An uncertain network response permits only replay of exactly the saved bytes.\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce > prepared.nonce) return result;\n const raw = await unsealSeed(prepared.signed,this.mnemonic);\n if (this.verifySigned(raw,prepared) !== prepared.hash || !same(await this.address(),prepared.from)) throw new Error('Recovery wallet mismatch');\n await this.current().sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n async receipt(hash: string, target: PaymentTarget & {amount:number}, expectedFrom?:string): Promise<PaymentExecution> {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash) || target.chainId !== this.config.chainId || !same(target.token ?? '',this.config.token) || target.decimals !== this.config.decimals) throw new Error('Invalid receipt target');\n await this.assertToken();\n const tx = await this.rpc<{from:string;to:string;input:string;value:string;nonce:string}|null>('eth_getTransactionByHash',[hash]);\n if (!tx) return {txid:hash,settled:false};\n if (!same(tx.to,this.config.token) || (expectedFrom && !same(tx.from,expectedFrom)) || BigInt(tx.value)!==0n || tx.input !== erc20.encodeFunctionData('transfer',[getAddress(target.address),BigInt(target.amount)])) throw new Error('Transaction is not the requested token transfer');\n const receipt = await this.rpc<{status:string;blockNumber:string;blockHash:string;logs:Array<{address:string;topics:string[];data:string}>}|null>('eth_getTransactionReceipt',[hash]);\n if (!receipt) return {txid:hash,settled:false,pending:true};\n const block = await this.rpc<{hash:string;timestamp:string}>('eth_getBlockByNumber',[receipt.blockNumber,false]);\n if (!block || block.hash !== receipt.blockHash || BigInt(block.timestamp)*1000n < BigInt((target.issuedAt ?? 0)-1000)) return {txid:hash,settled:false};\n const height = BigInt(await this.rpc<string>('eth_blockNumber'));\n if (height-BigInt(receipt.blockNumber)+1n < BigInt(CONFIRMATIONS)) return {txid:hash,settled:false,pending:true};\n if (BigInt(receipt.status)!==1n) return {txid:hash,settled:false,failed:true,error:'Transaction reverted. Tokens were not sent; gas was spent.'};\n const transfer = receipt.logs.some(log=>{\n if (!same(log.address,this.config.token)) return false;\n try {const event=erc20.parseLog(log);return event?.name==='Transfer' && same(event.args[0],tx.from) && same(event.args[1],target.address) && event.args[2]===BigInt(target.amount);} catch {return false;}\n });\n if (!transfer) throw new Error('Receipt has no matching token Transfer');\n return {txid:hash,settled:true};\n }\n async dispose() { await this.queue.catch(()=>{}); this.account=undefined;this.manager?.dispose();this.manager=undefined;this.mnemonic=''; }\n private serial<T>(work:()=>Promise<T>):Promise<T> { const operation=this.queue.then(work,work);this.queue=operation.catch(()=>{});return operation; }\n}\n"],"mappings":";;;;;;AAoBA,IAAM,SAAS,IAAI,UAAU,CAAC,0EAA0E,CAAC;AACzG,IAAM,QAAQ,IAAI,UAAU;CAAC;CAA2C;CAAqD;CAAoD;AAAuE,CAAC;AACzP,IAAM,QAAQ,GAAW,MAAc,EAAE,YAAY,MAAM,EAAE,YAAY;AACzE,IAAM,gBAAgB;;AAEtB,IAAM,gCAAgB,IAAI,IAAI;CAAC;CAAe;CAAe;CAAY;CAAkB;CAAmB;CAAe;CAA2B;CAAmB;CAAwB;CAA4B;CAAgB;CAAkB;CAA4B;AAA2B,CAAC;AACzT,IAAM,iBAAiB;;AAEvB,IAAM,wBAAQ,IAAI,QAAgB;AAClC,IAAM,YAAY,UAAmB,iBAAiB,UAAU,MAAM,SAAS,gBAAgB,MAAM,SAAS;;;;;;;AAQ9G,SAAgB,aAAa,QAA0D;CACrF,OAAO,OAAO,YAAY,cAAc,IAAI,IAAI,OAAO,QAAQ,CAAC,CAAC,SAAS,gBAAgB,OAAO;AACnG;;AAGA,IAAa,cAAb,MAAa,YAAoD;CAOlC;CAN7B,SAAkB;CAClB;CACA;CACA,WAAmB;CACnB,SAAiB;CACjB,QAAkC,QAAQ,QAAQ;CAClD,YAAoB,QAA6B;EAAp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,SAAQ;EAAI;EAC/G,IAAI,OAAO,QAAQ,MAAM,MAAI,IAAI,OAAO;GAAC,MAAK;GAAK,SAAQ;GAAM,QAAO;GAAK,OAAM;EAA4D;EAK/I,IAAI,CAJa,QAAQ,KAAK,MAAK,QAAK;GACtC,IAAI,CAAC,KAAK,IAAI,SAAQ,KAAK,OAAO,KAAK,GAAG,OAAO;GACjD,IAAI;IAAC,MAAM,QAAM,MAAM,SAAS,GAAG;IAAE,OAAO,OAAO,SAAO,cAAc,KAAK,MAAM,KAAK,IAAG,GAAG,IAAI,KAAK,KAAK,MAAM,KAAK,IAAG,OAAO,OAAO,KAAK,MAAM,KAAK,OAAK,OAAO,OAAO,MAAM;GAAE,QAAQ;IAAC,OAAO;GAAM;EAC3M,CACK,GAAU,MAAM,IAAI,MAAM,wCAAwC;EACvE,OAAO;GAAC,MAAK;GAAK,SAAQ;EAAI;CAChC;CACA,MAAM,UAAU;EAAE,MAAM,KAAK,MAAM,YAAU,CAAC,CAAC;EAAG,KAAK,UAAQ,KAAA;EAAU,KAAK,SAAS,QAAQ;EAAE,KAAK,UAAQ,KAAA;EAAU,KAAK,WAAS;CAAI;CAC1I,OAAkB,MAAgC;EAAE,MAAM,YAAU,KAAK,MAAM,KAAK,MAAK,IAAI;EAAE,KAAK,QAAM,UAAU,YAAU,CAAC,CAAC;EAAE,OAAO;CAAW;AACtJ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as findGroup, h as node, i as chatOrGroup, y as state } from "./apiKit-
|
|
1
|
+
import { c as findGroup, h as node, i as chatOrGroup, y as state } from "./apiKit-BtsHrnoo.js";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
//#region src/engineMethods.ts
|
|
4
4
|
/**
|
|
@@ -180,7 +180,7 @@ var ENGINE_PARAMS = {
|
|
|
180
180
|
groupTaken: "{ groupId, messageId, edit? }",
|
|
181
181
|
chatUnconfirmed: "{ linkId }",
|
|
182
182
|
groupMessages: "{ groupId }",
|
|
183
|
-
messagePage: "{ linkId, limit?, before? }",
|
|
183
|
+
messagePage: "{ linkId, limit?, before?, after? }",
|
|
184
184
|
chatsFound: "{ query, linkIds }",
|
|
185
185
|
statusCardIndex: "",
|
|
186
186
|
saveMessage: "{ linkId, messageId, remove? }",
|
|
@@ -414,4 +414,4 @@ var TRANSPORT_NAMES = {
|
|
|
414
414
|
//#endregion
|
|
415
415
|
export { WALLET_TYPES as a, DESTRUCTIVE_CALLS as c, ENGINE_READS as d, READ_PARAMS as f, TRANSPORT_NAMES as i, ENGINE_METHODS as l, engineParamsProblem as m, CHAT_METHODS as n, turnRef as o, SECRET_RESULTS as p, PAY_METHODS as r, withStoredIds as s, ADDRESS_TYPES as t, ENGINE_PARAMS as u };
|
|
416
416
|
|
|
417
|
-
//# sourceMappingURL=words-
|
|
417
|
+
//# sourceMappingURL=words-BaumxjXe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"words-BaumxjXe.js","names":[],"sources":["../../src/engineMethods.ts","../../src/turnRefs.ts","../../src/words.ts"],"sourcesContent":["/**\n * What each call of the app's `EngineApi` (packages/browser/src/shared/rpc.ts) takes, as `engine --list --verbose`\n * shows it: `{ linkId, label }` an object with these keys (`?` an optional one), a type's name for an object of that\n * type, \"\" nothing; a trailing `?` when the object may be left out. `engineMethods.test.ts` reads it out of rpc.ts and\n * keeps the two equal. The device calls (WISP 06): a CLI profile is always on one device, so they answer `single` or refuse.\n */\nexport const ENGINE_PARAMS: Readonly<Record<string, string>> = {\n usdtCreate: \"UsdtCreate\",\n usdtUnlock: \"{ password, network? }\",\n usdtReveal: \"{ password?, network? }\",\n usdtLock: \"{ network? }?\",\n usdtRefresh: \"{ network? }?\",\n usdtExportBackup: \"{ password, network? }\",\n usdtRestoreBackup: \"{ text, password, network? }\",\n arkCreate: \"ArkCreate\",\n arkUnlock: \"{ password, network? }\",\n arkLock: \"{ network? }?\",\n arkBackup: \"{ password?, network? }\",\n arkExportBackup: \"{ password, network? }\",\n arkRestoreBackup: \"{ text, password, network? }\",\n arkRefresh: \"{ network? }?\",\n arkRecover: \"{ network? }?\",\n barkCreate: \"BarkCreate\",\n barkBackup: \"{ network? }?\",\n barkExportBackup: \"{ password, network? }\",\n barkRestoreBackup: \"{ text, password, network? }\",\n barkRefresh: \"{ network? }?\",\n barkBoard: \"{ network? }?\",\n fedimintPreview: \"{ invite, network? }\",\n fedimintJoin: \"{ invite, recover?, network? }\",\n fedimintLeave: \"{ federation }\",\n fedimintRefresh: \"{ network? }?\",\n fedimintSpendNotes: \"{ federation, amount, confirmedReal? }\",\n fedimintReceiveNotes: \"{ notes, network? }\",\n fedimintInvoice: \"{ federation, amount, memo? }\",\n fedimintTakeBack: \"{ federation, operation }\",\n fedimintBackup: \"{ network? }?\",\n fedimintExportBackup: \"{ password, network? }\",\n fedimintRestoreBackup: \"{ text, password, network? }\",\n fedimintRestorePhrase: \"{ mnemonic, invites, network? }\",\n sparkCreate: \"SparkCreate\",\n sparkBackup: \"{ network? }?\",\n sparkExportBackup: \"{ password, network? }\",\n sparkRestoreBackup: \"{ text, password, apiKey?, network? }\",\n sparkRefresh: \"{ network? }?\",\n sparkUseForLightning: \"{ network? }?\",\n preparePayment: \"{ target, amount, feeCap, payee, linkId?, requestId?, memo?, network? }\",\n approvePayment: \"{ id, confirmedReal? }\",\n reconcilePayment: \"{ id }\",\n cancelPayment: \"{ id }\",\n refreshPublicProfiles: \"{ linkId, force? }\",\n choosePublicProfile: \"{ linkId, choice }\",\n preparePeerProof: \"{ linkId, externalKey, adapter? }\",\n submitPeerProof: \"{ linkId, challenge, event }\",\n withdrawPeerProof: \"{ linkId, adapter? }\",\n beginIdentityProof: \"{ provider, subject, validityDays? }\",\n completeIdentityProof: \"{ draftId, evidence }\",\n cancelIdentityProof: \"{ draftId }\",\n removeIdentityProof: \"{ id }\",\n shareIdentityProof: \"{ linkId, id }\",\n withdrawIdentityProof: \"{ linkId, id }\",\n recheckIdentityProof: \"{ linkId, id }\",\n lookupIdentityDisplay: \"{ linkId, id }\",\n loadPublicProfile: \"{ provider, subject, force? }\",\n loadPublicPosts: \"{ provider, subject, more?, force? }\",\n loadPublicGraph: \"{ provider, subject, force? }\",\n loadPublicPostImage: \"{ provider, subject, postId, index }\",\n clearProfileData: \"\",\n setDidListed: \"{ id, listed }\",\n nostrLoadContact: \"{ linkId, subject, what, more? }\",\n nostrForgetContact: \"{ linkId, subject }\",\n nostrLoadOwn: \"{ subject }\",\n nostrLookup: \"NostrLookupRequest\",\n nostrDraft: \"NostrDraftRequest\",\n nostrPublish: \"{ draftId, event }\",\n createLink: \"\",\n takeInvite: \"\",\n joinLink: \"{ inviteCode }\",\n ensureLink: \"LinkParams & { inviteCode?: string }\",\n confirmPair: \"{ linkId, code }\",\n pollNow: \"{ linkId }\",\n removeLink: \"{ linkId }\",\n renameLink: \"{ linkId, label }\",\n setActiveLink: \"{ linkId }\",\n sendMessage: \"{ linkId, text, timestamp?, preview?, replyTo?, card? }\",\n editMessage: \"{ linkId, messageId, text, preview?, mentions?, card? }\",\n retryMessage: \"{ linkId, messageId }\",\n react: \"{ linkId, messageId, emoji }\",\n pinMessage: \"{ linkId, messageId?, remove? }\",\n appId: \"{ linkId, ref }\",\n appOpen: \"{ linkId, ref, version, digest? }\",\n appClose: \"{ linkId, ref }\",\n appSend: \"{ linkId, ref, data, digest? }\",\n appServe: \"{ linkId, ref, file, digest? }\",\n appUnserve: \"{ linkId, serve }\",\n appRangeAnswer: \"{ linkId, app, request, bytes?, size?, error? }\",\n appRemoteRead: \"{ linkId, ref, serve, offset, length, digest? }\",\n messageDetails: \"{ linkId, messageId }\",\n deleteMessage: \"{ linkId, messageId }\",\n removeMessage: \"{ linkId, messageId }\",\n exportLinks: \"\",\n sendFile: \"{ linkId, file, timestamp, replyTo?, forwarded? }\",\n sendGroupFile: \"{ groupId, file, caption?, replyTo?, forwarded? }\",\n groupFileCheck: \"{ groupId }\",\n forwardMessages: \"{ linkId, messageIds, to }\",\n fileAction: \"{ linkId, fileId, action }\",\n setDeliveryMode: \"{ linkId, mode }\",\n setTransportPreference: \"{ linkId, preferred, fallback }\",\n setChatTransport: \"{ linkId, transport }\",\n setChatPaymentMethods: \"{ linkId, methods, networks? }\",\n setChatHold: \"{ linkId, enabled }\",\n connect: \"{ linkId }\",\n walletAddMint: \"{ url, primary?, network? }\",\n walletCreate: \"WalletCreate\",\n walletRemove: \"WalletRemove\",\n walletTestCoins: \"WalletTestCoins\",\n walletSetupRetry: \"{ type }\",\n walletSetupDismiss: \"{ type }\",\n wake: \"{ network? }?\",\n peekProfile: \"{ profile, dbName }\",\n walletSetPrimaryMint: \"{ url }\",\n walletRemoveMint: \"{ url, acceptLoss? }\",\n walletReceiveLightning: \"{ amount, via?, network?, card? }\",\n walletQuoteInvoice: \"{ invoice, via?, network?, card? }\",\n walletPayQuote: \"{ quote, mint, note?, confirmedReal?, linkId?, invoice? }\",\n lnurlResolve: \"{ text, network? }\",\n lnurlInvoice: \"{ id, amount, comment?, network? }\",\n checkPayment: \"{ linkId, paymentId }\",\n lightningSetSource: \"{ providerId, values, network?, card? }\",\n lightningClearSource: \"{ network?, card? }?\",\n lightningRetrySource: \"{ network?, card? }?\",\n lightningReconfigureSource: \"{ values, network?, card? }\",\n lightningRefresh: \"{ network?, card? }?\",\n lightningSetReceive: \"{ network, card }\",\n lightningRename: \"{ network, card, name }\",\n bitcoinSetSource: \"{ providerId, values, network? }\",\n bitcoinClearSource: \"{ network? }?\",\n bitcoinRetrySource: \"{ network? }?\",\n bitcoinReconfigureSource: \"{ values, network? }\",\n bitcoinReceiveAddress: \"{ network? }?\",\n bitcoinRefresh: \"{ network? }?\",\n walletReceiveToken: \"{ token }\",\n walletInspectCashu: \"{ text }\",\n walletExport: \"{ network? }?\",\n walletBackupReminder: \"{ event: \\\"later\\\"; wallet: string } | { event: \\\"profile\\\" }\",\n sendPayment: \"{ linkId, amount, memo?, timestamp, network?, confirmedReal? }\",\n requestPayment: \"{ linkId, amount, memo?, timestamp, method?, rail?, network?, card? }\",\n requestGroupPayment: \"{ groupId, amount, memo?, timestamp, rail, network?, card? }\",\n groupPaymentHello: \"{ groupId, member }\",\n askToPay: \"{ linkId, amount, method, memo?, timestamp, network? }\",\n payRequest: \"{ linkId, paymentId, via?, maxFee?, network?, confirmedReal?, card? }\",\n reclaimPayment: \"{ paymentId }\",\n disconnect: \"{ linkId }\",\n addService: \"{ name, target }\",\n removeService: \"{ serviceId }\",\n setServiceEnabled: \"{ serviceId, enabled }\",\n setServiceShared: \"{ serviceId, peerPubKeyZ32, shared }\",\n updateSettings: \"{ settings }\",\n setCallSignal: \"{ linkId, signal }\",\n setTyping: \"{ linkId, typing, kind?, status? }\",\n setGroupTyping: \"{ groupId, typing, kind?, status? }\",\n setWakeSubscription: \"{ subscription }\",\n wakeConfirm: \"{ endpoint }\",\n setWakeMuted: \"{ linkId, muted }\",\n wakeForCall: \"{ linkId }\",\n setCallOn: \"{ on }\",\n setFastPoll: \"{ linkId, fast }\",\n createGroup: \"{ name, profile? }\",\n inviteToGroup: \"{ groupId, linkId }\",\n acceptGroupInvitation: \"{ groupId }\",\n declineGroupInvitation: \"{ groupId }\",\n enableGroupLink: \"{ groupId, reset? }\",\n disableGroupLink: \"{ groupId }\",\n joinGroupByLink: \"{ link }\",\n sendGroupMessage: \"{ groupId, text, mentions?, replyTo?, card? }\",\n pressButton: \"{ linkId, messageId, buttonId }\",\n groupTaken: \"{ groupId, messageId, edit? }\",\n chatUnconfirmed: \"{ linkId }\",\n groupMessages: \"{ groupId }\",\n messagePage: \"{ linkId, limit?, before?, after? }\",\n chatsFound: \"{ query, linkIds }\",\n statusCardIndex: \"\",\n saveMessage: \"{ linkId, messageId, remove? }\",\n savedMessages: \"\",\n leaveGroup: \"{ groupId }\",\n removeGroupMember: \"{ groupId, key }\",\n makeGroupAdmin: \"{ groupId, key }\",\n setGroupHub: \"{ groupId, key, role }\",\n rotateGroup: \"{ groupId }\",\n setGroupPicture: \"{ groupId, picture }\",\n renameGroup: \"{ groupId, name }\",\n forgetGroup: \"{ groupId }\",\n setGroupManage: \"{ groupId, on }\",\n deviceEnrollInvite: \"{ name }\",\n deviceEnrollConfirm: \"{ match }\",\n deviceEnrollCancel: \"\",\n deviceEnrollView: \"\",\n deviceEnrollJoin: \"{ code, name, kind?, app? }\",\n deviceEnrollReady: \"\",\n deviceEnrollFinish: \"\",\n deviceEnrollRemove: \"\",\n deviceSet: \"\",\n devicePing: \"{ key }\",\n devicePushState: \"\",\n devicePushSet: \"{ subscription }\",\n deviceHandoffVerifier: \"{ password, current? }\",\n deviceHandoffPush: \"{ key }\",\n deviceHandoffPull: \"{ password, later? }\",\n deviceHandoffAccept: \"{ later? }\",\n deviceHandoffSettle: \"\",\n deviceHandoffCancel: \"\",\n deviceHandoffView: \"\",\n deviceHandoffAllow: \"{ key }\",\n deviceTakeoverInfo: \"\",\n deviceTakeover: \"{ password, name, lost? }\",\n deviceTurnPeek: \"{ d }\",\n deviceForkDiscard: \"{ database }\",\n deviceRestoreStartOwn: \"\",\n deviceRemove: \"{ key }\",\n deviceNewSecret: \"\",\n deviceSecretOfferDismiss: \"\",\n deviceTurnCheck: \"\",\n deviceSetNoticeSeen: \"{ wrong? }\",\n appList: \"\",\n appBuiltIns: \"\",\n appStoreList: \"\",\n appStorePreview: \"{ url }\",\n appStoreAdd: \"{ url, key? }\",\n appStoreRemove: \"{ key }\",\n appStoreRefresh: \"{ key? }?\",\n appPreview: \"AppSource\",\n appInstall: \"{ digest, grant }\",\n appUpdateAccept: \"{ ref }\",\n appCheckUpdates: \"\",\n appUninstall: \"{ ref }\",\n appRunCheck: \"{ ref }\",\n appFetchFiles: \"{ ref }\",\n appEntry: \"{ ref, runAnyway? }\",\n appFile: \"{ ref, path, digest? }\",\n appFileAt: \"{ ref, path, digest? }\",\n appStorageGet: \"{ ref, scope, key, digest? }\",\n appStorageSet: \"{ ref, scope, key, value, digest? }\",\n appStorageDelete: \"{ ref, scope, key, digest? }\",\n appStorageKeys: \"{ ref, scope, digest? }\",\n appDataExport: \"{ ref }\",\n appDataExportText: \"{ ref }\",\n};\n\n/**\n * The engine's calls the daemon passes through as `engine.<method>` (WISP 1100 § Local control API): exactly the\n * app's `EngineApi`, plus two reads every host has. Nothing else on the engine object is reachable.\n */\nexport const ENGINE_METHODS: readonly string[] = Object.keys(ENGINE_PARAMS);\n\n/** Reads the hosts use outside `EngineApi`: the whole state, and one chat's stored messages. */\nexport const ENGINE_READS: readonly string[] = [\"getState\", \"getMessages\"];\n\n/** What the two reads take, in `ENGINE_PARAMS`' words. */\nexport const READ_PARAMS: Readonly<Record<string, string>> = { getState: \"\", getMessages: \"{ linkId }\" };\n\n/**\n * Why `params` is not what `method` takes: missing when it takes some, or a key it needs not there (a key holding\n * null is there: `setActiveLink { linkId: null }`). Undefined when it is, or when the shape names a type, which is not\n * looked into here.\n */\nexport function engineParamsProblem(method: string, params: Record<string, unknown> | undefined): string | undefined {\n const takes = ENGINE_PARAMS[method] ?? READ_PARAMS[method];\n if (!takes) return undefined;\n if (params === undefined) return takes.endsWith(\"?\") ? undefined : \"no parameters given\";\n const keys = /^\\{ ([\\w?, ]*) \\}\\??$/.exec(takes)?.[1].split(\", \") ?? [];\n const missing = keys.filter((key) => !key.endsWith(\"?\") && params[key] === undefined);\n return missing.length ? `${missing.join(\", \")} missing` : undefined;\n}\n\n/**\n * Calls that delete what this device holds, by what they delete: they go only with `--yes` (`yes: true` over the\n * socket), as `chat remove`, `group leave` and `group forget` ask for it.\n */\nexport const DESTRUCTIVE_CALLS: ReadonlyMap<string, string> = new Map([\n [\"clearProfileData\", \"deletes every chat and group on this device (the wallets stay)\"],\n [\"removeLink\", \"deletes a chat's keys and history on this device\"],\n [\"leaveGroup\", \"deletes a group's history and files on this device\"],\n [\"forgetGroup\", \"deletes a group's history on this device\"],\n [\"deviceRemove\", \"takes a device off this profile\"],\n]);\n\n/**\n * Calls whose answer holds a secret (chat seeds, wallet phrases and keys, ecash, backups): the CLI prints their\n * result only with `--show-secret`.\n */\nexport const SECRET_RESULTS: ReadonlySet<string> = new Set([\n \"exportLinks\", \"takeInvite\", \"walletExport\", \"usdtReveal\",\n \"arkBackup\", \"barkBackup\", \"sparkBackup\", \"fedimintBackup\",\n \"usdtExportBackup\", \"arkExportBackup\", \"barkExportBackup\", \"sparkExportBackup\", \"fedimintExportBackup\",\n \"fedimintSpendNotes\",\n]);\n","import { createHash } from \"node:crypto\";\nimport { chatOrGroup, findGroup, node, state, type ApiContext, type Params } from \"./apiKit\";\n\n/**\n * The id an agent turn names its message by (docs/CLI.md § Agent turns). A message is stored under an id its sender\n * chose most of (`peer_<the id they sent>`), so a turn carries this one instead, made here from the chat (or group) and\n * that id: `t_` and 32 hex digits, in which nobody can write a word. Every command that takes a message's id takes it.\n */\nexport function turnRef(where: string, messageId: string): string {\n return \"t_\" + createHash(\"sha256\").update(`${where}\\n${messageId}`).digest(\"hex\").slice(0, 32);\n}\n\nconst TURN_REF = /^t_[0-9a-f]{32}$/;\nconst isRef = (value: unknown): value is string => typeof value === \"string\" && TURN_REF.test(value);\n\n/**\n * `params` with each turn's id in `message`, `reply` and `messages` as the id its message is stored under: looked for\n * among the chat's (or group's) newest messages first, where a turn's almost always is, then in all of them. One that\n * names no message stays as given, and its command says so as for any unknown id.\n */\nexport async function withStoredIds(ctx: ApiContext, params: Params): Promise<Params> {\n const wanted = new Set([params.message, params.reply, ...(Array.isArray(params.messages) ? params.messages : [])].filter(isRef));\n if (!wanted.size) return params;\n let target: { id: string; linkId: string; group: boolean } | null = null;\n try {\n if (typeof params.group === \"string\") { const group = findGroup(state(ctx).groups, params.group); target = { id: group.id, linkId: `group:${group.id}`, group: true }; }\n else if (typeof params.chat === \"string\") target = chatOrGroup(ctx, params.chat);\n } catch { /* the command says what is wrong with its chat or group */ }\n if (!target) return params;\n const { id, linkId, group } = target;\n const found = new Map<string, string>();\n const look = (messages: readonly { id: string }[]) => {\n for (const message of messages) { const ref = turnRef(id, message.id); if (wanted.has(ref)) found.set(ref, message.id); }\n return found.size === wanted.size;\n };\n if (!look((await node(ctx).messagePage({ linkId, limit: 200 })).messages)) look(group ? await node(ctx).groupMessages({ groupId: id }) : await node(ctx).getMessages(linkId));\n const stored = (value: unknown) => (isRef(value) ? found.get(value) ?? value : value);\n return {\n ...params,\n ...(params.message !== undefined && { message: stored(params.message) }),\n ...(params.reply !== undefined && { reply: stored(params.reply) }),\n ...(Array.isArray(params.messages) && { messages: params.messages.map(stored) }),\n };\n}\n","import type { PairedTransport } from \"@ghostly/core\";\n\n/**\n * The words an argument takes, for the API's methods and the command table both: the command line refuses any other\n * before the profile opens (`commands/index.ts` positionals), and the socket keeps its own refusal for its callers.\n * Its own module, with no code from the package: the command table is read by every command.\n */\n\nexport const WALLET_TYPES = [\"cashu\", \"lightning\", \"arkade\", \"bark\", \"spark\", \"bitcoin\", \"fedimint\", \"usdt\"] as const;\n/** The wallets that have an address to be paid on (`wallet address`). */\nexport const ADDRESS_TYPES = [\"bitcoin\", \"arkade\", \"spark\", \"usdt\"] as const;\n/** What a payment request may name as its way of paying (`chat request --method`). */\nexport const PAY_METHODS = [\"cashu\", \"arkade\", \"usdt\", \"bark\", \"bitcoin\", \"fedimint\", \"spark\"] as const;\n/** The ways of paying a chat takes (`chat accept`). */\nexport const CHAT_METHODS = [\"cashu\", \"lightning\", ...PAY_METHODS.filter((m) => m !== \"cashu\")] as const;\n\n/** A chat's transport by the name the command line gives it (`chat transport`). */\nexport const TRANSPORT_NAMES: Record<string, PairedTransport | \"auto\" | \"dht\"> = {\n auto: \"auto\", dht: \"dht\", webrtc: \"webrtc/1\", iroh: \"iroh/1\", hyperdht: \"hyperdht/1\",\n \"webrtc/1\": \"webrtc/1\", \"iroh/1\": \"iroh/1\", \"hyperdht/1\": \"hyperdht/1\",\n};\n"],"mappings":";;;;;;;;;AAMA,IAAa,gBAAkD;CAC7D,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,aAAa;CACb,kBAAkB;CAClB,mBAAmB;CACnB,WAA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ache();
|
|
27
|
-
var { run } = await import("./assets/main-
|
|
27
|
+
var { run } = await import("./assets/main-BX4oPWCJ.js");
|
|
28
28
|
run(process.argv.slice(2));
|
|
29
29
|
//#endregion
|
|
30
30
|
export {};
|
package/package.json
CHANGED