From 57eef234b13d13f59a707a0525454bd1c36d1e52 Mon Sep 17 00:00:00 2001 From: xmanrui <841206367@qq.com> Date: Fri, 28 Aug 2026 15:32:09 +0800 Subject: [PATCH] feat(ui): add manual update commands and simplify update dialog --- CHANGELOG.md | 5 + README.en.md | 2 + README.md | 2 + lib/client.js | 689 ++++++++++++++++++++++++++++- lib/index.js | 6 +- plugin-src/client/i18n.js | 17 +- plugin-src/client/styles.js | 11 + plugin-src/client/update-panel.js | 115 ++++- plugin-src/host/update-runtime.mjs | 5 +- plugin-src/host/update-service.mjs | 2 + test/update-runtime.test.mjs | 8 +- test/update-service.test.mjs | 12 + test/update-ui.test.mjs | 217 ++++++++- 13 files changed, 1050 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30d451a..f14a59c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ This file records the notable changes in each dsh-im release. Its format follows ## [Unreleased] +### Added / 新增 + +- 更新窗口新增手工更新命令及一键复制,页面更新失败时可在相同 Harness / Desktop 环境中通过 npm 更新;复制受限时可选中文本手动复制,安装完成后仍需手动重启。 + Added a manual npm update command and copy button to the update dialog for use in the same Harness / Desktop environment when the in-page update fails. The command remains selectable if clipboard access fails, and installation still requires a manual restart. + ## [3.1.1] - 2026-08-28 ### Fixed / 修复 diff --git a/README.en.md b/README.en.md index 5db660c..b11c109 100644 --- a/README.en.md +++ b/README.en.md @@ -147,6 +147,8 @@ The button reuses Desktop's package-management service or the current Harness CL dsh plugin --profile web add -w --save-exact @xmanrui/dsh-im@3.1.0 --registry=https://registry.npmjs.org/ ``` +The **Manual update** section at the bottom of the dialog generates a short command for the current profile, such as `dsh plugin --profile web add -w @xmanrui/dsh-im@3.1.1`. Click the copy icon at the far right of the command, then run it in a terminal. It requests a known target version; otherwise, `@latest` resolves the version from npm when executed. The manual command uses your local npm registry configuration without fetching GitHub; the install button still forces the official registry and saves an exact version. If clipboard access fails, select and copy the command manually. For Desktop, use the current Desktop's built-in terminal. For Web, use the environment that started the current Harness and preserve the same `DSH_HOME`. If a restart is already pending, restarting is usually enough without another installation. No potentially destructive command is generated for source links or profiles that cannot be safely identified. + Source `link:`, `file:`, Git, and unrecognized installations can check versions but are never replaced automatically. Confirm the intended profile before manually migrating to npm. Conflicting scoped registries, incompatible Node versions, and unavailable Host executors disable installation with an explanation. Standard Windows CLI installations currently require a manual update; Desktop uses its existing executor. Do not modify the same profile through a terminal or plugin market during installation. A failed command may leave partial dependency changes; it is not an automatic rollback. Inspect the installation, reinstall the previous exact version if needed, and restart manually. The updater keeps only the profile's latest job and manifest backup under the current `DSH_HOME/updates/dsh-im`, without copying bot credentials. Resolve uncertain remaining installers or locks before retrying; do not blindly delete a lock. diff --git a/README.md b/README.md index dd4dff4..d400f27 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,8 @@ dsh web dsh plugin --profile web add -w --save-exact @xmanrui/dsh-im@3.1.0 --registry=https://registry.npmjs.org/ ``` +更新窗口下方的「手工更新」会按当前 profile 生成精简命令,例如 `dsh plugin --profile web add -w @xmanrui/dsh-im@3.1.1`,点击命令最右侧的复制图标后可在终端执行。已知目标版本时指定该版本;尚未查到版本时使用 `@latest`,以执行时 npm 返回的版本为准。手工命令沿用本机 npm 源配置,不拉取 GitHub;按钮安装仍固定使用官方源并保存精确版本。浏览器无法复制时可选中文本手动复制。Desktop 请使用当前 Desktop 的内置终端;Web 请使用启动当前 Harness 的环境并保持相同 `DSH_HOME`。如果已经提示「待手动重启」,通常只需重启,无需再次安装。源码链接或无法安全确认的 profile 不生成可能覆盖安装的命令。 + 源码 `link:`、`file:`、Git 来源或无法确认归属的安装只提供版本检查,不会替换开发链接;如需迁移为 npm 安装,请自行确认对应 profile。作用域 registry 冲突、Node 版本不满足要求或缺少当前 Host 的执行器时,按钮会说明原因。标准 Windows CLI 暂需手动更新;Desktop 使用其原有执行器。 安装期间不要同时在终端或插件市场修改该 profile。失败可能已经改变部分依赖,不能视为自动回滚;先检查安装状态,必要时按上述命令重装原精确版本,再手动重启。更新器只在当前 `DSH_HOME/updates/dsh-im` 下保存该 profile 最近一次任务与清单备份,不复制机器人凭据;残留安装进程或锁状态不明确时,请先人工确认,不要盲目重试或删除锁。 diff --git a/lib/client.js b/lib/client.js index 7a46e9e..423c6b2 100644 --- a/lib/client.js +++ b/lib/client.js @@ -9,6 +9,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; var __export = (target, all) => { for (var name2 in all) __defProp(target, name2, { get: all[name2], enumerable: true }); @@ -31,6 +34,527 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +// node_modules/semver/internal/debug.js +var require_debug = __commonJS({ + "node_modules/semver/internal/debug.js"(exports, module2) { + "use strict"; + var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { + }; + module2.exports = debug; + } +}); + +// node_modules/semver/internal/constants.js +var require_constants = __commonJS({ + "node_modules/semver/internal/constants.js"(exports, module2) { + "use strict"; + var SEMVER_SPEC_VERSION = "2.0.0"; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ + 9007199254740991; + var MAX_SAFE_COMPONENT_LENGTH = 16; + var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; + var RELEASE_TYPES = [ + "major", + "premajor", + "minor", + "preminor", + "patch", + "prepatch", + "prerelease" + ]; + module2.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 1, + FLAG_LOOSE: 2 + }; + } +}); + +// node_modules/semver/internal/re.js +var require_re = __commonJS({ + "node_modules/semver/internal/re.js"(exports, module2) { + "use strict"; + var { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH + } = require_constants(); + var debug = require_debug(); + exports = module2.exports = {}; + var re = exports.re = []; + var safeRe = exports.safeRe = []; + var src = exports.src = []; + var safeSrc = exports.safeSrc = []; + var t = exports.t = {}; + var R = 0; + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var safeRegexReplacements = [ + ["\\s", 1], + ["\\d", MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] + ]; + var makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); + } + return value; + }; + var createToken = (name2, value, isGlobal) => { + const safe = makeSafeRegex(value); + const index = R++; + debug(name2, index, value); + t[name2] = index; + src[index] = value; + safeSrc[index] = safe; + re[index] = new RegExp(value, isGlobal ? "g" : void 0); + safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0); + }; + createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); + createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); + createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); + createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); + createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`); + createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); + createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken("FULL", `^${src[t.FULLPLAIN]}$`); + createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); + createToken("GTLT", "((?:<|>)?=?)"); + createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); + createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`); + createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`); + createToken("COERCERTL", src[t.COERCE], true); + createToken("COERCERTLFULL", src[t.COERCEFULL], true); + createToken("LONETILDE", "(?:~>?)"); + createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = "$1~"; + createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("LONECARET", "(?:\\^)"); + createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = "$1^"; + createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = "$1$2$3"; + createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); + createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); + createToken("STAR", "(<|>)?=?\\s*\\*"); + createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); + createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); + } +}); + +// node_modules/semver/internal/parse-options.js +var require_parse_options = __commonJS({ + "node_modules/semver/internal/parse-options.js"(exports, module2) { + "use strict"; + var looseOption = Object.freeze({ loose: true }); + var emptyOpts = Object.freeze({}); + var parseOptions = (options) => { + if (!options) { + return emptyOpts; + } + if (typeof options !== "object") { + return looseOption; + } + return options; + }; + module2.exports = parseOptions; + } +}); + +// node_modules/semver/internal/identifiers.js +var require_identifiers = __commonJS({ + "node_modules/semver/internal/identifiers.js"(exports, module2) { + "use strict"; + var numeric = /^[0-9]+$/; + var compareIdentifiers = (a, b) => { + if (typeof a === "number" && typeof b === "number") { + return a === b ? 0 : a < b ? -1 : 1; + } + const anum = numeric.test(a); + const bnum = numeric.test(b); + if (anum && bnum) { + a = +a; + b = +b; + } + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + }; + var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); + module2.exports = { + compareIdentifiers, + rcompareIdentifiers + }; + } +}); + +// node_modules/semver/classes/semver.js +var require_semver = __commonJS({ + "node_modules/semver/classes/semver.js"(exports, module2) { + "use strict"; + var debug = require_debug(); + var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); + var { safeRe: re, t } = require_re(); + var parseOptions = require_parse_options(); + var { compareIdentifiers } = require_identifiers(); + var isPrereleaseIdentifier = (prerelease, identifier) => { + const identifiers = identifier.split("."); + if (identifiers.length > prerelease.length) { + return false; + } + for (let i = 0; i < identifiers.length; i++) { + if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) { + return false; + } + } + return true; + }; + var SemVer = class _SemVer { + constructor(version, options) { + options = parseOptions(options); + if (version instanceof _SemVer) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== "string") { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`); + } + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ); + } + debug("SemVer", version, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); + if (!m) { + throw new TypeError(`Invalid Version: ${version}`); + } + this.raw = version; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map((id5) => { + if (/^[0-9]+$/.test(id5)) { + const num = +id5; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id5; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join(".")}`; + } + return this.version; + } + toString() { + return this.version; + } + compare(other) { + debug("SemVer.compare", this.version, this.options, other); + if (!(other instanceof _SemVer)) { + if (typeof other === "string" && other === this.version) { + return 0; + } + other = new _SemVer(other, this.options); + } + if (other.version === this.version) { + return 0; + } + return this.compareMain(other) || this.comparePre(other); + } + compareMain(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.major < other.major) { + return -1; + } + if (this.major > other.major) { + return 1; + } + if (this.minor < other.minor) { + return -1; + } + if (this.minor > other.minor) { + return 1; + } + if (this.patch < other.patch) { + return -1; + } + if (this.patch > other.patch) { + return 1; + } + return 0; + } + comparePre(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug("prerelease compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + compareBuild(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug("build compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc(release, identifier, identifierBase) { + if (release.startsWith("pre")) { + if (!identifier && identifierBase === false) { + throw new Error("invalid increment argument: identifier is empty"); + } + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]); + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`); + } + } + } + switch (release) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier, identifierBase); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier, identifierBase); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier, identifierBase); + this.inc("pre", identifier, identifierBase); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier, identifierBase); + } + this.inc("pre", identifier, identifierBase); + break; + case "release": + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`); + } + this.prerelease.length = 0; + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case "pre": { + const base = Number(identifierBase) ? 1 : 0; + if (this.prerelease.length === 0) { + this.prerelease = [base]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === "number") { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + if (identifier === this.prerelease.join(".") && identifierBase === false) { + throw new Error("invalid increment argument: identifier already exists"); + } + this.prerelease.push(base); + } + } + if (identifier) { + let prerelease = [identifier, base]; + if (identifierBase === false) { + prerelease = [identifier]; + } + if (isPrereleaseIdentifier(this.prerelease, identifier)) { + const prereleaseBase = this.prerelease[identifier.split(".").length]; + if (isNaN(prereleaseBase)) { + this.prerelease = prerelease; + } + } else { + this.prerelease = prerelease; + } + } + break; + } + default: + throw new Error(`invalid increment argument: ${release}`); + } + this.raw = this.format(); + if (this.build.length) { + this.raw += `+${this.build.join(".")}`; + } + return this; + } + }; + module2.exports = SemVer; + } +}); + +// node_modules/semver/functions/parse.js +var require_parse = __commonJS({ + "node_modules/semver/functions/parse.js"(exports, module2) { + "use strict"; + var SemVer = require_semver(); + var parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version; + } + try { + return new SemVer(version, options); + } catch (er) { + if (!throwErrors) { + return null; + } + throw er; + } + }; + module2.exports = parse; + } +}); + +// node_modules/semver/functions/valid.js +var require_valid = __commonJS({ + "node_modules/semver/functions/valid.js"(exports, module2) { + "use strict"; + var parse = require_parse(); + var valid = (version, options) => { + const v = parse(version, options); + return v ? v.version : null; + }; + module2.exports = valid; + } +}); + +// node_modules/semver/functions/compare.js +var require_compare = __commonJS({ + "node_modules/semver/functions/compare.js"(exports, module2) { + "use strict"; + var SemVer = require_semver(); + var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)); + module2.exports = compare; + } +}); + +// node_modules/semver/functions/rcompare.js +var require_rcompare = __commonJS({ + "node_modules/semver/functions/rcompare.js"(exports, module2) { + "use strict"; + var compare = require_compare(); + var rcompare = (a, b, loose) => compare(b, a, loose); + module2.exports = rcompare; + } +}); + // plugin-src/client/index.js var index_exports = {}; __export(index_exports, { @@ -315,17 +839,28 @@ var EN = Object.freeze({ "\u68C0\u67E5\u66F4\u65B0": "Check for updates", "\u91CD\u65B0\u68C0\u67E5": "Check again", "\u5237\u65B0\u72B6\u6001": "Refresh status", + "\u624B\u5DE5\u66F4\u65B0": "Manual update", + "\u624B\u5DE5\u66F4\u65B0\u547D\u4EE4": "Manual update command", + "\u590D\u5236\u547D\u4EE4": "Copy command", + "\u590D\u5236\u4E2D\u2026": "Copying\u2026", + "\u5DF2\u590D\u5236": "Copied", + "\u547D\u4EE4\u5DF2\u590D\u5236\u3002": "Command copied.", + "\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u9009\u4E2D\u547D\u4EE4\u540E\u6309 Ctrl+C \u6216 \u2318C \u590D\u5236\u3002": "Copy failed. Select the command and press Ctrl+C or \u2318C to copy it.", + "\u81EA\u52A8\u66F4\u65B0\u5931\u8D25\u53EF\u4EE5\u4F7F\u7528\u547D\u4EE4\u66F4\u65B0\uFF1A": "If the automatic update fails, update with this command:", + "\u5C1A\u672A\u786E\u8BA4\u76EE\u6807\u7248\u672C\uFF0C\u6B64\u547D\u4EE4\u5B89\u88C5\u6267\u884C\u65F6 npm \u7684 latest \u7248\u672C\u3002": "No target version has been confirmed. This command installs the npm latest version available when you run it.", + "\u8BF7\u5728\u5F53\u524D Desktop \u7684\u5185\u7F6E\u7EC8\u7AEF\u6267\u884C\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002": "Run this in the current Desktop\u2019s built-in terminal, then restart manually.", + "\u8BF7\u5728\u8FD0\u884C\u5F53\u524D Harness \u7684\u540C\u4E00\u73AF\u5883\u6267\u884C\uFF0C\u4FDD\u6301 DSH_HOME \u4E00\u81F4\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002": "Run this in the same environment as the current Harness, with the same DSH_HOME, then restart manually.", + "\u8BF7\u7B49\u5F85\u5F53\u524D\u64CD\u4F5C\u7ED3\u675F\uFF0C\u786E\u8BA4\u6CA1\u6709\u5B89\u88C5\u8FDB\u7A0B\u8FD0\u884C\u540E\u518D\u6267\u884C\u547D\u4EE4\u3002": "Wait for the current operation to finish and confirm no installer is running before using this command.", + "\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\u8BF7\u6309\u539F\u5B89\u88C5\u65B9\u5F0F\u66F4\u65B0\uFF0C\u4E0D\u63D0\u4F9B\u8986\u76D6\u6E90\u7801\u7684 npm \u547D\u4EE4\u3002": "Update source or linked installations using their original method. No npm command is provided to overwrite the source.", + "\u65E0\u6CD5\u5B89\u5168\u751F\u6210\u5F53\u524D profile \u7684\u547D\u4EE4\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u624B\u52A8\u786E\u8BA4 profile \u540E\u66F4\u65B0\u3002": "A safe command cannot be generated for this profile. Confirm the profile in your terminal before updating manually.", "\u66F4\u65B0\u81F3": "Update to", "\u5B89\u88C5\u66F4\u65B0": "Install update", "\u6B63\u5728\u66F4\u65B0\u2026": "Updating\u2026", "\u5F85\u624B\u52A8\u91CD\u542F": "Restart needed", "\u8FD0\u884C\u7248\u672C": "Running version", "\u5DF2\u5B89\u88C5\u7248\u672C": "Installed version", - "npm \u6700\u65B0\u7248\u672C": "Latest on npm", "\u76EE\u6807 profile": "Target profile", "\u76EE\u6807\u7248\u672C": "Target version", - "\u66F4\u65B0\u6765\u6E90": "Update source", - "\u9875\u9762\u7248\u672C": "Page version", "\u65E0\u6CD5\u786E\u8BA4": "Unknown", "\u53D1\u73B0\u65B0\u7248\u672C": "Update available", "\u5DF2\u662F\u6700\u65B0\u7248\u672C": "Up to date", @@ -10467,6 +11002,17 @@ var CSS11 = String.raw` .dim-updateHint, .dim-updateError { margin: 12px 0 0; font-size: 12px; line-height: 19px; overflow-wrap: anywhere; } .dim-updateHint { color: var(--dsw-alias-label-secondary, #646a73); } .dim-updateError { color: var(--dsw-alias-state-danger-primary, #d92d20); } +.dim-updateManual { margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--dsw-alias-border-l1, #eef0f3); } +.dim-updateManualHeading { margin: 0; font-size: 13px; line-height: 20px; font-weight: 600; } +.dim-updateManualHint { margin: 8px 0 0; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; line-height: 19px; } +.dim-updateCommandRow { display: flex; align-items: center; gap: 8px; margin-top: 10px; padding: 10px 12px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 8px; background: var(--dsw-alias-bg-layer-1, #f7f8fa); } +.dim-updateCommand { display: block; flex: 1; width: 100%; min-width: 0; padding: 0; resize: none; border: 0; color: var(--dsw-alias-label-primary, #1f2329); background: transparent; font: 12px/19px ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; } +.dim-updateCommand:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary, #3370ff); outline-offset: 2px; } +.dim-updateCopy { display: inline-flex; flex: 0 0 28px; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 6px; color: var(--dsw-alias-label-secondary, #646a73); background: transparent; cursor: pointer; } +.dim-updateCopy:hover:not(:disabled) { color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-interactive-bg-hover, #eef0f3); } +.dim-updateCopy:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary, #3370ff); outline-offset: 2px; } +.dim-updateCopy:disabled { opacity: .55; cursor: default; } +.dim-updateCopyCopied { color: var(--dsw-alias-state-success-primary, #20a162); } .dim-updateFooter { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px; padding: 14px 24px; border-top: 1px solid var(--dsw-alias-border-l1, #eef0f3); } .dim-updateFooter .dim-updateButton:first-child { margin-right: auto; } .dim-updatePrimary, .dim-updatePrimary:hover:not(:disabled) { border-color: var(--dsw-alias-state-business-primary, #3370ff); color: #fff; background: var(--dsw-alias-state-business-primary, #3370ff); } @@ -10779,6 +11325,8 @@ function installImStyles() { // plugin-src/client/update-panel.js var React20 = __toESM(require("react"), 1); var import_react_dom2 = require("react-dom"); +var import_valid = __toESM(require_valid(), 1); +var import_rcompare = __toESM(require_rcompare(), 1); var UPDATE_RPC_CHANNEL = "/dsh-im"; var ACTIVE_STATES4 = /* @__PURE__ */ new Set(["installing", "verifying"]); var BLOCKED_REASONS = Object.freeze({ @@ -10850,6 +11398,117 @@ function summary(snapshot, action, error) { function retainDialogFocus(event) { event?.currentTarget?.closest?.(".dim-updateDialog")?.focus?.({ preventScroll: true }); } +function manualUpdateCommand(snapshot) { + const profile = snapshot?.profileName; + if (snapshot?.sourceInstall || ["source-install", "unknown-profile"].includes(snapshot?.blockedReason) || typeof profile !== "string" || !profile.trim() || profile.length > 255 || profile.startsWith("-") || [".", "..", "node_modules"].includes(profile) || !/^[\p{L}\p{N}_. -]+$/u.test(profile)) return null; + const profileArgument = /^[A-Za-z0-9_.-]+$/.test(profile) ? profile : `"${profile}"`; + const validVersion = (version2) => typeof version2 === "string" && (0, import_valid.default)(version2) === version2; + const pendingRestart = snapshot.blockedReason === "pending-restart" || snapshot.job?.state === "restart-required"; + const targets = [ + snapshot.latestVersion, + pendingRestart ? snapshot.installedVersion : null, + snapshot.job?.state !== "completed" ? snapshot.job?.targetVersion : null + ].filter(validVersion); + const version = targets.length ? [...targets, snapshot.runningVersion, snapshot.installedVersion].filter(validVersion).sort(import_rcompare.default)[0] : "latest"; + return `dsh plugin --profile ${profileArgument} add -w @xmanrui/dsh-im@${version}`; +} +function ManualUpdateCommand({ command, disabled, sourceInstall, desktop }) { + const [copyState, setCopyState] = React20.useState("idle"); + const commandRef = React20.useRef(null); + const mounted = React20.useRef(false); + const copying = React20.useRef(false); + React20.useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + const copy = async (event) => { + if (!command || disabled || copying.current) return; + retainDialogFocus(event); + copying.current = true; + setCopyState("copying"); + try { + const clipboard = globalThis.navigator?.clipboard; + if (typeof clipboard?.writeText !== "function") throw new Error("Clipboard unavailable"); + await clipboard.writeText(command); + if (mounted.current) setCopyState("copied"); + } catch { + if (mounted.current) { + setCopyState("failed"); + commandRef.current?.focus?.({ preventScroll: true }); + commandRef.current?.select?.(); + } + } finally { + copying.current = false; + } + }; + const copyLabel = copyState === "copying" ? "\u590D\u5236\u4E2D\u2026" : copyState === "copied" ? "\u5DF2\u590D\u5236" : "\u590D\u5236\u547D\u4EE4"; + return h2( + "section", + { className: "dim-updateManual", "aria-label": "\u624B\u5DE5\u66F4\u65B0" }, + h2("h4", { className: "dim-updateManualHeading" }, "\u624B\u5DE5\u66F4\u65B0"), + command ? h2( + React20.Fragment, + null, + h2("p", { className: "dim-updateManualHint" }, "\u81EA\u52A8\u66F4\u65B0\u5931\u8D25\u53EF\u4EE5\u4F7F\u7528\u547D\u4EE4\u66F4\u65B0\uFF1A"), + h2( + "div", + { className: "dim-updateCommandRow" }, + h2("textarea", { + ref: commandRef, + className: "dim-updateCommand", + "aria-label": "\u624B\u5DE5\u66F4\u65B0\u547D\u4EE4", + value: command, + readOnly: true, + spellCheck: false, + rows: 2, + dir: "ltr" + }), + h2("button", { + type: "button", + className: `dim-updateCopy${copyState === "copied" ? " dim-updateCopyCopied" : ""}`, + "aria-label": copyLabel, + title: copyLabel, + "aria-busy": copyState === "copying", + disabled: disabled || copyState === "copying", + onClick: (event) => void copy(event) + }, h2("svg", { + width: 16, + height: 16, + viewBox: "0 0 20 20", + fill: "none", + stroke: "currentColor", + strokeWidth: 1.6, + strokeLinecap: "round", + strokeLinejoin: "round", + "aria-hidden": "true", + focusable: "false" + }, copyState === "copied" ? h2("path", { d: "m4 10 4 4 8-8" }) : h2( + React20.Fragment, + null, + h2("rect", { x: 7, y: 7, width: 10, height: 11, rx: 1.5 }), + h2("path", { d: "M5 13H3.5A1.5 1.5 0 0 1 2 11.5v-8A1.5 1.5 0 0 1 3.5 2h8A1.5 1.5 0 0 1 13 3.5V5" }) + ))) + ), + command.endsWith("@xmanrui/dsh-im@latest") ? h2( + "p", + { className: "dim-updateManualHint" }, + "\u5C1A\u672A\u786E\u8BA4\u76EE\u6807\u7248\u672C\uFF0C\u6B64\u547D\u4EE4\u5B89\u88C5\u6267\u884C\u65F6 npm \u7684 latest \u7248\u672C\u3002" + ) : null, + h2("p", { className: "dim-updateManualHint" }, desktop ? "\u8BF7\u5728\u5F53\u524D Desktop \u7684\u5185\u7F6E\u7EC8\u7AEF\u6267\u884C\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002" : "\u8BF7\u5728\u8FD0\u884C\u5F53\u524D Harness \u7684\u540C\u4E00\u73AF\u5883\u6267\u884C\uFF0C\u4FDD\u6301 DSH_HOME \u4E00\u81F4\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002"), + disabled ? h2( + "p", + { className: "dim-updateManualHint" }, + "\u8BF7\u7B49\u5F85\u5F53\u524D\u64CD\u4F5C\u7ED3\u675F\uFF0C\u786E\u8BA4\u6CA1\u6709\u5B89\u88C5\u8FDB\u7A0B\u8FD0\u884C\u540E\u518D\u6267\u884C\u547D\u4EE4\u3002" + ) : null, + copyState === "failed" || copyState === "copied" ? h2("p", { + className: copyState === "failed" ? "dim-updateError" : "dim-updateManualHint", + role: copyState === "failed" ? "alert" : "status" + }, copyState === "failed" ? "\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u9009\u4E2D\u547D\u4EE4\u540E\u6309 Ctrl+C \u6216 \u2318C \u590D\u5236\u3002" : "\u547D\u4EE4\u5DF2\u590D\u5236\u3002") : null + ) : h2("p", { className: "dim-updateManualHint" }, sourceInstall ? "\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\u8BF7\u6309\u539F\u5B89\u88C5\u65B9\u5F0F\u66F4\u65B0\uFF0C\u4E0D\u63D0\u4F9B\u8986\u76D6\u6E90\u7801\u7684 npm \u547D\u4EE4\u3002" : "\u65E0\u6CD5\u5B89\u5168\u751F\u6210\u5F53\u524D profile \u7684\u547D\u4EE4\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u624B\u52A8\u786E\u8BA4 profile \u540E\u66F4\u65B0\u3002") + ); +} function UpdateDialog({ children, onClose }) { const dialogRef = React20.useRef(null); const titleId = React20.useId(); @@ -10886,7 +11545,7 @@ function UpdateDialog({ children, onClose }) { onClose(); } if (event.key !== "Tab") return; - const buttons = dialogRef.current?.querySelectorAll?.("button:not(:disabled)"); + const buttons = dialogRef.current?.querySelectorAll?.("button:not(:disabled), textarea:not(:disabled)"); if (!buttons?.length) return; const first = buttons[0]; const last = buttons[buttons.length - 1]; @@ -11059,6 +11718,7 @@ function UpdatePanel({ rpcCall, clientVersion, onStatus }) { const failedJob = ["failed", "interrupted"].includes(snapshot?.job?.state); const jobMessage = snapshot?.job?.message; const targetVersion = snapshot?.job?.targetVersion; + const manualCommand = manualUpdateCommand(snapshot); const buttonLabel = action === "checking" ? "\u68C0\u67E5\u4E2D\u2026" : action === "starting" || activeJob ? "\u6B63\u5728\u66F4\u65B0\u2026" : restartRequired ? "\u5F85\u624B\u52A8\u91CD\u542F" : snapshot?.canInstall ? "\u66F4\u65B0\u81F3" : "\u68C0\u67E5\u66F4\u65B0"; return h2( React20.Fragment, @@ -11091,8 +11751,6 @@ function UpdatePanel({ rpcCall, clientVersion, onStatus }) { h2("dt", null, "\u5DF2\u5B89\u88C5\u7248\u672C"), h2("dd", null, `v${snapshot.installedVersion}`) ) : null, - h2("dt", null, "npm \u6700\u65B0\u7248\u672C"), - h2("dd", null, snapshot?.latestVersion ? `v${snapshot.latestVersion}` : "\u5C1A\u672A\u68C0\u67E5"), targetVersion ? h2( React20.Fragment, null, @@ -11100,15 +11758,7 @@ function UpdatePanel({ rpcCall, clientVersion, onStatus }) { h2("dd", null, `v${targetVersion}`) ) : null, h2("dt", null, "\u76EE\u6807 profile"), - h2("dd", null, snapshot?.profileName ?? "\u65E0\u6CD5\u786E\u8BA4"), - h2("dt", null, "\u66F4\u65B0\u6765\u6E90"), - h2("dd", null, "registry.npmjs.org"), - versionsDiffer ? h2( - React20.Fragment, - null, - h2("dt", null, "\u9875\u9762\u7248\u672C"), - h2("dd", null, `v${clientVersion}`) - ) : null + h2("dd", null, snapshot?.profileName ?? "\u65E0\u6CD5\u786E\u8BA4") ), h2( "div", @@ -11134,7 +11784,14 @@ function UpdatePanel({ rpcCall, clientVersion, onStatus }) { "p", { className: "dim-updateHint" }, "\u8BF7\u5728\u673A\u5668\u4EBA\u7A7A\u95F2\u65F6\u5B89\u88C5\uFF1B\u5B89\u88C5\u4F1A\u4FEE\u6539\u5F53\u524D profile \u7684\u4F9D\u8D56\uFF0C\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u3002" - ) : null + ) : null, + h2(ManualUpdateCommand, { + key: manualCommand ?? "unavailable", + command: manualCommand, + disabled: busyAction || activeJob || uncertainInstall, + sourceInstall: snapshot?.sourceInstall || snapshot?.blockedReason === "source-install", + desktop: snapshot?.environmentKind === "desktop" + }) ), h2( "footer", diff --git a/lib/index.js b/lib/index.js index 34d59b0..9a9aed8 100644 --- a/lib/index.js +++ b/lib/index.js @@ -353,7 +353,7 @@ ID\uFF1A{id}`,{title:A,id:a?.sessionId??i}),D("\u53D1\u9001 /history \u67E5\u770 ${D("\u5185\u5BB9\u8F83\u957F\uFF0C\u751F\u6210\u5B8C\u6210\u540E\u5C06\u5206\u6BB5\u53D1\u9001\u5B8C\u6574\u56DE\u7B54\u3002")}`;return Iv(n,JC-t.length)+t}function O0e(n){let t=[],o=n;for(;o.length>JC;){let i=Iv(o,JC),e=i.lastIndexOf(` `)+1;e{let c=String(g??"")||"\u2026";await this.#c(a,KV(c)),A=c}};await o.markdown(r);let s=O0e(A);for(let[g,c]of s.entries()){let I=g===0?a:await this.#i(t,i.replyTo);g>0&&e.push(I),await this.#c(I,c),await this.#s(I)}return{messageId:a.messageId,providerMessageIds:e.map(g=>g.messageId)}}catch(a){for(let A of e)await this.#o(A.messageId);throw a}}async sendFile(t,o,{replyTo:i,signal:e}={}){return this.#a(t,o,{replyTo:i,signal:e,messageType:"file",presentation:"feishu-file"})}async sendImage(t,o,{replyTo:i,signal:e}={}){return this.#a(t,o,{replyTo:i,signal:e,messageType:"image",presentation:"feishu-image"})}async#a(t,o,{replyTo:i,signal:e,messageType:a,presentation:A}){if(e?.throwIfAborted(),typeof t!="string"||!t)throw new TypeError("chatId is required");if(!o||typeof o!="object"||typeof o.artifactId!="string"||!o.artifactId||typeof o.deliveryKey!="string"||!o.deliveryKey||typeof o.fileName!="string"||!o.fileName||!Buffer.isBuffer(o.bytes))throw new TypeError("A materialized result file is required");let r;try{r=await HV(Q=>{Q.throwIfAborted();let y=a==="image"?this.#e.im.v1.image.create({data:{image_type:"message",image:o.bytes}}):this.#e.im.v1.file.create({data:{file_type:"stream",file_name:o.fileName,file:o.bytes}});return An(o,y),y},{signal:e,timeoutMs:this.#t,stage:"upload"})}catch(Q){throw e?.aborted?cv(e):jC("upload",Q)}e?.throwIfAborted();let s=a==="image"?r?.image_key??r?.data?.image_key:r?.file_key??r?.data?.file_key;if(typeof s!="string"||!s)throw jC("upload",void 0,r?.code);let g=D0e(o,t,a),c=JSON.stringify(a==="image"?{image_key:s}:{file_key:s}),I=i?{path:{message_id:i},data:{msg_type:a,content:c,uuid:g}}:{params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:a,content:c,uuid:g}},d=()=>{let Q=i?this.#e.im.v1.message.reply(I):this.#e.im.v1.message.create(I);return An(o,Q),Q},B;try{B=await HV(async Q=>{Q.throwIfAborted();let y;try{y=await d()}catch(m){if(jV(m)!==230049)throw m;y={code:230049}}return Q.throwIfAborted(),Number(y?.code)===230049&&(y=await d(),Q.throwIfAborted()),y},{signal:e,timeoutMs:this.#r,stage:"message send"})}catch(Q){throw e?.aborted?cv(e):jC("message send",Q,void 0,{uncertain:!0})}if(Number.isFinite(Number(B?.code))&&Number(B.code)!==0)throw jC("message send",void 0,B.code,{uncertain:!0});let f=B?.data?.message_id;if(typeof f!="string"||!f)throw jC("message send",void 0,void 0,{uncertain:!0});return Vt({deliveryId:o.deliveryKey,presentation:A,providerMessageIds:[f],artifacts:[{artifactId:o.artifactId,outcome:"sent"}]})}async#i(t,o){let i=KV(this.#A),a=YI("Feishu card.create",await this.#e.cardkit.v1.card.create({data:{type:"card_json",data:JSON.stringify(b0e(i))}}))?.data?.card_id;if(!a)throw new Error("Feishu card.create returned no card_id");let A=await this.#I(t,a,o);return{cardId:a,messageId:A,content:i,sequence:0}}async#c(t,o){if(o===t.content)return;let i=await this.#e.cardkit.v1.cardElement.content({path:{card_id:t.cardId,element_id:xV},data:{content:o,sequence:++t.sequence,uuid:`content_${t.cardId}_${t.sequence}`}});YI("Feishu cardElement.content",i),t.content=o}async#s(t){let o=await this.#e.cardkit.v1.card.settings({path:{card_id:t.cardId},data:{settings:JSON.stringify({config:{streaming_mode:!1,summary:{content:w0e(t.content)||D("\u56DE\u7B54\u5B8C\u6210")}}}),sequence:++t.sequence,uuid:`settings_${t.cardId}_${t.sequence}`}});YI("Feishu card.settings",o)}async#I(t,o,i){let e=JSON.stringify({type:"card",data:{card_id:o}}),a=i?await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"interactive",content:e}}):await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"interactive",content:e}});YI("Feishu message send",a);let A=a?.data?.message_id;if(!A)throw new Error("Feishu message send returned no message_id");return A}async#o(t){try{let o=await this.#e.im.v1.message.delete({path:{message_id:t}});YI("Feishu message delete",o)}catch(o){console.warn("[bridge] unable to recall a failed streaming card:",o.message)}}async addReaction(t,o){let e=YI("Feishu reaction.create",await this.#e.im.v1.messageReaction.create({path:{message_id:t},data:{reaction_type:{emoji_type:o}}}))?.data?.reaction_id;if(!e)throw new Error("Feishu reaction.create returned no reaction_id");return e}async removeReaction(t,o){YI("Feishu reaction.delete",await this.#e.im.v1.messageReaction.delete({path:{message_id:t,reaction_id:o}}))}};var _0e=15e3,T0e="\u2705 \u4FEE\u590D\u5B8C\u6210\uFF1A\u5DF2\u5B9E\u6D4B\u6536\u5230 card.action.trigger\uFF0C\u83DC\u5355\u6309\u94AE\u73B0\u5728\u53EF\u7528\u3002",N0e="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u8D85\u65F6\uFF1A\u672A\u6536\u5230\u6D4B\u8BD5\u5361\u6309\u94AE\u7684 card.action.trigger\uFF0C\u4E0D\u80FD\u786E\u8BA4\u6309\u94AE\u5DF2\u4FEE\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u7684\u5361\u7247\u56DE\u8C03\u914D\u7F6E\uFF0C\u786E\u8BA4\u540E\u518D\u53D1\u9001 /repair\u3002",lv="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u5931\u8D25\uFF1A\u65E0\u6CD5\u53D1\u9001\u4E13\u7528\u6D4B\u8BD5\u5361\uFF0C\u4E0D\u80FD\u786E\u8BA4 card.action.trigger \u5DF2\u6062\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u673A\u5668\u4EBA\u6D88\u606F\u6743\u9650\u548C\u8FDE\u63A5\u72B6\u6001\u3002",R0e="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u4E2D\u65AD\uFF1ARuntime \u5DF2\u505C\u6B62\uFF0C\u672A\u5B8C\u6210 card.action.trigger \u5B9E\u6D4B\uFF0C\u4E0D\u80FD\u786E\u8BA4\u4FEE\u590D\u6210\u529F\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u7B49\u5F85\u673A\u5668\u4EBA\u6062\u590D\u8FDE\u63A5\u3002",k0e=new Set(["connected","connecting","reconnecting"]);function gg(n){return typeof n=="string"&&n.trim()?n.trim():null}function v0e(n){return gg(n?.operator?.open_id)??gg(n?.operator?.operator_id?.open_id)}function P0e(n,t){try{let o=n?.getConnectionStatus?.()?.state;return typeof o=="string"&&o?o:t}catch{return t}}function od(n,t){let o=new Error(t);return o.code=n,o}function G0e(n,t){if(!n||typeof n.request!="function")return;let o=i=>({...i??{},timeout:i?.timeout??t});return{request:i=>n.request(o(i)),get:(i,e)=>n.get(i,o(e)),delete:(i,e)=>n.delete(i,o(e)),head:(i,e)=>n.head(i,o(e)),options:(i,e)=>n.options(i,o(e)),post:(i,e,a)=>n.post(i,e,o(a)),put:(i,e,a)=>n.put(i,e,o(a)),patch:(i,e,a)=>n.patch(i,e,o(a))}}function F0e({allowedSenderCount:n=1}={}){return{startedAt:null,ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1,messagesReceived:0,messagesReplied:0,messagesRejected:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,streamResponses:0,streamUpdates:0,streamFallbacks:0,streamErrors:0,cardActionsReceived:0,cardActionProbesVerified:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastCardActionAt:null,lastError:null,agentPreset:"standard",authorizationMode:"sender-open-id-allowlist",allowedSenderCount:n}}var ym=class{#e;#A;#t;#r;#a;#i;#c;#s;#I;#o;#n;#g;#l;#p;#d;#h;#E=null;#B=null;#u=null;#f=null;#m=null;#y=null;#Q=new Map;#C;constructor({lark:t,botId:o,appId:i,appSecret:e,domain:a="feishu",botOpenId:A,groupResponseMode:r,ownerOpenId:s,ownerOpenIds:g,harness:c,state:I,repair:d,replyTimeoutMs:B=6e5,connectTimeoutMs:f=15e3,requestTimeoutMs:Q=_0e,wsAgent:y,logger:m=console}){if(!t)throw new Error("FeishuRuntime requires the Feishu SDK");if(!i||!e)throw new Error("FeishuRuntime requires app credentials");let _=Array.isArray(g)?g:[s],T=[...new Set(_.filter(R=>typeof R=="string"&&R))];if(T.length===0)throw new Error("FeishuRuntime requires at least one owner open_id");if(!c)throw new Error("FeishuRuntime requires a Harness client");if(!I)throw new Error("FeishuRuntime requires a state store");if(d!=null&&!gg(o))throw new TypeError("FeishuRuntime repair capability requires a botId");if(!Number.isFinite(Q)||Q<=0)throw new TypeError("FeishuRuntime requestTimeoutMs must be a positive number");this.#e=t,this.#A=gg(o),this.#t=i,this.#r=e,this.#a=a,this.#i=gg(A),this.#c=Wi(r),this.#s=T,this.#I=c,this.#o=I,this.#h=d??null,this.#n=B,this.#g=f,this.#l=Q,this.#p=y,this.#d=m,this.#C=F0e({allowedSenderCount:T.length})}get status(){return structuredClone(this.#C)}setGroupResponseMode(t){this.#c=Wi(t),this.#B?.setGroupResponseMode(this.#c)}async start(){for(;;){for(;this.#m;)await this.#m;if(this.#f)return this.#f;let o=this.#u;if(o){let i=P0e(o,this.#C.feishuLongConnectionState);if(k0e.has(i))return this.status;await this.stop({preserveError:i==="failed"});continue}if(this.#E||this.#B||this.#y){await this.stop({preserveError:this.#C.feishuLongConnectionState==="failed"});continue}break}let t;return t=this.#M().finally(()=>{this.#f===t&&(this.#f=null)}),this.#f=t,t}async#M(){let t=new AbortController;this.#y=t;let{signal:o}=t,i=()=>o.reason??new DOMException("Feishu runtime stopped","AbortError"),e=()=>!o.aborted&&this.#y===t,a=()=>{if(!e())throw i()};this.#C.startedAt=new Date().toISOString(),this.#C.feishuLongConnectionState="connecting",this.#C.lastError=null;try{await this.#I.ensureRunning({signal:o}),a(),this.#C.harnessReachable=!0;let A=this.#a==="lark"?this.#e.Domain.Lark:this.#e.Domain.Feishu,r={appId:this.#t,appSecret:this.#r,domain:A},s=G0e(this.#e.defaultHttpInstance,this.#l);s&&(r.httpInstance=s);let g=new this.#e.Client(r);this.#E=g;let c=new Qm({client:g,initialText:D("\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026")}),I=new Bm({client:g,channel:c,harness:this.#I,state:this.#o,status:this.#C,allowedSenderOpenIds:new Set(this.#s),botId:this.#A,appId:this.#t,botOpenId:this.#i,groupResponseMode:this.#c,repair:this.#h,replyTimeoutMs:this.#n,signal:o,logger:this.#d});this.#B=I;let d=new this.#e.EventDispatcher({}).register({"im.message.receive_v1":_=>{e()&&I.accept(_)},"im.message.reaction.created_v1":()=>{},"im.message.reaction.deleted_v1":()=>{},"card.action.trigger":_=>{e()&&(this.#C.cardActionsReceived+=1,this.#C.lastCardActionAt=new Date().toISOString(),this.#b(_)||I.onCardAction(_))}}),B,f,Q=new Promise((_,T)=>{let R=!1,H=()=>{f(i())},j=(q,J)=>{R||(R=!0,clearTimeout(F),o.removeEventListener("abort",H),q(J))},F=setTimeout(()=>{j(T,new Error(`Feishu WebSocket handshake timed out after ${this.#g}ms`))},this.#g);B=()=>{j(_)},f=q=>{j(T,q)},o.addEventListener("abort",H,{once:!0}),o.aborted&&H()});Q.catch(()=>{});let y=new this.#e.WSClient({...r,...this.#p?{agent:this.#p}:{},loggerLevel:this.#e.LoggerLevel.info,handshakeTimeoutMs:this.#g,onReady:()=>{e()&&(this.#C.feishuLongConnectionState="connected",this.#C.ready=!0,this.#C.lastError=null,B())},onError:_=>{e()&&(this.#C.feishuLongConnectionState="failed",this.#C.ready=!1,this.#C.lastError=_?.message??String(_),this.#d.error("[dsh-feishu] Feishu long connection failed:",this.#C.lastError),f(_))},onReconnecting:()=>{e()&&(this.#C.feishuLongConnectionState="reconnecting",this.#C.ready=!1)},onReconnected:()=>{e()&&(this.#C.feishuLongConnectionState="connected",this.#C.ready=!0,this.#C.lastError=null)}});this.#u=y;let m=Promise.resolve().then(()=>y.start({eventDispatcher:d})).catch(_=>{throw f(_),_});return await Promise.all([m,Q]),a(),this.status}catch(A){throw o.aborted||(this.#C.ready=!1,this.#C.feishuLongConnectionState="failed",this.#C.lastError=A?.message??String(A),await this.#_({preserveError:!0,abortController:t})),A}}async beginCardActionProbe({expectedOperatorOpenId:t,timeoutMs:o=9e4}={}){if(!this.#C.ready||!this.#E)throw od("card_action_probe_unavailable","\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");let i=gg(t);if(!i||i==="*")throw new TypeError("A precise Feishu operator open_id is required");if(!Number.isFinite(o)||o<=0||o>10*6e4)throw new TypeError("Card-action probe timeout must be between 1 and 600000ms");let e=M0e().replaceAll("-",""),a;try{a=await this.#E.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:i,msg_type:"interactive",content:DV(e)}})}catch{throw this.#w(i,D(lv),"failure"),od("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5")}if(a?.code&&a.code!==0)throw this.#w(i,D(lv),"failure"),od("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5");let A=gg(a?.data?.message_id)??gg(a?.message_id);if(!A)throw this.#w(i,D(lv),"failure"),od("card_action_probe_send_failed","\u98DE\u4E66\u672A\u8FD4\u56DE\u6D4B\u8BD5\u5361\u7247\u7684\u6D88\u606F ID");return new Promise((r,s)=>{let g=setTimeout(()=>{let c=this.#Q.get(A);!c||c.nonce!==e||(this.#Q.delete(A),this.#w(i,D(N0e),"timeout"),s(od("card_action_probe_timeout","\u5728\u89C4\u5B9A\u65F6\u95F4\u5185\u672A\u6536\u5230\u98DE\u4E66\u5361\u7247\u6309\u94AE\u56DE\u8C03")))},o);g.unref?.(),this.#Q.set(A,{messageId:A,nonce:e,expectedOperatorOpenId:i,timeout:g,resolve:r,reject:s})})}#b(t){let o=gg(t?.context?.open_message_id);if(!o)return!1;let i=this.#Q.get(o);if(!i)return!1;let e=t?.action?.value,a=v0e(t);return e?.action!=="repair_verify"||e?.nonce!==i.nonce||a!==i.expectedOperatorOpenId?!1:(clearTimeout(i.timeout),this.#Q.delete(o),this.#C.cardActionProbesVerified+=1,this.#w(a,D(T0e),"success").finally(()=>{i.resolve({verified:!0,messageId:o,operatorOpenId:a})}),!0)}#w(t,o,i){let e=this.#E;return e?Promise.resolve().then(async()=>{let a=await e.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:t,msg_type:"text",content:JSON.stringify({text:o})}});if(a?.code&&a.code!==0)throw new Error("Feishu callback repair notice failed");return!0}).catch(()=>(this.#d.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),!1)):(this.#d.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),Promise.resolve(!1))}async sendConnectionTest(t){if(!this.#C.ready||!this.#E){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}if(typeof t!="string"||!t.trim())throw new TypeError("Feishu connection test text is required");let o=async(e,a,A)=>{let r=await this.#E.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:A})}});if(r?.code&&r.code!==0)throw new Error(`Feishu connection test failed: ${r.msg||r.code}`)},i=this.#s.find(e=>e!=="*");return i?(await o("open_id",i,t),{sent:!0}):Hg({state:this.#o,text:t,channelLabel:D("\u98DE\u4E66\u673A\u5668\u4EBA"),send:async(e,a)=>{let A=typeof e?.chatId=="string"?e.chatId.trim():"";if(!A)throw lr(D("\u98DE\u4E66\u673A\u5668\u4EBA"));await o("chat_id",A,a)}})}stop(t={}){if(this.#m)return this.#m;let o;return o=this.#S(t).finally(()=>{this.#m===o&&(this.#m=null)}),this.#m=o,o}async#S({preserveError:t=!1}={}){let o=this.#y;this.#y===o&&(this.#y=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));let i=this.#f;return i&&await i.catch(()=>{}),this.#_({preserveError:t,abortController:o})}async#_({preserveError:t=!1,abortController:o}={}){let i=t?this.#C.lastError:null;this.#y===o&&(this.#y=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));for(let A of this.#Q.values())clearTimeout(A.timeout),this.#w(A.expectedOperatorOpenId,D(R0e),"abort"),A.reject(od("abort","\u98DE\u4E66\u8FD0\u884C\u65F6\u5DF2\u505C\u6B62"));this.#Q.clear(),this.#C.ready=!1;let e=this.#u;this.#u=null,e?.close({force:!0});let a=this.#B;return this.#B=null,a&&await a.waitForIdle(),this.#E=null,this.#C.feishuLongConnectionState=t?"failed":"idle",this.#C.lastError=i,this.status}};var mm=class extends pr{constructor(t){super({...t,rpcIdPrefix:"feishu",logPrefix:"dsh-feishu"})}};import{createHash as L0e}from"node:crypto";import{mkdir as U0e,readFile as H0e,rename as K0e,unlink as x0e,writeFile as Y0e}from"node:fs/promises";import{dirname as j0e}from"node:path";var wm="DSH_FEISHU_APP_SECRET";function rs(n){return typeof n=="string"&&n.trim()?n.trim():null}function JV(n){let t=rs(n);return t&&/^[A-Za-z0-9_-]{1,128}$/.test(t)?t:null}function qV(n){return`bot_${L0e("sha256").update(n).digest("hex").slice(0,24)}`}function J0e(n){let t=Array.isArray(n.ownerOpenIds)?n.ownerOpenIds:[n.ownerOpenId];return[...new Set(t.map(rs).filter(Boolean))]}function Sm(n,{legacy:t=!1}={}){if(!n||typeof n!="object")return null;let o=rs(n.appId),i=J0e(n);if(!o||i.length===0)return null;let e=JV(n.id)??(t?qV(o):null),a=rs(n.secretRef)??(t?wm:null);if(!e||!a||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))return null;let A=n.domain==="lark"?"lark":"feishu";return Object.freeze({id:e,appId:o,secretRef:a,ownerOpenIds:Object.freeze(i),domain:A,botName:rs(n.botName),botOpenId:rs(n.botOpenId),activated:n.activated??null,groupResponseMode:Wi(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:rs(n.connectedAt),createdAt:rs(n.createdAt)??rs(n.connectedAt)})}function q0e(n){if(!n||typeof n!="object")return null;if(n.version===2&&Array.isArray(n.bots)){let o=n.bots.map(A=>Sm(A));if(o.some(A=>A===null))throw new Error("dsh-feishu config contains an invalid bot entry");let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.id)||e.has(A.secretRef)||a.has(A.appId))throw new Error("dsh-feishu config contains duplicate bot identities");i.add(A.id),e.add(A.secretRef),a.add(A.appId)}return{value:Object.freeze({version:2,bots:Object.freeze(o)}),migrated:!1}}let t=Sm(n,{legacy:!0});return t?{value:Object.freeze({version:2,bots:Object.freeze([t])}),migrated:!0}:null}var Dm=class{#e;#A=Object.freeze({version:2,bots:Object.freeze([])});#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=JSON.parse(await H0e(this.#e,"utf8")),o=q0e(t);if(!o)throw new Error("dsh-feishu config is incomplete or invalid");this.#A=o.value,o.migrated&&await this.#i(this.#A)}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=Object.freeze({version:2,bots:Object.freeze([])})}return this}get(){let t=this.#A.bots[0];if(!t)return null;let o=structuredClone(t);return o.ownerOpenId=o.ownerOpenIds[0],o}list(){return structuredClone(this.#A.bots)}getBot(t){let o=this.#A.bots.find(i=>i.id===t);return o?structuredClone(o):null}async save(t){let o={...t};o.id||(o.id=qV(rs(o.appId)??"invalid")),o.secretRef||(o.secretRef=wm);let i=Sm(o);if(!i)throw new Error("Refusing to persist incomplete dsh-feishu configuration");return await this.#r([i]),this.get()}async saveBot(t){let o=Sm(t);if(!o)throw new Error("Refusing to persist incomplete dsh-feishu bot configuration");return this.#a(i=>{if(i.find(r=>r.secretRef===o.secretRef&&r.id!==o.id))throw new Error("Refusing to share a credential reference between Feishu bots");if(i.find(r=>r.appId===o.appId&&r.id!==o.id))throw new Error("Refusing to persist the same Feishu app twice");let A=i.findIndex(r=>r.id===o.id);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async removeBot(t){if(!JV(t))throw new TypeError("Invalid Feishu bot id");return this.#a(o=>{let i=o.findIndex(a=>a.id===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await x0e(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=Object.freeze({version:2,bots:Object.freeze([])})});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o=Object.freeze({version:2,bots:Object.freeze([...t])}),i=this.#t.then(async()=>{await this.#i(o),this.#A=o});this.#t=i.then(()=>{},()=>{}),await i}async#a(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#i(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#i(t){await U0e(j0e(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await Y0e(o,`${JSON.stringify(t,null,2)} -`,{encoding:"utf8",mode:384}),await K0e(o,this.#e)}};import{randomUUID as $V}from"node:crypto";var pv=new Set(["starting","qr_ready","polling","slow_down","domain_switched","saving"]),z0e=new Set(["polling","slow_down","domain_switched"]),wi=Object.freeze({IDLE:"idle",STARTING:"starting",QR_READY:"qr_ready",POLLING:"polling",SLOW_DOWN:"slow_down",DOMAIN_SWITCHED:"domain_switched",SAVING:"saving",SUCCEEDED:"succeeded",EXPIRED:"expired",CANCELLED:"cancelled",ERROR:"error"});function zV(n){return["access_denied","expired_token","abort"].includes(n?.code)?n.code:"registration_failed"}function dv(n){let t=zV(n);return{code:t,message:{access_denied:"Registration was denied.",abort:"Registration was cancelled.",expired_token:"The registration QR code expired."}[t]??"Unable to register the Feishu app."}}function V0e(n){let t=Number(n);if(!Number.isFinite(t)||t<=0)throw new TypeError("registerApp onQRCodeReady returned an invalid expireIn");return t}function W0e(n){if(n!==void 0){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError("registerApp returned invalid user_info");return{...n}}}var cg=class{#e;#A;#t;#r;#a;#i=0;#c=null;#s;constructor({registerApp:t,onCredentials:o,now:i=Date.now,setTimeout:e=globalThis.setTimeout,clearTimeout:a=globalThis.clearTimeout}={}){if(typeof t!="function")throw new TypeError("RegistrationManager requires a registerApp function");if(typeof o!="function")throw new TypeError("RegistrationManager requires an onCredentials function");if(typeof i!="function"||typeof e!="function"||typeof a!="function")throw new TypeError("RegistrationManager clock dependencies must be functions");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#a=a,this.#s=this.#o(null,wi.IDLE)}start(t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("Registration options must be an object");this.#f();let o={id:++this.#i,controller:new AbortController,qrCodeUrl:null,expiresAt:null,pollIntervalSeconds:null,expiryTimer:null};this.#c=o,this.#s=this.#o(o,wi.STARTING);let i={...t,signal:o.controller.signal,onQRCodeReady:a=>this.#g(o,a),onStatusChange:a=>this.#l(o,a)};return Promise.resolve().then(()=>this.#e(i)).then(a=>this.#p(o,a),a=>this.#d(o,a)),this.status()}status(){this.#h();let t={...this.#s};t.error&&(t.error={...t.error});let o=this.#c;return o&&o.expiresAt!==null&&pv.has(t.state)&&(t.remainingSeconds=Math.max(0,Math.ceil((o.expiresAt-this.#t())/1e3))),t}cancel(){let t=this.#c;return t?(this.#B(t,wi.CANCELLED,{error:{code:"abort",message:"Registration was cancelled."}}),t.controller.abort(),this.status()):this.status()}#I(t){return this.#c===t}#o(t,o,i={}){let e={state:o,attempt:t?.id??this.#i,updatedAt:this.#t(),...i};return t?.qrCodeUrl&&pv.has(o)&&(e.qrCodeUrl=t.qrCodeUrl,e.expiresAt=t.expiresAt),t?.pollIntervalSeconds!==null&&pv.has(o)&&(e.pollIntervalSeconds=t.pollIntervalSeconds),e}#n(t,o,i={}){this.#I(t)&&(this.#s=this.#o(t,o,i))}#g(t,o){if(!this.#I(t))return;if(typeof o?.url!="string"||!o.url)throw new TypeError("registerApp onQRCodeReady returned an invalid URL");let i=V0e(o.expireIn);t.qrCodeUrl=o.url,t.expiresAt=this.#t()+i*1e3,this.#u(t),t.expiryTimer=this.#r(()=>this.#E(t),i*1e3),t.expiryTimer?.unref?.(),this.#n(t,wi.QR_READY)}#l(t,o){!this.#I(t)||!z0e.has(o?.status)||(o.status===wi.SLOW_DOWN&&Number.isFinite(Number(o.interval))&&(t.pollIntervalSeconds=Number(o.interval)),this.#n(t,o.status))}async#p(t,o){if(!this.#I(t))return;let i=o?.client_id,e=o?.client_secret;if(typeof i!="string"||!i||typeof e!="string"||!e){this.#B(t,wi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}let a;try{a=W0e(o.user_info)}catch{this.#B(t,wi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}this.#u(t),t.qrCodeUrl=null,t.expiresAt=null,t.pollIntervalSeconds=null,this.#n(t,wi.SAVING);try{await this.#A({client_id:i,client_secret:e,user_info:a})}catch{this.#I(t)&&this.#B(t,wi.ERROR,{error:{code:"credentials_callback_failed",message:"Unable to store the Feishu credentials."}});return}this.#I(t)&&this.#B(t,wi.SUCCEEDED)}#d(t,o){if(!this.#I(t))return;let i=zV(o);if(i==="expired_token"){this.#B(t,wi.EXPIRED,{error:dv(o)});return}if(i==="abort"){this.#B(t,wi.CANCELLED,{error:dv(o)});return}this.#B(t,wi.ERROR,{error:dv(o)})}#h(){let t=this.#c;t&&t.expiresAt!==null&&this.#t()>=t.expiresAt&&this.#E(t)}#E(t){this.#I(t)&&(this.#B(t,wi.EXPIRED,{error:{code:"expired_token",message:"The registration QR code expired."}}),t.controller.abort())}#B(t,o,i={}){this.#I(t)&&(this.#u(t),this.#s=this.#o(t,o,i),this.#c=null)}#u(t){t.expiryTimer!==null&&(this.#a(t.expiryTimer),t.expiryTimer=null)}#f(){let t=this.#c;t&&(this.#u(t),this.#c=null,t.controller.abort())}};var Z0e="card.action.trigger",X0e="im:message:readonly",$0e="im:resource",qC="callback_repair";function eNe(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function ANe(n){return n==="lark"?"open.larksuite.com":"open.feishu.cn"}function hv(n,t,o="feishu",i="Feishu app update"){let e;try{e=new URL(n)}catch{throw new Error(`${i} returned an invalid verification URL`)}let a=o==="feishu"||o==="lark",A=e.searchParams.getAll("clientID"),r=e.searchParams.getAll("tp"),s=e.searchParams.getAll("addons"),g=String(t).includes("{{")||String(t).includes("}}")||[...e.searchParams.values()].some(c=>c.includes("{{")||c.includes("}}"));if(!a||e.protocol!=="https:"||e.hostname!==ANe(o)||e.port!==""||e.username!==""||e.password!==""||r.length!==1||r[0]!=="sdk"||A.length!==1||A[0]!==t||e.searchParams.has("createOnly")||s.length!==1||!s[0]?.trim()||g)throw new Error(`${i} returned an unsafe verification URL`);return e.toString()}function tNe(n,t,o="feishu"){return hv(n,t,o,"Feishu callback repair")}var Om=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new cg({registerApp:a=>t({...a,onQRCodeReady:A=>{tNe(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-card-action-repair",domain:eNe(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[X0e,$0e]},callbacks:{items:[Z0e]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var rNe="im:message.group_msg",Mm="group_message_permission";function aNe(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function iNe(n,t,o="feishu"){return hv(n,t,o,"Feishu group message permission update")}var bm=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new cg({registerApp:a=>t({...a,onQRCodeReady:A=>{iNe(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-group-message-permission",domain:aNe(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[rNe]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var VV=Object.freeze(["im:message.p2p_msg:readonly","im:message.group_at_msg:readonly","im:message:readonly","im:message:send_as_bot","im:message.reactions:write_only","im:message:recall","im:resource","cardkit:card:write"]);var Ev=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),_m=new Set([...Ev,"saving"]),WV=new Set([qC,Mm]),ZV="*",oNe=12e4,nNe=6e5;function eW(){return{ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1}}function Tm(n){return n?n.status:eW()}function Nm(n){return n.ready===!0&&n.feishuLongConnectionState==="connected"&&n.harnessReachable===!0}function AW(n){return n.length>12?`${n.slice(0,8)}\u2022\u2022\u2022\u2022${n.slice(-4)}`:"cli_\u2022\u2022\u2022\u2022"}function sNe(n){return{name:n.botName,appIdMasked:AW(n.appId),activated:n.activated,domain:n.domain}}function gNe({connected:n,error:t,connection:o}){return n?"connected":t||o.feishuLongConnectionState==="failed"?"error":"disconnected"}function cNe(){return`bot_${$V().replaceAll("-","")}`}function INe(){return`reg_${$V().replaceAll("-","")}`}function XV(n){return`DSH_FEISHU_APP_SECRET_${n.slice(4).toUpperCase()}`}function Rm(n){return JSON.stringify({id:n.id,appId:n.appId,secretRef:n.secretRef,ownerOpenIds:n.ownerOpenIds,domain:n.domain,botName:n.botName,botOpenId:n.botOpenId,activated:n.activated,groupResponseMode:Wi(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:n.connectedAt??null,createdAt:n.createdAt??null})}function km(n){return typeof n=="string"&&n.trim()?n.trim():null}var zC=class{#e;#A;#t;#r;#a;#i;#c;#s;#I=new Map;#o=new Map;#n=new Map;#g=new Map;#l=new Map;#p=null;#d=Promise.resolve();#h=new Map;#E=1;#B;#u=!1;constructor({registerApp:t,verifyApp:o,credentials:i,configStore:e,createRuntime:a,deleteState:A=async()=>{},createBotId:r=cNe,createRegistrationId:s=INe,callbackProbeTimeoutMs:g=oNe}){if(typeof t!="function")throw new Error("registerApp is required");if(typeof o!="function")throw new Error("verifyApp is required");if(!i)throw new Error("credentials service is required");if(!e||typeof e.list!="function")throw new Error("multi-bot config store is required");if(typeof a!="function")throw new Error("createRuntime is required");if(typeof A!="function")throw new Error("deleteState must be a function");if(!Number.isFinite(g)||g<=0||g>nNe)throw new TypeError("callbackProbeTimeoutMs must be between 1 and 600000ms");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#a=a,this.#i=A,this.#c=r,this.#s=s,this.#B=g}async initialize(){if(this.#u)return this.status();let t=this.#r.list(),o=!1;return await Promise.allSettled(t.map(i=>this.#N(i.id,async()=>{let e=Tm(this.#I.get(i.id));if(Nm(e)||e.feishuLongConnectionState==="connecting"||e.feishuLongConnectionState==="reconnecting")return;if(o=!0,i.deletionPending){this.#o.set(i.id,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"});return}let a;try{a=await this.#t.resolve(i.secretRef)}catch{this.#o.set(i.id,{code:"missing_credentials",message:"\u65E0\u6CD5\u8BFB\u53D6\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u3002"});return}if(!a?.value){this.#o.set(i.id,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"});return}try{await this.#b(i,a.value),this.#o.delete(i.id)}catch{this.#o.set(i.id,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}}))),o&&this.#O(),this.status()}startRegistration(){this.#T();let t=this.#s();if(typeof t!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t)||this.#n.has(t))throw new Error("Registration id generator returned an invalid or duplicate id");let o={id:t,manager:null,botId:null,createdNew:!1,cancelled:!1};return o.manager=new cg({registerApp:this.#e,onCredentials:i=>this.#v(()=>this.#M(o,i))}),this.#n.set(t,o),this.#p=t,this.#F(),o.manager.start({source:"deepseek-harness",createOnly:!0,appPreset:{name:"{user} \u7684\u5317\u6C47\u661F\u6CB3 AI \u52A9\u624B",desc:"\u8FDE\u63A5\u98DE\u4E66\u4E0E DeepSeek Harness\uFF0C\u5728\u804A\u5929\u4E2D\u4F7F\u7528\u4F01\u4E1A AI \u52A9\u624B\u3002"},addons:{preset:!1,scopes:{tenant:[...VV]},events:{items:{tenant:["im.message.receive_v1"]}},callbacks:{items:["card.action.trigger"]}}}),this.#O(),this.registrationStatus(t)}startCallbackRepair(t,{actorOpenId:o,chatId:i}={}){this.#T();let e=this.#k(t);if(e.deletionPending)throw new Error("Cannot repair a Feishu bot pending deletion");let a=this.#g.get(t),A=a?this.#n.get(a):null;if(A&&_m.has(A.manager.status().state)){if(A.operation!==qC)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(A.id)}this.#g.delete(t);let r=this.#s();if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(r)||this.#n.has(r))throw new Error("Registration id generator returned an invalid or duplicate id");let s={id:r,operation:qC,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(e),targetFingerprint:Rm(e),initiator:{actorOpenId:km(o),chatId:km(i)}};return s.manager=new Om({registerApp:this.#e,appId:e.appId,domain:e.domain,onCredentials:g=>{s.remoteCommitted=!0;let I=this.#Q(s,g).finally(()=>{s.processing===I&&(s.processing=null)});return s.processing=I,I}}),this.#n.set(r,s),this.#g.set(t,r),this.#p=r,this.#F(),s.manager.start(),this.#O(),this.registrationStatus(r)}startGroupMessagePermission(t){this.#T();let o=this.#k(t);if(o.deletionPending)throw new Error("Cannot update permissions for a Feishu bot pending deletion");let i=this.#g.get(t),e=i?this.#n.get(i):null;if(e&&_m.has(e.manager.status().state)){if(e.operation!==Mm)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(e.id)}this.#g.delete(t);let a=this.#s();if(typeof a!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(a)||this.#n.has(a))throw new Error("Registration id generator returned an invalid or duplicate id");let A={id:a,operation:Mm,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(o),targetFingerprint:Rm(o),initiator:{actorOpenId:null,chatId:null}};return A.manager=new bm({registerApp:this.#e,appId:o.appId,domain:o.domain,onCredentials:r=>{A.remoteCommitted=!0;let g=this.#y(A,r).finally(()=>{A.processing===g&&(A.processing=null)});return A.processing=g,g}}),this.#n.set(a,A),this.#g.set(t,a),this.#p=a,this.#F(),A.manager.start(),this.#O(),this.registrationStatus(a)}hasRegistration(t){return this.#n.has(t)}registrationStatus(t){let o=this.#n.get(t);return o?this.#f({registration:o,selectedBotId:o.botId}):null}async cancelRegistration(t=this.#p){let o=this.#n.get(t);if(!o)return this.status();let i=o.manager.status().state;return WV.has(o.operation)&&i==="saving"?this.registrationStatus(t):_m.has(i)?(o.cancelled=!0,o.manager.cancel(),await this.#v(async()=>{o.createdNew&&o.botId&&this.#l.get(o.botId)===o.id&&this.#r.getBot(o.botId)&&await this.#N(o.botId,()=>this.#_(o.botId))}),this.#O(),this.registrationStatus(t)??this.status()):this.registrationStatus(t)}status(t){return this.#f({registration:this.#n.get(this.#p)??null,selectedBotId:t})}async bindCredentials({appId:t,appSecret:o,domain:i="feishu"}={}){this.#T();let e=typeof t=="string"?t.trim():"",a=typeof o=="string"?o.trim():"",A=i==="lark"?"lark":"feishu";if(!e||!a)throw new TypeError("Feishu App ID and App Secret are required");return this.#v(async()=>{this.#T();let r=await this.#A({appId:e,appSecret:a,domain:A});this.#T();let s=this.#r.list().find(f=>f.appId===e),g=s?.id??this.#c();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??XV(g),I=await this.#t.resolve(c).catch(()=>{}),d={...s,id:g,appId:e,secretRef:c,ownerOpenIds:s?.ownerOpenIds?.length?s.ownerOpenIds:[ZV],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()};await this.#t.set(c,a);let B;try{B=await this.#r.saveBot(d)}catch(f){throw await this.#R(c,I),f}return await this.#N(g,async()=>{try{await this.#b(B,a),this.#o.delete(g)}catch{this.#o.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u7ED1\u5B9A\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"})}}),this.#O(),this.status(g)})}async reconnectBot(t){return this.#T(),this.#N(t,async()=>{let o=this.#k(t);if(o.deletionPending)return this.#o.set(t,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"}),this.status(t);if(Nm(Tm(this.#I.get(t))))return this.status(t);let i;try{i=await this.#t.resolve(o.secretRef)}catch{i=null}if(!i?.value)return this.#o.set(t,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"}),this.#O(),this.status(t);try{await this.#b(o,i.value),this.#o.delete(t)}catch{this.#o.set(t,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}return this.#O(),this.status(t)})}async sendConnectionTest(t){return this.#T(),this.#N(t,async()=>{let o=this.#k(t),i=this.#I.get(t);if(!Nm(Tm(i))||typeof i.sendConnectionTest!="function"){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return i.sendConnectionTest(Da(`${o.botName}\uFF08${AW(o.appId)}\uFF09`,"\u98DE\u4E66\u673A\u5668\u4EBA"))})}async disconnectBot(t){return this.#T(),this.#N(t,async()=>(this.#k(t),await this.#S(t),this.#o.delete(t),this.#O(),this.status(t)))}async updateGroupResponseMode(t,o){if(this.#T(),!lm(o))throw new TypeError("Invalid Feishu group response mode");return this.#v(()=>this.#N(t,async()=>{let i=this.#k(t);if(o==="all"&&i.groupMessagePermissionGranted!==!0){let a=new Error("Authorize im:message.group_msg before enabling all group messages");throw a.code="group_message_permission_required",a}let e=await this.#r.saveBot({...i,groupResponseMode:o});return this.#I.get(t)?.setGroupResponseMode?.(e.groupResponseMode),this.#O(),this.status(t)}))}async deleteBot(t){return this.#T(),this.#v(()=>this.#N(t,async()=>(this.#k(t),await this.#_(t),this.#O(),this.status())))}async reconnect(){let t=this.#r.list()[0];return t?this.reconnectBot(t.id):this.status()}async disconnect(){let t=this.#r.list()[0];return t?this.deleteBot(t.id):this.status()}async close(){if(this.#u)return;this.#u=!0;let t=[];for(let o of this.#n.values()){let i=o.manager.status().state;WV.has(o.operation)&&i==="saving"?(o.manager.cancel(),o.processing&&t.push(o.processing)):_m.has(i)&&(o.cancelled=!0,o.manager.cancel())}await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#S(o))),await Promise.allSettled(t),await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#S(o)))}#f({registration:t,selectedBotId:o}={}){let i=this.#r.list().map(I=>{let d=Tm(this.#I.get(I.id)),B=Nm(d),f=this.#o.get(I.id)??null;return{botId:I.id,phase:gNe({connected:B,error:f,connection:d}),connected:B,configured:!0,groupResponseMode:Wi(I.groupResponseMode),groupMessagePermissionGranted:I.groupMessagePermissionGranted===!0,bot:sNe(I),connection:d,lastMessageError:zr(d.lastMessageError),error:f}}),e=t?this.#m(t):{state:"idle",attempt:0,updatedAt:Date.now()},a=Ev.has(e.state),A=e.state==="saving",r=!!t&&(a||A),s=i.find(I=>I.botId===o)??(r?null:i[0]??null),g=i.some(I=>I.connected),c=s?.phase??"unconfigured";return a?c="registering":A?c="connecting":e.state==="error"&&!s&&(c="error"),{schemaVersion:2,revision:this.#E,phase:c,connected:s?.connected??!1,configured:i.length>0,bot:s?.bot??null,connection:s?.connection??eW(),error:s?.error??e.error??null,registration:e,bots:i,totals:{configured:i.length,connected:i.filter(I=>I.connected).length},anyConnected:g}}#m(t){let o=t.manager.status();return{...o,attempt:t.id,...t.botId?{botId:t.botId}:{},...t.operation?{operation:t.operation}:{},...t.stage?{stage:t.stage}:{},...o.state==="error"&&t.publicError?{error:{...t.publicError}}:{}}}async#y(t,o){let i=o.client_id,e=o.client_secret,a=km(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#C(t,"abort","Group message permission update was cancelled before local activation.");if(i!==r.appId)throw this.#C(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#C(t,"repair_owner_missing","Feishu returned no permission operator identity.");if(A!==void 0&&A!==r.domain)throw this.#C(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");if(!r.ownerOpenIds.includes(ZV)&&!r.ownerOpenIds.includes(a))throw this.#C(t,"repair_owner_mismatch","The Feishu permission operator is not an owner of this configured bot.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(g){throw this.#C(t,"repair_credentials_invalid","Feishu could not verify the updated app credentials.",g)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#C(t,"repair_bot_mismatch","The updated Feishu app belongs to a different bot identity.");await this.#v(()=>this.#N(t.botId,async()=>{let g=this.#r.getBot(t.botId);if(!g||g.deletionPending||Rm(g)!==t.targetFingerprint)throw this.#C(t,"repair_target_changed","The Feishu bot changed while its permission update was in progress.");let c;try{c=await this.#t.resolve(g.secretRef)}catch(d){throw this.#C(t,"credential_update_failed","Unable to read the current Feishu credential.",d)}if(c?.value!==e){t.stage="persisting_secret";try{await this.#t.set(g.secretRef,e)}catch(B){if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_update_failed","Unable to store the updated Feishu credential.",B)}if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_state_unknown","The updated Feishu credential could not be confirmed after writing.")}t.stage="enabling_all_messages";let I;try{I=await this.#r.saveBot({...g,groupMessagePermissionGranted:!0,groupResponseMode:"all"})}catch(d){throw this.#C(t,"group_message_permission_save_failed","The permission was accepted, but all-message mode could not be saved.",d)}t.stage="restarting";try{await this.#b(I,e)}catch(d){throw this.#o.set(t.botId,{code:"connection_failed",message:"\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u4F46\u673A\u5668\u4EBA\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#O(),this.#C(t,"group_message_permission_connection_failed","The permission was accepted, but the Feishu runtime could not restart.",d)}this.#o.delete(t.botId),t.stage="verified",t.publicError=null,this.#O()}))}async#Q(t,o){let i=o.client_id,e=o.client_secret,a=km(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#C(t,"abort","Callback repair was cancelled before local activation.");if(i!==r.appId)throw this.#C(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#C(t,"repair_owner_missing","Feishu returned no repair operator identity.");if(A!==void 0&&A!==r.domain)throw this.#C(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(c){throw this.#C(t,"repair_credentials_invalid","Feishu could not verify the repaired app credentials.",c)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#C(t,"repair_bot_mismatch","The repaired Feishu app belongs to a different bot identity.");let g=await this.#v(()=>this.#N(t.botId,async()=>{let c=this.#r.getBot(t.botId);if(!c||c.deletionPending||Rm(c)!==t.targetFingerprint)throw this.#C(t,"repair_target_changed","The Feishu bot changed while its callback repair was in progress.");let I;try{I=await this.#t.resolve(c.secretRef)}catch(f){throw this.#C(t,"credential_update_failed","Unable to read the current Feishu credential.",f)}if(I?.value!==e){t.stage="persisting_secret";try{await this.#t.set(c.secretRef,e)}catch(Q){if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_update_failed","Unable to store the repaired Feishu credential.",Q)}if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_state_unknown","The repaired Feishu credential could not be confirmed after writing.")}let B;t.stage="restarting";try{await this.#b(c,e),B=this.#I.get(t.botId)}catch(f){throw this.#o.set(t.botId,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u56DE\u8C03\u4FEE\u590D\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#O(),this.#C(t,"repair_connection_failed","The repaired Feishu runtime could not be started.",f)}if(!B)throw this.#C(t,"repair_connection_failed","The repaired Feishu runtime is unavailable.");return this.#o.delete(t.botId),this.#O(),B}));if(typeof g.beginCardActionProbe!="function")throw this.#C(t,"card_action_probe_unavailable","The Feishu runtime cannot verify card callbacks.");t.stage="awaiting_callback";try{if((await g.beginCardActionProbe({expectedOperatorOpenId:t.initiator.actorOpenId??a,timeoutMs:this.#B,...t.initiator.chatId?{chatId:t.initiator.chatId}:{}}))?.verified!==!0){let I=new Error("Feishu runtime returned no callback proof");throw I.code="card_action_probe_failed",I}}catch(c){let I=c?.code==="card_action_probe_timeout"?"card_action_probe_timeout":c?.code==="card_action_probe_unavailable"?"card_action_probe_unavailable":c?.code==="card_action_probe_send_failed"?"card_action_probe_send_failed":"card_action_probe_failed";throw this.#C(t,I,I==="card_action_probe_timeout"?"Timed out waiting for the Feishu callback verification button.":"The Feishu card callback probe failed.",c)}t.stage="verified",t.publicError=null,this.#O()}#C(t,o,i,e){t.publicError={code:o,message:i};let a=new Error(i,e?{cause:e}:void 0);return a.code=o,a}async#M(t,o){if(t.cancelled)throw new Error("Registration was cancelled");let i=o.client_id,e=o.client_secret,a=o.user_info?.open_id,A=o.user_info?.tenant_brand==="lark"?"lark":"feishu";if(!a)throw new Error("Feishu registration returned no owner open_id");let r=await this.#A({appId:i,appSecret:e,domain:A});if(t.cancelled)throw new Error("Registration was cancelled");let s=this.#r.list().find(Q=>Q.appId===i),g=s?.id??this.#c();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??XV(g),I=this.#l.get(g),d=await this.#t.resolve(c).catch(()=>{});await this.#t.set(c,e);let B;try{B=await this.#r.saveBot({...s,id:g,appId:i,secretRef:c,ownerOpenIds:[...new Set([...s?.ownerOpenIds??[],a])],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()}),t.botId=g,t.createdNew=!s,this.#l.set(g,t.id)}catch(Q){try{await this.#R(c,d)}catch(y){throw new Error("Unable to restore the Feishu credential after a config failure.",{cause:y})}throw Q}if(t.cancelled)throw t.createdNew?await this.#N(g,()=>this.#_(g)):(await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g)),new Error("Registration was cancelled");let f=!1;try{if(await this.#N(g,()=>this.#b(B,e)),t.cancelled)throw t.createdNew?await this.#N(g,()=>this.#_(g)):(await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g),d?.value&&!s.deletionPending?await this.#N(g,()=>this.#b(s,d.value)):await this.#N(g,()=>this.#S(g))),f=!0,new Error("Registration was cancelled");this.#o.delete(g),this.#O()}catch(Q){if(t.cancelled)throw!f&&t.createdNew&&this.#r.getBot(g)?await this.#N(g,()=>this.#_(g)):!f&&s&&(await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g),!this.#u&&d?.value&&!s.deletionPending?await this.#N(g,()=>this.#b(s,d.value)):await this.#N(g,()=>this.#S(g))),this.#O(),Q;if(s&&d?.value)try{throw await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g),s.deletionPending?(await this.#N(g,()=>this.#S(g)),this.#o.set(g,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"})):(await this.#N(g,()=>this.#b(s,d.value)),this.#o.delete(g)),this.#O(),Q}catch(y){throw y===Q?Q:(this.#o.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u8FDE\u63A5\u66F4\u65B0\u5931\u8D25\uFF0C\u4E14\u539F\u8FDE\u63A5\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002"}),this.#O(),new Error("Unable to restore the previous Feishu bot connection.",{cause:y}))}throw this.#o.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#O(),Q}}async#b(t,o){await this.#S(t.id);let i=await this.#a({botId:t.id,config:t,appSecret:o,repair:this.#w(t.id)});this.#I.set(t.id,i);try{await i.start()}catch(e){throw this.#I.get(t.id)===i&&this.#I.delete(t.id),await i.stop({preserveError:!0}).catch(()=>{}),e}}#w(t){let o=i=>{let e=this.#n.get(i);return e?.operation===qC&&e.botId===t?e:null};return Object.freeze({start:({actorOpenId:i,chatId:e}={})=>this.startCallbackRepair(t,{actorOpenId:i,chatId:e}),status:({attemptId:i}={})=>o(i)?this.registrationStatus(i):null,cancel:async({attemptId:i}={})=>o(i)?this.cancelRegistration(i):this.status(t)})}async#S(t){let o=this.#I.get(t);this.#I.delete(t),o&&await o.stop()}async#_(t){let o=this.#r.getBot(t);if(o){o.deletionPending||(o=await this.#r.saveBot({...o,deletionPending:!0})),await this.#S(t);try{await this.#t.unset(o.secretRef)}catch(i){throw this.#o.set(t,{code:"credential_removal_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu credential.",{cause:i})}try{await this.#i({botId:t,config:o})}catch(i){throw this.#o.set(t,{code:"state_cleanup_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u7684\u672C\u5730\u4F1A\u8BDD\u6570\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu bot session state.",{cause:i})}await this.#r.removeBot(t),this.#o.delete(t),this.#l.delete(t)}}async#R(t,o){o?.value?await this.#t.set(t,o.value):await this.#t.unset(t)}#k(t){let o=this.#r.getBot(t);if(!o)throw new Error("Unknown Feishu bot");return o}#T(){if(this.#u)throw new Error("The Feishu controller is closed")}#v(t){let o=this.#d.then(t,t);return this.#d=o.then(()=>{},()=>{}),o}#N(t,o){let e=(this.#h.get(t)??Promise.resolve()).then(o,o),a=e.then(()=>{},()=>{});return this.#h.set(t,a),a.finally(()=>{this.#h.get(t)===a&&this.#h.delete(t)}),e}#F(){if(!(this.#n.size<=32))for(let[t,o]of this.#n){if(t===this.#p)continue;let i=o.manager.status().state;if(!Ev.has(i)&&i!=="saving"&&this.#n.delete(t),this.#n.size<=32)break}}#O(){this.#E+=1}};function dNe(n){for(let t of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY"]){let o=n?.[t];if(typeof o=="string"&&o.trim())return o.trim()}}function hNe(n,t=o=>new tW.default(o)){let o=dNe(n);return o?t(o):void 0}function ENe(n){let t=Ic(n.dshHome??process.env.DSH_HOME??nd(lNe(),".dsh")),o=Ic(n.dataDir??nd(t,"integrations","dsh-feishu"));return{root:o,config:Ic(n.configPath??nd(o,"config.json")),legacyState:Ic(n.statePath??nd(o,"state.json")),bots:Ic(n.botsDir??nd(o,"bots")),workspaces:Ic(n.workspacesPath??nd(o,"workspaces.json"))}}async function Cv(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-feishu requires ctx.credentials");let i=$r(n,t),e=o.lark??Av,a=o.Controller??zC,A=o.ConfigStore??Dm,r=o.StateStore??cm,s=o.HarnessClient??mm,g=o.FeishuRuntime??ym,c=o.verifyFeishuApp??dV,I=fe=>c({...fe,httpInstance:e.defaultHttpInstance}),d=o.createConnectionSupervisor??tv,B=typeof n.logger=="function"?n.logger("dsh-feishu"):n.logger??console,f=()=>_a(n),Q=ENe(t),y=await new A(Q.config).load(),m=Ic(t.workspace??process.cwd()),_=o.WorkspaceStore??Xr,T=o.workspaces??await new _(Q.workspaces,{defaultWorkspace:m}).load(),R=typeof y.list=="function",H=()=>R?y.list():[],j=H();R&&await T.reconcile(j.map(fe=>fe.id)),await Promise.all(j.map(fe=>T.ensure(fe.id,{defaultAgentPreset:t.agentPreset})));let F=typeof y.removeBot=="function"?Ra(y,{workspaces:T,method:"removeBot",botIdFromRemoved:fe=>fe.id}):y,q=new Map,J=fe=>!fe.id||!fe.secretRef||fe.secretRef===wm?Q.legacyState:Ic(Q.bots,fe.id,"state.json"),x=async fe=>{let De=fe.id??"__legacy__",Ke=q.get(De);return Ke||(Ke=await new r(J(fe)).load(),q.set(De,Ke)),Ke},P=async fe=>{let De=H().find(Ke=>Ke.id===fe);if(!De)throw new Error("Unknown Feishu bot");return x(De)},z=Pa(n,o.commandExecutor),{controlExecutor:U,sessionMaintenanceExecutor:N,fileIngressExecutor:k}=Ga(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),V=new s({...i,workspace:m,autostart:!1,dshBin:t.dshBin??"dsh",...z?{commandExecutor:z}:{},...U?{controlExecutor:U}:{},...N?{sessionMaintenanceExecutor:N}:{},...k?{fileIngressExecutor:k}:{}}),ee=o.proxyEnv??process.env,ie=hNe(ee,o.createProxyAgent),Te=new a({registerApp:fe=>e.registerApp(fe),verifyApp:I,credentials:n.credentials,configStore:F,createRuntime:async({botId:fe,config:De,appSecret:Ke,repair:rA})=>{let ve=await x(De),iA=fe??De.id??De.appId;await T.ensure(iA,{defaultAgentPreset:t.agentPreset});let Ce=ka(V,{botId:iA,workspaces:T,state:ve,agentPresetCatalog:f});return new g({lark:e,botId:iA,repair:rA,appId:De.appId,appSecret:Ke,domain:De.domain,botOpenId:De.botOpenId,groupResponseMode:De.groupResponseMode,ownerOpenIds:De.ownerOpenIds??[De.ownerOpenId],harness:Ce.harness,state:Ce.state,replyTimeoutMs:t.replyTimeoutMs??6e5,...ie?{wsAgent:ie}:{},logger:{error:(...he)=>B.error?.(`[${fe??De.id}]`,...he),warn:(...he)=>B.warn?.(`[${fe??De.id}]`,...he),info:(...he)=>B.info?.(`[${fe??De.id}]`,...he),debug:(...he)=>B.debug?.(`[${fe??De.id}]`,...he)}})},deleteState:async({botId:fe,config:De})=>{q.delete(fe);try{await pNe(J(De))}catch(Ke){if(Ke?.code!=="ENOENT")throw Ke}}}),se=va(Te,{workspaces:T,stateFor:P,agentPresetCatalog:f}),Ne=d({controller:se,harness:V,logger:B,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:se,ready:Ne.ready,async close(){await Ne.close(),await se.close(),V.stopManagedProcess(),ie?.destroy?.()}}}import vNe from"qrcode";var gd=qe(Sv(),1);var NNe=qe(Sv(),1);var RNe=Object.freeze({$locale:"en",IM\u673A\u5668\u4EBA:"IM bots",IM\u673A\u5668\u4EBA\u8BBE\u7F6E:"IM bot settings","IM \u6E20\u9053":"IM channels","\u8BA9 DeepSeek Harness \u89E6\u624B\u53EF\u53CA":"Connecting DeepSeek Harness",\u5F53\u524D\u7248\u672C:"Current version","DSH-IM \u66F4\u65B0":"DSH-IM update",\u68C0\u67E5\u66F4\u65B0:"Check for updates",\u91CD\u65B0\u68C0\u67E5:"Check again",\u5237\u65B0\u72B6\u6001:"Refresh status",\u66F4\u65B0\u81F3:"Update to",\u5B89\u88C5\u66F4\u65B0:"Install update","\u6B63\u5728\u66F4\u65B0\u2026":"Updating\u2026",\u5F85\u624B\u52A8\u91CD\u542F:"Restart needed",\u8FD0\u884C\u7248\u672C:"Running version",\u5DF2\u5B89\u88C5\u7248\u672C:"Installed version","npm \u6700\u65B0\u7248\u672C":"Latest on npm","\u76EE\u6807 profile":"Target profile",\u76EE\u6807\u7248\u672C:"Target version",\u66F4\u65B0\u6765\u6E90:"Update source",\u9875\u9762\u7248\u672C:"Page version",\u65E0\u6CD5\u786E\u8BA4:"Unknown",\u53D1\u73B0\u65B0\u7248\u672C:"Update available",\u5DF2\u662F\u6700\u65B0\u7248\u672C:"Up to date",\u5F53\u524D\u7248\u672C\u65E0\u9700\u66F4\u65B0:"No newer version available","\u5DF2\u83B7\u53D6 npm \u6700\u65B0\u7248\u672C":"Latest npm version retrieved","\u68C0\u67E5 npm \u6700\u65B0\u7248\u672C\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u5B89\u88C5\u3002":"Check the latest npm version. Nothing is installed automatically.","\u6B63\u5728\u4ECE npm \u68C0\u67E5\u6700\u65B0\u7248\u672C\u2026":"Checking npm for the latest version\u2026","\u6B63\u5728\u5B89\u88C5\uFF0C\u8BF7\u7A0D\u5019\u2026":"Installing, please wait\u2026","\u6B63\u5728\u6821\u9A8C\u5B89\u88C5\u7ED3\u679C\u2026":"Verifying the installation\u2026","\u5DF2\u5B89\u88C5\uFF0C\u5F85\u624B\u52A8\u91CD\u542F":"Installed \u2014 manual restart needed",\u66F4\u65B0\u5DF2\u751F\u6548:"Updated version is active",\u66F4\u65B0\u5931\u8D25:"Update failed",\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25:"Update request failed","\u4EC5\u66F4\u65B0 DSH-IM\u3002\u5B89\u88C5\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u540E\u53F0\uFF1B\u672C\u529F\u80FD\u4E0D\u4F1A\u81EA\u52A8\u91CD\u542F\u6216\u4E3B\u52A8\u5237\u65B0\u9875\u9762\u3002":"Only DSH-IM will be updated. Restart the backend manually after installation. This feature does not automatically restart it or initiate a page refresh.","\u5F53\u524D\u662F\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\uFF0C\u53EA\u80FD\u68C0\u67E5\u7248\u672C\uFF1B\u8BF7\u624B\u52A8\u66F4\u65B0\u6E90\u7801\uFF0C\u6216\u8FC1\u79FB\u5230 npm \u5B89\u88C5\u3002":"This is a source or linked installation. You can check versions, but must update the source manually or migrate to an npm installation.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D profile\uFF0C\u8BF7\u5728\u5BF9\u5E94\u7684 Harness \u73AF\u5883\u4E2D\u624B\u52A8\u66F4\u65B0\u3002":"The current profile could not be identified. Update manually in the corresponding Harness environment.","\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u4E0D\u652F\u6301\u6309\u94AE\u5B89\u88C5\uFF0C\u8BF7\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u3002":"This runtime cannot install through this button. Update the plugin manually.","\u5F53\u524D npm \u6E90\u914D\u7F6E\u4E0E\u5B98\u65B9\u6E90\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u5148\u68C0\u67E5 registry \u914D\u7F6E\u3002":"The npm registry configuration differs from the official registry. Check your registry settings first.","\u5F53\u524D Host \u7684 Node.js \u7248\u672C\u4E0D\u6EE1\u8DB3\u65B0\u7248\u8981\u6C42\uFF0C\u8BF7\u5148\u66F4\u65B0\u8FD0\u884C\u73AF\u5883\u3002":"The Host Node.js version does not meet the new version\u2019s requirements. Update the runtime first.","\u65B0\u7248\u672C\u5DF2\u5B89\u88C5\uFF0C\u8BF7\u5728\u65B9\u4FBF\u65F6\u624B\u52A8\u91CD\u542F\u5F53\u524D Harness \u6216 Desktop\u3002":"The new version is installed. Manually restart this Harness or Desktop when convenient.","\u4E0A\u6B21\u5B89\u88C5\u7ED3\u679C\u65E0\u6CD5\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u6B64 profile \u7684\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u3002":"The previous installation result is uncertain. Check this profile\u2019s plugin installation first.","\u65E0\u6CD5\u8BBF\u95EE npm \u6216\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u68C0\u67E5\u3002":"npm is unreachable or the request timed out. Check again later.","npm \u8FD4\u56DE\u7684\u7248\u672C\u4FE1\u606F\u65E0\u6548\uFF0C\u6682\u65F6\u65E0\u6CD5\u66F4\u65B0\u3002":"npm returned invalid release information. Updating is unavailable.","\u7248\u672C\u786E\u8BA4\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u540E\u518D\u5B89\u88C5\u3002":"The version confirmation expired. Check again before installing.","\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u3002":"The plugin installation changed. Check again.","\u6B64 profile \u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u67E5\u770B\u72B6\u6001\u3002":"This profile is already updating. Check its status shortly.","\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"Installation failed. Check the current installation before retrying.","\u5B89\u88C5\u7ED3\u679C\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u63D2\u4EF6\u7248\u672C\u3002":"Installation verification failed. Check the plugin version manually.","\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u66F4\u65B0\u72B6\u6001\uFF0C\u8BF7\u5148\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u7ED3\u679C\u3002":"Update state could not be saved safely. Check the current installation result before retrying.","\u4E0A\u6B21\u66F4\u65B0\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u68C0\u67E5\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"The previous update was interrupted. Check the installation before retrying.","\u66F4\u65B0\u670D\u52A1\u5DF2\u5173\u95ED\uFF0C\u8BF7\u624B\u52A8\u91CD\u65B0\u6253\u5F00\u8BBE\u7F6E\u9875\u3002":"The update service has closed. Reopen settings manually.","\u66F4\u65B0\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u7248\u672C\u3002":"The update request is invalid. Check the version again.","\u5F53\u524D\u63D2\u4EF6\u5B89\u88C5\u4E0D\u5B8C\u6574\u6216\u4E0E profile \u4E0D\u7B26\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u5B89\u88C5\u914D\u7F6E\u3002":"The plugin installation is incomplete or does not match this profile. Check the installation configuration manually.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D npm \u6E90\u914D\u7F6E\uFF0C\u6682\u65F6\u4E0D\u80FD\u5B89\u88C5\u66F4\u65B0\u3002":"The npm registry configuration could not be verified. Installation is unavailable.","\u5B89\u88C5\u8D85\u65F6\uFF0C\u8BF7\u5148\u786E\u8BA4\u5F53\u524D\u5B89\u88C5\u72B6\u6001\uFF0C\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\u3002":"Installation timed out. Check the current installation before retrying.","\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"The update request failed. Try again.","\u66F4\u65B0\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002":"The update service returned an unrecognized response.","\u5F53\u524D Host \u4E0D\u652F\u6301\u66F4\u65B0\u63A5\u53E3\uFF0C\u8BF7\u5148\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u5E76\u91CD\u542F\u3002":"This Host does not support the update API. Update the plugin manually and restart first.","\u5173\u95ED\u7A97\u53E3\u4E0D\u4F1A\u53D6\u6D88\u5B89\u88C5\u3002\u8BF7\u52FF\u540C\u65F6\u5728\u5176\u4ED6\u7A97\u53E3\u7BA1\u7406\u6B64 profile \u7684\u63D2\u4EF6\u3002":"Closing this window does not cancel installation. Do not manage this profile\u2019s plugins in another window at the same time.","\u9875\u9762\u7248\u672C\u4E0E\u8FD0\u884C\u7248\u672C\u4E0D\u540C\uFF0C\u8BF7\u624B\u52A8\u5237\u65B0\u9875\u9762\uFF1B\u82E5\u4ECD\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u624B\u52A8\u91CD\u542F Harness \u6216 Desktop\u3002":"The page and running versions differ. Refresh the page manually; if they still differ, manually restart Harness or Desktop.","\u8BF7\u5728\u673A\u5668\u4EBA\u7A7A\u95F2\u65F6\u5B89\u88C5\uFF1B\u5B89\u88C5\u4F1A\u4FEE\u6539\u5F53\u524D profile \u7684\u4F9D\u8D56\uFF0C\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u3002":"Install while bots are idle. This changes the current profile\u2019s dependencies and requires a manual restart afterward.","AI Office":"AI Office","\uFF08\u5B9E\u9A8C\u529F\u80FD\uFF09":"(Experimental)","AI Office \u8BBE\u7F6E":"AI Office settings","AI Office \u8BBE\u7F6E\u9875\u7F3A\u5C11 RPC \u8FDE\u63A5":"AI Office settings are missing an RPC connection","\u6B63\u5728\u8BFB\u53D6 AI Office Connector\u2026":"Loading AI Office Connector\u2026","\u672C\u673A\u4E3B\u52A8\u8FDE\u63A5\u516C\u7F51 Office\uFF1BHarness \u4E0D\u5F00\u653E\u7AEF\u53E3\u3002\u534F\u8BAE Hook \u56FA\u5B9A\u4E3A ":"This machine connects outward to the public Office; Harness exposes no port. Protocol hooks: ",\u5C1A\u672A\u914D\u7F6E:"Not configured","\u5DF2\u8FDE\u63A5 Office":"Connected to Office",\u5DF2\u914D\u7F6E:"Configured",\u7B49\u5F85\u91CD\u8FDE:"Waiting to reconnect",\u51ED\u636E\u7F3A\u5931:"Credential missing",\u6700\u8FD1\u5FC3\u8DF3:"Last heartbeat",\u6700\u8FD1\u4E8B\u4EF6:"Last event",\u91CD\u8FDE\u6B21\u6570:"Reconnects","\u8FD0\u884C Job":"Running Jobs","\u5B8C\u6210 Job":"Completed Jobs",\u5C1A\u65E0:"None yet",\u8BBE\u5907\u8FDE\u63A5:"Device connection","Token \u53EA\u5199\u5165\u672C\u673A\u51ED\u636E\u5B58\u50A8":"Token is written only to the local credential store","\u7C98\u8D34 Office \u4E00\u6B21\u6027\u51ED\u636E":"Paste the one-time Office credential","\u5DF2\u5B89\u5168\u4FDD\u5B58\uFF1B\u7559\u7A7A\u4FDD\u6301\u4E0D\u53D8":"Stored securely; leave blank to keep it",\u6700\u5927\u5E76\u53D1:"Max concurrency","Heartbeat \u79D2\u6570":"Heartbeat seconds","Workspace \u6620\u5C04":"Workspace mappings","\u6BCF\u884C alias=/\u672C\u673A/\u7EDD\u5BF9\u8DEF\u5F84\uFF1BOffice \u53EA\u80FD\u770B\u5230 alias\u3002":"One alias=/local/absolute/path per line; Office sees only aliases.","Instruction Preset \u6620\u5C04":"Instruction preset mappings","\u6BCF\u884C alias=\u6307\u4EE4\uFF1B\u65B0\u589E preset \u4E0D\u9700\u8981\u6539 Office \u4EE3\u7801\u3002":"One alias=instruction per line; new presets require no Office code change.",\u4FDD\u5B58\u5E76\u8FDE\u63A5:"Save and connect",\u6D4B\u8BD5\u8FDE\u63A5:"Test connection","\u6D4B\u8BD5\u4E2D\u2026":"Testing\u2026",\u91CD\u65B0\u8FDE\u63A5:"Reconnect",\u79FB\u9664\u8FDE\u63A5:"Remove connection","\u8FDE\u63A5\u6D4B\u8BD5\u901A\u8FC7\u3002":"Connection test passed.","\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002":"Configuration saved.","\u534F\u8BAE Hook \u9884\u89C8":"Protocol hook preview","\u7531 Base URL \u81EA\u52A8\u6D3E\u751F\uFF0C\u4E0D\u5355\u72EC\u586B\u5199":"Derived from Base URL; no separate input","Base URL \u65E0\u6548":"Invalid Base URL","Office Hook \u5C1A\u672A\u90E8\u7F72\u65F6\uFF0C\u914D\u7F6E\u4F1A\u5B89\u5168\u4FDD\u5B58\u5E76\u81EA\u52A8\u91CD\u8BD5\uFF1B\u51FA\u73B0 HTTP 404 \u4EE3\u8868\u534F\u8BAE\u7AEF\u70B9\u5F85\u4E0A\u7EBF\uFF0C\u4E0D\u4EE3\u8868 Harness \u6545\u969C\u3002":"Configuration is saved and retried while Office hooks are unavailable; HTTP 404 means the protocol endpoint is pending, not a Harness failure.","Workspace \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each workspace mapping must use alias=value","Instruction Preset \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each instruction preset mapping must use alias=value","action-items=\u8F6C\u6362\u4E3A\u8D1F\u8D23\u4EBA\u3001\u622A\u6B62\u548C\u9A8C\u6536\u660E\u786E\u7684\u5DE5\u5355":"action-items=Turn this into accountable tasks with deadlines and acceptance criteria","AI Office \u62D2\u7EDD\u4E86 Device Token\u3002":"AI Office rejected the Device Token.","AI Office Connector Hook \u5C1A\u672A\u5C31\u7EEA\u3002":"AI Office Connector hooks are not available yet.","AI Office Connector \u534F\u8BAE\u7248\u672C\u4E0D\u517C\u5BB9\u3002":"The AI Office Connector protocol is incompatible.","\u672C\u673A\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE AI Office\u3002":"AI Office cannot currently be reached from this machine.","AI Office \u8FDE\u63A5\u5DF2\u4E2D\u65AD\u3002":"The AI Office connection was interrupted.","\u5E2E\u52A9\u4E0E\u53CD\u9988 \xB7 \u524D\u5F80 GitHub":"Help & feedback \xB7 Open GitHub","\u8BF7\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u9875\u9762\u4F1A\u5728\u5F53\u524D\u7AEF\u53E3\u91CD\u65B0\u6253\u5F00\uFF0C\u673A\u5668\u4EBA\u914D\u7F6E\u4E0D\u4F1A\u6539\u53D8\u3002":"The page will reopen on the current port. Your bot configuration will not change.","\u4F7F\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u5F53\u524D\u5730\u5740\u4E0E\u6D4F\u89C8\u5668\u7684\u672C\u673A\u8BF7\u6C42\u6821\u9A8C\u4E0D\u517C\u5BB9\u3002\u8BF7\u4F7F\u7528\u4E0A\u65B9\u6309\u94AE\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00\u3002":"This address is incompatible with the browser\u2019s local-request checks. Use the button above to reopen with localhost.",\u5FAE\u4FE1:"WeChat",\u98DE\u4E66:"Feishu",\u9489\u9489:"DingTalk",\u4F01\u4E1A\u5FAE\u4FE1:"WeCom",\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeChat bot",\u98DE\u4E66\u673A\u5668\u4EBA:"Feishu bot",\u9489\u9489\u673A\u5668\u4EBA:"DingTalk bot",\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeCom bot",QQ\u673A\u5668\u4EBA:"QQ bot",WhatsApp\u673A\u5668\u4EBA:"WhatsApp bot",WhatsApp\u8D26\u53F7:"WhatsApp account",\u5FAE\u4FE1\u8BBE\u7F6E:"WeChat settings",\u98DE\u4E66\u673A\u5668\u4EBA\u8BBE\u7F6E:"Feishu bot settings",\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F:"Group response mode","\u4EC5\u5728 @\u673A\u5668\u4EBA\u65F6\u54CD\u5E94\uFF08\u63A8\u8350\uFF09":"Only respond when @mentioned (recommended)",\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F:"Respond to all group messages","\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\uFF08\u9700\u98DE\u4E66\u654F\u611F\u6743\u9650\uFF09":"Respond to all group messages (requires a sensitive Feishu scope)",\u91CD\u65B0\u6388\u6743:"Reauthorize",\u53BB\u6388\u6743:"Authorize",\u91CD\u65B0\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Reauthorize group-message permission",\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Authorize group-message permission","\u6B63\u5728\u51C6\u5907\u6388\u6743\u2026":"Preparing authorization\u2026","\u6B63\u5728\u51C6\u5907\u2026":"Preparing\u2026","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u518D\u6B21\u5207\u6362\u65E0\u9700\u6388\u6743\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. The group-message permission is already granted, so switching again needs no authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u9009\u62E9\u5168\u90E8\u6D88\u606F\u540E\u4F1A\u6253\u5F00\u98DE\u4E66\u5B98\u65B9\u6388\u6743\u6D41\u7A0B\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. Selecting all messages opens the official Feishu authorization flow.","\u5DF2\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"The \u201CRead all messages in associated group chat\u201D scope (im:message.group_msg) is granted; the bot processes every visible group message.","\u5C1A\u672A\u786E\u8BA4\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF0C\u8BF7\u5B8C\u6210\u98DE\u4E66\u6388\u6743\u3002":"The \u201CRead all messages in associated group chat\u201D scope has not been confirmed. Complete Feishu authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002":"Direct messages always work; group chats require an explicit @mention of this bot.","\u9700\u5728\u98DE\u4E66\u4E3A\u8BE5\u673A\u5668\u4EBA\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u5F00\u901A\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"Grant this bot the \u201CRead all messages in associated group chat\u201D Feishu scope (im:message.group_msg); once granted, it will process every visible group message.","\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the group response mode. Try again.","\u7FA4\u6D88\u606F\u6743\u9650\u6388\u6743\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not authorize group-message permission. Try again.",\u9489\u9489\u8BBE\u7F6E:"DingTalk settings",\u4F01\u4E1A\u5FAE\u4FE1\u8BBE\u7F6E:"WeCom settings",\u626B\u7801\u63A5\u5165\u673A\u5668\u4EBA:"Scan QR code",\u6B63\u5728\u63A5\u5165:"Connecting",\u624B\u52A8\u63A5\u5165:"Manual setup",\u6536\u8D77\u51ED\u636E:"Hide credentials",\u6536\u8D77\u63A5\u5165:"Hide setup",\u63A5\u5165\u673A\u5668\u4EBA:"Connect bot",\u5F00\u59CB\u63A5\u5165:"Start setup",\u5728\u7EBF:"online",\u8FD0\u884C\u6B63\u5E38:"Connected",\u6B63\u5728\u8FDE\u63A5:"Connecting","\u6B63\u5728\u8FDE\u63A5\u2026":"Connecting\u2026",\u8FDE\u63A5\u672A\u5C31\u7EEA:"Not connected",\u8FDE\u63A5\u4E2D:"Connecting",\u8FDE\u63A5\u4E2D\u65AD:"Disconnected",\u9700\u8981\u5904\u7406:"Needs attention",\u72B6\u6001\u672A\u77E5:"Unknown status",\u79BB\u7EBF:"Offline",\u5DF2\u65AD\u5F00:"Disconnected",\u6D88\u606F\u901A\u9053:"Message channel",\u67E5\u770B\u6D88\u606F\u901A\u9053\u8BF4\u660E:"View message channel details",\u6700\u8FD1\u68C0\u67E5:"Last checked",\u6700\u8FD1\u4E00\u6761\u6D88\u606F\u5904\u7406\u5931\u8D25:"Latest message failed",\u9519\u8BEF\u7801:"Code",\u53C2\u8003\u53F7:"Reference",\u5F53\u524D\u5DE5\u4F5C\u533A:"Current workspace",\u9009\u62E9\u76EE\u5F55:"Choose folder",\u9009\u62E9\u673A\u5668\u4EBA\u5DE5\u4F5C\u533A\u76EE\u5F55:"Select bot workspace folder",\u5F53\u524D\u76EE\u5F55:"Current folder",\u4E3B\u76EE\u5F55:"Home",\u76F4\u63A5\u8F93\u5165\u8DEF\u5F84:"Enter a path directly","\u652F\u6301 Windows \u76D8\u7B26\u3001UNC \u4E0E POSIX \u7EDD\u5BF9\u8DEF\u5F84\u3002":"Supports Windows drives, UNC paths, and POSIX absolute paths.","\u8F93\u5165 Host \u4E0A\u7684\u5B8C\u6574\u7EDD\u5BF9\u8DEF\u5F84":"Enter a full absolute path on the Host",\u524D\u5F80:"Go","\u8BFB\u53D6\u4E2D\u2026":"Loading\u2026","\u6B63\u5728\u51C6\u5907\u76EE\u5F55\u9009\u62E9\u5668\u2026":"Preparing folder picker\u2026","\u6B63\u5728\u8BFB\u53D6\u76EE\u5F55\u2026":"Loading folders\u2026","\u8FD9\u4E2A\u76EE\u5F55\u4E2D\u6CA1\u6709\u5B50\u6587\u4EF6\u5939\u3002":"This folder has no subfolders.","\u6B64\u76EE\u5F55\u7684\u5B50\u6587\u4EF6\u5939\u8FC7\u591A\uFF0C\u4EC5\u663E\u793A\u524D\u4E00\u90E8\u5206\u3002":"This folder has too many subfolders; only the first group is shown.","\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not load the folder. Try again.",\u91CD\u8BD5:"Retry",\u663E\u793A\u9690\u85CF\u6587\u4EF6\u5939:"Show hidden folders","\u5207\u6362\u540E\u4F1A\u6E05\u9664\u8FD9\u4E2A\u673A\u5668\u4EBA\u7684\u65E7\u4F1A\u8BDD\u6620\u5C04\u3002":"Switching clears this bot\u2019s previous session mappings.","\u5207\u6362\u4E2D\u2026":"Switching\u2026",\u9009\u62E9\u6B64\u76EE\u5F55:"Select this folder",\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84:"Absolute workspace path","/\u7EDD\u5BF9\u8DEF\u5F84/\u5230/\u5DE5\u4F5C\u533A":"/absolute/path/to/workspace",\u4FEE\u6539:"Change",\u4FDD\u5B58:"Save","\u4FDD\u5B58\u4E2D\u2026":"Saving\u2026",\u672A\u8BBE\u7F6E:"Not set","\u5DE5\u4F5C\u533A\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the workspace. Try again.","\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Enter an absolute workspace path.","\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002":"The workspace must be an absolute path.","\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002":"The workspace path does not exist.","\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002":"The workspace path must point to a directory.","\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002":"The bot could not be found.","Agent Preset":"Agent Preset","\u67E5\u770B Agent Preset \u8BF4\u660E":"View Agent Preset help","\u8DDF\u968F Host \u9ED8\u8BA4":"Follow the Host default","\uFF08\u5DF2\u4E0D\u53EF\u7528\uFF09":" (unavailable)","\u53EA\u5F71\u54CD\u65B0\u5EFA\u4F1A\u8BDD\uFF1B\u82E5\u5F53\u524D\u804A\u5929\u5DF2\u6709\u4F1A\u8BDD\uFF0C\u5148\u53D1\u9001 /new\uFF0C\u518D\u53D1\u9001\u666E\u901A\u6D88\u606F\u751F\u6548\u3002":"This affects only new sessions. If the current chat already has a session, send /new, then send a regular message to apply it.","\u5F53\u524D Agent Preset \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u9009\u62E9\u5176\u4ED6 Preset \u6216\u8DDF\u968F Host \u9ED8\u8BA4\u3002":"The current Agent Preset is unavailable. Choose another preset or follow the Host default.","Agent Preset \u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the Agent Preset. Try again.","\u8BF7\u9009\u62E9 Agent Preset\u3002":"Choose an Agent Preset.","Agent Preset \u65E0\u6548\u3002":"The Agent Preset is invalid.","Agent Preset \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\u3002":"The Agent Preset does not exist or is unavailable.",\u5C1A\u672A\u68C0\u67E5:"Not checked yet",\u521A\u521A:"Just now",\u68C0\u67E5\u8FDE\u63A5:"Check connection","\u68C0\u67E5\u4E2D\u2026":"Checking\u2026","\u8FDE\u63A5\u68C0\u67E5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Connection check failed. Try again later.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230\u5BF9\u5E94\u673A\u5668\u4EBA\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the matching bot conversation.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\u3002\u673A\u5668\u4EBA\u5C1A\u672A\u6536\u5230\u53EF\u7528\u4E8E\u6D4B\u8BD5\u7684\u79C1\u804A\u6D88\u606F\u3002":"Connection check completed. The bot has not received a direct message it can use for testing.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"Connection check completed, but the test message could not be sent.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230\u98DE\u4E66\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the Feishu conversation.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230 WhatsApp \u81EA\u804A\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the WhatsApp self-chat.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684 WhatsApp \u81EA\u804A\u76EE\u6807\u3002":"Connection check completed, but no WhatsApp self-chat target is available.","\u9489\u9489\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"DingTalk connection check completed and the test message was sent.","\u9489\u9489\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"DingTalk connection check completed, but the test message could not be sent.","\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"WeChat connection check completed and the test message was sent.","\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"WeChat connection check completed, but the test message could not be sent.","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"WeCom connection check completed and the test message was sent.","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"WeCom connection check completed, but the test message could not be sent.",\u91CD\u8BD5\u8FDE\u63A5:"Reconnect","\u91CD\u8BD5\u4E2D\u2026":"Retrying\u2026",\u79FB\u9664\u63A5\u5165:"Remove connection",\u786E\u8BA4\u79FB\u9664\u63A5\u5165:"Remove connection",\u786E\u8BA4\u79FB\u9664:"Remove","\u6B63\u5728\u79FB\u9664\u2026":"Removing\u2026",\u4FDD\u7559\u673A\u5668\u4EBA:"Keep bot",\u4FDD\u7559\u8D26\u53F7:"Keep account",\u53D6\u6D88:"Cancel",\u5173\u95ED:"Close",\u7ACB\u5373\u91CD\u8BD5:"Retry now",\u91CD\u65B0\u8BFB\u53D6:"Reload",\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801:"Generate a new QR code",\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u540E\u7EE7\u7EED:"Generate a new QR code",\u5237\u65B0\u4E8C\u7EF4\u7801:"Refresh QR code","\u5237\u65B0\u4E2D\u2026":"Refreshing\u2026",\u6362\u4E00\u4E2A\u4E8C\u7EF4\u7801:"Get another QR code",\u7EE7\u7EED\u8FDE\u63A5:"Continue connecting",\u7ED1\u5B9A\u5E76\u8FDE\u63A5:"Connect","\u6B63\u5728\u7ED1\u5B9A\u2026":"Connecting\u2026",\u9A8C\u8BC1\u5E76\u8FDE\u63A5:"Verify and connect","\u6B63\u5728\u9A8C\u8BC1\u5E76\u8FDE\u63A5\u2026":"Verifying and connecting\u2026","\u6B63\u5728\u9A8C\u8BC1\u2026":"Verifying\u2026","\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"The operation failed. Try again later.",\u8BF7\u7A0D\u540E\u91CD\u8BD5:"Try again later.",\u5F53\u524D\u4E8C\u7EF4\u7801\u6709\u6548\u65F6\u95F4:"QR code expires in",\u4E8C\u7EF4\u7801\u6709\u6548\u65F6\u95F4:"QR code expires in",\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F:"QR code expired",\u4E8C\u7EF4\u7801\u5DF2\u5931\u6548:"QR code expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\n\u8BF7\u91CD\u65B0\u751F\u6210":`QR code expired +`,{encoding:"utf8",mode:384}),await K0e(o,this.#e)}};import{randomUUID as $V}from"node:crypto";var pv=new Set(["starting","qr_ready","polling","slow_down","domain_switched","saving"]),z0e=new Set(["polling","slow_down","domain_switched"]),wi=Object.freeze({IDLE:"idle",STARTING:"starting",QR_READY:"qr_ready",POLLING:"polling",SLOW_DOWN:"slow_down",DOMAIN_SWITCHED:"domain_switched",SAVING:"saving",SUCCEEDED:"succeeded",EXPIRED:"expired",CANCELLED:"cancelled",ERROR:"error"});function zV(n){return["access_denied","expired_token","abort"].includes(n?.code)?n.code:"registration_failed"}function dv(n){let t=zV(n);return{code:t,message:{access_denied:"Registration was denied.",abort:"Registration was cancelled.",expired_token:"The registration QR code expired."}[t]??"Unable to register the Feishu app."}}function V0e(n){let t=Number(n);if(!Number.isFinite(t)||t<=0)throw new TypeError("registerApp onQRCodeReady returned an invalid expireIn");return t}function W0e(n){if(n!==void 0){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError("registerApp returned invalid user_info");return{...n}}}var cg=class{#e;#A;#t;#r;#a;#i=0;#c=null;#s;constructor({registerApp:t,onCredentials:o,now:i=Date.now,setTimeout:e=globalThis.setTimeout,clearTimeout:a=globalThis.clearTimeout}={}){if(typeof t!="function")throw new TypeError("RegistrationManager requires a registerApp function");if(typeof o!="function")throw new TypeError("RegistrationManager requires an onCredentials function");if(typeof i!="function"||typeof e!="function"||typeof a!="function")throw new TypeError("RegistrationManager clock dependencies must be functions");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#a=a,this.#s=this.#o(null,wi.IDLE)}start(t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("Registration options must be an object");this.#f();let o={id:++this.#i,controller:new AbortController,qrCodeUrl:null,expiresAt:null,pollIntervalSeconds:null,expiryTimer:null};this.#c=o,this.#s=this.#o(o,wi.STARTING);let i={...t,signal:o.controller.signal,onQRCodeReady:a=>this.#g(o,a),onStatusChange:a=>this.#l(o,a)};return Promise.resolve().then(()=>this.#e(i)).then(a=>this.#p(o,a),a=>this.#d(o,a)),this.status()}status(){this.#h();let t={...this.#s};t.error&&(t.error={...t.error});let o=this.#c;return o&&o.expiresAt!==null&&pv.has(t.state)&&(t.remainingSeconds=Math.max(0,Math.ceil((o.expiresAt-this.#t())/1e3))),t}cancel(){let t=this.#c;return t?(this.#B(t,wi.CANCELLED,{error:{code:"abort",message:"Registration was cancelled."}}),t.controller.abort(),this.status()):this.status()}#I(t){return this.#c===t}#o(t,o,i={}){let e={state:o,attempt:t?.id??this.#i,updatedAt:this.#t(),...i};return t?.qrCodeUrl&&pv.has(o)&&(e.qrCodeUrl=t.qrCodeUrl,e.expiresAt=t.expiresAt),t?.pollIntervalSeconds!==null&&pv.has(o)&&(e.pollIntervalSeconds=t.pollIntervalSeconds),e}#n(t,o,i={}){this.#I(t)&&(this.#s=this.#o(t,o,i))}#g(t,o){if(!this.#I(t))return;if(typeof o?.url!="string"||!o.url)throw new TypeError("registerApp onQRCodeReady returned an invalid URL");let i=V0e(o.expireIn);t.qrCodeUrl=o.url,t.expiresAt=this.#t()+i*1e3,this.#u(t),t.expiryTimer=this.#r(()=>this.#E(t),i*1e3),t.expiryTimer?.unref?.(),this.#n(t,wi.QR_READY)}#l(t,o){!this.#I(t)||!z0e.has(o?.status)||(o.status===wi.SLOW_DOWN&&Number.isFinite(Number(o.interval))&&(t.pollIntervalSeconds=Number(o.interval)),this.#n(t,o.status))}async#p(t,o){if(!this.#I(t))return;let i=o?.client_id,e=o?.client_secret;if(typeof i!="string"||!i||typeof e!="string"||!e){this.#B(t,wi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}let a;try{a=W0e(o.user_info)}catch{this.#B(t,wi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}this.#u(t),t.qrCodeUrl=null,t.expiresAt=null,t.pollIntervalSeconds=null,this.#n(t,wi.SAVING);try{await this.#A({client_id:i,client_secret:e,user_info:a})}catch{this.#I(t)&&this.#B(t,wi.ERROR,{error:{code:"credentials_callback_failed",message:"Unable to store the Feishu credentials."}});return}this.#I(t)&&this.#B(t,wi.SUCCEEDED)}#d(t,o){if(!this.#I(t))return;let i=zV(o);if(i==="expired_token"){this.#B(t,wi.EXPIRED,{error:dv(o)});return}if(i==="abort"){this.#B(t,wi.CANCELLED,{error:dv(o)});return}this.#B(t,wi.ERROR,{error:dv(o)})}#h(){let t=this.#c;t&&t.expiresAt!==null&&this.#t()>=t.expiresAt&&this.#E(t)}#E(t){this.#I(t)&&(this.#B(t,wi.EXPIRED,{error:{code:"expired_token",message:"The registration QR code expired."}}),t.controller.abort())}#B(t,o,i={}){this.#I(t)&&(this.#u(t),this.#s=this.#o(t,o,i),this.#c=null)}#u(t){t.expiryTimer!==null&&(this.#a(t.expiryTimer),t.expiryTimer=null)}#f(){let t=this.#c;t&&(this.#u(t),this.#c=null,t.controller.abort())}};var Z0e="card.action.trigger",X0e="im:message:readonly",$0e="im:resource",qC="callback_repair";function eNe(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function ANe(n){return n==="lark"?"open.larksuite.com":"open.feishu.cn"}function hv(n,t,o="feishu",i="Feishu app update"){let e;try{e=new URL(n)}catch{throw new Error(`${i} returned an invalid verification URL`)}let a=o==="feishu"||o==="lark",A=e.searchParams.getAll("clientID"),r=e.searchParams.getAll("tp"),s=e.searchParams.getAll("addons"),g=String(t).includes("{{")||String(t).includes("}}")||[...e.searchParams.values()].some(c=>c.includes("{{")||c.includes("}}"));if(!a||e.protocol!=="https:"||e.hostname!==ANe(o)||e.port!==""||e.username!==""||e.password!==""||r.length!==1||r[0]!=="sdk"||A.length!==1||A[0]!==t||e.searchParams.has("createOnly")||s.length!==1||!s[0]?.trim()||g)throw new Error(`${i} returned an unsafe verification URL`);return e.toString()}function tNe(n,t,o="feishu"){return hv(n,t,o,"Feishu callback repair")}var Om=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new cg({registerApp:a=>t({...a,onQRCodeReady:A=>{tNe(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-card-action-repair",domain:eNe(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[X0e,$0e]},callbacks:{items:[Z0e]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var rNe="im:message.group_msg",Mm="group_message_permission";function aNe(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function iNe(n,t,o="feishu"){return hv(n,t,o,"Feishu group message permission update")}var bm=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new cg({registerApp:a=>t({...a,onQRCodeReady:A=>{iNe(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-group-message-permission",domain:aNe(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[rNe]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var VV=Object.freeze(["im:message.p2p_msg:readonly","im:message.group_at_msg:readonly","im:message:readonly","im:message:send_as_bot","im:message.reactions:write_only","im:message:recall","im:resource","cardkit:card:write"]);var Ev=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),_m=new Set([...Ev,"saving"]),WV=new Set([qC,Mm]),ZV="*",oNe=12e4,nNe=6e5;function eW(){return{ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1}}function Tm(n){return n?n.status:eW()}function Nm(n){return n.ready===!0&&n.feishuLongConnectionState==="connected"&&n.harnessReachable===!0}function AW(n){return n.length>12?`${n.slice(0,8)}\u2022\u2022\u2022\u2022${n.slice(-4)}`:"cli_\u2022\u2022\u2022\u2022"}function sNe(n){return{name:n.botName,appIdMasked:AW(n.appId),activated:n.activated,domain:n.domain}}function gNe({connected:n,error:t,connection:o}){return n?"connected":t||o.feishuLongConnectionState==="failed"?"error":"disconnected"}function cNe(){return`bot_${$V().replaceAll("-","")}`}function INe(){return`reg_${$V().replaceAll("-","")}`}function XV(n){return`DSH_FEISHU_APP_SECRET_${n.slice(4).toUpperCase()}`}function Rm(n){return JSON.stringify({id:n.id,appId:n.appId,secretRef:n.secretRef,ownerOpenIds:n.ownerOpenIds,domain:n.domain,botName:n.botName,botOpenId:n.botOpenId,activated:n.activated,groupResponseMode:Wi(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:n.connectedAt??null,createdAt:n.createdAt??null})}function km(n){return typeof n=="string"&&n.trim()?n.trim():null}var zC=class{#e;#A;#t;#r;#a;#i;#c;#s;#I=new Map;#o=new Map;#n=new Map;#g=new Map;#l=new Map;#p=null;#d=Promise.resolve();#h=new Map;#E=1;#B;#u=!1;constructor({registerApp:t,verifyApp:o,credentials:i,configStore:e,createRuntime:a,deleteState:A=async()=>{},createBotId:r=cNe,createRegistrationId:s=INe,callbackProbeTimeoutMs:g=oNe}){if(typeof t!="function")throw new Error("registerApp is required");if(typeof o!="function")throw new Error("verifyApp is required");if(!i)throw new Error("credentials service is required");if(!e||typeof e.list!="function")throw new Error("multi-bot config store is required");if(typeof a!="function")throw new Error("createRuntime is required");if(typeof A!="function")throw new Error("deleteState must be a function");if(!Number.isFinite(g)||g<=0||g>nNe)throw new TypeError("callbackProbeTimeoutMs must be between 1 and 600000ms");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#a=a,this.#i=A,this.#c=r,this.#s=s,this.#B=g}async initialize(){if(this.#u)return this.status();let t=this.#r.list(),o=!1;return await Promise.allSettled(t.map(i=>this.#N(i.id,async()=>{let e=Tm(this.#I.get(i.id));if(Nm(e)||e.feishuLongConnectionState==="connecting"||e.feishuLongConnectionState==="reconnecting")return;if(o=!0,i.deletionPending){this.#o.set(i.id,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"});return}let a;try{a=await this.#t.resolve(i.secretRef)}catch{this.#o.set(i.id,{code:"missing_credentials",message:"\u65E0\u6CD5\u8BFB\u53D6\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u3002"});return}if(!a?.value){this.#o.set(i.id,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"});return}try{await this.#b(i,a.value),this.#o.delete(i.id)}catch{this.#o.set(i.id,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}}))),o&&this.#O(),this.status()}startRegistration(){this.#T();let t=this.#s();if(typeof t!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t)||this.#n.has(t))throw new Error("Registration id generator returned an invalid or duplicate id");let o={id:t,manager:null,botId:null,createdNew:!1,cancelled:!1};return o.manager=new cg({registerApp:this.#e,onCredentials:i=>this.#v(()=>this.#M(o,i))}),this.#n.set(t,o),this.#p=t,this.#F(),o.manager.start({source:"deepseek-harness",createOnly:!0,appPreset:{name:"{user} \u7684\u5317\u6C47\u661F\u6CB3 AI \u52A9\u624B",desc:"\u8FDE\u63A5\u98DE\u4E66\u4E0E DeepSeek Harness\uFF0C\u5728\u804A\u5929\u4E2D\u4F7F\u7528\u4F01\u4E1A AI \u52A9\u624B\u3002"},addons:{preset:!1,scopes:{tenant:[...VV]},events:{items:{tenant:["im.message.receive_v1"]}},callbacks:{items:["card.action.trigger"]}}}),this.#O(),this.registrationStatus(t)}startCallbackRepair(t,{actorOpenId:o,chatId:i}={}){this.#T();let e=this.#k(t);if(e.deletionPending)throw new Error("Cannot repair a Feishu bot pending deletion");let a=this.#g.get(t),A=a?this.#n.get(a):null;if(A&&_m.has(A.manager.status().state)){if(A.operation!==qC)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(A.id)}this.#g.delete(t);let r=this.#s();if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(r)||this.#n.has(r))throw new Error("Registration id generator returned an invalid or duplicate id");let s={id:r,operation:qC,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(e),targetFingerprint:Rm(e),initiator:{actorOpenId:km(o),chatId:km(i)}};return s.manager=new Om({registerApp:this.#e,appId:e.appId,domain:e.domain,onCredentials:g=>{s.remoteCommitted=!0;let I=this.#Q(s,g).finally(()=>{s.processing===I&&(s.processing=null)});return s.processing=I,I}}),this.#n.set(r,s),this.#g.set(t,r),this.#p=r,this.#F(),s.manager.start(),this.#O(),this.registrationStatus(r)}startGroupMessagePermission(t){this.#T();let o=this.#k(t);if(o.deletionPending)throw new Error("Cannot update permissions for a Feishu bot pending deletion");let i=this.#g.get(t),e=i?this.#n.get(i):null;if(e&&_m.has(e.manager.status().state)){if(e.operation!==Mm)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(e.id)}this.#g.delete(t);let a=this.#s();if(typeof a!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(a)||this.#n.has(a))throw new Error("Registration id generator returned an invalid or duplicate id");let A={id:a,operation:Mm,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(o),targetFingerprint:Rm(o),initiator:{actorOpenId:null,chatId:null}};return A.manager=new bm({registerApp:this.#e,appId:o.appId,domain:o.domain,onCredentials:r=>{A.remoteCommitted=!0;let g=this.#y(A,r).finally(()=>{A.processing===g&&(A.processing=null)});return A.processing=g,g}}),this.#n.set(a,A),this.#g.set(t,a),this.#p=a,this.#F(),A.manager.start(),this.#O(),this.registrationStatus(a)}hasRegistration(t){return this.#n.has(t)}registrationStatus(t){let o=this.#n.get(t);return o?this.#f({registration:o,selectedBotId:o.botId}):null}async cancelRegistration(t=this.#p){let o=this.#n.get(t);if(!o)return this.status();let i=o.manager.status().state;return WV.has(o.operation)&&i==="saving"?this.registrationStatus(t):_m.has(i)?(o.cancelled=!0,o.manager.cancel(),await this.#v(async()=>{o.createdNew&&o.botId&&this.#l.get(o.botId)===o.id&&this.#r.getBot(o.botId)&&await this.#N(o.botId,()=>this.#_(o.botId))}),this.#O(),this.registrationStatus(t)??this.status()):this.registrationStatus(t)}status(t){return this.#f({registration:this.#n.get(this.#p)??null,selectedBotId:t})}async bindCredentials({appId:t,appSecret:o,domain:i="feishu"}={}){this.#T();let e=typeof t=="string"?t.trim():"",a=typeof o=="string"?o.trim():"",A=i==="lark"?"lark":"feishu";if(!e||!a)throw new TypeError("Feishu App ID and App Secret are required");return this.#v(async()=>{this.#T();let r=await this.#A({appId:e,appSecret:a,domain:A});this.#T();let s=this.#r.list().find(f=>f.appId===e),g=s?.id??this.#c();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??XV(g),I=await this.#t.resolve(c).catch(()=>{}),d={...s,id:g,appId:e,secretRef:c,ownerOpenIds:s?.ownerOpenIds?.length?s.ownerOpenIds:[ZV],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()};await this.#t.set(c,a);let B;try{B=await this.#r.saveBot(d)}catch(f){throw await this.#R(c,I),f}return await this.#N(g,async()=>{try{await this.#b(B,a),this.#o.delete(g)}catch{this.#o.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u7ED1\u5B9A\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"})}}),this.#O(),this.status(g)})}async reconnectBot(t){return this.#T(),this.#N(t,async()=>{let o=this.#k(t);if(o.deletionPending)return this.#o.set(t,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"}),this.status(t);if(Nm(Tm(this.#I.get(t))))return this.status(t);let i;try{i=await this.#t.resolve(o.secretRef)}catch{i=null}if(!i?.value)return this.#o.set(t,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"}),this.#O(),this.status(t);try{await this.#b(o,i.value),this.#o.delete(t)}catch{this.#o.set(t,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}return this.#O(),this.status(t)})}async sendConnectionTest(t){return this.#T(),this.#N(t,async()=>{let o=this.#k(t),i=this.#I.get(t);if(!Nm(Tm(i))||typeof i.sendConnectionTest!="function"){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return i.sendConnectionTest(Da(`${o.botName}\uFF08${AW(o.appId)}\uFF09`,"\u98DE\u4E66\u673A\u5668\u4EBA"))})}async disconnectBot(t){return this.#T(),this.#N(t,async()=>(this.#k(t),await this.#S(t),this.#o.delete(t),this.#O(),this.status(t)))}async updateGroupResponseMode(t,o){if(this.#T(),!lm(o))throw new TypeError("Invalid Feishu group response mode");return this.#v(()=>this.#N(t,async()=>{let i=this.#k(t);if(o==="all"&&i.groupMessagePermissionGranted!==!0){let a=new Error("Authorize im:message.group_msg before enabling all group messages");throw a.code="group_message_permission_required",a}let e=await this.#r.saveBot({...i,groupResponseMode:o});return this.#I.get(t)?.setGroupResponseMode?.(e.groupResponseMode),this.#O(),this.status(t)}))}async deleteBot(t){return this.#T(),this.#v(()=>this.#N(t,async()=>(this.#k(t),await this.#_(t),this.#O(),this.status())))}async reconnect(){let t=this.#r.list()[0];return t?this.reconnectBot(t.id):this.status()}async disconnect(){let t=this.#r.list()[0];return t?this.deleteBot(t.id):this.status()}async close(){if(this.#u)return;this.#u=!0;let t=[];for(let o of this.#n.values()){let i=o.manager.status().state;WV.has(o.operation)&&i==="saving"?(o.manager.cancel(),o.processing&&t.push(o.processing)):_m.has(i)&&(o.cancelled=!0,o.manager.cancel())}await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#S(o))),await Promise.allSettled(t),await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#S(o)))}#f({registration:t,selectedBotId:o}={}){let i=this.#r.list().map(I=>{let d=Tm(this.#I.get(I.id)),B=Nm(d),f=this.#o.get(I.id)??null;return{botId:I.id,phase:gNe({connected:B,error:f,connection:d}),connected:B,configured:!0,groupResponseMode:Wi(I.groupResponseMode),groupMessagePermissionGranted:I.groupMessagePermissionGranted===!0,bot:sNe(I),connection:d,lastMessageError:zr(d.lastMessageError),error:f}}),e=t?this.#m(t):{state:"idle",attempt:0,updatedAt:Date.now()},a=Ev.has(e.state),A=e.state==="saving",r=!!t&&(a||A),s=i.find(I=>I.botId===o)??(r?null:i[0]??null),g=i.some(I=>I.connected),c=s?.phase??"unconfigured";return a?c="registering":A?c="connecting":e.state==="error"&&!s&&(c="error"),{schemaVersion:2,revision:this.#E,phase:c,connected:s?.connected??!1,configured:i.length>0,bot:s?.bot??null,connection:s?.connection??eW(),error:s?.error??e.error??null,registration:e,bots:i,totals:{configured:i.length,connected:i.filter(I=>I.connected).length},anyConnected:g}}#m(t){let o=t.manager.status();return{...o,attempt:t.id,...t.botId?{botId:t.botId}:{},...t.operation?{operation:t.operation}:{},...t.stage?{stage:t.stage}:{},...o.state==="error"&&t.publicError?{error:{...t.publicError}}:{}}}async#y(t,o){let i=o.client_id,e=o.client_secret,a=km(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#C(t,"abort","Group message permission update was cancelled before local activation.");if(i!==r.appId)throw this.#C(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#C(t,"repair_owner_missing","Feishu returned no permission operator identity.");if(A!==void 0&&A!==r.domain)throw this.#C(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");if(!r.ownerOpenIds.includes(ZV)&&!r.ownerOpenIds.includes(a))throw this.#C(t,"repair_owner_mismatch","The Feishu permission operator is not an owner of this configured bot.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(g){throw this.#C(t,"repair_credentials_invalid","Feishu could not verify the updated app credentials.",g)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#C(t,"repair_bot_mismatch","The updated Feishu app belongs to a different bot identity.");await this.#v(()=>this.#N(t.botId,async()=>{let g=this.#r.getBot(t.botId);if(!g||g.deletionPending||Rm(g)!==t.targetFingerprint)throw this.#C(t,"repair_target_changed","The Feishu bot changed while its permission update was in progress.");let c;try{c=await this.#t.resolve(g.secretRef)}catch(d){throw this.#C(t,"credential_update_failed","Unable to read the current Feishu credential.",d)}if(c?.value!==e){t.stage="persisting_secret";try{await this.#t.set(g.secretRef,e)}catch(B){if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_update_failed","Unable to store the updated Feishu credential.",B)}if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_state_unknown","The updated Feishu credential could not be confirmed after writing.")}t.stage="enabling_all_messages";let I;try{I=await this.#r.saveBot({...g,groupMessagePermissionGranted:!0,groupResponseMode:"all"})}catch(d){throw this.#C(t,"group_message_permission_save_failed","The permission was accepted, but all-message mode could not be saved.",d)}t.stage="restarting";try{await this.#b(I,e)}catch(d){throw this.#o.set(t.botId,{code:"connection_failed",message:"\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u4F46\u673A\u5668\u4EBA\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#O(),this.#C(t,"group_message_permission_connection_failed","The permission was accepted, but the Feishu runtime could not restart.",d)}this.#o.delete(t.botId),t.stage="verified",t.publicError=null,this.#O()}))}async#Q(t,o){let i=o.client_id,e=o.client_secret,a=km(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#C(t,"abort","Callback repair was cancelled before local activation.");if(i!==r.appId)throw this.#C(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#C(t,"repair_owner_missing","Feishu returned no repair operator identity.");if(A!==void 0&&A!==r.domain)throw this.#C(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(c){throw this.#C(t,"repair_credentials_invalid","Feishu could not verify the repaired app credentials.",c)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#C(t,"repair_bot_mismatch","The repaired Feishu app belongs to a different bot identity.");let g=await this.#v(()=>this.#N(t.botId,async()=>{let c=this.#r.getBot(t.botId);if(!c||c.deletionPending||Rm(c)!==t.targetFingerprint)throw this.#C(t,"repair_target_changed","The Feishu bot changed while its callback repair was in progress.");let I;try{I=await this.#t.resolve(c.secretRef)}catch(f){throw this.#C(t,"credential_update_failed","Unable to read the current Feishu credential.",f)}if(I?.value!==e){t.stage="persisting_secret";try{await this.#t.set(c.secretRef,e)}catch(Q){if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_update_failed","Unable to store the repaired Feishu credential.",Q)}if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#C(t,"credential_state_unknown","The repaired Feishu credential could not be confirmed after writing.")}let B;t.stage="restarting";try{await this.#b(c,e),B=this.#I.get(t.botId)}catch(f){throw this.#o.set(t.botId,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u56DE\u8C03\u4FEE\u590D\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#O(),this.#C(t,"repair_connection_failed","The repaired Feishu runtime could not be started.",f)}if(!B)throw this.#C(t,"repair_connection_failed","The repaired Feishu runtime is unavailable.");return this.#o.delete(t.botId),this.#O(),B}));if(typeof g.beginCardActionProbe!="function")throw this.#C(t,"card_action_probe_unavailable","The Feishu runtime cannot verify card callbacks.");t.stage="awaiting_callback";try{if((await g.beginCardActionProbe({expectedOperatorOpenId:t.initiator.actorOpenId??a,timeoutMs:this.#B,...t.initiator.chatId?{chatId:t.initiator.chatId}:{}}))?.verified!==!0){let I=new Error("Feishu runtime returned no callback proof");throw I.code="card_action_probe_failed",I}}catch(c){let I=c?.code==="card_action_probe_timeout"?"card_action_probe_timeout":c?.code==="card_action_probe_unavailable"?"card_action_probe_unavailable":c?.code==="card_action_probe_send_failed"?"card_action_probe_send_failed":"card_action_probe_failed";throw this.#C(t,I,I==="card_action_probe_timeout"?"Timed out waiting for the Feishu callback verification button.":"The Feishu card callback probe failed.",c)}t.stage="verified",t.publicError=null,this.#O()}#C(t,o,i,e){t.publicError={code:o,message:i};let a=new Error(i,e?{cause:e}:void 0);return a.code=o,a}async#M(t,o){if(t.cancelled)throw new Error("Registration was cancelled");let i=o.client_id,e=o.client_secret,a=o.user_info?.open_id,A=o.user_info?.tenant_brand==="lark"?"lark":"feishu";if(!a)throw new Error("Feishu registration returned no owner open_id");let r=await this.#A({appId:i,appSecret:e,domain:A});if(t.cancelled)throw new Error("Registration was cancelled");let s=this.#r.list().find(Q=>Q.appId===i),g=s?.id??this.#c();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??XV(g),I=this.#l.get(g),d=await this.#t.resolve(c).catch(()=>{});await this.#t.set(c,e);let B;try{B=await this.#r.saveBot({...s,id:g,appId:i,secretRef:c,ownerOpenIds:[...new Set([...s?.ownerOpenIds??[],a])],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()}),t.botId=g,t.createdNew=!s,this.#l.set(g,t.id)}catch(Q){try{await this.#R(c,d)}catch(y){throw new Error("Unable to restore the Feishu credential after a config failure.",{cause:y})}throw Q}if(t.cancelled)throw t.createdNew?await this.#N(g,()=>this.#_(g)):(await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g)),new Error("Registration was cancelled");let f=!1;try{if(await this.#N(g,()=>this.#b(B,e)),t.cancelled)throw t.createdNew?await this.#N(g,()=>this.#_(g)):(await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g),d?.value&&!s.deletionPending?await this.#N(g,()=>this.#b(s,d.value)):await this.#N(g,()=>this.#S(g))),f=!0,new Error("Registration was cancelled");this.#o.delete(g),this.#O()}catch(Q){if(t.cancelled)throw!f&&t.createdNew&&this.#r.getBot(g)?await this.#N(g,()=>this.#_(g)):!f&&s&&(await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g),!this.#u&&d?.value&&!s.deletionPending?await this.#N(g,()=>this.#b(s,d.value)):await this.#N(g,()=>this.#S(g))),this.#O(),Q;if(s&&d?.value)try{throw await this.#r.saveBot(s),await this.#R(c,d),I?this.#l.set(g,I):this.#l.delete(g),s.deletionPending?(await this.#N(g,()=>this.#S(g)),this.#o.set(g,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"})):(await this.#N(g,()=>this.#b(s,d.value)),this.#o.delete(g)),this.#O(),Q}catch(y){throw y===Q?Q:(this.#o.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u8FDE\u63A5\u66F4\u65B0\u5931\u8D25\uFF0C\u4E14\u539F\u8FDE\u63A5\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002"}),this.#O(),new Error("Unable to restore the previous Feishu bot connection.",{cause:y}))}throw this.#o.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#O(),Q}}async#b(t,o){await this.#S(t.id);let i=await this.#a({botId:t.id,config:t,appSecret:o,repair:this.#w(t.id)});this.#I.set(t.id,i);try{await i.start()}catch(e){throw this.#I.get(t.id)===i&&this.#I.delete(t.id),await i.stop({preserveError:!0}).catch(()=>{}),e}}#w(t){let o=i=>{let e=this.#n.get(i);return e?.operation===qC&&e.botId===t?e:null};return Object.freeze({start:({actorOpenId:i,chatId:e}={})=>this.startCallbackRepair(t,{actorOpenId:i,chatId:e}),status:({attemptId:i}={})=>o(i)?this.registrationStatus(i):null,cancel:async({attemptId:i}={})=>o(i)?this.cancelRegistration(i):this.status(t)})}async#S(t){let o=this.#I.get(t);this.#I.delete(t),o&&await o.stop()}async#_(t){let o=this.#r.getBot(t);if(o){o.deletionPending||(o=await this.#r.saveBot({...o,deletionPending:!0})),await this.#S(t);try{await this.#t.unset(o.secretRef)}catch(i){throw this.#o.set(t,{code:"credential_removal_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu credential.",{cause:i})}try{await this.#i({botId:t,config:o})}catch(i){throw this.#o.set(t,{code:"state_cleanup_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u7684\u672C\u5730\u4F1A\u8BDD\u6570\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu bot session state.",{cause:i})}await this.#r.removeBot(t),this.#o.delete(t),this.#l.delete(t)}}async#R(t,o){o?.value?await this.#t.set(t,o.value):await this.#t.unset(t)}#k(t){let o=this.#r.getBot(t);if(!o)throw new Error("Unknown Feishu bot");return o}#T(){if(this.#u)throw new Error("The Feishu controller is closed")}#v(t){let o=this.#d.then(t,t);return this.#d=o.then(()=>{},()=>{}),o}#N(t,o){let e=(this.#h.get(t)??Promise.resolve()).then(o,o),a=e.then(()=>{},()=>{});return this.#h.set(t,a),a.finally(()=>{this.#h.get(t)===a&&this.#h.delete(t)}),e}#F(){if(!(this.#n.size<=32))for(let[t,o]of this.#n){if(t===this.#p)continue;let i=o.manager.status().state;if(!Ev.has(i)&&i!=="saving"&&this.#n.delete(t),this.#n.size<=32)break}}#O(){this.#E+=1}};function dNe(n){for(let t of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY"]){let o=n?.[t];if(typeof o=="string"&&o.trim())return o.trim()}}function hNe(n,t=o=>new tW.default(o)){let o=dNe(n);return o?t(o):void 0}function ENe(n){let t=Ic(n.dshHome??process.env.DSH_HOME??nd(lNe(),".dsh")),o=Ic(n.dataDir??nd(t,"integrations","dsh-feishu"));return{root:o,config:Ic(n.configPath??nd(o,"config.json")),legacyState:Ic(n.statePath??nd(o,"state.json")),bots:Ic(n.botsDir??nd(o,"bots")),workspaces:Ic(n.workspacesPath??nd(o,"workspaces.json"))}}async function Cv(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-feishu requires ctx.credentials");let i=$r(n,t),e=o.lark??Av,a=o.Controller??zC,A=o.ConfigStore??Dm,r=o.StateStore??cm,s=o.HarnessClient??mm,g=o.FeishuRuntime??ym,c=o.verifyFeishuApp??dV,I=fe=>c({...fe,httpInstance:e.defaultHttpInstance}),d=o.createConnectionSupervisor??tv,B=typeof n.logger=="function"?n.logger("dsh-feishu"):n.logger??console,f=()=>_a(n),Q=ENe(t),y=await new A(Q.config).load(),m=Ic(t.workspace??process.cwd()),_=o.WorkspaceStore??Xr,T=o.workspaces??await new _(Q.workspaces,{defaultWorkspace:m}).load(),R=typeof y.list=="function",H=()=>R?y.list():[],j=H();R&&await T.reconcile(j.map(fe=>fe.id)),await Promise.all(j.map(fe=>T.ensure(fe.id,{defaultAgentPreset:t.agentPreset})));let F=typeof y.removeBot=="function"?Ra(y,{workspaces:T,method:"removeBot",botIdFromRemoved:fe=>fe.id}):y,q=new Map,J=fe=>!fe.id||!fe.secretRef||fe.secretRef===wm?Q.legacyState:Ic(Q.bots,fe.id,"state.json"),x=async fe=>{let De=fe.id??"__legacy__",Ke=q.get(De);return Ke||(Ke=await new r(J(fe)).load(),q.set(De,Ke)),Ke},P=async fe=>{let De=H().find(Ke=>Ke.id===fe);if(!De)throw new Error("Unknown Feishu bot");return x(De)},z=Pa(n,o.commandExecutor),{controlExecutor:U,sessionMaintenanceExecutor:N,fileIngressExecutor:k}=Ga(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),V=new s({...i,workspace:m,autostart:!1,dshBin:t.dshBin??"dsh",...z?{commandExecutor:z}:{},...U?{controlExecutor:U}:{},...N?{sessionMaintenanceExecutor:N}:{},...k?{fileIngressExecutor:k}:{}}),ee=o.proxyEnv??process.env,ie=hNe(ee,o.createProxyAgent),Te=new a({registerApp:fe=>e.registerApp(fe),verifyApp:I,credentials:n.credentials,configStore:F,createRuntime:async({botId:fe,config:De,appSecret:Ke,repair:rA})=>{let ve=await x(De),iA=fe??De.id??De.appId;await T.ensure(iA,{defaultAgentPreset:t.agentPreset});let Ce=ka(V,{botId:iA,workspaces:T,state:ve,agentPresetCatalog:f});return new g({lark:e,botId:iA,repair:rA,appId:De.appId,appSecret:Ke,domain:De.domain,botOpenId:De.botOpenId,groupResponseMode:De.groupResponseMode,ownerOpenIds:De.ownerOpenIds??[De.ownerOpenId],harness:Ce.harness,state:Ce.state,replyTimeoutMs:t.replyTimeoutMs??6e5,...ie?{wsAgent:ie}:{},logger:{error:(...he)=>B.error?.(`[${fe??De.id}]`,...he),warn:(...he)=>B.warn?.(`[${fe??De.id}]`,...he),info:(...he)=>B.info?.(`[${fe??De.id}]`,...he),debug:(...he)=>B.debug?.(`[${fe??De.id}]`,...he)}})},deleteState:async({botId:fe,config:De})=>{q.delete(fe);try{await pNe(J(De))}catch(Ke){if(Ke?.code!=="ENOENT")throw Ke}}}),se=va(Te,{workspaces:T,stateFor:P,agentPresetCatalog:f}),Ne=d({controller:se,harness:V,logger:B,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:se,ready:Ne.ready,async close(){await Ne.close(),await se.close(),V.stopManagedProcess(),ie?.destroy?.()}}}import vNe from"qrcode";var gd=qe(Sv(),1);var NNe=qe(Sv(),1);var RNe=Object.freeze({$locale:"en",IM\u673A\u5668\u4EBA:"IM bots",IM\u673A\u5668\u4EBA\u8BBE\u7F6E:"IM bot settings","IM \u6E20\u9053":"IM channels","\u8BA9 DeepSeek Harness \u89E6\u624B\u53EF\u53CA":"Connecting DeepSeek Harness",\u5F53\u524D\u7248\u672C:"Current version","DSH-IM \u66F4\u65B0":"DSH-IM update",\u68C0\u67E5\u66F4\u65B0:"Check for updates",\u91CD\u65B0\u68C0\u67E5:"Check again",\u5237\u65B0\u72B6\u6001:"Refresh status",\u624B\u5DE5\u66F4\u65B0:"Manual update",\u624B\u5DE5\u66F4\u65B0\u547D\u4EE4:"Manual update command",\u590D\u5236\u547D\u4EE4:"Copy command","\u590D\u5236\u4E2D\u2026":"Copying\u2026",\u5DF2\u590D\u5236:"Copied","\u547D\u4EE4\u5DF2\u590D\u5236\u3002":"Command copied.","\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u9009\u4E2D\u547D\u4EE4\u540E\u6309 Ctrl+C \u6216 \u2318C \u590D\u5236\u3002":"Copy failed. Select the command and press Ctrl+C or \u2318C to copy it.","\u81EA\u52A8\u66F4\u65B0\u5931\u8D25\u53EF\u4EE5\u4F7F\u7528\u547D\u4EE4\u66F4\u65B0\uFF1A":"If the automatic update fails, update with this command:","\u5C1A\u672A\u786E\u8BA4\u76EE\u6807\u7248\u672C\uFF0C\u6B64\u547D\u4EE4\u5B89\u88C5\u6267\u884C\u65F6 npm \u7684 latest \u7248\u672C\u3002":"No target version has been confirmed. This command installs the npm latest version available when you run it.","\u8BF7\u5728\u5F53\u524D Desktop \u7684\u5185\u7F6E\u7EC8\u7AEF\u6267\u884C\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the current Desktop\u2019s built-in terminal, then restart manually.","\u8BF7\u5728\u8FD0\u884C\u5F53\u524D Harness \u7684\u540C\u4E00\u73AF\u5883\u6267\u884C\uFF0C\u4FDD\u6301 DSH_HOME \u4E00\u81F4\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the same environment as the current Harness, with the same DSH_HOME, then restart manually.","\u8BF7\u7B49\u5F85\u5F53\u524D\u64CD\u4F5C\u7ED3\u675F\uFF0C\u786E\u8BA4\u6CA1\u6709\u5B89\u88C5\u8FDB\u7A0B\u8FD0\u884C\u540E\u518D\u6267\u884C\u547D\u4EE4\u3002":"Wait for the current operation to finish and confirm no installer is running before using this command.","\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\u8BF7\u6309\u539F\u5B89\u88C5\u65B9\u5F0F\u66F4\u65B0\uFF0C\u4E0D\u63D0\u4F9B\u8986\u76D6\u6E90\u7801\u7684 npm \u547D\u4EE4\u3002":"Update source or linked installations using their original method. No npm command is provided to overwrite the source.","\u65E0\u6CD5\u5B89\u5168\u751F\u6210\u5F53\u524D profile \u7684\u547D\u4EE4\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u624B\u52A8\u786E\u8BA4 profile \u540E\u66F4\u65B0\u3002":"A safe command cannot be generated for this profile. Confirm the profile in your terminal before updating manually.",\u66F4\u65B0\u81F3:"Update to",\u5B89\u88C5\u66F4\u65B0:"Install update","\u6B63\u5728\u66F4\u65B0\u2026":"Updating\u2026",\u5F85\u624B\u52A8\u91CD\u542F:"Restart needed",\u8FD0\u884C\u7248\u672C:"Running version",\u5DF2\u5B89\u88C5\u7248\u672C:"Installed version","\u76EE\u6807 profile":"Target profile",\u76EE\u6807\u7248\u672C:"Target version",\u65E0\u6CD5\u786E\u8BA4:"Unknown",\u53D1\u73B0\u65B0\u7248\u672C:"Update available",\u5DF2\u662F\u6700\u65B0\u7248\u672C:"Up to date",\u5F53\u524D\u7248\u672C\u65E0\u9700\u66F4\u65B0:"No newer version available","\u5DF2\u83B7\u53D6 npm \u6700\u65B0\u7248\u672C":"Latest npm version retrieved","\u68C0\u67E5 npm \u6700\u65B0\u7248\u672C\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u5B89\u88C5\u3002":"Check the latest npm version. Nothing is installed automatically.","\u6B63\u5728\u4ECE npm \u68C0\u67E5\u6700\u65B0\u7248\u672C\u2026":"Checking npm for the latest version\u2026","\u6B63\u5728\u5B89\u88C5\uFF0C\u8BF7\u7A0D\u5019\u2026":"Installing, please wait\u2026","\u6B63\u5728\u6821\u9A8C\u5B89\u88C5\u7ED3\u679C\u2026":"Verifying the installation\u2026","\u5DF2\u5B89\u88C5\uFF0C\u5F85\u624B\u52A8\u91CD\u542F":"Installed \u2014 manual restart needed",\u66F4\u65B0\u5DF2\u751F\u6548:"Updated version is active",\u66F4\u65B0\u5931\u8D25:"Update failed",\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25:"Update request failed","\u4EC5\u66F4\u65B0 DSH-IM\u3002\u5B89\u88C5\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u540E\u53F0\uFF1B\u672C\u529F\u80FD\u4E0D\u4F1A\u81EA\u52A8\u91CD\u542F\u6216\u4E3B\u52A8\u5237\u65B0\u9875\u9762\u3002":"Only DSH-IM will be updated. Restart the backend manually after installation. This feature does not automatically restart it or initiate a page refresh.","\u5F53\u524D\u662F\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\uFF0C\u53EA\u80FD\u68C0\u67E5\u7248\u672C\uFF1B\u8BF7\u624B\u52A8\u66F4\u65B0\u6E90\u7801\uFF0C\u6216\u8FC1\u79FB\u5230 npm \u5B89\u88C5\u3002":"This is a source or linked installation. You can check versions, but must update the source manually or migrate to an npm installation.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D profile\uFF0C\u8BF7\u5728\u5BF9\u5E94\u7684 Harness \u73AF\u5883\u4E2D\u624B\u52A8\u66F4\u65B0\u3002":"The current profile could not be identified. Update manually in the corresponding Harness environment.","\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u4E0D\u652F\u6301\u6309\u94AE\u5B89\u88C5\uFF0C\u8BF7\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u3002":"This runtime cannot install through this button. Update the plugin manually.","\u5F53\u524D npm \u6E90\u914D\u7F6E\u4E0E\u5B98\u65B9\u6E90\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u5148\u68C0\u67E5 registry \u914D\u7F6E\u3002":"The npm registry configuration differs from the official registry. Check your registry settings first.","\u5F53\u524D Host \u7684 Node.js \u7248\u672C\u4E0D\u6EE1\u8DB3\u65B0\u7248\u8981\u6C42\uFF0C\u8BF7\u5148\u66F4\u65B0\u8FD0\u884C\u73AF\u5883\u3002":"The Host Node.js version does not meet the new version\u2019s requirements. Update the runtime first.","\u65B0\u7248\u672C\u5DF2\u5B89\u88C5\uFF0C\u8BF7\u5728\u65B9\u4FBF\u65F6\u624B\u52A8\u91CD\u542F\u5F53\u524D Harness \u6216 Desktop\u3002":"The new version is installed. Manually restart this Harness or Desktop when convenient.","\u4E0A\u6B21\u5B89\u88C5\u7ED3\u679C\u65E0\u6CD5\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u6B64 profile \u7684\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u3002":"The previous installation result is uncertain. Check this profile\u2019s plugin installation first.","\u65E0\u6CD5\u8BBF\u95EE npm \u6216\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u68C0\u67E5\u3002":"npm is unreachable or the request timed out. Check again later.","npm \u8FD4\u56DE\u7684\u7248\u672C\u4FE1\u606F\u65E0\u6548\uFF0C\u6682\u65F6\u65E0\u6CD5\u66F4\u65B0\u3002":"npm returned invalid release information. Updating is unavailable.","\u7248\u672C\u786E\u8BA4\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u540E\u518D\u5B89\u88C5\u3002":"The version confirmation expired. Check again before installing.","\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u3002":"The plugin installation changed. Check again.","\u6B64 profile \u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u67E5\u770B\u72B6\u6001\u3002":"This profile is already updating. Check its status shortly.","\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"Installation failed. Check the current installation before retrying.","\u5B89\u88C5\u7ED3\u679C\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u63D2\u4EF6\u7248\u672C\u3002":"Installation verification failed. Check the plugin version manually.","\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u66F4\u65B0\u72B6\u6001\uFF0C\u8BF7\u5148\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u7ED3\u679C\u3002":"Update state could not be saved safely. Check the current installation result before retrying.","\u4E0A\u6B21\u66F4\u65B0\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u68C0\u67E5\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"The previous update was interrupted. Check the installation before retrying.","\u66F4\u65B0\u670D\u52A1\u5DF2\u5173\u95ED\uFF0C\u8BF7\u624B\u52A8\u91CD\u65B0\u6253\u5F00\u8BBE\u7F6E\u9875\u3002":"The update service has closed. Reopen settings manually.","\u66F4\u65B0\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u7248\u672C\u3002":"The update request is invalid. Check the version again.","\u5F53\u524D\u63D2\u4EF6\u5B89\u88C5\u4E0D\u5B8C\u6574\u6216\u4E0E profile \u4E0D\u7B26\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u5B89\u88C5\u914D\u7F6E\u3002":"The plugin installation is incomplete or does not match this profile. Check the installation configuration manually.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D npm \u6E90\u914D\u7F6E\uFF0C\u6682\u65F6\u4E0D\u80FD\u5B89\u88C5\u66F4\u65B0\u3002":"The npm registry configuration could not be verified. Installation is unavailable.","\u5B89\u88C5\u8D85\u65F6\uFF0C\u8BF7\u5148\u786E\u8BA4\u5F53\u524D\u5B89\u88C5\u72B6\u6001\uFF0C\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\u3002":"Installation timed out. Check the current installation before retrying.","\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"The update request failed. Try again.","\u66F4\u65B0\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002":"The update service returned an unrecognized response.","\u5F53\u524D Host \u4E0D\u652F\u6301\u66F4\u65B0\u63A5\u53E3\uFF0C\u8BF7\u5148\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u5E76\u91CD\u542F\u3002":"This Host does not support the update API. Update the plugin manually and restart first.","\u5173\u95ED\u7A97\u53E3\u4E0D\u4F1A\u53D6\u6D88\u5B89\u88C5\u3002\u8BF7\u52FF\u540C\u65F6\u5728\u5176\u4ED6\u7A97\u53E3\u7BA1\u7406\u6B64 profile \u7684\u63D2\u4EF6\u3002":"Closing this window does not cancel installation. Do not manage this profile\u2019s plugins in another window at the same time.","\u9875\u9762\u7248\u672C\u4E0E\u8FD0\u884C\u7248\u672C\u4E0D\u540C\uFF0C\u8BF7\u624B\u52A8\u5237\u65B0\u9875\u9762\uFF1B\u82E5\u4ECD\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u624B\u52A8\u91CD\u542F Harness \u6216 Desktop\u3002":"The page and running versions differ. Refresh the page manually; if they still differ, manually restart Harness or Desktop.","\u8BF7\u5728\u673A\u5668\u4EBA\u7A7A\u95F2\u65F6\u5B89\u88C5\uFF1B\u5B89\u88C5\u4F1A\u4FEE\u6539\u5F53\u524D profile \u7684\u4F9D\u8D56\uFF0C\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u3002":"Install while bots are idle. This changes the current profile\u2019s dependencies and requires a manual restart afterward.","AI Office":"AI Office","\uFF08\u5B9E\u9A8C\u529F\u80FD\uFF09":"(Experimental)","AI Office \u8BBE\u7F6E":"AI Office settings","AI Office \u8BBE\u7F6E\u9875\u7F3A\u5C11 RPC \u8FDE\u63A5":"AI Office settings are missing an RPC connection","\u6B63\u5728\u8BFB\u53D6 AI Office Connector\u2026":"Loading AI Office Connector\u2026","\u672C\u673A\u4E3B\u52A8\u8FDE\u63A5\u516C\u7F51 Office\uFF1BHarness \u4E0D\u5F00\u653E\u7AEF\u53E3\u3002\u534F\u8BAE Hook \u56FA\u5B9A\u4E3A ":"This machine connects outward to the public Office; Harness exposes no port. Protocol hooks: ",\u5C1A\u672A\u914D\u7F6E:"Not configured","\u5DF2\u8FDE\u63A5 Office":"Connected to Office",\u5DF2\u914D\u7F6E:"Configured",\u7B49\u5F85\u91CD\u8FDE:"Waiting to reconnect",\u51ED\u636E\u7F3A\u5931:"Credential missing",\u6700\u8FD1\u5FC3\u8DF3:"Last heartbeat",\u6700\u8FD1\u4E8B\u4EF6:"Last event",\u91CD\u8FDE\u6B21\u6570:"Reconnects","\u8FD0\u884C Job":"Running Jobs","\u5B8C\u6210 Job":"Completed Jobs",\u5C1A\u65E0:"None yet",\u8BBE\u5907\u8FDE\u63A5:"Device connection","Token \u53EA\u5199\u5165\u672C\u673A\u51ED\u636E\u5B58\u50A8":"Token is written only to the local credential store","\u7C98\u8D34 Office \u4E00\u6B21\u6027\u51ED\u636E":"Paste the one-time Office credential","\u5DF2\u5B89\u5168\u4FDD\u5B58\uFF1B\u7559\u7A7A\u4FDD\u6301\u4E0D\u53D8":"Stored securely; leave blank to keep it",\u6700\u5927\u5E76\u53D1:"Max concurrency","Heartbeat \u79D2\u6570":"Heartbeat seconds","Workspace \u6620\u5C04":"Workspace mappings","\u6BCF\u884C alias=/\u672C\u673A/\u7EDD\u5BF9\u8DEF\u5F84\uFF1BOffice \u53EA\u80FD\u770B\u5230 alias\u3002":"One alias=/local/absolute/path per line; Office sees only aliases.","Instruction Preset \u6620\u5C04":"Instruction preset mappings","\u6BCF\u884C alias=\u6307\u4EE4\uFF1B\u65B0\u589E preset \u4E0D\u9700\u8981\u6539 Office \u4EE3\u7801\u3002":"One alias=instruction per line; new presets require no Office code change.",\u4FDD\u5B58\u5E76\u8FDE\u63A5:"Save and connect",\u6D4B\u8BD5\u8FDE\u63A5:"Test connection","\u6D4B\u8BD5\u4E2D\u2026":"Testing\u2026",\u91CD\u65B0\u8FDE\u63A5:"Reconnect",\u79FB\u9664\u8FDE\u63A5:"Remove connection","\u8FDE\u63A5\u6D4B\u8BD5\u901A\u8FC7\u3002":"Connection test passed.","\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002":"Configuration saved.","\u534F\u8BAE Hook \u9884\u89C8":"Protocol hook preview","\u7531 Base URL \u81EA\u52A8\u6D3E\u751F\uFF0C\u4E0D\u5355\u72EC\u586B\u5199":"Derived from Base URL; no separate input","Base URL \u65E0\u6548":"Invalid Base URL","Office Hook \u5C1A\u672A\u90E8\u7F72\u65F6\uFF0C\u914D\u7F6E\u4F1A\u5B89\u5168\u4FDD\u5B58\u5E76\u81EA\u52A8\u91CD\u8BD5\uFF1B\u51FA\u73B0 HTTP 404 \u4EE3\u8868\u534F\u8BAE\u7AEF\u70B9\u5F85\u4E0A\u7EBF\uFF0C\u4E0D\u4EE3\u8868 Harness \u6545\u969C\u3002":"Configuration is saved and retried while Office hooks are unavailable; HTTP 404 means the protocol endpoint is pending, not a Harness failure.","Workspace \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each workspace mapping must use alias=value","Instruction Preset \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each instruction preset mapping must use alias=value","action-items=\u8F6C\u6362\u4E3A\u8D1F\u8D23\u4EBA\u3001\u622A\u6B62\u548C\u9A8C\u6536\u660E\u786E\u7684\u5DE5\u5355":"action-items=Turn this into accountable tasks with deadlines and acceptance criteria","AI Office \u62D2\u7EDD\u4E86 Device Token\u3002":"AI Office rejected the Device Token.","AI Office Connector Hook \u5C1A\u672A\u5C31\u7EEA\u3002":"AI Office Connector hooks are not available yet.","AI Office Connector \u534F\u8BAE\u7248\u672C\u4E0D\u517C\u5BB9\u3002":"The AI Office Connector protocol is incompatible.","\u672C\u673A\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE AI Office\u3002":"AI Office cannot currently be reached from this machine.","AI Office \u8FDE\u63A5\u5DF2\u4E2D\u65AD\u3002":"The AI Office connection was interrupted.","\u5E2E\u52A9\u4E0E\u53CD\u9988 \xB7 \u524D\u5F80 GitHub":"Help & feedback \xB7 Open GitHub","\u8BF7\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u9875\u9762\u4F1A\u5728\u5F53\u524D\u7AEF\u53E3\u91CD\u65B0\u6253\u5F00\uFF0C\u673A\u5668\u4EBA\u914D\u7F6E\u4E0D\u4F1A\u6539\u53D8\u3002":"The page will reopen on the current port. Your bot configuration will not change.","\u4F7F\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u5F53\u524D\u5730\u5740\u4E0E\u6D4F\u89C8\u5668\u7684\u672C\u673A\u8BF7\u6C42\u6821\u9A8C\u4E0D\u517C\u5BB9\u3002\u8BF7\u4F7F\u7528\u4E0A\u65B9\u6309\u94AE\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00\u3002":"This address is incompatible with the browser\u2019s local-request checks. Use the button above to reopen with localhost.",\u5FAE\u4FE1:"WeChat",\u98DE\u4E66:"Feishu",\u9489\u9489:"DingTalk",\u4F01\u4E1A\u5FAE\u4FE1:"WeCom",\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeChat bot",\u98DE\u4E66\u673A\u5668\u4EBA:"Feishu bot",\u9489\u9489\u673A\u5668\u4EBA:"DingTalk bot",\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeCom bot",QQ\u673A\u5668\u4EBA:"QQ bot",WhatsApp\u673A\u5668\u4EBA:"WhatsApp bot",WhatsApp\u8D26\u53F7:"WhatsApp account",\u5FAE\u4FE1\u8BBE\u7F6E:"WeChat settings",\u98DE\u4E66\u673A\u5668\u4EBA\u8BBE\u7F6E:"Feishu bot settings",\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F:"Group response mode","\u4EC5\u5728 @\u673A\u5668\u4EBA\u65F6\u54CD\u5E94\uFF08\u63A8\u8350\uFF09":"Only respond when @mentioned (recommended)",\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F:"Respond to all group messages","\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\uFF08\u9700\u98DE\u4E66\u654F\u611F\u6743\u9650\uFF09":"Respond to all group messages (requires a sensitive Feishu scope)",\u91CD\u65B0\u6388\u6743:"Reauthorize",\u53BB\u6388\u6743:"Authorize",\u91CD\u65B0\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Reauthorize group-message permission",\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Authorize group-message permission","\u6B63\u5728\u51C6\u5907\u6388\u6743\u2026":"Preparing authorization\u2026","\u6B63\u5728\u51C6\u5907\u2026":"Preparing\u2026","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u518D\u6B21\u5207\u6362\u65E0\u9700\u6388\u6743\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. The group-message permission is already granted, so switching again needs no authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u9009\u62E9\u5168\u90E8\u6D88\u606F\u540E\u4F1A\u6253\u5F00\u98DE\u4E66\u5B98\u65B9\u6388\u6743\u6D41\u7A0B\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. Selecting all messages opens the official Feishu authorization flow.","\u5DF2\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"The \u201CRead all messages in associated group chat\u201D scope (im:message.group_msg) is granted; the bot processes every visible group message.","\u5C1A\u672A\u786E\u8BA4\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF0C\u8BF7\u5B8C\u6210\u98DE\u4E66\u6388\u6743\u3002":"The \u201CRead all messages in associated group chat\u201D scope has not been confirmed. Complete Feishu authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002":"Direct messages always work; group chats require an explicit @mention of this bot.","\u9700\u5728\u98DE\u4E66\u4E3A\u8BE5\u673A\u5668\u4EBA\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u5F00\u901A\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"Grant this bot the \u201CRead all messages in associated group chat\u201D Feishu scope (im:message.group_msg); once granted, it will process every visible group message.","\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the group response mode. Try again.","\u7FA4\u6D88\u606F\u6743\u9650\u6388\u6743\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not authorize group-message permission. Try again.",\u9489\u9489\u8BBE\u7F6E:"DingTalk settings",\u4F01\u4E1A\u5FAE\u4FE1\u8BBE\u7F6E:"WeCom settings",\u626B\u7801\u63A5\u5165\u673A\u5668\u4EBA:"Scan QR code",\u6B63\u5728\u63A5\u5165:"Connecting",\u624B\u52A8\u63A5\u5165:"Manual setup",\u6536\u8D77\u51ED\u636E:"Hide credentials",\u6536\u8D77\u63A5\u5165:"Hide setup",\u63A5\u5165\u673A\u5668\u4EBA:"Connect bot",\u5F00\u59CB\u63A5\u5165:"Start setup",\u5728\u7EBF:"online",\u8FD0\u884C\u6B63\u5E38:"Connected",\u6B63\u5728\u8FDE\u63A5:"Connecting","\u6B63\u5728\u8FDE\u63A5\u2026":"Connecting\u2026",\u8FDE\u63A5\u672A\u5C31\u7EEA:"Not connected",\u8FDE\u63A5\u4E2D:"Connecting",\u8FDE\u63A5\u4E2D\u65AD:"Disconnected",\u9700\u8981\u5904\u7406:"Needs attention",\u72B6\u6001\u672A\u77E5:"Unknown status",\u79BB\u7EBF:"Offline",\u5DF2\u65AD\u5F00:"Disconnected",\u6D88\u606F\u901A\u9053:"Message channel",\u67E5\u770B\u6D88\u606F\u901A\u9053\u8BF4\u660E:"View message channel details",\u6700\u8FD1\u68C0\u67E5:"Last checked",\u6700\u8FD1\u4E00\u6761\u6D88\u606F\u5904\u7406\u5931\u8D25:"Latest message failed",\u9519\u8BEF\u7801:"Code",\u53C2\u8003\u53F7:"Reference",\u5F53\u524D\u5DE5\u4F5C\u533A:"Current workspace",\u9009\u62E9\u76EE\u5F55:"Choose folder",\u9009\u62E9\u673A\u5668\u4EBA\u5DE5\u4F5C\u533A\u76EE\u5F55:"Select bot workspace folder",\u5F53\u524D\u76EE\u5F55:"Current folder",\u4E3B\u76EE\u5F55:"Home",\u76F4\u63A5\u8F93\u5165\u8DEF\u5F84:"Enter a path directly","\u652F\u6301 Windows \u76D8\u7B26\u3001UNC \u4E0E POSIX \u7EDD\u5BF9\u8DEF\u5F84\u3002":"Supports Windows drives, UNC paths, and POSIX absolute paths.","\u8F93\u5165 Host \u4E0A\u7684\u5B8C\u6574\u7EDD\u5BF9\u8DEF\u5F84":"Enter a full absolute path on the Host",\u524D\u5F80:"Go","\u8BFB\u53D6\u4E2D\u2026":"Loading\u2026","\u6B63\u5728\u51C6\u5907\u76EE\u5F55\u9009\u62E9\u5668\u2026":"Preparing folder picker\u2026","\u6B63\u5728\u8BFB\u53D6\u76EE\u5F55\u2026":"Loading folders\u2026","\u8FD9\u4E2A\u76EE\u5F55\u4E2D\u6CA1\u6709\u5B50\u6587\u4EF6\u5939\u3002":"This folder has no subfolders.","\u6B64\u76EE\u5F55\u7684\u5B50\u6587\u4EF6\u5939\u8FC7\u591A\uFF0C\u4EC5\u663E\u793A\u524D\u4E00\u90E8\u5206\u3002":"This folder has too many subfolders; only the first group is shown.","\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not load the folder. Try again.",\u91CD\u8BD5:"Retry",\u663E\u793A\u9690\u85CF\u6587\u4EF6\u5939:"Show hidden folders","\u5207\u6362\u540E\u4F1A\u6E05\u9664\u8FD9\u4E2A\u673A\u5668\u4EBA\u7684\u65E7\u4F1A\u8BDD\u6620\u5C04\u3002":"Switching clears this bot\u2019s previous session mappings.","\u5207\u6362\u4E2D\u2026":"Switching\u2026",\u9009\u62E9\u6B64\u76EE\u5F55:"Select this folder",\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84:"Absolute workspace path","/\u7EDD\u5BF9\u8DEF\u5F84/\u5230/\u5DE5\u4F5C\u533A":"/absolute/path/to/workspace",\u4FEE\u6539:"Change",\u4FDD\u5B58:"Save","\u4FDD\u5B58\u4E2D\u2026":"Saving\u2026",\u672A\u8BBE\u7F6E:"Not set","\u5DE5\u4F5C\u533A\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the workspace. Try again.","\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Enter an absolute workspace path.","\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002":"The workspace must be an absolute path.","\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002":"The workspace path does not exist.","\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002":"The workspace path must point to a directory.","\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002":"The bot could not be found.","Agent Preset":"Agent Preset","\u67E5\u770B Agent Preset \u8BF4\u660E":"View Agent Preset help","\u8DDF\u968F Host \u9ED8\u8BA4":"Follow the Host default","\uFF08\u5DF2\u4E0D\u53EF\u7528\uFF09":" (unavailable)","\u53EA\u5F71\u54CD\u65B0\u5EFA\u4F1A\u8BDD\uFF1B\u82E5\u5F53\u524D\u804A\u5929\u5DF2\u6709\u4F1A\u8BDD\uFF0C\u5148\u53D1\u9001 /new\uFF0C\u518D\u53D1\u9001\u666E\u901A\u6D88\u606F\u751F\u6548\u3002":"This affects only new sessions. If the current chat already has a session, send /new, then send a regular message to apply it.","\u5F53\u524D Agent Preset \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u9009\u62E9\u5176\u4ED6 Preset \u6216\u8DDF\u968F Host \u9ED8\u8BA4\u3002":"The current Agent Preset is unavailable. Choose another preset or follow the Host default.","Agent Preset \u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the Agent Preset. Try again.","\u8BF7\u9009\u62E9 Agent Preset\u3002":"Choose an Agent Preset.","Agent Preset \u65E0\u6548\u3002":"The Agent Preset is invalid.","Agent Preset \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\u3002":"The Agent Preset does not exist or is unavailable.",\u5C1A\u672A\u68C0\u67E5:"Not checked yet",\u521A\u521A:"Just now",\u68C0\u67E5\u8FDE\u63A5:"Check connection","\u68C0\u67E5\u4E2D\u2026":"Checking\u2026","\u8FDE\u63A5\u68C0\u67E5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Connection check failed. Try again later.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230\u5BF9\u5E94\u673A\u5668\u4EBA\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the matching bot conversation.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\u3002\u673A\u5668\u4EBA\u5C1A\u672A\u6536\u5230\u53EF\u7528\u4E8E\u6D4B\u8BD5\u7684\u79C1\u804A\u6D88\u606F\u3002":"Connection check completed. The bot has not received a direct message it can use for testing.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"Connection check completed, but the test message could not be sent.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230\u98DE\u4E66\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the Feishu conversation.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230 WhatsApp \u81EA\u804A\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the WhatsApp self-chat.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684 WhatsApp \u81EA\u804A\u76EE\u6807\u3002":"Connection check completed, but no WhatsApp self-chat target is available.","\u9489\u9489\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"DingTalk connection check completed and the test message was sent.","\u9489\u9489\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"DingTalk connection check completed, but the test message could not be sent.","\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"WeChat connection check completed and the test message was sent.","\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"WeChat connection check completed, but the test message could not be sent.","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"WeCom connection check completed and the test message was sent.","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"WeCom connection check completed, but the test message could not be sent.",\u91CD\u8BD5\u8FDE\u63A5:"Reconnect","\u91CD\u8BD5\u4E2D\u2026":"Retrying\u2026",\u79FB\u9664\u63A5\u5165:"Remove connection",\u786E\u8BA4\u79FB\u9664\u63A5\u5165:"Remove connection",\u786E\u8BA4\u79FB\u9664:"Remove","\u6B63\u5728\u79FB\u9664\u2026":"Removing\u2026",\u4FDD\u7559\u673A\u5668\u4EBA:"Keep bot",\u4FDD\u7559\u8D26\u53F7:"Keep account",\u53D6\u6D88:"Cancel",\u5173\u95ED:"Close",\u7ACB\u5373\u91CD\u8BD5:"Retry now",\u91CD\u65B0\u8BFB\u53D6:"Reload",\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801:"Generate a new QR code",\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u540E\u7EE7\u7EED:"Generate a new QR code",\u5237\u65B0\u4E8C\u7EF4\u7801:"Refresh QR code","\u5237\u65B0\u4E2D\u2026":"Refreshing\u2026",\u6362\u4E00\u4E2A\u4E8C\u7EF4\u7801:"Get another QR code",\u7EE7\u7EED\u8FDE\u63A5:"Continue connecting",\u7ED1\u5B9A\u5E76\u8FDE\u63A5:"Connect","\u6B63\u5728\u7ED1\u5B9A\u2026":"Connecting\u2026",\u9A8C\u8BC1\u5E76\u8FDE\u63A5:"Verify and connect","\u6B63\u5728\u9A8C\u8BC1\u5E76\u8FDE\u63A5\u2026":"Verifying and connecting\u2026","\u6B63\u5728\u9A8C\u8BC1\u2026":"Verifying\u2026","\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"The operation failed. Try again later.",\u8BF7\u7A0D\u540E\u91CD\u8BD5:"Try again later.",\u5F53\u524D\u4E8C\u7EF4\u7801\u6709\u6548\u65F6\u95F4:"QR code expires in",\u4E8C\u7EF4\u7801\u6709\u6548\u65F6\u95F4:"QR code expires in",\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F:"QR code expired",\u4E8C\u7EF4\u7801\u5DF2\u5931\u6548:"QR code expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\n\u8BF7\u91CD\u65B0\u751F\u6210":`QR code expired Generate a new one`,"\u4E8C\u7EF4\u7801\u56FE\u7247\u6B63\u5728\u751F\u6210\u2026":"Generating QR code\u2026","\u4E8C\u7EF4\u7801\u6B63\u5728\u751F\u6210\u2026":"Generating QR code\u2026","\u4E8C\u7EF4\u7801\u6B63\u5728\u81EA\u52A8\u5237\u65B0\u2026":"Refreshing QR code\u2026","\u4E8C\u7EF4\u7801\u672A\u5C31\u7EEA\uFF0C\u8BF7\u6253\u5F00\u6388\u6743\u94FE\u63A5":"The QR code is not ready. Open the authorization link.","\u4E8C\u7EF4\u7801\u56FE\u7247\u672A\u5C31\u7EEA\uFF0C\u8BF7\u4F7F\u7528\u5907\u7528\u94FE\u63A5\u3002":"The QR code is not ready. Use the alternate link.","\u4E8C\u7EF4\u7801\u56FE\u7247\u672A\u5C31\u7EEA\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002":"The QR code is not ready. Generate a new one.",\u7B49\u5F85\u5237\u65B0:"Waiting to refresh",\u6B63\u5728\u5237\u65B0\u4E8C\u7EF4\u7801:"Refreshing QR code",\u6253\u5F00\u5907\u7528\u94FE\u63A5:"Open alternate link",\u751F\u6210\u4E8C\u7EF4\u7801:"Generate QR code",\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801:"Generate WeChat QR code",\u751F\u6210\u98DE\u4E66\u4E8C\u7EF4\u7801:"Generate Feishu QR code",\u751F\u6210\u9489\u9489\u4E8C\u7EF4\u7801:"Generate DingTalk QR code",\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801:"Generate WeCom QR code","\u751F\u6210 QQ \u4E8C\u7EF4\u7801":"Generate QQ QR code","\u6B63\u5728\u751F\u6210\u4E8C\u7EF4\u7801\u2026":"Generating QR code\u2026",\u6B63\u5728\u51C6\u5907\u6388\u6743\u4E8C\u7EF4\u7801:"Preparing authorization QR code",\u6B63\u5728\u51C6\u5907\u6743\u9650\u6388\u6743\u4E8C\u7EF4\u7801:"Preparing permission authorization QR code",\u6B63\u5728\u51C6\u5907\u5FAE\u4FE1\u4E8C\u7EF4\u7801:"Preparing WeChat QR code",\u6B63\u5728\u6DFB\u52A0\u65B0\u673A\u5668\u4EBA:"Adding a new bot","\u6B63\u5728\u7533\u8BF7\u9489\u9489\u6388\u6743\u4E8C\u7EF4\u7801\u2026":"Requesting DingTalk authorization QR code\u2026","\u6B63\u5728\u7533\u8BF7\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u2026":"Requesting WeCom QR code\u2026","\u6B63\u5728\u7533\u8BF7 QQ \u4E8C\u7EF4\u7801\u2026":"Requesting QQ QR code\u2026","\u6B63\u5728\u751F\u6210 WhatsApp \u4E8C\u7EF4\u7801":"Generating WhatsApp QR code","\u626B\u7801\uFF0C\u521B\u5EFA\u7B2C\u4E00\u4E2A\u98DE\u4E66\u5165\u53E3":"Scan to create your first Feishu bot","\u626B\u7801\u53EA\u4F1A\u65B0\u589E\u4E00\u4E2A\u673A\u5668\u4EBA\uFF0C\u5DF2\u63A5\u5165\u7684\u673A\u5668\u4EBA\u4F1A\u7EE7\u7EED\u6B63\u5E38\u6536\u53D1\u6D88\u606F\u3002":"Scanning adds one bot. Existing bots will continue to send and receive messages.","\u65E0\u9700\u624B\u52A8\u586B\u5199 App ID\u3002\u4EE5\u540E\u8FD8\u53EF\u4EE5\u7EE7\u7EED\u6DFB\u52A0\u673A\u5668\u4EBA\uFF0C\u5206\u522B\u670D\u52A1\u4E0D\u540C\u56E2\u961F\u6216\u98DE\u4E66\u79DF\u6237\u3002":"No App ID is required. You can add more bots later for different teams or Feishu tenants.",\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u521B\u5EFA\u673A\u5668\u4EBA:"Scan with Feishu to create a bot",\u5237\u65B0\u4E8C\u7EF4\u7801\u540E\u7EE7\u7EED:"Refresh the QR code to continue","\u6253\u5F00\u98DE\u4E66\u79FB\u52A8\u7AEF\uFF0C\u4F7F\u7528\u626B\u4E00\u626B\u8BFB\u53D6\u4E8C\u7EF4\u7801":"Open Feishu on your phone and scan the QR code","\u6838\u5BF9\u5E94\u7528\u540D\u79F0\u4E0E\u6743\u9650\u8303\u56F4\uFF0C\u5E76\u786E\u8BA4\u521B\u5EFA":"Review the app name and permissions, then confirm","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u65B0\u673A\u5668\u4EBA\u7684\u957F\u8FDE\u63A5\u5C31\u7EEA":"Keep this page open until the bot connection is ready",\u5728\u98DE\u4E66\u4E2D\u6253\u5F00:"Open in Feishu",\u53D6\u6D88\u6DFB\u52A0:"Cancel",\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u8865\u5168\u6743\u9650:"Scan with Feishu to complete permissions",\u4F7F\u7528\u98DE\u4E66\u786E\u8BA4\u7FA4\u6D88\u606F\u6743\u9650:"Confirm group-message permission with Feishu","\u626B\u7801\u4F1A\u66F4\u65B0\u73B0\u6709\u98DE\u4E66\u5E94\u7528\uFF0C\u53EA\u589E\u91CF\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF1B\u4E0D\u4F1A\u521B\u5EFA\u65B0\u5E94\u7528\u3002\u786E\u8BA4\u540E\u4F1A\u81EA\u52A8\u542F\u7528\u201C\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\u201D\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u53D7\u5F71\u54CD\u3002":"Scanning updates the existing Feishu app with only the \u201CRead all messages in associated group chat\u201D scope. It does not create a new app. After confirmation, \u201CRespond to all group messages\u201D is enabled automatically; other bots are unaffected.","\u6838\u5BF9\u73B0\u6709\u5E94\u7528\uFF0C\u5E76\u786E\u8BA4\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650":"Review the existing app and confirm the \u201CRead all messages in associated group chat\u201D permission","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u6743\u9650\u751F\u6548\u5E76\u81EA\u52A8\u5207\u6362\u54CD\u5E94\u65B9\u5F0F":"Keep this page open while the permission takes effect and the response mode switches automatically",\u53D6\u6D88\u6388\u6743:"Cancel authorization","\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u542F\u7528\u5168\u90E8\u6D88\u606F\u6A21\u5F0F":"Confirmed. Enabling all-message mode","\u6743\u9650\u914D\u7F6E\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u4FDD\u5B58\u8BBE\u7F6E\u5E76\u91CD\u8FDE\u6B64\u673A\u5668\u4EBA\uFF1B\u6B64\u9636\u6BB5\u65E0\u6CD5\u53D6\u6D88\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"The permission update was submitted. Saving the setting and reconnecting this bot. This stage cannot be cancelled; other bots will not be interrupted.","\u6743\u9650\u914D\u7F6E\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u542F\u7528\u5168\u90E8\u6D88\u606F\u6A21\u5F0F\u5E76\u91CD\u8FDE\u6B64\u673A\u5668\u4EBA\uFF1B\u6B64\u9636\u6BB5\u65E0\u6CD5\u53D6\u6D88\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"The permission update was submitted. Enabling all-message mode and reconnecting this bot. This stage cannot be cancelled; other bots will not be interrupted.","\u6B63\u5728\u4E3A\u73B0\u6709\u98DE\u4E66\u5E94\u7528\u7533\u8BF7\u7FA4\u6D88\u606F\u6743\u9650\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u5019\u3002":"Requesting a group-message permission QR code for the existing Feishu app\u2026",\u7FA4\u6D88\u606F\u6743\u9650\u6CA1\u6709\u5F00\u901A\u5B8C\u6210:"Group-message permission was not granted","\u626B\u7801\u4F1A\u66F4\u65B0\u73B0\u6709\u98DE\u4E66\u5E94\u7528\uFF0C\u6700\u591A\u589E\u91CF\u8865\u5145\u5361\u7247\u6309\u94AE\u56DE\u8C03\u3001\u8BFB\u53D6\u7528\u6237\u6D88\u606F\u5185\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:message:readonly\uFF08\u98DE\u4E66\u663E\u793A\u4E3A\u201C\u83B7\u53D6\u5355\u804A\u3001\u7FA4\u7EC4\u6D88\u606F\u201D\uFF09\uFF0C\u4EE5\u53CA\u4E0A\u4F20\u673A\u5668\u4EBA\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:resource\uFF1B\u4E0D\u4F1A\u521B\u5EFA\u65B0\u5E94\u7528\u3002\u786E\u8BA4\u9875\u53EA\u663E\u793A\u5F53\u524D\u7F3A\u5C11\u9879\uFF0C\u5B8C\u6210\u540E\u6B64\u673A\u5668\u4EBA\u4F1A\u77ED\u6682\u91CD\u8FDE\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u53D7\u5F71\u54CD\u3002":"Scanning updates the existing Feishu app with up to three missing items: the card-button callback, im:message:readonly for reading images or files in user messages (shown by Feishu as \u201CRead direct and group messages\u201D), and im:resource for uploading images or files sent by the bot. It does not create a new app. The confirmation page shows only missing items; this bot reconnects briefly afterward, while other bots are unaffected.","\u6838\u5BF9\u73B0\u6709\u5E94\u7528\u540D\u79F0\uFF0C\u5E76\u786E\u8BA4\u53EA\u65B0\u589E\u5F53\u524D\u7F3A\u5C11\u7684\u4E0A\u8FF0\u914D\u7F6E":"Review the existing app name and confirm that only the missing items described above are added","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u6743\u9650\u4E0E\u56DE\u8C03\u8865\u5168\u5B8C\u6210":"Keep this page open until permissions and the callback are complete",\u53D6\u6D88\u8865\u5168:"Cancel setup","\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u5B8C\u6210\u6743\u9650\u4E0E\u56DE\u8C03\u914D\u7F6E":"Confirmed. Completing permissions and callback setup",\u6B63\u5728\u51C6\u5907\u6743\u9650\u8865\u5168\u4E8C\u7EF4\u7801:"Preparing the permission-completion QR code","\u914D\u7F6E\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u4FDD\u5B58\u6743\u9650\u3001\u9A8C\u8BC1\u5361\u7247\u56DE\u8C03\u5E76\u91CD\u8FDE\u6B64\u673A\u5668\u4EBA\uFF1B\u6B64\u9636\u6BB5\u65E0\u6CD5\u53D6\u6D88\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"The update was submitted. Saving permissions, verifying the card callback, and reconnecting this bot. This stage cannot be cancelled; other bots will not be interrupted.","\u6B63\u5728\u4E3A\u73B0\u6709\u98DE\u4E66\u5E94\u7528\u7533\u8BF7\u4E00\u6B21\u6027\u66F4\u65B0\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u5019\u3002":"Requesting a one-time update QR code for the existing Feishu app\u2026",\u6743\u9650\u4E0E\u56DE\u8C03\u6CA1\u6709\u8865\u5168\u5B8C\u6210:"Permissions and callback setup did not finish",\u8865\u5168\u6743\u9650:"Complete permissions",\u8865\u5168\u8303\u56F4:"Completion scope","\u6700\u591A\u589E\u91CF\u6DFB\u52A0\u5361\u7247\u56DE\u8C03 card.action.trigger\u3001\u8BFB\u53D6\u6D88\u606F\u5185\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:message:readonly\uFF08\u98DE\u4E66\u663E\u793A\u4E3A\u201C\u83B7\u53D6\u5355\u804A\u3001\u7FA4\u7EC4\u6D88\u606F\u201D\uFF09\uFF0C\u4EE5\u53CA\u4E0A\u4F20\u673A\u5668\u4EBA\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:resource\uFF1B\u786E\u8BA4\u9875\u53EA\u663E\u793A\u5F53\u524D\u7F3A\u5C11\u9879\uFF0C\u4E0D\u4F1A\u521B\u5EFA\u65B0\u5E94\u7528\u3002":"Adds up to the missing card callback card.action.trigger, im:message:readonly for reading images or files in messages (shown by Feishu as \u201CRead direct and group messages\u201D), and im:resource for uploading images or files sent by the bot. The confirmation page shows only missing items; no new app is created.","\u7B49\u5F85\u626B\u7801\u2026":"Waiting for scan\u2026",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u5339\u914D\u7684\u6743\u9650\u8865\u5168\u4E8C\u7EF4\u7801:"Feishu returned a permission-completion QR code for a different bot",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u5339\u914D\u7684\u7FA4\u6D88\u606F\u6743\u9650\u4E8C\u7EF4\u7801:"Feishu returned a group-message permission QR code for a different bot","\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u4FEE\u590D\u4FE1\u606F\u7F3A\u5C11 botId":"Feishu repair status is missing the bot ID","\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u5E94\u7528\u66F4\u65B0\u4FE1\u606F\u7F3A\u5C11 botId":"Feishu app-update status is missing the bot ID",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u5339\u914D\u7684\u6CE8\u518C\u8FDB\u5EA6:"Feishu returned registration progress for a different operation",\u6B64\u673A\u5668\u4EBA:"this bot","\u7528\u4E8E\u4E3A${botName}\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\u7684\u4E00\u6B21\u6027\u6388\u6743\u4E8C\u7EF4\u7801":"One-time QR code for granting group-message permission to ${botName}","\u6B63\u5728\u4E3A\u300C${botName}\u300D\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650":"Granting group-message permission to \u201C${botName}\u201D",'${botName ?? "\u673A\u5668\u4EBA"}\u7684\u6743\u9650\u8865\u5168\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u3002':'Permission-completion QR code generated for ${botName ?? "bot"}. Scan it with Feishu.','${botName ?? "\u673A\u5668\u4EBA"}\u7684\u7FA4\u6D88\u606F\u6743\u9650\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u98DE\u4E66\u786E\u8BA4\u3002':'Group-message permission QR code generated for ${botName ?? "bot"}. Confirm it with Feishu.',"${targetBotName}\u5DF2\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\uFF0C\u5E76\u542F\u7528\u201C\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\u201D\u3002":"${targetBotName} now has group-message permission and \u201CRespond to all group messages\u201D is enabled.","${targetBot.bot.name}\u5DF2\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\uFF0C\u5E76\u542F\u7528\u201C\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\u201D\u3002":"${targetBot.bot.name} now has group-message permission and \u201CRespond to all group messages\u201D is enabled.","${targetBot.bot.name}\u5DF2\u8FDE\u63A5\uFF0C\u53EF\u4EE5\u5728\u98DE\u4E66\u4E2D\u5F00\u59CB\u804A\u5929\u3002":"${targetBot.bot.name} is connected and ready to chat in Feishu.","\u5DF2\u53D6\u6D88\u8865\u5168\u6743\u9650\u4E0E\u56DE\u8C03\u3002":"Completing permissions and the callback was cancelled.","\u5DF2\u53D6\u6D88\u7FA4\u6D88\u606F\u6743\u9650\u6388\u6743\u3002":"Group-message permission authorization was cancelled.","\u6743\u9650\u4E0E\u56DE\u8C03\u5DF2\u66F4\u65B0\uFF0C\u4F46\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u673A\u5668\u4EBA\u8FDE\u63A5\u72B6\u6001":"Permissions and the callback were updated, but the bot connection could not be confirmed yet","\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u66F4\u65B0\uFF0C\u4F46\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u673A\u5668\u4EBA\u8FDE\u63A5\u72B6\u6001":"The group-message permission was updated, but the bot connection could not be confirmed yet",\u98DE\u4E66\u6743\u9650\u4E0E\u56DE\u8C03\u8865\u5168\u5931\u8D25:"Could not complete Feishu permissions and callback setup",\u98DE\u4E66\u7FA4\u6D88\u606F\u6743\u9650\u5F00\u901A\u5931\u8D25:"Could not grant the Feishu group-message permission","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u98DE\u4E66\u6388\u6743\u64CD\u4F5C\uFF0C\u518D\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\u3002":"Finish the current Feishu authorization before granting group-message permission.","\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u8FDE\u63A5\u65B0\u673A\u5668\u4EBA":"Confirmed. Connecting the new bot","\u6B63\u5728\u5B89\u5168\u4FDD\u5B58\u51ED\u636E\u5E76\u68C0\u67E5\u65B0\u673A\u5668\u4EBA\u7684\u6D88\u606F\u901A\u9053\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"Saving credentials and checking the new bot connection. Existing bots will not be interrupted.","\u6B63\u5728\u5411\u98DE\u4E66\u7533\u8BF7\u4E00\u6B21\u6027\u6388\u6743\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u5019\u3002":"Requesting a one-time authorization QR code from Feishu\u2026",\u65B0\u673A\u5668\u4EBA\u6CA1\u6709\u6DFB\u52A0\u5B8C\u6210:"The new bot was not added","\u65B0\u98DE\u4E66\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5\uFF0C\u53EF\u4EE5\u5F00\u59CB\u804A\u5929\u3002":"The new Feishu bot is connected and ready to chat.",\u98DE\u4E66\u5E94\u7528\u521B\u5EFA\u5931\u8D25:"Could not create the Feishu app","\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u8FDE\u63A5\u72B6\u6001":"The bot was created, but its connection could not be confirmed yet",\u673A\u5668\u4EBA\u4ECD\u672A\u8FDE\u63A5:"The bot is still offline",\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5:"The bot is not connected yet",\u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38:"Persistent connection is healthy",\u957F\u8FDE\u63A5:"Persistent connection",\u5E94\u7528\u6807\u8BC6\u5DF2\u5B89\u5168\u4FDD\u5B58:"App identifier stored securely",\u673A\u5668\u4EBA\u6807\u8BC6\u5DF2\u5B89\u5168\u4FDD\u5B58:"Bot identifier stored securely",\u5DF2\u5B89\u5168\u4FDD\u5B58:"Stored securely",\u5DF2\u63A5\u5165\u7684\u5FAE\u4FE1\u8D26\u53F7:"Connected WeChat accounts",\u5DF2\u63A5\u5165\u7684\u673A\u5668\u4EBA:"Connected bots",\u5DF2\u63A5\u5165\u7684\u9489\u9489\u673A\u5668\u4EBA:"Connected DingTalk bots",\u5DF2\u7ED1\u5B9A\u7684\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connected WeCom bots","\u5DF2\u7ED1\u5B9A\u7684 QQ \u673A\u5668\u4EBA":"Connected QQ bots","\u5DF2\u63A5\u5165\u7684 WhatsApp \u673A\u5668\u4EBA":"Connected WhatsApp accounts",\u4F7F\u7528\u624B\u673A\u5FAE\u4FE1\u626B\u63CF\u4E8C\u7EF4\u7801:"Scan with WeChat on your phone","\u626B\u4E00\u6B21\u7801\uFF0C\u5C31\u80FD\u5728\u5FAE\u4FE1\u91CC\u4F7F\u7528 Harness":"Scan once to use Harness in WeChat",\u6253\u5F00\u624B\u673A\u5FAE\u4FE1\u5E76\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801:"Open WeChat on your phone and scan the QR code",\u5728\u5FAE\u4FE1\u4E2D\u786E\u8BA4\u8FDE\u63A5\u8BE5\u673A\u5668\u4EBA:"Confirm the bot connection in WeChat","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u673A\u5668\u4EBA\u81EA\u52A8\u8FDE\u63A5":"Keep this page open while the bot connects",\u7B49\u5F85\u5FAE\u4FE1\u626B\u7801:"Waiting for WeChat scan",\u9700\u8981\u914D\u5BF9\u7801:"Pairing code required",\u8F93\u5165\u624B\u673A\u5FAE\u4FE1\u663E\u793A\u7684\u6570\u5B57:"Enter the number shown in WeChat",\u5FAE\u4FE1\u914D\u5BF9\u7801:"WeChat pairing code","\u5DF2\u626B\u7801\uFF0C\u8BF7\u5728\u624B\u673A\u4E0A\u786E\u8BA4":"Scanned. Confirm on your phone","\u914D\u5BF9\u7801\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u7B49\u5F85\u5FAE\u4FE1\u786E\u8BA4\u3002":"Pairing code submitted. Waiting for WeChat confirmation.","\u8FD9\u662F\u5FAE\u4FE1\u9644\u52A0\u7684\u5B89\u5168\u786E\u8BA4\u6B65\u9AA4\u3002\u914D\u5BF9\u7801\u53EA\u7528\u4E8E\u672C\u6B21\u626B\u7801\u8F6E\u8BE2\uFF0C\u4E0D\u4F1A\u5199\u5165\u914D\u7F6E\u6216\u65E5\u5FD7\u3002":"This is an additional WeChat confirmation step. The pairing code is used only for this connection and is never stored.","\u6B63\u5728\u4FDD\u5B58\u51ED\u636E\u5E76\u9A8C\u8BC1 Harness \u4E0E\u5FAE\u4FE1\u957F\u8F6E\u8BE2\u3002":"Saving credentials and verifying the WeChat connection.","\u5FAE\u4FE1\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u542F\u52A8\u6D88\u606F\u8FDE\u63A5":"Confirmed in WeChat. Starting the message connection","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u8BFB\u53D6\u73B0\u6709\u767B\u5F55\u51ED\u636E\u3002\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u5B58\u50A8\u3002":"WeChat was authorized, but the existing login credential could not be read. Check the DSH credential store.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u767B\u5F55\u51ED\u636E\u65E0\u6CD5\u5199\u5165 DSH \u51ED\u636E\u5B58\u50A8\u3002\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u662F\u5426\u53EF\u5199\u3002":"WeChat was authorized, but the login credential could not be written to the DSH credential store. Check that the store is writable.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u8D26\u53F7\u914D\u7F6E\u65E0\u6CD5\u5199\u5165\u672C\u673A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u76EE\u5F55\u6743\u9650\u3002":"WeChat was authorized, but the account configuration could not be saved locally. Check the DSH_HOME directory permissions.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u521D\u59CB\u5316\u8D26\u53F7\u72B6\u6001\u6216\u5DE5\u4F5C\u533A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u548C\u5DE5\u4F5C\u533A\u76EE\u5F55\u3002":"WeChat was authorized, but the account state or workspace could not be initialized. Check DSH_HOME and the workspace directory.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u63D2\u4EF6\u65E0\u6CD5\u8FDE\u63A5\u672C\u673A Harness\u3002\u8BF7\u68C0\u67E5 dsh web \u5730\u5740\u548C\u7AEF\u53E3\u3002":"WeChat was authorized, but the plugin could not connect to the local Harness. Check the dsh web address and port.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\u3002\u8BF7\u786E\u8BA4 dsh web \u672A\u963B\u585E\u3002":"WeChat was authorized, but the Harness health check timed out. Confirm that dsh web is not blocked.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u62D2\u7EDD\u4E86\u672C\u673A\u5065\u5EB7\u68C0\u67E5\u3002\u8BF7\u68C0\u67E5 Host \u4FE1\u4EFB\u914D\u7F6E\u3002":"WeChat was authorized, but Harness denied the local health check. Check the Host trust configuration.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u627E\u4E0D\u5230 Harness \u5065\u5EB7\u68C0\u67E5\u63A5\u53E3\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002":"WeChat was authorized, but the Harness health endpoint was not found. Confirm that Harness and the plugin are compatible.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8FD4\u56DE\u670D\u52A1\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but the Harness health check returned a service error. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002":"WeChat was authorized, but Harness returned an unrecognized response. Confirm that Harness and the plugin are compatible.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u62D2\u7EDD\u4E86\u5065\u5EB7\u68C0\u67E5\u8BF7\u6C42\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but Harness rejected the health-check request. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but the Harness health check failed unexpectedly. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6D88\u606F\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u540E\u91CD\u8BD5\u3002":"WeChat was authorized, but the message connection could not be initialized. Check the dsh web logs and try again.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6FC0\u6D3B\u8FC7\u7A0B\u4E2D\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but an unknown error occurred during activation. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u7ED1\u5B9A\uFF0C\u53EF\u4EE5\u5F00\u59CB\u5411\u5DF2\u7ED1\u5B9A\u7684\u673A\u5668\u4EBA\u53D1\u6D88\u606F\u3002":"WeChat is connected and ready for messages.","\u8FD9\u4E2A\u5FAE\u4FE1\u8D26\u53F7\u5DF2\u7ECF\u7ED1\u5B9A\u5E76\u4FDD\u6301\u5728\u7EBF\u3002":"This WeChat account is connected and online.","\u5FAE\u4FE1\u8D26\u53F7\u53CA\u672C\u673A\u51ED\u636E\u5DF2\u79FB\u9664\u3002":"The WeChat account and local credentials were removed.","\u5DF2\u53D6\u6D88\u5FAE\u4FE1\u7ED1\u5B9A\u3002":"WeChat setup was cancelled.","\u6B63\u5728\u8054\u7CFB\u817E\u8BAF\u5FAE\u4FE1 iLink \u670D\u52A1\u3002":"Contacting the WeChat iLink service.","iLink \u957F\u8F6E\u8BE2":"iLink long polling","\u626B\u4E00\u6B21\u7801\uFF0C\u81EA\u52A8\u521B\u5EFA\u5E76\u8FDE\u63A5\u673A\u5668\u4EBA":"Scan once to create and connect a bot","\u4F7F\u7528\u9489\u9489 App \u5B8C\u6210\u673A\u5668\u4EBA\u6388\u6743":"Authorize the bot with the DingTalk app","\u4F7F\u7528\u5DF2\u52A0\u5165\u4F01\u4E1A/\u7EC4\u7EC7\u7684\u9489\u9489\u8D26\u53F7\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Scan the QR code with a DingTalk account that belongs to an organization","\u5728\u6388\u6743\u9875\u70B9\u51FB\u201C\u4E00\u952E\u521B\u5EFA\u65B0\u673A\u5668\u4EBA\u201D":"Select \u201CCreate new bot\u201D on the authorization page","\u8BF7\u52FF\u5173\u95ED\u672C\u9875\uFF0C\u9489\u9489\u5B8C\u6210\u6388\u6743\u540E\u5C06\u81EA\u52A8\u7EE7\u7EED\u3002":"Keep this page open. Setup will continue after DingTalk authorization.",\u7B49\u5F85\u9489\u9489\u626B\u7801\u6388\u6743:"Waiting for DingTalk authorization","\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u521B\u5EFA\u9489\u9489\u673A\u5668\u4EBA":"Authorized. Creating the DingTalk bot",\u6B63\u5728\u786E\u8BA4\u9489\u9489\u6388\u6743:"Confirming DingTalk authorization","\u6B63\u5728\u68C0\u67E5\u9489\u9489 Stream \u957F\u8FDE\u63A5\uFF0C\u6210\u529F\u540E\u4F1A\u81EA\u52A8\u663E\u793A\u4E3A\u5728\u7EBF\u3002":"Checking the DingTalk Stream connection. It will appear online when ready.","\u9489\u9489\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u53EF\u4EE5\u5F00\u59CB\u53D1\u9001\u6D88\u606F\u3002":"The DingTalk bot is connected and ready for messages.","\u8FD9\u4E2A\u9489\u9489\u673A\u5668\u4EBA\u5DF2\u7ECF\u63A5\u5165\u5E76\u4FDD\u6301\u5728\u7EBF\u3002":"This DingTalk bot is connected and online.","Stream \u957F\u8FDE\u63A5":"Stream persistent connection","\u4F7F\u7528\u4F01\u4E1A\u5FAE\u4FE1 App \u626B\u7801\u521B\u5EFA\u667A\u80FD\u673A\u5668\u4EBA":"Scan with WeCom to create an AI bot","\u4F7F\u7528\u4F01\u4E1A\u5FAE\u4FE1 App \u5B8C\u6210\u667A\u80FD\u673A\u5668\u4EBA\u6388\u6743":"Authorize the AI bot with WeCom","\u6253\u5F00\u4F01\u4E1A\u5FAE\u4FE1 App\uFF0C\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Open WeCom and scan the QR code",\u5728\u817E\u8BAF\u6388\u6743\u9875\u9762\u786E\u8BA4\u521B\u5EFA\u667A\u80FD\u673A\u5668\u4EBA:"Confirm bot creation on the Tencent authorization page",\u8FD4\u56DE\u8FD9\u91CC\u7B49\u5F85\u8FDE\u63A5\u5B8C\u6210:"Return here and wait for the connection to complete","\u7B49\u5F85\u4F01\u4E1A\u5FAE\u4FE1 App \u626B\u7801":"Waiting for WeCom scan","\u4F01\u4E1A\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u6B63\u5728\u8FDE\u63A5\u673A\u5668\u4EBA":"Authorized in WeCom. Connecting the bot","\u51ED\u636E\u6B63\u5728\u5199\u5165\u672C\u673A\uFF0C\u5E76\u542F\u52A8\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u6D88\u606F\u8FDE\u63A5\u3002":"Saving credentials locally and starting the WeCom WebSocket connection.","WebSocket \u957F\u8FDE\u63A5":"WebSocket persistent connection","\u4F7F\u7528\u624B\u673A QQ \u626B\u7801\u521B\u5EFA\u5E76\u7ED1\u5B9A\u673A\u5668\u4EBA":"Scan with mobile QQ to create and connect a bot","\u4F7F\u7528\u624B\u673A QQ \u5B8C\u6210\u673A\u5668\u4EBA\u7ED1\u5B9A":"Complete bot setup with mobile QQ","\u6253\u5F00\u624B\u673A QQ\uFF0C\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Open mobile QQ and scan the QR code",\u5728\u817E\u8BAF\u6388\u6743\u9875\u9762\u786E\u8BA4\u521B\u5EFA\u6216\u7ED1\u5B9A\u673A\u5668\u4EBA:"Confirm bot creation or connection on the Tencent authorization page","\u7B49\u5F85\u624B\u673A QQ \u626B\u7801":"Waiting for mobile QQ scan","QQ \u5DF2\u6388\u6743\uFF0C\u6B63\u5728\u8FDE\u63A5\u673A\u5668\u4EBA":"Authorized in QQ. Connecting the bot","\u51ED\u636E\u6B63\u5728\u5199\u5165\u672C\u673A\uFF0C\u5E76\u542F\u52A8 QQ WebSocket \u6D88\u606F\u8FDE\u63A5\u3002":"Saving credentials locally and starting the QQ WebSocket connection.","\u4F7F\u7528\u624B\u673A WhatsApp \u626B\u63CF\u4E8C\u7EF4\u7801\u5373\u53EF\u63A5\u5165\u3002":"Scan the QR code with WhatsApp to connect.","\u7528\u624B\u673A WhatsApp \u626B\u63CF\u4E8C\u7EF4\u7801":"Scan with WhatsApp on your phone","\u6253\u5F00 WhatsApp \u2192 \u8BBE\u7F6E \u2192 \u5DF2\u5173\u8054\u8BBE\u5907":"Open WhatsApp \u2192 Settings \u2192 Linked devices","\u70B9\u51FB\u201C\u5173\u8054\u8BBE\u5907\u201D\u5E76\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Select \u201CLink a device\u201D and scan the QR code","\u7B49\u5F85 WhatsApp \u626B\u7801":"Waiting for WhatsApp scan","\u5DF2\u626B\u7801\uFF0C\u6B63\u5728\u8FDE\u63A5 WhatsApp":"Scanned. Connecting WhatsApp","\u6B63\u5728\u5EFA\u7ACB\u5B89\u5168\u7684\u5173\u8054\u8BBE\u5907\u4F1A\u8BDD\u3002":"Creating a secure linked-device session.","\u5173\u8054\u8BBE\u5907\u6B63\u5728\u63A5\u5165 DeepSeek Harness\u3002":"Linking the device to DeepSeek Harness.","WhatsApp Web \u5173\u8054\u8BBE\u5907\u8FD0\u884C\u6B63\u5E38":"WhatsApp linked device is healthy","\u67E5\u770B WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u8BF4\u660E":"View WhatsApp access mode details","WhatsApp \u8BBF\u95EE\u6A21\u5F0F":"WhatsApp access mode",\u4EC5\u81EA\u5DF1\u6A21\u5F0F:"Only me",\u6307\u5B9A\u8054\u7CFB\u4EBA\u6A21\u5F0F:"Selected contacts",\u5F00\u653E\u54CD\u5E94\u6A21\u5F0F:"Open responses","\u4EC5\u81EA\u5DF1\u6A21\u5F0F\uFF08\u9ED8\u8BA4\uFF09":"Only me (default)","\u5DF2\u751F\u6548\uFF1A":"Active: ","\u53EA\u54CD\u5E94\u5DF2\u7ED1\u5B9A WhatsApp \u8D26\u53F7\u7684\u81EA\u804A\u6D88\u606F\u3002":"Only respond to self-chat messages from the linked WhatsApp account.","\u54CD\u5E94\u81EA\u804A\u548C\u767D\u540D\u5355\u8054\u7CFB\u4EBA\u7684\u79C1\u804A\uFF0C\u5FFD\u7565\u7FA4\u804A\u3002":"Respond to self-chat and allowlisted direct messages; ignore group messages.","\u54CD\u5E94\u6240\u6709\u79C1\u804A\u3001\u5DF2\u7ED1\u5B9A\u8D26\u53F7\u81EA\u5DF1\u53D1\u51FA\u7684\u7FA4\u804A\u6D88\u606F\uFF0C\u4EE5\u53CA\u5176\u4ED6\u7FA4\u6210\u5458\u7684\u63D0\u53CA\u6216\u56DE\u590D\u3002":"Respond to all direct messages, group messages sent by the linked account, and mentions or replies from other group members.","\u5141\u8BB8\u79C1\u804A\u7684 WhatsApp \u7535\u8BDD\u53F7\u7801":"WhatsApp phone numbers allowed to send direct messages",\u6BCF\u884C\u4E00\u4E2A\u542B\u56FD\u5BB6\u6216\u5730\u533A\u4EE3\u7801\u7684\u53F7\u7801:"One number with country or region code per line","\u53EF\u4EE5\u5305\u542B\u5F00\u5934\u7684 +\uFF0C\u4FDD\u5B58\u65F6\u4F1A\u81EA\u52A8\u79FB\u9664\u3002":"A leading + is allowed and removed when saved.","\u4EC5\u6307\u5B9A\u8054\u7CFB\u4EBA\u6A21\u5F0F\u4F7F\u7528\u767D\u540D\u5355\uFF0C\u5207\u6362\u6A21\u5F0F\u65F6\u4F1A\u4FDD\u7559\u3002":"Only Selected contacts uses the allowlist; it is retained when modes change.","\u767D\u540D\u5355\u4E3A\u7A7A\uFF1B\u4FDD\u5B58\u540E\u5C06\u53EA\u63A5\u53D7\u81EA\u804A\u6D88\u606F\u3002":"The allowlist is empty; only self-chat messages will be accepted after saving.","\u7535\u8BDD\u53F7\u7801\u5FC5\u987B\u5305\u542B\u56FD\u5BB6\u6216\u5730\u533A\u4EE3\u7801\uFF0C\u6BCF\u884C\u4E00\u4E2A\u3002":"Each phone number must include a country or region code on its own line.","WhatsApp \u8BBF\u95EE\u8BBE\u7F6E\u6682\u4E0D\u53EF\u7528\u3002":"WhatsApp access settings are currently unavailable.","WhatsApp \u8BBF\u95EE\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\u3002":"Could not save WhatsApp access settings.","Bot API \u957F\u8F6E\u8BE2":"Bot API long polling"," Gateway \u957F\u8FDE\u63A5":" Gateway persistent connection","Gateway \u957F\u8FDE\u63A5":"Gateway persistent connection"," Socket Mode \u957F\u8FDE\u63A5":" Socket Mode persistent connection","Socket Mode \u957F\u8FDE\u63A5":"Socket Mode persistent connection","\u63A5\u5165 Telegram \u673A\u5668\u4EBA":"Connect a Telegram bot","\u5148\u901A\u8FC7 @BotFather \u83B7\u53D6 Bot Token\uFF0C\u518D\u5728\u8FD9\u91CC\u5B8C\u6210\u63A5\u5165\u3002":"Get a Bot Token from @BotFather, then connect it here.","\u586B\u5199 @BotFather \u751F\u6210\u7684 Bot Token":"Enter the Bot Token from @BotFather",\u8BBF\u95EE\u6A21\u5F0F:"Access mode",\u8BBF\u95EE\u8BBE\u7F6E:"Access settings","Telegram \u8BBF\u95EE\u6A21\u5F0F":"Telegram access mode","\u67E5\u770B Telegram \u8BBF\u95EE\u6A21\u5F0F\u8BF4\u660E":"View Telegram access mode details","\u7FA4\u804A\u5168\u90E8\u5FFD\u7565\uFF0C\u79C1\u804A\u4EC5\u5141\u8BB8\u767D\u540D\u5355\u7528\u6237\u3002":"All group messages are ignored; only allowlisted users may send DMs.","\u4FDD\u6301\u539F\u6709\u884C\u4E3A\uFF1A\u79C1\u804A\u76F4\u63A5\u54CD\u5E94\uFF0C\u7FA4\u804A\u5728\u88AB\u63D0\u53CA\u6216\u56DE\u590D\u65F6\u54CD\u5E94\u3002":"Keep the original behavior: respond to DMs and to group mentions or replies.",\u5B89\u5168\u6A21\u5F0F:"Safe mode",\u517C\u5BB9\u6A21\u5F0F:"Compatible mode","\u5DF2\u751F\u6548\uFF1A\u5B89\u5168\u6A21\u5F0F":"Active: Safe mode","\u5DF2\u751F\u6548\uFF1A\u517C\u5BB9\u6A21\u5F0F":"Active: Compatible mode",\u6A21\u5F0F:"Mode","\u517C\u5BB9\u6A21\u5F0F\uFF08\u9ED8\u8BA4\uFF09":"Compatible mode (default)","\u5B89\u5168\u6A21\u5F0F\uFF08\u79C1\u804A\u767D\u540D\u5355\uFF09":"Safe mode (private-chat allowlist)","\u5141\u8BB8\u79C1\u804A\u7684 Telegram User ID":"Telegram User IDs allowed to send DMs","\u6BCF\u884C\u4E00\u4E2A\u6570\u5B57 User ID":"One numeric User ID per line","\u767D\u540D\u5355\u4EC5\u5C5E\u4E8E\u5F53\u524D\u673A\u5668\u4EBA\u3002":"This allowlist belongs only to the current bot.","\u517C\u5BB9\u6A21\u5F0F\u4E0B\u6682\u4E0D\u4F7F\u7528\u767D\u540D\u5355\uFF0C\u5207\u6362\u6A21\u5F0F\u65F6\u4F1A\u4FDD\u7559\u3002":"Compatible mode does not enforce the allowlist; it is retained when modes change.","\u767D\u540D\u5355\u4E3A\u7A7A\uFF1B\u4FDD\u5B58\u540E\u8BE5\u673A\u5668\u4EBA\u4F1A\u62D2\u7EDD\u6240\u6709\u5165\u7AD9\u6D88\u606F\u3002":"The allowlist is empty; this bot will reject all inbound messages after saving.","\u6B63\u5728\u4FDD\u5B58\u2026":"Saving\u2026",\u4FDD\u5B58\u8BBF\u95EE\u8BBE\u7F6E:"Save access settings","User ID \u5FC5\u987B\u662F 1\u201316 \u4F4D\u6B63\u6574\u6570\uFF0C\u6BCF\u884C\u4E00\u4E2A\u3002":"Each User ID must be a 1\u201316 digit positive integer on its own line.","Telegram \u8BBF\u95EE\u8BBE\u7F6E\u6682\u4E0D\u53EF\u7528\u3002":"Telegram access settings are currently unavailable.","Telegram \u8BBF\u95EE\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\u3002":"Could not save Telegram access settings.","\u63A5\u5165 Discord \u673A\u5668\u4EBA":"Connect a Discord bot","\u5148\u5728 Developer Portal \u521B\u5EFA Bot \u5E76\u9080\u8BF7\u5230\u670D\u52A1\u5668\uFF0C\u518D\u5728\u8FD9\u91CC\u5B8C\u6210\u63A5\u5165\u3002":"Create a bot in the Developer Portal and invite it to your server, then connect it here.","\u586B\u5199 Discord Developer Portal \u7684 Bot Token":"Enter the Bot Token from the Discord Developer Portal","\u63A5\u5165 Slack \u673A\u5668\u4EBA":"Connect a Slack bot","\u5148\u7528 Manifest \u521B\u5EFA\u5E76\u914D\u7F6E Slack App":"Create and configure a Slack app with the manifest","\u590D\u5236\u914D\u7F6E\u540E\uFF0C\u5728 Slack \u9009\u62E9 From a manifest\uFF1B\u521B\u5EFA\u5B8C\u6210\u540E\u751F\u6210 connections:write App Token\uFF0C\u5E76\u5C06\u5E94\u7528\u5B89\u88C5\u5230\u5DE5\u4F5C\u533A\u3002":"Copy the manifest and choose \u201CFrom a manifest\u201D in Slack. Then create a connections:write App Token and install the app to your workspace.","\u590D\u5236 Manifest":"Copy manifest","\u5DF2\u590D\u5236 Manifest":"Manifest copied","\u6253\u5F00 Slack \u521B\u5EFA\u9875":"Open Slack app creation","Bot Token \u6765\u81EA OAuth & Permissions\uFF1BApp Token \u6765\u81EA Basic Information\uFF0C\u5E76\u4E14\u5FC5\u987B\u5305\u542B connections:write\u3002":"Get the Bot Token from OAuth & Permissions and the App Token from Basic Information. The App Token must include connections:write.","\u4F7F\u7528\u5B98\u65B9 App Manifest \u5FEB\u901F\u914D\u7F6E\u673A\u5668\u4EBA\uFF0C\u518D\u586B\u5199 Bot Token \u4E0E App Token \u5EFA\u7ACB\u672C\u5730 Socket Mode \u8FDE\u63A5\u3002":"Configure the bot with the official app manifest, then enter the Bot Token and App Token to start a local Socket Mode connection.","Slack \u5DE5\u4F5C\u533A":"Slack workspace","Bot Token \u4E0E App Token":"Bot Token and App Token","\u586B\u5199 Bot Token":"Enter Bot Token",\u624B\u52A8\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA:"Connect Feishu bot manually",\u624B\u52A8\u63A5\u5165\u9489\u9489\u673A\u5668\u4EBA:"Connect DingTalk bot manually",\u624B\u52A8\u63A5\u5165\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connect WeCom bot manually",\u624B\u52A8\u63A5\u5165QQ\u673A\u5668\u4EBA:"Connect QQ bot manually","\u586B\u5199\u98DE\u4E66\u5F00\u653E\u5E73\u53F0 App ID":"Enter the Feishu Open Platform App ID","\u586B\u5199\u98DE\u4E66\u5F00\u653E\u5E73\u53F0 App Secret":"Enter the Feishu Open Platform App Secret","\u586B\u5199\u9489\u9489\u5E94\u7528 Client ID":"Enter the DingTalk Client ID","\u586B\u5199\u9489\u9489\u5E94\u7528 Client Secret":"Enter the DingTalk Client Secret","\u586B\u5199\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA Bot ID":"Enter the WeCom AI Bot ID","\u586B\u5199\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA Secret":"Enter the WeCom AI Bot Secret","\u586B\u5199 QQ \u5F00\u653E\u5E73\u53F0 AppID":"Enter the QQ Open Platform AppID","\u586B\u5199 QQ \u5F00\u653E\u5E73\u53F0 AppSecret":"Enter the QQ Open Platform AppSecret",\u626B\u7801\u63A5\u5165\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connect WeChat bot by QR code",\u626B\u7801\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA:"Connect Feishu bot by QR code",\u626B\u7801\u63A5\u5165\u9489\u9489\u673A\u5668\u4EBA:"Connect DingTalk bot by QR code",\u626B\u7801\u63A5\u5165\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connect WeCom bot by QR code","\u626B\u7801\u63A5\u5165 QQ \u673A\u5668\u4EBA":"Connect QQ bot by QR code","\u626B\u7801\u63A5\u5165 WhatsApp \u673A\u5668\u4EBA":"Connect WhatsApp by QR code","\u626B\u7801\u7ED1\u5B9A WhatsApp \u673A\u5668\u4EBA":"Connect WhatsApp by QR code","\u4F7F\u7528 App ID \u548C App Secret \u7ED1\u5B9A\u98DE\u4E66\u673A\u5668\u4EBA":"Connect a Feishu bot with App ID and App Secret","\u4F7F\u7528 Client ID \u548C Client Secret \u7ED1\u5B9A\u9489\u9489\u673A\u5668\u4EBA":"Connect a DingTalk bot with Client ID and Client Secret","\u4F7F\u7528 Bot ID \u548C Secret \u7ED1\u5B9A\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA":"Connect a WeCom bot with Bot ID and Secret","\u4F7F\u7528 AppID \u548C AppSecret \u7ED1\u5B9A QQ \u673A\u5668\u4EBA":"Connect a QQ bot with AppID and AppSecret","\u4F7F\u7528 Manifest \u548C\u53CC Token \u63A5\u5165 Slack \u673A\u5668\u4EBA":"Connect a Slack bot with a manifest and two tokens","\u4F7F\u7528 Bot Token \u63A5\u5165 Telegram \u673A\u5668\u4EBA":"Connect a Telegram bot with a Bot Token","\u4F7F\u7528 Bot Token \u63A5\u5165 Discord \u673A\u5668\u4EBA":"Connect a Discord bot with a Bot Token",\u53D6\u6D88\u7ED1\u5B9A:"Cancel setup",\u53D6\u6D88\u63A5\u5165:"Cancel setup","\u4E8C\u7EF4\u7801\u7531\u817E\u8BAF\u5FAE\u4FE1 iLink \u670D\u52A1\u7B7E\u53D1\u3002\u7528\u624B\u673A\u5FAE\u4FE1\u626B\u63CF\u5E76\u786E\u8BA4\u540E\uFF0C\u8D26\u53F7\u51ED\u636E\u4F1A\u76F4\u63A5\u5199\u5165 Harness Host\uFF0C\u6D4F\u89C8\u5668\u4E0D\u4F1A\u6536\u5230 bot_token\u3002":"The QR code is issued by Tencent WeChat iLink. After you scan and confirm, account credentials are written directly to the Harness Host and are never exposed to the browser.","\u626B\u7801\u8D26\u53F7\u5FC5\u987B\u5DF2\u52A0\u5165\u4F01\u4E1A/\u7EC4\u7EC7\u3002\u5982\u679C\u9489\u9489\u63D0\u793A\u5C1A\u672A\u52A0\u5165\u7EC4\u7EC7\uFF0C\u8BF7\u5728\u63D0\u793A\u9875\u521B\u5EFA\u7EC4\u7EC7\uFF0C\u6216\u6362\u7528\u5DF2\u52A0\u5165\u7EC4\u7EC7\u7684\u8D26\u53F7\u3002":"The DingTalk account must belong to an organization. If prompted, create an organization or use an account that already belongs to one.","\u8BF7\u5728\u624B\u673A\u4E0A\u6838\u5BF9\u5E76\u786E\u8BA4\u6388\u6743\u3002\u90E8\u5206\u8D26\u53F7\u4F1A\u989D\u5916\u663E\u793A\u4E00\u4E2A\u914D\u5BF9\u6570\u5B57\uFF0C\u9875\u9762\u4F1A\u5728\u9700\u8981\u65F6\u63D0\u793A\u8F93\u5165\u3002":"Review and confirm authorization on your phone. Some accounts may also require a pairing number.","\u6388\u6743\u7531\u9489\u9489\u5B98\u65B9\u9875\u9762\u5B8C\u6210\u3002\u626B\u7801\u8D26\u53F7\u5FC5\u987B\u5DF2\u52A0\u5165\u4E00\u4E2A\u4F01\u4E1A/\u7EC4\u7EC7\u5E76\u6709\u6743\u521B\u5EFA\u673A\u5668\u4EBA\uFF1B\u521B\u5EFA\u6210\u529F\u540E\uFF0C\u5E94\u7528\u51ED\u636E\u4F1A\u76F4\u63A5\u5199\u5165 Harness Host\u3002":"Authorization is completed on DingTalk\u2019s official page. The account must belong to an organization and be allowed to create bots. Credentials are written directly to the Harness Host.","\u626B\u7801\u7531\u817E\u8BAF\u5B98\u65B9\u9875\u9762\u5B8C\u6210\uFF0C\u4E0D\u9700\u8981\u624B\u52A8\u586B\u5199 AppID \u6216 AppSecret\u3002\u626B\u7801\u6210\u529F\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u81EA\u52A8\u8FDE\u63A5 DeepSeek Harness\u3002":"Scanning is completed on Tencent\u2019s official page. No AppID or AppSecret is required, and the bot connects automatically.","\u626B\u7801\u7531\u817E\u8BAF\u5B98\u65B9\u9875\u9762\u5B8C\u6210\uFF0C\u4E0D\u9700\u8981\u624B\u52A8\u586B\u5199 Bot ID \u6216 Secret\u3002\u521B\u5EFA\u6210\u529F\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u81EA\u52A8\u8FDE\u63A5 DeepSeek Harness\u3002":"Scanning is completed on Tencent\u2019s official page. No Bot ID or Secret is required, and the bot connects automatically.","\u817E\u8BAF\u9875\u9762\u4F1A\u521B\u5EFA\u6216\u7ED1\u5B9A\u4E00\u4E2A QQ \u673A\u5668\u4EBA\uFF0C\u5E76\u628A\u8FDE\u63A5\u51ED\u636E\u5B89\u5168\u4EA4\u7ED9\u672C\u673A Harness Host\u3002":"Tencent will create or connect a QQ bot and securely deliver its credentials to the local Harness Host.","\u4F01\u4E1A\u5FAE\u4FE1\u5B98\u65B9\u9875\u9762\u4F1A\u521B\u5EFA\u4E00\u4E2A\u667A\u80FD\u673A\u5668\u4EBA\uFF0C\u5E76\u628A\u8FDE\u63A5\u51ED\u636E\u5B89\u5168\u4EA4\u7ED9\u672C\u673A Harness Host\u3002":"WeCom will create an AI bot and securely deliver its credentials to the local Harness Host.","\u4ECE\u6B64 Harness \u79FB\u9664\u8FD9\u4E2A\u5FAE\u4FE1\u8D26\u53F7\uFF1F":"Remove this WeChat account from Harness?","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684 bot_token\u3001\u8D26\u53F7\u914D\u7F6E\u548C\u4F1A\u8BDD\u6620\u5C04\u3002\u5176\u4ED6\u5FAE\u4FE1\u8D26\u53F7\u4E0D\u53D7\u5F71\u54CD\u3002":"This stops the message connection and removes the locally stored bot_token, account configuration, and session mappings. Other WeChat accounts are not affected.","\u6B64\u64CD\u4F5C\u4F1A\u505C\u6B62\u8FD9\u4E2A\u673A\u5668\u4EBA\u7684\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u4FDD\u5B58\u5728\u672C\u673A\u7684\u63A5\u5165\u914D\u7F6E\u548C\u51ED\u636E\u3002\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u4E2D\u7684\u5E94\u7528\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E5F\u4E0D\u53D7\u5F71\u54CD\u3002":"This stops the bot connection and removes the locally stored configuration and credentials. The app in Feishu Open Platform is not deleted, and other bots are not affected.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684\u5E94\u7528\u51ED\u636E\u3001\u673A\u5668\u4EBA\u914D\u7F6E\u53CA\u4F1A\u8BDD\u6620\u5C04\u3002\u9489\u9489\u5F00\u653E\u5E73\u53F0\u4E2D\u7684\u673A\u5668\u4EBA\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\u3002":"This stops the message connection and removes the locally stored app credentials, bot configuration, and session mappings. The bot in DingTalk Open Platform is not deleted.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684\u5E94\u7528\u51ED\u636E\u3001\u673A\u5668\u4EBA\u914D\u7F6E\u53CA\u4F1A\u8BDD\u6620\u5C04\u3002\u4F01\u4E1A\u5FAE\u4FE1\u5E73\u53F0\u4E2D\u7684\u673A\u5668\u4EBA\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\u3002":"This stops the message connection and removes the locally stored app credentials, bot configuration, and session mappings. The bot in WeCom is not deleted.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684\u5E94\u7528\u51ED\u636E\u3001\u673A\u5668\u4EBA\u914D\u7F6E\u53CA\u4F1A\u8BDD\u6620\u5C04\u3002\u817E\u8BAF\u5E73\u53F0\u4E2D\u7684\u673A\u5668\u4EBA\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\u3002":"This stops the message connection and removes the locally stored app credentials, bot configuration, and session mappings. The bot on Tencent\u2019s platform is not deleted.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684 WhatsApp \u5173\u8054\u8BBE\u5907\u548C\u4F1A\u8BDD\u6620\u5C04\u3002":"This stops the message connection and removes the locally stored WhatsApp linked device and session mappings.",\u6B63\u5728\u8BFB\u53D6\u98DE\u4E66\u673A\u5668\u4EBA\u5217\u8868:"Loading Feishu bots","\u6B63\u5728\u8BFB\u53D6\u98DE\u4E66\u8FDE\u63A5\u72B6\u6001\u2026":"Loading Feishu connection status\u2026","\u6B63\u5728\u8BFB\u53D6\u5FAE\u4FE1\u8FDE\u63A5\u72B6\u6001\u2026":"Loading WeChat connection status\u2026","\u6B63\u5728\u8BFB\u53D6\u9489\u9489\u8FDE\u63A5\u72B6\u6001\u2026":"Loading DingTalk connection status\u2026","\u901A\u8FC7\u626B\u7801\u628A\u9489\u9489\u673A\u5668\u4EBA\u63A5\u5165 DeepSeek Harness":"Connect a DingTalk bot to DeepSeek Harness by QR code",\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u7ED1\u5B9A\u8FDB\u5EA6:"DingTalk did not return QR setup progress",\u9489\u9489\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1:"DingTalk did not return a valid setup attempt","\u9489\u9489 Stream \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":"DingTalk Stream connection is healthy",\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868:"DingTalk did not return a valid bot list","${totals.connected} / ${totals.configured} \u5728\u7EBF":"${totals.connected} / ${totals.configured} online","\u7528\u4E8E\u628A\u9489\u9489\u673A\u5668\u4EBA\u63A5\u5165 DeepSeek Harness \u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for connecting a DingTalk bot to DeepSeek Harness","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\\n\u8BF7\u91CD\u65B0\u751F\u6210":"QR code expired\\nGenerate a new one","\u673A\u5668\u4EBA\u5DF2\u521B\u5EFA\uFF0C\u6B63\u5728\u5EFA\u7ACB\u6D88\u606F\u8FDE\u63A5":"Bot created. Starting the message connection",\u9489\u9489\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u5B89\u5168\u7684\u4E8C\u7EF4\u7801:"DingTalk did not return a secure QR code","\u9489\u9489\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u9489\u9489 App \u626B\u63CF\u3002":"DingTalk QR code generated. Scan it with the DingTalk app.","\u9489\u9489\u673A\u5668\u4EBA\u51ED\u636E\u5DF2\u7ED1\u5B9A\u3002":"DingTalk bot credentials connected.","\u5DF2\u53D6\u6D88\u9489\u9489\u673A\u5668\u4EBA\u63A5\u5165\u3002":"DingTalk bot setup cancelled.","\u9489\u9489\u673A\u5668\u4EBA\u53CA\u672C\u673A\u51ED\u636E\u5DF2\u79FB\u9664\u3002":"DingTalk bot and local credentials removed.",\u98DE\u4E66\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4FE1\u606F:"Feishu did not return QR code information",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u4E8C\u7EF4\u7801\u4FE1\u606F\u4E0D\u5B8C\u6574:"Feishu returned incomplete QR code information",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u673A\u5668\u4EBA\u72B6\u6001:"Feishu returned an invalid bot status","\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u673A\u5668\u4EBA\u7F3A\u5C11 botId":"The Feishu bot is missing botId",\u98DE\u4E66\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u8FDE\u63A5\u72B6\u6001:"Feishu did not return connection status",\u98DE\u4E66\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u521B\u5EFA\u8FDB\u5EA6:"Feishu did not return creation progress",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u672A\u77E5\u7684\u521B\u5EFA\u72B6\u6001:"Feishu returned an unknown creation status","\u5DF2\u63A5\u5165 ${totals.configured} \u4E2A\u673A\u5668\u4EBA\uFF0C\u5176\u4E2D ${totals.connected} \u4E2A\u5728\u7EBF":"${totals.connected} of ${totals.configured} bots online",\u5C1A\u672A\u63A5\u5165\u673A\u5668\u4EBA:"No bot connected yet","\u7528\u4E8E\u65B0\u589E DeepSeek Harness \u98DE\u4E66\u673A\u5668\u4EBA\u7684\u4E00\u6B21\u6027\u6388\u6743\u4E8C\u7EF4\u7801":"One-time authorization QR code for adding a Feishu bot to DeepSeek Harness",\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u626B\u7801:"Refresh and scan again",'${connected ? "\u68C0\u67E5\u8FDE\u63A5" : "\u91CD\u8BD5\u8FDE\u63A5"}${bot.name}':'${connected ? "Check connection" : "Reconnect"} ${bot.name}',\u65E0\u6CD5\u8BFB\u53D6\u98DE\u4E66\u673A\u5668\u4EBA:"Could not load Feishu bots","\u6388\u6743\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u3002":"Authorization QR code generated. Scan it with Feishu.","\u98DE\u4E66\u673A\u5668\u4EBA\u51ED\u636E\u5DF2\u7ED1\u5B9A\u3002":"Feishu bot credentials connected.","\u5DF2\u53D6\u6D88\u6DFB\u52A0\u673A\u5668\u4EBA\u3002":"Adding the bot was cancelled.","${newBot.bot.name}\u5DF2\u8FDE\u63A5\uFF0C\u53EF\u4EE5\u5728\u98DE\u4E66\u4E2D\u5F00\u59CB\u804A\u5929\u3002":"${newBot.bot.name} is connected and ready to chat in Feishu.","${bot.name}\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B\u673A\u5668\u4EBA\u72B6\u6001\u3002":"${bot.name} operation failed. Check the bot status.","${bot.name}\u5DF2\u4ECE\u6B64 DeepSeek Harness \u79FB\u9664\uFF1B\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u4E2D\u7684\u5E94\u7528\u672A\u88AB\u5220\u9664\u3002":"${bot.name} was removed from this DeepSeek Harness. The app in Feishu Open Platform was not deleted.",\u65E0\u6CD5\u8BFB\u53D6\u8FDE\u63A5\u72B6\u6001:"Could not load connection status","QQ \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u7ED1\u5B9A\u8FDB\u5EA6":"QQ did not return QR setup progress","QQ \u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1":"QQ did not return a valid setup attempt","QQ WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":"QQ WebSocket connection is healthy","QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002":"The QQ connection is not ready; the plugin will retry automatically.","QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"The QQ connection is not ready; the plugin will retry automatically","QQ \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF":"The QQ connection is currently offline","QQ \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868":"QQ did not return a valid bot list","\u5C1A\u672A\u7ED1\u5B9A QQ \u673A\u5668\u4EBA":"No QQ bot connected yet","\u7528\u4E8E\u7ED1\u5B9A QQ \u673A\u5668\u4EBA\u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for connecting a QQ bot","${channel}${connectionSummary}\u8FD0\u884C\u6B63\u5E38":"${channel}${connectionSummary} is healthy","${channel} \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868":"${channel} did not return a valid bot list","\u4F7F\u7528 Bot Token \u63A5\u5165 ${channel} \u673A\u5668\u4EBA":"Connect a ${channel} bot with a Bot Token","${model.totals.connected} / ${model.totals.configured} \u5728\u7EBF":"${model.totals.connected}/${model.totals.configured} online"," Bot API \u957F\u8F6E\u8BE2":" Bot API long polling",\u4F01\u4E1A\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u7ED1\u5B9A\u8FDB\u5EA6:"WeCom did not return QR setup progress",\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1:"WeCom did not return a valid setup attempt","\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":"WeCom WebSocket connection is healthy",\u4F01\u4E1A\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868:"WeCom did not return a valid bot list",\u5C1A\u672A\u7ED1\u5B9A\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"No WeCom bot connected yet",\u7528\u4E8E\u7ED1\u5B9A\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801:"One-time QR code for connecting a WeCom bot",\u5FAE\u4FE1\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1:"WeChat did not return a valid setup attempt",\u5FAE\u4FE1\u7ED1\u5B9A\u6CA1\u6709\u5B8C\u6210:"WeChat setup did not complete",\u5FAE\u4FE1\u8FDE\u63A5\u6B63\u5E38:"WeChat connection is healthy",\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA:"WeChat connection is not ready","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u56FE\u7247\uFF0C\u8BF7\u7528 /models \u67E5\u770B\u53EF\u7528\u6A21\u578B\uFF0C\u518D\u7528 /model <\u5E8F\u53F7> \u5207\u6362\u540E\u91CD\u53D1\u3002":"The current model does not support images. Use /models to list models, then /model to switch and resend.","\u56FE\u7247\u8D85\u8FC7\u5BBF\u4E3B\u5141\u8BB8\u7684\u5927\u5C0F\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The image exceeds the Host size limit. Compress it and try again.","\u56FE\u7247\u5206\u8FA8\u7387\u8FC7\u9AD8\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The image resolution is too high. Compress it and try again.","\u56FE\u7247\u5185\u5BB9\u65E0\u6548\u6216\u683C\u5F0F\u4E0D\u53D7\u652F\u6301\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002":"The image is invalid or unsupported. Send it again.","\u672A\u80FD\u8BFB\u53D6\u56FE\u7247\u5185\u5BB9\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002":"The image could not be read. Send it again.","\u56FE\u7247\u683C\u5F0F\u4E0E\u5B9E\u9645\u5185\u5BB9\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002":"The declared image format does not match its content. Send it again.","\u4E00\u6B21\u53D1\u9001\u7684\u56FE\u7247\u6570\u91CF\u8D85\u8FC7\u5BBF\u4E3B\u9650\u5236\uFF0C\u8BF7\u51CF\u5C11\u540E\u91CD\u8BD5\u3002":"The message exceeds the Host image-count limit. Remove some images and try again.","\u56FE\u7247\u603B\u5927\u5C0F\u8D85\u8FC7\u5BBF\u4E3B\u9650\u5236\uFF0C\u8BF7\u51CF\u5C11\u56FE\u7247\u6216\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The images exceed the Host total-size limit. Remove or compress some images and try again.","\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\u53D1\u751F\u4E86\u91CD\u5B9A\u5411\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u3002":"The image download redirected and cannot be read.","\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The image exceeds 5 MB. Compress it and try again.","\u4E00\u6B21\u53D1\u9001\u7684\u56FE\u7247\u603B\u5927\u5C0F\u8FC7\u5927\uFF0C\u8BF7\u51CF\u5C11\u56FE\u7247\u6570\u91CF\u6216\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The images are too large in total. Remove or compress some images and try again.","\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002":"The image download failed. Send it again.","\u6682\u4E0D\u652F\u6301\u8BE5\u56FE\u7247\u683C\u5F0F\uFF0C\u8BF7\u53D1\u9001 JPEG\u3001PNG\u3001WebP \u6216 GIF \u56FE\u7247\u3002":"This image format is unsupported. Send a JPEG, PNG, WebP, or GIF image.","\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Message processing failed. Try again later.",\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u8D26\u53F7\u5217\u8868:"WeChat did not return a valid account list",\u5C1A\u672A\u7ED1\u5B9A\u5FAE\u4FE1:"No WeChat account connected yet","\u7528\u4E8E\u628A\u5FAE\u4FE1\u673A\u5668\u4EBA\u7ED1\u5B9A\u5230 DeepSeek Harness \u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for connecting a WeChat bot to DeepSeek Harness","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u6D88\u606F\u957F\u8F6E\u8BE2\u53D8\u4E3A\u5728\u7EBF":"Keep this page open until long polling is online","\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u624B\u673A\u5FAE\u4FE1\u626B\u63CF\u3002":"WeChat QR code generated. Scan it with WeChat on your phone.","\u79FB\u9664\u5931\u8D25\uFF1A${presentError(error).message}":"Removal failed: ${presentError(error).message}",\u65E0\u6CD5\u8BFB\u53D6\u5FAE\u4FE1\u72B6\u6001:"Could not load WeChat status","WhatsApp \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u8FDB\u5EA6":"WhatsApp did not return QR setup progress","WhatsApp \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u626B\u7801\u4EFB\u52A1":"WhatsApp did not return a valid setup attempt","WhatsApp \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868":"WhatsApp did not return a valid account list","\u7528\u4E8E\u5173\u8054 WhatsApp \u8BBE\u5907\u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for linking a WhatsApp device"});var VnA=Object.freeze(Object.fromEntries(Object.keys(RNe).map(n=>[n,n==="$locale"?"zh":n])));var WnA=Object.freeze(["aria-label","alt","placeholder","title"]);var kNe=Object.freeze({defaultId:"",items:Object.freeze([])}),esA=gd.createContext(kNe);var Dv="/feishu",vt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",beginCallbackRepair:"bot.callback-repair.begin",beginGroupMessagePermission:"bot.group-message-permission.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete",setWorkspace:"bot.workspace.set",setAgentPreset:"bot.preset.set",setGroupResponseMode:"bot.group-response-mode.set",testConnection:"connection.test",disconnect:"connection.disconnect"}),ssA=Object.freeze({PROVISION:"provision",CALLBACK_REPAIR:"callback_repair",GROUP_MESSAGE_PERMISSION:"group_message_permission"});var jI=Object.freeze({reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete"}),fW=Object.freeze([...new Set([...Object.values(vt),...Object.values(jI)])]),PNe=new Set(["idle","starting","qr_ready","polling","slow_down","domain_switched","saving","succeeded","expired","cancelled","error"]),GNe=new Set(["provision","callback_repair","group_message_permission"]),QW="callback_repair",Ov="group_message_permission",Hm=new Set([QW,Ov]),FNe=new Set(["accounts.feishu.cn","accounts.larksuite.com","open.feishu.cn","open.larksuite.com"]),LNe=/^[A-Za-z0-9_-]{1,128}$/,UNe=/^cli_[A-Za-z0-9_-]+$/,EW=Object.freeze({abort:"Registration was cancelled.",access_denied:"Registration was denied.",expired_token:"The registration QR code expired.",invalid_credentials:"Feishu returned invalid app credentials.",credentials_callback_failed:"Unable to activate the Feishu connection.",registration_failed:"Unable to register the Feishu app.",connection_failed:"The bot was created, but its connection could not be started.",credential_removal_failed:"Unable to remove the Feishu credentials.",state_cleanup_failed:"Unable to remove the bot session data. Please retry.",deletion_pending:"Bot deletion is incomplete. Retry removal to finish cleanup.",missing_credentials:"The bot credentials are missing. Delete it and scan again.",repair_app_mismatch:"The authorized Feishu app does not match the selected bot.",repair_owner_missing:"Feishu did not return the authorizing account identity.",repair_domain_mismatch:"The authorized Feishu tenant does not match the selected bot.",repair_owner_mismatch:"The authorizing Feishu account is not an owner of the selected bot.",repair_credentials_invalid:"Feishu returned credentials that could not be verified for the selected bot.",repair_bot_mismatch:"The verified Feishu bot does not match the selected bot.",repair_target_changed:"The selected bot changed while repair was in progress. Start the repair again.",credential_update_failed:"Unable to store the repaired Feishu credentials.",credential_state_unknown:"The repaired Feishu credentials could not be confirmed after saving.",repair_connection_failed:"The callback update was accepted, but the selected bot could not reconnect.",group_message_permission_required:"Authorize access to all group messages before enabling this mode.",group_message_permission_save_failed:"Feishu granted the permission, but all-message mode could not be saved.",group_message_permission_connection_failed:"Feishu granted the permission, but the selected bot could not reconnect.",card_action_probe_unavailable:"The selected bot is not connected, so its card button cannot be verified.",card_action_probe_send_failed:"The callback update was accepted, but the verification card could not be sent.",card_action_probe_timeout:"Feishu accepted the update, but the card button was not verified in time. Start the repair again and click the test button within two minutes.",card_action_probe_failed:"Feishu accepted the update, but the card button verification failed."}),HNe=Object.freeze({idle:"pending",starting:"pending",qr_ready:"pending",polling:"pending",slow_down:"pending",domain_switched:"pending",saving:"connecting",succeeded:"connected",expired:"expired",cancelled:"failed",error:"failed"});function KNe(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}function To(n,t){return KNe(n)&&Reflect.ownKeys(n).every(o=>typeof o=="string"&&t.has(o))}function WC(n){return Number.isFinite(n)?n:void 0}function ln(n){return typeof n=="string"&&LNe.test(n)}function CW(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function Mv(n){if(!n||typeof n!="object")return null;let t=typeof n.code=="string"&&Object.hasOwn(EW,n.code)?n.code:"registration_failed";return{code:t,message:EW[t]}}function as(n){if(!n||typeof n!="object")return{state:"idle",attempt:0};let t=PNe.has(n.state)?n.state:"error",o=ln(n.attempt)?n.attempt:WC(n.attempt)??0,i={state:t,attempt:o};i.operation=GNe.has(n.operation)?n.operation:"provision";let e=WC(n.updatedAt),a=WC(n.expiresAt),A=WC(n.remainingSeconds),r=WC(n.pollIntervalSeconds);e!==void 0&&(i.updatedAt=e),typeof n.qrCodeUrl=="string"&&n.qrCodeUrl.length>0&&(i.qrCodeUrl=n.qrCodeUrl),a!==void 0&&(i.expiresAt=a),A!==void 0&&(i.remainingSeconds=A),r!==void 0&&(i.pollIntervalSeconds=r),ln(n.botId)&&(i.botId=n.botId);let s=Mv(n.error);return s&&(i.error=s),i}function xNe(n,t,o){if(!(typeof n!="string"||n.length===0))try{let i=new URL(n);if(i.protocol!=="https:"||!FNe.has(i.hostname)||i.port||i.username||i.password)return;if(Hm.has(t)){let e=i.searchParams.getAll("clientID"),a=i.searchParams.getAll("tp"),A=i.searchParams.getAll("addons"),r=[...i.searchParams.values()].some(s=>s.includes("{{")||s.includes("}}"));if(e.length!==1||a.length!==1||a[0]!=="sdk"||!UNe.test(e[0]??"")||i.hostname!==o||i.searchParams.has("createOnly")||A.length!==1||!A[0]?.trim()||r)return}return i.toString()}catch{return}}function Km(n){let t=n&&typeof n=="object"?n:{};return{connected:t.connected===!0||t.ready===!0&&t.feishuLongConnectionState==="connected"&&t.harnessReachable===!0,ready:t.ready===!0,harnessReachable:t.harnessReachable===!0}}function yW(n){let t=n&&typeof n=="object"?n:{},o={name:typeof t.name=="string"&&t.name.length>0?t.name:"\u98DE\u4E66\u673A\u5668\u4EBA"};return typeof t.avatarUrl=="string"&&(o.avatarUrl=t.avatarUrl),typeof t.appIdMasked=="string"&&(o.appIdMasked=t.appIdMasked),typeof t.tenantName=="string"&&(o.tenantName=t.tenantName),(t.domain==="feishu"||t.domain==="lark")&&(o.domain=t.domain),(typeof t.activated=="boolean"||typeof t.activated=="number")&&(o.activated=t.activated),o}function mW(n,t){return t?{status:"healthy",summary:"\u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38",lastCheckedAt:Date.now()}:n?.configured===!0?{status:"offline",summary:"\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",lastCheckedAt:Date.now()}:{status:"offline",summary:"\u5C1A\u672A\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA",lastCheckedAt:Date.now()}}function SW(n,t,o){return o?"connected":n?.phase==="error"||t.state==="error"?"error":n?.phase==="connecting"||t.state==="saving"?"connecting":n?.phase==="registering"||["starting","qr_ready","polling","slow_down","domain_switched"].includes(t.state)?"provisioning":"disconnected"}async function DW(n){return vNe.toDataURL(n,{errorCorrectionLevel:"M",margin:1,width:320,type:"image/png"})}async function YNe(n,t,o){let i=xNe(n.qrCodeUrl,n.operation,o),e={attemptId:String(n.attempt),operation:n.operation,...n.botId?{botId:n.botId}:{},expiresAt:n.expiresAt??Date.now()+5*6e4,pollIntervalMs:Math.max(800,Math.min(1e4,(n.pollIntervalSeconds??1.8)*1e3))};if(i)return{...e,verificationUrl:i,qrCodeDataUrl:await t(i)};if(n.state==="saving"&&Hm.has(n.operation)&&n.botId)return{...e,submitted:!0}}function jNe(n){let t=n&&typeof n=="object"?n:{};if(!ln(t.botId))return null;let o=Km(t.connection),i=t.connected===!0||o.connected,e={state:"idle"},a={botId:t.botId,state:SW(t,e,i),connected:i,configured:t.configured===!0,agentPreset:xs(t.agentPreset),groupResponseMode:Wi(t.groupResponseMode),groupMessagePermissionGranted:t.groupMessagePermissionGranted===!0,bot:yW(t.bot),health:mW(t,i)};typeof t.workspace=="string"&&t.workspace&&(a.workspace=t.workspace);let A=zr(t.lastMessageError);A&&(a.lastMessageError=A);let r=Mv(t.error);return r&&(a.error=r),a}async function Wa(n,{encodeQr:t=DW}={}){let o=n&&typeof n=="object"?n:{},i=as(o.registration),e=Km(o.connection),a=o.connected===!0||e.connected,r=(Hm.has(i.operation)&&i.botId&&Array.isArray(o.bots)?o.bots.find(d=>d?.botId===i.botId):void 0)?.bot?.domain==="lark"?"open.larksuite.com":"open.feishu.cn",s=await YNe(i,t,r),g=Mv(o.error)??i.error??null,c=Array.isArray(o.bots)?o.bots.map(jNe).filter(Boolean):[],I={schemaVersion:o.schemaVersion===2?2:1,revision:Number.isSafeInteger(o.revision)&&o.revision>=0?o.revision:0,state:SW(o,i,a),connected:a,configured:o.configured===!0,bot:yW(o.bot),health:mW(o,a),bots:c,agentPresetCatalog:Pn(o.agentPresetCatalog),totals:{configured:c.length||(o.configured===!0?1:0),connected:c.length?c.filter(d=>d.connected).length:a?1:0}};return s&&(I.provisioning=s),g&&(I.error=g),I}function Lm(n){return{ok:!1,error:{code:"bad-request",message:n,details:{issues:[]}}}}function Um(){return{ok:!1,error:{code:"cancelled",message:"The Feishu request was cancelled.",details:{}}}}function JNe(){return{ok:!1,error:{code:"internal",message:"The Feishu integration operation failed.",details:{}}}}function qNe(n,t){return n===vt.status?To(t,new Set)?null:"This endpoint accepts an empty payload only.":n===vt.testConnection?To(t,new Set)?null:"This endpoint accepts an empty payload only.":n===vt.beginProvisioning?To(t,new Set(["locale","replaceAttemptId"]))?t.locale!==void 0&&t.locale!=="zh-CN"?"The provisioning locale must be zh-CN.":t.replaceAttemptId!==void 0&&!ln(t.replaceAttemptId)?"replaceAttemptId must be a valid opaque id.":null:"Provisioning accepts locale and replaceAttemptId only.":n===vt.beginCallbackRepair?To(t,new Set(["botId"]))&&ln(t.botId)?null:"Callback repair requires a single valid botId.":n===vt.beginGroupMessagePermission?To(t,new Set(["botId"]))&&ln(t.botId)?null:"Group message permission update requires a single valid botId.":n===vt.bindCredentials?To(t,new Set(["appId","appSecret"]))&&CW(t.appId,256)&&CW(t.appSecret,1024)?null:"Credential binding requires App ID and App Secret.":n===vt.pollProvisioning||n===vt.cancelProvisioning?To(t,new Set(["attemptId"]))&&ln(t.attemptId)?null:"A single valid attemptId is required.":n===vt.disconnect?To(t,new Set(["removeCredentials"]))&&t.removeCredentials===!0?null:"Disconnect requires removeCredentials=true.":n===jI.reconnectBot?To(t,new Set(["botId","sendTest"]))&&ln(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"A valid botId and optional sendTest flag are required.":n===jI.disconnectBot?To(t,new Set(["botId"]))&&ln(t.botId)?null:"A single valid botId is required.":n===jI.deleteBot?To(t,new Set(["botId","confirm"]))&&ln(t.botId)&&t.confirm===!0?null:"Deleting a bot requires a valid botId and confirm=true.":n===vt.setWorkspace?Fa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===vt.setAgentPreset?Ua(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===vt.setGroupResponseMode?To(t,new Set(["botId","groupResponseMode"]))&&ln(t.botId)&&lm(t.groupResponseMode)?null:"\u8BF7\u9009\u62E9\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F\u3002":"Unknown Feishu endpoint."}function zNe(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new Error("aborted"));return}let e=setTimeout(a,n);e.unref?.();function a(){t?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(t.reason??new Error("aborted"))}t?.addEventListener("abort",A,{once:!0})})}async function bv(n,t){return typeof n.registrationStatus=="function"?n.registrationStatus(t):n.status()}async function wv(n,t,o,i){let e=t,a=Date.now()+15e3;for(;;){let A=as(e?.registration);if(A.qrCodeUrl)return e;if(["error","expired","cancelled"].includes(A.state))throw new Error("Provisioning stopped before the QR code was ready.");if(Date.now()>=a)throw new Error("Provisioning QR code timed out.");if(await zNe(50,i),e=await bv(n,o),!e)throw new Error("The provisioning attempt is no longer active.")}}function uW(n,t){return String(as(n?.registration).attempt)===t}function BW(n){let t=as(n?.registration);return t.state==="succeeded"?t.botId&&(n?.connected===!0||Km(n?.connection).connected)?"connected":"connecting":HNe[t.state]??"failed"}function VNe(n){if(!n||typeof n.status!="function"||typeof n.startRegistration!="function"||typeof n.cancelRegistration!="function"||typeof n.disconnect!="function")throw new TypeError("A Feishu controller with status/start/cancel/disconnect is required")}function wW(n,{encodeQr:t=DW}={}){VNe(n);let o=new Map,i=new Map,e=a=>{let A=o.get(a);return A||(o.size>=32&&o.delete(o.keys().next().value),A=Promise.resolve().then(()=>t(a)),o.set(a,A)),A};return async(a,A,r)=>{if(r?.aborted)return Um();if(!fW.includes(a))return Lm("Unknown Feishu endpoint.");let s=qNe(a,A);if(s)return Lm(s);try{let g;if(a===vt.status)g=await Wa(await n.status(),{encodeQr:e});else if(a===vt.beginProvisioning){A.replaceAttemptId&&await n.cancelRegistration(A.replaceAttemptId);let c=await n.startRegistration({locale:A.locale}),I=String(as(c?.registration).attempt),d=await wv(n,c,I,r);if(g=(await Wa(d,{encodeQr:e})).provisioning,!g)throw new Error("Provisioning did not produce a QR code.");i.set(I,g.verificationUrl)}else if(a===vt.beginCallbackRepair){if(typeof n.startCallbackRepair!="function")throw new Error("Feishu callback repair is unavailable.");let c=await n.startCallbackRepair(A.botId),I=String(as(c?.registration).attempt),d=await wv(n,c,I,r);if(g=(await Wa(d,{encodeQr:e})).provisioning,!g||g.operation!==QW||g.botId!==A.botId)throw new Error("Callback repair did not produce a safe QR code.");i.set(I,g.verificationUrl)}else if(a===vt.beginGroupMessagePermission){if(typeof n.startGroupMessagePermission!="function")throw new Error("Feishu group message permission update is unavailable.");let c=await n.startGroupMessagePermission(A.botId),I=String(as(c?.registration).attempt),d=await wv(n,c,I,r);if(g=(await Wa(d,{encodeQr:e})).provisioning,!g||g.operation!==Ov||g.botId!==A.botId)throw new Error("Group message permission update did not produce a safe QR code.");i.set(I,g.verificationUrl)}else if(a===vt.pollProvisioning){let c=await bv(n,A.attemptId);if(!c||!uW(c,A.attemptId))return Lm("The provisioning attempt is no longer active.");let I=as(c.registration),d=await Wa(c,{encodeQr:e});if(g={status:BW(c),operation:I.operation,...I.botId?{botId:I.botId}:{},...d.provisioning?{provisioning:d.provisioning}:{},...I.botId&&d.connected?{connection:d}:{},...d.error?{message:d.error.message}:{}},["connected","expired","failed"].includes(g.status)){let B=i.get(A.attemptId);B&&o.delete(B),i.delete(A.attemptId)}}else if(a===vt.cancelProvisioning){let c=await bv(n,A.attemptId);if(!c||!uW(c,A.attemptId))return Lm("The provisioning attempt is no longer active.");let I=typeof n.registrationStatus=="function",d=as(c.registration),B;!I&&d.state==="saving"?B=await n.disconnect():B=await n.cancelRegistration(A.attemptId);let f=as(B?.registration);if(Hm.has(d.operation)&&d.state==="saving"&&["saving","succeeded"].includes(f.state)&&(g={status:BW(B),operation:f.operation,...f.botId?{botId:f.botId}:{},message:d.operation===Ov?"The permission update was already submitted and is still being applied.":"Callback repair was already submitted and is still being verified."}),g?.status!=="connecting"){let Q=i.get(A.attemptId);Q&&o.delete(Q),i.delete(A.attemptId),g??={status:"failed",operation:d.operation,...d.botId?{botId:d.botId}:{},message:"Registration was cancelled."}}}else if(a===vt.bindCredentials){if(typeof n.bindCredentials!="function")throw new Error("Credential binding is unavailable");g=await Wa(await n.bindCredentials(A),{encodeQr:e})}else if(a===vt.testConnection){let c=await n.status(),d=c?.connected===!0||Km(c?.connection).connected||typeof n.reconnect!="function"?c:await n.reconnect();g=await Wa(d,{encodeQr:e})}else if(a===vt.disconnect)g=await Wa(await n.disconnect(),{encodeQr:e});else if(a===jI.reconnectBot){if(typeof n.reconnectBot!="function")throw new Error("Multi-bot reconnect is unavailable");let c=await n.reconnectBot(A.botId);if(r?.aborted)return Um();if(g=await Wa(c,{encodeQr:e}),A.sendTest===!0){let I=null;if(!(c?.bots?.some(B=>B?.botId===A.botId&&B.connected===!0)===!0))I=new Error("Feishu bot is not connected"),I.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let B=new Error("Connection test is unavailable");throw B.code="test-target-unavailable",B}await n.sendConnectionTest(A.botId)}catch(B){I=B}g={...g,testMessage:ar(I)}}}else if(a===jI.disconnectBot){if(typeof n.disconnectBot!="function")throw new Error("Multi-bot disconnect is unavailable");g=await Wa(await n.disconnectBot(A.botId),{encodeQr:e})}else if(a===vt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");g=await Wa(await n.updateWorkspace(A.botId,A.workspace),{encodeQr:e})}else if(a===vt.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");g=await Wa(await n.updateAgentPreset(A.botId,A.agentPreset),{encodeQr:e})}else if(a===vt.setGroupResponseMode){if(typeof n.updateGroupResponseMode!="function")throw new Error("Group response mode update is unavailable");g=await Wa(await n.updateGroupResponseMode(A.botId,A.groupResponseMode),{encodeQr:e})}else{if(typeof n.deleteBot!="function")throw new Error("Multi-bot delete is unavailable");g=await Wa(await n.deleteBot(A.botId),{encodeQr:e})}return r?.aborted?Um():{ok:!0,value:g}}catch(g){let c=La(g);return r?.aborted?Um():c?{ok:!1,error:{...c,details:{}}}:JNe()}}}function xm(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(Dv,wW(t,o),{authority:mr(i)})}function WNe(n,t){if(t?.controller)return t.controller;if(typeof t?.createController=="function")return t.createController();if(typeof t?.createProvisioningManager=="function")return i_(t)}async function OW(n,t={}){let o=WNe(n,t);if(o)return xm(n,o,t.rpcOptions,t.rpcAuthority);let i=await Cv(n,t),e=xm(n,i.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i.close()},"dsh-feishu: close controller and live connection"),e}import{unlink as JRe}from"node:fs/promises";import{homedir as qRe}from"node:os";import{join as Au,resolve as zI}from"node:path";import{createHash as ZNe}from"node:crypto";import{mkdir as XNe,readFile as $Ne,rename as eRe,unlink as ARe,writeFile as tRe}from"node:fs/promises";import{dirname as rRe}from"node:path";var _v=Object.freeze({version:1,bots:Object.freeze([])});function lc(n){return typeof n=="string"&&n.trim()?n.trim():null}function bW(n){let t=lc(n);return t&&/^qq_[a-f0-9]{24}$/.test(t)?t:null}function aRe(n){let t=lc(n);return t&&/^DSH_QQBOT_APP_SECRET_[A-F0-9]{24}$/.test(t)?t:null}function jm(n){let t=lc(n);if(!t)throw new TypeError("appId is required");let o=ZNe("sha256").update(t).digest("hex").slice(0,24);return{botId:`qq_${o}`,secretRef:`DSH_QQBOT_APP_SECRET_${o.toUpperCase()}`}}function Tv(n){let t=lc(n)??"";return t.length<=10?t?`${t.slice(0,3)}\u2022\u2022\u2022`:D("QQ\u673A\u5668\u4EBA"):`${t.slice(0,6)}\u2022\u2022\u2022\u2022${t.slice(-4)}`}function MW(n){if(!n||typeof n!="object")return null;let t=lc(n.appId),o=lc(n.ownerUserOpenid),i=bW(n.botId),e=aRe(n.secretRef);if(!t||!o||!i||!e)return null;let a=jm(t);return a.botId!==i||a.secretRef!==e?null:Object.freeze({botId:i,appId:t,secretRef:e,ownerUserOpenid:o,createdAt:lc(n.createdAt)??new Date().toISOString(),connectedAt:lc(n.connectedAt)})}function iRe(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let t=n.bots.map(MW);if(t.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of t){if(o.has(a.botId)||i.has(a.appId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.appId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(t)})}var Ym=class{#e;#A=_v;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=iRe(JSON.parse(await $Ne(this.#e,"utf8")));if(!t)throw new Error("dsh-im QQ config contains invalid bot data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=_v}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByAppId(t){let o=this.#A.bots.find(i=>i.appId===t);return o?structuredClone(o):null}async save(t){let o=MW(t);if(!o)throw new Error("Refusing to persist incomplete QQ bot data");return this.#r(i=>{let e=i.find(r=>r.appId===o.appId&&r.botId!==o.botId),a=i.find(r=>r.secretRef===o.secretRef&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate QQ bot identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!bW(t))throw new TypeError("Invalid QQ bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await ARe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=_v});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#a(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#a(t){await XNe(rRe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await tRe(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await eRe(o,this.#e)}};var Jm=class extends pr{constructor(t){super({...t,rpcIdPrefix:"qq",logPrefix:"dsh-qq"})}};import{randomUUID as oRe}from"node:crypto";var _W=new Set(["starting","pending","refreshing","connecting"]),JI=new Set(["connected","failed","cancelled"]),nRe=5*6e4;function qI(n){return typeof n=="string"&&n.trim()?n.trim():null}function pn(n,t){return Object.freeze({code:n,message:t})}function qm(n){return n?{attemptId:n.id,status:n.state,qrRevision:n.qrRevision,pollIntervalMs:1e3,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var ZC=class{#e;#A;#t;#r;#a;#i;#c=new Map;#s=new Map;#I=new Map;#o=null;#n=new Map;#g=0;#l=!1;constructor({qrAuth:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.start!="function")throw new TypeError("QQ QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("QqController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("QqController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#a=a,this.#i=A}async initialize(){if(this.#l)return this.status();for(let t of this.#t.list())await this.#f(t.botId,async()=>{if(this.#l||this.#c.get(t.botId)?.status?.ready)return;let o=await this.#B(t.secretRef);if(!o){this.#s.set(t.botId,pn("missing-secret",D("QQ \u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002")));return}try{await this.#h(t,o),this.#s.delete(t.botId)}catch(i){this.#s.set(t.botId,pn("connection-failed",D("QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#i.warn?.(`[dsh-im:qq] bot ${t.botId} failed to initialize:`,i)}finally{this.#m()}});return this.status()}async startProvisioning(){if(this.#l)throw new Error("QQ controller is closed");this.#o&&await this.cancelProvisioning(this.#o);let t,o,i=new Promise((a,A)=>{t=a,o=A}),e={id:oRe(),state:"starting",createdAt:Date.now(),expiresAt:null,qrRevision:0,verificationUrl:null,controller:new AbortController,dispose:null,task:null,error:null,botId:null};this.#I.set(e.id,e),this.#o=e.id,this.#m();try{return e.dispose=this.#e.start({onQrDisplayed:a=>{if(e.controller.signal.aborted||JI.has(e.state))return;let A=qI(a);A&&(e.verificationUrl=A,e.qrRevision+=1,e.expiresAt=Date.now()+nRe,e.state="pending",this.#m(),t())},onQrExpired:()=>{e.controller.signal.aborted||JI.has(e.state)||(e.state="refreshing",e.verificationUrl=null,e.expiresAt=null,this.#m())},onSuccess:a=>{e.controller.signal.aborted||JI.has(e.state)||(e.task=this.#p(e,a))},onFailure:a=>{e.controller.signal.aborted||JI.has(e.state)||(e.state="failed",e.error=pn("qr-connect-failed",D("QQ \u626B\u7801\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002")),this.#o===e.id&&(this.#o=null),this.#m(),o(a))}},{signal:e.controller.signal}),await i,qm(e)}catch(a){throw e.controller.signal.aborted?(e.state="cancelled",e.error=pn("cancelled",D("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):JI.has(e.state)||(e.state="failed",e.error=pn("qr-start-failed",D("\u65E0\u6CD5\u751F\u6210 QQ \u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),this.#o===e.id&&(this.#o=null),this.#m(),a}}registrationStatus(t){return qm(this.#I.get(t))}async bindCredentials({appId:t,appSecret:o}={}){if(this.#l)throw new Error("QQ controller is closed");let i=qI(t),e=qI(o);if(!i||!e)throw new TypeError("QQ AppID and AppSecret are required");if(this.#o&&await this.cancelProvisioning(this.#o),this.#l)throw new Error("QQ controller is closed");let a=jm(i);return await this.#f(a.botId,async()=>{if(this.#l)throw new Error("QQ controller is closed");let A=this.#t.getByAppId(i),r=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#l)throw new Error("QQ controller is closed");let s={botId:a.botId,appId:i,secretRef:a.secretRef,ownerUserOpenid:A?.ownerUserOpenid??"*",createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#u(a.secretRef,r),g}try{await this.#h(s,e),this.#s.delete(a.botId)}catch(g){this.#s.set(a.botId,pn("connection-failed",D("QQ \u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#i.warn?.(`[dsh-im:qq] bot ${a.botId} credential connection failed:`,g)}this.#m()}),this.status()}async cancelProvisioning(t){let o=this.#I.get(t);return o?(JI.has(o.state)||(o.controller.abort(),o.dispose?.(),await o.task?.catch(()=>{}),JI.has(o.state)||(o.state="cancelled"),o.error??=pn("cancelled",D("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))),this.#o===o.id&&(this.#o=null),this.#m(),qm(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown QQ bot");return await this.#f(t,async()=>{let i=await this.#B(o.secretRef);if(!i)throw new Error("QQ bot secret is missing");try{await this.#h(o,i),this.#s.delete(t)}catch(e){throw this.#s.set(t,pn("connection-failed",D("QQ \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#m()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown QQ bot");return this.#f(t,async()=>{let i=this.#c.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error(D("QQ\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(Da(D("QQ \u673A\u5668\u4EBA\uFF08{appId}\uFF09",{appId:Tv(o.appId)}))),{sent:!0}})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown QQ bot");return await this.#f(t,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#E(t);try{await this.#A.unset(o.secretRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the QQ bot safely.",{cause:e})}await this.#a({botId:t,config:o}).catch(e=>{this.#i.warn?.(`[dsh-im:qq] bot ${t} state cleanup failed:`,e)}),this.#s.delete(t),this.#m()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#c.get(e.botId)?.status??null,A=a?.ready===!0&&a.qqConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.qqConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||a?.qqConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:D("QQ\u673A\u5668\u4EBA"),appIdMasked:Tv(e.appId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?D("QQ WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38"):r==="error"?D("QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):D("QQ \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:zr(a?.lastMessageError),error:structuredClone(this.#s.get(e.botId)??null)}}),o=t.filter(e=>e.connected).length,i=this.#o?this.#I.get(this.#o):null;return{schemaVersion:1,revision:this.#g,state:i&&_W.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&_W.has(i.state)?{provisioning:qm(i)}:{}}}async close(){this.#l||(this.#l=!0,this.#o&&await this.cancelProvisioning(this.#o),await Promise.allSettled([...this.#n.values()]),await Promise.allSettled([...this.#c.keys()].map(t=>this.#E(t))))}async#p(t,o){try{t.state="connecting",t.verificationUrl=null,t.expiresAt=null,this.#m();let i=Array.isArray(o)?o[0]:null,e=qI(i?.appId),a=qI(i?.appSecret),A=qI(i?.userOpenid);if(!e||!a||!A)throw new Error("QQ authorization returned incomplete credentials");t.botId=await this.#d(t,{appId:e,appSecret:a,ownerUserOpenid:A}),t.state="connected",t.error=null}catch(i){t.controller.signal.aborted?(t.state="cancelled",t.error=pn("cancelled",D("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=pn("activation-failed",D("QQ \u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u63A5\u5165\u914D\u7F6E\u3002")),this.#i.error?.("[dsh-im:qq] provisioning failed:",i))}finally{t.dispose?.(),this.#o===t.id&&(this.#o=null),this.#m()}}async#d(t,{appId:o,appSecret:i,ownerUserOpenid:e}){let a=jm(o),A=this.#t.getByAppId(o),r=await this.#A.resolve(a.secretRef).catch(()=>{}),s={botId:a.botId,appId:o,secretRef:a.secretRef,ownerUserOpenid:e,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#f(a.botId,async()=>{await this.#A.set(a.secretRef,i);try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(s)}catch(g){throw await this.#u(a.secretRef,r),g}try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#h(s,i),this.#s.delete(a.botId)}catch(g){if(t.controller.signal.aborted)throw await this.#E(a.botId),A?await this.#t.save(A).catch(()=>{}):await this.#t.remove(a.botId).catch(()=>null)&&await this.#a({botId:a.botId,config:s}).catch(I=>{this.#i.warn?.("[dsh-im:qq] cancelled bot state cleanup failed:",I)}),await this.#u(a.secretRef,r),g;this.#s.set(a.botId,pn("connection-failed",D("QQ \u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#i.warn?.(`[dsh-im:qq] bot ${a.botId} activation connection failed:`,g)}return this.#m(),a.botId})}async#h(t,o){if(this.#l)throw new Error("QQ controller is closed");if(await this.#E(t.botId),this.#l)throw new Error("QQ controller is closed");let i=await this.#r({botId:t.botId,config:t,appSecret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid QQ runtime");this.#c.set(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#c.delete(t.botId),e}}async#E(t){let o=this.#c.get(t);this.#c.delete(t),await o?.stop().catch(i=>{this.#i.warn?.(`[dsh-im:qq] bot ${t} failed to stop cleanly:`,i)})}async#B(t){let o=await this.#A.resolve(t).catch(()=>{});return qI(o?.value)}async#u(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#f(t,o){let a=(this.#n.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#n.get(t)===a&&this.#n.delete(t)});return this.#n.set(t,a),a}#m(){this.#g+=1}};import{QQBot as RRe,typingIndicator as kRe}from"@tencent-connect/qqbot-nodejs";import{ApiError as sRe}from"@tencent-connect/qqbot-nodejs";var TW=4500,gRe=/^( {0,3})(`{3,}|~{3,})(.*)$/,cRe=new Set([40034090]),IRe=Object.freeze({c2c:4,group:5}),lRe=()=>D("\u56DE\u7B54\u8F83\u957F\uFF0C\u540E\u7EED\u5185\u5BB9\u672A\u80FD\u901A\u8FC7 QQ \u5B8C\u6574\u53D1\u9001\uFF0C\u8BF7\u56DE\u590D\u201C\u7EE7\u7EED\u201D\u3002");function Rv(n,t){let o=Math.min(t,n.length),i=n.charCodeAt(o-1),e=n.charCodeAt(o);return i>=55296&&i<=56319&&e>=56320&&e<=57343&&(o-=1),Math.max(1,o)}function kW(n){let t=n.endsWith("\r")?n.slice(0,-1):n,o=gRe.exec(t);return!o||o[2][0]==="`"&&o[3].includes("`")?null:{delimiter:o[2],info:o[3],indent:o[1].length}}function pRe(n,t){let o=/^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(n);return!!(o&&o[1][0]===t.delimiter[0]&&o[1].length>=t.delimiter.length)}function NW(n,t){let o=0;for(let i of n.split(` `)){let e=0;for(;e<3&&i[e]===" ";)e+=1;let a=0;for(;i[e+a]===t;)a+=1;o=Math.max(o,a)}return o}function dRe(n,t){let o="`".repeat(Math.max(3,NW(n,"`")+1)),i="~".repeat(Math.max(3,NW(n,"~")+1));return t.includes("`")?i:o.length<=i.length?o:i}function hRe(n,t){let o=0,i=0,e=t;for(;e>0&&ohRe(o,t))}function Nv(n,t){if(n.length<=t)return[n];let o=[],i=n;for(;i.length>t;){let e=Rv(i,t),a=i.lastIndexOf(` @@ -406,8 +406,8 @@ ${B}`:dt(m),s,g),I||await this.#i.markSeen(A)}catch(_){this.#s.error?.("[dsh-wei `);let o=Bn(n.content,t+1),i=`<${n.tag} ${Object.entries(n.attrs||{}).filter(([,a])=>a!==void 0).map(([a,A])=>`${a}='${A}'`).join(" ")}`,e=o?`> ${o} ${lD(t)}`:"/>";return i+e}var _c=qe(Bc(),1);import{createCipheriv as PG,createDecipheriv as GG,createHash as ALe,createHmac as tLe,randomBytes as rLe}from"crypto";var xu=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,B9.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,B9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_expandedappstatekeys_free(t,0)}get indexKey(){let t=ae.expandedappstatekeys_indexKey(this.__wbg_ptr);return mA(t)}get patchMacKey(){let t=ae.expandedappstatekeys_patchMacKey(this.__wbg_ptr);return mA(t)}get snapshotMacKey(){let t=ae.expandedappstatekeys_snapshotMacKey(this.__wbg_ptr);return mA(t)}get valueEncryptionKey(){let t=ae.expandedappstatekeys_valueEncryptionKey(this.__wbg_ptr);return mA(t)}get valueMacKey(){let t=ae.expandedappstatekeys_valueMacKey(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(xu.prototype[Symbol.dispose]=xu.prototype.free);var dD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,f9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_groupcipher_free(t,0)}decrypt(t){let o=_t(t,ae.__wbindgen_export),i=KA,e=ae.groupcipher_decrypt(this.__wbg_ptr,o,i);return mA(e)}encrypt(t){let o=_t(t,ae.__wbindgen_export),i=KA,e=ae.groupcipher_encrypt(this.__wbg_ptr,o,i);return mA(e)}constructor(t,o,i){let e=Qn(o,ae.__wbindgen_export,ae.__wbindgen_export2),a=KA;bc(i,Mc);let A=ae.groupcipher_new(tA(t),e,a,i.__wbg_ptr);return this.__wbg_ptr=A>>>0,f9.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(dD.prototype[Symbol.dispose]=dD.prototype.free);var hD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Q9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_groupsessionbuilder_free(t,0)}create(t){bc(t,Pd);let o=ae.groupsessionbuilder_create(this.__wbg_ptr,t.__wbg_ptr);return mA(o)}constructor(t){let o=ae.groupsessionbuilder_new(tA(t));return this.__wbg_ptr=o>>>0,Q9.register(this,this.__wbg_ptr,this),this}process(t,o){bc(t,Pd),bc(o,vd);let i=ae.groupsessionbuilder_process(this.__wbg_ptr,t.__wbg_ptr,o.__wbg_ptr);return mA(i)}};Symbol.dispose&&(hD.prototype[Symbol.dispose]=hD.prototype.free);var Yu=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,y9.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,y9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_internalbinarynode_free(t,0)}get attrs(){let t=ae.internalbinarynode_attrs(this.__wbg_ptr);return mA(t)}get content(){let t=ae.internalbinarynode_content(this.__wbg_ptr);return mA(t)}set attrs(t){ae.internalbinarynode_set_attrs(this.__wbg_ptr,tA(t))}set content(t){ae.internalbinarynode_set_content(this.__wbg_ptr,tA(t))}get tag(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.internalbinarynode_tag(a,this.__wbg_ptr);var i=$e().getInt32(a+0,!0),e=$e().getInt32(a+4,!0);return t=i,o=e,wr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}toJSON(){let t=ae.internalbinarynode_toJSON(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(Yu.prototype[Symbol.dispose]=Yu.prototype.free);var kd=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,m9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_lthashantitampering_free(t,0)}constructor(){let t=ae.lthashantitampering_new();return this.__wbg_ptr=t>>>0,m9.register(this,this.__wbg_ptr,this),this}subtractThenAdd(t,o,i){try{let r=ae.__wbindgen_add_to_stack_pointer(-16),s=_t(t,ae.__wbindgen_export),g=KA,c=T9(o,ae.__wbindgen_export),I=KA,d=T9(i,ae.__wbindgen_export),B=KA;ae.lthashantitampering_subtractThenAdd(r,this.__wbg_ptr,s,g,c,I,d,B);var e=$e().getInt32(r+0,!0),a=$e().getInt32(r+4,!0),A=$e().getInt32(r+8,!0);if(A)throw mA(a);return mA(e)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(kd.prototype[Symbol.dispose]=kd.prototype.free);var ED=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,TG.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,TG.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_lthashstate_free(t,0)}clone(){let t=ae.lthashstate_clone(this.__wbg_ptr);return n.__wrap(t)}deleteValueMac(t){let o=Qn(t,ae.__wbindgen_export,ae.__wbindgen_export2),i=KA;return ae.lthashstate_deleteValueMac(this.__wbg_ptr,o,i)!==0}getValueMac(t){let o=Qn(t,ae.__wbindgen_export,ae.__wbindgen_export2),i=KA,e=ae.lthashstate_getValueMac(this.__wbg_ptr,o,i);return mA(e)}hasValueMac(t){let o=Qn(t,ae.__wbindgen_export,ae.__wbindgen_export2),i=KA;return ae.lthashstate_hasValueMac(this.__wbg_ptr,o,i)!==0}get hash(){let t=ae.lthashstate_hash(this.__wbg_ptr);return mA(t)}constructor(){let t=ae.lthashstate_new();return this.__wbg_ptr=t>>>0,TG.register(this,this.__wbg_ptr,this),this}setValueMac(t,o){let i=Qn(t,ae.__wbindgen_export,ae.__wbindgen_export2),e=KA,a=_t(o,ae.__wbindgen_export),A=KA;ae.lthashstate_setValueMac(this.__wbg_ptr,i,e,a,A)}set hash(t){let o=_t(t,ae.__wbindgen_export),i=KA;ae.lthashstate_set_hash(this.__wbg_ptr,o,i)}set version(t){ae.lthashstate_set_version(this.__wbg_ptr,t)}get version(){let t=ae.lthashstate_version(this.__wbg_ptr);return BigInt.asUintN(64,t)}};Symbol.dispose&&(ED.prototype[Symbol.dispose]=ED.prototype.free);var CD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,S9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_noisesession_free(t,0)}authenticate(t){let o=_t(t,ae.__wbindgen_export),i=KA;ae.noisesession_authenticate(this.__wbg_ptr,o,i)}get bufferedBytes(){return ae.noisesession_bufferedBytes(this.__wbg_ptr)>>>0}clearBuffer(){ae.noisesession_clearBuffer(this.__wbg_ptr)}decodeFrame(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=_t(t,ae.__wbindgen_export),r=KA;ae.noisesession_decodeFrame(a,this.__wbg_ptr,A,r);var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}decrypt(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=_t(t,ae.__wbindgen_export),r=KA;ae.noisesession_decrypt(a,this.__wbg_ptr,A,r);var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}encodeFrame(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.noisesession_encodeFrame(a,this.__wbg_ptr,tA(t));var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}encodeFrameRaw(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=_t(t,ae.__wbindgen_export),r=KA;ae.noisesession_encodeFrameRaw(a,this.__wbg_ptr,A,r);var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}encrypt(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=_t(t,ae.__wbindgen_export),r=KA;ae.noisesession_encrypt(a,this.__wbg_ptr,A,r);var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}finishInit(){try{let i=ae.__wbindgen_add_to_stack_pointer(-16);ae.noisesession_finishInit(i,this.__wbg_ptr);var t=$e().getInt32(i+0,!0),o=$e().getInt32(i+4,!0);if(o)throw mA(t)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}getHash(){let t=ae.noisesession_getHash(this.__wbg_ptr);return mA(t)}get isFinished(){return ae.noisesession_isFinished(this.__wbg_ptr)!==0}mixIntoKey(t){try{let e=ae.__wbindgen_add_to_stack_pointer(-16),a=_t(t,ae.__wbindgen_export),A=KA;ae.noisesession_mixIntoKey(e,this.__wbg_ptr,a,A);var o=$e().getInt32(e+0,!0),i=$e().getInt32(e+4,!0);if(i)throw mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}constructor(t,o,i){try{let g=ae.__wbindgen_add_to_stack_pointer(-16),c=_t(t,ae.__wbindgen_export),I=KA,d=_t(o,ae.__wbindgen_export),B=KA;var e=fn(i)?0:_t(i,ae.__wbindgen_export),a=KA;ae.noisesession_new(g,c,I,d,B,e,a);var A=$e().getInt32(g+0,!0),r=$e().getInt32(g+4,!0),s=$e().getInt32(g+8,!0);if(s)throw mA(r);return this.__wbg_ptr=A>>>0,S9.register(this,this.__wbg_ptr,this),this}finally{ae.__wbindgen_add_to_stack_pointer(16)}}processHandshakeFinish(t,o,i){try{let r=ae.__wbindgen_add_to_stack_pointer(-16),s=_t(t,ae.__wbindgen_export),g=KA,c=_t(o,ae.__wbindgen_export),I=KA,d=_t(i,ae.__wbindgen_export),B=KA;ae.noisesession_processHandshakeFinish(r,this.__wbg_ptr,s,g,c,I,d,B);var e=$e().getInt32(r+0,!0),a=$e().getInt32(r+4,!0),A=$e().getInt32(r+8,!0);if(A)throw mA(a);return mA(e)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}processHandshakeInit(t,o,i,e){try{let s=ae.__wbindgen_add_to_stack_pointer(-16),g=_t(t,ae.__wbindgen_export),c=KA,I=_t(o,ae.__wbindgen_export),d=KA,B=_t(i,ae.__wbindgen_export),f=KA,Q=_t(e,ae.__wbindgen_export),y=KA;ae.noisesession_processHandshakeInit(s,this.__wbg_ptr,g,c,I,d,B,f,Q,y);var a=$e().getInt32(s+0,!0),A=$e().getInt32(s+4,!0),r=$e().getInt32(s+8,!0);if(r)throw mA(A);return mA(a)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(CD.prototype[Symbol.dispose]=CD.prototype.free);var Mc=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,NG.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,NG.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_protocoladdress_free(t,0)}get deviceId(){return ae.protocoladdress_deviceId(this.__wbg_ptr)>>>0}static from(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_from(a,tA(t));var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}get id(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_id(a,this.__wbg_ptr);var i=$e().getInt32(a+0,!0),e=$e().getInt32(a+4,!0);return t=i,o=e,wr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}is(t){return bc(t,n),ae.protocoladdress_is(this.__wbg_ptr,t.__wbg_ptr)!==0}constructor(t,o){try{let A=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_new(A,tA(t),tA(o));var i=$e().getInt32(A+0,!0),e=$e().getInt32(A+4,!0),a=$e().getInt32(A+8,!0);if(a)throw mA(e);return this.__wbg_ptr=i>>>0,NG.register(this,this.__wbg_ptr,this),this}finally{ae.__wbindgen_add_to_stack_pointer(16)}}toString(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_toString(a,this.__wbg_ptr);var i=$e().getInt32(a+0,!0),e=$e().getInt32(a+4,!0);return t=i,o=e,wr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}};Symbol.dispose&&(Mc.prototype[Symbol.dispose]=Mc.prototype.free);var vd=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,D9.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,D9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_senderkeydistributionmessage_free(t,0)}static deserialize(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=_t(t,ae.__wbindgen_export),r=KA;ae.senderkeydistributionmessage_deserialize(a,A,r);var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}serialize(){let t=ae.senderkeydistributionmessage_serialize(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(vd.prototype[Symbol.dispose]=vd.prototype.free);var Pd=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,w9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_senderkeyname_free(t,0)}constructor(t,o){let i=Qn(t,ae.__wbindgen_export,ae.__wbindgen_export2),e=KA;bc(o,Mc);let a=ae.senderkeyname_new(i,e,o.__wbg_ptr);return this.__wbg_ptr=a>>>0,w9.register(this,this.__wbg_ptr,this),this}toString(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.senderkeyname_toString(a,this.__wbg_ptr);var i=$e().getInt32(a+0,!0),e=$e().getInt32(a+4,!0);return t=i,o=e,wr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}};Symbol.dispose&&(Pd.prototype[Symbol.dispose]=Pd.prototype.free);var uD=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,RG.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,RG.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_senderkeyrecord_free(t,0)}static deserialize(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=_t(t,ae.__wbindgen_export),r=KA;ae.senderkeyrecord_deserialize(a,A,r);var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}isEmpty(){return ae.senderkeyrecord_isEmpty(this.__wbg_ptr)!==0}constructor(){let t=ae.senderkeyrecord_new();return this.__wbg_ptr=t>>>0,RG.register(this,this.__wbg_ptr,this),this}serialize(){try{let e=ae.__wbindgen_add_to_stack_pointer(-16);ae.senderkeyrecord_serialize(e,this.__wbg_ptr);var t=$e().getInt32(e+0,!0),o=$e().getInt32(e+4,!0),i=$e().getInt32(e+8,!0);if(i)throw mA(o);return mA(t)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(uD.prototype[Symbol.dispose]=uD.prototype.free);var BD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,O9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_sessionbuilder_free(t,0)}initOutgoing(t){let o=ae.sessionbuilder_initOutgoing(this.__wbg_ptr,tA(t));return mA(o)}constructor(t,o){bc(o,Mc);let i=ae.sessionbuilder_new(tA(t),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,O9.register(this,this.__wbg_ptr,this),this}processPreKeyBundle(t){let o=ae.sessionbuilder_processPreKeyBundle(this.__wbg_ptr,tA(t));return mA(o)}};Symbol.dispose&&(BD.prototype[Symbol.dispose]=BD.prototype.free);var fD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,b9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_sessioncipher_free(t,0)}decryptPreKeyWhisperMessage(t){let o=_t(t,ae.__wbindgen_export),i=KA,e=ae.sessioncipher_decryptPreKeyWhisperMessage(this.__wbg_ptr,o,i);return mA(e)}decryptWhisperMessage(t){let o=_t(t,ae.__wbindgen_export),i=KA,e=ae.sessioncipher_decryptWhisperMessage(this.__wbg_ptr,o,i);return mA(e)}encrypt(t){let o=_t(t,ae.__wbindgen_export),i=KA,e=ae.sessioncipher_encrypt(this.__wbg_ptr,o,i);return mA(e)}hasOpenSession(){let t=ae.sessioncipher_hasOpenSession(this.__wbg_ptr);return mA(t)}constructor(t,o){bc(o,Mc);let i=ae.sessioncipher_new(tA(t),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,b9.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(fD.prototype[Symbol.dispose]=fD.prototype.free);var ju=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,M9.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,M9.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_sessionrecord_free(t,0)}static deserialize(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.sessionrecord_deserialize(a,tA(t));var o=$e().getInt32(a+0,!0),i=$e().getInt32(a+4,!0),e=$e().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}haveOpenSession(){return ae.sessionrecord_haveOpenSession(this.__wbg_ptr)!==0}serialize(){let t=ae.sessionrecord_serialize(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(ju.prototype[Symbol.dispose]=ju.prototype.free);function N9(n){let t=_t(n,ae.__wbindgen_export),o=KA,i=ae.expandAppStateKeys(t,o);return xu.__wrap(i)}function yn(n,t,o){try{let A=ae.__wbindgen_add_to_stack_pointer(-16),r=_t(n,ae.__wbindgen_export),s=KA;ae.hkdf(A,r,s,t,tA(o));var i=$e().getInt32(A+0,!0),e=$e().getInt32(A+4,!0),a=$e().getInt32(A+8,!0);if(a)throw mA(e);return mA(i)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}function HFe(){return{__proto__:null,"./whatsapp_rust_bridge_bg.js":{__proto__:null,__wbg_Error_83742b46f01ce22d:function(t,o){let i=Error(wr(t,o));return tA(i)},__wbg_Number_a5a435bd7bbec835:function(t){return Number(Ge(t))},__wbg_String_8564e559799eccda:function(t,o){let i=String(Ge(o)),e=Qn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=KA;$e().setInt32(t+4,a,!0),$e().setInt32(t+0,e,!0)},__wbg___wbindgen_bigint_get_as_i64_447a76b5c6ef7bda:function(t,o){let i=Ge(o),e=typeof i=="bigint"?i:void 0;$e().setBigInt64(t+8,fn(e)?BigInt(0):e,!0),$e().setInt32(t+0,!fn(e),!0)},__wbg___wbindgen_boolean_get_c0f3f60bac5a78d1:function(t){let o=Ge(t),i=typeof o=="boolean"?o:void 0;return fn(i)?16777215:i?1:0},__wbg___wbindgen_debug_string_5398f5bb970e0daa:function(t,o){let i=vG(Ge(o)),e=Qn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=KA;$e().setInt32(t+4,a,!0),$e().setInt32(t+0,e,!0)},__wbg___wbindgen_in_41dbb8413020e076:function(t,o){return Ge(t)in Ge(o)},__wbg___wbindgen_is_bigint_e2141d4f045b7eda:function(t){return typeof Ge(t)=="bigint"},__wbg___wbindgen_is_function_3c846841762788c1:function(t){return typeof Ge(t)=="function"},__wbg___wbindgen_is_null_0b605fc6b167c56f:function(t){return Ge(t)===null},__wbg___wbindgen_is_object_781bc9f159099513:function(t){let o=Ge(t);return typeof o=="object"&&o!==null},__wbg___wbindgen_is_undefined_52709e72fb9f179c:function(t){return Ge(t)===void 0},__wbg___wbindgen_jsval_eq_ee31bfad3e536463:function(t,o){return Ge(t)===Ge(o)},__wbg___wbindgen_jsval_loose_eq_5bcc3bed3c69e72b:function(t,o){return Ge(t)==Ge(o)},__wbg___wbindgen_number_get_34bb9d9dcfa21373:function(t,o){let i=Ge(o),e=typeof i=="number"?i:void 0;$e().setFloat64(t+8,fn(e)?0:e,!0),$e().setInt32(t+0,!fn(e),!0)},__wbg___wbindgen_string_get_395e606bd0ee4427:function(t,o){let i=Ge(o),e=typeof i=="string"?i:void 0;var a=fn(e)?0:Qn(e,ae.__wbindgen_export,ae.__wbindgen_export2),A=KA;$e().setInt32(t+4,A,!0),$e().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_6ddd609b62940d55:function(t,o){throw new Error(wr(t,o))},__wbg__wbg_cb_unref_6b5b6b8576d35cb1:function(t){Ge(t)._wbg_cb_unref()},__wbg_attrs_eb268b5ce109b817:function(t){let o=Ge(t).attrs;return tA(o)},__wbg_call_2d781c1f4d5c0ef8:function(){return Dr(function(t,o,i){let e=Ge(t).call(Ge(o),Ge(i));return tA(e)},arguments)},__wbg_call_e133b57c9155d22c:function(){return Dr(function(t,o){let i=Ge(t).call(Ge(o));return tA(i)},arguments)},__wbg_content_54fb4ecf37d1b68a:function(t){let o=Ge(t).content;return tA(o)},__wbg_debug_10ca7029b12f8d85:function(t,o,i,e){Ge(t).debug(Ge(o),i===0?void 0:wr(i,e))},__wbg_done_08ce71ee07e3bd17:function(t){return Ge(t).done},__wbg_entries_e8a20ff8c9757101:function(t){let o=Object.entries(Ge(t));return tA(o)},__wbg_error_9cce413345f88385:function(t,o,i,e){Ge(t).error(Ge(o),i===0?void 0:wr(i,e))},__wbg_from_4bdf88943703fd48:function(t){let o=Array.from(Ge(t));return tA(o)},__wbg_getOurIdentity_85a51d9b5b46c006:function(){return Dr(function(t){let o=Ge(t).getOurIdentity();return tA(o)},arguments)},__wbg_getOurRegistrationId_6d41d022f3c2af8a:function(){return Dr(function(t){let o=Ge(t).getOurRegistrationId();return tA(o)},arguments)},__wbg_getRandomValues_3f44b700395062e5:function(){return Dr(function(t,o){globalThis.crypto.getRandomValues(Lu(t,o))},arguments)},__wbg_get_326e41e095fb2575:function(){return Dr(function(t,o){let i=Reflect.get(Ge(t),Ge(o));return tA(i)},arguments)},__wbg_get_3ef1eba1850ade27:function(){return Dr(function(t,o){let i=Reflect.get(Ge(t),Ge(o));return tA(i)},arguments)},__wbg_get_a8ee5c45dabc1b3b:function(t,o){let i=Ge(t)[o>>>0];return tA(i)},__wbg_get_unchecked_329cfe50afab7352:function(t,o){let i=Ge(t)[o>>>0];return tA(i)},__wbg_get_with_ref_key_6412cf3094599694:function(t,o){let i=Ge(t)[Ge(o)];return tA(i)},__wbg_has_926ef2ff40b308cf:function(){return Dr(function(t,o){return Reflect.has(Ge(t),Ge(o))},arguments)},__wbg_info_b728e87a346ff6a2:function(t,o,i,e){Ge(t).info(Ge(o),i===0?void 0:wr(i,e))},__wbg_instanceof_ArrayBuffer_101e2bf31071a9f6:function(t){let o;try{o=Ge(t)instanceof ArrayBuffer}catch{o=!1}return o},__wbg_instanceof_Map_f194b366846aca0c:function(t){let o;try{o=Ge(t)instanceof Map}catch{o=!1}return o},__wbg_instanceof_Object_be1962063fcc0c9f:function(t){let o;try{o=Ge(t)instanceof Object}catch{o=!1}return o},__wbg_instanceof_Promise_7c3bdd7805c2c6e6:function(t){let o;try{o=Ge(t)instanceof Promise}catch{o=!1}return o},__wbg_instanceof_Uint8Array_740438561a5b956d:function(t){let o;try{o=Ge(t)instanceof Uint8Array}catch{o=!1}return o},__wbg_internalbinarynode_new:function(t){let o=Yu.__wrap(t);return tA(o)},__wbg_isArray_33b91feb269ff46e:function(t){return Array.isArray(Ge(t))},__wbg_isSafeInteger_ecd6a7f9c3e053cd:function(t){return Number.isSafeInteger(Ge(t))},__wbg_isTrustedIdentity_8beedd37958ed6af:function(){return Dr(function(t,o,i,e,a){let A=Ge(t).isTrustedIdentity(wr(o,i),Ge(e),a>>>0);return tA(A)},arguments)},__wbg_iterator_d8f549ec8fb061b1:function(){return tA(Symbol.iterator)},__wbg_keys_ab0d051a1c55236d:function(t){let o=Object.keys(Ge(t));return tA(o)},__wbg_length_b3416cf66a5452c8:function(t){return Ge(t).length},__wbg_length_ea16607d7b61445b:function(t){return Ge(t).length},__wbg_level_4b50b181832c5acf:function(t,o){let i=Ge(o).level,e=Qn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=KA;$e().setInt32(t+4,a,!0),$e().setInt32(t+0,e,!0)},__wbg_loadPreKey_db3458e3339f7328:function(){return Dr(function(t,o){let i=Ge(t).loadPreKey(o>>>0);return tA(i)},arguments)},__wbg_loadSenderKey_fd075b57283fd71b:function(){return Dr(function(t,o,i){let e=Ge(t).loadSenderKey(wr(o,i));return tA(e)},arguments)},__wbg_loadSession_8564b20b09724f27:function(){return Dr(function(t,o,i){let e=Ge(t).loadSession(wr(o,i));return tA(e)},arguments)},__wbg_loadSignedPreKey_3d5c6c6819f3adf3:function(){return Dr(function(t,o){let i=Ge(t).loadSignedPreKey(o>>>0);return tA(i)},arguments)},__wbg_new_5f486cdf45a04d78:function(t){let o=new Uint8Array(Ge(t));return tA(o)},__wbg_new_7dce085c132c6f91:function(t,o){let i=new TypeError(wr(t,o));return tA(i)},__wbg_new_a70fbab9066b301f:function(){let t=new Array;return tA(t)},__wbg_new_ab79df5bd7c26067:function(){let t=new Object;return tA(t)},__wbg_new_from_slice_22da9388ac046e50:function(t,o){let i=new Uint8Array(Lu(t,o));return tA(i)},__wbg_new_typed_aaaeaf29cf802876:function(t,o){try{var i={a:t,b:o},e=(A,r)=>{let s=i.a;i.a=0;try{return xFe(s,i.b,A,r)}finally{i.a=s}};let a=new Promise(e);return tA(a)}finally{i.a=i.b=0}},__wbg_new_with_length_3259a525196bd8cc:function(t){let o=new Array(t>>>0);return tA(o)},__wbg_new_with_length_825018a1616e9e55:function(t){let o=new Uint8Array(t>>>0);return tA(o)},__wbg_next_11b99ee6237339e3:function(){return Dr(function(t){let o=Ge(t).next();return tA(o)},arguments)},__wbg_next_e01a967809d1aa68:function(t){let o=Ge(t).next;return tA(o)},__wbg_parse_e9eddd2a82c706eb:function(){return Dr(function(t,o){let i=JSON.parse(wr(t,o));return tA(i)},arguments)},__wbg_prototypesetcall_d62e5099504357e6:function(t,o,i){Uint8Array.prototype.set.call(Lu(t,o),Ge(i))},__wbg_push_e87b0e732085a946:function(t,o){return Ge(t).push(Ge(o))},__wbg_queueMicrotask_0c399741342fb10f:function(t){let o=Ge(t).queueMicrotask;return tA(o)},__wbg_queueMicrotask_a082d78ce798393e:function(t){queueMicrotask(Ge(t))},__wbg_removePreKey_c0b0a066eb6f2e1e:function(){return Dr(function(t,o){let i=Ge(t).removePreKey(o>>>0);return tA(i)},arguments)},__wbg_resolve_ae8d83246e5bcc12:function(t){let o=Promise.resolve(Ge(t));return tA(o)},__wbg_senderkeydistributionmessage_new:function(t){let o=vd.__wrap(t);return tA(o)},__wbg_sessionrecord_new:function(t){let o=ju.__wrap(t);return tA(o)},__wbg_set_282384002438957f:function(t,o,i){Ge(t)[o>>>0]=mA(i)},__wbg_set_6be42768c690e380:function(t,o,i){Ge(t)[mA(o)]=mA(i)},__wbg_set_7eaa4f96924fd6b3:function(){return Dr(function(t,o,i){return Reflect.set(Ge(t),Ge(o),Ge(i))},arguments)},__wbg_set_8c0b3ffcf05d61c2:function(t,o,i){Ge(t).set(Lu(o,i))},__wbg_static_accessor_GLOBAL_8adb955bd33fac2f:function(){let t=typeof global>"u"?null:global;return fn(t)?0:tA(t)},__wbg_static_accessor_GLOBAL_THIS_ad356e0db91c7913:function(){let t=typeof globalThis>"u"?null:globalThis;return fn(t)?0:tA(t)},__wbg_static_accessor_SELF_f207c857566db248:function(){let t=typeof self>"u"?null:self;return fn(t)?0:tA(t)},__wbg_static_accessor_WINDOW_bb9f1ba69d61b386:function(){let t=typeof window>"u"?null:window;return fn(t)?0:tA(t)},__wbg_storeSenderKey_8a6c9ec5f7e1cd2e:function(){return Dr(function(t,o,i,e){let a=Ge(t).storeSenderKey(wr(o,i),Ge(e));return tA(a)},arguments)},__wbg_storeSessionRaw_09b5cc73064d12d8:function(){return Dr(function(t,o,i,e){let a=Ge(t).storeSessionRaw(wr(o,i),Ge(e));return tA(a)},arguments)},__wbg_storeSession_4d419555ce654965:function(){return Dr(function(t,o,i,e){let a=Ge(t).storeSession(wr(o,i),mA(e));return tA(a)},arguments)},__wbg_tag_33cfe8e9ee66b4db:function(t,o){let i=Ge(o).tag,e=Qn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=KA;$e().setInt32(t+4,a,!0),$e().setInt32(t+0,e,!0)},__wbg_then_098abe61755d12f6:function(t,o){let i=Ge(t).then(Ge(o));return tA(i)},__wbg_then_9e335f6dd892bc11:function(t,o,i){let e=Ge(t).then(Ge(o),Ge(i));return tA(e)},__wbg_trace_58264fbce2ceb5e6:function(t,o,i,e){Ge(t).trace(Ge(o),i===0?void 0:wr(i,e))},__wbg_value_21fc78aab0322612:function(t){let o=Ge(t).value;return tA(o)},__wbg_warn_db531770752932a9:function(t,o,i,e){Ge(t).warn(Ge(o),i===0?void 0:wr(i,e))},__wbindgen_cast_0000000000000001:function(t,o){let i=jFe(t,o,ae.__wasm_bindgen_func_elem_694,KFe);return tA(i)},__wbindgen_cast_0000000000000002:function(t){return tA(t)},__wbindgen_cast_0000000000000003:function(t){return tA(t)},__wbindgen_cast_0000000000000004:function(t,o){let i=Lu(t,o);return tA(i)},__wbindgen_cast_0000000000000005:function(t,o){let i=wr(t,o);return tA(i)},__wbindgen_cast_0000000000000006:function(t){let o=BigInt.asUintN(64,t);return tA(o)},__wbindgen_object_clone_ref:function(t){let o=Ge(t);return tA(o)},__wbindgen_object_drop_ref:function(t){mA(t)}}}}function KFe(n,t,o){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.__wasm_bindgen_func_elem_699(a,n,t,tA(o));var i=$e().getInt32(a+0,!0),e=$e().getInt32(a+4,!0);if(e)throw mA(i)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}function xFe(n,t,o,i){ae.__wasm_bindgen_func_elem_1248(n,t,tA(o),tA(i))}var B9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_expandedappstatekeys_free(n>>>0,1)),f9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_groupcipher_free(n>>>0,1)),Q9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_groupsessionbuilder_free(n>>>0,1)),y9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_internalbinarynode_free(n>>>0,1)),m9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_lthashantitampering_free(n>>>0,1)),TG=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_lthashstate_free(n>>>0,1)),S9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_noisesession_free(n>>>0,1)),NG=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_protocoladdress_free(n>>>0,1)),D9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_senderkeydistributionmessage_free(n>>>0,1)),w9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_senderkeyname_free(n>>>0,1)),RG=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_senderkeyrecord_free(n>>>0,1)),O9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_sessionbuilder_free(n>>>0,1)),b9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_sessioncipher_free(n>>>0,1)),M9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_sessionrecord_free(n>>>0,1));function tA(n){Hu===fg.length&&fg.push(fg.length+1);let t=Hu;return Hu=fg[t],fg[t]=n,t}function bc(n,t){if(!(n instanceof t))throw new Error(`expected instance of ${t.name}`)}var _9=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>n.dtor(n.a,n.b));function vG(n){let t=typeof n;if(t=="number"||t=="boolean"||n==null)return`${n}`;if(t=="string")return`"${n}"`;if(t=="symbol"){let e=n.description;return e==null?"Symbol":`Symbol(${e})`}if(t=="function"){let e=n.name;return typeof e=="string"&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(n)){let e=n.length,a="[";e>0&&(a+=vG(n[0]));for(let A=1;A1)i=o[1];else return toString.call(n);if(i=="Object")try{return"Object("+JSON.stringify(n)+")"}catch{return"Object"}return n instanceof Error?`${n.name}: ${n.message} -${n.stack}`:i}function YFe(n){n<1028||(fg[n]=Hu,Hu=n)}function Lu(n,t){return n=n>>>0,Rd().subarray(n/1,n/1+t)}var ol=null;function $e(){return(ol===null||ol.buffer.detached===!0||ol.buffer.detached===void 0&&ol.buffer!==ae.memory.buffer)&&(ol=new DataView(ae.memory.buffer)),ol}function wr(n,t){return n=n>>>0,qFe(n,t)}var Uu=null;function Rd(){return(Uu===null||Uu.byteLength===0)&&(Uu=new Uint8Array(ae.memory.buffer)),Uu}function Ge(n){return fg[n]}function Dr(n,t){try{return n.apply(this,t)}catch(o){ae.__wbindgen_export3(tA(o))}}var fg=new Array(1024).fill(void 0);fg.push(void 0,null,!0,!1);var Hu=fg.length;function fn(n){return n==null}function jFe(n,t,o,i){let e={a:n,b:t,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let r=e.a;e.a=0;try{return i(r,e.b,...A)}finally{e.a=r,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,_9.unregister(e))},_9.register(a,e,e),a}function _t(n,t){let o=t(n.length*1,1)>>>0;return Rd().set(n,o/1),KA=n.length,o}function T9(n,t){let o=t(n.length*4,4)>>>0,i=$e();for(let e=0;e>>0;return Rd().subarray(s,s+r.length).set(r),KA=r.length,s}let i=n.length,e=t(i,1)>>>0,a=Rd(),A=0;for(;A127)break;a[e+A]=r}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let r=Rd().subarray(e+A,e+i),s=Ku.encodeInto(n,r);A+=s.written,e=o(e,i,A,1)>>>0}return KA=A,e}function mA(n){let t=Ge(n);return YFe(n),t}var pD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});pD.decode();var JFe=2146435072,kG=0;function qFe(n,t){return kG+=t,kG>=JFe&&(pD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),pD.decode(),kG=t),pD.decode(Rd().subarray(n,n+t))}var Ku=new TextEncoder;"encodeInto"in Ku||(Ku.encodeInto=function(n,t){let o=Ku.encode(n);return t.set(o),{read:n.length,written:o.length}});var KA=0,zFe,ae;function VFe(n,t){return ae=n.exports,zFe=t,ol=null,Uu=null,ae}function R9(n){if(ae!==void 0)return ae;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=HFe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,t);return VFe(o,n)}var WFe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function k9(n){let t=atob(n),o=new Uint8Array(t.length);for(let i=0;in.length===33?n:Buffer.concat([Qg,n]),ur={generateKeyPair:()=>{let{pubKey:n,privKey:t}=_c.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(n.slice(1))}},sharedKey:(n,t)=>{let o=_c.calculateAgreement(vo(t),n);return Buffer.from(o)},sign:(n,t)=>_c.calculateSignature(n,t),verify:(n,t,o)=>{try{return _c.verifySignature(vo(n),t,o),!0}catch{return!1}}},QD=(n,t)=>{let o=ur.generateKeyPair(),i=vo(o.public),e=ur.sign(n.private,i);return{keyPair:o,signature:e,keyId:t}},P9=16;function nl(n,t,o,i){let e=PG("aes-256-gcm",t,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function sl(n,t,o,i){let e=GG("aes-256-gcm",t,o),a=n.slice(0,n.length-P9),A=n.slice(n.length-P9);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function G9(n,t,o){let i=PG("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function F9(n,t,o){let i=GG("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function L9(n,t){return aLe(n.subarray(16),t,n.subarray(0,16))}function aLe(n,t,o){let i=GG("aes-256-cbc",t,o);return Buffer.concat([i.update(n),i.final()])}function U9(n,t){let o=rLe(16),i=PG("aes-256-cbc",t,o);return Buffer.concat([o,i.update(n),i.final()])}function mn(n,t,o="sha256"){return tLe(o,t).update(n).digest()}function Gd(n){return ALe("sha256").update(n).digest()}async function yD(n,t){let i=new TextEncoder().encode(n),e=new Uint8Array(t instanceof Uint8Array?t:new Uint8Array(t)),a=await v9.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await v9.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var qu={replacer:(n,t)=>Buffer.isBuffer(t)||t instanceof Uint8Array||t?.type==="Buffer"?{type:"Buffer",data:Buffer.from(t?.data||t).toString("base64")}:t,reviver:(n,t)=>{if(typeof t=="object"&&t!==null&&t.type==="Buffer"&&typeof t.data=="string")return Buffer.from(t.data,"base64");if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(t);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return t}},Fd=(n,t="me")=>(n?.fromMe?t:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",x9=n=>n==null||n==="",oLe=n=>{let o=(Ju(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},Y9=n=>{let t=new Uint8Array(n);if(t.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=t[t.length-1];if(o>t.length)throw new Error(`unpad given ${t.length} bytes, but pad is ${o}`);return new Uint8Array(t.buffer,t.byteOffset,t.length-o)},j9=n=>(n.sort(),"2:"+Gd(Buffer.from(n.join(""))).toString("base64").slice(0,6)),Ld=n=>oLe(oe.Message.encode(n).finish()),J9=()=>Uint16Array.from(Ju(2))[0]&16383,yg=(n,t=4)=>{let o=n,i=new Uint8Array(t);for(let e=t-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},Lr=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,Ba=(n=new Date)=>Math.floor(n.getTime()/1e3);var zu=n=>q9(n).delay,q9=n=>{let t=new Error().stack,o,i;return{delay:new Promise((A,r)=>{o=setTimeout(A,n),i=r}),cancel:()=>{clearTimeout(o),i(new mD.Boom("Cancelled",{statusCode:500,data:{stack:t}}))}}};async function Ud(n,t){if(!n)return new Promise(t);let o=new Error().stack,{delay:i,cancel:e}=q9(n);return new Promise((A,r)=>{i.then(()=>r(new mD.Boom("Timed Out",{statusCode:Zt.timedOut,data:{stack:o}}))).catch(s=>r(s)),t(A,r)}).finally(e)}var Ur=n=>{let t=Buffer.alloc(44);if(t.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=yA(n);e?.user&&(t.write(e.user,8),t.write("@c.us",8+e.user.length))}return Ju(16).copy(t,28),"3EB0"+iLe("sha256").update(t).digest().toString("hex").toUpperCase().substring(0,18)},FG=()=>"3EB0"+Ju(18).toString("hex").toUpperCase();function LG(n,t){return async(o,i)=>{let e,a;await Ud(i,(A,r)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&r(g?.error||new mD.Boom("Connection Closed",{statusCode:Zt.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(t,e)}).finally(()=>{n.off(t,e),n.off("connection.update",a)})}}var z9=n=>LG(n,"connection.update");var V9=()=>{let n=Ju(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},nLe={sender:oe.WebMessageInfo.Status.SERVER_ACK,played:oe.WebMessageInfo.Status.PLAYED,read:oe.WebMessageInfo.Status.READ,"read-self":oe.WebMessageInfo.Status.READ},W9=n=>{let t=nLe[n];return typeof n>"u"?oe.WebMessageInfo.Status.DELIVERY_ACK:t},sLe={conflict:Zt.connectionReplaced},Z9=n=>{let[t]=ls(n),o=t?.tag||"unknown",i=+(n.attrs.code||sLe[o]||Zt.badSession);return i===Zt.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},X9=({tag:n,attrs:t})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":t.reason==="timeout"?o="timeout":o="terminate";break;case"preaccept":o="preaccept";break;case"transport":o="transport";break;case"relaylatency":o="relaylatency";break;case"reject":o="reject";break;case"accept":o="accept";break;default:o="ringing";break}return o},H9="Unexpected server response: ",$9=n=>{let t=500;if(n?.message?.includes(H9)){let o=+n?.message.slice(H9.length);!Number.isNaN(o)&&o>=400&&(t=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(t=408);return t};function SD(n){for(let t in n)typeof n[t]>"u"&&delete n[t];return n}var K9="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function eX(n){let t=0,o=0,i=[];for(let e of n)for(t=t<<8|e&255,o+=8;o>=5;)i.push(K9.charAt(t>>>o-5&31)),o-=5;return o>0&&i.push(K9.charAt(t<<5-o&31)),i.join("")}function AX(n){return oe.Message.encode(n).finish()}var gl=qe(Gr(),1);var gLe=async(n,t)=>qA(n)||oa(n)?n:await t.lidMapping.getLIDForPN(n)||n,cLe=async(n,t,o,i,e)=>{let{senderAlt:a}=wD(n);if(a&&qA(a)&&bt(t)&&i===t)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:t}]),await o.migrateSession(t,a),e.debug({sender:t,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:t,senderAlt:a,error:A},"Failed to store LID mapping")}},DD="Message absent from node",tX="Key used already or never filled",rX="Your account has been restricted",ILe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},cl={SenderReachoutTimelocked:463,ParsingError:487,UnrecognizedStanza:488,UnrecognizedStanzaClass:489,UnrecognizedStanzaType:490,InvalidProtobuf:491,InvalidHostedCompanionStanza:493,MissingMessageSecret:495,SignalErrorOldCounter:496,MessageDeletedOnPeer:499,UnhandledError:500,UnsupportedAdminRevoke:550,UnsupportedLIDGroup:551,DBOperationFailed:552},UG={MessageAccountRestriction:"463",SmaxInvalid:"479"},wD=n=>{let t,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(t=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(t=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:t,recipientAlt:o}};function HG(n,t,o){let i,e,a,A=!1,r=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!r)throw new gl.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new gl.Boom("Invalid message stanza: missing from attribute",{data:n});let I=wD(n),d=m=>Mt(m,t),B=m=>Mt(m,o);if(bt(s)||qA(s)||oa(s)||Cr(s)){if(c&&!Nd(c)){if(!d(s)&&!B(s))throw new gl.Boom("receipient present, but msg not from me",{data:n});(d(s)||B(s))&&(A=!0),e=c}else(d(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(Fr(s)){if(!g)throw new gl.Boom("No participant in group message");(d(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(Fu(s)){if(!g)throw new gl.Boom("No participant in group message");let m=d(g);Bg(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(wc(s))i="newsletter",e=s,a=s,(d(s)||B(s))&&(A=!0);else throw new gl.Boom("Unknown message type",{data:n});let f=n?.attrs?.notify,Q={remoteJid:e,remoteJidAlt:Fr(e)?void 0:I.senderAlt,remoteJidUsername:Fr(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:r,participant:g,participantAlt:Fr(e)?I.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:I.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:Q,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:f,broadcast:Fu(s)};return Q.fromMe&&(y.status=oe.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var aX=(n,t,o,i,e)=>{let{fullMessage:a,author:A,sender:r}=HG(n,t,o);return{fullMessage:a,category:n.attrs.category,author:A,async decrypt(){let s=0;if(Array.isArray(n.content))for(let{tag:g,attrs:c,content:I}of n.content){if(g==="verified_name"&&I instanceof Uint8Array){let f=oe.VerifiedNameCertificate.decode(I),Q=oe.VerifiedNameCertificate.Details.decode(f.details);a.verifiedBizName=Q.verifiedName}if(g==="unavailable"&&c.type==="view_once"&&(a.key.isViewOnce=!0),c.count&&g==="enc"&&(a.retryCount=Number(c.count)),g!=="enc"&&g!=="plaintext"||!(I instanceof Uint8Array))continue;s+=1;let d,B=await gLe(A,i);g!=="plaintext"&&await cLe(n,A,i,B,e);try{let f=g==="plaintext"?"plaintext":c.type;switch(f){case"skmsg":d=await i.decryptGroupMessage({group:r,authorJid:A,msg:I});break;case"pkmsg":case"msg":d=await i.decryptMessage({jid:B,type:f,ciphertext:I});break;case"plaintext":d=I;break;default:throw new Error(`Unknown e2e type: ${f}`)}let Q=oe.Message.decode(f!=="plaintext"?Y9(d):d);if(Q=Q.deviceSentMessage?.message||Q,Q.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:Q.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,Q):a.message=Q}catch(f){let Q={key:a.key,err:f,messageType:g==="plaintext"?"plaintext":c.type,sender:r,author:A,isSessionRecordError:lLe(f)};e.error(Q,"failed to decrypt message"),a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[f.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[DD])}}};function lLe(n){let t=n?.message||n?.toString()||"";return ILe.sessionRecordErrors.some(o=>t.includes(o))}var Ng=qe(Gr(),1);import{randomBytes as A2}from"crypto";import{promises as t2}from"fs";var Dn=qe(Gr(),1);import{exec as lje}from"child_process";import*as io from"crypto";import{once as Oh}from"events";import{createReadStream as mO,createWriteStream as qL,promises as Mh}from"fs";import{tmpdir as _ae}from"os";import{join as QO}from"path";import{Readable as LB,Transform as pje}from"stream";import{URL as zL}from"url";var VL=()=>_ae(),Tae=async()=>{let[n,t]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(hee(),dee)).catch(()=>{})]);if(t)return{sharp:t};if(n)return{jimp:n};throw new Dn.Boom("No image processing library available")},dje=n=>`WhatsApp ${xae[n]} Keys`,SO=async(n,t,o)=>{let{stream:i}=await UB(n);o?.debug("got stream for raw upload");let e=io.createHash("sha256"),a=QO(_ae(),t+Ur()),A=qL(a),r=0;try{for await(let g of i)r+=g.length,e.update(g),A.write(g)||await Oh(A,"drain");A.end(),await Oh(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:r}}catch(s){A.destroy(),i.destroy();try{await Mh.unlink(a)}catch{}throw s}};async function Nae(n,t){if(!n)throw new Dn.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=yn(n,112,{info:dje(t)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var hje=async(n,t,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${t}`;lje(A,r=>{r?a(r):e()})}),WL=async(n,t=32)=>{n instanceof LB&&(n=await yO(n));let o=await Tae();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(t).jpeg({quality:50}).toBuffer(),original:{width:e.width,height:e.height}}}else if("jimp"in o&&typeof o.jimp?.Jimp=="object"){let i=await o.jimp.Jimp.read(n),e={width:i.width,height:i.height};return{buffer:await i.resize({w:t,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new Dn.Boom("No image processing library available")},Eje=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),DO=async(n,t)=>{let o,{width:i=640,height:e=640}=t||{};if(Buffer.isBuffer(n))o=n;else{let{stream:r}=await UB(n);o=await yO(r)}let a=await Tae(),A;if("sharp"in a&&typeof a.sharp?.default=="function")A=a.sharp.default(o).resize(i,e).jpeg({quality:50}).toBuffer();else if("jimp"in a&&typeof a.jimp?.Jimp=="function"){let r=await a.jimp.Jimp.read(o),s=Math.min(r.width,r.height);A=r.crop({x:0,y:0,w:s,h:s}).resize({w:i,h:e,mode:a.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50})}else throw new Dn.Boom("No image processing library available");return{img:await A}};async function Rae(n){let t=await Promise.resolve().then(()=>(bae(),Oae)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await t.parseBuffer(n,void 0,i):typeof n=="string"?o=await t.parseFile(n,i):o=await t.parseStream(n,void 0,i),o.format.duration}async function kae(n,t){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let d=mO(n);i=await yO(d)}else i=await yO(n);let a=(await o(i)).getChannelData(0),A=64,r=Math.floor(a.length/A),s=[];for(let d=0;dd*g);return new Uint8Array(c.map(d=>Math.floor(100*d)))}catch(o){t?.debug("Failed to generate waveform: "+o)}}var Mae=n=>{let t=new LB({read:()=>{}});return t.push(n),t.push(null),t},yO=async n=>{let t=[];for await(let o of n)t.push(o);return n.destroy(),Buffer.concat(t)},UB=async(n,t)=>{if(Buffer.isBuffer(n))return{stream:Mae(n),type:"buffer"};if("stream"in n)return{stream:n.stream,type:"readable"};let o=n.url.toString();if(o.startsWith("data:")){let i=Buffer.from(o.split(",")[1],"base64");return{stream:Mae(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await wO(n.url,t),type:"remote"}:{stream:mO(n.url),type:"file"}};async function vae(n,t,o){let i,e;if(t==="image"){let{buffer:a,original:A}=await WL(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(t==="video"){let a=QO(VL(),Ur()+".jpg");try{await hje(n,a,"00:00:00",{width:32,height:32}),i=(await Mh.readFile(a)).toString("base64"),await Mh.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var wO=async(n,t={})=>{let o=await fetch(n.toString(),{dispatcher:t.dispatcher,method:"GET",headers:t.headers});if(!o.ok)throw new Dn.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof LB?o.body:LB.fromWeb(o.body)},Pae=async(n,t,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await UB(n,e);o?.debug("fetched media stream");let r=io.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await Nae(r,t),I=QO(VL(),t+Ur()+"-enc"),d=qL(I),B,f;i&&(f=QO(VL(),t+Ur()+"-original"),B=qL(f));let Q=0,y=io.createCipheriv("aes-256-cbc",s,g),m=io.createHmac("sha256",c).update(g),_=io.createHash("sha256"),T=io.createHash("sha256"),R=async H=>{T.update(H),m.update(H),d.write(H)||await Oh(d,"drain")};try{for await(let x of a){if(Q+=x.length,A==="remote"&&e?.maxContentLength&&Q+x.length>e.maxContentLength)throw new Dn.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(x)||await Oh(B,"drain")),_.update(x),await R(y.update(x))}await R(y.final());let H=m.digest().slice(0,10);T.update(H);let j=_.digest(),F=T.digest();d.write(H);let q=Oh(d,"finish"),J=B?Oh(B,"finish"):Promise.resolve();return d.end(),B?.end?.(),a.destroy(),await q,await J,o?.debug("encrypted data successfully"),{mediaKey:r,originalFilePath:f,encFilePath:I,mac:H,fileEncSha256:F,fileSha256:j,fileLength:Q}}catch(H){d.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),_.destroy(),T.destroy(),a.destroy();try{await Mh.unlink(I),f&&await Mh.unlink(f)}catch(j){o?.error({err:j},"failed deleting tmp files")}throw H}},ZL="mmg.whatsapp.net",bh=16,JL=n=>Math.floor(n/bh)*bh,HB=(n,t=ZL)=>`https://${t}${n}`,Cje=n=>{if(n)try{return new zL(n).host}catch{return}},_h=async({mediaKey:n,directPath:t,url:o},i,e={})=>{let a=e.host??Cje(o),A=t?HB(t,a):o;if(!A)throw new Dn.Boom("No valid media URL or directPath present in message",{statusCode:400});let r=await Nae(n,i);return uje(A,r,e)},uje=async(n,{cipherKey:t,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,r=0,s=!1;if(i){let m=JL(i||0);m&&(r=m-bh,A=m,s=!0)}let g=e?JL(e||0)+bh:void 0,c=a?.headers?a.headers:void 0,I={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:KB};(r||g)&&(I.Range=`bytes=${r}-`,g&&(I.Range+=g));let d=await wO(n,{...a||{},headers:I}),B=Buffer.from([]),f,Q=(m,_)=>{if(i||e){let T=A>=i?void 0:Math.max(i-A,0),R=A+m.lengththis.push(j)),T()}catch(j){T(j)}},final(m){try{Q(f.final(),_=>this.push(_)),m()}catch(_){m(_)}}});return d.pipe(y,{end:!0})};var Bje=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",Gae=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new zL(n),r=A.protocol==="https:"?await import("https"):await import("http"),g=(await Mh.stat(t)).size;return new Promise((c,I)=>{let d=r.request({hostname:A.hostname,port:A.port||(A.protocol==="https:"?443:80),path:A.pathname+A.search,method:"POST",headers:{...o,"Content-Length":g},agent:e,timeout:i},f=>{if(f.statusCode&&f.statusCode>=300&&f.statusCode<400&&f.headers.location){f.resume();let y=new zL(f.headers.location,n).toString();c(Gae({url:y,filePath:t,headers:o,timeoutMs:i,agent:e},a+1));return}let Q="";f.on("data",y=>Q+=y),f.on("end",()=>{try{c(JSON.parse(Q))}catch{c(void 0)}})});d.on("error",I),d.on("timeout",()=>{d.destroy(),I(new Error("Upload timeout"))});let B=mO(t);B.pipe(d),B.on("error",f=>{d.destroy(),I(f)})})},fje=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e})=>{let a=mO(t),A=LB.toWeb(a),r=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...r?{dispatcher:r}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},Qje=async(n,t)=>Bje()?(t?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),Gae(n)):(t?.debug("Using web-standard Fetch API for upload"),fje(n)),Fae=({customUploadHosts:n,fetchAgent:t,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:r,timeoutMs:s})=>{let g=await e(!1),c,I=[...n,...g.hosts];r=Eje(r);let B={...(()=>{let f=i?.headers;return f?Array.isArray(f)?Object.fromEntries(f):f:{}})(),"Content-Type":"application/octet-stream",Origin:KB};for(let{hostname:f}of I){o.debug(`uploading to "${f}"`);let Q=encodeURIComponent(g.auth),y=`https://${f}${$L[A]}/${r}?auth=${Q}&token=${r}`,m;try{if(m=await Qje({url:y,filePath:a,headers:B,timeoutMs:s,agent:t},o),m?.url||m?.direct_path){c={mediaUrl:m.url,directPath:m.direct_path,meta_hmac:m.meta_hmac,fbid:m.fbid,ts:m.ts};break}else throw g=await e(!0),new Error(`upload failed, reason: ${JSON.stringify(m)}`)}catch(_){let T=f===I[g.hosts.length-1]?.hostname;o.warn({trace:_?.stack,uploadResult:m},`Error in uploading to ${f} ${T?"":", retrying..."}`)}}if(!c)throw new Dn.Boom("Media upload failed on all hosts",{statusCode:500});return c},Lae=n=>yn(n,32,{info:"WhatsApp Media Retry Notification"}),Uae=(n,t,o)=>{let i={stanzaId:n.id},e=oe.ServerErrorReceipt.encode(i).finish(),a=io.randomBytes(12),A=Lae(t),r=nl(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:uA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:r},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},Hae=n=>{let t=Ie(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:t.attrs.jid,fromMe:t.attrs.from_me==="true",participant:t.attrs.participant}},i=Ie(n,"error");if(i){let e=+i.attrs.code;o.error=new Dn.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:XL(e)})}else{let e=Ie(n,"encrypt"),a=ua(e,"enc_p"),A=ua(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new Dn.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},Kae=({ciphertext:n,iv:t},o,i)=>{let e=Lae(o),a=sl(n,e,t,Buffer.from(i));return oe.MediaRetryNotification.decode(a)},XL=n=>yje[n],yje={[oe.MediaRetryNotification.ResultType.SUCCESS]:200,[oe.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[oe.MediaRetryNotification.ResultType.NOT_FOUND]:404,[oe.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as mje}from"crypto";var Sje=[{f:1},{f:3,s:[{f:2},{f:3},{f:8},{f:11},{f:17,s:[{f:21},{f:22}]},{f:25}]},{f:4,s:[{f:1},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:5,s:[{f:3},{f:4},{f:5},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:6,s:[{f:1},{f:17,s:[{f:21},{f:22}]},{f:30}]},{f:7,s:[{f:2},{f:7},{f:10},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:8,s:[{f:2},{f:7},{f:9},{f:17,s:[{f:21},{f:22}]},{f:21}]},{f:9,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:12,s:[{f:1},{f:2},{f:14,m:!0},{f:15}]},{f:18,s:[{f:6},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:26,s:[{f:4},{f:5},{f:8},{f:13},{f:17,s:[{f:21},{f:22}]}]},{f:28,s:[{f:1},{f:2},{f:4},{f:5},{f:6},{f:7,s:[{f:21},{f:22}]}]},{f:37,s:[{f:1,m:!0}]},{f:49,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:53,s:[{f:1,m:!0}]},{f:55,s:[{f:1,m:!0}]},{f:58,s:[{f:1,m:!0}]},{f:59,s:[{f:1,m:!0}]},{f:60,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:64,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:66,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:74,s:[{f:1,m:!0}]},{f:87,s:[{f:1,m:!0}]},{f:88,s:[{f:1},{f:2,s:[{f:1}]},{f:3,s:[{f:21},{f:22}]}]},{f:92,s:[{f:1,m:!0}]},{f:93,s:[{f:1,m:!0}]},{f:94,s:[{f:1,m:!0}]}],jae=n=>{let t=new Map;for(let o of n)t.set(o.f,{m:o.m,children:o.s?jae(o.s):void 0});return t},Dje=jae(Sje),wje=new Map,Oje="Report Token",OO={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},bO=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,bje=(n,t,o,i,e)=>{let a=Buffer.concat([Buffer.from(t,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return yn(e,32,{info:a.toString("latin1")})},Jae=(n,t)=>{let o=[],i=0;for(;i>3,A=e.value&7,r=i;i+=e.bytes;let s=t.get(a),g=I=>I>n.length?!1:(o.push({num:a,bytes:n.subarray(r,I)}),i=I,!0),c=I=>I>n.length?!1:(i=I,!0);if(A===OO.VARINT){let I=e2(n,i);if(!I.ok)return null;let d=i+I.bytes;if(!s){if(!c(d))return null;continue}if(!g(d))return null;continue}if(A===OO.FIXED64){let I=i+8;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===OO.FIXED32){let I=i+4;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===OO.BYTES){let I=e2(n,i);if(!I.ok)return null;let d=i+I.bytes,B=d+I.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let f=Jae(n.subarray(d,B),s.children??wje);if(f===null)return null;if(f.length>0){let Q=Yae(e.value),y=Yae(f.length);o.push({num:a,bytes:Buffer.concat([Q,y,f])})}i=B;continue}o.push({num:a,bytes:n.subarray(r,B)}),i=B;continue}return null}return o.length===0?Buffer.alloc(0):(o.sort((e,a)=>e.num-a.num),Buffer.concat(o.map(e=>e.bytes)))},e2=(n,t)=>{let o=0,i=0,e=0;for(;t+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},Yae=n=>{let t=[],o=n>>>0;for(;o>127;)t.push(o&127|128),o>>>=7;return t.push(o),Buffer.from(t)},qae=async(n,t,o)=>{let i=t.messageContextInfo?.messageSecret;if(!i||!o.id)return null;let e=o.fromMe?o.remoteJid:o.participant||o.remoteJid,a=o.fromMe&&o.participant||o.remoteJid,A=bje(Oje,o.id,e,a,i),r=Jae(n,Dje);if(!r||r.length===0)return null;let s=mje("sha256",A).update(r).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var Mje={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},zae={image:oe.Message.ImageMessage,video:oe.Message.VideoMessage,audio:oe.Message.AudioMessage,sticker:oe.Message.StickerMessage,document:oe.Message.DocumentMessage},_je=n=>n.match(tie)?.[0],Tje=async(n,t,o)=>{let i=_je(n);if(t&&i)try{return await t(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},Vae=async n=>{let t;if(typeof n=="number")t=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),t=parseInt(o,16),t}},xB=async(n,t)=>{let o=t.logger,i;for(let j of rie)j in n&&(i=j);if(!i)throw new Ng.Boom("Invalid media type",{statusCode:400});let e={...n,media:n[i]};delete e[i];let a=typeof e.media=="object"&&"url"in e.media&&!!e.media.url&&!!t.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=Mje[i]),a){let j=await t.mediaCache.get(a);if(j){o?.debug({cacheableKey:a},"got media cache hit");let F=oe.Message.decode(j),q=`${i}Message`;return Object.assign(F[q],{...e,media:void 0}),F}}if(!!t.jid&&wc(t.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:j,fileSha256:F,fileLength:q}=await SO(e.media,t.mediaTypeOverride||i,o),J=F.toString("base64"),{mediaUrl:x,directPath:P}=await t.upload(j,{fileEncSha256B64:J,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});await t2.unlink(j);let z=oe.Message.fromObject({[`${i}Message`]:zae[i].fromObject({url:x,directPath:P,fileSha256:F,fileLength:q,...e,media:void 0})});return e.ptv&&(z.ptvMessage=z.videoMessage,delete z.videoMessage),z.stickerMessage&&(z.stickerMessage.stickerSentTs=Date.now()),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(z).finish())),z}let r=i==="audio"&&typeof e.seconds>"u",s=(i==="image"||i==="video")&&typeof e.jpegThumbnail>"u",g=i==="audio"&&e.ptt===!0&&typeof e.waveform>"u",c=t.backgroundColor&&i==="audio"&&e.ptt===!0,I=r||s,{mediaKey:d,encFilePath:B,originalFilePath:f,fileEncSha256:Q,fileSha256:y,fileLength:m}=await Pae(e.media,t.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:I,opts:t.options}),_=Q.toString("base64"),[{mediaUrl:T,directPath:R}]=await Promise.all([(async()=>{let j=await t.upload(B,{fileEncSha256B64:_,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),j})(),(async()=>{try{if(s){let{thumbnail:j,originalImageDimensions:F}=await vae(f,i,t);e.jpegThumbnail=j,!e.width&&F&&(e.width=F.width,e.height=F.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}r&&(e.seconds=await Rae(f),o?.debug("computed audio duration")),g&&(e.waveform=await kae(f,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await Vae(t.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(j){o?.warn({trace:j.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await t2.unlink(B),f&&await t2.unlink(f),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),H=oe.Message.fromObject({[`${i}Message`]:zae[i].fromObject({url:T,directPath:R,mediaKey:d,fileEncSha256:Q,fileSha256:y,fileLength:m,mediaKeyTimestamp:Ba(),...e,media:void 0})});return e.ptv&&(H.ptvMessage=H.videoMessage,delete H.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(H).finish())),H},Nje=n=>{n=n||0;let t={ephemeralMessage:{message:{protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return oe.Message.fromObject(t)},Rje=(n,t)=>{let o=n.message;if(!o)throw new Ng.Boom("no content in message",{statusCode:400});o=Sa(o),o=oe.Message.decode(oe.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!t?0:1,i==="conversation"&&(o.extendedTextMessage={text:o[i]},delete o.conversation,i="extendedTextMessage");let a=o?.[i];return e>0?a.contextInfo={forwardingScore:e,isForwarded:!0}:a.contextInfo={},o},Ia=(n,t)=>typeof n=="object"&&n!==null&&t in n&&n[t]!==null&&n[t]!==void 0;function Tl(n,t){return typeof n=="object"&&n!==null&&t in n&&n[t]!==null}var kje=async(n,t)=>{var o,i;let e={};if(Ia(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await Tje(n.text,t.getUrlInfo,t.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let r=A.highQualityThumbnail;r&&(a.thumbnailDirectPath=r.directPath,a.mediaKey=r.mediaKey,a.mediaKeyTimestamp=r.mediaKeyTimestamp,a.thumbnailWidth=r.width,a.thumbnailHeight=r.height,a.thumbnailSha256=r.fileSha256,a.thumbnailEncSha256=r.fileEncSha256)}t.backgroundColor&&(a.backgroundArgb=await Vae(t.backgroundColor)),t.font&&(a.font=t.font),e.extendedTextMessage=a}else if(Ia(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new Ng.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=oe.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=oe.Message.ContactsArrayMessage.create(n.contacts)}else if(Ia(n,"location"))e.locationMessage=oe.Message.LocationMessage.create(n.location);else if(Ia(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=oe.Message.ReactionMessage.create(n.react);else if(Ia(n,"delete"))e.protocolMessage={key:n.delete,type:oe.Message.ProtocolMessage.Type.REVOKE};else if(Ia(n,"forward"))e=Rje(n.forward,n.force);else if(Ia(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?jB:0:n.disappearingMessagesInChat;e=Nje(a)}else if(Ia(n,"groupInvite")){if(e.groupInviteMessage={},e.groupInviteMessage.inviteCode=n.groupInvite.inviteCode,e.groupInviteMessage.inviteExpiration=n.groupInvite.inviteExpiration,e.groupInviteMessage.caption=n.groupInvite.text,e.groupInviteMessage.groupJid=n.groupInvite.jid,e.groupInviteMessage.groupName=n.groupInvite.subject,t.getProfilePicUrl){let a=await t.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:t?.options?.dispatcher});if(A.ok){let r=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=r}}}}else if(Ia(n,"pin"))e.pinInChatMessage={},e.messageContextInfo={},e.pinInChatMessage.key=n.pin,e.pinInChatMessage.type=n.type,e.pinInChatMessage.senderTimestampMs=Date.now(),e.messageContextInfo.messageAddOnDurationInSecs=n.type===1?n.time||86400:0;else if(Ia(n,"buttonReply"))switch(n.type){case"template":e.templateButtonReplyMessage={selectedDisplayText:n.buttonReply.displayText,selectedId:n.buttonReply.id,selectedIndex:n.buttonReply.index};break;case"plain":e.buttonsResponseMessage={selectedButtonId:n.buttonReply.id,selectedDisplayText:n.buttonReply.displayText,type:oe.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(Tl(n,"ptv")&&n.ptv){let{videoMessage:a}=await xB({video:n.video},t);e.ptvMessage=a}else if(Ia(n,"product")){let{imageMessage:a}=await xB({image:n.product.productImage},t);e.productMessage=oe.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(Ia(n,"listReply"))e.listResponseMessage={...n.listReply};else if(Ia(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&t.getCallLink){let A=await t.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?Aie:eie)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||A2(32)},e.eventMessage.name=n.event.name,e.eventMessage.description=n.event.description,e.eventMessage.startTime=a,e.eventMessage.endTime=n.event.endDate?n.event.endDate.getTime()/1e3:void 0,e.eventMessage.isCanceled=n.event.isCancelled??!1,e.eventMessage.extraGuestsAllowed=n.event.extraGuestsAllowed,e.eventMessage.isScheduleCall=n.event.isScheduleCall??!1,e.eventMessage.location=n.event.location}else if(Ia(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new Ng.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new Ng.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||A2(32)};let a={name:n.poll.name,selectableOptionsCount:n.poll.selectableCount,options:n.poll.values.map(A=>({optionName:A}))};n.poll.toAnnouncementGroup?e.pollCreationMessageV2=a:n.poll.selectableCount===1?e.pollCreationMessageV3=a:e.pollCreationMessage=a}else Ia(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:Ia(n,"sharePhoneNumber")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:Ia(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:Ia(n,"limitSharing")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await xB(n,t);if(Tl(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),Tl(n,"mentions")&&n.mentions?.length||Tl(n,"mentionAll")&&n.mentionAll){let a=Object.keys(e)[0],A=e[a];A&&"contextInfo"in A?(A.contextInfo=A.contextInfo||{},n.mentions?.length&&(A.contextInfo.mentionedJid=n.mentions),n.mentionAll&&(A.contextInfo.nonJidMentions=1)):A&&(A.contextInfo={mentionedJid:n.mentions,nonJidMentions:n.mentionAll?1:0})}if(Tl(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:oe.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),Tl(n,"contextInfo")&&n.contextInfo){let a=Object.keys(e)[0],A=e[a];"contextInfo"in A&&A.contextInfo?A.contextInfo={...A.contextInfo,...n.contextInfo}:A&&(A.contextInfo=n.contextInfo)}return Tl(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:oe.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),bO(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=A2(32))),oe.Message.create(e)},vje=(n,t,o)=>{o.timestamp||(o.timestamp=new Date);let i=Sa(t),e=YB(i),a=Ba(o.timestamp),{quoted:A,userJid:r}=o;if(A&&!wc(n)){let g=A.key.fromMe?r:A.participant||A.key.participant||A.key.remoteJid,c=Sa(A.message),I=YB(c);c=oe.Message.create({[I]:c[I]});let d=c[I];typeof d=="object"&&d&&"contextInfo"in d&&delete d.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=uA(g),B.stanzaId=A.key.id,B.quotedMessage=c,n!==A.key.remoteJid&&(B.remoteJid=A.key.remoteJid),B&&i[e]&&(i[e].contextInfo=B)}o?.ephemeralExpiration&&e!=="protocolMessage"&&e!=="ephemeralMessage"&&!wc(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||jB}),t=oe.Message.create(t);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||Ur()},message:t,messageTimestamp:a,messageStubParameters:[],participant:Fr(n)||Bg(n)?r:void 0,status:Td.PENDING};return oe.WebMessageInfo.fromObject(s)},Wae=async(n,t,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),vje(n,await kje(t,{...o,jid:n}),o)),YB=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},Sa=n=>{if(!n)return;for(let o=0;o<5;o++){let i=t(n);if(!i)break;n=i.message}return n;function t(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},Zae=n=>{let t=o=>o.imageMessage?{imageMessage:o.imageMessage}:o.documentMessage?{documentMessage:o.documentMessage}:o.videoMessage?{videoMessage:o.videoMessage}:o.locationMessage?{locationMessage:o.locationMessage}:{conversation:"contentText"in o?o.contentText:"hydratedContentText"in o?o.hydratedContentText:""};return n=Sa(n),n?.buttonsMessage?t(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?t(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?t(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?t(n?.templateMessage?.fourRowTemplate):n};var r2=(n,t)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===t.userJid);o?Object.assign(o,t):n.userReceipt.push(t)},a2=(n,t)=>{let o=Fd(t.key),i=(n.reactions||[]).filter(e=>Fd(e.key)!==o);t.text=t.text||"",i.push(t),n.reactions=i};var Xae=n=>{let t={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;t[A]||(t[A]={jid:o,participant:e,messageIds:[]}),t[A].messageIds.push(i)}return Object.values(t)},Pje=[410,404],i2=async(n,t,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&Pje.includes(A.status))return i.logger.info({key:n.key},"sending reupload media request..."),n=await i.reuploadRequest(n),await a();throw A});async function a(){let A=Zae(n.message);if(!A)throw new Ng.Boom("No message present",{statusCode:400,data:n});let r=YB(A),s=r?.replace("Message",""),g=A[r];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new Ng.Boom(`"${r}" message is not a media message`);let c;"thumbnailDirectPath"in g&&!("url"in g)?(c={directPath:g.thumbnailDirectPath,mediaKey:g.mediaKey},s="thumbnail-link"):c=g;let I=await _h(c,s,o);if(t==="buffer"){let d=[];for await(let B of I)d.push(B);return Buffer.concat(d)}return I}},$ae=n=>{n=Zae(n);let t=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!t)throw new Ng.Boom("given message is not a media message",{statusCode:400,data:n});return t};var MO=qe(Gr(),1);import{createHash as Uje}from"crypto";function Gje(n,t){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:vo(t)}),Fje=async({get:n},t,o)=>{let i=[];for(let e=t;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=t-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=ur.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,t]}},JB=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:yg(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),n2=(n,t)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:yg(t,3)},{tag:"value",attrs:{},content:n.public}]}),o2=n=>typeof n=="number"&&Number.isInteger(n),iie=n=>{let t=Ie(n,"keys");if(!t)return null;let o=ua(t,"type");if(!o||o.length!==1||o[0]!==Qg[0])return null;let i=ua(t,"identity"),e=Ie(t,"skey");if(!i||i.length!==32||!e)return null;let a=Oc(n,"registration",4);if(!o2(a))return null;let A=ua(e,"value"),r=ua(e,"signature"),s=Oc(e,"id",3);if(!A||A.length!==32||!r||!o2(s))return null;let g=Ie(t,"key"),c;if(g){let I=ua(g,"value"),d=Oc(g,"id",3);if(!I||I.length!==32||!o2(d))return null;c={keyId:d,publicKey:vo(I)}}return{registrationId:a,identityKey:vo(i),signedPreKey:{keyId:s,publicKey:vo(A),signature:r},preKey:c}},oie=async(n,t)=>{let o=A=>A?{keyId:Oc(A,"id",3),publicKey:vo(ua(A,"value")),signature:ua(A,"signature")}:void 0,i=PA(Ie(n,"list"),"user");for(let A of i)_i(A);let a=Gje(i,100);for(let A of a)for(let r of A){let s=Ie(r,"skey"),g=Ie(r,"key"),c=ua(r,"identity"),I=r.attrs.jid,d=Oc(r,"registration",4);await t.injectE2ESession({jid:I,session:{registrationId:d,identityKey:vo(c),signedPreKey:o(s),preKey:o(g)}})}},nie=(n,t,o,i)=>{let{user:e,device:a}=yA(t),A=[];for(let r of n){let{devices:s,id:g}=r,c=yA(g),{user:I,server:d}=c,{domainType:B}=c,f=s?.deviceList;if(Array.isArray(f))for(let{id:Q,keyIndex:y,isHosted:m}of f)(!i||Q!==0)&&(e!==I&&o!==I||a!==Q)&&(Q===0||y)&&(m&&(B=B===xt.LID?xt.HOSTED_LID:xt.HOSTED),A.push({user:I,device:Q,domainType:B,server:c9(d,B)}))}return A},s2=async({creds:n,keys:t},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=Lje(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await t.set({"pre-key":i});let r=await Fje(t,a[0],a[0]+a[1]);return{update:A,preKeys:r}},sie=async(n,t)=>{let{creds:o}=n,{update:i,preKeys:e}=await s2(n,t),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:OA},content:[{tag:"registration",attrs:{},content:yg(o.registrationId)},{tag:"type",attrs:{},content:Qg},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>n2(e[+A],+A))},JB(o.signedPreKey)]};return{update:i,node:a}};var Hje=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?oe.ClientPayload.UserAgent.Platform.ANDROID:oe.ClientPayload.UserAgent.Platform.WEB,releaseChannel:oe.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),gie={"Mac OS":oe.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:oe.ClientPayload.WebInfo.WebSubPlatform.WIN32},Kje=n=>{let t=oe.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&gie[n.browser[0]]&&n.browser[1]==="Desktop"&&(t=gie[n.browser[0]]),{webSubPlatform:t}},cie=n=>{let t={connectType:oe.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:oe.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:Hje(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(t.webInfo=Kje(n)),n.pushName&&(t.pushName=n.pushName),t},Iie=(n,t)=>{let{user:o,device:i}=yA(n),e={...cie(t),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return oe.ClientPayload.fromObject(e)},xje=n=>{let t=n.toUpperCase();return t==="ANDROID"?oe.DeviceProps.PlatformType.ANDROID_PHONE:oe.DeviceProps.PlatformType[t]||oe.DeviceProps.PlatformType.CHROME},lie=({registrationId:n,signedPreKey:t,signedIdentityKey:o},i)=>{let e=Uje("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:xje(i.browser[1]),requireFullSync:i.syncFullHistory,historySyncConfig:{storageQuotaMb:10240,inlineInitialPayloadInE2EeMsg:!0,recentSyncDaysLimit:void 0,supportCallLogHistory:!1,supportBotUserAgentChatHistory:!0,supportCagReactionsAndPolls:!0,supportBizHostedMsg:!0,supportRecentSyncChunkMessageCountTuning:!0,supportHostedGroupMsg:!0,supportFbidBotChatHistory:!0,supportAddOnHistorySyncMigration:void 0,supportMessageAssociation:!0,supportGroupHistory:!1,onDemandReady:void 0,supportGuestChat:void 0},version:{primary:10,secondary:15,tertiary:7}},A=oe.DeviceProps.encode(a).finish(),r={...cie(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:yg(n),eKeytype:Qg,eIdent:o.public,eSkeyId:yg(t.keyId,3),eSkeyVal:t.keyPair.public,eSkeySig:t.signature}};return oe.ClientPayload.fromObject(r)},pie=(n,{advSecretKey:t,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=Ie(n,"pair-success"),A=Ie(a,"device-identity"),r=Ie(a,"platform"),s=Ie(a,"device"),g=Ie(a,"biz");if(!A||!s)throw new MO.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,I=s.attrs.jid,d=s.attrs.lid,{details:B,hmac:f,accountType:Q}=oe.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);Q!==void 0&&Q===oe.ADVEncryptionType.HOSTED&&(y=g2);let m=mn(Buffer.concat([y,B]),Buffer.from(t,"base64"));if(Buffer.compare(f,m)!==0)throw new MO.Boom("Invalid account signature");let _=oe.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:T,accountSignature:R,details:H}=_,j=oe.ADVDeviceIdentity.decode(H),F=j.deviceType===oe.ADVEncryptionType.HOSTED?g2:die,q=Buffer.concat([F,H,o.public]);if(!ur.verify(T,q,R))throw new MO.Boom("Failed to verify account signature");let J=Buffer.concat([hie,H,o.public,T]);_.deviceSignature=ur.sign(o.private,J);let x=aie(d,T),P=qB(_,!1),z={tag:"iq",attrs:{to:OA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":j.keyIndex.toString()},content:P}]}]};return{creds:{account:_,me:{id:I,name:c,lid:d},signalIdentities:[...i||[],x],platform:r?.attrs.name},reply:z}},qB=(n,t)=>(n={...n},(!t||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),oe.ADVSignedDeviceIdentity.encode(n).finish());var Th=qe(Gr(),1);var uie=12,Eie=Buffer.alloc(0),Cie=n=>{let t=new ArrayBuffer(uie);return new DataView(t).setUint32(8,n),new Uint8Array(t)},c2=class{constructor(t,o){this.encKey=t,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(uie)}encrypt(t){let o=this.writeCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,nl(t,this.encKey,this.iv,Eie)}decrypt(t){let o=this.readCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,sl(t,this.decKey,this.iv,Eie)}},Bie=({keyPair:{private:n,public:t},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(fie),A=a.byteLength===32?a:Gd(a),r=A,s=A,g=A,c=0,I=!1,d=Buffer.alloc(0),B=null,f=!1,Q=null,y;e?(y=Buffer.alloc(7+e.byteLength+o.length),y.write("ED",0,"utf8"),y.writeUint8(0,2),y.writeUint8(1,3),y.writeUint8(e.byteLength>>16,4),y.writeUint16BE(e.byteLength&65535,5),y.set(e,7),y.set(o,7+e.byteLength)):y=Buffer.from(o);let m=q=>{B||(A=Gd(Buffer.concat([A,q])))},_=q=>{if(B)return B.encrypt(q);let J=nl(q,s,Cie(c++),A);return m(J),J},T=q=>{if(B)return B.decrypt(q);let J=sl(q,g,Cie(c++),A);return m(q),J},R=q=>{let J=yn(Buffer.from(q),64,{salt:r,info:""});return[J.subarray(0,32),J.subarray(32)]},H=q=>{let[J,x]=R(q);r=J,s=x,g=x,c=0},j=async()=>{f=!0;let[q,J]=R(new Uint8Array(0));B=new c2(q,J),f=!1,i.trace("Noise handler transitioned to Transport state"),Q&&(i.trace({length:d.length},"Flushing buffered frames after transport ready"),await F(Q),Q=null)},F=async q=>{let J;for(;;){if(d.length<3||(J=d[0]<<16|d[1]<<8|d[2],d.length{m(q.ephemeral),H(ur.sharedKey(n,q.ephemeral));let x=T(q.static);H(ur.sharedKey(n,x));let P=T(q.payload),{intermediate:z,leaf:U}=oe.CertChain.decode(P);if(!U?.details||!U?.signature)throw new Th.Boom("invalid noise leaf certificate",{statusCode:400});if(!z?.details||!z?.signature)throw new Th.Boom("invalid noise intermediate certificate",{statusCode:400});let N=oe.CertChain.NoiseCertificate.Details.decode(z.details),{issuerSerial:k}=N,V=ur.verify(N.key,U.details,U.signature),ee=ur.verify(I2.PUBLIC_KEY,z.details,z.signature);if(!V)throw new Th.Boom("noise certificate signature invalid",{statusCode:400});if(!ee)throw new Th.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(k!==I2.SERIAL)throw new Th.Boom("certification match failed",{statusCode:400});let ie=_(J.public);return H(ur.sharedKey(J.private,q.ephemeral)),ie},encodeFrame:q=>{B&&(q=B.encrypt(q));let J=q.byteLength,x=I?0:y.length,P=Buffer.allocUnsafe(x+3+J);return I||(P.set(y),I=!0),P[x]=J>>>16&255,P[x+1]=J>>>8&255,P[x+2]=J&255,P.set(q,x+3),P},decodeFrame:async(q,J)=>{if(f){d=Buffer.concat([d,q]),Q=J;return}d.length===0?d=Buffer.from(q):d=Buffer.concat([d,q]),await F(J)}}};import{pipeline as Yje}from"stream/promises";import{promisify as jje}from"util";import{createInflate as Jje,inflate as qje}from"zlib";var zje=jje(qje),Vje=n=>{for(let t of n){let o=t.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(bt(i)||Cr(i)))return i}},Wje=async(n,t)=>{let o=await _h(n,"md-msg-hist",{options:t}),i=Jje(),e=[];i.on("data",r=>e.push(r)),await Yje(o,i);let a=Buffer.concat(e);return oe.HistorySync.decode(a)},Zje=(n,t)=>{let o=[],i=[],e=[],a=[];t?.trace({progress:n.progress},"processing history of type "+n.syncType?.toString());for(let A of n.phoneNumberToLidMappings||[])A.lidJid&&A.pnJid&&a.push({lid:A.lidJid,pn:A.pnJid});switch(n.syncType){case oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case oe.HistorySync.HistorySyncType.RECENT:case oe.HistorySync.HistorySyncType.FULL:case oe.HistorySync.HistorySyncType.ON_DEMAND:for(let A of n.conversations){i.push({id:A.id,name:A.displayName||A.name||A.username||void 0,username:A.username||void 0,lid:A.lidJid||A.accountLid||void 0,phoneNumber:A.pnJid||void 0});let r=A.id,s=qA(r)||oa(r),g=bt(r)||Cr(r);if(s&&A.pnJid)a.push({lid:r,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:r});else if(s&&!A.pnJid){let I=Vje(A.messages||[]);I&&a.push({lid:r,pn:I})}let c=A.messages||[];delete A.messages;for(let I of c){let d=I.message;o.push(d),A.messages?.length||(A.messages=[{message:d}]),!d.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=Lr(d.messageTimestamp)),(d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_BSP||d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_FB)&&d.messageStubParameters?.[0]&&i.push({id:d.key.participant||d.key.remoteJid,verifiedName:d.messageStubParameters?.[0]})}e.push(A)}break;case oe.HistorySync.HistorySyncType.PUSH_NAME:for(let A of n.pushnames)i.push({id:A.id,notify:A.pushname});break}return{chats:e,contacts:i,messages:o,lidPnMappings:a,pastParticipants:n.pastParticipants,syncType:n.syncType,progress:n.progress}},Qie=async(n,t,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=oe.HistorySync.decode(await zje(n.initialHistBootstrapInlinePayload)):i=await Wje(n,t),Zje(i,o)},_O=n=>(n?Sa(n):void 0)?.protocolMessage?.historySyncNotification;var Jo=qe(Gr(),1);var Rs;(function(n){n.Chat="label_jid",n.Message="label_message"})(Rs||(Rs={}));var yie=new kd;var mie=(n,t,o)=>{let i=[];if(!t)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=bt(t),A=a?t:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:t,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&qA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:t}}),i},Sie=(n,t)=>{for(let o of t)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var zB=n=>{let t=N9(n);return{indexKey:t.indexKey,valueEncryptionKey:t.valueEncryptionKey,valueMacKey:t.valueMacKey,snapshotMacKey:t.snapshotMacKey,patchMacKey:t.patchMacKey}},Die=(n,t,o,i)=>{let e=n===oe.SyncdMutation.SyncdOperation.SET?1:2,a=typeof o=="string"?Buffer.from(o,"base64"):o,A=new Uint8Array(1+a.length);A[0]=e,A.set(a,1);let r=new Uint8Array(8);r[7]=A.length;let s=new Uint8Array(A.length+t.length+r.length);return s.set(A,0),s.set(t,A.length),s.set(r,A.length+t.length),mn(s,i,"sha512").subarray(0,32)},wie=n=>{let t=Buffer.alloc(8);return t.writeUint32BE(n,4),t},Oie=({indexValueMap:n,hash:t})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let r=Buffer.from(e).toString("base64"),s=n[r];if(A===oe.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[r]}else o.push(a),n[r]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=yie.subtractThenAdd(t,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},l2=(n,t,o,i)=>{let e=Buffer.concat([n,wie(t),Buffer.from(o,"utf-8")]);return mn(e,i,"sha256")},bie=(n,t,o,i,e)=>{let a=Buffer.concat([n,...t,wie(o),Buffer.from(i,"utf-8")]);return mn(a,e)},TO=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),p2=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),d2=2,VB=n=>n?.data?.isMissingKey===!0,Mie=(n,t)=>t>=d2||n?.name==="TypeError",_ie=async({type:n,index:t,syncAction:o,apiVersion:i,operation:e},a,A,r)=>{let s=a?await r(a):void 0;if(!s)throw new Jo.Boom(`myAppStateKey ("${a}") not present`,{data:{isMissingKey:!0}});let g=Buffer.from(a,"base64");A={...A,indexValueMap:{...A.indexValueMap}};let c=Buffer.from(JSON.stringify(t)),I=oe.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),d=oe.SyncActionData.encode(I).finish(),B=zB(s.keyData),f=U9(d,B.valueEncryptionKey),Q=Die(e,f,g,B.valueMacKey),y=mn(c,B.indexKey),m=Oie(A);m.mix({indexMac:y,valueMac:Q,operation:e}),Object.assign(A,m.finish()),A.version+=1;let _=l2(A.hash,A.version,n,B.snapshotMacKey),T={patchMac:bie(_,[Q],A.version,n,B.patchMacKey),snapshotMac:_,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([f,Q])},keyId:{id:g}}}]},R=y.toString("base64");return A.indexValueMap[R]={valueMac:Q},{patch:T,state:A}},Tie=async(n,t,o,i,e)=>{let a=Oie(t),A=new Map;for(let s of n){let g="operation"in s?s.operation:oe.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,I;try{I=await r(c.keyId.id)}catch(_){if(VB(_))throw _;continue}let d=c.value.blob,B=d.subarray(0,-32),f=d.subarray(-32);if(e){let _=Die(g,B,c.keyId.id,I.valueMacKey);if(Buffer.compare(_,f)!==0)continue}let Q;try{Q=L9(B,I.valueEncryptionKey)}catch{continue}let y=oe.SyncActionData.decode(Q);if(e){let _=mn(y.index,I.indexKey);if(Buffer.compare(_,c.index.blob)!==0)throw new Jo.Boom("HMAC index verification failed")}let m=Buffer.from(y.index).toString();i({syncAction:y,index:JSON.parse(m)}),a.mix({indexMac:c.index.blob,valueMac:f,operation:g})}return a.finish();async function r(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let I=await o(g);if(!I)throw new Jo.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let d=zB(I.keyData);return A.set(g,d),d}},Xje=async(n,t,o,i,e,a)=>{if(a){let r=Buffer.from(n.keyId.id).toString("base64"),s=await i(r);if(!s)throw new Jo.Boom(`failed to find key "${r}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=zB(s.keyData),c=n.mutations.map(d=>d.record.value.blob.slice(-32)),I=bie(n.snapshotMac,c,Lr(n.version.version),t,g.patchMacKey);if(Buffer.compare(I,n.patchMac)!==0)throw new Jo.Boom("Invalid patch mac")}return await Tie(n.mutations,o,i,e,a)},Nie=async(n,t)=>{let o=Ie(n,"sync"),i=PA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=Ie(a,"patches"),r=PA(A||a,"patch"),s=Ie(a,"snapshot"),g=[],c=a.attrs.name,I=a.attrs.has_more_patches==="true",d;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=oe.ExternalBlobReference.decode(s.content),f=await Rie(B,t);d=oe.SyncdSnapshot.decode(f)}for(let{content:B}of r)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let f=oe.SyncdPatch.decode(B);f.version||(f.version={version:+a.attrs.version+1}),g.push(f)}e[c]={patches:g,hasMorePatches:I,snapshot:d}})),e},Rie=async(n,t)=>{let o=await _h(n,"md-app-state",{options:t}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},$je=async(n,t)=>{let o=await Rie(n,t);return oe.SyncdMutations.decode(o)},kie=async(n,t,o,i,e=!0,a)=>{let A=TO();A.version=Lr(t.version.version);let r={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await Tie(t.records,A,o,s?I=>{let d=I.syncAction.index?.toString();r[d]=I}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let I=Buffer.from(t.keyId.id).toString("base64"),d=await o(I);if(!d)throw new Jo.Boom(`failed to find key "${I}" to decode mutation`,{data:{isMissingKey:!0}});let B=zB(d.keyData),f=l2(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(t.mac,f)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:r}},h2=async(n,t,o,i,e,a,A,r=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of t){let{version:I,keyId:d,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:I},"downloading external patch");let m=await $je(c.externalMutations,e);A?.debug({name:n,version:I,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let f=Lr(I.version);s.version=f;let Q=typeof a>"u"||f>a,y;try{y=await Xje(c,n,s,i,Q?m=>{let _=m.syncAction.index?.toString();g[_]=m}:()=>{},r)}catch(m){if(VB(m))throw m;A?.warn({name:n,version:f,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,r){let m=Buffer.from(d.id).toString("base64"),_=await i(m);if(!_)throw new Jo.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let T=zB(_.keyData),R=l2(s.hash,s.version,n,T.snapshotMacKey);if(Buffer.compare(B,R)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},vie=(n,t)=>{let o=oe.SyncdMutation.SyncdOperation,i=a=>{let A;return Array.isArray(a)?A={lastMessageTimestamp:a[a.length-1]?.messageTimestamp,messages:a?.length?a.map(s=>{if(!s.key?.id||!s.key?.remoteJid)throw new Jo.Boom("Incomplete key",{statusCode:400,data:s});if(Fr(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new Jo.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!Lr(s.messageTimestamp))throw new Jo.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=uA(s.key.participant)),s}):void 0}:A=a,A},e;if("mute"in n)e={syncAction:{muteAction:{muted:!!n.mute,muteEndTimestamp:n.mute||void 0}},index:["mute",t],type:"regular_high",apiVersion:2,operation:o.SET};else if("archive"in n)e={syncAction:{archiveChatAction:{archived:!!n.archive,messageRange:i(n.lastMessages)}},index:["archive",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("markRead"in n)e={syncAction:{markChatAsReadAction:{read:n.markRead,messageRange:i(n.lastMessages)}},index:["markChatAsRead",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:r}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:r,messageTimestamp:a}},index:["deleteMessageForMe",t,A.id,A.fromMe?"1":"0","0"],type:"regular_high",apiVersion:3,operation:o.SET}}else if("clear"in n)e={syncAction:{clearChatAction:{messageRange:i(n.lastMessages)}},index:["clearChat",t,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",t],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",t],type:"critical_unblock_low",apiVersion:2,operation:n.contact?o.SET:o.REMOVE};else if("disableLinkPreviews"in n)e={syncAction:{privacySettingDisableLinkPreviewsAction:n.disableLinkPreviews||{}},index:["setting_disableLinkPreviews"],type:"regular",apiVersion:8,operation:o.SET};else if("star"in n){let a=n.star.messages[0];e={syncAction:{starAction:{starred:!!n.star.star}},index:["star",t,a.id,a.fromMe?"1":"0","0"],type:"regular_low",apiVersion:2,operation:o.SET}}else if("delete"in n)e={syncAction:{deleteChatAction:{messageRange:i(n.lastMessages)}},index:["deleteChat",t,"1"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pushNameSetting"in n)e={syncAction:{pushNameSetting:{name:n.pushNameSetting}},index:["setting_pushName"],type:"critical_block",apiVersion:1,operation:o.SET};else if("quickReply"in n)e={syncAction:{quickReplyAction:{count:0,deleted:n.quickReply.deleted||!1,keywords:[],message:n.quickReply.message||"",shortcut:n.quickReply.shortcut||""}},index:["quick_reply",n.quickReply.timestamp||String(Math.floor(Date.now()/1e3))],type:"regular",apiVersion:2,operation:o.SET};else if("addLabel"in n)e={syncAction:{labelEditAction:{name:n.addLabel.name,color:n.addLabel.color,predefinedId:n.addLabel.predefinedId,deleted:n.addLabel.deleted}},index:["label_edit",n.addLabel.id],type:"regular",apiVersion:3,operation:o.SET};else if("addChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Rs.Chat,n.addChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Rs.Chat,n.removeChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Rs.Message,n.addMessageLabel.labelId,t,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Rs.Message,n.removeMessageLabel.labelId,t,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new Jo.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},Pie=(n,t,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:r},index:[s,g,c,I]}=n;if(r?.muteAction)t.emit("chats.update",[{id:g,muteEndTime:r.muteAction?.muted?Lr(r.muteAction.muteEndTimestamp):null,conditional:d(g,void 0)}]);else if(r?.archiveChatAction||s==="archive"||s==="unarchive"){let f=r?.archiveChatAction,Q=f?f.archived:s==="archive",y=A?.unarchiveChats?f?.messageRange:void 0;t.emit("chats.update",[{id:g,archived:Q,conditional:d(g,y)}])}else if(r?.markChatAsReadAction){let f=r.markChatAsReadAction,Q=a&&f.read;t.emit("chats.update",[{id:g,unreadCount:Q?null:f?.read?0:-1,conditional:d(g,f?.messageRange)}])}else if(r?.deleteMessageForMeAction||s==="deleteMessageForMe")t.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:I==="1"}]});else if(r?.contactAction){let f=mie(r.contactAction,g,e);Sie(t,f)}else if(r?.pushNameSetting){let f=r?.pushNameSetting?.name;f&&o?.name!==f&&t.emit("creds.update",{me:{...o,name:f}})}else if(r?.pinAction)t.emit("chats.update",[{id:g,pinned:r.pinAction?.pinned?Lr(r.timestamp):null,conditional:d(g,void 0)}]);else if(r?.unarchiveChatsSetting){let f=!!r.unarchiveChatsSetting.unarchiveChats;t.emit("creds.update",{accountSettings:{unarchiveChats:f}}),e?.info(`archive setting updated => '${r.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=f)}else if(r?.starAction||s==="star"){let f=r?.starAction?.starred;typeof f!="boolean"&&(f=n.index[n.index.length-1]==="1"),t.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:I==="1"},update:{starred:f}}])}else if(r?.deleteChatAction||s==="deleteChat")a||t.emit("chats.delete",[g]);else if(r?.labelEditAction){let{name:f,color:Q,deleted:y,predefinedId:m}=r.labelEditAction;t.emit("labels.edit",{id:g,name:f,color:Q,deleted:y,predefinedId:m?String(m):void 0})}else r?.labelAssociationAction?t.emit("labels.association",{type:r.labelAssociationAction.labeled?"add":"remove",association:s===Rs.Chat?{type:Rs.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:Rs.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):r?.localeSetting?.locale?t.emit("settings.update",{setting:"locale",value:r.localeSetting.locale}):r?.timeFormatAction?t.emit("settings.update",{setting:"timeFormat",value:r.timeFormatAction}):r?.pnForLidChatAction?r.pnForLidChatAction.pnJid&&t.emit("lid-mapping.update",{lid:g,pn:r.pnForLidChatAction.pnJid}):r?.privacySettingRelayAllCalls?t.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:r.privacySettingRelayAllCalls}):r?.statusPrivacy?t.emit("settings.update",{setting:"statusPrivacy",value:r.statusPrivacy}):r?.lockChatAction?t.emit("chats.lock",{id:g,locked:!!r.lockChatAction.locked}):r?.privacySettingDisableLinkPreviewsAction?t.emit("settings.update",{setting:"disableLinkPreviews",value:r.privacySettingDisableLinkPreviewsAction}):r?.notificationActivitySettingAction?.notificationActivitySetting?t.emit("settings.update",{setting:"notificationActivitySetting",value:r.notificationActivitySettingAction.notificationActivitySetting}):r?.lidContactAction?t.emit("contacts.upsert",[{id:g,name:r.lidContactAction.fullName||r.lidContactAction.firstName||r.lidContactAction.username||void 0,username:r.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):r?.privacySettingChannelsPersonalisedRecommendationAction?t.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:r.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function d(f,Q){return a?y=>{let m=y.historySets.chats[f]||y.chatUpserts[f];if(m)return Q?B(m,Q):!0}:void 0}function B(f,Q){let y=Number(Q?.lastMessageTimestamp||Q?.lastSystemMessageTimestamp||0),m=Number(f?.lastMessageRecvTimestamp||0);return y>=m}};var eJe=class{_eventListeners;_maxListeners;_logger;_throwOnEmitError=!1;_throwOnEmptyListeners=!1;_errorEvent="error";constructor(n){this._eventListeners=new Map,this._maxListeners=100,this._logger=n?.logger,n?.throwOnEmitError!==void 0&&(this._throwOnEmitError=n.throwOnEmitError),n?.throwOnEmptyListeners!==void 0&&(this._throwOnEmptyListeners=n.throwOnEmptyListeners)}get logger(){return this._logger}set logger(n){this._logger=n}get throwOnEmitError(){return this._throwOnEmitError}set throwOnEmitError(n){this._throwOnEmitError=n}get throwOnEmptyListeners(){return this._throwOnEmptyListeners}set throwOnEmptyListeners(n){this._throwOnEmptyListeners=n}once(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let t=this._eventListeners.get(n);return t?t.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,t){let o=this._eventListeners.get(n)??[];return o.unshift(t),this._eventListeners.set(n,o),this}prependOnceListener(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,t){return this.on(n,t),this}on(n,t){this._eventListeners.has(n)||this._eventListeners.set(n,[]);let o=this._eventListeners.get(n);return o&&(o.length>=this._maxListeners&&console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${o.length+1} ${n} listeners added. Use setMaxListeners() to increase limit.`),o.push(t)),this}removeListener(n,t){return this.off(n,t),this}off(n,t){let o=this._eventListeners.get(n)??[],i=o.indexOf(t);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...t){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...t),o=!0;if(n===this._errorEvent){let e=t[0]instanceof Error?t[0]:new Error(`${t[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,t),o}listeners(n){return this._eventListeners.get(n)??[]}removeAllListeners(n){return n!==void 0?this._eventListeners.delete(n):this._eventListeners.clear(),this}setMaxListeners(n){this._maxListeners=n;for(let t of this._eventListeners.values())t.length>n&&t.splice(n)}getAllListeners(){let n=[];for(let t of this._eventListeners.values())n=[...n,...t];return n}sendLog(n,t){if(!this._logger)return;let o;switch(typeof t=="string"?o=t:Array.isArray(t)&&t.length>0&&t[0]instanceof Error?o=t[0].message:t instanceof Error?o=t.message:Array.isArray(t)&&t.length>0&&typeof t[0]?.message=="string"?o=t[0].message:o=JSON.stringify(t),n){case"error":{this._logger.error?.(o,{event:n,data:t});break}case"warn":{this._logger.warn?.(o,{event:n,data:t});break}case"trace":{this._logger.trace?.(o,{event:n,data:t});break}case"debug":{this._logger.debug?.(o,{event:n,data:t});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:t});break}default:{this._logger.info?.(o,{event:n,data:t});break}}}},Zc=class extends eJe{_hooks;_throwOnHookError=!1;_enforceBeforeAfter=!1;_deprecatedHooks;_allowDeprecated=!0;constructor(n){super({logger:n?.logger,throwOnEmitError:n?.throwOnEmitError,throwOnEmptyListeners:n?.throwOnEmptyListeners}),this._hooks=new Map,this._deprecatedHooks=n?.deprecatedHooks?new Map(n.deprecatedHooks):new Map,n?.throwOnHookError!==void 0?this._throwOnHookError=n.throwOnHookError:n?.throwHookErrors!==void 0&&(this._throwOnHookError=n.throwHookErrors),n?.enforceBeforeAfter!==void 0&&(this._enforceBeforeAfter=n.enforceBeforeAfter),n?.allowDeprecated!==void 0&&(this._allowDeprecated=n.allowDeprecated)}get hooks(){return this._hooks}get throwHookErrors(){return this._throwOnHookError}set throwHookErrors(n){this._throwOnHookError=n}get throwOnHookError(){return this._throwOnHookError}set throwOnHookError(n){this._throwOnHookError=n}get enforceBeforeAfter(){return this._enforceBeforeAfter}set enforceBeforeAfter(n){this._enforceBeforeAfter=n}get deprecatedHooks(){return this._deprecatedHooks}set deprecatedHooks(n){this._deprecatedHooks=n}get allowDeprecated(){return this._allowDeprecated}set allowDeprecated(n){this._allowDeprecated=n}validateHookName(n){if(this._enforceBeforeAfter){let t=n.trim().toLocaleLowerCase();if(!t.startsWith("before")&&!t.startsWith("after"))throw new Error(`Hook event "${n}" must start with "before" or "after" when enforceBeforeAfter is enabled`)}}checkDeprecatedHook(n){if(this._deprecatedHooks.has(n)){let t=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${t?`: ${t}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,t){this.onHookEntry({event:n,handler:t})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let t=this._hooks.get(n.event);t?t.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,t){this.onHookEntry({event:n,handler:t})}onHooks(n){for(let t of n)this.onHook(t.event,t.handler)}prependHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(t):this._hooks.set(n,[t])}prependOnceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.prependHook(n,o)}onceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.onHook(n,o)}removeHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let t of n)this.removeHook(t.event,t.handler)}async hook(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){for(let i of o)if(i.constructor.name!=="AsyncFunction")try{i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...t){await this.hook(`before:${n}`,...t)}async afterHook(n,...t){await this.hook(`after:${n}`,...t)}async callHook(n,...t){await this.hook(n,...t)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var AJe=class{_enabled=!0;_maxSize=4e3;_store=new Map;_keys=[];constructor(n){n?.enabled!==void 0&&(this._enabled=n.enabled),n?.maxSize!==void 0&&(this._maxSize=n.maxSize)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get maxSize(){return this._maxSize}set maxSize(n){this._maxSize=n}get store(){return this._store}get size(){return this._store.size}get(n){return this._store.get(n)}set(n,t){if(this._enabled){if(this._store.has(n)){this._store.set(n,t);return}if(this._store.size>=this._maxSize){let o=this._keys.shift();o&&this._store.delete(o)}this._keys.push(n),this._store.set(n,t)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},tJe=class{get name(){return"crc32"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;t=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}let o=3988292384,i=4294967295;for(let a=0;a>>1^o&-(i&1)}return i=(i^4294967295)>>>0,i.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},NO=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let t=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}},rJe=class{get name(){return"djb2"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let o=5381;for(let e=0;e>>0;return o.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},aJe=class{get name(){return"fnv1"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;t=new Uint8Array(A.buffer,A.byteOffset,A.byteLength)}let o=2166136261,i=16777619,e=o;for(let A=0;A>>0;return e.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},iJe=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;t=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=t.length,a=Math.floor(e/4),A=this._seed;for(let c=0;c>>16,A=this._imul(A,2246822507),A^=A>>>13,A=this._imul(A,3266489909),A^=A>>>16,A=A>>>0,A.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}_imul(n,t){if(Math.imul)return Math.imul(n,t);let o=n>>>16&65535,i=n&65535,e=t>>>16&65535,a=t&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,t){return n<>>32-t}},oJe=class{_providers=new Map;_getFuzzy=!0;constructor(n){n?.providers&&this.loadProviders(n?.providers),n?.getFuzzy!==void 0&&(this._getFuzzy=!!n?.getFuzzy)}loadProviders(n){for(let t of n)this._providers.set(t.name,t)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,t){let o=t?.fuzzy??this._getFuzzy;n=n.trim();let i=this._providers.get(n);return i===void 0&&o===!0&&(n=n.toLowerCase(),i=this._providers.get(n)),i===void 0&&o===!0&&(n=n.replaceAll("-",""),i=this._providers.get(n)),i}add(n){this._providers.set(n.name,n)}remove(n){return this._providers.delete(n)}},E2=class extends Zc{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new oJe;_defaultAlgorithm="SHA-256";_defaultAlgorithmSync="djb2";_cache;constructor(n){super(n),n?.parse&&(this._parse=n.parse),n?.stringify&&(this._stringify=n.stringify),n?.defaultAlgorithm&&(this._defaultAlgorithm=n.defaultAlgorithm),n?.defaultAlgorithmSync&&(this._defaultAlgorithmSync=n.defaultAlgorithmSync),this._cache=new AJe(n?.cache),this.loadProviders(n?.providers,{includeBase:n?.includeBase??!0})}get parse(){return this._parse}set parse(n){this._parse=n}get stringify(){return this._stringify}set stringify(n){this._stringify=n}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return this._providers.names}get defaultAlgorithm(){return this._defaultAlgorithm}set defaultAlgorithm(n){this._defaultAlgorithm=n}get defaultAlgorithmSync(){return this._defaultAlgorithmSync}set defaultAlgorithmSync(n){this._defaultAlgorithmSync=n}get cache(){return this._cache}async toHash(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithm,maxLength:t?.maxLength};await this.beforeHook("toHash",o);let i=this._stringify(o.data),e=`${o.algorithm}:${i}`;if(this._cache.enabled){let c=this._cache.get(e);if(c!==void 0){let I=c;t?.maxLength&&I.length>t.maxLength&&(I=I.substring(0,t.maxLength));let d={hash:I,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",d),d.hash}}let A=new TextEncoder().encode(i),r=this._providers.get(o.algorithm);r||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),r=new NO({algorithm:this._defaultAlgorithm}));let s=await r.toHash(A);this._cache.enabled&&this._cache.set(e,s),t?.maxLength&&s.length>t?.maxLength&&(s=s.substring(0,t.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}toHashSync(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithmSync,maxLength:t?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let I=this._cache.get(a);if(I!==void 0){let d=I;t?.maxLength&&d.length>t.maxLength&&(d=d.substring(0,t.maxLength));let B={hash:d,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let r=new TextEncoder().encode(e),s=this._providers.get(i);if(!s&&(this.emit("warn",`Invalid algorithm '${i}' not found. Falling back to default algorithm '${this._defaultAlgorithmSync}'.`),s=this._providers.get(this._defaultAlgorithmSync),!s))throw new Error(`Hash provider '${this._defaultAlgorithmSync}' (default) not found`);if(!s.toHashSync)throw new Error(`Hash provider '${i}' does not support synchronous hashing. Use toHash() instead or choose a different algorithm (djb2, fnv1, murmur, crc32).`);let g=s.toHashSync(r);this._cache.enabled&&this._cache.set(a,g),t?.maxLength&&g.length>t?.maxLength&&(g=g.substring(0,t.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}loadProviders(n,t={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);t.includeBase&&(this.providers.add(new NO({algorithm:"SHA-256"})),this.providers.add(new NO({algorithm:"SHA-384"})),this.providers.add(new NO({algorithm:"SHA-512"})),this.providers.add(new tJe),this.providers.add(new rJe),this.providers.add(new aJe),this.providers.add(new iJe))}};var B2=n=>{let t;if(n!==void 0){if(typeof n=="number")t=n;else{if(typeof n!="string")return;if(n=n.trim(),Number.isNaN(Number(n))){let o=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(n);if(!o)throw new Error(`Unsupported time format: "${n}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,e]=o,a=Number.parseFloat(i);switch(e.toLowerCase()){case"ms":t=a;break;case"s":t=a*1e3;break;case"m":t=a*1e3*60;break;case"h":t=a*1e3*60*60;break;case"hr":t=a*1e3*60*60;break;case"d":t=a*1e3*60*60*24;break;default:t=Number(n)}}else t=Number(n)}return t}},Nl=(n,t)=>{t??=new Date;let o=B2(n);return o===void 0?t.getTime():t.getTime()+o};var WB=(function(n){return n.SHA256="SHA-256",n.SHA384="SHA-384",n.SHA512="SHA-512",n.DJB2="djb2",n.FNV1="fnv1",n.MURMER="murmer",n.CRC32="crc32",n})({});function C2(n,t={algorithm:"djb2",serialize:JSON.stringify}){let o=t?.algorithm??"djb2",i=(t?.serialize??JSON.stringify)(n);return new E2().toHashSync(i,{algorithm:o})}function Gie(n,t={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=t?.min??0,i=t?.max??10,e=t?.algorithm??"djb2",a=t?.serialize??JSON.stringify,A=t?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let r=a(n);return new E2().toNumberSync(r,{algorithm:e,min:o,max:i,hashLength:A})}function f2(n,t){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=t;return(...A)=>{let r=nJe(n,A,{keyPrefix:i,serialize:a});t.createKey&&(r=t.createKey(n,A,t));let s=e.get(r);if(s===void 0)try{s=n(...A),e.set(r,s,o)}catch(g){e.emit("error",g),t.cacheErrors&&e.set(r,g,o)}return s}}function Q2(n,t,o){let i=typeof n=="function"?n(o):n,e;try{e=o.cache.get(i)}catch(a){if(o.cache.emit("error",a),o.throwErrors===!0||o.throwErrors==="store")throw a}if(e===void 0)try{try{e=t()}catch(a){throw new RO(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new RO(a,"store")}}catch(a){let A=a instanceof RO?a.context:void 0,r=a instanceof RO?a.error:a;if(o.cache.emit("error",r),o.cacheErrors&&A==="function")try{o.cache.set(i,r,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw r}return e}function nJe(n,t,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${C2(t,{serialize:e})}`:`${n.name}::${C2(t,{serialize:e})}`}var RO=class{error;context;constructor(n,t){this.error=n,this.context=t}};var Xc=class{_counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0};_vsize=0;_ksize=0;_enabled=!1;_lastUpdated;_lastReset;_subscriptions=[];_trackedKeys=new Map;_trackKeys=!1;_maxTrackedKeys;constructor(n){n?.enabled&&(this._enabled=n.enabled),n?.trackKeys&&(this._trackKeys=n.trackKeys),n?.maxTrackedKeys!==void 0&&(this._maxTrackedKeys=n.maxTrackedKeys),n?.emitter&&n?.eventMap&&this.subscribe(n.emitter,n.eventMap)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get trackKeys(){return this._trackKeys}set trackKeys(n){this._trackKeys=n}get maxTrackedKeys(){return this._maxTrackedKeys}set maxTrackedKeys(n){this._maxTrackedKeys=n}get trackedKeys(){return this._trackedKeys}get hits(){return this._counters.hits}get misses(){return this._counters.misses}get gets(){return this._counters.gets}get sets(){return this._counters.sets}get deletes(){return this._counters.deletes}get clears(){return this._counters.clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._counters.count}get hitRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.hits/n}get missRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.misses/n}get lastUpdated(){return this._lastUpdated}get lastReset(){return this._lastReset}increment(n,t=1){this._enabled&&(this._counters[n]+=t,this.touch())}decrement(n,t=1){this._enabled&&(this._counters[n]-=t,this.touch())}incrementHits(n=1){this.increment("hits",n)}incrementMisses(n=1){this.increment("misses",n)}incrementGets(n=1){this.increment("gets",n)}incrementSets(n=1){this.increment("sets",n)}incrementDeletes(n=1){this.increment("deletes",n)}incrementClears(n=1){this.increment("clears",n)}incrementVSize(n){this._enabled&&(this._vsize+=this.roughSizeOfObject(n),this.touch())}decreaseVSize(n){this._enabled&&(this._vsize=Math.max(0,this._vsize-this.roughSizeOfObject(n)),this.touch())}incrementKSize(n){this._enabled&&(this._ksize+=this.roughSizeOfString(n),this.touch())}decreaseKSize(n){this._enabled&&(this._ksize=Math.max(0,this._ksize-this.roughSizeOfString(n)),this.touch())}incrementCount(n=1){this.increment("count",n)}decreaseCount(n=1){this._enabled&&(this._counters.count=Math.max(0,this._counters.count-n),this.touch())}setCount(n){this._enabled&&(this._counters.count=n,this.touch())}roughSizeOfString(n){return n.length*2}roughSizeOfObject(n){let t=[],o=[n],i=0;for(;o.length>0;){let e=o.pop();if(typeof e=="boolean")i+=4;else if(typeof e=="string")i+=e.length*2;else if(typeof e=="number")i+=8;else{if(e==null){i+=4;continue}if(t.includes(e))continue;t.push(e);for(let a in e)i+=a.length*2,o.push(e[a])}}return i}enable(){this._enabled=!0}disable(){this._enabled=!1}clear(){this.reset()}reset(){this._counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0},this._vsize=0,this._ksize=0,this._trackedKeys.clear(),this._lastReset=Date.now(),this._lastUpdated=void 0}resetStoreValues(){this._vsize=0,this._ksize=0,this._counters.count=0}toJSON(){return{enabled:this._enabled,hits:this._counters.hits,misses:this._counters.misses,gets:this._counters.gets,sets:this._counters.sets,deletes:this._counters.deletes,clears:this._counters.clears,vsize:this._vsize,ksize:this._ksize,count:this._counters.count,hitRate:this.hitRate,missRate:this.missRate,trackedKeys:this._trackedKeys.size,lastUpdated:this._lastUpdated,lastReset:this._lastReset}}snapshot(){return this.toJSON()}recordKey(n,t,o=1){if(!this._enabled||!this._trackKeys)return;let i=this._trackedKeys.get(n);i||(i={hits:0,misses:0,gets:0,sets:0,deletes:0},this._trackedKeys.set(n,i),this.pruneTrackedKeys(n)),i[t]+=o,this.touch()}mostUsedKeys(n=100,t){return this.sortedKeyEntries(t,"desc").slice(0,n)}leastUsedKeys(n=100,t){return this.sortedKeyEntries(t,"asc").slice(0,n)}keyStats(n){let t=this._trackedKeys.get(n);return t?this.toKeyEntry(n,t):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,t){let o=t.hits+t.misses;return{key:n,count:this.totalOf(t),hits:t.hits,misses:t.misses,gets:t.gets,sets:t.sets,deletes:t.deletes,hitRate:o===0?0:t.hits/o}}sortedKeyEntries(n,t){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=t==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,r=n?a[n]:a.count;return A!==r?(A-r)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=t)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,t){for(let[o,i]of Object.entries(t)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let t=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){t.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=t}applyEvent(n,t){if(this._enabled){if(typeof n=="function"){n(this,...t);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var sJe=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},y2=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let t=new sJe(n);this.head?(t.next=this.head,this.head.prev=t,this.head=t):this.head=this.tail=t,this.nodesMap.set(n,t)}moveToFront(n){let t=this.nodesMap.get(n);if(!t||this.head===t)return;t.prev&&(t.prev.next=t.next);t.next&&(t.next.prev=t.prev);t===this.tail&&(this.tail=t.prev),t.prev=void 0,t.next=this.head;this.head&&(this.head.prev=t),this.head=t,this.tail??=t}getOldest(){return this.tail?this.tail.value:void 0}removeOldest(){if(!this.tail)return;let n=this.tail.value;return this.tail.prev?(this.tail=this.tail.prev,this.tail.next=void 0):this.head=this.tail=void 0,this.nodesMap.delete(n),n}remove(n){let t=this.nodesMap.get(n);return t?(t.prev?t.prev.next=t.next:(this.head=t.next,this.head&&(this.head.prev=void 0)),t.next?t.next.prev=t.prev:(this.tail=t.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var Fie=16777216,m2=class extends Zc{_lru=new y2;_storeHashSize=16;_storeHashAlgorithm=WB.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new Xc({enabled:!1});constructor(n){super(),n?.ttl&&this.setTtl(n.ttl),n?.maxTtl!==void 0&&this.setMaxTtl(n.maxTtl),n?.useClone!==void 0&&(this._useClone=n.useClone),n?.stats&&(this._stats.enabled=n.stats),n?.storeHashSize&&n.storeHashSize>0&&(this._storeHashSize=n.storeHashSize),n?.lruSize&&(n.lruSize>16777216?this.emit("error",new Error(`LRU size cannot be larger than ${Fie} due to Map limitations.`)):this._lruSize=n.lruSize),n?.checkInterval&&(this._checkInterval=n.checkInterval),n?.storeHashAlgorithm&&(this._storeHashAlgorithm=n.storeHashAlgorithm),this._store=Array.from({length:this._storeHashSize},()=>new Map),this.startIntervalCheck()}get ttl(){return this._ttl}set ttl(n){this.setTtl(n)}get maxTtl(){return this._maxTtl}set maxTtl(n){this.setMaxTtl(n)}get useClone(){return this._useClone}set useClone(n){this._useClone=n}get lruSize(){return this._lruSize}set lruSize(n){if(n>16777216){this.emit("error",new Error(`LRU size cannot be larger than ${Fie} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new y2;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let t of this._store)n+=t.size;return n}get stats(){return this._stats}get storeHashSize(){return this._storeHashSize}set storeHashSize(n){n!==this._storeHashSize&&(this._storeHashSize=n,this._store=Array.from({length:this._storeHashSize},()=>new Map),this._stats.enabled&&this._stats.resetStoreValues())}get storeHashAlgorithm(){return this._storeHashAlgorithm}set storeHashAlgorithm(n){this._storeHashAlgorithm=n}get keys(){let n=[];for(let t of this._store)for(let o of t.keys()){let i=t.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),t.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let t of this._store)for(let o of t.values()){if(this.hasExpired(o)){this.recordExpiration(o),t.delete(o.key),this.lruRemove(o.key);continue}n.push(o)}return n.values()}get store(){return this._store}get(n){this.hookSync("BEFORE_GET",n);let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}this.lruMoveToFront(n);let i;return this._useClone?i=this.clone(o.value):i=o.value,this.recordRead(!0),this.hookSync("AFTER_GET",{key:n,result:i}),i}getMany(n){this.hookSync("BEFORE_GET_MANY",n);let t=[];for(let o of n)t.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:t}),t}getRaw(n){let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let t=[];for(let o of n)t.push(this.getRaw(o));return t}set(n,t,o){let i={key:n,value:t,ttl:o};this.hookSync("BEFORE_SET",i);let e=this.getStore(i.key),a,A=i.ttl;if(A!==void 0||this._ttl!==void 0)if(typeof A=="object"){if(A.expire&&(a=typeof A.expire=="number"?A.expire:A.expire.getTime()),A.ttl){let s=Nl(A.ttl);s!==void 0&&(a=s)}}else{let s=Nl(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=Nl(this._maxTtl);(a===void 0||a>s)&&(a=s)}if(this._lruSize>0){if(e.has(i.key))this.lruMoveToFront(i.key);else if(this.lruAddToFront(i.key),this._lru.size>this._lruSize){let s=this._lru.getOldest();s&&(this._lru.removeOldest(),this.delete(s))}}if(this._stats.enabled){let s=e.get(i.key);s?this._stats.decreaseVSize(s.value):(this._stats.incrementKSize(i.key),this._stats.incrementCount()),this._stats.incrementVSize(i.value),this._stats.incrementSets()}let r={key:i.key,value:i.value,expires:a};e.set(i.key,r),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let t of n)this.set(t.key,t.value,t.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let t=[];for(let o of n){let i=this.get(o);t.push(!!i)}return t}take(n){let t=this.get(n);if(t)return this.delete(n),t}takeMany(n){let t=[];for(let o of n)t.push(this.take(o));return t}delete(n){this.hookSync("BEFORE_DELETE",n);let t=this.getStore(n);if(this._stats.enabled){let o=t.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}t.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let t of n)this.delete(t);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new y2,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let t=this.getKeyStoreHash(n);return this._store[t]||=new Map,this._store[t]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):Gie(n,{min:0,max:this._storeHashSize-1,algorithm:this._storeHashAlgorithm})}clone(n){return this.isPrimitive(n)?n:structuredClone(n)}lruAddToFront(n){this._lruSize!==0&&this._lru.addToFront(n)}lruMoveToFront(n){this._lruSize!==0&&this._lru.moveToFront(n)}lruRemove(n){this._lruSize!==0&&this._lru.remove(n)}lruResize(){for(;this._lru.size>this._lruSize;){let n=this._lru.getOldest();n&&(this._lru.removeOldest(),this.delete(n))}}checkExpiration(){for(let n of this._store)for(let t of n.values())t.expires&&Date.now()>t.expires&&(this.recordExpiration(t),n.delete(t.key),this.lruRemove(t.key))}startIntervalCheck(){if(this._checkInterval>0){this._interval&&clearInterval(this._interval),this._interval=setInterval(()=>{this.checkExpiration()},this._checkInterval).unref()}}stopIntervalCheck(){this._interval&&clearInterval(this._interval),this._interval=0,this._checkInterval=0}wrap(n,t){return f2(n,{ttl:t?.ttl??this._ttl,keyPrefix:t?.keyPrefix,createKey:t?.createKey,cache:this})}getOrSet(n,t,o){return Q2(n,t,{cache:this,ttl:o?.ttl??this._ttl,cacheErrors:o?.cacheErrors,throwErrors:o?.throwErrors})}recordRead(n){this._stats.enabled&&(n?this._stats.incrementHits():this._stats.incrementMisses(),this._stats.incrementGets())}recordExpiration(n){this._stats.enabled&&(this._stats.decreaseKSize(n.key),this._stats.decreaseVSize(n.value),this._stats.decreaseCount())}isPrimitive(n){return n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}setTtl(n){typeof n=="string"||n===void 0?this._ttl=n:n>0?this._ttl=n:this._ttl=void 0}setMaxTtl(n){typeof n=="string"||n===void 0?this._maxTtl=n:n>0?this._maxTtl=n:this._maxTtl=void 0}hasExpired(n){return!!(n.expires&&Date.now()>n.expires)}};var hJe=class extends Zc{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new Xc({enabled:!0});_cacheable=new m2;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,t,o=0){if(typeof n!="string"&&typeof n!="number")throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`",n);if(o&&typeof o!="number"&&typeof o!="string")throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.",this.formatKey(n));let i=this.formatKey(n),e=0;this.options.stdTTL&&(e=this.getExpirationTimestamp(this.options.stdTTL)),o&&(e=this.getExpirationTimestamp(o));let a=0;if(e&&e>0&&(a=e),this.options.maxKeys){let{maxKeys:A}=this.options;if(A>-1&&this.store.size>=A)throw this.createError("Cache max keys amount exceeded",this.formatKey(n))}return this.store.set(i,{key:i,value:t,ttl:a}),this.emit("set",i,t,e),this._stats.incrementKSize(i),this._stats.incrementVSize(t),this._stats.setCount(this.store.size),!0}mset(n){if(!Array.isArray(n))throw this.createError("The keys argument has to be an array.");for(let t of n)this.set(t.key,t.value,t.ttl);return!0}get(n){let t=this.store.get(this.formatKey(n));if(t){if(t.ttl>0){if(t.ttl0){let n=this.options.checkperiod*1e3;this.intervalId=setInterval(()=>{this.checkData()},n).unref();return}this.intervalId=0}stopInterval(){this.intervalId!==0&&(clearInterval(this.intervalId),this.intervalId=0)}formatKey(n){return n.toString()}getExpirationTimestamp(n){if(typeof n=="string")return Nl(n);let t=Date.now(),o=n*1e3;return t+o}checkData(){for(let[n,t]of this.store.entries())t.ttl>0&&t.ttl{let a={resolve:i,reject:e,weight:t,priority:o},A=Uie(this._queue,r=>o<=r.priority);A===-1&&t<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(t){return CJe(this,arguments,void 0,function*(o,i=1,e=0){let[a,A]=yield this.acquire(i,e);try{return yield o(a)}finally{A()}})}waitForUnlock(t=1,o=0){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return this._couldLockImmediately(t,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),uJe(this._weightedWaiters[t-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatchQueue()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatchQueue()}cancel(){this._queue.forEach(t=>t.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(t){let o=this._value;this._value-=t.weight,t.resolve([o,this._newReleaser(t.weight)])}_newReleaser(t){let o=!1;return()=>{o||(o=!0,this.release(t))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let t=this._value;t>0;t--){let o=this._weightedWaiters[t-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[t-1]=[])}else{let t=this._queue[0].priority;for(let o=this._value;o>0;o--){let i=this._weightedWaiters[o-1];if(!i)continue;let e=i.findIndex(a=>a.priority<=t);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(t,o){return(this._queue.length===0||this._queue[0].priorityt.priority<=i.priority);n.splice(o+1,0,t)}function Uie(n,t){for(let o=n.length-1;o>=0;o--)if(t(n[o]))return o;return-1}var BJe=function(n,t,o,i){function e(a){return a instanceof o?a:new o(function(A){A(a)})}return new(o||(o=Promise))(function(a,A){function r(c){try{g(i.next(c))}catch(I){A(I)}}function s(c){try{g(i.throw(c))}catch(I){A(I)}}function g(c){c.done?a(c.value):e(c.value).then(r,s)}g((i=i.apply(n,t||[])).next())})},kg=class{constructor(t){this._semaphore=new S2(1,t)}acquire(){return BJe(this,arguments,void 0,function*(t=0){let[,o]=yield this._semaphore.acquire(1,t);return o})}runExclusive(t,o=0){return this._semaphore.runExclusive(()=>t(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(t=0){return this._semaphore.waitForUnlock(1,t)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as SJe}from"crypto";var w2=qe(Kie(),1);var O2=class n extends Error{name="TimeoutError";constructor(t,o){super(t,o),Error.captureStackTrace?.(this,n)}},xie=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function b2(n,t){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=t,r,s,c=new Promise((I,d)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){d(xie(A));return}if(A&&(s=()=>{d(xie(A))},A.addEventListener("abort",s,{once:!0})),n.then(I,d),o===Number.POSITIVE_INFINITY)return;let B=new O2;r=a.setTimeout.call(void 0,()=>{if(i){try{I(i())}catch(f){d(f)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?I():e instanceof Error?d(e):(B.message=e??`Promise timed out after ${o} milliseconds`,d(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,r),r=void 0},c}function M2(n,t,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],t)<=0?(i=++A,e-=a+1):e=a}return i}var yJe=100,Nh=class{#e=[];#A=0;enqueue(t,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:t};if(a===0){this.#e.length=0,this.#A=0,this.#e.push(A);return}if(this.#e.at(-1).priority>=i){this.#e.push(A);return}this.#t();let r=M2(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(r,0,A)}setPriority(t,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===t);if(i===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:t})}remove(t){let o=this.#e.findIndex((i,e)=>eyJe&&this.#A>this.#e.length/2&&this.#t(),t?.run}filter(t){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);if(t.strict&&t.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(t.strict&&t.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=t.carryoverIntervalCount??t.carryoverConcurrencyCount??!1,this.#A=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#r=t.intervalCap,this.#c=t.interval,this.#n=t.strict,this.#p=new t.queueClass,this.#d=t.queueClass,this.concurrency=t.concurrency,t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);this.timeout=t.timeout,this.#B=t.autoStart===!1,this.#Y()}#y(t){for(;this.#l=this.#c)this.#l++;else break}(this.#l>100&&this.#l>this.#g.length/2||this.#l===this.#g.length)&&(this.#g=this.#g.slice(this.#l),this.#l=0)}#Q(t){this.#n?this.#g.push(t):this.#t++}#C(){this.#n?this.#g.length>this.#l&&this.#g.pop():this.#t>0&&this.#t--}#M(){return this.#g.length-this.#l}get#b(){return this.#A?!0:this.#n?this.#M()=this.#r){let i=this.#g[this.#l],e=this.#c-(t-i);return this.#k(e),!0}return!1}if(this.#I===void 0){let o=this.#s-t;if(o<0)this.#t=this.#e?this.#h:0;else return this.#k(o),!0}return!1}#k(t){this.#o===void 0&&(this.#o=setTimeout(()=>{this.#_()},t))}#T(){this.#I&&(clearInterval(this.#I),this.#I=void 0)}#v(){this.#o&&(clearTimeout(this.#o),this.#o=void 0)}#N(){if(this.#p.size===0){if(this.#T(),this.emit("empty"),this.#h===0){if(this.#v(),this.#n&&this.#l>0){let o=Date.now();this.#y(o)}this.emit("idle")}return!1}let t=!1;if(!this.#B){let o=Date.now(),i=!this.#R(o);if(this.#b&&this.#w){let e=this.#p.dequeue();this.#A||(this.#Q(o),this.#K()),i&&this.#F(),this.emit("active"),e(),t=!0}}return t}#F(){this.#A||this.#I!==void 0||this.#n||(this.#I=setInterval(()=>{this.#O()},this.#c),this.#s=Date.now()+this.#c)}#O(){this.#n||(this.#I!==void 0&&(this.#t===0&&this.#h===0?this.#T():this.#s=Date.now()+this.#c),this.#t=this.#e?this.#h:0),this.#U(),this.#K()}#U(){for(;this.#N(););}get concurrency(){return this.#E}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#E=t,this.#U()}setPriority(t,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#p.setPriority(t,o)}async add(t,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#u++).toString()},o.timeout!==void 0&&!(Number.isFinite(o.timeout)&&o.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${o.timeout}\` (${typeof o.timeout})`);return new Promise((i,e)=>{let a=Symbol(`task-${o.id}`),A=()=>{},r=async()=>{A(),this.#h++,this.#f.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(d){throw this.#J(),this.#f.delete(a),d}let c=t({signal:o.signal});if(o.timeout!==void 0&&(c=b2(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#h} running, ${this.#p.size} waiting)`})),o.signal){let{signal:d}=o;c=Promise.race([c,new Promise((B,f)=>{g=()=>{f(d.reason)},d.addEventListener("abort",g,{once:!0})})])}let I=await c;i(I),this.emit("completed",I)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#f.delete(a),queueMicrotask(()=>{this.#S()})}};this.#p.enqueue(r,o);let s=()=>{if(this.#p instanceof Nh){this.#p.remove(r);return}this.#p.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#N(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#m.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#m.add(A)}this.emit("add"),this.#N()})}async addAll(t,o){return Promise.all(t.map(async i=>this.add(i,o)))}start(){return this.#B?(this.#B=!1,this.#U(),this):this}pause(){this.#B=!0}clear(){for(let t of this.#m)t();this.#p=new this.#d,this.#T(),this.#P(),this.emit("empty"),this.#h===0&&(this.#v(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#p.size!==0&&await this.#L("empty")}async onSizeLessThan(t){this.#p.sizethis.#p.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#L(t,o){let i=Array.isArray(t)?t:[t];return new Promise(e=>{let a=()=>{if(!(o&&!o())){for(let A of i)this.off(A,a);e()}};for(let A of i)this.on(A,a)})}get size(){return this.#p.size}sizeBy(t){return this.#p.filter(t).length}get pending(){return this.#h}get isPaused(){return this.#B}#Y(){this.#A||(this.on("add",()=>{this.#p.size>0&&this.#K()}),this.on("next",()=>{this.#K()}))}#K(){this.#A||this.#i||(this.#i=!0,queueMicrotask(()=>{this.#i=!1,this.#P()}))}#J(){this.#A||(this.#C(),this.#K())}#P(){let t=this.#a;if(this.#A||this.#p.size===0){t&&(this.#a=!1,this.emit("rateLimitCleared"));return}let o;if(this.#n){let e=Date.now();this.#y(e),o=this.#M()}else o=this.#t;let i=o>=this.#r;i!==t&&(this.#a=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#a}get isSaturated(){return this.#h===this.#E&&this.#p.size>0||this.isRateLimited&&this.#p.size>0}get runningTasks(){return[...this.#f.values()].map(t=>({...t,timeoutRemaining:t.timeout?Math.max(0,t.startTime+t.timeout-Date.now()):void 0}))}};var vO=class{constructor(t,o){this.store=t,this.logger=o,this.queues=new Map}getQueue(t){return this.queues.has(t)||this.queues.set(t,new Rl({concurrency:1})),this.queues.get(t)}async processOperations(t,o,i,e,a){let A=t[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let r=[],s={};for(let g in A)A[g]===null?r.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),r.length>0&&await this.processDeletions(o,r,i,e,a)})}async processDeletions(t,o,i,e,a){if(a)for(let A of o)i[t]?.[A]?(i[t][A]=null,e[t][A]=null):this.logger.warn(`Skipping deletion of non-existent ${t} in transaction: ${A}`);else{let A=await this.store.get(t,o);for(let r of o)A[r]?(i[t][r]=null,e[t][r]=null):this.logger.warn(`Skipping deletion of non-existent ${t}: ${r}`)}}async validateDeletions(t,o){let i=t[o];if(i)return this.getQueue(o).add(async()=>{let e=Object.keys(i).filter(A=>i[A]===null);if(e.length===0)return;let a=await this.store.get(o,e);for(let A of e)a[A]||(this.logger.warn(`Skipping deletion of non-existent ${o}: ${A}`),delete t[o][A])})}};var jie=(n,t,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new mJe,a=new Map,A=new Map,r=new Map,s=new vO(n,t);function g(Q){return a.has(Q)||a.set(Q,new Rl({concurrency:1})),a.get(Q)}function c(Q){return A.has(Q)||(A.set(Q,new kg),r.set(Q,0)),A.get(Q)}function I(Q){let y=r.get(Q)??0;r.set(Q,y+1)}function d(Q){let y=(r.get(Q)??1)-1;if(r.set(Q,y),y<=0){let m=A.get(Q);m&&!m.isLocked()&&(A.delete(Q),r.delete(Q))}}function B(){return!!e.getStore()}async function f(Q){if(Object.keys(Q).length===0){t.trace("no mutations in transaction");return}t.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(Q,y);let _=m.cache[Q]||{},T=y.filter(H=>!(H in _));if(T.length>0){m.dbQueries++,t.trace({type:Q,count:T.length},"fetching missing keys in transaction");let H=await c(Q).runExclusive(()=>n.get(Q,T));m.cache[Q]=m.cache[Q]||{},Object.assign(m.cache[Q],H)}let R={};for(let H of y){let j=m.cache[Q]?.[H];j!=null&&(R[H]=j)}return R},set:async Q=>{let y=e.getStore();if(!y){let m=Object.keys(Q);for(let _ of m){let T=_;T==="pre-key"&&await s.validateDeletions(Q,T)}await Promise.all(m.map(_=>g(_).add(async()=>{let T={[_]:Q[_]};await n.set(T)})));return}t.trace({types:Object.keys(Q)},"caching in transaction");for(let m in Q){let _=m;y.cache[_]=y.cache[_]||{},y.mutations[_]=y.mutations[_]||{},_==="pre-key"?await s.processOperations(Q,_,y.cache,y.mutations,!0):(Object.assign(y.cache[_],Q[_]),Object.assign(y.mutations[_],Q[_]))}},isInTransaction:B,transaction:async(Q,y)=>{if(e.getStore())return t.trace("reusing existing transaction context"),Q();let _=c(y);I(y);try{return await _.runExclusive(async()=>{let T={cache:{},mutations:{},dbQueries:0};t.trace("entering transaction");try{let R=await e.run(T,Q);return await f(T.mutations),t.trace({dbQueries:T.dbQueries},"transaction completed"),R}catch(R){throw t.error({error:R},"transaction failed, rolling back"),R}})}finally{d(y)}}}},Jie=n=>{let t=n.me?.id;if(!t)throw new Yie.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return t},qie=()=>{let n=ur.generateKeyPair();return{noiseKey:ur.generateKeyPair(),pairingEphemeralKeyPair:ur.generateKeyPair(),signedIdentityKey:n,signedPreKey:QD(n,1),registrationId:J9(),advSecretKey:SJe(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},registered:!1,pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0,additionalData:void 0}};import{mkdir as DJe,readFile as wJe,stat as OJe,unlink as bJe,writeFile as MJe}from"fs/promises";import{join as _2}from"path";var zie=new Map,T2=n=>{let t=zie.get(n);return t||(t=new kg,zie.set(n,t)),t},Vie=async n=>{let t=async(r,s)=>{let g=_2(n,a(s));return T2(g).acquire().then(async I=>{try{await MJe(g,JSON.stringify(r,qu.replacer))}finally{I()}})},o=async r=>{try{let s=_2(n,a(r));return await T2(s).acquire().then(async c=>{try{let I=await wJe(s,{encoding:"utf-8"});return JSON.parse(I,qu.reviver)}finally{c()}})}catch{return null}},i=async r=>{try{let s=_2(n,a(r));return T2(s).acquire().then(async c=>{try{await bJe(s)}catch{}finally{c()}})}catch{}},e=await OJe(n).catch(()=>{});if(e){if(!e.isDirectory())throw new Error(`found something that is not a directory at ${n}, either delete it or specify a different location`)}else await DJe(n,{recursive:!0});let a=r=>r?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||qie();return{state:{creds:A,keys:{get:async(r,s)=>{let g={};return await Promise.all(s.map(async c=>{let I=await o(`${r}-${c}.json`);r==="app-state-sync-key"&&I&&(I=oe.Message.AppStateSyncKeyData.fromObject(I)),g[c]=I})),g},set:async r=>{let s=[];for(let g in r)for(let c in r[g]){let I=r[g][c],d=`${g}-${c}.json`;s.push(I?t(I,d):i(d))}await Promise.all(s)}}},saveCreds:async()=>t(A,"creds.json")}};var _Je=192,TJe=async(n,{thumbnailWidth:t,fetchOpts:o})=>{let i=await wO(n,o);return await WL(i,t)},Wie=async(n,t={thumbnailWidth:_Je,fetchOpts:{timeout:3e3}})=>{try{let o=0,i=5,{getLinkPreview:e}=await import("link-preview-js"),a=n;!n.startsWith("https://")&&!n.startsWith("http://")&&(a="https://"+a);let A=await e(a,{...t.fetchOpts,followRedirects:"follow",handleRedirects:(r,s)=>{let g=new URL(r),c=new URL(s);return o>=i?!1:c.hostname===g.hostname||c.hostname==="www."+g.hostname||"www."+c.hostname===g.hostname?(o+=1,!0):!1},headers:t.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[r]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:r};if(t.uploadImage){let{imageMessage:g}=await xB({image:{url:r}},{upload:t.uploadImage,mediaTypeOverride:"thumbnail-link",options:t.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=r?(await TJe(r,t)).buffer:void 0}catch(g){t.logger?.debug({err:g.stack,url:a},"error in generating thumbnail")}return s}}catch(o){if(!o.message.includes("receive a valid"))throw o}};import HJe from"events";var R2=qe(Gr(),1);var NJe=/^1313555\d{4}$|^131655500\d{2}$/;function RJe(n){if(!n)return!1;let t=n.split("@")[0]??"";return t==="0"||NJe.test(t)||Nd(n)?!1:!!(bt(n)||qA(n)||Cr(n)||oa(n)||n.endsWith("@c.us"))}var PO=604800,kJe=4,eI="__index";async function GO(n){let o=(await n.get("tctoken",[eI]))[eI];if(!o?.token?.length)return[];try{let i=JSON.parse(Buffer.from(o.token).toString());return Array.isArray(i)?i.filter(e=>typeof e=="string"&&e.length>0&&e!==eI):[]}catch{return[]}}async function Rh(n,t){let o=await GO(n),i=new Set(o);for(let e of t)e&&e!==eI&&i.add(e);return{[eI]:{token:Buffer.from(JSON.stringify([...i]))}}}function kl(n){if(n==null)return!0;let t=typeof n=="string"?parseInt(n):n;if(isNaN(t))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/PO)-(kJe-1))*PO;return ti}async function ks(n,t){return qA(n)?n:await t(n)??n}async function XB(n,t,o,i){return t?qA(n)?n:await o(n)??n:qA(n)&&i?await i(n)??n:n}async function N2({authState:n,jid:t,baseContent:o=[],getLIDForPN:i}){try{let e=await ks(t,i),A=(await n.keys.get("tctoken",[e]))?.[e],r=A?.token,s=A?.timestamp;if(!r?.length||s===void 0||kl(s)){if(r){let g=A?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:A.senderTimestamp}:null;await n.keys.set({tctoken:{[e]:g}})}return o.length>0?o:void 0}return o.push({tag:"tctoken",attrs:{t:String(s)},content:r}),o}catch{return o.length>0?o:void 0}}async function kh({result:n,fallbackJid:t,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=Ie(n,"tokens");if(!a)return;let A=PA(a,"token");for(let r of A){if(r.attrs.type!=="trusted_contact"||!(r.content instanceof Uint8Array))continue;let s=uA(t||r.attrs.jid);if(!RJe(s))continue;let g=await ks(s,i),I=(await o.get("tctoken",[g]))[g],d=I?.timestamp?Number(I.timestamp):0,B=r.attrs.t?Number(r.attrs.t):0;B&&(d>0&&d>B||(await o.set({tctoken:{[g]:{...I,token:Buffer.from(r.content),timestamp:r.attrs.t}}}),e?.(g)))}}var vJe=new Set([RA.CALL_MISSED_GROUP_VIDEO,RA.CALL_MISSED_GROUP_VOICE,RA.CALL_MISSED_VIDEO,RA.CALL_MISSED_VOICE]),PJe=new Set([RA.GROUP_PARTICIPANT_ADD]);async function GJe(n,t,o,i){let e=t.lidMapping.getLIDForPN.bind(t.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?Lr(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let I=uA(g.id),d=await ks(I,e);a.push({storageJid:d,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?Lr(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),r=await o.get("tctoken",A),s={};for(let g of a){let c=r[g.storageJid],I=c?.timestamp?Number(c.timestamp):0;I>0&&I>=g.ts||(s[g.storageJid]={...c,token:g.token,timestamp:String(g.ts),...g.senderTs!==void 0?{senderTimestamp:g.senderTs}:{}})}if(Object.keys(s).length){i?.debug({count:Object.keys(s).length},"storing tctokens from history sync");try{let g=await Rh(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Xie=(n,t,o)=>{Cr(n.key.remoteJid)||oa(n.key.remoteJid)?n.key.remoteJid=Er(yA(n.key?.remoteJid)?.user,Cr(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=uA(n.key.remoteJid),Cr(n.key.participant)||oa(n.key.participant)?n.key.participant=Er(yA(n.key.participant)?.user,Cr(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=uA(n.key.participant);let i=Sa(n.message);i?.reactionMessage&&e(i.reactionMessage.key),i?.pollUpdateMessage&&e(i.pollUpdateMessage.pollCreationMessageKey);function e(a){n.key.fromMe||(a.fromMe=a.fromMe?!1:Mt(a.participant||a.remoteJid,t)||Mt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},k2=n=>{let t=Sa(n.message),o=!!YB(t);return(!!t||vJe.has(n.messageStubType)||PJe.has(n.messageStubType))&&o&&!t?.protocolMessage&&!t?.reactionMessage&&!t?.pollUpdateMessage},v2=n=>!n.key.fromMe&&!n.messageStubType,FJe=({remoteJid:n,participant:t,fromMe:o})=>{if(!n)throw new R2.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:t,fromMe:o}});if(Fu(n)&&!Bg(n)&&!o){if(!t)throw new R2.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return t}return n};function LJe({encPayload:n,encIv:t},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([I(i),I(o),I(a),I("Event Response"),new Uint8Array([1])]),r=mn(e,new Uint8Array(32),"sha256"),s=mn(A,r,"sha256"),g=I(`${i}\0${a}`),c=sl(n,s,t,g);return oe.Message.EventResponseMessage.decode(c);function I(d){return Buffer.from(d)}}var UJe=async(n,{shouldProcessHistoryMsg:t,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:r,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:I}=e,d={id:uA(FJe(n.key))},B=k2(n);B&&(d.messages=[{message:n}],d.conversationTimestamp=Lr(n.messageTimestamp),v2(n)&&(d.unreadCount=(d.unreadCount||0)+1));let f=Sa(n.message);(B||f?.reactionMessage?.key?.fromMe)&&I?.unarchiveChats&&(d.archived=!1,d.readOnly=!1);let Q=f?.protocolMessage;if(Q){let y=new Set([oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(Q.type!==null&&Q.type!==void 0&&y.has(Q.type)&&!n.key.fromMe){r?.warn({msgId:n.key.id,type:Q.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(Q.type){case oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=Q.historySyncNotification,_=t,T=!e.processedHistoryMessages?.length;if(r?.info({histNotification:m,process:_,id:n.key.id,isLatest:T},"got history notification"),_){m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let P=await Qie(m,s,r);P.lidPnMappings?.length&&(r?.debug({count:P.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(P.lidPnMappings).catch(z=>r?.warn({err:z},"failed to store LID-PN mappings from history sync"))),await GJe(P.chats,a,A,r),i.emit("messaging-history.set",{...P,isLatest:m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND?T:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let R=Q.appStateSyncKeyShare.keys;if(R?.length){let P="";await A.transaction(async()=>{let z=[];for(let{keyData:U,keyId:N}of R){let k=Buffer.from(N.keyId).toString("base64");z.push(k),await A.set({"app-state-sync-key":{[k]:U}}),P=k}r?.info({newAppStateSyncKeyId:P,newKeys:z},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:P})}else r?.info({protocolMsg:Q},"recv app state sync with 0 keys");break;case oe.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:Q.key.id},update:{message:null,messageStubType:RA.REVOKE,key:n.key}}]);break;case oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(d,{ephemeralSettingTimestamp:Lr(n.messageTimestamp),ephemeralExpiration:Q.ephemeralExpiration||null});break;case oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let H=Q.peerDataOperationRequestResponseMessage;if(H){let P=H.peerDataOperationResult||[];for(let z of P){let U=z?.placeholderMessageResendResponse;if(U?.webMessageInfoBytes)try{let N=oe.WebMessageInfo.decode(U.webMessageInfoBytes),k=N.key?.id,V=k?await o?.get(k):void 0;k&&await o?.del(k);let ee;V&&typeof V=="object"?(V.message=N.message,N.messageTimestamp&&(V.messageTimestamp=N.messageTimestamp),ee=V):ee=N,r?.debug({msgId:k,requestId:H.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[ee],type:"notify",requestId:H.stanzaId})}catch(N){r?.warn({err:N,stanzaId:H.stanzaId},"failed to decode placeholder resend response")}}}break;case oe.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:Q.key?.id},update:{message:{editedMessage:{message:Q.editedMessage}},messageTimestamp:Q.timestampMs?Math.floor(Lr(Q.timestampMs)/1e3):n.messageTimestamp}}]);break;case oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let j=Q.memberLabel;j?.label&&i.emit("group.member-tag.update",{groupId:d.id,label:j.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let F=Q.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:J}=oe.LIDMigrationMappingSyncPayload.decode(F);r?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:J},"got lid mappings and chat db migration timestamp");let x=[];for(let{pn:P,latestLid:z,assignedLid:U}of q){let N=z||U;x.push({lid:`${N}@lid`,pn:`${P}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(x),x.length)for(let{pn:P,lid:z}of x)await a.migrateSession(P,z)}}else if(f?.reactionMessage){let y={...f.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:f.reactionMessage?.key}])}else if(f?.encEventResponseMessage){let y=f.encEventResponseMessage,m=y.eventCreationMessageKey,_=await g(m);if(_)try{let T=uA(c),R=m.participant||m.remoteJid,H=qA(R)?await a.lidMapping.getPNForLID(R):R,j=Fd({remoteJid:uA(H),fromMe:T===H},T),F=Fd(n.key,T),q=_?.messageContextInfo?.messageSecret;if(!q)r?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let J=LJe(y,{eventEncKey:q,eventCreatorJid:j,eventMsgId:m.id,responderJid:F}),x={eventResponseMessageKey:n.key,senderTimestampMs:J.timestampMs,response:J};i.emit("messages.update",[{key:m,update:{eventResponses:[x]}}])}}catch(T){r?.warn({err:T,creationMsgKey:m},"failed to decrypt event response")}else r?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,_=j=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:j}),T=j=>{i.emit("groups.update",[{id:y,...j,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},R=(j,F,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:j.lid,participantPn:j.pn,action:F,method:q})},H=()=>m.find(j=>Mt(c,j.phoneNumber));switch(n.messageStubType){case RA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("modify");break;case RA.GROUP_PARTICIPANT_LEAVE:case RA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("remove"),H()&&(d.readOnly=!0);break;case RA.GROUP_PARTICIPANT_ADD:case RA.GROUP_PARTICIPANT_INVITE:case RA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],H()&&(d.readOnly=!1),_("add");break;case RA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("demote");break;case RA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("promote");break;case RA.GROUP_CHANGE_ANNOUNCE:let j=n.messageStubParameters?.[0];T({announce:j==="true"||j==="on"});break;case RA.GROUP_CHANGE_RESTRICT:let F=n.messageStubParameters?.[0];T({restrict:F==="true"||F==="on"});break;case RA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];d.name=q,T({subject:q});break;case RA.GROUP_CHANGE_DESCRIPTION:let J=n.messageStubParameters?.[0];d.description=J,T({desc:J});break;case RA.GROUP_CHANGE_INVITE_LINK:let x=n.messageStubParameters?.[0];T({inviteCode:x});break;case RA.GROUP_MEMBER_ADD_MODE:let P=n.messageStubParameters?.[0];T({memberAddMode:P==="all_member_add"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let z=n.messageStubParameters?.[0];T({joinApprovalMode:z==="on"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let U=JSON.parse(n.messageStubParameters?.[0]),N=n.messageStubParameters?.[1],k=n.messageStubParameters?.[2];R(U,N,k);break}}Object.keys(d).length>1&&i.emit("chats.update",[d])},$ie=UJe;var KJe=["messaging-history.set","chats.upsert","chats.update","chats.delete","contacts.upsert","contacts.update","messages.upsert","messages.update","messages.delete","messages.reaction","message-receipt.update","groups.update"],xJe=new Set(KJe),eoe=n=>{let t=new HJe,o=new Set,i=P2(),e=!1,a=null,A=null,r=0,s=1e4,g=3e4;t.on("event",d=>{for(let B in d)t.emit(B,d[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,r=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),I())},g)),r++}function I(){if(!e)return!1;n.debug({bufferCount:r},"Flushing event buffer"),e=!1,r=0,a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.size>s&&(n.debug({cacheSize:o.size},"Clearing history cache"),o.clear());let d=P2(),B=Object.values(i.chatUpdates),f=0;for(let y of B)y.conditional&&(f+=1,d.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let Q=jJe(i);return Object.keys(Q).length&&t.emit("event",Q),i=d,n.trace({conditionalChatUpdatesLeft:f},"released buffered events"),!0}return{process(d){let B=async f=>{await d(f)};return t.on("event",B),()=>{t.off("event",B)}},emit(d,B){if(d==="messages.upsert"){let{type:f}=B,Q=Object.values(i.messageUpserts);if(Q.length>0){let y=Q[0].type;y!==f&&(n.debug({bufferedType:y,newType:f},"messages.upsert type mismatch, emitting buffered messages"),t.emit("event",{"messages.upsert":{messages:Q.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&xJe.has(d)?(YJe(i,o,d,B,n),!0):t.emit("event",{[d]:B})},isBuffering(){return e},buffer:c,flush:I,createBufferedFunction(d){return async(...B)=>{c();try{let f=await d(...B);return r===1&&setTimeout(()=>{e&&r===1&&I()},100),f}catch(f){throw f}finally{r=Math.max(0,r-1),r===0&&(A||(A=setTimeout(I,100)))}}},on:(...d)=>t.on(...d),off:(...d)=>t.off(...d),removeAllListeners:(...d)=>t.removeAllListeners(...d),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=P2(),e=!1,r=0,t.removeAllListeners(),n.debug("Event buffer destroyed")}}},P2=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function YJe(n,t,o,i,e){switch(o){case"messaging-history.set":for(let Q of i.chats){let y=Q.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=Q.endOfHistoryTransferType),!m&&!t.has(y)&&(n.historySets.chats[y]=Q,t.add(y),a(Q))}for(let Q of i.contacts){let y=n.historySets.contacts[Q.id];if(y)Object.assign(y,SD(Q));else{let m=`c:${Q.id}`,_=Q.notify||Q.name||Q.verifiedName;(!t.has(m)||_)&&(n.historySets.contacts[Q.id]=Q,t.add(m))}}for(let Q of i.messages){let y=vh(Q.key);!n.historySets.messages[y]&&!t.has(y)&&(n.historySets.messages[y]=Q,t.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let Q=new Map,y=_=>`${_.userJid||""}:${_.leaveTs||""}:${_.leaveReason||""}`,m=_=>{let T=_.groupJid??JSON.stringify(_),R=Q.get(T);if(!R){Q.set(T,{..._,pastParticipants:[..._.pastParticipants||[]]});return}let H=new Set((R.pastParticipants||[]).map(y));for(let j of _.pastParticipants||[]){let F=y(j);H.has(F)||(R.pastParticipants.push(j),H.add(F))}};for(let _ of n.historySets.pastParticipants||[])m(_);for(let _ of i.pastParticipants)m(_);n.historySets.pastParticipants=[...Q.values()]}n.historySets.progress=i.progress,n.historySets.chunkOrder=i.chunkOrder,n.historySets.peerDataRequestSessionId=i.peerDataRequestSessionId,n.historySets.isLatest=i.isLatest||n.historySets.isLatest;break;case"chats.upsert":for(let Q of i){let y=Q.id||"",m=n.chatUpserts[y];y&&!m&&(m=n.historySets.chats[y],m&&e.debug({chatId:y},"absorbed chat upsert in chat set")),m?m=FO(m,Q):(m=Q,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let Q of i){let y=Q.id,m=Q.conditional?Q.conditional(n):!0;if(m){delete Q.conditional;let _=n.historySets.chats[y]||n.chatUpserts[y];if(_)FO(_,Q);else{let T=n.chatUpdates[y]||{};n.chatUpdates[y]=FO(T,Q)}}else m===void 0&&(n.chatUpdates[y]=Q);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let Q of i)n.chatDeletes.has(Q)||n.chatDeletes.add(Q),n.chatUpdates[Q]&&delete n.chatUpdates[Q],n.chatUpserts[Q]&&delete n.chatUpserts[Q],n.historySets.chats[Q]&&delete n.historySets.chats[Q];break;case"contacts.upsert":for(let Q of i){let y=n.contactUpserts[Q.id];y||(y=n.historySets.contacts[Q.id],y&&e.debug({contactId:Q.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,SD(Q)):(y=Q,n.contactUpserts[Q.id]=y),n.contactUpdates[Q.id]&&(y=Object.assign(n.contactUpdates[Q.id],SD(Q)),delete n.contactUpdates[Q.id])}break;case"contacts.update":let r=i;for(let Q of r){let y=Q.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,Q);else{let _=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(_,Q)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let Q of s){let y=vh(Q.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(Q.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(Q,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=Q:n.messageUpserts[y]={message:Q,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:Q,update:y}of c){let m=vh(Q),_=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(_)Object.assign(_,y),y.status===Td.READ&&!Q.fromMe&&A(_);else{let T=n.messageUpdates[m]||{key:Q,update:{}};Object.assign(T.update,y),n.messageUpdates[m]=T}}break;case"messages.delete":let I=i;if("keys"in I){let{keys:Q}=I;for(let y of Q){let m=vh(y);n.messageDeletes[m]||(n.messageDeletes[m]=y),n.messageUpserts[m]&&delete n.messageUpserts[m],n.messageUpdates[m]&&delete n.messageUpdates[m]}}break;case"messages.reaction":let d=i;for(let{key:Q,reaction:y}of d){let m=vh(Q),_=n.messageUpserts[m];_?a2(_.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:Q,reactions:[]},a2(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:Q,receipt:y}of B){let m=vh(Q),_=n.messageUpserts[m];_?r2(_.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:Q,userReceipt:[]},r2(n.messageReceipts[m],y))}break;case"groups.update":let f=i;for(let Q of f){let y=Q.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,Q))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(r){let s=r.id||"",g=n.chatUpdates[s];if(g){let c=g.conditional?g.conditional(n):!0;c?(delete g.conditional,e.debug({chatId:s},"absorbed chat update in existing chat"),Object.assign(r,FO(g,r)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(r){let s=r.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];k2(r)&&v2(r)&&typeof g?.unreadCount=="number"&&g.unreadCount>0&&(e.debug({chatId:g.id},"decrementing chat counter"),g.unreadCount-=1,g.unreadCount===0&&delete g.unreadCount)}}function jJe(n){let t={};n.historySets.empty||(t["messaging-history.set"]={chats:Object.values(n.historySets.chats),messages:Object.values(n.historySets.messages),contacts:Object.values(n.historySets.contacts),pastParticipants:n.historySets.pastParticipants,syncType:n.historySets.syncType,progress:n.historySets.progress,isLatest:n.historySets.isLatest,chunkOrder:n.historySets.chunkOrder,peerDataRequestSessionId:n.historySets.peerDataRequestSessionId});let o=Object.values(n.chatUpserts);o.length&&(t["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(t["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(t["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;t["messages.upsert"]={messages:a.map(f=>f.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(t["messages.update"]=A);let r=Object.values(n.messageDeletes);r.length&&(t["messages.delete"]={keys:r});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:f})=>f.flatMap(Q=>({key:B,reaction:Q})));s.length&&(t["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:f})=>f.flatMap(Q=>({key:B,receipt:Q})));g.length&&(t["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(t["contacts.upsert"]=c);let I=Object.values(n.contactUpdates);I.length&&(t["contacts.update"]=I);let d=Object.values(n.groupUpdates);return d.length&&(t["groups.update"]=d),t}function FO(n,t){return t.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,t.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof t.unreadCount=="number"&&(t={...t},t.unreadCount>=0&&(t.unreadCount=Math.max(t.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,t)}var vh=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var JJe=512,G2="\0",Aoe=3600*1e3,qJe=3e3,vg;(function(n){n[n.UnknownError=0]="UnknownError",n[n.SignalErrorNoSession=1]="SignalErrorNoSession",n[n.SignalErrorInvalidKey=2]="SignalErrorInvalidKey",n[n.SignalErrorInvalidKeyId=3]="SignalErrorInvalidKeyId",n[n.SignalErrorInvalidMessage=4]="SignalErrorInvalidMessage",n[n.SignalErrorInvalidSignature=5]="SignalErrorInvalidSignature",n[n.SignalErrorFutureMessage=6]="SignalErrorFutureMessage",n[n.SignalErrorBadMac=7]="SignalErrorBadMac",n[n.SignalErrorInvalidSession=8]="SignalErrorInvalidSession",n[n.SignalErrorInvalidMsgKey=9]="SignalErrorInvalidMsgKey",n[n.BadBroadcastEphemeralSetting=10]="BadBroadcastEphemeralSetting",n[n.UnknownCompanionNoPrekey=11]="UnknownCompanionNoPrekey",n[n.AdvFailure=12]="AdvFailure",n[n.StatusRevokeDelay=13]="StatusRevokeDelay"})(vg||(vg={}));var toe=new Set([vg.SignalErrorInvalidMessage,vg.SignalErrorBadMac]),LO=class{constructor(t,o){this.logger=t,this.recentMessagesMap=new Cg({max:JJe,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(G2);if(a>-1){let A=e.slice(a+G2.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Cg({ttl:Aoe*2,ttlAutopurge:!0}),this.retryCounters=new Cg({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Cg({max:1024,ttl:900*1e3,ttlAutopurge:!0}),this.pendingPhoneRequests={},this.maxMsgRetryCount=5,this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0},this.maxMsgRetryCount=o}addRecentMessage(t,o,i){let e={to:t,id:o},a=this.keyToString(e);this.recentMessagesMap.set(a,{message:i,timestamp:Date.now()}),this.messageKeyIndex.set(o,a),this.logger.debug(`Added message to retry cache: ${t}/${o}`)}getRecentMessage(t,o){let i={to:t,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(t,o,i){if(!o)return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&toe.has(i))return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:t,errorCode:vg[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${vg[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(t);return!a||e-a>Aoe?(this.sessionRecreateHistory.set(t,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(t){if(t===void 0||t==="")return;let o=parseInt(t,10);if(!Number.isNaN(o))return o>=vg.UnknownError&&o<=vg.StatusRevokeDelay?o:vg.UnknownError}isMacError(t){return t!==void 0&&toe.has(t)}incrementRetryCount(t){return this.retryCounters.set(t,(this.retryCounters.get(t)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(t)}getRetryCount(t){return this.retryCounters.get(t)||0}hasExceededMaxRetries(t){return this.getRetryCount(t)>=this.maxMsgRetryCount}markRetrySuccess(t){this.statistics.successfulRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}markRetryFailed(t){this.statistics.failedRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}schedulePhoneRequest(t,o,i=qJe){this.cancelPendingPhoneRequest(t),this.pendingPhoneRequests[t]=setTimeout(()=>{delete this.pendingPhoneRequests[t],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${t} with ${i}ms delay`)}cancelPendingPhoneRequest(t){let o=this.pendingPhoneRequests[t];o&&(clearTimeout(o),delete this.pendingPhoneRequests[t],this.logger.debug(`Cancelled pending phone request for message ${t}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let t of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(t);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(t,o,i){this.baseKeys.set(`${t}:${o}`,i)}hasSameBaseKey(t,o,i){let e=this.baseKeys.get(`${t}:${o}`);if(!e||e.length!==i.length)return!1;for(let a=0;a["Ubuntu",n,"22.04.4"],macOS:n=>["Mac OS",n,"14.4.1"],baileys:n=>["Baileys",n,"6.5.0"],windows:n=>["Windows",n,"10.0.22631"],android:n=>[n,"Android",""],appropriate:n=>[WJe[zJe()]||"Ubuntu",n,VJe()]};var wn;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.CHROME=1]="CHROME",n[n.EDGE=2]="EDGE",n[n.FIREFOX=3]="FIREFOX",n[n.IE=4]="IE",n[n.OPERA=5]="OPERA",n[n.SAFARI=6]="SAFARI",n[n.ELECTRON=7]="ELECTRON",n[n.UWP=8]="UWP",n[n.OTHER_WEB_CLIENT=9]="OTHER_WEB_CLIENT"})(wn||(wn={}));var ZJe={Chrome:wn.CHROME,Edge:wn.EDGE,Firefox:wn.FIREFOX,IE:wn.IE,Opera:wn.OPERA,Safari:wn.SAFARI},XJe=([n,t])=>t==="Desktop"?n==="Windows"?wn.UWP:wn.ELECTRON:ZJe[t]||wn.OTHER_WEB_CLIENT,F2=n=>XJe(n).toString(),roe=(n,t,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,t,o,i,F2(e)].join(",");async function aoe(n,t){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!Ie(n,"identity"))return{action:"no_identity_node"};t.logger.info({jid:o},"identity changed");let e=yA(o);if(e?.device&&e.device!==0)return t.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(t.meId&&(Mt(o,t.meId)||t.meLid&&Mt(o,t.meLid)))return t.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(t.debounceCache.get(o))return t.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};t.debounceCache.set(o,!0);let A=!x9(n.attrs.offline);if(!(await t.validateSession(o)).exists)return t.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(t.logger.debug({jid:o},"old session exists, will refresh session"),A)return t.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};t.onBeforeSessionRefresh?.(o);try{return await t.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return t.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function ioe(n,t,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return t&&(a.attrs.error=t.toString()),e.participant&&(a.attrs.participant=e.participant),e.recipient&&(a.attrs.recipient=e.recipient),e.type&&(a.attrs.type=e.type),i==="message"&&o&&(a.attrs.from=o),a}function $Je(n){return n===null||n===""}function eqe(n){return n>2147483647||n<-2147483648?n&4294967295:n}function ooe(n){let t=0;if(!$Je(n))for(let o=0;oo.iteration===t)}addSenderMessageKey(t){this.senderKeyStateStructure.senderMessageKeys.push({iteration:t.getIteration(),seed:t.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(t){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===t);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new vl(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var Pg=class n{constructor(t){if(this.MAX_STATES=5,this.senderKeyStates=[],t)for(let o of t)this.senderKeyStates.push(new Pl(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(t){return t===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===t)}addSenderKeyState(t,o,i,e){this.senderKeyStates.push(new Pl(t,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(t,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new Pl(t,o,i,e))}serialize(){return this.senderKeyStates.map(t=>t.getStructure())}static deserialize(t){let o=Buffer.from(t).toString("utf-8"),i=JSON.parse(o,qu.reviver);return new n(i)}};var goe=qe(Bc(),1);import*as HO from"crypto";function coe(){return HO.randomBytes(32)}function Ioe(){return HO.randomInt(2147483647)}function loe(n){return n||(n=(0,goe.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var Gl=class{constructor(){this.UNSUPPORTED_VERSION=1,this.CURRENT_VERSION=3,this.WHISPER_TYPE=2,this.PREKEY_TYPE=3,this.SENDERKEY_TYPE=4,this.SENDERKEY_DISTRIBUTION_TYPE=5,this.ENCRYPTED_MESSAGE_OVERHEAD=53}};var Fl=class extends Gl{constructor(t,o,i,e,a){if(super(),a)try{let A=a.slice(1),r=oe.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=r.id,this.iteration=r.iteration,this.chainKey=typeof r.chainKey=="string"?Buffer.from(r.chainKey,"base64"):r.chainKey,this.signatureKey=typeof r.signingKey=="string"?Buffer.from(r.signingKey,"base64"):r.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=t,this.iteration=o,this.chainKey=i,this.signatureKey=e;let r=oe.SenderKeyDistributionMessage.encode(oe.SenderKeyDistributionMessage.create({id:t,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),r])}}intsToByteHighAndLow(t,o){return((t<<4|o)&255)%256}serialize(){return this.serialized}getType(){return this.SENDERKEY_DISTRIBUTION_TYPE}getIteration(){return this.iteration}getChainKey(){return this.chainKey}getSignatureKey(){return this.signatureKey}getId(){return this.id}};var Ph=class{constructor(t){this.senderKeyStore=t}async process(t,o){let i=await this.senderKeyStore.loadSenderKey(t);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(t,i)}async create(t){let o=await this.senderKeyStore.loadSenderKey(t);if(o.isEmpty()){let e=Ioe(),a=coe(),A=loe();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(t,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new Fl(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var xO=qe(rl(),1);var KO=qe(Bc(),1);var Gh=class extends Gl{constructor(t,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],r=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=oe.SenderKeyMessage.decode(r).toJSON();this.serialized=a,this.messageVersion=(A&255)>>4,this.keyId=g.id,this.iteration=g.iteration,this.ciphertext=typeof g.ciphertext=="string"?Buffer.from(g.ciphertext,"base64"):g.ciphertext,this.signature=s}else{let A=((this.CURRENT_VERSION<<4|this.CURRENT_VERSION)&255)%256,r=Buffer.from(i),s=oe.SenderKeyMessage.encode(oe.SenderKeyMessage.create({id:t,iteration:o,ciphertext:r})).finish(),g=this.getSignature(e,Buffer.concat([Buffer.from([A]),s]));this.serialized=Buffer.concat([Buffer.from([A]),s,Buffer.from(g)]),this.messageVersion=this.CURRENT_VERSION,this.keyId=t,this.iteration=o,this.ciphertext=r,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(t){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,KO.verifySignature)(t,o,i))throw new Error("Invalid signature!")}getSignature(t,o){return Buffer.from((0,KO.calculateSignature)(t,o))}serialize(){return this.serialized}getType(){return 4}};var Fh=class{constructor(t,o){this.senderKeyStore=t,this.senderKeyName=o}async encrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for encryption");let i=o.getSenderKeyState();if(!i)throw new Error("No session to encrypt message");let e=i.getSenderChainKey().getIteration(),a=this.getSenderKey(i,e===0?0:e+1),A=await this.getCipherText(a.getIv(),a.getCipherKey(),t),r=new Gh(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),r.serialize()}async decrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new Gh(null,null,null,null,t),e=o.getSenderKeyState(i.getKeyId());if(!e)throw new Error("No session found to decrypt message");i.verifySignature(e.getSigningKeyPublic());let a=this.getSenderKey(e,i.getIteration()),A=await this.getPlainText(a.getIv(),a.getCipherKey(),i.getCipherText());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),A}getSenderKey(t,o){let i=t.getSenderChainKey();if(i.getIteration()>o){if(t.hasSenderMessageKey(o)){let e=t.removeSenderMessageKey(o);if(!e)throw new Error("No sender message key found for iteration");return e}throw new Error(`Received message with old counter: ${i.getIteration()}, ${o}`)}if(o-i.getIteration()>2e3)throw new Error("Over 2000 messages into the future!");for(;i.getIteration()0){let r=[...i];this.logger.trace(`Batch fetching ${r.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",r);for(let g of r){let c=s[g];c&&(e.set(g,c),this.mappingCache.set(`pn:${g}`,c),this.mappingCache.set(`lid:${c}`,g))}}let a={};for(let{pnUser:r,lidUser:s}of o){if(e.get(r)===s){this.logger.debug({pnUser:r,lidUser:s},"LID mapping already exists, skipping");continue}a[r]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[r,s]of Object.entries(a))A[r]=s,A[`${s}_reverse`]=r;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[r,s]of Object.entries(a))this.mappingCache.set(`pn:${r}`,s),this.mappingCache.set(`lid:${s}`,r)}async getLIDForPN(t){return(await this.getLIDsForPNs([t]))?.[0]?.lid||null}async getLIDsForPNs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightLIDLookups.get(i);if(e)return this.logger.trace(`Coalescing getLIDsForPNs request for ${o.length} PNs`),e;let a=this._getLIDsForPNsImpl(t);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(t){let o={},i={},e=[],a=(A,r,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=r.device!==void 0?r.device:0,I=`${g}${c?`:${c}`:""}@${r.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${I} (user mapping with device ${c})`),i[A]={lid:I,pn:A},!0};for(let A of t){if(!bt(A)&&!Cr(A))continue;let r=yA(A);if(!r)continue;let s=r.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,r,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:r})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],r=await this.keys.get("lid-mapping",A);for(let s of A){let g=r[s];g&&typeof g=="string"&&(this.mappingCache.set(`pn:${s}`,g),this.mappingCache.set(`lid:${g}`,s))}for(let{pn:s,pnUser:g,decoded:c}of e){let I=this.mappingCache.get(`pn:${g}`);if(I&&typeof I=="string"){if(!a(s,c,I)){this.logger.warn(`Invalid entry for ${s} (pair not resolved)`);continue}}else{this.logger.trace(`No LID mapping found for PN user ${g}; batch getting from USync`);let d=c.device||0,B=uA(s);Cr(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(d):o[B]=[d]}}}if(Object.keys(o).length>0){let A=await this.pnToLIDFunc?.(Object.keys(o));if(A&&A.length>0){await this.storeLIDPNMappings(A);for(let r of A){let g=yA(r.pn)?.user;if(!g)continue;let c=yA(r.lid)?.user;if(c)for(let I of o[r.pn]){let d=`${c}${I?`:${I}`:""}@${I===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${r.pn} \u2192 ${d} (user mapping with device ${I})`);let B=`${g}${I?`:${I}`:""}@${I===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:d,pn:B}}}}else this.logger.warn("USync fetch yielded no results for pending PNs")}return Object.values(i).length>0?Object.values(i):null}async getPNForLID(t){return(await this.getPNsForLIDs([t]))?.[0]?.pn||null}async getPNsForLIDs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightPNLookups.get(i);if(e)return this.logger.trace(`Coalescing getPNsForLIDs request for ${o.length} LIDs`),e;let a=this._getPNsForLIDsImpl(t);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(t){let o={},i=[],e=(a,A,r)=>{if(!r||typeof r!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${r}:${s}@${A.domainType===xt.HOSTED_LID?"hosted":"s.whatsapp.net"}`;return this.logger.trace(`Found reverse mapping: ${a} \u2192 ${g}`),o[a]={lid:a,pn:g},!0};for(let a of t){if(!qA(a))continue;let A=yA(a);if(!A)continue;let r=A.user,s=this.mappingCache.get(`lid:${r}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:r,decoded:A})}if(i.length){let a=[...new Set(i.map(r=>`${r.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:r,lidUser:s,decoded:g}of i){let c=this.mappingCache.get(`lid:${s}`);(!c||typeof c!="string")&&(c=A[`${s}_reverse`],c&&typeof c=="string"&&(this.mappingCache.set(`lid:${s}`,c),this.mappingCache.set(`pn:${c}`,s))),c&&typeof c=="string"?e(r,g,c):this.logger.trace(`No reverse mapping found for LID user: ${s}`)}}return Object.values(o).length?Object.values(o):null}close(){this.mappingCache.clear()}};function Aqe(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=doe.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function hoe(n,t,o){let i=new YO(n.keys,t,o),e=tqe(n,i),a=n.keys,A=new Cg({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),r=async(g,c)=>{let I=jO(g,c),d=I.toString(),{[d]:B}=await n.keys.get("sender-key",[d]);B||await e.storeSenderKey(I,new Pg);let f=await new Ph(e).create(I);return{senderName:I,skdm:f}};return{decryptGroupMessage({group:g,authorJid:c,msg:I}){let d=jO(g,c),B=new Fh(e,d);return a.transaction(async()=>B.decrypt(I),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let I=new Ph(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let d=jO(g.groupId,c),B=new Fl(null,null,null,null,g.axolotlSenderKeyDistributionMessage),f=d.toString(),{[f]:Q}=await n.keys.get("sender-key",[f]);return Q||await e.storeSenderKey(d,new Pg),a.transaction(async()=>{let{[f]:y}=await n.keys.get("sender-key",[f]);y||await e.storeSenderKey(d,new Pg),await I.process(d,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:I}){let d=On(g),B=new vs.SessionCipher(e,d);if(c==="pkmsg"){let Q=Aqe(I);if(Q){let y=d.toString();await e.saveIdentity(y,Q)&&t.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function f(){let Q;switch(c){case"pkmsg":Q=await B.decryptPreKeyWhisperMessage(I);break;case"msg":Q=await B.decryptWhisperMessage(I);break}return Q}return a.transaction(async()=>await f(),g)},async encryptMessage({jid:g,data:c}){let I=On(g),d=new vs.SessionCipher(e,I);return a.transaction(async()=>{let{type:B,body:f}=await d.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(f,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:I}){return a.transaction(async()=>{let{senderName:d,skdm:B}=await r(g,c);return{ciphertext:await new Fh(e,d).encrypt(I),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:I}=await r(g,c);return I.serialize()},g)},async hasSenderKey({group:g,meId:c}){let I=jO(g,c).toString(),{[I]:d}=await n.keys.get("sender-key",[I]);return!!d},async getSessionInfo(g){let c=On(g).toString(),I=await e.loadSession(c);if(!I)return null;let d=I.getOpenSession?.(),B=d?.indexInfo?.baseKey,f=d?.registrationId;return!B||typeof f!="number"?null:{baseKey:new Uint8Array(B),registrationId:f}},async injectE2ESession({jid:g,session:c}){t.trace({jid:g},"injecting E2EE session");let I=new vs.SessionBuilder(e,On(g));return a.transaction(async()=>{await I.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return On(g).toString()},lidMapping:i,async validateSession(g){try{let c=On(g),I=await e.loadSession(c.toString());return I?I.haveOpenSession()?{exists:!0}:{exists:!1,reason:"no open session"}:{exists:!1,reason:"no session"}}catch{return{exists:!1,reason:"validation error"}}},async deleteSession(g){if(!g.length)return;let c={};return g.forEach(I=>{let d=On(I);c[d.toString()]=null}),a.transaction(async()=>{await n.keys.set({session:c})},`delete-${g.length}-sessions`)},close(){A.clear(),i.close()},async migrateSession(g,c){if(!g||!qA(c)&&!oa(c))return{migrated:0,skipped:0,total:0};if(!bt(g)&&!Cr(g))return{migrated:0,skipped:0,total:1};let{user:I}=yA(g);t.debug({fromJid:g},"bulk device migration - loading all user devices");let{[I]:d}=await a.get("device-list",[I]);if(!d)return{migrated:0,skipped:0,total:0};let{device:B}=yA(g),f=B?.toString()||"0";d.includes(f)||d.push(f);let y=d.filter(T=>{let R=`${I}.${T}`;return!A.has(R)}).map(T=>`${I}.${T}`),m=await a.get("session",y),_=[];for(let[T,R]of Object.entries(m))if(R){let H=T.split(".")[1];if(!H)continue;let j=parseInt(H),F=j===0?`${I}@s.whatsapp.net`:`${I}:${j}@s.whatsapp.net`;j===99&&(F=`${I}:99@hosted`),_.push(F)}return t.debug({fromJid:g,totalDevices:d.length,devicesWithSessions:_.length,devices:_},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let T=_.map(x=>{let P=l9(x,c),z=yA(x),U=yA(P);return{fromJid:x,toJid:P,pnUser:z.user,lidUser:U.user,deviceId:z.device||0,fromAddr:On(x),toAddr:On(P)}}),R=T.length,H=0,j=Array.from(new Set(T.map(x=>x.fromAddr.toString()))),F=await a.get("session",j),q={};for(let x of T){let P=x.fromAddr.toString(),z=x.toAddr.toString(),U=F[P];if(U){let N=vs.SessionRecord.deserialize(U);N.haveOpenSession()&&(q[z]=N.serialize(),q[P]=null,H++)}}if(Object.keys(q).length>0){await a.set({session:q}),t.debug({migratedSessions:H},"bulk session migration complete");for(let x of T)if(q[x.toAddr.toString()]){let P=`${x.pnUser}.${x.deviceId}`;A.set(P,!0)}}let J=R-H;return{migrated:H,skipped:J,total:R}},`migrate-${_.length}-sessions-${yA(c)?.user}`)}}}var On=n=>{let t=yA(n),{user:o,device:i,server:e,domainType:a}=t;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==xt.WHATSAPP?`${o}_${a}`:o,r=i||0;if(i===99&&t.server!=="hosted"&&t.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new vs.ProtocolAddress(A,r)},jO=(n,t)=>new $B(n,On(t));function tqe({creds:n,keys:t},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[r,s]=a.split("_"),g=parseInt(s||"0");if(g===xt.LID||g===xt.HOSTED_LID)return e;let c=`${r}${A!=="0"?`:${A}`:""}@${g===xt.HOSTED?"hosted":"s.whatsapp.net"}`,I=await o.getLIDForPN(c);if(I)return On(I).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await t.get("session",[a]);if(A)return vs.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await t.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await t.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:r}=await t.get("identity-key",[A]),s=r?.length===a.length&&r.every((g,c)=>g===a[c]);return r&&!s?(await t.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):r?!1:(await t.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>t.set({"pre-key":{[e]:null}}),loadSignedPreKey:()=>{let e=n.signedPreKey;return{privKey:Buffer.from(e.keyPair.private),pubKey:Buffer.from(e.keyPair.public)}},loadSenderKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("sender-key",[a]);return A?Pg.deserialize(A):new Pg},storeSenderKey:async(e,a)=>{let A=e.toString(),r=JSON.stringify(a.serialize());await t.set({"sender-key":{[A]:Buffer.from(r,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from(vo(e.public))}}}}var Cse=qe(Ese(),1),of=(0,Cse.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var TVe=[2,3e3,1043857760];var KB="https://web.whatsapp.com",eie="https://call.whatsapp.com/video/",Aie="https://call.whatsapp.com/voice/",xh="CB:",use="TAG:";var die=Buffer.from([6,0]),hie=Buffer.from([6,1]),g2=Buffer.from([6,5]),hTA=Buffer.from([6,6]),jB=10080*60,Bse=1440*60,fse=336*60*60,fie="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",NVe=3,Qg=Buffer.from([5]),Qse=Buffer.from([87,65,6,NVe]),tie=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,I2={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},nf=[oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,oe.HistorySync.HistorySyncType.PUSH_NAME,oe.HistorySync.HistorySyncType.RECENT,oe.HistorySync.HistorySyncType.FULL,oe.HistorySync.HistorySyncType.ON_DEMAND,oe.HistorySync.HistorySyncType.NON_BLOCKING_DATA,oe.HistorySync.HistorySyncType.INITIAL_STATUS_V3],$c={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},yse={version:TVe,browser:UO.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:of.child({class:"baileys"}),emitOwnEvents:!0,defaultQueryTimeoutMs:6e4,customUploadHosts:[],retryRequestDelayMs:250,maxMsgRetryCount:5,fireInitQueries:!0,auth:void 0,markOnlineOnConnect:!0,syncFullHistory:!0,patchMessageBeforeSending:n=>n,shouldSyncHistoryMessage:({syncType:n})=>n!==oe.HistorySync.HistorySyncType.FULL,shouldIgnoreJid:()=>!1,linkPreviewImageThumbnailWidth:192,transactionOpts:{maxCommitRetries:10,delayBetweenTriesMs:3e3},generateHighQualityLinkPreview:!1,enableAutoSessionRecreation:!0,enableRecentMessageCache:!0,options:{},appStateMacVerification:{patch:!1,snapshot:!1},countryCode:"US",getMessage:async()=>{},cachedGroupMetadata:async()=>{},makeSignalRepository:hoe},$L={image:"/mms/image",video:"/mms/video",document:"/mms/document",audio:"/mms/audio",sticker:"/mms/image","thumbnail-link":"/mms/image","product-catalog-image":"/product/image","md-app-state":"","md-msg-hist":"/mms/md-app-state","biz-cover-photo":"/pps/biz-cover-photo"},xae={audio:"Audio",document:"Document",gif:"Video",image:"Image",ppic:"",product:"Image",ptt:"Audio",sticker:"Image",video:"Video","thumbnail-document":"Document Thumbnail","thumbnail-image":"Image Thumbnail","thumbnail-video":"Video Thumbnail","thumbnail-link":"Link Thumbnail","md-msg-hist":"History","md-app-state":"App State","product-catalog-image":"","payment-bg-image":"Payment Background",ptv:"Video","biz-cover-photo":"Image"},rie=Object.keys($L),mse=12e4,sf=5,Sse=812,Dse=3e4,TU={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var wse=qe(Gr(),1);import{createHash as RVe}from"crypto";import{createWriteStream as kVe,promises as vVe}from"fs";import{tmpdir as PVe}from"os";import{join as GVe}from"path";var Ose=n=>{let t=Ie(n,"product_catalog"),o=PA(t,"product").map(gf),i=Ie(t,"paging");return{products:o,nextPageCursor:i?jA(i,"after"):void 0}},bse=n=>{let t=Ie(n,"collections");return{collections:PA(t,"collection").map(i=>{let e=jA(i,"id"),a=jA(i,"name"),A=PA(i,"product").map(gf);return{id:e,name:a,products:A,status:UVe(i)}})}},Mse=n=>{let t=Ie(n,"order"),o=PA(t,"product").map(a=>{let A=Ie(a,"image");return{id:jA(a,"id"),name:jA(a,"name"),imageUrl:jA(A,"url"),price:+jA(a,"price"),currency:jA(a,"currency"),quantity:+jA(a,"quantity")}}),i=Ie(t,"price");return{price:{total:+jA(i,"total"),currency:jA(i,"currency")},products:o}},NU=(n,t)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof t.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(t.name)}),typeof t.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(t.description)}),typeof t.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(t.retailerId)}),t.images.length&&i.push({tag:"media",attrs:{},content:t.images.map(a=>{if(!("url"in a))throw new wse.Boom("Expected img for product to already be uploaded",{statusCode:400});return{tag:"image",attrs:{},content:[{tag:"url",attrs:{},content:Buffer.from(a.url.toString())}]}})}),typeof t.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(t.price.toString())}),typeof t.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(t.currency)}),"originCountryCode"in t&&(typeof t.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(t.originCountryCode)}]})),typeof t.isHidden<"u"&&(o.is_hidden=t.isHidden.toString()),{tag:"product",attrs:o,content:i}},gf=n=>{let t=n.attrs.is_hidden==="true",o=jA(n,"id"),i=Ie(n,"media"),e=Ie(n,"status_info");return{id:o,imageUrls:LVe(i),reviewStatus:{whatsapp:jA(e,"status")},availability:"in stock",name:jA(n,"name"),retailerId:jA(n,"retailer_id"),url:jA(n,"url"),description:jA(n,"description"),price:+jA(n,"price"),currency:jA(n,"currency"),isHidden:t}};async function RU(n,t,o=3e4){return n={...n,images:n.images?await FVe(n.images,t,o):n.images},n}var FVe=async(n,t,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let I=e.url.toString();if(I.includes(".whatsapp.net"))return{url:I}}let{stream:a}=await UB(e),A=RVe("sha256"),r=GVe(PVe(),"img"+Ur()),s=kVe(r);for await(let I of a)A.update(I),s.write(I);let g=A.digest("base64"),{directPath:c}=await t(r,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await vVe.unlink(r).catch(I=>console.log("Error deleting temp file ",I)),{url:HB(c)}})),LVe=n=>{let t=Ie(n,"image");return{requested:jA(t,"request_image_url"),original:jA(t,"original_image_url")}},UVe=n=>{let t=Ie(n,"status_info");return{status:jA(t,"status"),canAppeal:jA(t,"can_appeal")==="true"}};var If=qe(Gr(),1);import{randomBytes as LU}from"crypto";var Vo=null;try{Vo=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Nt(n,t,o){this.low=n|0,this.high=t|0,this.unsigned=!!o}Nt.prototype.__isLong__;Object.defineProperty(Nt.prototype,"__isLong__",{value:!0});function za(n){return(n&&n.__isLong__)===!0}function _se(n){var t=Math.clz32(n&-n);return n?31-t:t}Nt.isLong=za;var Tse={},Nse={};function xl(n,t){var o,i,e;return t?(n>>>=0,(e=0<=n&&n<256)&&(i=Nse[n],i)?i:(o=yt(n,0,!0),e&&(Nse[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=Tse[n],i)?i:(o=yt(n,n<0?-1:0,!1),e&&(Tse[n]=o),o))}Nt.fromInt=xl;function Wo(n,t){if(isNaN(n))return t?Gg:_n;if(t){if(n<0)return Gg;if(n>=Pse)return Lse}else{if(n<=-kse)return Pi;if(n+1>=kse)return Fse}return n<0?Wo(-n,t).neg():yt(n%jh|0,n/jh|0,t)}Nt.fromNumber=Wo;function yt(n,t,o){return new Nt(n,t,o)}Nt.fromBits=yt;var pb=Math.pow;function vU(n,t,o){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(o=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Gg:_n;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return vU(n.substring(1),t,o).neg();for(var e=Wo(pb(o,8)),a=_n,A=0;A>>0:this.low};Ue.toNumber=function(){return this.unsigned?(this.high>>>0)*jh+(this.low>>>0):this.high*jh+(this.low>>>0)};Ue.toString=function(t){if(t=t||10,t<2||36>>0,c=g.toString(t);if(A=s,A.isZero())return c+r;for(;c.length<6;)c="0"+c;r=""+c+r}};Ue.getHighBits=function(){return this.high};Ue.getHighBitsUnsigned=function(){return this.high>>>0};Ue.getLowBits=function(){return this.low};Ue.getLowBitsUnsigned=function(){return this.low>>>0};Ue.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Pi)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,o=31;o>0&&(t&1<>21;return t?this.unsigned?!1:t===-1&&!(this.low===0&&this.high===-2097152):!0};Ue.isZero=function(){return this.high===0&&this.low===0};Ue.eqz=Ue.isZero;Ue.isNegative=function(){return!this.unsigned&&this.high<0};Ue.isPositive=function(){return this.unsigned||this.high>=0};Ue.isOdd=function(){return(this.low&1)===1};Ue.isEven=function(){return(this.low&1)===0};Ue.equals=function(t){return za(t)||(t=Zo(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};Ue.eq=Ue.equals;Ue.notEquals=function(t){return!this.eq(t)};Ue.neq=Ue.notEquals;Ue.ne=Ue.notEquals;Ue.lessThan=function(t){return this.comp(t)<0};Ue.lt=Ue.lessThan;Ue.lessThanOrEqual=function(t){return this.comp(t)<=0};Ue.lte=Ue.lessThanOrEqual;Ue.le=Ue.lessThanOrEqual;Ue.greaterThan=function(t){return this.comp(t)>0};Ue.gt=Ue.greaterThan;Ue.greaterThanOrEqual=function(t){return this.comp(t)>=0};Ue.gte=Ue.greaterThanOrEqual;Ue.ge=Ue.greaterThanOrEqual;Ue.compare=function(t){if(za(t)||(t=Zo(t)),this.eq(t))return 0;var o=this.isNegative(),i=t.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};Ue.comp=Ue.compare;Ue.negate=function(){return!this.unsigned&&this.eq(Pi)?Pi:this.not().add(Yh)};Ue.neg=Ue.negate;Ue.add=function(t){za(t)||(t=Zo(t));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=t.high>>>16,r=t.high&65535,s=t.low>>>16,g=t.low&65535,c=0,I=0,d=0,B=0;return B+=a+g,d+=B>>>16,B&=65535,d+=e+s,I+=d>>>16,d&=65535,I+=i+r,c+=I>>>16,I&=65535,c+=o+A,c&=65535,yt(d<<16|B,c<<16|I,this.unsigned)};Ue.subtract=function(t){return za(t)||(t=Zo(t)),this.add(t.neg())};Ue.sub=Ue.subtract;Ue.multiply=function(t){if(this.isZero())return this;if(za(t)||(t=Zo(t)),Vo){var o=Vo.mul(this.low,this.high,t.low,t.high);return yt(o,Vo.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Gg:_n;if(this.eq(Pi))return t.isOdd()?Pi:_n;if(t.eq(Pi))return this.isOdd()?Pi:_n;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(vse)&&t.lt(vse))return Wo(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,r=t.high>>>16,s=t.high&65535,g=t.low>>>16,c=t.low&65535,I=0,d=0,B=0,f=0;return f+=A*c,B+=f>>>16,f&=65535,B+=a*c,d+=B>>>16,B&=65535,B+=A*g,d+=B>>>16,B&=65535,d+=e*c,I+=d>>>16,d&=65535,d+=a*g,I+=d>>>16,d&=65535,d+=A*s,I+=d>>>16,d&=65535,I+=i*c+e*g+a*s+A*r,I&=65535,yt(B<<16|f,I<<16|d,this.unsigned)};Ue.mul=Ue.multiply;Ue.divide=function(t){if(za(t)||(t=Zo(t)),t.isZero())throw Error("division by zero");if(Vo){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var o=(this.unsigned?Vo.div_u:Vo.div_s)(this.low,this.high,t.low,t.high);return yt(o,Vo.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Gg:_n;var i,e,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Gg;if(t.gt(this.shru(1)))return Gse;a=Gg}else{if(this.eq(Pi)){if(t.eq(Yh)||t.eq(kU))return Pi;if(t.eq(Pi))return Yh;var A=this.shr(1);return i=A.div(t).shl(1),i.eq(_n)?t.isNegative()?Yh:kU:(e=this.sub(t.mul(i)),a=i.add(e.div(t)),a)}else if(t.eq(Pi))return this.unsigned?Gg:_n;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=_n}for(e=this;e.gte(t);){i=Math.max(1,Math.floor(e.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(i)/Math.LN2),s=r<=48?1:pb(2,r-48),g=Wo(i),c=g.mul(t);c.isNegative()||c.gt(e);)i-=s,g=Wo(i,this.unsigned),c=g.mul(t);g.isZero()&&(g=Yh),a=a.add(g),e=e.sub(c)}return a};Ue.div=Ue.divide;Ue.modulo=function(t){if(za(t)||(t=Zo(t)),Vo){var o=(this.unsigned?Vo.rem_u:Vo.rem_s)(this.low,this.high,t.low,t.high);return yt(o,Vo.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};Ue.mod=Ue.modulo;Ue.rem=Ue.modulo;Ue.not=function(){return yt(~this.low,~this.high,this.unsigned)};Ue.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};Ue.clz=Ue.countLeadingZeros;Ue.countTrailingZeros=function(){return this.low?_se(this.low):_se(this.high)+32};Ue.ctz=Ue.countTrailingZeros;Ue.and=function(t){return za(t)||(t=Zo(t)),yt(this.low&t.low,this.high&t.high,this.unsigned)};Ue.or=function(t){return za(t)||(t=Zo(t)),yt(this.low|t.low,this.high|t.high,this.unsigned)};Ue.xor=function(t){return za(t)||(t=Zo(t)),yt(this.low^t.low,this.high^t.high,this.unsigned)};Ue.shiftLeft=function(t){return za(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low<>>32-t,this.unsigned):yt(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):yt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};Ue.shr=Ue.shiftRight;Ue.shiftRightUnsigned=function(t){return za(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?yt(this.high,0,this.unsigned):yt(this.high>>>t-32,0,this.unsigned)};Ue.shru=Ue.shiftRightUnsigned;Ue.shr_u=Ue.shiftRightUnsigned;Ue.rotateLeft=function(t){var o;return za(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.low<>>o,this.high<>>o,this.unsigned)):(t-=32,o=32-t,yt(this.high<>>o,this.low<>>o,this.unsigned))};Ue.rotl=Ue.rotateLeft;Ue.rotateRight=function(t){var o;return za(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,o=32-t,yt(this.low<>>t,this.high<>>t,this.unsigned))};Ue.rotr=Ue.rotateRight;Ue.toSigned=function(){return this.unsigned?yt(this.low,this.high,!1):this};Ue.toUnsigned=function(){return this.unsigned?this:yt(this.low,this.high,!0)};Ue.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};Ue.toBytesLE=function(){var t=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};Ue.toBytesBE=function(){var t=this.high,o=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};Nt.fromBytes=function(t,o,i){return i?Nt.fromBytesLE(t,o):Nt.fromBytesBE(t,o)};Nt.fromBytesLE=function(t,o){return new Nt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,o)};Nt.fromBytesBE=function(t,o){return new Nt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],o)};typeof BigInt=="function"&&(Nt.fromBigInt=function(t,o){var i=Number(BigInt.asIntN(32,t)),e=Number(BigInt.asIntN(32,t>>BigInt(32)));return yt(i,e,o)},Nt.fromValue=function(t,o){return typeof t=="bigint"?Nt.fromBigInt(t,o):Zo(t,o)},Ue.toBigInt=function(){var t=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new kg;return{mutex(t){return n.runExclusive(t)}}},Use=()=>{let n=new Map;return{async mutex(t,o){let i=n.get(t);i||(i={mutex:new kg,refCount:0},n.set(t,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(t)===i&&n.delete(t)}}}};function Hse(n,t,o=10){let i=[],e=!1;return{enqueue:(A,r)=>{if(i.push({type:A,node:r}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&t.isWsOpen();){let{type:c,node:I}=i.shift(),d=n.get(c);if(!d){t.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await d(I).catch(B=>t.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await t.yieldToEventLoop())}e=!1})().catch(g=>t.onUnexpectedError(g,"processing offline nodes"))}}}var Sb=qe(Gr(),1);var tI=qe(Gr(),1);var db=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(t){let o=[],i;if(t.tag==="devices"){_i(t);let e=Ie(t,"device-list"),a=Ie(t,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:r}of e.content){let s=+r.id,g=+r["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(r.is_hosted&&r.is_hosted==="true")})}a?.tag==="key-index-list"&&(i={timestamp:+a.attrs.ts,signedKeyIndex:a?.content,expectedTimestamp:a.attrs.expected_ts?+a.attrs.expected_ts:void 0})}return{deviceList:o,keyIndex:i}}};var Fs=class{withId(t){return this.id=t,this}withLid(t){return this.lid=t,this}withPhone(t){return this.phone=t,this}withUsername(t){return this.username=t,this}withUsernameKey(t){return this.usernameKey=t,this}withType(t){return this.type=t,this}withPersonaId(t){return this.personaId=t,this}};var hb=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(t){return t.phone?{tag:"contact",attrs:{},content:t.phone}:t.username?{tag:"contact",attrs:{username:t.username,...t.usernameKey?{pin:t.usernameKey}:{},...t.lid?{lid:t.lid}:{}}}:t.type?{tag:"contact",attrs:{type:t.type}}:{tag:"contact",attrs:{}}}parser(t){return t.tag==="contact"?(_i(t),t?.attrs?.type==="in"):!1}};var Eb=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="status"){_i(t);let o=t?.content?.toString()??null,i=new Date(+(t?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):t.attrs?.code&&+t.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var Cb=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="disappearing_mode"){_i(t);let o=+t?.attrs.duration,i=new Date(+(t?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var ub=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(t){return null}parser(t){return t.tag==="username"?(_i(t),typeof t.content=="string"?t.content:null):null}};var Bb=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(t){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:t.personaId}}]}}parser(t){let o=Ie(t,"bot"),i=Ie(o,"profile"),e=Ie(i,"commands"),a=Ie(i,"prompts"),A=[],r=[];for(let s of PA(e,"command"))A.push({name:jA(s,"name"),description:jA(s,"description")});for(let s of PA(a,"prompt"))r.push(`${jA(s,"emoji")} ${jA(s,"text")}`);return{isDefault:!!Ie(i,"default"),jid:t.attrs.jid,name:jA(i,"name"),attributes:jA(i,"attributes"),description:jA(i,"description"),category:jA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:jA(e,"description"),commands:A,prompts:r}}};var fb=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(t){return t.lid?{tag:"lid",attrs:{jid:t.lid}}:null}parser(t){return t.tag==="lid"?t.attrs.val:null}};var Ls=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(t){return this.mode=t,this}withContext(t){return this.context=t,this}withUser(t){return this.users.push(t),this}parseUSyncQueryResult(t){if(t?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=Ie(t,"usync"),a=e?Ie(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,r)=>{let s=r?.attrs.jid;if(s){let g=Array.isArray(r?.content)?Object.fromEntries(r.content.map(c=>{let I=c.tag,d=o[I];return d?[I,d(c)]:[I,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new db),this}withContactProtocol(){return this.protocols.push(new hb),this}withStatusProtocol(){return this.protocols.push(new Eb),this}withDisappearingModeProtocol(){return this.protocols.push(new Cb),this}withBotProfileProtocol(){return this.protocols.push(new Bb),this}withLIDProtocol(){return this.protocols.push(new fb),this}withUsernameProtocol(){return this.protocols.push(new ub),this}};var jr=qe(Gr(),1);import{randomBytes as GU}from"crypto";import{URL as YVe}from"url";import{promisify as jVe}from"util";var Qb=class{constructor(t={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,t)}};import{EventEmitter as KVe}from"events";var yb=class extends KVe{constructor(t,o){super(),this.url=t,this.config=o,this.setMaxListeners(0)}};var mb=class extends yb{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===wo.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===wo.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===wo.CLOSING}get isConnecting(){return this.socket?.readyState===wo.CONNECTING}connect(){if(this.socket)return;this.socket=new wo(this.url,{origin:KB,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let t=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of t)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let t=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await t,this.socket=null}send(t,o){return this.socket?.send(t,o),!!this.socket}};var PU=qe(Gr(),1);var xVe=(n,t,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:OA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:t},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),cf=async(n,t,o,i,e)=>{let a=await xVe(n,t,i,e),A=Ie(a,"result");if(A?.content){let s=JSON.parse(A.content.toString());if(s.errors&&s.errors.length>0){let c=s.errors.map(B=>B.message||"Unknown error").join(", "),I=s.errors[0],d=I.extensions?.error_code||400;throw new PU.Boom(`GraphQL server error: ${c}`,{statusCode:d,data:I})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let r=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new PU.Boom(`Failed to ${r}, unexpected response structure.`,{statusCode:400,data:a})};var Kse=n=>{let{waWebSocketUrl:t,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:r,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:I}=n,d=new Qb,B=0,f=V9(),Q=()=>`${f}${se++}`;r&&i.warn({},"\u26A0\uFE0F The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version."),a[1].toLocaleLowerCase().includes("android")&&i.warn("\u26A0\uFE0F Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk."),nf.map(le=>n.shouldSyncHistoryMessage({syncType:le})).filter(le=>le===!1).length===nf.length&&i.warn("\u26A0\uFE0F DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS");let m=typeof t=="string"?new YVe(t):t;if(n.mobile||m.protocol==="tcp:")throw new jr.Boom("Mobile API is not supported anymore",{statusCode:Zt.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let _=ur.generateKeyPair(),T=Bie({keyPair:_,NOISE_HEADER:Qse,logger:i,routingInfo:A?.creds?.routingInfo}),R=new mb(m,n);R.connect();let H=jVe(R.send),j=async le=>{if(!R.isOpen)throw new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed});let Qe=T.encodeFrame(le);await Ud(o,async(be,oA)=>{try{await H.call(R,Qe),be()}catch(lA){oA(lA)}})},F=le=>{i.level==="trace"&&i.trace({xml:Bn(le),msg:"xml send"});let Qe=p9(le);return j(Qe)},q=async(le,Qe=s)=>{let be,oA;try{return await Ud(Qe,(FA,Ut)=>(be=st=>{FA(st)},oA=st=>{Ut(st||new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed}))},R.on(`TAG:${le}`,be),R.on("close",oA),R.on("error",oA),()=>Ut(new jr.Boom("Query Cancelled"))))}catch(lA){if(lA instanceof jr.Boom&&lA.output?.statusCode===Zt.timedOut){i?.warn?.({msgId:le},"timed out waiting for message");return}throw lA}finally{be&&R.off(`TAG:${le}`,be),oA&&(R.off("close",oA),R.off("error",oA))}},J=async(le,Qe)=>{le.attrs.id||(le.attrs.id=Q());let be=le.attrs.id,oA=await Ud(Qe,async(lA,FA)=>{let Ut=q(be,Qe).catch(FA);F(le).then(async()=>lA(await Ut)).catch(FA)});return oA&&"tag"in oA&&_i(oA),oA},x=async()=>{let le=await J({tag:"iq",attrs:{to:OA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!Ie(le,"digest"))throw await Ze(),new Error("encrypt/get digest returned no digest node")},P=async()=>{let le=(V.signedPreKey.keyId||0)+1,Qe=await QD(V.signedIdentityKey,le);await J({tag:"iq",attrs:{to:OA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[JB(Qe)]}]}),k.emit("creds.update",{signedPreKey:Qe})},z=async le=>{if(le.protocols.length===0)throw new jr.Boom("USyncQuery must have at least one protocol");let be=le.users.map(st=>({tag:"user",attrs:{jid:st.phone?void 0:st.id},content:le.protocols.map(fr=>fr.getUserElement(st)).filter(fr=>fr!==null)})),oA={tag:"list",attrs:{},content:be},lA={tag:"query",attrs:{},content:le.protocols.map(st=>st.getQueryElement())},FA={tag:"iq",attrs:{to:OA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:le.context,mode:le.mode,sid:Q(),last:"true",index:"0"},content:[lA,oA]}]},Ut=await J(FA);return le.parseUSyncQueryResult(Ut)},U=async(...le)=>{let Qe=new Ls,be=!1;for(let lA of le)if(qA(lA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{be||(be=!0,Qe=Qe.withContactProtocol());let FA=`+${lA.replace("+","").split("@")[0]?.split(":")[0]}`;Qe.withUser(new Fs().withPhone(FA))}if(Qe.users.length===0)return[];let oA=await z(Qe);if(oA)return oA.list.filter(lA=>!!lA.contact).map(({contact:lA,id:FA})=>({jid:FA,exists:lA}))},N=async le=>{let Qe=new Ls().withLIDProtocol().withContext("background");for(let oA of le)if(qA(oA)){i?.warn("LID user found in LID fetch call");continue}else Qe.withUser(new Fs().withId(oA));if(Qe.users.length===0)return[];let be=await z(Qe);return be?be.list.filter(oA=>!!oA.lid).map(({lid:oA,id:lA})=>({pn:lA,lid:oA})):[]},k=eoe(i),{creds:V}=A,ee=jie(A.keys,i,g),ie=I({creds:V,keys:ee},i,N),Te,se=1,Ne,fe,De=!1,Ke=[],rA=(le,Qe)=>{i.error({err:le},`unexpected error in '${Qe}'`)},ve=async le=>{if(!R.isOpen)throw new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed});let Qe,be,oA=Ud(o,(lA,FA)=>{Qe=lA,be=FU(FA),R.on("frame",Qe),R.on("close",be),R.on("error",be)}).finally(()=>{R.off("frame",Qe),R.off("close",be),R.off("error",be)});return le&&j(le).catch(be),oA},iA=async()=>{let le={clientHello:{ephemeral:_.public}};le=oe.HandshakeMessage.fromObject(le),i.info({browser:a,helloMsg:le},"connected to WA");let Qe=oe.HandshakeMessage.encode(le).finish(),be=await ve(Qe),oA=oe.HandshakeMessage.decode(be);i.trace({handshake:oA},"handshake recv from WA");let lA=T.processHandshake(oA,V.noiseKey),FA;V.me?(FA=Iie(V.me.id,n),i.info({node:FA},"logging in...")):(FA=lie(V,n),i.info({node:FA},"not logged in, attempting registration..."));let Ut=T.encrypt(oe.ClientPayload.encode(FA).finish());await j(oe.HandshakeMessage.encode({clientFinish:{static:lA,payload:Ut}}).finish()),await T.finishInit(),We()},Ce=async()=>{let le=await J({tag:"iq",attrs:{id:Q(),xmlns:"encrypt",type:"get",to:OA},content:[{tag:"count",attrs:{}}]});return+Ie(le,"count").attrs.value},he=null,Ze=async(le=sf)=>{if(he){i.debug("Pre-key upload already in progress, waiting for completion"),await he;return}let Qe=async be=>{i.info({count:le,retryCount:be},"uploading pre-keys");let oA=await ee.transaction(async()=>{i.debug({requestedCount:le},"generating pre-keys with requested count");let{update:lA,node:FA}=await sie({creds:V,keys:ee},le);return k.emit("creds.update",lA),FA},V?.me?.id||"upload-pre-keys");try{await J(oA),i.info({count:le},"uploaded pre-keys successfully")}catch(lA){if(i.error({uploadError:lA.toString(),count:le},"Failed to upload pre-keys to server"),be<3){let FA=Math.min(1e3*Math.pow(2,be),1e4);return i.info(`Retrying pre-key upload in ${FA}ms`),await new Promise(Ut=>setTimeout(Ut,FA)),Qe(be+1)}throw lA}};he=Promise.race([Qe(0),new Promise((be,oA)=>setTimeout(()=>oA(new jr.Boom("Pre-key upload timeout",{statusCode:408})),Dse))]);try{await he}finally{he=null}},je=async()=>{let le=V.nextPreKeyId-1;return le<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await ee.get("pre-key",[le.toString()]))[le.toString()],currentPreKeyId:le}},Oe=async()=>{try{let le=0,Qe=await Ce();Qe===0?le=Sse:le=sf;let{exists:be,currentPreKeyId:oA}=await je();i.info(`${Qe} pre-keys found on server`),i.info(`Current prekey ID: ${oA}, exists in storage: ${be}`);let lA=Qe<=le,FA=!be&&oA>0;if(lA||FA){let st=[];lA&&st.push(`server count low (${Qe})`),FA&&st.push(`current prekey ${oA} missing from storage`),i.info(`Uploading PreKeys due to: ${st.join(", ")}`),await Ze(le)}else i.info(`PreKey validation passed - Server: ${Qe}, Current prekey ${oA} exists`)}catch(le){i.error({error:le},"Failed to check/upload pre-keys during initialization")}},hA=async le=>{await T.decodeFrame(le,Qe=>{Te=new Date;let be=!1;if(be=R.emit("frame",Qe),!(Qe instanceof Uint8Array)){let oA=Qe.attrs.id;i.level==="trace"&&i.trace({xml:Bn(Qe),msg:"recv xml"}),be=R.emit(`${use}${oA}`,Qe)||be;let lA=Qe.tag,FA=Qe.attrs||{},Ut=Array.isArray(Qe.content)?Qe.content[0]?.tag:"";for(let st of Object.keys(FA))be=R.emit(`${xh}${lA},${st}:${FA[st]},${Ut}`,Qe)||be,be=R.emit(`${xh}${lA},${st}:${FA[st]}`,Qe)||be,be=R.emit(`${xh}${lA},${st}`,Qe)||be;be=R.emit(`${xh}${lA},,${Ut}`,Qe)||be,be=R.emit(`${xh}${lA}`,Qe)||be,!be&&i.level==="debug"&&i.debug({unhandled:!0,msgId:oA,fromMe:!1,frame:Qe},"communication recv")}})},dA=async le=>{if(De){i.trace({trace:le?.stack},"connection already closed");return}if(De=!0,i.info({trace:le?.stack},le?"connection errored":"connection closed"),clearInterval(Ne),clearTimeout(fe),R.removeAllListeners("close"),R.removeAllListeners("open"),R.removeAllListeners("message"),ie.close?.(),!R.isClosed&&!R.isClosing)try{await R.close()}catch{}for(let Qe of Ke)try{await Qe(le)}catch(be){i.error({err:be},"error in socket end handler")}k.emit("connection.update",{connection:"close",lastDisconnect:{error:le,date:new Date}}),k.removeAllListeners("connection.update"),k.destroy()},aA=async()=>{if(R.isOpen)return;if(R.isClosed||R.isClosing)throw new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed});let le,Qe;await new Promise((be,oA)=>{le=()=>be(void 0),Qe=FU(oA),R.on("open",le),R.on("close",Qe),R.on("error",Qe)}).finally(()=>{R.off("open",le),R.off("close",Qe),R.off("error",Qe)})},We=()=>Ne=setInterval(()=>{Te||(Te=new Date),Date.now()-Te.getTime()>e+5e3?dA(new jr.Boom("Connection was lost",{statusCode:Zt.connectionLost})):R.isOpen?J({tag:"iq",attrs:{id:Q(),to:OA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(Qe=>{i.error({trace:Qe.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),bA=le=>J({tag:"iq",attrs:{to:OA,xmlns:"passive",type:"set"},content:[{tag:le,attrs:{}}]}),Be=async le=>{let Qe=A.creds.me?.id;Qe&&await F({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:Qe,reason:"user_initiated"}}]}),dA(new jr.Boom(le||"Intentional Logout",{statusCode:Zt.loggedOut}))},Re=async(le,Qe)=>{let be=Qe??eX(GU(5));if(Qe&&Qe?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=be,A.creds.me={id:Er(le,"s.whatsapp.net"),name:"~"},k.emit("creds.update",A.creds),await F({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:A.creds.me.id,stage:"companion_hello",should_show_push_notification:"true"},content:[{tag:"link_code_pairing_wrapped_companion_ephemeral_pub",attrs:{},content:await Le()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:F2(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function Le(){let le=GU(32),Qe=GU(16),be=await yD(A.creds.pairingCode,le),oA=G9(A.creds.pairingEphemeralKeyPair.public,be,Qe);return Buffer.concat([le,Qe,oA])}let MA=le=>J({tag:"iq",attrs:{to:OA,id:Q(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:le}]});R.on("message",hA),R.on("open",async()=>{try{await iA()}catch(le){i.error({err:le},"error in validating connection"),dA(le)}}),R.on("error",FU(dA)),R.on("close",()=>void dA(new jr.Boom("Connection Terminated",{statusCode:Zt.connectionClosed}))),R.on("CB:xmlstreamend",()=>void dA(new jr.Boom("Connection Terminated by Server",{statusCode:Zt.connectionClosed}))),R.on("CB:iq,type:set,pair-device",async le=>{let Qe={tag:"iq",attrs:{to:OA,type:"result",id:le.attrs.id}};await F(Qe);let be=Ie(le,"pair-device"),oA=PA(be,"ref"),lA=Buffer.from(V.noiseKey.public).toString("base64"),FA=Buffer.from(V.signedIdentityKey.public).toString("base64"),Ut=V.advSecretKey,st=c||6e4,fr=()=>{if(!R.isOpen)return;let Ar=oA.shift();if(!Ar){dA(new jr.Boom("QR refs attempts ended",{statusCode:Zt.timedOut}));return}let oo=Ar.content.toString("utf-8"),Gi=roe(oo,lA,FA,Ut,a);k.emit("connection.update",{qr:Gi}),fe=setTimeout(fr,st),st=c||2e4};fr()}),R.on("CB:iq,,pair-success",async le=>{i.debug("pair success recv");try{_A(le);let{reply:Qe,creds:be}=pie(le,V);i.info({me:be.me,platform:be.platform},"pairing configured successfully, expect to restart the connection..."),k.emit("creds.update",be),k.emit("connection.update",{isNewLogin:!0,qr:void 0}),await F(Qe),DA()}catch(Qe){i.info({trace:Qe.stack},"error in pairing"),dA(Qe)}}),R.on("CB:success",async le=>{try{_A(le),await Oe(),await bA("active");try{await x()}catch(Qe){i.warn({e:Qe},"failed to run digest after login")}}catch(Qe){i.warn({err:Qe},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(fe),k.emit("creds.update",{me:{...A.creds.me,lid:le.attrs.lid}}),k.emit("connection.update",{connection:"open"}),DA(),le.attrs.lid&&A.creds.me?.id){let Qe=le.attrs.lid;process.nextTick(async()=>{try{let be=A.creds.me.id;await ie.lidMapping.storeLIDPNMappings([{lid:Qe,pn:be}]);let{user:oA,device:lA}=yA(be);await A.keys.set({"device-list":{[oA]:[lA?.toString()||"0"]}}),await ie.migrateSession(be,Qe),i.info({myPN:be,myLID:Qe},"Own LID session created successfully")}catch(be){i.error({error:be,lid:Qe},"Failed to create own LID session")}})}}),R.on("CB:stream:error",le=>{let[Qe]=ls(le);i.error({reasonNode:Qe,fullErrorNode:le},"stream errored out");let{reason:be,statusCode:oA}=Z9(le);dA(new jr.Boom(`Stream Errored (${be})`,{statusCode:oA,data:Qe||le}))}),R.on("CB:failure",le=>{let Qe=+(le.attrs.reason||500);dA(new jr.Boom("Connection Failure",{statusCode:Qe,data:le.attrs}))}),R.on("CB:ib,,downgrade_webclient",()=>{dA(new jr.Boom("Multi-device beta not joined",{statusCode:Zt.multideviceMismatch}))}),R.on("CB:ib,,offline_preview",async le=>{i.info("offline preview received",JSON.stringify(le)),await F({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),R.on("CB:ib,,edge_routing",le=>{let Qe=Ie(le,"edge_routing"),be=Ie(Qe,"routing_info");be?.content&&(A.creds.routingInfo=Buffer.from(be?.content),k.emit("creds.update",A.creds))});let He=!1;process.nextTick(()=>{V.me?.id&&(k.buffer(),He=!0),k.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),R.on("CB:ib,,offline",le=>{let be=+(Ie(le,"offline")?.attrs.count||0);i.info(`handled ${be} offline messages/notifications`),He&&(k.flush(),i.trace("flushed events for initial buffer")),k.emit("connection.update",{receivedPendingNotifications:!0})}),k.on("creds.update",le=>{let Qe=le.me?.name;V.me?.name!==Qe&&(i.debug({name:Qe},"updated pushName"),F({tag:"presence",attrs:{name:Qe}}).catch(be=>{i.warn({trace:be.stack},"error in sending presence update on name change")})),Object.assign(V,le)});let _A=({attrs:le})=>{let Qe=le?.t;if(!Qe)return;let be=Number(Qe);if(Number.isNaN(be)||be<=0)return;let oA=Date.now();B=be*1e3-oA,i.debug({offset:B},"calculated server time offset")},at=()=>{let le=3*TU.Day;return((Date.now()+B+le)%TU.Week).toString()},DA=async()=>{if(!R.isOpen)return;let le={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:at()}}]};try{await F(le)}catch(Qe){i.debug({error:Qe},"failed to send unified_session telemetry")}},lt=le=>{Ke.push(le)},Ir=async()=>{let le=await cf({},ia.REACHOUT_TIMELOCK,Ca.xwa2_fetch_account_reachout_timelock,J,Q),Qe={isActive:!!le?.is_active,timeEnforcementEnds:le?.time_enforcement_ends&&le?.time_enforcement_ends!=="0"?new Date(parseInt(le.time_enforcement_ends,10)*1e3):void 0,enforcementType:le?.enforcement_type??Dc.DEFAULT};return k.emit("connection.update",{reachoutTimeLock:Qe}),Qe},UA=async()=>cf({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},ia.MESSAGE_CAPPING_INFO,Ca.xwa2_message_capping_info,J,Q);return{type:"md",ws:R,ev:k,authState:{creds:V,keys:ee},signalRepository:ie,get user(){return A.creds.me},generateMessageTag:Q,query:J,waitForMessage:q,waitForSocketOpen:aA,sendRawMessage:j,sendNode:F,logout:Be,end:dA,registerSocketEndHandler:lt,onUnexpectedError:rA,uploadPreKeys:Ze,uploadPreKeysToServerIfRequired:Oe,digestKeyBundle:x,rotateSignedPreKey:P,requestPairingCode:Re,updateServerTimeOffset:_A,sendUnifiedSession:DA,wamBuffer:d,waitForConnectionUpdate:z9(k),sendWAMBuffer:MA,executeUSyncQuery:z,onWhatsApp:U,fetchAccountReachoutTimelock:Ir,fetchNewChatMessageCap:UA}};function FU(n){return t=>{n(new jr.Boom(`WebSocket Error (${t?.message})`,{statusCode:$9(t),data:t}))}}var JVe=(n,t)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return t?.length&&(o.content=t),[o]},xse=n=>{let{logger:t,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:r}=n,s=Kse(n),{ev:g,ws:c,authState:I,generateMessageTag:d,sendNode:B,query:f,signalRepository:Q,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:_}=s,T=Q.lidMapping.getLIDForPN.bind(Q.lidMapping),R,H={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},j=aa.Connecting,F=Fg(),q=Fg(),J=Fg(),x=Fg(),P,z={initialBootstrapComplete:!1,recentSyncComplete:!1},U,N=new Set,k=n.placeholderResendCache||new Rg({stdTTL:$c.MSG_RETRY,useClones:!1}),V=async W=>{let{[W]:X}=await I.keys.get("app-state-sync-key",[W]);return X},ee=async(W=!1)=>{if(!R||W){let{content:X}=await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"get"},content:[{tag:"privacy",attrs:{}}]});R=_G(X?.[0],"category")}return R},ie=async(W,X)=>{await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:W,value:X}}]}]})},Te=async W=>{await ie("messages",W)},se=async W=>{await ie("calladd",W)},Ne=async W=>{await ie("last",W)},fe=async W=>{await ie("online",W)},De=async W=>{await ie("profile",W)},Ke=async W=>{await ie("status",W)},rA=async W=>{await ie("readreceipts",W)},ve=async W=>{await ie("groupadd",W)},iA=async W=>{await f({tag:"iq",attrs:{xmlns:"disappearing_mode",to:OA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:W.toString()}}]})},Ce=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"bot",to:OA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),X=Ie(W,"bot"),re=[];for(let ne of PA(X,"section"))if(ne.attrs.type==="all")for(let Se of PA(ne,"bot"))re.push({jid:Se.attrs.jid,personaId:Se.attrs.persona_id});return re},he=async(...W)=>{let X=new Ls().withStatusProtocol();for(let ne of W)X.withUser(new Fs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},Ze=async(...W)=>{let X=new Ls().withDisappearingModeProtocol();for(let ne of W)X.withUser(new Fs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},je=async(W,X,re)=>{let ne;if(!W)throw new tI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?ne=uA(W):ne=void 0;let{img:Se}=await DO(X,re);await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...ne?{target:ne}:{}},content:[{tag:"picture",attrs:{type:"image"},content:Se}]})},Oe=async W=>{let X;if(!W)throw new tI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?X=uA(W):X=void 0,await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...X?{target:X}:{}}})},hA=async W=>{await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(W,"utf-8")}]})},dA=async W=>{await UA({pushNameSetting:W},"")},aA=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"get"}}),X=Ie(W,"list");return PA(X,"item").map(re=>re.attrs.jid)},We=async(W,X)=>{let re=uA(W),ne,Se;if(qA(re)||oa(re)){if(ne=re,X==="block"){let de=await Q.lidMapping.getPNForLID(re);if(!de)throw new tI.Boom(`Unable to resolve PN JID for LID: ${W}`,{statusCode:400});Se=uA(de)}}else if(bt(re)||Cr(re)){let de=await Q.lidMapping.getLIDForPN(re);if(!de)throw new tI.Boom(`Unable to resolve LID for PN JID: ${W}`,{statusCode:400});ne=de,X==="block"&&(Se=uA(re))}else throw new tI.Boom(`Invalid jid: ${W}`,{statusCode:400});let Ee={action:X,jid:ne};if(X==="block"){if(!Se)throw new tI.Boom(`pn_jid required for block: ${W}`,{statusCode:400});Ee.pn_jid=Se}await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"set"},content:[{tag:"item",attrs:Ee}]})},bA=async W=>{let X=await f({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:W}}]}]}),re=Ie(X,"business_profile"),ne=Ie(re,"profile");if(ne){let Se=Ie(ne,"address"),Ee=Ie(ne,"description"),de=Ie(ne,"website"),ye=Ie(ne,"email"),Je=Ie(Ie(ne,"categories"),"category"),IA=Ie(ne,"business_hours"),QA=IA?PA(IA,"business_hours_config"):void 0,XA=de?.content?.toString();return{wid:ne.attrs?.jid,address:Se?.content?.toString(),description:Ee?.content?.toString()||"",website:XA?[XA]:[],email:ye?.content?.toString(),category:Je?.content?.toString(),business_hours:{timezone:IA?.attrs?.timezone,business_config:QA?.map(({attrs:vA})=>vA)}}}},Be=async(W,X)=>{t.info({fromTimestamp:X},"clean dirty bits "+W),await B({tag:"iq",attrs:{to:OA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:d()},content:[{tag:"clean",attrs:{type:W,...X?{timestamp:X.toString()}:null}}]})},Re=W=>({onMutation(X){Pie(X,g,I.creds.me,W?{accountSettings:I.creds.accountSettings}:void 0,t)}}),Le=g.createBufferedFunction(async(W,X)=>{let re=new Map,ne=async ye=>{if(re.has(ye))return re.get(ye)??void 0;let Je=await V(ye);return re.set(ye,Je??null),Je},Se={},Ee={};await I.keys.transaction(async()=>{let ye=new Set(W),Je={},IA=new Set;for(;ye.size;){let QA={},XA=[];for(let $A of ye){let AA=(await I.keys.get("app-state-sync-version",[$A]))[$A];AA?(AA=p2(AA),typeof Se[$A]>"u"&&(Se[$A]=AA.version)):AA=TO(),QA[$A]=AA;let et=IA.has($A);et&&IA.delete($A),t.info(`resyncing ${$A} from v${AA.version}${et?" (forcing snapshot)":""}`),XA.push({tag:"collection",attrs:{name:$A,version:AA.version.toString(),return_snapshot:(et||!AA.version).toString()}})}let vA=await f({tag:"iq",attrs:{to:OA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:XA}]}),YA=await Nie(vA,n?.options);for(let $A in YA){let Pe=$A,{patches:AA,hasMorePatches:et,snapshot:qr}=YA[Pe];try{if(qr){let{state:tr,mutationMap:no}=await kie(Pe,qr,ne,Se[Pe],e.snapshot,t);QA[Pe]=tr,Object.assign(Ee,no),t.info(`restored state of ${Pe} from snapshot to v${tr.version} with mutations`),await I.keys.set({"app-state-sync-version":{[Pe]:tr}})}if(AA.length){let{state:tr,mutationMap:no}=await h2(Pe,AA,QA[Pe],ne,n.options,Se[Pe],t,e.patch);await I.keys.set({"app-state-sync-version":{[Pe]:tr}}),t.info(`synced ${Pe} to v${tr.version}`),Se[Pe]=tr.version,Object.assign(Ee,no)}et?t.info(`${Pe} has more patches...`):ye.delete(Pe)}catch(tr){Je[Pe]=(Je[Pe]||0)+1;let no={name:Pe,attempt:Je[Pe],version:QA[Pe].version,statusCode:tr.output?.statusCode,errorType:tr.name,error:tr.stack};VB(tr)&&Je[Pe]>=d2?(t.warn(no,`${Pe} blocked on missing key from v${QA[Pe].version}, parking after ${Je[Pe]} attempts`),N.add(Pe),ye.delete(Pe)):VB(tr)?(t.info(no,`${Pe} blocked on missing key from v${QA[Pe].version}, retrying with snapshot`),IA.add(Pe)):Mie(tr,Je[Pe])?(t.warn(no,`failed to sync ${Pe} from v${QA[Pe].version}, giving up`),ye.delete(Pe)):(t.info(no,`failed to sync ${Pe} from v${QA[Pe].version}, forcing snapshot retry`),IA.add(Pe))}}}},I?.creds?.me?.id||"resync-app-state");let{onMutation:de}=Re(X);for(let ye in Ee)de(Ee[ye])}),MA=async(W,X="preview",re)=>{let ne=uA(W),Se=bt(ne)||qA(ne),Ee=I.creds.me,de=Ee&&(ne===uA(Ee.id)||Ee.lid&&ne===uA(Ee.lid)),ye;H.profilePicPrivacyToken&&Se&&!de&&(ye=await N2({authState:I,jid:ne,getLIDForPN:T})),W=uA(W);let Je=await f({tag:"iq",attrs:{target:W,to:OA,type:"get",xmlns:"w:profile:picture"},content:JVe(X,ye)},re);return Ie(Je,"picture")?.attrs?.url},He=async(W,X,re)=>{let ne=await f({tag:"call",attrs:{id:d(),to:"@call"},content:[{tag:"link_create",attrs:{media:W},content:X?[{tag:"event",attrs:{start_time:String(X.startTime)}}]:void 0}]},re);return Ie(ne,"link_create")?.attrs?.token},_A=async(W,X)=>{let re=I.creds.me,ne=W==="available";if(ne||W==="unavailable"){if(!re.name){t.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:ne}),ne&&m(),await B({tag:"presence",attrs:{name:re.name.replace(/@/g,""),type:W}})}else{let{server:Se}=yA(X);await B({tag:"chatstate",attrs:{from:Se==="lid"?re.lid:re.id,to:X},content:[{tag:W==="recording"?"composing":W,attrs:W==="recording"?{media:"audio"}:{}}]})}},at=async W=>{let X=uA(W),ne=bt(X)||qA(X)?await N2({authState:I,jid:X,getLIDForPN:T}):void 0;return B({tag:"presence",attrs:{to:W,id:d(),type:"subscribe"},content:ne})},DA=({tag:W,attrs:X,content:re})=>{let ne,Se=X.from,Ee=X.participant||X.from;if(!(a(Se)&&Se!==OA)){if(W==="presence")ne={lastKnownPresence:X.type==="unavailable"?"unavailable":"available",lastSeen:X.last&&X.last!=="deny"?+X.last:void 0,groupOnlineCount:X.count?+X.count:void 0};else if(Array.isArray(re)){let[de]=re,ye=de.tag;ye==="paused"&&(ye="available"),de.attrs?.media==="audio"&&(ye="recording"),ne={lastKnownPresence:ye}}else t.error({tag:W,attrs:X,content:re},"recv invalid presence node");ne&&g.emit("presence.update",{id:Se,presences:{[Ee]:ne}})}},lt=async W=>{let X=W.type,re=I.creds.myAppStateKeyId;if(!re)throw new tI.Boom("App state key not present!",{statusCode:400});let ne,Se;if(await J.mutex(async()=>{await I.keys.transaction(async()=>{t.debug({patch:W},"applying app patch"),await Le([X],!1);let{[X]:Ee}=await I.keys.get("app-state-sync-version",[X]);ne=Ee?p2(Ee):TO(),Se=await _ie(W,re,ne,V);let{patch:de,state:ye}=Se,Je={tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:X,version:(ye.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:oe.SyncdPatch.encode(de).finish()}]}]}]};await f(Je),await I.keys.set({"app-state-sync-version":{[X]:ye}})},I?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:Ee}=Re(!1),{mutationMap:de}=await h2(X,[{...Se.patch,version:{version:Se.state.version}}],ne,V,n.options,void 0,t);for(let ye in de)Ee(de[ye])}},Ir=async()=>{let W=await f({tag:"iq",attrs:{to:OA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...I?.creds?.lastPropHash?{hash:I.creds.lastPropHash}:{}}}]}),X=Ie(W,"props"),re={};X&&(X.attrs?.hash&&(I.creds.lastPropHash=X?.attrs?.hash,g.emit("creds.update",I.creds)),re=_G(X,"prop"));let ne=re[10518]??re.privacy_token_sending_on_all_1_on_1_messages;ne!==void 0&&(H.privacyTokenOn1to1=ne==="true"||ne==="1");let Se=re[9666]??re.profile_scraping_privacy_token_in_photo_iq;Se!==void 0&&(H.profilePicPrivacyToken=Se==="true"||Se==="1");let Ee=re[14303]??re.lid_trusted_token_issue_to_lid;return Ee!==void 0&&(H.lidTrustedTokenIssueToLid=Ee==="true"||Ee==="1"),t.debug({serverProps:H},"fetched props"),re},UA=(W,X)=>{let re=vie(W,X);return lt(re)},le=W=>UA({disableLinkPreviews:{isPreviewsDisabled:W}},""),Qe=(W,X,re)=>UA({star:{messages:X,star:re}},W),be=(W,X)=>UA({contact:X},W),oA=W=>UA({contact:null},W),lA=(W,X)=>UA({addLabel:{...X}},W),FA=(W,X)=>UA({addChatLabel:{labelId:X}},W),Ut=(W,X)=>UA({removeChatLabel:{labelId:X}},W),st=(W,X,re)=>UA({addMessageLabel:{messageId:X,labelId:re}},W),fr=(W,X,re)=>UA({removeMessageLabel:{messageId:X,labelId:re}},W),Ar=W=>UA({quickReply:W},""),oo=W=>UA({quickReply:{timestamp:W,deleted:!0}},""),Gi=async()=>{await Promise.all([Ir(),aA(),ee()])},Ae=g.createBufferedFunction(async(W,X)=>{if(g.emit("messages.upsert",{messages:[W],type:X}),W.pushName){let Ee=W.key.fromMe?I.creds.me.id:W.key.participant||W.key.remoteJid;Ee=uA(Ee),W.key.fromMe||g.emit("contacts.update",[{id:Ee,notify:W.pushName,verifiedName:W.verifiedBizName}]),W.key.fromMe&&W.pushName&&I.creds.me?.name!==W.pushName&&g.emit("creds.update",{me:{...I.creds.me,name:W.pushName}})}let re=_O(W.message),ne=re?A(re)&&nf.includes(re.syncType):!1;if(re&&ne){let Ee=re.syncType;Ee===oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!z.initialBootstrapComplete&&(z.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===oe.HistorySync.HistorySyncType.RECENT&&re.progress===100&&!z.recentSyncComplete&&(z.recentSyncComplete=!0,clearTimeout(U),U=void 0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===oe.HistorySync.HistorySyncType.RECENT&&!z.recentSyncComplete&&(clearTimeout(U),U=setTimeout(()=>{z.recentSyncComplete||(z.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:oe.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),U=void 0},mse))}re&&j===aa.AwaitingInitialSync&&(P&&(clearTimeout(P),P=void 0),ne?(j=aa.Syncing,t.info("Transitioned to Syncing state")):(j=aa.Online,t.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let Se=async()=>{if(j===aa.Syncing){N.clear(),t.info("Doing app state sync"),await Le(r9,!0),j=aa.Online,t.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let Ee=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:Ee})}};await Promise.all([(async()=>{ne&&await Se()})(),$ie(W,{signalRepository:Q,shouldProcessHistoryMsg:ne,placeholderResendCache:k,ev:g,creds:I.creds,keyStore:I.keys,logger:t,options:n.options,getMessage:r})]),W.message?.protocolMessage?.appStateSyncKeyShare&&j===aa.Syncing&&(t.info("App state sync key arrived, triggering app state sync"),await Se())});return c.on("CB:presence",DA),c.on("CB:chatstate",DA),c.on("CB:ib,,dirty",async W=>{let{attrs:X}=Ie(W,"dirty");switch(X.type){case"account_sync":if(X.timestamp){let{lastAccountSyncTimestamp:ne}=I.creds;ne&&await Be("account_sync",ne),ne=+X.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:ne})}break;case"groups":break;default:t.info({node:W},"received unknown sync");break}}),g.on("connection.update",({connection:W,receivedPendingNotifications:X})=>{if(W==="close"&&(N.clear(),clearTimeout(U),U=void 0),W==="open"&&(i&&Gi().catch(ne=>y(ne,"init queries")),_A(o?"available":"unavailable").catch(ne=>y(ne,"presence update requests"))),!X||j!==aa.Connecting)return;if(z.initialBootstrapComplete=!1,z.recentSyncComplete=!1,clearTimeout(U),U=void 0,j=aa.AwaitingInitialSync,t.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(oe.Message.HistorySyncNotification.create({syncType:oe.HistorySync.HistorySyncType.RECENT}))){t.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),j=aa.Online,setTimeout(()=>g.flush(),0);return}if(I.creds.accountSyncCounter>0){t.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),j=aa.Online,setTimeout(()=>g.flush(),0);return}t.info("First connection, awaiting history sync notification with a 20s timeout."),P&&clearTimeout(P),P=setTimeout(()=>{if(j===aa.AwaitingInitialSync){t.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),j=aa.Online,g.flush();let ne=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:ne})}},2e4)}),g.on("creds.update",({myAppStateKeyId:W})=>{if(!W||N.size===0)return;if(j===aa.Syncing){N.clear();return}let X=[...N];N.clear(),t.info({collections:X},"app state sync key arrived, re-syncing blocked collections"),Le(X,!1).catch(re=>y(re,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:W,pn:X})=>{try{await Q.lidMapping.storeLIDPNMappings([{lid:W,pn:X}])}catch(re){t.warn({lid:W,pn:X,error:re},"Failed to store LID-PN mapping")}}),_(()=>{P&&(clearTimeout(P),P=void 0),!n.placeholderResendCache&&k.close&&k.close(),j=aa.Connecting,R=void 0}),{...s,serverProps:H,createCallLink:He,getBotListV2:Ce,messageMutex:F,receiptMutex:q,appStatePatchMutex:J,notificationMutex:x,fetchPrivacySettings:ee,upsertMessage:Ae,appPatch:lt,sendPresenceUpdate:_A,presenceSubscribe:at,profilePictureUrl:MA,fetchBlocklist:aA,fetchStatus:he,fetchDisappearingDuration:Ze,updateProfilePicture:je,removeProfilePicture:Oe,updateProfileStatus:hA,updateProfileName:dA,updateBlockStatus:We,updateDisableLinkPreviewsPrivacy:le,updateCallPrivacy:se,updateMessagesPrivacy:Te,updateLastSeenPrivacy:Ne,updateOnlinePrivacy:fe,updateProfilePicturePrivacy:De,updateStatusPrivacy:Ke,updateReadReceiptsPrivacy:rA,updateGroupsAddPrivacy:ve,updateDefaultDisappearingMode:iA,getBusinessProfile:bA,resyncAppState:Le,chatModify:UA,cleanDirtyBits:Be,addOrEditContact:be,removeContact:oA,placeholderResendCache:k,addLabel:lA,addChatLabel:FA,removeChatLabel:Ut,addMessageLabel:st,removeMessageLabel:fr,star:Qe,addOrEditQuickReply:Ar,removeQuickReply:oo}};var Yse=n=>{let t=xse(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(g,c,I)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:I}),r=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return Jh(c)},s=async()=>{let g=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),c={},I=Ie(g,"groups");if(I){let d=PA(I,"group");for(let B of d){let f=Jh({tag:"result",attrs:{},content:[B]});c[f.id]=f}}return t.ev.emit("groups.update",Object.values(c)),c};return t.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=Ie(g,"dirty");c.type==="groups"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,groupMetadata:r,groupCreate:async(g,c)=>{let I=Ur(),d=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:I},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return Jh(d)},groupLeave:async g=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"group",attrs:{id:g}}]}])},groupUpdateSubject:async(g,c)=>{await A(g,"set",[{tag:"subject",attrs:{},content:Buffer.from(c,"utf-8")}])},groupRequestParticipantsList:async g=>{let c=await A(g,"get",[{tag:"membership_approval_requests",attrs:{}}]),I=Ie(c,"membership_approval_requests");return PA(I,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:I,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=Ie(d,"membership_requests_action"),f=Ie(B,I);return PA(f,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:I,attrs:{},content:c.map(Q=>({tag:"participant",attrs:{jid:Q}}))}]),B=Ie(d,I);return PA(B,"participant").map(Q=>({status:Q.attrs.error||"200",jid:Q.attrs.jid,content:Q}))},groupUpdateDescription:async(g,c)=>{let d=(await r(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:Ur()}:{delete:"true"},...d?{prev:d}:{}},content:c?[{tag:"body",attrs:{},content:Buffer.from(c,"utf-8")}]:void 0}])},groupInviteCode:async g=>{let c=await A(g,"get",[{tag:"invite",attrs:{}}]);return Ie(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return Ie(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return Ie(c,"group")?.attrs.jid},groupRevokeInviteV4:async(g,c)=>!!await A(g,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:c}}]}]),groupAcceptInviteV4:i.createBufferedFunction(async(g,c)=>{g=typeof g=="string"?{remoteJid:g}:g;let I=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=oe.Message.GroupInviteMessage.fromObject(c),c.inviteExpiration=0,c.inviteCode="",i.emit("messages.update",[{key:g,update:{message:{groupInviteMessage:c}}}])),await a({key:{remoteJid:c.groupJid,id:Ur(t.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:Ba()},"notify"),I.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return Jh(c)},groupToggleEphemeral:async(g,c)=>{let I=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[I])},groupSettingUpdate:async(g,c)=>{await A(g,"set",[{tag:c,attrs:{}}])},groupMemberAddMode:async(g,c)=>{await A(g,"set",[{tag:"member_add_mode",attrs:{},content:c}])},groupJoinApprovalMode:async(g,c)=>{await A(g,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"group_join",attrs:{state:c}}]}])},groupFetchAllParticipating:s}},Jh=n=>{let t=Ie(n,"group");if(!t){let B=Ie(n,"error");if(B){let f=B.attrs.code?+B.attrs.code:500,Q=B.attrs.text||"group metadata query failed";throw new Sb.Boom(Q,{statusCode:f,data:B})}throw new Sb.Boom("Invalid group metadata response: missing node",{data:n})}if(!t.attrs.id)throw new Sb.Boom("Invalid group metadata response: missing group id",{data:t});let o=Ie(t,"description"),i,e,a,A,r,s;o&&(i=jA(o,"body"),a=o.attrs.participant?uA(o.attrs.participant):void 0,A=o.attrs.participant_pn?uA(o.attrs.participant_pn):void 0,r=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=t.attrs.id.includes("@")?t.attrs.id:Er(t.attrs.id,"g.us"),c=Ie(t,"ephemeral")?.attrs.expiration,I=jA(t,"member_add_mode")==="all_member_add";return{id:g,notify:t.attrs.notify,addressingMode:t.attrs.addressing_mode==="lid"?Pu.LID:Pu.PN,subject:t.attrs.subject,subjectOwner:t.attrs.s_o,subjectOwnerPn:t.attrs.s_o_pn,subjectOwnerUsername:t.attrs.s_o_username,subjectTime:+t.attrs.s_t,size:t.attrs.size?+t.attrs.size:PA(t,"participant").length,creation:+t.attrs.creation,owner:t.attrs.creator?uA(t.attrs.creator):void 0,ownerPn:t.attrs.creator_pn?uA(t.attrs.creator_pn):void 0,ownerUsername:t.attrs.creator_username||void 0,owner_country_code:t.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:r,descTime:s,linkedParent:Ie(t,"linked_parent")?.attrs.jid||void 0,restrict:!!Ie(t,"locked"),announce:!!Ie(t,"announcement"),isCommunity:!!Ie(t,"parent"),isCommunityAnnounce:!!Ie(t,"default_sub_group"),joinApprovalMode:!!Ie(t,"membership_approval_mode"),memberAddMode:I,participants:PA(t,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:qA(B.jid)&&bt(B.phone_number)?B.phone_number:void 0,lid:bt(B.jid)&&qA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var qh=qe(Gr(),1);var qVe=n=>{let{id:t,thread_metadata:o,viewer_metadata:i}=n;return{id:t,owner:void 0,name:o.name.text,creation_time:parseInt(o.creation_time,10),description:o.description.text,invite:o.invite,subscribers:parseInt(o.subscribers_count,10),verification:o.verification,picture:{id:o.picture.id,directPath:o.picture.direct_path},mute_state:i.mute}},zVe=n=>typeof n!="object"||n===null?null:"id"in n&&typeof n.id=="string"?n:"result"in n&&typeof n.result=="object"&&n.result!==null&&"id"in n.result?n.result:null,jse=n=>{let t=Yse(n),{query:o,generateMessageTag:i}=t,e=(A,r,s)=>cf(A,r,s,o,i),a=async(A,r)=>{let s={newsletter_id:A,updates:{...r,settings:null}};return e(s,ia.UPDATE_METADATA,"xwa2_newsletter_update")};return{...t,newsletterCreate:async(A,r)=>{let g=await e({input:{name:A,description:r??null}},ia.CREATE,Ca.xwa2_newsletter_create);return qVe(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},ia.SUBSCRIBERS,Ca.xwa2_newsletter_subscribers),newsletterMetadata:async(A,r)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:r,type:A.toUpperCase()}},g=await e(s,ia.METADATA,Ca.xwa2_newsletter_metadata);return zVe(g)},newsletterFollow:A=>e({newsletter_id:A},ia.FOLLOW,Ca.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},ia.UNFOLLOW,Ca.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},ia.MUTE,Ca.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},ia.UNMUTE,Ca.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,r)=>await a(A,{name:r}),newsletterUpdateDescription:async(A,r)=>await a(A,{description:r}),newsletterUpdatePicture:async(A,r)=>{let{img:s}=await DO(r);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,r,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:r,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,r,s,g)=>{let c={count:r.toString()};return typeof s=="number"&&(c.since=s.toString()),g&&(c.after=g.toString()),await o({tag:"iq",attrs:{id:i(),type:"get",xmlns:"newsletter",to:A},content:[{tag:"message_updates",attrs:c}]})},subscribeNewsletterUpdates:async A=>{let r=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=Ie(r,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},ia.ADMIN_COUNT,Ca.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,r)=>{await e({newsletter_id:A,user_id:r},ia.CHANGE_OWNER,Ca.xwa2_newsletter_change_owner)},newsletterDemote:async(A,r)=>{await e({newsletter_id:A,user_id:r},ia.DEMOTE,Ca.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},ia.DELETE,Ca.xwa2_newsletter_delete_v2)}}};var Jse=n=>{let{logger:t,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:r,maxMsgRetryCount:s}=n,g=jse(n),{ev:c,authState:I,messageMutex:d,signalRepository:B,upsertMessage:f,query:Q,fetchPrivacySettings:y,sendNode:m,groupMetadata:_,groupToggleEphemeral:T,registerSocketEndHandler:R}=g,H=B.lidMapping.getLIDForPN.bind(B.lidMapping),j=new Set,F=n.userDevicesCache||new Rg({stdTTL:$c.USER_DEVICES,useClones:!1}),q=Fg(),J=r?new LO(t,s):null,x=Use(),P,z=ZL,U=async(Ce=!1)=>{let he=await P;return(!he||Ce||new Date().getTime()-he.fetchDate.getTime()>he.ttl*1e3)&&(P=(async()=>{let Ze=await Q({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:OA},content:[{tag:"media_conn",attrs:{}}]}),je=Ie(Ze,"media_conn"),Oe={hosts:PA(je,"host").map(({attrs:hA})=>({hostname:hA.hostname,maxContentLengthBytes:+hA.maxContentLengthBytes})),auth:je.attrs.auth,ttl:+je.attrs.ttl,fetchDate:new Date};return t.debug("fetched media conn"),Oe.hosts[0]&&(z=Oe.hosts[0].hostname),Oe})()),P},N=async(Ce,he,Ze,je)=>{if(!Ze||Ze.length===0)throw new qh.Boom("missing ids in receipt");let Oe={tag:"receipt",attrs:{id:Ze[0]}};(je==="read"||je==="read-self")&&(Oe.attrs.t=Ba().toString()),je==="sender"&&(bt(Ce)||qA(Ce))?(Oe.attrs.recipient=Ce,Oe.attrs.to=he):(Oe.attrs.to=Ce,he&&(Oe.attrs.participant=he)),je&&(Oe.attrs.type=je);let dA=Ze.slice(1);dA.length&&(Oe.content=[{tag:"list",attrs:{},content:dA.map(aA=>({tag:"item",attrs:{id:aA}}))}]),t.debug({attrs:Oe.attrs,messageIds:Ze},"sending receipt for messages"),await m(Oe)},k=async(Ce,he)=>{let Ze=Xae(Ce);for(let{jid:je,participant:Oe,messageIds:hA}of Ze)await N(je,Oe,hA,he)},V=async Ce=>{let Ze=(await y()).readreceipts==="all"?"read":"read-self";await k(Ce,Ze)},ee=async(Ce,he,Ze)=>{let je=[];he||t.debug("not using cache for devices");let Oe=[],hA=Ce.map(Be=>{let Re=yA(Be),Le=Re?.user,MA=Re?.device;return typeof MA=="number"&&MA>=0&&Le?(je.push({user:Le,device:MA,jid:Be}),null):(Be=uA(Be),{jid:Be,user:Le})}).filter(Be=>Be!==null),dA;if(he&&F.mget){let Be=hA.map(Re=>Re?.user).filter(Boolean);dA=await F.mget(Be)}for(let{jid:Be,user:Re}of hA)if(he){let Le=dA?.[Re]||(F.mget?void 0:await F.get(Re));if(Le){let MA=Le.map(He=>({...He,jid:Er(He.user,He.server,He.device)}));je.push(...MA),t.trace({user:Re},"using cache for devices")}else Oe.push(Be)}else Oe.push(Be);if(!Oe.length)return je;let aA=new Set;for(let Be of Oe)if(qA(Be)||oa(Be)){let Re=yA(Be)?.user;Re&&aA.add(Re)}let We=new Ls().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Be of Oe)We.withUser(new Fs().withId(Be));let bA=await g.executeUSyncQuery(We);if(bA){let Be=bA.list.filter(He=>!!He.lid);if(Be.length>0){t.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Be.map(He=>({lid:He.lid,pn:He.id})));try{let He=Be.map(_A=>_A.lid);He.length&&await Te(He,!0)}catch(He){t.warn({e:He,count:Be.length},"failed to assert sessions for newly mapped LIDs")}}let Re=nie(bA?.list,I.creds.me.id,I.creds.me.lid,Ze),Le={};for(let He of Re)Le[He.user]=Le[He.user]||[],Le[He.user]?.push(He);for(let[He,_A]of Object.entries(Le)){let at=aA.has(He);for(let DA of _A){let lt=at?Er(He,DA.server,DA.device):Er(DA.user,DA.server,DA.device);je.push({...DA,jid:lt}),t.debug({user:DA.user,device:DA.device,finalJid:lt,usedLid:at},"Processed device with LID priority")}}await q.mutex(async()=>{if(F.mset)await F.mset(Object.entries(Le).map(([He,_A])=>({key:He,value:_A})));else for(let He in Le)Le[He]&&await F.set(He,Le[He])});let MA={};for(let[He,_A]of Object.entries(Le))_A&&_A.length>0&&(MA[He]=_A.map(at=>at.device?.toString()||"0"));if(Object.keys(MA).length>0)try{await I.keys.set({"device-list":MA}),t.debug({userCount:Object.keys(MA).length},"stored user device lists for bulk migration")}catch(He){t.warn({error:He},"failed to store user device lists")}}return je},ie=(Ce,he)=>fe(Ce,{protocolMessage:{type:oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:he?.slice(0,30),labelTimestamp:Ba()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),Te=async(Ce,he)=>{let Ze=!1,je=[...new Set(Ce)],Oe=[];t.debug({jids:Ce},"assertSessions call with jids");for(let hA of je)!he&&(await B.validateSession(hA)).exists||Oe.push(hA);if(Oe.length){let hA=[...Oe.filter(aA=>!!qA(aA)||!!oa(aA)),...(await B.lidMapping.getLIDsForPNs(Oe.filter(aA=>!!bt(aA)||!!Cr(aA)))||[]).map(aA=>aA.lid)];t.debug({jidsRequiringFetch:Oe,wireJids:hA},"fetching sessions");let dA=await Q({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:OA},content:[{tag:"key",attrs:{},content:hA.map(aA=>{let We={jid:aA};return he&&(We.reason="identity"),{tag:"user",attrs:We}})}]});await oie(dA,B),Ze=!0}return Ze},se=async Ce=>{if(!I.creds.me?.id)throw new qh.Boom("Not authenticated");let he={protocolMessage:{peerDataOperationRequestMessage:Ce,type:oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},Ze=uA(I.creds.me.id);return await fe(Ze,he,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},Ne=async(Ce,he,Ze,je)=>{if(!Ce.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let Oe=await a(he,Ce),hA=Array.isArray(Oe)?Oe:Ce.map(Le=>({recipientJid:Le,message:Oe})),dA=!1,aA=I.creds.me.id,We=I.creds.me?.lid,bA=We?yA(We)?.user:null,Be=hA.map(async({recipientJid:Le,message:MA})=>{try{if(!Le)return null;let He=MA;if(je){let{user:lt}=yA(Le),{user:Ir}=yA(aA),UA=bA;(lt===Ir||UA&<===UA)&&!(Le===aA||We&&Le===We)&&(He=je,t.debug({jid:Le,targetUser:lt},"Using DSM for own device"))}let _A=Ld(He),at=Le;return await x.mutex(at,async()=>{let{type:lt,ciphertext:Ir}=await B.encryptMessage({jid:Le,data:_A});return lt==="pkmsg"&&(dA=!0),{tag:"to",attrs:{jid:Le},content:[{tag:"enc",attrs:{v:"2",type:lt,...Ze||{}},content:Ir}]}})}catch(He){return t.error({jid:Le,err:He},"Failed to encrypt for recipient"),null}}),Re=(await Promise.all(Be)).filter(Le=>Le!==null);if(Ce.length>0&&Re.length===0)throw new qh.Boom("All encryptions failed",{statusCode:500});return{nodes:Re,shouldIncludeDeviceIdentity:dA}},fe=async(Ce,he,{messageId:Ze,participant:je,additionalAttributes:Oe,additionalNodes:hA,useUserDevicesCache:dA,useCachedGroupMetadata:aA,statusJidList:We})=>{let bA=Jie(I.creds),Be=I.creds.me?.lid,Re=!!je?.jid,Le=Re,MA="status@broadcast",{user:He,server:_A}=yA(Ce),at=_A==="g.us",DA=Ce===MA,lt=_A==="lid",Ir=_A==="newsletter",UA=at||DA,le=Ce;Ze=Ze||Ur(bA),dA=dA!==!1,aA=aA!==!1&&!DA;let Qe=[],be=DA?MA:le,oA=[],lA=[],FA,Ut={deviceSentMessage:{destinationJid:be,message:he},messageContextInfo:he.messageContextInfo},st={};if(je){!at&&!DA&&(Oe={...Oe,device_fanout:"false"});let{user:fr,device:Ar}=yA(je.jid);lA.push({user:fr,device:Ar,jid:je.jid})}return await I.keys.transaction(async()=>{let fr=Ke(he);if(fr&&(st.mediatype=fr),Ir){let Ee=a?await a(he,[]):he,de=AX(Ee);oA.push({tag:"plaintext",attrs:{},content:de});let ye={tag:"message",attrs:{to:Ce,id:Ze,type:De(he),...Oe||{}},content:oA};t.debug({msgId:Ze},`sending newsletter message to ${Ce}`),await m(ye);return}if((Sa(he)?.pinInChatMessage||Sa(he)?.reactionMessage)&&(st["decrypt-fail"]="hide"),UA&&!Re){let[Ee,de]=await Promise.all([(async()=>{let AA=aA&&A?await A(Ce):void 0;return AA&&Array.isArray(AA?.participants)?t.trace({jid:Ce,participants:AA.participants.length},"using cached group metadata"):DA||(AA=await _(Ce)),AA})(),(async()=>!je&&!DA?(await I.keys.get("sender-key-memory",[Ce]))[Ce]||{}:{})()]),ye=Ee?Ee.participants.map(AA=>AA.id):[];Ee?.ephemeralDuration&&Ee.ephemeralDuration>0&&(Oe={...Oe,expiration:Ee.ephemeralDuration.toString()}),DA&&We&&ye.push(...We);let Je=await ee(ye,!!dA,!1);lA.push(...Je),at&&(Oe={...Oe,addressing_mode:Ee?.addressingMode||"lid"});let IA=await a(he);if(Array.isArray(IA))throw new qh.Boom("Per-jid patching is not supported in groups");let QA=Ld(IA);FA=IA;let vA=(Oe?.addressing_mode||Ee?.addressingMode||"lid")==="lid"&&Be?Be:bA,{ciphertext:YA,senderKeyDistributionMessage:$A}=await B.encryptGroupMessage({group:be,data:QA,meId:vA}),Pe=[];for(let AA of lA){let et=AA.jid;(!!!de[et]||je)&&!oa(et)&&!Cr(et)&&AA.device!==99&&(Pe.push(et),de[et]=!0)}if(Pe.length){t.debug({senderKeyJids:Pe},"sending new sender key");let AA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:$A,groupId:be}};await Te(Pe);let qr=await Ne(Pe,AA,st);Le=Le||qr.shouldIncludeDeviceIdentity,Qe.push(...qr.nodes)}oA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...st},content:YA}),await I.keys.set({"sender-key-memory":{[Ce]:de}})}else{let Ee=bA;lt&&Be?(Ee=Be,t.debug({to:Ce,ownId:Ee},"Using LID identity for @lid conversation")):t.debug({to:Ce,ownId:Ee},"Using PN identity for @s.whatsapp.net conversation");let{user:de}=yA(Ee);if(!je){let AA=await a(he,[Ce]);FA=Array.isArray(AA)?AA.find(et=>et.recipientJid===Ce)||AA[0]:AA}if(!Re){let AA=lt?"lid":"s.whatsapp.net";if(lA.push({user:He,device:0,jid:Er(He,AA,0)}),He!==de){let et=lt?"lid":"s.whatsapp.net",qr=lt&&Be?yA(Be).user:yA(bA).user;lA.push({user:qr,device:0,jid:Er(qr,et,0)})}if(Oe?.category!=="peer"){lA.length=0;let et=lt&&Be?Er(yA(Be)?.user,"lid",void 0):Er(yA(bA)?.user,"s.whatsapp.net",void 0),qr=await ee([et,Ce],!0,!1);lA.push(...qr),t.debug({deviceCount:lA.length,devices:lA.map(tr=>`${tr.user}:${tr.device}@${yA(tr.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let ye=[],Je=[],IA=[],{user:QA}=yA(bA),{user:XA}=Be?yA(Be):{user:null};for(let{user:AA,jid:et}of lA){if(et===bA||Be&&et===Be){t.debug({jid:et,meId:bA,meLid:Be},"Skipping exact sender device (whatsmeow pattern)");continue}AA===QA||AA===XA?Je.push(et):IA.push(et),ye.push(et)}await Te(ye);let[{nodes:vA,shouldIncludeDeviceIdentity:YA},{nodes:$A,shouldIncludeDeviceIdentity:Pe}]=await Promise.all([Ne(Je,Ut||he,st),Ne(IA,he,st,Ut)]);Qe.push(...vA),Qe.push(...$A),(Je.length>0||IA.length>0)&&(st.phash=j9([...Je,...IA])),Le=Le||YA||Pe}if(Re){let Ee=qA(je.jid),de=Mt(je.jid,Ee?Be:bA),ye=he;if(UA){let XA;if(Be&&await B.hasSenderKey({group:be,meId:Be})?XA=Be:await B.hasSenderKey({group:be,meId:bA})&&(XA=bA),XA)try{let vA=await B.getSenderKeyDistributionMessage({group:be,meId:XA});ye={...he,senderKeyDistributionMessage:{groupId:be,axolotlSenderKeyDistributionMessage:vA}}}catch(vA){t.warn({err:vA,jid:be},"failed to build SKDM for retry, sending without it")}}let Je=de?Ld({deviceSentMessage:{destinationJid:be,message:ye}}):Ld(ye),{type:IA,ciphertext:QA}=await B.encryptMessage({data:Je,jid:je.jid});oA.push({tag:"enc",attrs:{v:"2",type:IA,count:je.count.toString()},content:QA})}if(Qe.length)if(Oe?.category==="peer"){let Ee=Qe[0]?.content?.[0];Ee&&oA.push(Ee)}else oA.push({tag:"participants",attrs:{},content:Qe});let Ar={tag:"message",attrs:{id:Ze,to:be,type:De(he),...Oe||{}},content:oA};if(je?Fr(be)?(Ar.attrs.to=be,Ar.attrs.participant=je.jid):Mt(je.jid,bA)?(Ar.attrs.to=je.jid,Ar.attrs.recipient=be):Ar.attrs.to=je.jid:Ar.attrs.to=be,Le&&(Ar.content.push({tag:"device-identity",attrs:{},content:qB(I.creds.account,!0)}),t.debug({jid:Ce},"adding device identity")),!Ir&&!Re&&FA?.messageContextInfo?.messageSecret&&bO(FA))try{let Ee=Ld(FA),de={id:Ze,fromMe:!0,remoteJid:be,participant:je?.jid},ye=await qae(Ee,FA,de);ye&&(Ar.content.push(ye),t.trace({jid:Ce},"added reporting token to message"))}catch(Ee){t.warn({jid:Ce,trace:Ee?.stack},"failed to attach reporting token")}let oo=Oe?.category==="peer",Gi=!at&&!Re&&!DA&&!Ir&&!oo,Ae=Gi?await ks(be,H):be,X=(Gi?await I.keys.get("tctoken",[Ae]):{})[Ae],re=X?.token;if(re?.length&&kl(X?.timestamp)){t.debug({jid:be,timestamp:X?.timestamp},"tctoken expired, clearing"),re=void 0;let Ee=X?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:X.senderTimestamp}:null;try{await I.keys.set({tctoken:{[Ae]:Ee}})}catch(de){t.debug({jid:be,err:de?.message},"failed to persist tctoken expiry cleanup")}}re?.length&&g.serverProps.privacyTokenOn1to1&&Ar.content.push({tag:"tctoken",attrs:{},content:re}),hA&&hA.length>0&&Ar.content.push(...hA),t.debug({msgId:Ze},`sending message to ${Qe.length} devices`),await m(Ar);let ne=!!Sa(he)?.protocolMessage,Se=be===g9||I9(be)||Nd(be);if(Gi&&!ne&&!Se&&Zie(X?.senderTimestamp)&&!j.has(Ae)){j.add(Ae);let Ee=Ba(),de=B.lidMapping.getPNForLID.bind(B.lidMapping);XB(be,g.serverProps.lidTrustedTokenIssueToLid,H,de).then(ye=>rA([ye],Ee)).then(async ye=>{await kh({result:ye,fallbackJid:Ae,keys:I.keys,getLIDForPN:H});let IA=(await I.keys.get("tctoken",[Ae]))[Ae],QA=await Rh(I.keys,[Ae]);await I.keys.set({tctoken:{[Ae]:{token:Buffer.alloc(0),...IA,senderTimestamp:Ee},...QA}})}).catch(ye=>{t.debug({jid:be,err:ye?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{j.delete(Ae)})}J&&!je&&J.addRecentMessage(be,Ze,he)},bA),Ze},De=Ce=>{let he=Sa(Ce);return he?he.reactionMessage||he.encReactionMessage?"reaction":he.pollCreationMessage||he.pollCreationMessageV2||he.pollCreationMessageV3||he.pollUpdateMessage?"poll":he.eventMessage?"event":Ke(he)!==""?"media":"text":"text"},Ke=Ce=>Ce.imageMessage?"image":Ce.videoMessage?Ce.videoMessage.gifPlayback?"gif":"video":Ce.audioMessage?Ce.audioMessage.ptt?"ptt":"audio":Ce.contactMessage?"vcard":Ce.documentMessage?"document":Ce.contactsArrayMessage?"contact_array":Ce.liveLocationMessage?"livelocation":Ce.stickerMessage?"sticker":Ce.listMessage?"list":Ce.listResponseMessage?"list_response":Ce.buttonsResponseMessage?"buttons_response":Ce.orderMessage?"order":Ce.productMessage?"product":Ce.interactiveResponseMessage?"native_flow_response":Ce.groupInviteMessage?"url":"",rA=async(Ce,he)=>{let Ze=(he??Ba()).toString();return await Q({tag:"iq",attrs:{to:OA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:Ce.map(Oe=>({tag:"token",attrs:{jid:uA(Oe),t:Ze,type:"trusted_contact"}}))}]})},ve=Fae(n,U),iA=LG(c,"messages.media-update");return R(()=>{!n.userDevicesCache&&F.close&&F.close(),P=void 0,J&&J.clear()}),{...g,userDevicesCache:F,devicesMutex:q,issuePrivacyTokens:rA,assertSessions:Te,relayMessage:fe,sendReceipt:N,sendReceipts:k,readMessages:V,refreshMediaConn:U,getMediaHost:()=>z,waUploadToServer:ve,fetchPrivacySettings:y,sendPeerDataOperationMessage:se,createParticipantNodes:Ne,getUSyncDevices:ee,messageRetryManager:J,updateMemberLabel:ie,updateMediaMessage:async Ce=>{let he=$ae(Ce.message),Ze=he.mediaKey,je=I.creds.me.id,Oe=Uae(Ce.key,Ze,je),hA;if(await Promise.all([m(Oe),iA(async dA=>{let aA=dA.find(We=>We.key.id===Ce.key.id);if(aA){if(aA.error)hA=aA.error;else try{let We=Kae(aA.media,Ze,aA.key.id);if(We.result!==oe.MediaRetryNotification.ResultType.SUCCESS){let bA=oe.MediaRetryNotification.ResultType[We.result];throw new qh.Boom(`Media re-upload failed by device (${bA})`,{data:We,statusCode:XL(We.result)||404})}he.directPath=We.directPath,he.url=HB(he.directPath,z),t.debug({directPath:We.directPath,key:aA.key},"media update successful")}catch(We){hA=We}return!0}})]),hA)throw hA;return c.emit("messages.update",[{key:Ce.key,update:{message:Ce.message}}]),Ce},sendMessage:async(Ce,he,Ze={})=>{let je=I.creds.me.id;if(typeof he=="object"&&"disappearingMessagesInChat"in he&&typeof he.disappearingMessagesInChat<"u"&&Fr(Ce)){let{disappearingMessagesInChat:Oe}=he;await T(Ce,typeof Oe=="boolean"?Oe?jB:0:Oe)}else{let Oe=await Wae(Ce,he,{logger:t,userJid:je,getUrlInfo:Le=>Wie(Le,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:t,uploadImage:i?ve:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:ve,mediaCache:n.mediaCache,options:n.options,messageId:Ur(g.user?.id),...Ze}),hA="event"in he&&!!he.event,dA="delete"in he&&!!he.delete,aA="edit"in he&&!!he.edit,We="pin"in he&&!!he.pin,bA="poll"in he&&!!he.poll,Be={},Re=[];return dA?Fr(he.delete?.remoteJid)&&!he.delete?.fromMe?Be.edit="8":Be.edit="7":aA?Be.edit="1":We?Be.edit="2":bA?Re.push({tag:"meta",attrs:{polltype:"creation"}}):hA&&Re.push({tag:"meta",attrs:{event_type:"creation"}}),await fe(Ce,Oe.message,{messageId:Oe.key.id,useCachedGroupMetadata:Ze.useCachedGroupMetadata,additionalAttributes:Be,statusJidList:Ze.statusJidList,additionalNodes:Re}),n.emitOwnEvents&&process.nextTick(async()=>{await d.mutex(()=>f(Oe,"append"))}),Oe}}}};var VVe=new Set(Object.values(Dc));function WVe(n){return typeof n=="string"&&VVe.has(n)}var qse=n=>{let{logger:t,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,r=Jse(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:I,ws:d,messageMutex:B,notificationMutex:f,receiptMutex:Q,signalRepository:y,query:m,upsertMessage:_,resyncAppState:T,onUnexpectedError:R,assertSessions:H,sendNode:j,relayMessage:F,sendReceipt:q,uploadPreKeys:J,sendPeerDataOperationMessage:x,messageRetryManager:P,registerSocketEndHandler:z,issuePrivacyTokens:U,fetchAccountReachoutTimelock:N,placeholderResendCache:k}=r,V=y.lidMapping.getLIDForPN.bind(y.lidMapping),ee=Fg(),ie=n.msgRetryCounterCache||new Rg({stdTTL:$c.MSG_RETRY,useClones:!1}),Te=n.callOfferCache||new Rg({stdTTL:$c.CALL_OFFER,useClones:!1}),se=new Rg({stdTTL:5,useClones:!1}),Ne=!1,fe=async(Ae,W,X)=>{if(!I.creds.me?.id)throw new If.Boom("Not authenticated");let re={historySyncOnDemandRequest:{chatJid:W.remoteJid,oldestMsgFromMe:W.fromMe,oldestMsgId:W.id,oldestMsgTimestampMs:X,onDemandMsgCount:Ae},peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return x(re)},De=async(Ae,W)=>{if(!I.creds.me?.id)throw new If.Boom("Not authenticated");if(await k.get(Ae?.id)){t.debug({messageKey:Ae},"already requested resend");return}else await k.set(Ae?.id,W||!0);if(await zu(2e3),!await k.get(Ae?.id))return t.debug({messageKey:Ae},"message received while resend requested"),"RESOLVED";let X={placeholderMessageResendRequest:[{messageKey:Ae}],peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await k.get(Ae?.id)&&(t.debug({messageKey:Ae},"PDO message without response after 8 seconds. Phone possibly offline"),await k.del(Ae?.id))},8e3),x(X)},Ke=async Ae=>{let W=Ie(Ae,"update");if(W){let X=W.attrs?.op_name;if(!X){t.warn({node:Bn(Ae)},"mex notification missing op_name, fallback to legacy"),await iA(Ae);return}let re;try{re=JSON.parse(W.content.toString())}catch(Se){t.error({err:Se,opName:X},"failed to parse mex notification JSON");return}if(re.errors?.length){t.warn({errors:re.errors,opName:X},"mex notification has GQL errors");return}let ne=re.data;if(!ne){t.warn({opName:X},"mex notification has null data");return}switch(t.debug({opName:X},"processing mex notification"),X){case"NotificationUserReachoutTimelockUpdate":rA(ne);break;case"MessageCappingInfoNotification":ve(ne);break;case"NotificationNewsletterUpdate":case"NotificationLinkedProfilesUpdates":case"NotificationNewsletterAdminPromote":case"NotificationNewsletterAdminDemote":case"NotificationNewsletterUserSettingChange":case"NotificationNewsletterJoin":case"NotificationNewsletterLeave":case"NotificationNewsletterStateChange":case"NotificationNewsletterAdminMetadataUpdate":case"NotificationNewsletterOwnerUpdate":case"NotificationNewsletterAdminInviteRevoke":case"NotificationNewsletterWamoSubStatusChange":case"NotificationNewsletterBlockUser":case"NotificationNewsletterPaidPartnership":case"NotificationNewsletterMilestone":case"NewsletterResponseStateUpdate":await iA(Ae);break;default:t.debug({opName:X},"unhandled mex notification");break}return}await iA(Ae)},rA=Ae=>{let W=Ae.xwa2_notify_account_reachout_timelock;if(!W){t.warn("reachout timelock notification missing payload");return}if(!W.is_active){t.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:Dc.DEFAULT}});return}let X=W.time_enforcement_ends?new Date(parseInt(W.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),re=WVe(W.enforcement_type)?W.enforcement_type:Dc.DEFAULT;t.info({enforcementType:re,timeEnforcementEnds:X},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:X,enforcementType:re}})},ve=Ae=>{let W=Ae.xwa2_notify_new_chat_messages_capping_info_update;if(!W){t.warn("message capping notification missing payload");return}t.info({payload:W},"received message capping update"),c.emit("message-capping.update",W)},iA=async Ae=>{let W=Ie(Ae,"mex"),X=W?.content?null:Ie(Ae,"update")||ls(Ae)[0],re=W?.content?W:X;if(!re?.content){t.warn({node:Bn(Ae)},"invalid mex newsletter notification");return}let ne;try{let de=re.content;if(Array.isArray(de)){t.warn({payloadNode:re},"invalid mex newsletter notification payload format");return}let ye=typeof de=="string"?Buffer.from(de,"binary"):Buffer.from(de);ne=JSON.parse(ye.toString())}catch(de){t.error({err:de,node:Bn(Ae)},"failed to parse mex newsletter notification");return}let Se=ne?.operation??re?.attrs?.op_name,Ee=ne?.updates;if(!Ee){let de=ne?.data?.xwa2_notify_linked_profiles;de&&(Ee=[de])}if(!Ee||!Se){t.warn({data:ne},"invalid mex newsletter notification content");return}switch(t.info({operation:Se,updates:Ee},"got mex newsletter notification"),Se){case"NotificationNewsletterUpdate":for(let de of Ee)de.jid&&de.settings&&Object.keys(de.settings).length>0&&c.emit("newsletter-settings.update",{id:de.jid,update:de.settings});break;case"NotificationNewsletterAdminPromote":for(let de of Ee)de.jid&&de.user&&c.emit("newsletter-participants.update",{id:de.jid,author:Ae.attrs.from,user:de.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let de of Ee){let ye=de?.jid,Je=Array.isArray(de?.added_profiles)?de.added_profiles:[],IA=[];for(let QA of Je){let XA=typeof QA=="string"?QA:QA?.pn??QA?.jid??null;if(ye&&XA){let vA={lid:ye,pn:XA};c.emit("lid-mapping.update",vA),IA.push(vA)}}await y.lidMapping.storeLIDPNMappings(IA)}break;default:t.info({operation:Se,data:ne},"unhandled mex newsletter notification");break}},Ce=async Ae=>{let W=Ae.attrs.from,X=ls(Ae),re=Ae.attrs.participant;for(let ne of X)switch(t.debug({from:W,child:ne},"got newsletter notification"),ne.tag){case"reaction":{let Se={id:W,server_id:ne.attrs.message_id,reaction:{code:jA(ne,"reaction"),count:1}};c.emit("newsletter.reaction",Se);break}case"view":{let Se={id:W,server_id:ne.attrs.message_id,count:parseInt(ne.content?.toString()||"0",10)};c.emit("newsletter.view",Se);break}case"participant":{let Se={id:W,author:re,user:ne.attrs.jid,action:ne.attrs.action,new_role:ne.attrs.role};c.emit("newsletter-participants.update",Se);break}case"update":{let Se=Ie(ne,"settings");if(Se){let Ee={},de=Ie(Se,"name");de?.content&&(Ee.name=de.content.toString());let ye=Ie(Se,"description");ye?.content&&(Ee.description=ye.content.toString()),c.emit("newsletter-settings.update",{id:W,update:Ee})}break}case"message":{let Se=Ie(ne,"plaintext");if(Se?.content)try{let Ee=typeof Se.content=="string"?Buffer.from(Se.content,"binary"):Buffer.from(Se.content),de=oe.Message.decode(Ee).toJSON(),ye=oe.WebMessageInfo.fromObject({key:{remoteJid:W,id:ne.attrs.message_id||ne.attrs.server_id,fromMe:!1},message:de,messageTimestamp:+ne.attrs.t}).toJSON();await _(ye,"append"),t.debug("Processed plaintext newsletter message")}catch(Ee){t.error({error:Ee},"Failed to decode plaintext newsletter message")}break}default:t.warn({node:Ae,child:ne},"Unknown newsletter notification child");break}},he=async(Ae,W)=>{let X=ioe(Ae,W,I.creds.me.id);t.debug({recv:{tag:Ae.tag,attrs:Ae.attrs},sent:X.attrs},"sent ack"),await j(X)},Ze=async(Ae,W)=>{let X={tag:"call",attrs:{from:I.creds.me.id,to:W},content:[{tag:"reject",attrs:{"call-id":Ae,"call-creator":W,count:"0"},content:void 0}]};await m(X)},je=async(Ae,W=!1)=>{let{fullMessage:X}=HG(Ae,I.creds.me.id,I.creds.me.lid||""),{key:re}=X,ne=re.id;if(P){if(P.hasExceededMaxRetries(ne)){t.debug({msgId:ne},"reached retry limit with new retry manager, clearing"),P.markRetryFailed(ne);return}let YA=P.incrementRetryCount(ne),$A=`${ne}:${re?.participant}`;await ie.set($A,YA)}else{let YA=`${ne}:${re?.participant}`,$A=await ie.get(YA)||0;if($A>=i){t.debug({retryCount:$A,msgId:ne},"reached retry limit, clearing"),await ie.del(YA);return}$A+=1,await ie.set(YA,$A)}let Se=`${ne}:${re?.participant}`,Ee=await ie.get(Se)||1,{account:de,signedPreKey:ye,signedIdentityKey:Je}=I.creds,IA=Ae.attrs.from,QA=!1,XA="";if(A&&P&&Ee>1)try{let YA=y.jidToSignalProtocolAddress(IA),$A=await y.validateSession(IA),Pe=P.shouldRecreateSession(IA,$A.exists);QA=Pe.recreate,XA=Pe.reason,QA&&(t.debug({fromJid:IA,retryCount:Ee,reason:XA},"recreating session for retry"),await I.keys.set({session:{[YA]:null}}),W=!0)}catch(YA){t.warn({error:YA,fromJid:IA},"failed to check session recreation")}if(Ee<=2)if(P)P.schedulePhoneRequest(ne,async()=>{try{let YA=await De(re);t.debug(`sendRetryRequest: requested placeholder resend (${YA}) for message ${ne} (scheduled)`)}catch(YA){t.warn({error:YA,msgId:ne},"failed to send scheduled phone request")}});else{let YA=await De(re);t.debug(`sendRetryRequest: requested placeholder resend for message ${YA}`)}let vA=qB(de,!0);await I.keys.transaction(async()=>{let YA={tag:"receipt",attrs:{id:ne,type:"retry",to:Ae.attrs.from},content:[{tag:"retry",attrs:{count:Ee.toString(),id:Ae.attrs.id,t:Ae.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:yg(I.creds.registrationId)}]};if(Ae.attrs.recipient&&(YA.attrs.recipient=Ae.attrs.recipient),Ae.attrs.participant&&(YA.attrs.participant=Ae.attrs.participant),Ee>1||W||QA){let{update:$A,preKeys:Pe}=await s2(I,1),[AA]=Object.keys(Pe),et=Pe[+AA];YA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Qg)},{tag:"identity",attrs:{},content:Je.public},n2(et,+AA),JB(ye),{tag:"device-identity",attrs:{},content:vA}]}),c.emit("creds.update",$A)}await j(YA),t.info({msgAttrs:Ae.attrs,retryCount:Ee},"sent retry receipt")},I?.creds?.me?.id||"sendRetryRequest")},Oe=new Set,hA=Ae=>{(async()=>{let W=uA(Ae),X=await ks(W,V),ne=(await I.keys.get("tctoken",[X]))?.[X]?.senderTimestamp;if(ne==null||kl(ne))return;t.debug({jid:W,senderTimestamp:ne},"identity changed, re-issuing tctoken");let Se=y.lidMapping.getPNForLID.bind(y.lidMapping),Ee=await XB(W,r.serverProps.lidTrustedTokenIssueToLid,V,Se),de=await U([Ee],ne);await kh({result:de,fallbackJid:X,keys:I.keys,getLIDForPN:V,onNewJidStored:_A})})().catch(W=>{t.debug({jid:Ae,err:W?.message},"failed to re-issue tctoken after identity change")})},dA=async Ae=>{if(Ae.attrs.from===OA){let X=Ae.attrs.id;if(X&&Oe.has(X))return;let ne=+Ie(Ae,"count").attrs.value,Se=ne{let re=Ae.attrs.participant,ne=Ae.attrs.participant_pn,Se=Ae.attrs.participant_username,Ee=Ie(W,"participant")?.attrs?.jid||re,de=Ie(W,"participant")?.attrs?.phone_number||ne;switch(W?.tag){case"create":let ye=Jh(W);X.messageStubType=RA.GROUP_CREATE,X.messageStubParameters=[ye.subject],X.key={participant:ye.owner,participantAlt:ye.ownerPn},c.emit("chats.upsert",[{id:ye.id,name:ye.subject,conversationTimestamp:ye.creation}]),c.emit("groups.upsert",[{...ye,author:re,authorPn:ne,authorUsername:Se}]);break;case"ephemeral":case"not_ephemeral":X.message={protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(W.attrs.expiration||0)}};break;case"modify":let Je=PA(W,"participant").map(Pe=>Pe.attrs.jid);X.messageStubParameters=Je||[],X.messageStubType=RA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let IA=`GROUP_PARTICIPANT_${W.tag.toUpperCase()}`;X.messageStubType=RA[IA];let QA=PA(W,"participant").map(({attrs:Pe})=>({id:Pe.jid,phoneNumber:qA(Pe.jid)&&bt(Pe.phone_number)?Pe.phone_number:void 0,lid:bt(Pe.jid)&&qA(Pe.lid)?Pe.lid:void 0,username:Pe.participant_username||Pe.username||void 0,admin:Pe.type||null}));QA.length===1&&(Mt(QA[0].id,re)||Mt(QA[0].id,ne))&&W.tag==="remove"&&(X.messageStubType=RA.GROUP_PARTICIPANT_LEAVE),X.messageStubParameters=QA.map(Pe=>JSON.stringify(Pe));break;case"subject":X.messageStubType=RA.GROUP_CHANGE_SUBJECT,X.messageStubParameters=[W.attrs.subject];break;case"description":let XA=Ie(W,"body")?.content?.toString();X.messageStubType=RA.GROUP_CHANGE_DESCRIPTION,X.messageStubParameters=XA?[XA]:void 0;break;case"announcement":case"not_announcement":X.messageStubType=RA.GROUP_CHANGE_ANNOUNCE,X.messageStubParameters=[W.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":X.messageStubType=RA.GROUP_CHANGE_RESTRICT,X.messageStubParameters=[W.tag==="locked"?"on":"off"];break;case"invite":X.messageStubType=RA.GROUP_CHANGE_INVITE_LINK,X.messageStubParameters=[W.attrs.code];break;case"member_add_mode":let vA=W.content;vA&&(X.messageStubType=RA.GROUP_MEMBER_ADD_MODE,X.messageStubParameters=[vA.toString()]);break;case"membership_approval_mode":let YA=Ie(W,"group_join");YA&&(X.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,X.messageStubParameters=[YA.attrs.state]);break;case"created_membership_requests":X.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ee,pn:de}),"created",W.attrs.request_method];break;case"revoked_membership_requests":let $A=Mt(Ee,re);X.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ee,pn:de}),$A?"revoked":"rejected"];break}},We=async Ae=>{let[W]=ls(Ae),X=uA(Ae.attrs.from);if(!W){t.debug({from:X},"devices notification missing child, skipping");return}let re=W.tag,ne=W.attrs.device_hash,Se=PA(W,"device");if(Mt(X,I.creds.me.id)||Mt(X,I.creds.me.lid)){let de=Se.map(ye=>ye.attrs.jid);t.info({deviceJids:de},"got my own devices")}if(!Se.length){t.debug({from:X,tag:re},"no devices in notification, skipping");return}let Ee=[];for(let de of Se){let ye=de.attrs.jid;if(!ye)continue;let Je=yA(ye);if(!Je){t.debug({jid:ye},"failed to decode device jid, skipping");continue}Ee.push({jid:ye,user:Je.user,server:Je.server,device:Je.device})}Ee.length&&await g.mutex(async()=>{let de=new Map;for(let ye of Ee){let Je=de.get(ye.user)||[];Je.push(ye),de.set(ye.user,Je)}for(let[ye,Je]of de){if(re==="update"){t.debug({user:ye},`${ye}'s device list updated, dropping cached devices`),await s?.del(ye);continue}re==="remove"&&await y.deleteSession(Je.map(vA=>vA.jid));let IA=await s?.get(ye)||[];if(!IA.length){t.debug({user:ye,tag:re},"device list not cached, deferring to USync refresh");continue}let QA=new Set(Je.map(vA=>vA.device)),XA;switch(re){case"add":t.info({deviceHash:ne,count:Je.length},"devices added"),XA=[...IA.filter(vA=>!QA.has(vA.device)),...Je.map(vA=>({user:vA.user,server:vA.server,device:vA.device}))];break;case"remove":t.info({deviceHash:ne,count:Je.length},"devices removed"),XA=IA.filter(vA=>!QA.has(vA.device));break;default:t.debug({tag:re},"Unknown device list change tag");continue}XA.length===0?await s?.del(ye):await s?.set(ye,XA)}})},bA=async Ae=>{let W={},[X]=ls(Ae),re=Ae.attrs.type,ne=uA(Ae.attrs.from);switch(re){case"newsletter":await Ce(Ae);break;case"mex":await Ke(Ae);break;case"w:gp2":aA(Ae,X,W);break;case"mediaretry":let Se=Hae(Ae);c.emit("messages.media-update",[Se]);break;case"encrypt":await dA(Ae);break;case"devices":try{await We(Ae)}catch(so){t.error({error:so,node:Ae},"failed to handle devices notification")}break;case"server_sync":let Ee=Ie(Ae,"collection");if(Ee){let so=Ee.attrs.name;await T([so],!1)}break;case"picture":let de=Ie(Ae,"set"),ye=Ie(Ae,"delete");if(c.emit("contacts.update",[{id:uA(Ae?.attrs?.from)||(de||ye)?.attrs?.hash||"",imgUrl:de?"changed":"removed"}]),Fr(ne)){let so=de||ye;W.messageStubType=RA.GROUP_CHANGE_ICON,de&&(W.messageStubParameters=[de.attrs.id]),W.participant=so?.attrs.author,W.key={...W.key||{},participant:de?.attrs.author}}break;case"account_sync":if(X.tag==="disappearing_mode"){let so=+X.attrs.duration,Yl=+X.attrs.t;t.info({newDuration:so},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...I.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:so,ephemeralSettingTimestamp:Yl}}})}else if(X.tag==="blocklist"){let so=PA(X,"item");for(let{attrs:Yl}of so){let kb=[Yl.jid],vb=Yl.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:kb,type:vb})}}break;case"link_code_companion_reg":let Je=Ie(Ae,"link_code_companion_reg"),IA=lt(ua(Je,"link_code_pairing_ref")),QA=lt(ua(Je,"primary_identity_pub")),XA=lt(ua(Je,"link_code_pairing_wrapped_primary_ephemeral_pub")),vA=await DA(XA),YA=ur.sharedKey(I.creds.pairingEphemeralKeyPair.private,vA),$A=LU(32),Pe=LU(32),AA=yn(YA,32,{salt:Pe,info:"link_code_pairing_key_bundle_encryption_key"}),et=Buffer.concat([Buffer.from(I.creds.signedIdentityKey.public),QA,$A]),qr=LU(12),tr=nl(et,AA,qr,Buffer.alloc(0)),no=Buffer.concat([Pe,qr,tr]),Nb=ur.sharedKey(I.creds.signedIdentityKey.private,QA),Rb=Buffer.concat([YA,Nb,$A]);I.creds.advSecretKey=Buffer.from(yn(Rb,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:OA,type:"set",id:r.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:I.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:no},{tag:"companion_identity_public",attrs:{},content:I.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:IA}]}]}),I.creds.registered=!0,c.emit("creds.update",I.creds);break;case"privacy_token":await at(Ae);break}if(Object.keys(W).length)return W},Be=new Set,Re=(async()=>{try{let Ae=await GO(I.keys);for(let W of Ae)Be.add(W);t.debug({count:Be.size},"loaded tctoken index")}catch(Ae){t.warn({err:Ae?.message},"failed to load tctoken index")}})(),Le;async function MA(){Le&&(clearTimeout(Le),Le=void 0);let Ae=await Rh(I.keys,Be);return I.keys.set({tctoken:Ae})}function He(){Le&&clearTimeout(Le),Le=setTimeout(()=>{Le=void 0,MA().catch(Ae=>{t.warn({err:Ae?.message},"failed to save tctoken index")})},5e3)}function _A(Ae){Ae&&Ae!==eI&&!Be.has(Ae)&&(Be.add(Ae),He())}let at=async Ae=>{if(!Ie(Ae,"tokens"))return;let X=uA(Ae.attrs.from),ne=(Ae.attrs.sender_lid&&qA(uA(Ae.attrs.sender_lid))?uA(Ae.attrs.sender_lid):void 0)??await ks(X,V);t.debug({from:X,storageJid:ne},"processing privacy token notification"),await kh({result:Ae,fallbackJid:ne,keys:I.keys,getLIDForPN:V,onNewJidStored:_A})};async function DA(Ae){let W=lt(Ae),X=W.slice(0,32),re=await yD(I.creds.pairingCode,X),ne=W.slice(32,48),Se=W.slice(48,80);return F9(Se,re,ne)}function lt(Ae){if(Ae===void 0)throw new If.Boom("Invalid buffer",{statusCode:400});return Ae instanceof Buffer?Ae:Buffer.from(Ae)}let Ir=async(Ae,W)=>{let X=`${Ae}:${W}`;return(await ie.get(X)||0){let X=`${Ae}:${W}`,re=(await ie.get(X)||0)+1;await ie.set(X,re)},le=async(Ae,W,X,re)=>{let ne=Ae.remoteJid,Se=Ae.participant||ne,Ee=+X.attrs.count||1,de=W[0],ye=[];for(let Pe of W){let AA;if(P){let et=P.getRecentMessage(ne,Pe);et&&(AA=et.message,t.debug({jid:ne,id:Pe},"found message in retry cache"),P.markRetrySuccess(Pe))}AA||(AA=await e({...Ae,id:Pe}),AA&&(t.debug({jid:ne,id:Pe},"found message via getMessage"),P&&P.markRetrySuccess(Pe))),ye.push(AA)}let Je=!yA(Se)?.device,IA=y.jidToSignalProtocolAddress(Se),QA=!1,XA=iie(re);if(XA)try{await y.injectE2ESession({jid:Se,session:XA}),QA=!0,t.debug({participant:Se,retryCount:Ee},"injected session from retry receipt key bundle")}catch(Pe){t.warn({error:Pe,participant:Se},"failed to inject session from retry receipt")}if(!QA){let Pe=Oc(re,"registration",4);if(typeof Pe=="number"&&Number.isInteger(Pe)){let AA=await y.getSessionInfo(Se);AA&&AA.registrationId!==0&&AA.registrationId!==Pe&&(t.info({participant:Se,stored:AA.registrationId,received:Pe},"reg id mismatch on retry without bundle, deleting session"),await I.keys.set({session:{[IA]:null}}))}}let vA=2;if(de&&P){let Pe=await y.getSessionInfo(Se);Pe&&(Ee===vA?P.saveBaseKey(IA,de,Pe.baseKey):Ee>vA&&(P.hasSameBaseKey(IA,de,Pe.baseKey)&&(t.warn({participant:Se,retryCount:Ee},"base key collision on retry, forcing fresh session"),await I.keys.set({session:{[IA]:null}})),P.deleteBaseKey(IA,de)))}let YA=!1,$A="";if(A&&P&&Ee>1&&!QA)try{let Pe=await y.validateSession(Se),AA=P.shouldRecreateSession(Se,Pe.exists);YA=AA.recreate,$A=AA.reason,YA&&(t.debug({participant:Se,retryCount:Ee,reason:$A},"recreating session for outgoing retry"),await I.keys.set({session:{[IA]:null}}))}catch(Pe){t.warn({error:Pe,participant:Se},"failed to check session recreation for outgoing retry")}QA||await H([Se],!0),Fr(ne)&&await I.keys.set({"sender-key-memory":{[ne]:null}}),t.debug({participant:Se,sendToAll:Je,shouldRecreateSession:YA,recreateReason:$A,injectedFromBundle:QA},"prepared session for retry resend");for(let[Pe,AA]of ye.entries())if(W[Pe])if(AA&&await Ir(W[Pe],Se)){await UA(W[Pe],Se);let et={messageId:W[Pe]};Je?et.useUserDevicesCache=!1:et.participant={jid:Se,count:+X.attrs.count},await F(Ae.remoteJid,AA,et)}else t.debug({jid:Ae.remoteJid,id:W[Pe]},"recv retry request, but message not available")},Qe=async Ae=>{let{attrs:W,content:X}=Ae,re=W.from.includes("lid"),ne=Mt(W.participant||W.from,re?I.creds.me?.lid:I.creds.me?.id),Se=!ne||Fr(W.from)?W.from:W.recipient,Ee=!W.recipient||(W.type==="retry"||W.type==="sender")&&ne,de={remoteJid:Se,id:"",fromMe:Ee,participant:W.participant},ye=[W.id];if(Array.isArray(X)){let Je=PA(X[0],"item");ye.push(...Je.map(IA=>IA.attrs.id))}try{await Promise.all([Q.mutex(async()=>{let Je=W9(W.type);if(typeof Je<"u"&&(Je>=oe.WebMessageInfo.Status.SERVER_ACK||!ne))if(Fr(Se)||Bg(Se)){if(W.participant){let IA=Je===oe.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",ye.map(QA=>({key:{...de,id:QA},receipt:{userJid:uA(W.participant),[IA]:+W.t}})))}}else c.emit("messages.update",ye.map(IA=>({key:{...de,id:IA},update:{status:Je,messageTimestamp:Lr(+(W.t??0))}})));if(W.type==="retry"){de.participant=de.participant||W.from;let IA=Ie(Ae,"retry");if(ye[0]&&de.participant&&await Ir(ye[0],de.participant))if(de.fromMe)try{await UA(ye[0],de.participant),t.debug({attrs:W,key:de},"recv retry request"),await le(de,ye,IA,Ae)}catch(QA){t.error({key:de,ids:ye,trace:QA instanceof Error?QA.stack:"Unknown error"},"error in sending message again")}else t.info({attrs:W,key:de},"recv retry for not fromMe message");else t.info({attrs:W,key:de},"will not send message again, as sent too many times")}})])}finally{await he(Ae).catch(Je=>t.error({ackErr:Je},"failed to ack receipt"))}},be=async Ae=>{let W=Ae.attrs.from;try{await Promise.all([f.mutex(async()=>{let X=await bA(Ae);if(X){let re=Mt(Ae.attrs.participant||W,I.creds.me.id),{senderAlt:ne,addressingMode:Se}=wD(Ae);X.key={remoteJid:W,fromMe:re,participant:Ae.attrs.participant,participantAlt:ne,participantUsername:Ae.attrs.participant_username,addressingMode:Se,id:Ae.attrs.id,...X.key||{}},X.participant??(X.participant=Ae.attrs.participant),X.messageTimestamp=+Ae.attrs.t;let Ee=oe.WebMessageInfo.fromObject(X);await _(Ee,"append")}})])}finally{await he(Ae).catch(X=>t.error({ackErr:X},"failed to ack notification"))}},oA=async Ae=>{if(Ie(Ae,"enc")?.attrs.type==="msmsg"){t.debug({key:Ae.attrs.key},"ignored msmsg"),await he(Ae,cl.MissingMessageSecret);return}let X=!1;try{let{fullMessage:re,category:ne,author:Se,decrypt:Ee}=aX(Ae,I.creds.me.id,I.creds.me.lid||"",y,t),de=re.key.participantAlt||re.key.remoteJidAlt;if(de){let ye=yA(de)?.server,Je=re.key.participant||re.key.remoteJid;ye==="lid"?await y.lidMapping.getPNForLID(de)||(await y.lidMapping.storeLIDPNMappings([{lid:de,pn:Je}]),await y.migrateSession(Je,de)):(await y.lidMapping.storeLIDPNMappings([{lid:Je,pn:de}]),await y.migrateSession(de,Je))}await B.mutex(async()=>{if(await Ee(),re.key?.remoteJid&&re.key?.id&&re.message&&P&&P.addRecentMessage(re.key.remoteJid,re.key.id,re.message),re.messageStubType===oe.WebMessageInfo.StubType.CIPHERTEXT&&re.category!=="peer"){if(re?.messageStubParameters?.[0]===tX)return X=!0,he(Ae,cl.ParsingError);if(re.messageStubParameters?.[0]===DD){let Je=Ie(Ae,"unavailable")?.attrs?.type;if(Je==="bot_unavailable_fanout"||Je==="hosted_unavailable_fanout"||Je==="view_once_unavailable_fanout")return t.debug({msgId:re.key.id,unavailableType:Je},"skipping placeholder resend for excluded unavailable type"),X=!0,he(Ae);let IA=Ba()-Lr(re.messageTimestamp);if(IA>fse)return t.debug({msgId:re.key.id,messageAge:IA},"skipping placeholder resend for old message"),X=!0,he(Ae);let QA={remoteJid:re.key.remoteJid,fromMe:re.key.fromMe,id:re.key.id,participant:re.key.participant},XA={key:re.key,messageTimestamp:re.messageTimestamp,pushName:re.pushName,participant:re.participant,verifiedBizName:re.verifiedBizName};De(QA,XA).then(vA=>{vA&&vA!=="RESOLVED"&&(t.debug({msgId:re.key.id,requestId:vA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:re.key,update:{messageStubParameters:[DD,vA]}}]))}).catch(vA=>{t.warn({err:vA,msgId:re.key.id},"failed to request placeholder resend for unavailable message")}),X=!0,await he(Ae)}else{if(Bg(re.key.remoteJid)){let ye=Ba()-Lr(re.messageTimestamp);if(ye>Bse)return t.debug({msgId:re.key.id,messageAge:ye,remoteJid:re.key.remoteJid},"skipping retry for expired status message"),X=!0,he(Ae)}t.debug("[handleMessage] Attempting retry request for failed decryption"),await ee.mutex(async()=>{try{if(!d.isOpen){t.debug({node:Ae},"Connection closed, skipping retry");return}let ye=Ie(Ae,"enc");await je(Ae,!ye),o&&await zu(o)}catch(ye){t.error({err:ye},"Failed to send retry")}X=!0,await he(Ae,cl.UnhandledError)})}}else if(P&&re.key.id&&P.cancelPendingPhoneRequest(re.key.id),wc(re.key.remoteJid))X=!0,await he(Ae),t.debug({key:re.key},"processed newsletter message without receipts");else{let Je,IA=re.key.participant;if(ne==="peer"?Je="peer_msg":re.key.fromMe?(Je="sender",(qA(re.key.remoteJid)||qA(re.key.remoteJidAlt))&&(IA=Se)):Ne||(Je="inactive"),X=!0,await q(re.key.remoteJid,IA,[re.key.id],Je),_O(re.message)){let XA=uA(re.key.remoteJid);await q(XA,void 0,[re.key.id],"hist_sync")}}Xie(re,I.creds.me.id,I.creds.me.lid),await _(re,Ae.attrs.offline?"append":"notify")})}catch(re){t.error({error:re,node:Bn(Ae)},"error in handling message"),X||await he(Ae,cl.UnhandledError).catch(ne=>t.error({ackErr:ne},"failed to ack message after error"))}},lA=async Ae=>{try{let{attrs:W}=Ae,[X]=ls(Ae);if(!X)throw new If.Boom("Missing call info in call node");let re=X9(X),ne=X.attrs["call-id"],Se=X.attrs.from||X.attrs["call-creator"],Ee={chatId:W.from,from:Se,callerPn:X.attrs.caller_pn,id:ne,date:new Date(+W.t*1e3),offline:!!W.offline,status:re};if(re==="relaylatency"){let ye=X.attrs.latency||X.attrs.latency_ms||X.attrs["latency-ms"],Je=ye?Number(ye):void 0;Number.isFinite(Je)&&(Ee.latencyMs=Je)}re==="offer"&&(Ee.isVideo=!!Ie(X,"video"),Ee.isGroup=X.attrs.type==="group"||!!X.attrs["group-jid"],Ee.groupJid=X.attrs["group-jid"],await Te.set(Ee.id,Ee));let de=await Te.get(Ee.id);de&&(Ee.isVideo=de.isVideo,Ee.isGroup=de.isGroup,Ee.callerPn=Ee.callerPn||de.callerPn),(re==="reject"||re==="accept"||re==="timeout"||re==="terminate")&&await Te.del(Ee.id),c.emit("call",[Ee])}catch(W){t.error({error:W,node:Bn(Ae)},"error in handling call")}finally{await he(Ae).catch(W=>t.error({ackErr:W},"failed to ack call"))}},FA=async({attrs:Ae})=>{let W={remoteJid:Ae.from,fromMe:!0,id:Ae.id};if(Ae.error){let X=Ae.error===String(cl.SenderReachoutTimelocked);if(Ae.error===UG.MessageAccountRestriction){t.warn({msgId:Ae.id,from:Ae.from},"error 463: account restricted or missing tctoken for contact");let re=Ae.from;re&&!oo.has(re)&&(oo.add(re),(async()=>{try{let ne=y.lidMapping.getPNForLID.bind(y.lidMapping),Se=await ks(re,V),Ee=await XB(re,r.serverProps.lidTrustedTokenIssueToLid,V,ne),de=await U([Ee],Ba());await kh({result:de,fallbackJid:Se,keys:I.keys,getLIDForPN:V,onNewJidStored:_A}),t.debug({from:re},"completed 463 token recovery issuance")}catch(ne){t.debug({from:re,err:ne?.message},"failed 463 token recovery issuance")}finally{oo.delete(re)}})())}else Ae.error===UG.SmaxInvalid?t.warn({msgId:Ae.id,from:Ae.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):X?(await N().catch(re=>t.warn({err:re},"failed to fetch reachout timelock")),t.warn({attrs:Ae},"received error in ack")):t.warn({attrs:Ae},"received error in ack");c.emit("messages.update",[{key:W,update:{status:Td.ERROR,messageStubParameters:X?[Ae.error,rX]:[Ae.error]}}])}},Ut=async(Ae,W,X)=>{c.buffer(),await re(),c.flush();function re(){return X(Ae,!1).catch(ne=>R(ne,W))}},st=Hse(new Map([["message",oA],["call",lA],["receipt",Qe],["notification",be]]),{isWsOpen:()=>d.isOpen,onUnexpectedError:R,yieldToEventLoop:()=>new Promise(Ae=>setImmediate(Ae))}),fr=async(Ae,W,X,re)=>{let ne=W.attrs.from,Se=ne;if(Ae==="receipt"&&ne){let de=W.attrs,ye=de.from.includes("lid");Se=!Mt(de.participant||de.from,ye?I.creds.me?.lid:I.creds.me?.id)||Fr(de.from)?de.from:de.recipient}if(Se&&Se!==OA&&a(Se)){await he(W,Ae==="message"?cl.UnhandledError:void 0);return}!!W.attrs.offline?st.enqueue(Ae,W):await Ut(W,X,re)};d.on("CB:message",async Ae=>{await fr("message",Ae,"processing message",oA)}),d.on("CB:call",async Ae=>{await fr("call",Ae,"handling call",lA)}),d.on("CB:receipt",async Ae=>{await fr("receipt",Ae,"handling receipt",Qe)}),d.on("CB:notification",async Ae=>{await fr("notification",Ae,"handling notification",be)}),d.on("CB:ack,class:message",Ae=>{FA(Ae).catch(W=>R(W,"handling bad ack"))}),c.on("call",async([Ae])=>{if(Ae&&(Ae.status==="timeout"||Ae.status==="offer"&&Ae.isGroup)){let W={key:{remoteJid:Ae.chatId,id:Ae.id,fromMe:!1},messageTimestamp:Ba(Ae.date)};Ae.status==="timeout"?Ae.isGroup?W.messageStubType=Ae.isVideo?RA.CALL_MISSED_GROUP_VIDEO:RA.CALL_MISSED_GROUP_VOICE:W.messageStubType=Ae.isVideo?RA.CALL_MISSED_VIDEO:RA.CALL_MISSED_VOICE:W.message={call:{callKey:Buffer.from(Ae.id)}};let X=oe.WebMessageInfo.fromObject(W);await _(X,Ae.offline?"append":"notify")}});let Ar=0,oo=new Set;c.on("connection.update",({isOnline:Ae,connection:W})=>{if(typeof Ae<"u"&&(Ne=Ae,t.trace(`sendActiveReceipts set to "${Ne}"`)),W==="close"&&Le){clearTimeout(Le),Le=void 0;try{Promise.resolve(MA()).catch(()=>{})}catch{}}if(Ae){let X=Date.now(),re=1440*60*1e3;X-Ar>=re&&(Ar=X,Gi())}}),z(()=>{!n.msgRetryCounterCache&&ie.close&&ie.close(),!n.callOfferCache&&Te.close&&Te.close(),se.close(),Ne=!1});async function Gi(){try{await Re;let Ae=await GO(I.keys),W=new Set(Be);for(let de of Ae)W.add(de);if(!W.size)return;let X=[...W],re=await I.keys.get("tctoken",X),ne={},Se=new Set,Ee=0;for(let de of X){let ye=re[de];if(!ye){Ee++;continue}let Je=!!ye.token?.length,IA=Je&&kl(ye.timestamp),QA=ye.senderTimestamp!==void 0,XA=QA&&kl(ye.senderTimestamp),vA=Je&&!IA,YA=QA&&!XA;!vA&&!YA?(ne[de]=null,Ee++):IA&&YA?(ne[de]={token:Buffer.alloc(0),senderTimestamp:ye.senderTimestamp},Se.add(de),Ee++):Se.add(de)}if(Ee===0)return;await I.keys.set({tctoken:{...ne,[eI]:{token:Buffer.from(JSON.stringify([...Se]))}}}),Be.clear();for(let de of Se)Be.add(de);t.debug({mutated:Ee,remaining:Se.size},"pruned expired tctokens")}catch(Ae){t.warn({err:Ae?.message},"failed to prune expired tctokens")}}return{...r,sendMessageAck:he,sendRetryRequest:je,rejectCall:Ze,fetchMessageHistory:fe,requestPlaceholderResend:De,messageRetryManager:P}};var zse=n=>{let t=qse(n),{authState:o,query:i,waUploadToServer:e}=t,a=async f=>{let Q=[],y=["address","email","description"];return Q.push(...y.filter(_=>f[_]!==void 0&&f[_]!==null).map(_=>({tag:_,attrs:{},content:f[_]}))),f.websites!==void 0&&Q.push(...f.websites.map(_=>({tag:"website",attrs:{},content:_}))),f.hours!==void 0&&Q.push({tag:"business_hours",attrs:{timezone:f.hours.timezone},content:f.hours.days.map(_=>{let T={tag:"business_hours_config",attrs:{day_of_week:_.day,mode:_.mode}};return _.mode==="specific_hours"?{...T,attrs:{...T.attrs,open_time:_.openTimeInMinutes,close_time:_.closeTimeInMinutes}}:T})}),await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:Q}]})},A=async f=>{let{fileSha256:Q,filePath:y}=await SO(f,"biz-cover-photo"),m=Q.toString("base64"),{meta_hmac:_,fbid:T,ts:R}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(T),op:"update",token:_,ts:String(R)}}]}]}),T},r=async f=>await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:f}}]}]}),s=async({jid:f,limit:Q,cursor:y})=>{f=f||o.creds.me?.id,f=uA(f);let m=[{tag:"limit",attrs:{},content:Buffer.from((Q||10).toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}];y&&m.push({tag:"after",attrs:{},content:y});let _=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:f,allow_shop_source:"true"},content:m}]});return Ose(_)},g=async(f,Q=51)=>{f=f||o.creds.me?.id,f=uA(f);let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:f},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return bse(y)},c=async(f,Q)=>{let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:f},content:[{tag:"image_dimensions",attrs:{},content:[{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]},{tag:"token",attrs:{},content:Buffer.from(Q)}]}]});return Mse(y)},I=async(f,Q)=>{Q=await RU(Q,e);let y=NU(f,Q),m=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_edit",attrs:{v:"1"},content:[y,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),_=Ie(m,"product_catalog_edit"),T=Ie(_,"product");return gf(T)},d=async f=>{f.isHidden=!!f.isHidden,f=await RU(f,e);let Q=NU(void 0,f),y=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[Q,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=Ie(y,"product_catalog_add"),_=Ie(m,"product");return gf(_)},B=async f=>{let Q=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:f.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(Ie(Q,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...t,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:d,productDelete:B,productUpdate:I,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:r}};var Vse=n=>{let t=zse(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(I,d,B)=>e({tag:"iq",attrs:{type:d,xmlns:"w:g2",to:I},content:B}),r=async I=>{let d=await A(I,"get",[{tag:"query",attrs:{request:"interactive"}}]);return UU(d)},s=async()=>{let I=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),d={},B=Ie(I,"communities");if(B){let f=PA(B,"community");for(let Q of f){let y=UU({tag:"result",attrs:{},content:[Q]});d[y.id]=y}}return t.ev.emit("groups.update",Object.values(d)),d};async function g(I){of.info({node:I},"parseGroupResult");let d=Ie(I,"group");if(d)try{of.info({groupNode:d},"groupNode");let B=await t.groupMetadata(`${d.attrs.id}@g.us`);return B||c.empty()}catch(B){return console.error("Error parsing group metadata:",B),c.empty()}return c.empty()}let c={empty:()=>null,of:I=>I!==null?{value:I}:null};return t.ws.on("CB:ib,,dirty",async I=>{let{attrs:d}=Ie(I,"dirty");d.type==="communities"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,communityMetadata:r,communityCreate:async(I,d)=>{let B=FG().substring(0,12),f=await A("@g.us","set",[{tag:"create",attrs:{subject:I},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(d||"","utf-8")}]},{tag:"parent",attrs:{default_membership_approval_mode:"request_required"}},{tag:"allow_non_admin_sub_group_creation",attrs:{}},{tag:"create_general_chat",attrs:{}}]}]);return await g(f)},communityCreateGroup:async(I,d,B)=>{let f=Ur(),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:I,key:f},content:[...d.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(Q)},communityLeave:async I=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:I}}]}])},communityUpdateSubject:async(I,d)=>{await A(I,"set",[{tag:"subject",attrs:{},content:Buffer.from(d,"utf-8")}])},communityLinkGroup:async(I,d)=>{await A(d,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}]}])},communityUnlinkGroup:async(I,d)=>{await A(d,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}])},communityFetchLinkedGroups:async I=>{let d=I,B=!1,f=await t.groupMetadata(I);f.linkedParent?d=f.linkedParent:B=!0;let Q=await A(d,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=Ie(Q,"sub_groups");if(m){let _=PA(m,"group");for(let T of _)y.push({id:T.attrs.id?Er(T.attrs.id,"g.us"):void 0,subject:T.attrs.subject||"",creation:T.attrs.creation?Number(T.attrs.creation):void 0,owner:T.attrs.creator?uA(T.attrs.creator):void 0,size:T.attrs.size?Number(T.attrs.size):void 0})}return{communityJid:d,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async I=>{let d=await A(I,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=Ie(d,"membership_approval_requests");return PA(B,"membership_approval_request").map(Q=>Q.attrs)},communityRequestParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:d.map(_=>({tag:"participant",attrs:{jid:_}}))}]}]),Q=Ie(f,"membership_requests_action"),y=Ie(Q,B);return PA(y,"participant").map(_=>({status:_.attrs.error||"200",jid:_.attrs.jid}))},communityParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:d.map(m=>({tag:"participant",attrs:{jid:m}}))}]),Q=Ie(f,B);return PA(Q,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(I,d)=>{let f=(await r(I)).descId??null;await A(I,"set",[{tag:"description",attrs:{...d?{id:FG()}:{delete:"true"},...f?{prev:f}:{}},content:d?[{tag:"body",attrs:{},content:Buffer.from(d,"utf-8")}]:void 0}])},communityInviteCode:async I=>{let d=await A(I,"get",[{tag:"invite",attrs:{}}]);return Ie(d,"invite")?.attrs.code},communityRevokeInvite:async I=>{let d=await A(I,"set",[{tag:"invite",attrs:{}}]);return Ie(d,"invite")?.attrs.code},communityAcceptInvite:async I=>{let d=await A("@g.us","set",[{tag:"invite",attrs:{code:I}}]);return Ie(d,"community")?.attrs.jid},communityRevokeInviteV4:async(I,d)=>!!await A(I,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:d}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(I,d)=>{I=typeof I=="string"?{remoteJid:I}:I;let B=await A(d.groupJid,"set",[{tag:"accept",attrs:{code:d.inviteCode,expiration:d.inviteExpiration.toString(),admin:I.remoteJid}}]);return I.id&&(d=oe.Message.GroupInviteMessage.fromObject(d),d.inviteExpiration=0,d.inviteCode="",i.emit("messages.update",[{key:I,update:{message:{groupInviteMessage:d}}}])),await a({key:{remoteJid:d.groupJid,id:Ur(t.user?.id),fromMe:!1,participant:I.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:I.remoteJid,messageTimestamp:Ba()},"notify"),B.attrs.from}),communityGetInviteInfo:async I=>{let d=await A("@g.us","get",[{tag:"invite",attrs:{code:I}}]);return UU(d)},communityToggleEphemeral:async(I,d)=>{let B=d?{tag:"ephemeral",attrs:{expiration:d.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(I,"set",[B])},communitySettingUpdate:async(I,d)=>{await A(I,"set",[{tag:d,attrs:{}}])},communityMemberAddMode:async(I,d)=>{await A(I,"set",[{tag:"member_add_mode",attrs:{},content:d}])},communityJoinApprovalMode:async(I,d)=>{await A(I,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:d}}]}])},communityFetchAllParticipating:s}},UU=n=>{let t=Ie(n,"community"),o=Ie(t,"description"),i,e;o&&(i=jA(o,"body"),e=o.attrs.id);let a=t.attrs.id?.includes("@")?t.attrs.id:Er(t.attrs.id||"","g.us"),A=Ie(t,"ephemeral")?.attrs.expiration,r=jA(t,"member_add_mode")==="all_member_add";return{id:a,subject:t.attrs.subject||"",subjectOwner:t.attrs.s_o,subjectTime:Number(t.attrs.s_t||0),size:PA(t,"participant").length,creation:Number(t.attrs.creation||0),owner:t.attrs.creator?uA(t.attrs.creator):void 0,desc:i,descId:e,linkedParent:Ie(t,"linked_parent")?.attrs.jid||void 0,restrict:!!Ie(t,"locked"),announce:!!Ie(t,"announcement"),isCommunity:!!Ie(t,"parent"),isCommunityAnnounce:!!Ie(t,"default_sub_community"),joinApprovalMode:!!Ie(t,"membership_approval_mode"),memberAddMode:r,participants:PA(t,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:jA(t,"addressing_mode")}};var ZVe=n=>{let t={...yse,...n};return Vse(t)},Wse=ZVe;var Zse=Wse;var XVe=Object.freeze({key:"whatsapp",label:"WhatsApp",get connectionLabel(){return D(" Web \u5173\u8054\u8BBE\u5907")},reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),Db=class extends xn{constructor(t){super({...t,descriptor:XVe})}};import{chmod as Xse,mkdir as $Ve,readdir as eWe}from"node:fs/promises";var AWe=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),tWe=6e4;function $se(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function rWe(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function aWe(n){let t=n;if(typeof t=="string"){if(!/^\d+$/.test(t))return null;t=Number(t)}else typeof t=="bigint"?t=Number(t):t&&typeof t=="object"&&(t=Number(t.valueOf()));return Number.isFinite(t)&&t>=0?t*1e3:null}async function HU(n){await $Ve(n,{recursive:!0,mode:448}),await Xse(n,448);let t=await eWe(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(t.filter(o=>o.isFile()).map(o=>Xse(`${n}/${o.name}`,384).catch(()=>{})))}function iWe(n,t){let o=n.user??t.creds.me,i=uA(o?.id);if(!/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i??""))throw new Error("WhatsApp did not return a valid linked account");return{accountJid:i,name:typeof o?.name=="string"&&o.name.trim()?o.name.trim().slice(0,100):D("WhatsApp\u673A\u5668\u4EBA")}}async function wb({authDir:n,onQr:t,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=Zse,loadAuthState:r=Vie}={}){if(!n||typeof t!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await HU(n);let s=Date.now(),{state:g,saveCreds:c}=await r(n),I=g.keys.set.bind(g.keys);g.keys.set=async J=>{await I(J),await HU(n)};let d=!1,B=!1,f,Q,y=Promise.resolve(),m=null,_=0,T=null,R=new Promise((J,x)=>{f=J,Q=x}),H=J=>{B||(B=!0,Q(J))},j=async()=>{d||(d=!0,_+=1,H($se()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},F=async()=>{d||(d=!0,_+=1,H($se()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let J=++_,x=!1,P=A({auth:g,browser:UO.macOS("DeepSeek Harness"),logger:AWe,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=P;let z=()=>{!x||!g.creds.me||B||y.then(()=>{d||B||J!==_||!x||!g.creds.me||(B=!0,f(iWe(P,g)))}).catch(U=>H(U))};P.ev.on("creds.update",()=>{d||J!==_||(y=y.then(async()=>{await c(),await HU(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),z())}),P.ev.on("connection.update",U=>{if(!(d||J!==_)&&(typeof U.qr=="string"&&U.qr&&t(U.qr),U.connection==="open"&&(x=!0,z()),U.connection==="close")){let N=rWe(U.lastDisconnect?.error);if(N===Zt.restartRequired){T??=y.then(async()=>{d||J!==_||(await P.end(void 0).catch(()=>{}),!(d||J!==_)&&q())}).catch(ee=>H(ee)).finally(()=>{T=null});return}let k=N===Zt.loggedOut,V=Object.assign(new Error(k?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:k?"logged-out":"connection-closed"});B?i?.({error:V,loggedOut:k}):H(V)}}),P.ev.on("messages.upsert",({messages:U,type:N})=>{if(!(d||J!==_||N!=="notify"&&N!=="append"||typeof o!="function"))for(let k of Array.isArray(U)?U:[]){if(N==="append"){let V=aWe(k?.messageTimestamp);if(V===null||V{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await j():e.addEventListener("abort",()=>void j(),{once:!0})),Object.freeze({get socket(){return m},ready:R,close:j,logout:F})}var xU=new Set(["image/jpeg","image/png","image/webp","image/gif"]),nWe=5*1024*1024,KU=15e3,YU=12e4,sWe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],gWe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]);function cWe(n){let t=n;for(let o=0;o<5&&t&&typeof t=="object";o+=1){let i=sWe.find(e=>t[e]?.message);if(!i)return!1;if(gWe.has(i))return!0;t=t[i].message}return!1}function IWe(n){return n?.extendedTextMessage?.contextInfo??n?.imageMessage?.contextInfo??n?.videoMessage?.contextInfo??n?.documentMessage?.contextInfo??null}function lWe(n){return n?.conversation??n?.extendedTextMessage?.text??n?.imageMessage?.caption??n?.videoMessage?.caption??n?.documentMessage?.caption??""}function tge(n){if(Number.isSafeInteger(n)&&n>=0)return n;let t;try{t=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(t)&&t>=0?t:void 0}async function pWe(n,t,{signal:o,maxBytes:i=nWe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(KU),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>t(n,"stream",{options:{signal:a}})),r=await new Promise((I,d)=>{let B=!1,f=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",Q),y(m),!0),Q=()=>f(d,a.reason);a.addEventListener("abort",Q,{once:!0}),A.then(y=>{f(I,y)||y?.destroy?.()},y=>f(d,y)),a.aborted&&Q()}).catch(I=>{throw o?.aborted?o.reason??I:e.aborted?new ut("image-download-failed",`WhatsApp image download timed out after ${KU} ms`,D("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}),s=[],g=0,c=()=>r?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let I of r){a.throwIfAborted();let d=Buffer.from(I);if(g+=d.length,g>i)throw r.destroy?.(),new ut("image-too-large",`WhatsApp image exceeded ${i} bytes`,D("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));s.push(d)}}catch(I){throw o?.aborted?o.reason??I:e.aborted?new ut("image-download-failed",`WhatsApp image stream timed out after ${KU} ms`,D("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function dWe(n,t,o,{viewOnce:i=!1}={}){let e,a;if(!i&&t?.imageMessage&&t.imageMessage.viewOnce!==!0)e=t.imageMessage;else if(t?.documentMessage){let r=typeof t.documentMessage.mimetype=="string"?t.documentMessage.mimetype.toLowerCase():"";if(!xU.has(r))return null;e=t.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return xU.has(A)?{name:a,mediaType:A,size:tge(e.fileLength),load:r=>pWe(n,o,r)}:null}function hWe(n,t,o){let i=t?.documentMessage;if(!i)return null;let e=typeof i.mimetype=="string"&&i.mimetype?i.mimetype.toLowerCase():void 0;return xU.has(e)?null:{name:typeof i.fileName=="string"&&i.fileName?i.fileName:"whatsapp-file",...e?{mediaType:e}:{},size:tge(i.fileLength),async load({signal:a}={}){a?.throwIfAborted();let A=await o(n,"stream",{options:{signal:a}});return a?.throwIfAborted(),{stream:A}}}}function EWe({socket:n,logger:t=console,download:o=i2}={}){if(typeof o!="function")throw new TypeError("WhatsApp media downloader is required");return typeof n?.updateMediaMessage!="function"?o:(i,e,a)=>o(i,e,a,{logger:t,reuploadRequest:A=>n.updateMediaMessage(A)})}function CWe(n,t,{download:o=i2}={}){let i=typeof n?.key?.remoteJid=="string"?n.key.remoteJid:"",e=typeof n?.key?.remoteJidAlt=="string"?n.key.remoteJidAlt:"",a=typeof n?.key?.id=="string"?n.key.id:"";if(!i||!a||i==="status@broadcast"||i.endsWith("@newsletter"))return null;let A=i.endsWith("@g.us"),r=n.key.fromMe===!0,s=r&&!A&&[i,e].some(_=>_&&Mt(_,t));if(r&&!s&&!A)return null;let g=r?t:A?n.key.participant:i,c=A&&!r?n.key.participantAlt:e;if(typeof g!="string"||!g)return null;let I=cWe(n.message),d=Sa(n.message),B=IWe(d),f=Array.isArray(B?.mentionedJid)&&B.mentionedJid.some(_=>Mt(_,t)),Q=typeof B?.participant=="string"&&Mt(B.participant,t),y=dWe(n,d,o,{viewOnce:I}),m=hWe(n,d,o);return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,senderAlternateId:typeof c=="string"?c:"",senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:lWe(d),plainText:typeof d?.conversation=="string"||typeof d?.extendedTextMessage?.text=="string",images:y?[y]:[],files:m?[m]:[],addressed:!A||r||f||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s},reactionTarget:{jid:i,key:n.key}}}function uWe(n,{accessMode:t=md.selfOnly,allowedNumbers:o=new Set}={}){if(t===md.open)return!0;if(n?.kind!=="direct")return!1;if(n.selfChat===!0)return!0;if(t!==md.privateAllowlist||!(o instanceof Set))return!1;let i=[n.senderId,n.senderAlternateId].filter(e=>typeof e=="string"&&e.endsWith("@s.whatsapp.net"));return[...o].some(e=>i.some(a=>Mt(a,`${e}@s.whatsapp.net`)))}var jU=class{#e=new Map;has(t){return this.#t(),this.#e.has(t)}remember(t){this.#A(t)}reserve(t){this.#A(t)}#A(t){if(!(typeof t!="string"||!t))for(this.#t(),this.#e.set(t,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#t(){let t=Date.now();for(let[o,i]of this.#e)i>t||this.#e.delete(o)}};function rge(n){return n?.reason??new DOMException("The operation was aborted.","AbortError")}function Age(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,rge(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function BWe(n){if(n?.code==="artifact-delivery-uncertain")return n;let t=new Error("WhatsApp could not confirm artifact delivery.");return t.code="artifact-delivery-uncertain",t.cause=n,t}function fWe(n){if(n?.code?.startsWith?.("artifact-"))return n;let t=n?.output?.statusCode??n?.data?.statusCode??n?.statusCode,o;if(t===401||t===403?o="artifact-permission-required":t===413?o="artifact-too-large":t===429?o="artifact-rate-limited":[400,404,405,406,410,415,422].includes(t)&&(o="artifact-provider-rejected"),!o)return BWe(n);let i=new Error("WhatsApp rejected artifact delivery.");return i.code=o,i.cause=n,i}var JU=class{#e;#A;#t;#r;#a=new Map;constructor(t,o,{signal:i,mediaUploadTimeoutMs:e=YU}={}){this.#e=t,this.#A=o,this.#t=i,this.#r=e}async sendText(t,o){await this.#s(t.jid);let i=[];for(let[e,a]of Yn(o,4e3).entries()){let A=ege(10).toString("hex").toUpperCase(),r={...e===0&&t.quoted?{quoted:t.quoted}:{},messageId:A};typeof this.#A.reserve=="function"?this.#A.reserve(A):this.#A.remember(A);let s=await this.#e.sendMessage(t.jid,{text:a},r);this.#A.remember(s?.key?.id),typeof s?.key?.id=="string"&&s.key.id&&i.push(s.key.id)}return{providerMessageIds:i}}async sendFile(t,o){return this.#c(t,o,{document:o.bytes,mimetype:o.mediaType??"application/octet-stream",fileName:o.fileName},"file")}async sendImage(t,o){return this.#c(t,o,{image:o.bytes,mimetype:o.mediaType??"image/jpeg"},"image")}async addReaction(t,o,{signal:i}={}){if(typeof o!="string"||!o.trim())throw new TypeError("A WhatsApp reaction emoji is required");let e=o.trim();return await this.#i(t,e,i),e}removeReaction(t,o,{signal:i}={}){return this.#i(t,"",i)}async#i(t,o,i){if(typeof t?.jid!="string"||!t.jid||!t.key?.id)throw new TypeError("A WhatsApp reaction target is required");let e=i??this.#t;e?.throwIfAborted();let a=ege(10).toString("hex").toUpperCase();typeof this.#A.reserve=="function"?this.#A.reserve(a):this.#A.remember(a);let A=this.#e.sendMessage(t.jid,{react:{text:o,key:t.key}},{messageId:a}),r=await Age(A,e);return this.#A.remember(r?.key?.id),r}async#c(t,o,i,e){this.#t?.throwIfAborted(),await this.#s(t.jid),this.#t?.throwIfAborted();let a=typeof o.deliveryKey=="string"&&o.deliveryKey?o.deliveryKey:o.artifactId,A=e==="image"?`${a}:image`:a,r=typeof A=="string"&&A?oWe("sha256").update(A).digest("hex").slice(0,20).toUpperCase():void 0,s={...t.quoted?{quoted:t.quoted}:{},...r?{messageId:r}:{},mediaUploadTimeoutMs:this.#r};this.#A.remember(r);let g;try{let c=this.#e.sendMessage(t.jid,i,s);An(o,c);let I=AbortSignal.timeout(this.#r),d=this.#t?AbortSignal.any([this.#t,I]):I;g=await Age(c,d)}catch(c){throw this.#t?.aborted?rge(this.#t):fWe(c)}return this.#t?.throwIfAborted(),this.#A.remember(g?.key?.id),g}async sendTyping(t){!t.selfChat&&t.quoted?.key&&await this.#e.readMessages([t.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",t.jid),await this.#s(t.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",t.jid).catch(()=>{this.#s(t.jid)})},2e4);o.unref?.(),this.#a.set(t.jid,o)}async close(){let t=[...this.#a.keys()];await Promise.allSettled(t.map(o=>this.#s(o)))}async#s(t,o=!0){let i=this.#a.get(t);i&&clearInterval(i),this.#a.delete(t),o&&await this.#e.sendPresenceUpdate("paused",t).catch(()=>{})}};function QWe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Yi()}}var lf=class{#e;#A;#t;#r;#a;#i;#c;#s;#I;#o;#n;#g=QWe();#l=null;#p=null;#d=null;#h=null;#E=null;constructor({config:t,authDir:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:r=3e4,mediaUploadTimeoutMs:s=YU,createSession:g=wb}){if(!t||!o||!i||!e||typeof g!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");if(this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#a=a,this.#i=A,this.#c=r,!Number.isSafeInteger(s)||s<=0)throw new TypeError("mediaUploadTimeoutMs must be a positive safe integer");this.#s=Math.min(s,YU),this.#n=g,this.setAccessPolicy(t)}get status(){return structuredClone(this.#g)}setAccessPolicy(t){let o=pg(t);return this.#I=o.accessMode,this.#o=new Set(o.allowedNumbers),this.#e={...this.#e,...o},o}async start(){return this.#g.ready&&this.#p?this.status:this.#E?this.#E:(this.#E=this.#B().finally(()=>{this.#E=null}),this.#E)}async#B(){await this.stop(),this.#g.startedAt=new Date().toISOString(),this.#g.connectionState="connecting",this.#g.lastError=null,await this.#t.ensureRunning(),this.#g.harnessReachable=!0;let t=new AbortController;this.#l=t;let o=new jU,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#n({authDir:this.#A,signal:t.signal,logger:this.#a,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async(c,I)=>{let d=CWe(c,this.#e.accountJid,{download:EWe({socket:I?.socket,logger:this.#a})});if(!(!d||o.has(d.providerMessageId)||!this.#h)){if(this.#g.lastCheckedAt=Date.now(),!uWe(d,{accessMode:this.#I,allowedNumbers:this.#o})){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}await this.#h.accept(d)}},onDisconnect:({error:c})=>{t.signal.aborted||(this.#g.ready=!1,this.#g.connectionState="failed",this.#g.lastError=c?.message??"WhatsApp Web connection closed")}});this.#p=a;let A,r=await Promise.race([a.ready,e,new Promise((c,I)=>{A=setTimeout(()=>I(new Error("WhatsApp Web did not connect in time")),this.#c)})]).finally(()=>clearTimeout(A));if(!Mt(r.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new JU(a.socket,o,{signal:t.signal,mediaUploadTimeoutMs:this.#s});this.#d=s,this.#h=new Db({bot:s,harness:this.#t,state:this.#r,status:this.#g,logger:this.#a,replyTimeoutMs:this.#i,signal:t.signal});let g=Date.now();return this.#g.ready=!0,this.#g.connectionState="connected",this.#g.lastCheckedAt=g,this.#g.lastConnectedAt=g,this.status}catch(a){throw this.#g.ready=!1,this.#g.connectionState="failed",this.#g.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#p?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(t){if(!this.#g.ready||!this.#d){let o=new Error(D("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw o.code="test-target-unavailable",o}if(typeof t!="string"||!t.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#d.sendText({jid:this.#e.accountJid,selfChat:!0},t),{sent:!0}}async stop(){let t=this.#p,o=this.#d,i=this.#h;return this.#l?.abort(),this.#l=null,this.#p=null,this.#d=null,this.#h=null,await o?.close().catch(()=>{}),await t?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#g.ready=!1,this.#g.connectionState="idle",this.status}};var DWe=/^[a-f0-9-]{36}$/;function wWe(n){let t=Lg(n.dshHome??process.env.DSH_HOME??zh(SWe(),".dsh")),o=Lg(n.dataDir??zh(t,"integrations","dsh-whatsapp")),i=Lg(n.authDir??zh(o,"auth")),e=a=>{if(!DWe.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return Lg(i,a)};return{config:Lg(n.configPath??zh(o,"config.json")),bots:Lg(n.botsDir??zh(o,"bots")),workspaces:Lg(n.workspacesPath??zh(o,"workspaces.json")),authPath:e}}async function qU(n,t={},o={}){let i=$r(n,t),e=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,a=()=>_a(n),A=o.ConfigStore??HS,r=o.StateStore??xS,s=o.HarnessClient??KS,g=o.Controller??bu,c=o.Runtime??lf,I=o.createSession??wb,d=o.createConnectionSupervisor??sp,B=wWe(t),f=await new A(B.config).load(),Q=Lg(t.workspace??process.cwd()),y=o.WorkspaceStore??Xr,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(k=>k.botId)),await Promise.all(_.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Ra(f,{workspaces:m}):f,R=new Map,H=k=>Lg(B.bots,k,"state.json"),j=async k=>{let V=R.get(k);return V||(V=await new r(H(k)).load(),R.set(k,V)),V},F=Pa(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:J,fileIngressExecutor:x}=Ga(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),P=new s({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...F?{commandExecutor:F}:{},...q?{controlExecutor:q}:{},...J?{sessionMaintenanceExecutor:J}:{},...x?{fileIngressExecutor:x}:{}}),z=new g({configStore:T,authPath:B.authPath,createSession:I,logger:e,createRuntime:async({botId:k,config:V,authDir:ee})=>{let ie=await j(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset});let Te=ka(P,{botId:k,workspaces:m,state:ie,agentPresetCatalog:a});return new c({config:V,authDir:ee,harness:Te.harness,state:Te.state,replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??3e4,createSession:I,logger:{error:(...se)=>e.error?.(`[${k}]`,...se),warn:(...se)=>e.warn?.(`[${k}]`,...se),info:(...se)=>e.info?.(`[${k}]`,...se),debug:(...se)=>e.debug?.(`[${k}]`,...se)}})},deleteAuth:k=>yWe(B.authPath(k),{recursive:!0,force:!0}),deleteState:async({botId:k})=>{let V=R.get(k);if(R.delete(k),V&&typeof V.remove=="function")await V.remove();else try{await mWe(H(k))}catch(ee){if(ee?.code!=="ENOENT")throw ee}}}),U=va(z,{workspaces:m,stateFor:j,agentPresetCatalog:a}),N=d({channel:"whatsapp",controller:U,harness:P,logger:e,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:U,ready:N.ready,async close(){await N.close(),await U.close(),P.stopManagedProcess()}}}import OWe from"qrcode";var age="/whatsapp",Jr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setAccessPolicy:"bot.access-policy.set",setWorkspace:ui,setAgentPreset:Bi}),ige=Object.freeze(Object.values(Jr)),bWe=new Set(["qrValue","accountJid","authDirectory"]);function VU(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function pf(n,t){return VU(n)&&Object.keys(n).every(o=>t.includes(o))}function Ob(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function MWe(n,t){if(!VU(t))return"Payload must be an object.";if([Jr.status,Jr.beginProvisioning].includes(n))return pf(t,[])?null:`${n} does not accept fields.`;if([Jr.pollProvisioning,Jr.cancelProvisioning].includes(n))return pf(t,["attemptId"])&&Ob(t.attemptId)?null:`${n} requires an attemptId.`;if(n===Jr.reconnectBot)return pf(t,["botId","sendTest"])&&Ob(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.";if(n===Jr.deleteBot)return pf(t,["botId","confirm"])&&Ob(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.";if(n===Jr.setAccessPolicy){if(!pf(t,["botId","accessMode","allowedNumbers"])||Object.keys(t).length!==3||!Ob(t.botId))return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002";try{return pg(t),null}catch{return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002"}}return n===Jr.setWorkspace?Fa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Jr.setAgentPreset?Ua(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":"Unknown WhatsApp endpoint."}function Wh(n){if(Array.isArray(n))return n.map(Wh);if(!VU(n))return n;let t={};for(let[o,i]of Object.entries(n))bWe.has(o)||(t[o]=Wh(i));return t}async function _We(n){return OWe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function zU(n,t){return!n||typeof n.qrValue!="string"?Wh(n):Wh({...n,qrCodeDataUrl:await t(n.qrValue)})}async function Vh(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await zU(o.provisioning,t)),Wh(o)}function oge(n,{encodeQr:t=_We}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","reconnectBot","deleteBot","setAccessPolicy"])if(typeof n?.[e]!="function")throw new TypeError(`A complete WhatsApp controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!ige.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let r=MWe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===Jr.status)s=await Vh(await n.status(),i);else if(e===Jr.beginProvisioning)s=await zU(await n.startProvisioning(),i);else if(e===Jr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await zU(g,i)}else if(e===Jr.cancelProvisioning)s=Wh(await n.cancelProvisioning(a.attemptId));else if(e===Jr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(s=await Vh(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(d=>d?.botId===a.botId&&d.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let d=new Error("Connection test is unavailable");throw d.code="test-target-unavailable",d}await n.sendConnectionTest(a.botId)}catch(d){c=d}s={...s,testMessage:ar(c)}}}else if(e===Jr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Vh(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Jr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Vh(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Jr.setAccessPolicy?s=await Vh(await n.setAccessPolicy(a.botId,pg(a)),i):s=await Vh(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=La(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"whatsapp-operation-failed",message:"WhatsApp \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function bb(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(age,oge(t,o),{authority:mr(i)})}async function nge(n,t={}){if(t?.controller)return bb(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await qU(n,t,t.internals??{}),i=bb(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close WhatsApp Web connections"),i}var df=qe(xD(),1);import{createHash as TWe}from"node:crypto";import{readFile as cge,realpath as Tn,stat as NWe}from"node:fs/promises";import{homedir as RWe}from"node:os";import{basename as kWe,dirname as ZU,isAbsolute as eH,join as Ug,relative as vWe,resolve as _b,sep as PWe}from"node:path";import{fileURLToPath as GWe}from"node:url";var rI="@xmanrui/dsh-im",hf="https://registry.npmjs.org/",FWe=15*6e4,LWe=1e4,sge=16*1024;function Nn(n,t={}){return Object.assign(new Error(n),{code:n,...t})}function Mb(n,t){return typeof n?.get=="function"?n.get(t):n?.[t]}function XU(n,t){let o=vWe(n,t);return o!==".."&&!o.startsWith(`..${PWe}`)&&!eH(o)}async function UWe(n){try{return await cge(n,"utf8")}catch(t){if(t.code==="ENOENT")return"";throw t}}async function $U(n){let t=await cge(Ug(n,"package.json"),"utf8");return{directory:await Tn(n),manifest:JSON.parse(t),contents:t}}async function WU(n,t){let o=ZU(await Tn(n));for(;;){try{let e=await $U(o);return e.manifest?.name===t?e:null}catch(e){if(e.code!=="ENOENT")throw e}let i=ZU(o);if(i===o)return null;o=i}}function HWe(n){return typeof n=="string"&&n.length>0&&Buffer.byteLength(n)<=255&&!n.startsWith("-")&&![".","..","node_modules"].includes(n)&&!/[\\/\x00-\x1f\x7f<>:"|?*]/u.test(n)}function KWe(n){if(n[0]==="web")return"web";let t;for(let o=0;o0&&(df.default.validRange(n)!==null||/^[A-Za-z][A-Za-z0-9._-]*$/u.test(n))}async function jWe(n){if(n.manifest?.name!==rI||df.default.valid(n.manifest.version)===null)return!1;let t=[n.manifest.main,n.manifest.exports?.["./client"],n.manifest.dsh?.bundle?.patch];for(let o of t){if(typeof o!="string"||!o||eH(o)||o.includes("\0"))return!1;let i=_b(n.directory,o);if(!XU(n.directory,i)||!XU(n.directory,await Tn(i))||!(await NWe(i)).isFile())return!1}return!0}function JWe(n){if(n==null||n==="")return!0;if(typeof n!="string")return!1;try{return new URL(n).href===hf}catch{return!1}}async function gge(n,{signal:t,timeoutMs:o,errorCode:i,capture:e=!1}){if(t?.aborted)throw Nn("install-interrupted");let a=new AbortController,A,r,s=B=>{A??=B,a.abort(),r?.cancel?.()},g=()=>s("install-interrupted");t?.addEventListener("abort",g,{once:!0});let c=setTimeout(()=>s("install-timeout"),o),I="",d="";try{r=n(a.signal),r.stdout?.on("data",f=>{e&&(I=(I+f.toString()).slice(-sge))}),r.stderr?.on("data",f=>{d=(d+f.toString()).slice(-sge)}),r.stdout?.on("error",()=>s(i)),r.stderr?.on("error",()=>s(i));let B=await r.done;if(A)throw Nn(A);if(B.exitCode!==0||B.signal)throw Nn(i,{exitCode:B.exitCode,diagnosticCode:d.match(/\bERR_PNPM_[A-Z0-9_]+\b/u)?.[0]});return{exitCode:0,signal:null,...e?{stdout:I}:{}}}catch(B){throw A?Nn(A):B.code===i?B:Nn(i)}finally{clearTimeout(c),t?.removeEventListener("abort",g)}}function Ige(n={}){let t=n.ctx,o=n.env??process.env,i=n.argv??process.argv,e=n.execArgv??process.execArgv,a=n.execPath??process.execPath,A=n.cwd??process.cwd(),r=n.platform??process.platform,s=n.osHome??RWe(),g=n.electron??process.versions.electron,c=n.moduleUrl??import.meta.url,I=WU(GWe(c),rI).catch(()=>null),d;async function B(){let _=Mb(t,"desktopProfiles"),T=Mb(t,"desktopPnpm"),R=Mb(t,"desktopPnpmBootstrap"),H=!!(g||_||T||R),j=_?.current,F=H?j?.name:KWe(i.slice(2)),q=H&&R?.homeDir?_b(R.homeDir):xWe(o,s),J={environmentKind:H?"desktop":"cli",homeDir:q,profileName:F};if(!HWe(F))return{...J,blockedReason:"unknown-profile"};let x=await Tn(Ug(q,"profiles",F)),P=await Tn(q),z={...J,homeDir:P,profileDir:x};if(H)try{if(typeof T?.runPlugin!="function"||typeof T?.run!="function"||!R||!j?.dir||R.activeProfileName!==F||await Tn(j.dir)!==x||await Tn(R.activeProfileDir)!==x||await Tn(R.appExecutable)!==await Tn(a))return{...z,blockedReason:"executor-unavailable"};let N=await WU(R.dshBootstrapPath,"dsh-plugin-desktop");return!N||kWe(R.dshBootstrapPath)!=="desktop-cli.js"||ZU(await Tn(R.dshBootstrapPath))!==Ug(N.directory,"lib")?{...z,blockedReason:"executor-unavailable"}:{...z,desktop:T,executable:a,cliEntry:R.dshBootstrapPath}}catch{return{...z,blockedReason:"executor-unavailable"}}let U=Mb(t,"subprocess");if(typeof U?.spawn!="function"||typeof i[1]!="string"||!eH(i[1])||r==="win32")return{...z,blockedReason:"executor-unavailable"};try{let N=await WU(i[1],"@deepseek-ai/dsh");if(!N)return{...z,blockedReason:"executor-unavailable"};let k=await Tn(i[1]),V=typeof N.manifest.bin=="string"?N.manifest.bin:N.manifest.bin?.dsh,ee=typeof V=="string"?_b(N.directory,V):"";return k!==ee&&k!==Ug(N.directory,"src","bin.ts")?{...z,blockedReason:"executor-unavailable"}:{...z,subprocess:U,executable:a,cliEntry:k}}catch{return{...z,blockedReason:"executor-unavailable"}}}function f(_,T,R,H=!1){let j=_.subprocess.spawn({argv:H?["pnpm",...T]:[a,...e,_.cliEntry,...T],cwd:H?_.profileDir:A,env:{DSH_HOME:_.homeDir,CI:"true"},stdio:{stdin:"ignore",stdout:"pipe",stderr:"pipe"},graceMs:3e3,signal:R});return{stdout:j.stdout,stderr:j.stderr,cancel:()=>j.terminate(),done:(async()=>{try{return await j.done}finally{await j.waitForExit()}})()}}async function Q(_,T){let R=["config","get","@xmanrui:registry","--json"],j=(await gge(q=>_.desktop?_.desktop.run(R,q):f(_,R,q,!0),{signal:T,timeoutMs:n.configTimeoutMs??LWe,errorCode:"registry-check-failed",capture:!0})).stdout.trim(),F;try{F=j===""||j==="undefined"?void 0:JSON.parse(j)}catch{throw Nn("registry-check-failed")}if(!JWe(F))throw Nn("registry-conflict")}async function y({preflight:_=!1}={}){let T,R={installedVersion:null,packageValid:!1,eligible:!1,installationKey:null};try{T=await B();for(let P of["homeDir","profileDir","profileName","environmentKind","executable","cliEntry"])R[P]=T[P]??null;if(!T.profileDir)return{...R,blockedReason:T.blockedReason??"unknown-profile"};let H=await $U(T.profileDir),j=await $U(Ug(T.profileDir,"node_modules",rI));R.installedVersion=typeof j.manifest.version=="string"?j.manifest.version:null,R.packageValid=await jWe(j);let F=await I,q=`${T.homeDir}\0${T.profileDir}\0${T.profileName}`,J=F?.directory===j.directory&&F?.manifest.version===j.manifest.version;d===void 0&&J&&R.packageValid&&(d=q);let x=await Promise.all(["pnpm-lock.yaml","pnpm-workspace.yaml","package-lock.json"].map(P=>UWe(Ug(T.profileDir,P))));return R.installationKey=TWe("sha256").update(JSON.stringify([q,H.contents,j.directory,j.contents,T.cliEntry,T.executable,...x])).digest("hex"),d!==void 0&&d!==q||!J&&d===void 0?R.blockedReason="installation-changed":R.packageValid?!YWe(H.manifest.dependencies?.[rI])||!XU(Ug(T.profileDir,"node_modules"),j.directory)?R.blockedReason="source-install":T.blockedReason?R.blockedReason=T.blockedReason:J?_&&await Q(T):R.blockedReason="pending-restart":R.blockedReason="invalid-installation",R.eligible=!R.blockedReason,{...R,blockedReason:R.blockedReason??null}}catch(H){return{...R,blockedReason:["registry-conflict","registry-check-failed","install-timeout","install-interrupted"].includes(H.code)?H.code:T?.profileDir?"invalid-installation":"unknown-profile"}}}async function m(_,{signal:T,expectedInstallationKey:R}={}){if(df.default.valid(_)!==_||df.default.prerelease(_))throw Nn("invalid-version");let H=await y();if(R!==void 0&&H.installationKey!==R)throw Nn("installation-changed");if(!H.eligible)throw Nn(H.blockedReason);let j=await B();await Q(j,T);let F=await y();if(!F.eligible||F.installationKey!==H.installationKey)throw Nn("installation-changed");let q=["add","-w","--save-exact",`${rI}@${_}`,`--registry=${hf}`];return gge(J=>j.desktop?j.desktop.runPlugin(q,j.profileDir,J):f(j,["plugin","--profile",j.profileName,...q],J),{signal:T,timeoutMs:n.installTimeoutMs??FWe,errorCode:"install-failed"})}return Object.freeze({inspect:y,install:m})}var aI=qe(xD(),1);import{createHash as qWe,randomUUID as tH}from"node:crypto";import{mkdir as zWe,open as VWe,readFile as Ege,rename as WWe,stat as Cge,unlink as uge,writeFile as ZWe}from"node:fs/promises";import{isAbsolute as lge,join as Cf}from"node:path";var uf=new Set(["installing","verifying"]),XWe=new Set([...uf,"restart-required","completed","failed","interrupted"]),pge=256*1024,$We=["package.json","pnpm-lock.yaml","pnpm-workspace.yaml"],Tb=Symbol("no update lock");function wt(n){return Object.assign(new Error(n),{code:n})}async function dge(n=globalThis.fetch,t=1e4){let o;try{if(o=await n(`${hf}${encodeURIComponent(rI)}/latest`,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(t)}),!o.ok)throw wt("check-failed");if(Number(o.headers.get("content-length"))>pge)throw wt("invalid-release");let i=[],e=0;for await(let c of o.body){if(e+=c.byteLength,e>pge)throw wt("invalid-release");i.push(Buffer.from(c))}let a=JSON.parse(Buffer.concat(i).toString("utf8")),A=a.version;if(a.name!==rI||typeof A!="string"||aI.default.valid(A)!==A||aI.default.prerelease(A))throw wt("invalid-release");let r=a.engines?.node;if(r!==void 0&&(typeof r!="string"||!aI.default.validRange(r)))throw wt("invalid-release");let s=new URL(a.dist?.tarball),g=a.dist?.integrity;if(s.origin!==new URL(hf).origin||s.username||s.password||s.search||s.hash||s.pathname!==`/@xmanrui/dsh-im/-/dsh-im-${A}.tgz`||typeof g!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(g))throw wt("invalid-release");return{version:A,nodeRange:r??"*",integrity:g,tarball:s.href}}catch(i){throw i?.code==="invalid-release"||i instanceof SyntaxError||i instanceof TypeError&&o?.ok?wt("invalid-release"):wt("check-failed")}}function hge(n){if(!lge(n.homeDir??"")||!lge(n.profileDir??""))return null;let t=qWe("sha256").update(n.profileDir).digest("hex").slice(0,24),o=Cf(n.homeDir,"updates","dsh-im",t);return{directory:o,state:Cf(o,"state.json"),lock:Cf(o,"install.lock"),backup:Cf(o,"before.json")}}async function AH(n,t=null){try{if((await Cge(n)).size>10*1024*1024)throw wt("state-unavailable");return JSON.parse(await Ege(n,"utf8"))}catch(o){if(o.code==="ENOENT")return t;throw wt("state-unavailable")}}async function Ef(n,t){let o=`${n}.${tH()}.tmp`;try{await ZWe(o,`${JSON.stringify(t,null,2)} -`,{mode:384,flag:"wx"}),await WWe(o,n)}catch{throw wt("state-unavailable")}finally{await uge(o).catch(i=>{if(i.code!=="ENOENT")throw wt("state-unavailable")})}}function e6e(n){if(!Number.isSafeInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return t.code!=="ESRCH"}}function A6e(n){if(!n)return null;let{id:t,state:o,targetVersion:i,message:e}=n;return{id:t,state:o,targetVersion:i,message:e}}function Bge({runtime:n,runningVersion:t=Rf.version,nodeVersion:o=process.versions.node,fetchImpl:i=globalThis.fetch,now:e=Date.now,checkTimeoutMs:a=1e4,confirmationTtlMs:A=10*6e4,installTimeoutMs:r=15*6e4}={}){let s={},g=null,c=null,I=-1/0,d=null,B=null,f=null,Q=null,y=!1;function m(){if(y)throw wt("disposed")}async function _(z){let U=hge(z);if(!U)return null;if(Q?.statePath===U.state)return Q.job;let N=await AH(U.state),k=await AH(U.lock,Tb);if(!N)return k!==Tb?{id:"locked",state:"interrupted",message:"recovery-required",targetVersion:null}:null;if(!XWe.has(N.state)||typeof N.id!="string"||!aI.default.valid(N.targetVersion))throw wt("state-unavailable");if(uf.has(N.state)&&N.id!==d?.id&&(k===Tb||k?.id!==N.id||!e6e(k?.pid))&&(N={...N,state:"interrupted",message:"recovery-required"}),N.id!==d?.id&&!uf.has(N.state)){if(k!==Tb)return{...N,state:"interrupted",message:"recovery-required"};if(["failed","interrupted"].includes(N.state)&&z.packageValid===!0&&z.installedVersion===t&&!z.blockedReason)return N.targetVersion===t?{...N,state:"completed",message:"recovered"}:{...N,recoverable:!0}}return N.state==="restart-required"||N.state==="completed"?z.installedVersion!==N.targetVersion||z.packageValid!==!0?{...N,state:"interrupted",message:"installation-changed"}:{...N,state:t===N.targetVersion?"completed":"restart-required"}:N}function T(z,U){let N=z.blockedReason??g?.blockedReason??null;U?.state==="interrupted"&&!U.recoverable||U?.state==="failed"&&z.installedVersion!==t?N="recovery-required":(U?.state==="restart-required"||z.installedVersion&&z.installedVersion!==t)&&(N="pending-restart");let k=uf.has(U?.state),V=!!(z.eligible&&!N&&!k&&g?.checkId&&e(){try{let z=await n.inspect({preflight:!0}),U=await dge(i,a);return m(),g={release:U,checkId:tH(),checkedAt:e(),expiresAt:e()+A,installationKey:z.installationKey,profileDir:z.profileDir,blockedReason:z.blockedReason??(aI.default.satisfies(o,U.nodeRange)?null:"incompatible-node")},T(z,await _(z))}catch(z){throw g&&(g={...g,checkId:null,expiresAt:0}),z}finally{c=null}})(),c))}async function j(z,U){(await AH(z.lock))?.id===U&&await uge(z.lock)}async function F(z,U,N){let k={};for(let V of $We)try{let ee=Cf(z.profileDir,V);if((await Cge(ee)).size>3*1024*1024)throw wt("state-unavailable");k[V]=await Ege(ee,"utf8")}catch(ee){if(ee.code!=="ENOENT")throw wt("state-unavailable")}await Ef(U.backup,{jobId:N.id,previousVersion:N.previousVersion,files:k})}function q(z){d={...d,state:"interrupted",message:"state-unavailable"},Q={statePath:z.state,job:d}}async function J(z,U,N){let k=AbortSignal.timeout(r);try{if(await n.install(U.targetVersion,{signal:AbortSignal.any([f.signal,k]),expectedInstallationKey:N.installationKey}),y)throw wt("interrupted");d={...d,state:"verifying",updatedAt:e()},await Ef(z.state,d);let V=await n.inspect();if(V.homeDir!==N.homeDir||V.profileDir!==N.profileDir||V.profileName!==N.profileName||V.blockedReason==="installation-changed")throw wt("installation-changed");if(V.installedVersion!==U.targetVersion||V.packageValid!==!0||V.blockedReason&&V.blockedReason!=="pending-restart")throw wt("verify-failed");d={...d,state:"restart-required",message:null,updatedAt:e()},await Ef(z.state,d)}catch(V){let ee=k.aborted||V.code==="install-timeout",ie=y||f.signal.aborted||!ee&&["interrupted","install-interrupted"].includes(V.code);d={...d,state:ie?"interrupted":"failed",message:ie?"interrupted":ee?"install-timeout":["verify-failed","state-unavailable","installation-changed","registry-conflict"].includes(V.code)?V.code:"install-failed",updatedAt:e()};try{await Ef(z.state,d)}catch{q(z);return}}await j(z,U.id)}function x({checkId:z,requestId:U}){return Us(s,"install",async()=>{m();let N=await n.inspect({preflight:!0}),k=await _(N);if(k?.requestId===U)return T(N,k);if(uf.has(k?.state)||k?.state==="restart-required")throw wt("update-busy");let V=g;if(!V||!z||V.checkId!==z||e()>=V.expiresAt)throw wt("check-expired");if(N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw wt("installation-changed");if(!T(N,k).canInstall)throw wt(N.blockedReason??"update-busy");let ee=hge(N);if(!ee)throw wt("state-unavailable");let ie={id:tH(),requestId:U,state:"installing",message:null,targetVersion:V.release.version,previousVersion:N.installedVersion,startedAt:e(),updatedAt:e()},Te=!1;try{await zWe(ee.directory,{recursive:!0,mode:448});let se=await VWe(ee.lock,"wx",384);Te=!0;try{await se.writeFile(JSON.stringify({id:ie.id,pid:process.pid,startedAt:e()}))}finally{await se.close()}let Ne=await dge(i,a);if(JSON.stringify(Ne)!==JSON.stringify(V.release))throw wt("check-expired");if(N=await n.inspect({preflight:!0}),N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw wt("installation-changed");if(!N.eligible||N.blockedReason)throw wt(N.blockedReason??"update-busy");m(),await F(N,ee,ie),await Ef(ee.state,ie),m()}catch(se){throw Te&&await j(ee,ie.id),se.code==="EEXIST"?wt("update-busy"):se.code?.startsWith("E")?wt("state-unavailable"):se}return d=ie,f=new AbortController,B=J(ee,ie,N).catch(()=>{q(ee)}),T(N,ie)})}async function P(){y=!0,f?.abort(),B&&await B}return Object.freeze({status:R,check:H,install:x,close:P})}var t6e="/dsh-im",r6e=Object.freeze(["update.status","update.check","update.install"]);function a6e(n,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let o=Object.keys(t);return n!=="update.install"?o.length===0:o.length===2&&o.every(i=>i==="checkId"||i==="requestId")&&["checkId","requestId"].every(i=>typeof t[i]=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t[i]))}var i6e=new Set(["check-failed","invalid-release","check-expired","installation-changed","update-busy","install-failed","verify-failed","state-unavailable","interrupted","disposed","source-install","unknown-profile","unsupported-runtime","registry-conflict","incompatible-node","pending-restart","recovery-required","executor-unavailable","invalid-installation","registry-check-failed","install-timeout","install-interrupted","invalid-version"]);function o6e(n){return async(t,o,i)=>{if(!r6e.includes(t)||!a6e(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid update request."}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"Request cancelled."}};try{return{ok:!0,value:t==="update.install"?await n.install(o):t==="update.check"?await n.check():await n.status()}}catch(e){let a=i6e.has(e?.code)?e.code:"update-failed";return{ok:!1,error:{code:a,message:a}}}}}function fge(n,t={}){let o=t.runtime??Ige({ctx:n,moduleUrl:import.meta.url}),i=t.service??Bge({runtime:o}),e=n.connection.rpc.handle(t6e,o6e(i),{authority:"loopback"});return n.effect(()=>()=>i.close(),"dsh-im: close update installer"),e}var Qge="dsh-im-host",n6e=["connection","credentials","apiProxy","typertGateway"];function s6e(n,t){let o=n[t]??{};return n.rpcAuthority===void 0?o:{...o,rpcAuthority:n.rpcAuthority}}function g6e(n={}){let t=n.installUpdateRpc??fge,o=n.applyFeishu??OW,i=n.applyWeixin??C5,e=n.applyDingtalk??jx,a=n.applyWecom??H6,A=n.applyQq??JW,r=n.applySlack??g6,s=n.applyTelegram??D6,g=n.applyDiscord??EY,c=n.applyOffice??yY,I=n.applyWhatsapp??nge,d=[["feishu",o],["weixin",i],["dingtalk",e],["wecom",a],["qq",A],["slack",r],["telegram",s],["discord",g],["whatsapp",I],["office",c]];return Object.freeze({name:Qge,inject:n6e,async apply(B,f={}){KH(f.language??process.env.DSH_IM_LANGUAGE),typeof B?.inject=="function"?B.inject(["tools","systemPrompt"],m=>{SM(m)}):SM(B);let Q=typeof B?.logger=="function"?B.logger(Qge):B?.logger??console;if(B?.connection?.rpc)try{t(B)}catch(m){Q.error?.("[dsh-im] failed to activate update management; continuing with channels",m)}let y=[];for(let[m,_]of d)try{await _(B,s6e(f,m))}catch(T){y.push(T),Q.error?.(`[dsh-im] failed to activate ${m}; continuing with the remaining channels`,T)}if(y.length===d.length)throw new AggregateError(y,"dsh-im failed to activate every channel")}})}async function JkA(n,t={}){return g6e().apply(n,t)}export{JkA as apply,g6e as createImHostPlugin,n6e as inject,Qge as name}; +${n.stack}`:i}function YFe(n){n<1028||(fg[n]=Hu,Hu=n)}function Lu(n,t){return n=n>>>0,Rd().subarray(n/1,n/1+t)}var ol=null;function $e(){return(ol===null||ol.buffer.detached===!0||ol.buffer.detached===void 0&&ol.buffer!==ae.memory.buffer)&&(ol=new DataView(ae.memory.buffer)),ol}function wr(n,t){return n=n>>>0,qFe(n,t)}var Uu=null;function Rd(){return(Uu===null||Uu.byteLength===0)&&(Uu=new Uint8Array(ae.memory.buffer)),Uu}function Ge(n){return fg[n]}function Dr(n,t){try{return n.apply(this,t)}catch(o){ae.__wbindgen_export3(tA(o))}}var fg=new Array(1024).fill(void 0);fg.push(void 0,null,!0,!1);var Hu=fg.length;function fn(n){return n==null}function jFe(n,t,o,i){let e={a:n,b:t,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let r=e.a;e.a=0;try{return i(r,e.b,...A)}finally{e.a=r,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,_9.unregister(e))},_9.register(a,e,e),a}function _t(n,t){let o=t(n.length*1,1)>>>0;return Rd().set(n,o/1),KA=n.length,o}function T9(n,t){let o=t(n.length*4,4)>>>0,i=$e();for(let e=0;e>>0;return Rd().subarray(s,s+r.length).set(r),KA=r.length,s}let i=n.length,e=t(i,1)>>>0,a=Rd(),A=0;for(;A127)break;a[e+A]=r}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let r=Rd().subarray(e+A,e+i),s=Ku.encodeInto(n,r);A+=s.written,e=o(e,i,A,1)>>>0}return KA=A,e}function mA(n){let t=Ge(n);return YFe(n),t}var pD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});pD.decode();var JFe=2146435072,kG=0;function qFe(n,t){return kG+=t,kG>=JFe&&(pD=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),pD.decode(),kG=t),pD.decode(Rd().subarray(n,n+t))}var Ku=new TextEncoder;"encodeInto"in Ku||(Ku.encodeInto=function(n,t){let o=Ku.encode(n);return t.set(o),{read:n.length,written:o.length}});var KA=0,zFe,ae;function VFe(n,t){return ae=n.exports,zFe=t,ol=null,Uu=null,ae}function R9(n){if(ae!==void 0)return ae;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=HFe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,t);return VFe(o,n)}var WFe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function k9(n){let t=atob(n),o=new Uint8Array(t.length);for(let i=0;in.length===33?n:Buffer.concat([Qg,n]),ur={generateKeyPair:()=>{let{pubKey:n,privKey:t}=_c.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(n.slice(1))}},sharedKey:(n,t)=>{let o=_c.calculateAgreement(vo(t),n);return Buffer.from(o)},sign:(n,t)=>_c.calculateSignature(n,t),verify:(n,t,o)=>{try{return _c.verifySignature(vo(n),t,o),!0}catch{return!1}}},QD=(n,t)=>{let o=ur.generateKeyPair(),i=vo(o.public),e=ur.sign(n.private,i);return{keyPair:o,signature:e,keyId:t}},P9=16;function nl(n,t,o,i){let e=PG("aes-256-gcm",t,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function sl(n,t,o,i){let e=GG("aes-256-gcm",t,o),a=n.slice(0,n.length-P9),A=n.slice(n.length-P9);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function G9(n,t,o){let i=PG("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function F9(n,t,o){let i=GG("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function L9(n,t){return aLe(n.subarray(16),t,n.subarray(0,16))}function aLe(n,t,o){let i=GG("aes-256-cbc",t,o);return Buffer.concat([i.update(n),i.final()])}function U9(n,t){let o=rLe(16),i=PG("aes-256-cbc",t,o);return Buffer.concat([o,i.update(n),i.final()])}function mn(n,t,o="sha256"){return tLe(o,t).update(n).digest()}function Gd(n){return ALe("sha256").update(n).digest()}async function yD(n,t){let i=new TextEncoder().encode(n),e=new Uint8Array(t instanceof Uint8Array?t:new Uint8Array(t)),a=await v9.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await v9.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var qu={replacer:(n,t)=>Buffer.isBuffer(t)||t instanceof Uint8Array||t?.type==="Buffer"?{type:"Buffer",data:Buffer.from(t?.data||t).toString("base64")}:t,reviver:(n,t)=>{if(typeof t=="object"&&t!==null&&t.type==="Buffer"&&typeof t.data=="string")return Buffer.from(t.data,"base64");if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(t);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return t}},Fd=(n,t="me")=>(n?.fromMe?t:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",x9=n=>n==null||n==="",oLe=n=>{let o=(Ju(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},Y9=n=>{let t=new Uint8Array(n);if(t.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=t[t.length-1];if(o>t.length)throw new Error(`unpad given ${t.length} bytes, but pad is ${o}`);return new Uint8Array(t.buffer,t.byteOffset,t.length-o)},j9=n=>(n.sort(),"2:"+Gd(Buffer.from(n.join(""))).toString("base64").slice(0,6)),Ld=n=>oLe(oe.Message.encode(n).finish()),J9=()=>Uint16Array.from(Ju(2))[0]&16383,yg=(n,t=4)=>{let o=n,i=new Uint8Array(t);for(let e=t-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},Lr=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,Ba=(n=new Date)=>Math.floor(n.getTime()/1e3);var zu=n=>q9(n).delay,q9=n=>{let t=new Error().stack,o,i;return{delay:new Promise((A,r)=>{o=setTimeout(A,n),i=r}),cancel:()=>{clearTimeout(o),i(new mD.Boom("Cancelled",{statusCode:500,data:{stack:t}}))}}};async function Ud(n,t){if(!n)return new Promise(t);let o=new Error().stack,{delay:i,cancel:e}=q9(n);return new Promise((A,r)=>{i.then(()=>r(new mD.Boom("Timed Out",{statusCode:Zt.timedOut,data:{stack:o}}))).catch(s=>r(s)),t(A,r)}).finally(e)}var Ur=n=>{let t=Buffer.alloc(44);if(t.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=yA(n);e?.user&&(t.write(e.user,8),t.write("@c.us",8+e.user.length))}return Ju(16).copy(t,28),"3EB0"+iLe("sha256").update(t).digest().toString("hex").toUpperCase().substring(0,18)},FG=()=>"3EB0"+Ju(18).toString("hex").toUpperCase();function LG(n,t){return async(o,i)=>{let e,a;await Ud(i,(A,r)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&r(g?.error||new mD.Boom("Connection Closed",{statusCode:Zt.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(t,e)}).finally(()=>{n.off(t,e),n.off("connection.update",a)})}}var z9=n=>LG(n,"connection.update");var V9=()=>{let n=Ju(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},nLe={sender:oe.WebMessageInfo.Status.SERVER_ACK,played:oe.WebMessageInfo.Status.PLAYED,read:oe.WebMessageInfo.Status.READ,"read-self":oe.WebMessageInfo.Status.READ},W9=n=>{let t=nLe[n];return typeof n>"u"?oe.WebMessageInfo.Status.DELIVERY_ACK:t},sLe={conflict:Zt.connectionReplaced},Z9=n=>{let[t]=ls(n),o=t?.tag||"unknown",i=+(n.attrs.code||sLe[o]||Zt.badSession);return i===Zt.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},X9=({tag:n,attrs:t})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":t.reason==="timeout"?o="timeout":o="terminate";break;case"preaccept":o="preaccept";break;case"transport":o="transport";break;case"relaylatency":o="relaylatency";break;case"reject":o="reject";break;case"accept":o="accept";break;default:o="ringing";break}return o},H9="Unexpected server response: ",$9=n=>{let t=500;if(n?.message?.includes(H9)){let o=+n?.message.slice(H9.length);!Number.isNaN(o)&&o>=400&&(t=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(t=408);return t};function SD(n){for(let t in n)typeof n[t]>"u"&&delete n[t];return n}var K9="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function eX(n){let t=0,o=0,i=[];for(let e of n)for(t=t<<8|e&255,o+=8;o>=5;)i.push(K9.charAt(t>>>o-5&31)),o-=5;return o>0&&i.push(K9.charAt(t<<5-o&31)),i.join("")}function AX(n){return oe.Message.encode(n).finish()}var gl=qe(Gr(),1);var gLe=async(n,t)=>qA(n)||oa(n)?n:await t.lidMapping.getLIDForPN(n)||n,cLe=async(n,t,o,i,e)=>{let{senderAlt:a}=wD(n);if(a&&qA(a)&&bt(t)&&i===t)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:t}]),await o.migrateSession(t,a),e.debug({sender:t,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:t,senderAlt:a,error:A},"Failed to store LID mapping")}},DD="Message absent from node",tX="Key used already or never filled",rX="Your account has been restricted",ILe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},cl={SenderReachoutTimelocked:463,ParsingError:487,UnrecognizedStanza:488,UnrecognizedStanzaClass:489,UnrecognizedStanzaType:490,InvalidProtobuf:491,InvalidHostedCompanionStanza:493,MissingMessageSecret:495,SignalErrorOldCounter:496,MessageDeletedOnPeer:499,UnhandledError:500,UnsupportedAdminRevoke:550,UnsupportedLIDGroup:551,DBOperationFailed:552},UG={MessageAccountRestriction:"463",SmaxInvalid:"479"},wD=n=>{let t,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(t=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(t=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:t,recipientAlt:o}};function HG(n,t,o){let i,e,a,A=!1,r=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!r)throw new gl.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new gl.Boom("Invalid message stanza: missing from attribute",{data:n});let I=wD(n),d=m=>Mt(m,t),B=m=>Mt(m,o);if(bt(s)||qA(s)||oa(s)||Cr(s)){if(c&&!Nd(c)){if(!d(s)&&!B(s))throw new gl.Boom("receipient present, but msg not from me",{data:n});(d(s)||B(s))&&(A=!0),e=c}else(d(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(Fr(s)){if(!g)throw new gl.Boom("No participant in group message");(d(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(Fu(s)){if(!g)throw new gl.Boom("No participant in group message");let m=d(g);Bg(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(wc(s))i="newsletter",e=s,a=s,(d(s)||B(s))&&(A=!0);else throw new gl.Boom("Unknown message type",{data:n});let f=n?.attrs?.notify,Q={remoteJid:e,remoteJidAlt:Fr(e)?void 0:I.senderAlt,remoteJidUsername:Fr(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:r,participant:g,participantAlt:Fr(e)?I.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:I.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:Q,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:f,broadcast:Fu(s)};return Q.fromMe&&(y.status=oe.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var aX=(n,t,o,i,e)=>{let{fullMessage:a,author:A,sender:r}=HG(n,t,o);return{fullMessage:a,category:n.attrs.category,author:A,async decrypt(){let s=0;if(Array.isArray(n.content))for(let{tag:g,attrs:c,content:I}of n.content){if(g==="verified_name"&&I instanceof Uint8Array){let f=oe.VerifiedNameCertificate.decode(I),Q=oe.VerifiedNameCertificate.Details.decode(f.details);a.verifiedBizName=Q.verifiedName}if(g==="unavailable"&&c.type==="view_once"&&(a.key.isViewOnce=!0),c.count&&g==="enc"&&(a.retryCount=Number(c.count)),g!=="enc"&&g!=="plaintext"||!(I instanceof Uint8Array))continue;s+=1;let d,B=await gLe(A,i);g!=="plaintext"&&await cLe(n,A,i,B,e);try{let f=g==="plaintext"?"plaintext":c.type;switch(f){case"skmsg":d=await i.decryptGroupMessage({group:r,authorJid:A,msg:I});break;case"pkmsg":case"msg":d=await i.decryptMessage({jid:B,type:f,ciphertext:I});break;case"plaintext":d=I;break;default:throw new Error(`Unknown e2e type: ${f}`)}let Q=oe.Message.decode(f!=="plaintext"?Y9(d):d);if(Q=Q.deviceSentMessage?.message||Q,Q.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:Q.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,Q):a.message=Q}catch(f){let Q={key:a.key,err:f,messageType:g==="plaintext"?"plaintext":c.type,sender:r,author:A,isSessionRecordError:lLe(f)};e.error(Q,"failed to decrypt message"),a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[f.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[DD])}}};function lLe(n){let t=n?.message||n?.toString()||"";return ILe.sessionRecordErrors.some(o=>t.includes(o))}var Ng=qe(Gr(),1);import{randomBytes as A2}from"crypto";import{promises as t2}from"fs";var Dn=qe(Gr(),1);import{exec as lje}from"child_process";import*as io from"crypto";import{once as Oh}from"events";import{createReadStream as mO,createWriteStream as qL,promises as Mh}from"fs";import{tmpdir as _ae}from"os";import{join as QO}from"path";import{Readable as LB,Transform as pje}from"stream";import{URL as zL}from"url";var VL=()=>_ae(),Tae=async()=>{let[n,t]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(hee(),dee)).catch(()=>{})]);if(t)return{sharp:t};if(n)return{jimp:n};throw new Dn.Boom("No image processing library available")},dje=n=>`WhatsApp ${xae[n]} Keys`,SO=async(n,t,o)=>{let{stream:i}=await UB(n);o?.debug("got stream for raw upload");let e=io.createHash("sha256"),a=QO(_ae(),t+Ur()),A=qL(a),r=0;try{for await(let g of i)r+=g.length,e.update(g),A.write(g)||await Oh(A,"drain");A.end(),await Oh(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:r}}catch(s){A.destroy(),i.destroy();try{await Mh.unlink(a)}catch{}throw s}};async function Nae(n,t){if(!n)throw new Dn.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=yn(n,112,{info:dje(t)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var hje=async(n,t,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${t}`;lje(A,r=>{r?a(r):e()})}),WL=async(n,t=32)=>{n instanceof LB&&(n=await yO(n));let o=await Tae();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(t).jpeg({quality:50}).toBuffer(),original:{width:e.width,height:e.height}}}else if("jimp"in o&&typeof o.jimp?.Jimp=="object"){let i=await o.jimp.Jimp.read(n),e={width:i.width,height:i.height};return{buffer:await i.resize({w:t,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new Dn.Boom("No image processing library available")},Eje=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),DO=async(n,t)=>{let o,{width:i=640,height:e=640}=t||{};if(Buffer.isBuffer(n))o=n;else{let{stream:r}=await UB(n);o=await yO(r)}let a=await Tae(),A;if("sharp"in a&&typeof a.sharp?.default=="function")A=a.sharp.default(o).resize(i,e).jpeg({quality:50}).toBuffer();else if("jimp"in a&&typeof a.jimp?.Jimp=="function"){let r=await a.jimp.Jimp.read(o),s=Math.min(r.width,r.height);A=r.crop({x:0,y:0,w:s,h:s}).resize({w:i,h:e,mode:a.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50})}else throw new Dn.Boom("No image processing library available");return{img:await A}};async function Rae(n){let t=await Promise.resolve().then(()=>(bae(),Oae)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await t.parseBuffer(n,void 0,i):typeof n=="string"?o=await t.parseFile(n,i):o=await t.parseStream(n,void 0,i),o.format.duration}async function kae(n,t){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let d=mO(n);i=await yO(d)}else i=await yO(n);let a=(await o(i)).getChannelData(0),A=64,r=Math.floor(a.length/A),s=[];for(let d=0;dd*g);return new Uint8Array(c.map(d=>Math.floor(100*d)))}catch(o){t?.debug("Failed to generate waveform: "+o)}}var Mae=n=>{let t=new LB({read:()=>{}});return t.push(n),t.push(null),t},yO=async n=>{let t=[];for await(let o of n)t.push(o);return n.destroy(),Buffer.concat(t)},UB=async(n,t)=>{if(Buffer.isBuffer(n))return{stream:Mae(n),type:"buffer"};if("stream"in n)return{stream:n.stream,type:"readable"};let o=n.url.toString();if(o.startsWith("data:")){let i=Buffer.from(o.split(",")[1],"base64");return{stream:Mae(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await wO(n.url,t),type:"remote"}:{stream:mO(n.url),type:"file"}};async function vae(n,t,o){let i,e;if(t==="image"){let{buffer:a,original:A}=await WL(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(t==="video"){let a=QO(VL(),Ur()+".jpg");try{await hje(n,a,"00:00:00",{width:32,height:32}),i=(await Mh.readFile(a)).toString("base64"),await Mh.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var wO=async(n,t={})=>{let o=await fetch(n.toString(),{dispatcher:t.dispatcher,method:"GET",headers:t.headers});if(!o.ok)throw new Dn.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof LB?o.body:LB.fromWeb(o.body)},Pae=async(n,t,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await UB(n,e);o?.debug("fetched media stream");let r=io.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await Nae(r,t),I=QO(VL(),t+Ur()+"-enc"),d=qL(I),B,f;i&&(f=QO(VL(),t+Ur()+"-original"),B=qL(f));let Q=0,y=io.createCipheriv("aes-256-cbc",s,g),m=io.createHmac("sha256",c).update(g),_=io.createHash("sha256"),T=io.createHash("sha256"),R=async H=>{T.update(H),m.update(H),d.write(H)||await Oh(d,"drain")};try{for await(let x of a){if(Q+=x.length,A==="remote"&&e?.maxContentLength&&Q+x.length>e.maxContentLength)throw new Dn.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(x)||await Oh(B,"drain")),_.update(x),await R(y.update(x))}await R(y.final());let H=m.digest().slice(0,10);T.update(H);let j=_.digest(),F=T.digest();d.write(H);let q=Oh(d,"finish"),J=B?Oh(B,"finish"):Promise.resolve();return d.end(),B?.end?.(),a.destroy(),await q,await J,o?.debug("encrypted data successfully"),{mediaKey:r,originalFilePath:f,encFilePath:I,mac:H,fileEncSha256:F,fileSha256:j,fileLength:Q}}catch(H){d.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),_.destroy(),T.destroy(),a.destroy();try{await Mh.unlink(I),f&&await Mh.unlink(f)}catch(j){o?.error({err:j},"failed deleting tmp files")}throw H}},ZL="mmg.whatsapp.net",bh=16,JL=n=>Math.floor(n/bh)*bh,HB=(n,t=ZL)=>`https://${t}${n}`,Cje=n=>{if(n)try{return new zL(n).host}catch{return}},_h=async({mediaKey:n,directPath:t,url:o},i,e={})=>{let a=e.host??Cje(o),A=t?HB(t,a):o;if(!A)throw new Dn.Boom("No valid media URL or directPath present in message",{statusCode:400});let r=await Nae(n,i);return uje(A,r,e)},uje=async(n,{cipherKey:t,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,r=0,s=!1;if(i){let m=JL(i||0);m&&(r=m-bh,A=m,s=!0)}let g=e?JL(e||0)+bh:void 0,c=a?.headers?a.headers:void 0,I={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:KB};(r||g)&&(I.Range=`bytes=${r}-`,g&&(I.Range+=g));let d=await wO(n,{...a||{},headers:I}),B=Buffer.from([]),f,Q=(m,_)=>{if(i||e){let T=A>=i?void 0:Math.max(i-A,0),R=A+m.lengththis.push(j)),T()}catch(j){T(j)}},final(m){try{Q(f.final(),_=>this.push(_)),m()}catch(_){m(_)}}});return d.pipe(y,{end:!0})};var Bje=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",Gae=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new zL(n),r=A.protocol==="https:"?await import("https"):await import("http"),g=(await Mh.stat(t)).size;return new Promise((c,I)=>{let d=r.request({hostname:A.hostname,port:A.port||(A.protocol==="https:"?443:80),path:A.pathname+A.search,method:"POST",headers:{...o,"Content-Length":g},agent:e,timeout:i},f=>{if(f.statusCode&&f.statusCode>=300&&f.statusCode<400&&f.headers.location){f.resume();let y=new zL(f.headers.location,n).toString();c(Gae({url:y,filePath:t,headers:o,timeoutMs:i,agent:e},a+1));return}let Q="";f.on("data",y=>Q+=y),f.on("end",()=>{try{c(JSON.parse(Q))}catch{c(void 0)}})});d.on("error",I),d.on("timeout",()=>{d.destroy(),I(new Error("Upload timeout"))});let B=mO(t);B.pipe(d),B.on("error",f=>{d.destroy(),I(f)})})},fje=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e})=>{let a=mO(t),A=LB.toWeb(a),r=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...r?{dispatcher:r}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},Qje=async(n,t)=>Bje()?(t?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),Gae(n)):(t?.debug("Using web-standard Fetch API for upload"),fje(n)),Fae=({customUploadHosts:n,fetchAgent:t,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:r,timeoutMs:s})=>{let g=await e(!1),c,I=[...n,...g.hosts];r=Eje(r);let B={...(()=>{let f=i?.headers;return f?Array.isArray(f)?Object.fromEntries(f):f:{}})(),"Content-Type":"application/octet-stream",Origin:KB};for(let{hostname:f}of I){o.debug(`uploading to "${f}"`);let Q=encodeURIComponent(g.auth),y=`https://${f}${$L[A]}/${r}?auth=${Q}&token=${r}`,m;try{if(m=await Qje({url:y,filePath:a,headers:B,timeoutMs:s,agent:t},o),m?.url||m?.direct_path){c={mediaUrl:m.url,directPath:m.direct_path,meta_hmac:m.meta_hmac,fbid:m.fbid,ts:m.ts};break}else throw g=await e(!0),new Error(`upload failed, reason: ${JSON.stringify(m)}`)}catch(_){let T=f===I[g.hosts.length-1]?.hostname;o.warn({trace:_?.stack,uploadResult:m},`Error in uploading to ${f} ${T?"":", retrying..."}`)}}if(!c)throw new Dn.Boom("Media upload failed on all hosts",{statusCode:500});return c},Lae=n=>yn(n,32,{info:"WhatsApp Media Retry Notification"}),Uae=(n,t,o)=>{let i={stanzaId:n.id},e=oe.ServerErrorReceipt.encode(i).finish(),a=io.randomBytes(12),A=Lae(t),r=nl(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:uA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:r},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},Hae=n=>{let t=Ie(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:t.attrs.jid,fromMe:t.attrs.from_me==="true",participant:t.attrs.participant}},i=Ie(n,"error");if(i){let e=+i.attrs.code;o.error=new Dn.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:XL(e)})}else{let e=Ie(n,"encrypt"),a=ua(e,"enc_p"),A=ua(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new Dn.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},Kae=({ciphertext:n,iv:t},o,i)=>{let e=Lae(o),a=sl(n,e,t,Buffer.from(i));return oe.MediaRetryNotification.decode(a)},XL=n=>yje[n],yje={[oe.MediaRetryNotification.ResultType.SUCCESS]:200,[oe.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[oe.MediaRetryNotification.ResultType.NOT_FOUND]:404,[oe.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as mje}from"crypto";var Sje=[{f:1},{f:3,s:[{f:2},{f:3},{f:8},{f:11},{f:17,s:[{f:21},{f:22}]},{f:25}]},{f:4,s:[{f:1},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:5,s:[{f:3},{f:4},{f:5},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:6,s:[{f:1},{f:17,s:[{f:21},{f:22}]},{f:30}]},{f:7,s:[{f:2},{f:7},{f:10},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:8,s:[{f:2},{f:7},{f:9},{f:17,s:[{f:21},{f:22}]},{f:21}]},{f:9,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:12,s:[{f:1},{f:2},{f:14,m:!0},{f:15}]},{f:18,s:[{f:6},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:26,s:[{f:4},{f:5},{f:8},{f:13},{f:17,s:[{f:21},{f:22}]}]},{f:28,s:[{f:1},{f:2},{f:4},{f:5},{f:6},{f:7,s:[{f:21},{f:22}]}]},{f:37,s:[{f:1,m:!0}]},{f:49,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:53,s:[{f:1,m:!0}]},{f:55,s:[{f:1,m:!0}]},{f:58,s:[{f:1,m:!0}]},{f:59,s:[{f:1,m:!0}]},{f:60,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:64,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:66,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:74,s:[{f:1,m:!0}]},{f:87,s:[{f:1,m:!0}]},{f:88,s:[{f:1},{f:2,s:[{f:1}]},{f:3,s:[{f:21},{f:22}]}]},{f:92,s:[{f:1,m:!0}]},{f:93,s:[{f:1,m:!0}]},{f:94,s:[{f:1,m:!0}]}],jae=n=>{let t=new Map;for(let o of n)t.set(o.f,{m:o.m,children:o.s?jae(o.s):void 0});return t},Dje=jae(Sje),wje=new Map,Oje="Report Token",OO={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},bO=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,bje=(n,t,o,i,e)=>{let a=Buffer.concat([Buffer.from(t,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return yn(e,32,{info:a.toString("latin1")})},Jae=(n,t)=>{let o=[],i=0;for(;i>3,A=e.value&7,r=i;i+=e.bytes;let s=t.get(a),g=I=>I>n.length?!1:(o.push({num:a,bytes:n.subarray(r,I)}),i=I,!0),c=I=>I>n.length?!1:(i=I,!0);if(A===OO.VARINT){let I=e2(n,i);if(!I.ok)return null;let d=i+I.bytes;if(!s){if(!c(d))return null;continue}if(!g(d))return null;continue}if(A===OO.FIXED64){let I=i+8;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===OO.FIXED32){let I=i+4;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===OO.BYTES){let I=e2(n,i);if(!I.ok)return null;let d=i+I.bytes,B=d+I.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let f=Jae(n.subarray(d,B),s.children??wje);if(f===null)return null;if(f.length>0){let Q=Yae(e.value),y=Yae(f.length);o.push({num:a,bytes:Buffer.concat([Q,y,f])})}i=B;continue}o.push({num:a,bytes:n.subarray(r,B)}),i=B;continue}return null}return o.length===0?Buffer.alloc(0):(o.sort((e,a)=>e.num-a.num),Buffer.concat(o.map(e=>e.bytes)))},e2=(n,t)=>{let o=0,i=0,e=0;for(;t+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},Yae=n=>{let t=[],o=n>>>0;for(;o>127;)t.push(o&127|128),o>>>=7;return t.push(o),Buffer.from(t)},qae=async(n,t,o)=>{let i=t.messageContextInfo?.messageSecret;if(!i||!o.id)return null;let e=o.fromMe?o.remoteJid:o.participant||o.remoteJid,a=o.fromMe&&o.participant||o.remoteJid,A=bje(Oje,o.id,e,a,i),r=Jae(n,Dje);if(!r||r.length===0)return null;let s=mje("sha256",A).update(r).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var Mje={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},zae={image:oe.Message.ImageMessage,video:oe.Message.VideoMessage,audio:oe.Message.AudioMessage,sticker:oe.Message.StickerMessage,document:oe.Message.DocumentMessage},_je=n=>n.match(tie)?.[0],Tje=async(n,t,o)=>{let i=_je(n);if(t&&i)try{return await t(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},Vae=async n=>{let t;if(typeof n=="number")t=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),t=parseInt(o,16),t}},xB=async(n,t)=>{let o=t.logger,i;for(let j of rie)j in n&&(i=j);if(!i)throw new Ng.Boom("Invalid media type",{statusCode:400});let e={...n,media:n[i]};delete e[i];let a=typeof e.media=="object"&&"url"in e.media&&!!e.media.url&&!!t.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=Mje[i]),a){let j=await t.mediaCache.get(a);if(j){o?.debug({cacheableKey:a},"got media cache hit");let F=oe.Message.decode(j),q=`${i}Message`;return Object.assign(F[q],{...e,media:void 0}),F}}if(!!t.jid&&wc(t.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:j,fileSha256:F,fileLength:q}=await SO(e.media,t.mediaTypeOverride||i,o),J=F.toString("base64"),{mediaUrl:x,directPath:P}=await t.upload(j,{fileEncSha256B64:J,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});await t2.unlink(j);let z=oe.Message.fromObject({[`${i}Message`]:zae[i].fromObject({url:x,directPath:P,fileSha256:F,fileLength:q,...e,media:void 0})});return e.ptv&&(z.ptvMessage=z.videoMessage,delete z.videoMessage),z.stickerMessage&&(z.stickerMessage.stickerSentTs=Date.now()),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(z).finish())),z}let r=i==="audio"&&typeof e.seconds>"u",s=(i==="image"||i==="video")&&typeof e.jpegThumbnail>"u",g=i==="audio"&&e.ptt===!0&&typeof e.waveform>"u",c=t.backgroundColor&&i==="audio"&&e.ptt===!0,I=r||s,{mediaKey:d,encFilePath:B,originalFilePath:f,fileEncSha256:Q,fileSha256:y,fileLength:m}=await Pae(e.media,t.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:I,opts:t.options}),_=Q.toString("base64"),[{mediaUrl:T,directPath:R}]=await Promise.all([(async()=>{let j=await t.upload(B,{fileEncSha256B64:_,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),j})(),(async()=>{try{if(s){let{thumbnail:j,originalImageDimensions:F}=await vae(f,i,t);e.jpegThumbnail=j,!e.width&&F&&(e.width=F.width,e.height=F.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}r&&(e.seconds=await Rae(f),o?.debug("computed audio duration")),g&&(e.waveform=await kae(f,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await Vae(t.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(j){o?.warn({trace:j.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await t2.unlink(B),f&&await t2.unlink(f),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),H=oe.Message.fromObject({[`${i}Message`]:zae[i].fromObject({url:T,directPath:R,mediaKey:d,fileEncSha256:Q,fileSha256:y,fileLength:m,mediaKeyTimestamp:Ba(),...e,media:void 0})});return e.ptv&&(H.ptvMessage=H.videoMessage,delete H.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(H).finish())),H},Nje=n=>{n=n||0;let t={ephemeralMessage:{message:{protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return oe.Message.fromObject(t)},Rje=(n,t)=>{let o=n.message;if(!o)throw new Ng.Boom("no content in message",{statusCode:400});o=Sa(o),o=oe.Message.decode(oe.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!t?0:1,i==="conversation"&&(o.extendedTextMessage={text:o[i]},delete o.conversation,i="extendedTextMessage");let a=o?.[i];return e>0?a.contextInfo={forwardingScore:e,isForwarded:!0}:a.contextInfo={},o},Ia=(n,t)=>typeof n=="object"&&n!==null&&t in n&&n[t]!==null&&n[t]!==void 0;function Tl(n,t){return typeof n=="object"&&n!==null&&t in n&&n[t]!==null}var kje=async(n,t)=>{var o,i;let e={};if(Ia(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await Tje(n.text,t.getUrlInfo,t.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let r=A.highQualityThumbnail;r&&(a.thumbnailDirectPath=r.directPath,a.mediaKey=r.mediaKey,a.mediaKeyTimestamp=r.mediaKeyTimestamp,a.thumbnailWidth=r.width,a.thumbnailHeight=r.height,a.thumbnailSha256=r.fileSha256,a.thumbnailEncSha256=r.fileEncSha256)}t.backgroundColor&&(a.backgroundArgb=await Vae(t.backgroundColor)),t.font&&(a.font=t.font),e.extendedTextMessage=a}else if(Ia(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new Ng.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=oe.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=oe.Message.ContactsArrayMessage.create(n.contacts)}else if(Ia(n,"location"))e.locationMessage=oe.Message.LocationMessage.create(n.location);else if(Ia(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=oe.Message.ReactionMessage.create(n.react);else if(Ia(n,"delete"))e.protocolMessage={key:n.delete,type:oe.Message.ProtocolMessage.Type.REVOKE};else if(Ia(n,"forward"))e=Rje(n.forward,n.force);else if(Ia(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?jB:0:n.disappearingMessagesInChat;e=Nje(a)}else if(Ia(n,"groupInvite")){if(e.groupInviteMessage={},e.groupInviteMessage.inviteCode=n.groupInvite.inviteCode,e.groupInviteMessage.inviteExpiration=n.groupInvite.inviteExpiration,e.groupInviteMessage.caption=n.groupInvite.text,e.groupInviteMessage.groupJid=n.groupInvite.jid,e.groupInviteMessage.groupName=n.groupInvite.subject,t.getProfilePicUrl){let a=await t.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:t?.options?.dispatcher});if(A.ok){let r=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=r}}}}else if(Ia(n,"pin"))e.pinInChatMessage={},e.messageContextInfo={},e.pinInChatMessage.key=n.pin,e.pinInChatMessage.type=n.type,e.pinInChatMessage.senderTimestampMs=Date.now(),e.messageContextInfo.messageAddOnDurationInSecs=n.type===1?n.time||86400:0;else if(Ia(n,"buttonReply"))switch(n.type){case"template":e.templateButtonReplyMessage={selectedDisplayText:n.buttonReply.displayText,selectedId:n.buttonReply.id,selectedIndex:n.buttonReply.index};break;case"plain":e.buttonsResponseMessage={selectedButtonId:n.buttonReply.id,selectedDisplayText:n.buttonReply.displayText,type:oe.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(Tl(n,"ptv")&&n.ptv){let{videoMessage:a}=await xB({video:n.video},t);e.ptvMessage=a}else if(Ia(n,"product")){let{imageMessage:a}=await xB({image:n.product.productImage},t);e.productMessage=oe.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(Ia(n,"listReply"))e.listResponseMessage={...n.listReply};else if(Ia(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&t.getCallLink){let A=await t.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?Aie:eie)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||A2(32)},e.eventMessage.name=n.event.name,e.eventMessage.description=n.event.description,e.eventMessage.startTime=a,e.eventMessage.endTime=n.event.endDate?n.event.endDate.getTime()/1e3:void 0,e.eventMessage.isCanceled=n.event.isCancelled??!1,e.eventMessage.extraGuestsAllowed=n.event.extraGuestsAllowed,e.eventMessage.isScheduleCall=n.event.isScheduleCall??!1,e.eventMessage.location=n.event.location}else if(Ia(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new Ng.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new Ng.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||A2(32)};let a={name:n.poll.name,selectableOptionsCount:n.poll.selectableCount,options:n.poll.values.map(A=>({optionName:A}))};n.poll.toAnnouncementGroup?e.pollCreationMessageV2=a:n.poll.selectableCount===1?e.pollCreationMessageV3=a:e.pollCreationMessage=a}else Ia(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:Ia(n,"sharePhoneNumber")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:Ia(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:Ia(n,"limitSharing")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await xB(n,t);if(Tl(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),Tl(n,"mentions")&&n.mentions?.length||Tl(n,"mentionAll")&&n.mentionAll){let a=Object.keys(e)[0],A=e[a];A&&"contextInfo"in A?(A.contextInfo=A.contextInfo||{},n.mentions?.length&&(A.contextInfo.mentionedJid=n.mentions),n.mentionAll&&(A.contextInfo.nonJidMentions=1)):A&&(A.contextInfo={mentionedJid:n.mentions,nonJidMentions:n.mentionAll?1:0})}if(Tl(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:oe.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),Tl(n,"contextInfo")&&n.contextInfo){let a=Object.keys(e)[0],A=e[a];"contextInfo"in A&&A.contextInfo?A.contextInfo={...A.contextInfo,...n.contextInfo}:A&&(A.contextInfo=n.contextInfo)}return Tl(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:oe.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),bO(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=A2(32))),oe.Message.create(e)},vje=(n,t,o)=>{o.timestamp||(o.timestamp=new Date);let i=Sa(t),e=YB(i),a=Ba(o.timestamp),{quoted:A,userJid:r}=o;if(A&&!wc(n)){let g=A.key.fromMe?r:A.participant||A.key.participant||A.key.remoteJid,c=Sa(A.message),I=YB(c);c=oe.Message.create({[I]:c[I]});let d=c[I];typeof d=="object"&&d&&"contextInfo"in d&&delete d.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=uA(g),B.stanzaId=A.key.id,B.quotedMessage=c,n!==A.key.remoteJid&&(B.remoteJid=A.key.remoteJid),B&&i[e]&&(i[e].contextInfo=B)}o?.ephemeralExpiration&&e!=="protocolMessage"&&e!=="ephemeralMessage"&&!wc(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||jB}),t=oe.Message.create(t);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||Ur()},message:t,messageTimestamp:a,messageStubParameters:[],participant:Fr(n)||Bg(n)?r:void 0,status:Td.PENDING};return oe.WebMessageInfo.fromObject(s)},Wae=async(n,t,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),vje(n,await kje(t,{...o,jid:n}),o)),YB=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},Sa=n=>{if(!n)return;for(let o=0;o<5;o++){let i=t(n);if(!i)break;n=i.message}return n;function t(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},Zae=n=>{let t=o=>o.imageMessage?{imageMessage:o.imageMessage}:o.documentMessage?{documentMessage:o.documentMessage}:o.videoMessage?{videoMessage:o.videoMessage}:o.locationMessage?{locationMessage:o.locationMessage}:{conversation:"contentText"in o?o.contentText:"hydratedContentText"in o?o.hydratedContentText:""};return n=Sa(n),n?.buttonsMessage?t(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?t(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?t(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?t(n?.templateMessage?.fourRowTemplate):n};var r2=(n,t)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===t.userJid);o?Object.assign(o,t):n.userReceipt.push(t)},a2=(n,t)=>{let o=Fd(t.key),i=(n.reactions||[]).filter(e=>Fd(e.key)!==o);t.text=t.text||"",i.push(t),n.reactions=i};var Xae=n=>{let t={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;t[A]||(t[A]={jid:o,participant:e,messageIds:[]}),t[A].messageIds.push(i)}return Object.values(t)},Pje=[410,404],i2=async(n,t,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&Pje.includes(A.status))return i.logger.info({key:n.key},"sending reupload media request..."),n=await i.reuploadRequest(n),await a();throw A});async function a(){let A=Zae(n.message);if(!A)throw new Ng.Boom("No message present",{statusCode:400,data:n});let r=YB(A),s=r?.replace("Message",""),g=A[r];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new Ng.Boom(`"${r}" message is not a media message`);let c;"thumbnailDirectPath"in g&&!("url"in g)?(c={directPath:g.thumbnailDirectPath,mediaKey:g.mediaKey},s="thumbnail-link"):c=g;let I=await _h(c,s,o);if(t==="buffer"){let d=[];for await(let B of I)d.push(B);return Buffer.concat(d)}return I}},$ae=n=>{n=Zae(n);let t=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!t)throw new Ng.Boom("given message is not a media message",{statusCode:400,data:n});return t};var MO=qe(Gr(),1);import{createHash as Uje}from"crypto";function Gje(n,t){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:vo(t)}),Fje=async({get:n},t,o)=>{let i=[];for(let e=t;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=t-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=ur.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,t]}},JB=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:yg(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),n2=(n,t)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:yg(t,3)},{tag:"value",attrs:{},content:n.public}]}),o2=n=>typeof n=="number"&&Number.isInteger(n),iie=n=>{let t=Ie(n,"keys");if(!t)return null;let o=ua(t,"type");if(!o||o.length!==1||o[0]!==Qg[0])return null;let i=ua(t,"identity"),e=Ie(t,"skey");if(!i||i.length!==32||!e)return null;let a=Oc(n,"registration",4);if(!o2(a))return null;let A=ua(e,"value"),r=ua(e,"signature"),s=Oc(e,"id",3);if(!A||A.length!==32||!r||!o2(s))return null;let g=Ie(t,"key"),c;if(g){let I=ua(g,"value"),d=Oc(g,"id",3);if(!I||I.length!==32||!o2(d))return null;c={keyId:d,publicKey:vo(I)}}return{registrationId:a,identityKey:vo(i),signedPreKey:{keyId:s,publicKey:vo(A),signature:r},preKey:c}},oie=async(n,t)=>{let o=A=>A?{keyId:Oc(A,"id",3),publicKey:vo(ua(A,"value")),signature:ua(A,"signature")}:void 0,i=PA(Ie(n,"list"),"user");for(let A of i)_i(A);let a=Gje(i,100);for(let A of a)for(let r of A){let s=Ie(r,"skey"),g=Ie(r,"key"),c=ua(r,"identity"),I=r.attrs.jid,d=Oc(r,"registration",4);await t.injectE2ESession({jid:I,session:{registrationId:d,identityKey:vo(c),signedPreKey:o(s),preKey:o(g)}})}},nie=(n,t,o,i)=>{let{user:e,device:a}=yA(t),A=[];for(let r of n){let{devices:s,id:g}=r,c=yA(g),{user:I,server:d}=c,{domainType:B}=c,f=s?.deviceList;if(Array.isArray(f))for(let{id:Q,keyIndex:y,isHosted:m}of f)(!i||Q!==0)&&(e!==I&&o!==I||a!==Q)&&(Q===0||y)&&(m&&(B=B===xt.LID?xt.HOSTED_LID:xt.HOSTED),A.push({user:I,device:Q,domainType:B,server:c9(d,B)}))}return A},s2=async({creds:n,keys:t},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=Lje(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await t.set({"pre-key":i});let r=await Fje(t,a[0],a[0]+a[1]);return{update:A,preKeys:r}},sie=async(n,t)=>{let{creds:o}=n,{update:i,preKeys:e}=await s2(n,t),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:OA},content:[{tag:"registration",attrs:{},content:yg(o.registrationId)},{tag:"type",attrs:{},content:Qg},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>n2(e[+A],+A))},JB(o.signedPreKey)]};return{update:i,node:a}};var Hje=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?oe.ClientPayload.UserAgent.Platform.ANDROID:oe.ClientPayload.UserAgent.Platform.WEB,releaseChannel:oe.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),gie={"Mac OS":oe.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:oe.ClientPayload.WebInfo.WebSubPlatform.WIN32},Kje=n=>{let t=oe.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&gie[n.browser[0]]&&n.browser[1]==="Desktop"&&(t=gie[n.browser[0]]),{webSubPlatform:t}},cie=n=>{let t={connectType:oe.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:oe.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:Hje(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(t.webInfo=Kje(n)),n.pushName&&(t.pushName=n.pushName),t},Iie=(n,t)=>{let{user:o,device:i}=yA(n),e={...cie(t),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return oe.ClientPayload.fromObject(e)},xje=n=>{let t=n.toUpperCase();return t==="ANDROID"?oe.DeviceProps.PlatformType.ANDROID_PHONE:oe.DeviceProps.PlatformType[t]||oe.DeviceProps.PlatformType.CHROME},lie=({registrationId:n,signedPreKey:t,signedIdentityKey:o},i)=>{let e=Uje("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:xje(i.browser[1]),requireFullSync:i.syncFullHistory,historySyncConfig:{storageQuotaMb:10240,inlineInitialPayloadInE2EeMsg:!0,recentSyncDaysLimit:void 0,supportCallLogHistory:!1,supportBotUserAgentChatHistory:!0,supportCagReactionsAndPolls:!0,supportBizHostedMsg:!0,supportRecentSyncChunkMessageCountTuning:!0,supportHostedGroupMsg:!0,supportFbidBotChatHistory:!0,supportAddOnHistorySyncMigration:void 0,supportMessageAssociation:!0,supportGroupHistory:!1,onDemandReady:void 0,supportGuestChat:void 0},version:{primary:10,secondary:15,tertiary:7}},A=oe.DeviceProps.encode(a).finish(),r={...cie(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:yg(n),eKeytype:Qg,eIdent:o.public,eSkeyId:yg(t.keyId,3),eSkeyVal:t.keyPair.public,eSkeySig:t.signature}};return oe.ClientPayload.fromObject(r)},pie=(n,{advSecretKey:t,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=Ie(n,"pair-success"),A=Ie(a,"device-identity"),r=Ie(a,"platform"),s=Ie(a,"device"),g=Ie(a,"biz");if(!A||!s)throw new MO.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,I=s.attrs.jid,d=s.attrs.lid,{details:B,hmac:f,accountType:Q}=oe.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);Q!==void 0&&Q===oe.ADVEncryptionType.HOSTED&&(y=g2);let m=mn(Buffer.concat([y,B]),Buffer.from(t,"base64"));if(Buffer.compare(f,m)!==0)throw new MO.Boom("Invalid account signature");let _=oe.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:T,accountSignature:R,details:H}=_,j=oe.ADVDeviceIdentity.decode(H),F=j.deviceType===oe.ADVEncryptionType.HOSTED?g2:die,q=Buffer.concat([F,H,o.public]);if(!ur.verify(T,q,R))throw new MO.Boom("Failed to verify account signature");let J=Buffer.concat([hie,H,o.public,T]);_.deviceSignature=ur.sign(o.private,J);let x=aie(d,T),P=qB(_,!1),z={tag:"iq",attrs:{to:OA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":j.keyIndex.toString()},content:P}]}]};return{creds:{account:_,me:{id:I,name:c,lid:d},signalIdentities:[...i||[],x],platform:r?.attrs.name},reply:z}},qB=(n,t)=>(n={...n},(!t||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),oe.ADVSignedDeviceIdentity.encode(n).finish());var Th=qe(Gr(),1);var uie=12,Eie=Buffer.alloc(0),Cie=n=>{let t=new ArrayBuffer(uie);return new DataView(t).setUint32(8,n),new Uint8Array(t)},c2=class{constructor(t,o){this.encKey=t,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(uie)}encrypt(t){let o=this.writeCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,nl(t,this.encKey,this.iv,Eie)}decrypt(t){let o=this.readCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,sl(t,this.decKey,this.iv,Eie)}},Bie=({keyPair:{private:n,public:t},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(fie),A=a.byteLength===32?a:Gd(a),r=A,s=A,g=A,c=0,I=!1,d=Buffer.alloc(0),B=null,f=!1,Q=null,y;e?(y=Buffer.alloc(7+e.byteLength+o.length),y.write("ED",0,"utf8"),y.writeUint8(0,2),y.writeUint8(1,3),y.writeUint8(e.byteLength>>16,4),y.writeUint16BE(e.byteLength&65535,5),y.set(e,7),y.set(o,7+e.byteLength)):y=Buffer.from(o);let m=q=>{B||(A=Gd(Buffer.concat([A,q])))},_=q=>{if(B)return B.encrypt(q);let J=nl(q,s,Cie(c++),A);return m(J),J},T=q=>{if(B)return B.decrypt(q);let J=sl(q,g,Cie(c++),A);return m(q),J},R=q=>{let J=yn(Buffer.from(q),64,{salt:r,info:""});return[J.subarray(0,32),J.subarray(32)]},H=q=>{let[J,x]=R(q);r=J,s=x,g=x,c=0},j=async()=>{f=!0;let[q,J]=R(new Uint8Array(0));B=new c2(q,J),f=!1,i.trace("Noise handler transitioned to Transport state"),Q&&(i.trace({length:d.length},"Flushing buffered frames after transport ready"),await F(Q),Q=null)},F=async q=>{let J;for(;;){if(d.length<3||(J=d[0]<<16|d[1]<<8|d[2],d.length{m(q.ephemeral),H(ur.sharedKey(n,q.ephemeral));let x=T(q.static);H(ur.sharedKey(n,x));let P=T(q.payload),{intermediate:z,leaf:U}=oe.CertChain.decode(P);if(!U?.details||!U?.signature)throw new Th.Boom("invalid noise leaf certificate",{statusCode:400});if(!z?.details||!z?.signature)throw new Th.Boom("invalid noise intermediate certificate",{statusCode:400});let N=oe.CertChain.NoiseCertificate.Details.decode(z.details),{issuerSerial:k}=N,V=ur.verify(N.key,U.details,U.signature),ee=ur.verify(I2.PUBLIC_KEY,z.details,z.signature);if(!V)throw new Th.Boom("noise certificate signature invalid",{statusCode:400});if(!ee)throw new Th.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(k!==I2.SERIAL)throw new Th.Boom("certification match failed",{statusCode:400});let ie=_(J.public);return H(ur.sharedKey(J.private,q.ephemeral)),ie},encodeFrame:q=>{B&&(q=B.encrypt(q));let J=q.byteLength,x=I?0:y.length,P=Buffer.allocUnsafe(x+3+J);return I||(P.set(y),I=!0),P[x]=J>>>16&255,P[x+1]=J>>>8&255,P[x+2]=J&255,P.set(q,x+3),P},decodeFrame:async(q,J)=>{if(f){d=Buffer.concat([d,q]),Q=J;return}d.length===0?d=Buffer.from(q):d=Buffer.concat([d,q]),await F(J)}}};import{pipeline as Yje}from"stream/promises";import{promisify as jje}from"util";import{createInflate as Jje,inflate as qje}from"zlib";var zje=jje(qje),Vje=n=>{for(let t of n){let o=t.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(bt(i)||Cr(i)))return i}},Wje=async(n,t)=>{let o=await _h(n,"md-msg-hist",{options:t}),i=Jje(),e=[];i.on("data",r=>e.push(r)),await Yje(o,i);let a=Buffer.concat(e);return oe.HistorySync.decode(a)},Zje=(n,t)=>{let o=[],i=[],e=[],a=[];t?.trace({progress:n.progress},"processing history of type "+n.syncType?.toString());for(let A of n.phoneNumberToLidMappings||[])A.lidJid&&A.pnJid&&a.push({lid:A.lidJid,pn:A.pnJid});switch(n.syncType){case oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case oe.HistorySync.HistorySyncType.RECENT:case oe.HistorySync.HistorySyncType.FULL:case oe.HistorySync.HistorySyncType.ON_DEMAND:for(let A of n.conversations){i.push({id:A.id,name:A.displayName||A.name||A.username||void 0,username:A.username||void 0,lid:A.lidJid||A.accountLid||void 0,phoneNumber:A.pnJid||void 0});let r=A.id,s=qA(r)||oa(r),g=bt(r)||Cr(r);if(s&&A.pnJid)a.push({lid:r,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:r});else if(s&&!A.pnJid){let I=Vje(A.messages||[]);I&&a.push({lid:r,pn:I})}let c=A.messages||[];delete A.messages;for(let I of c){let d=I.message;o.push(d),A.messages?.length||(A.messages=[{message:d}]),!d.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=Lr(d.messageTimestamp)),(d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_BSP||d.messageStubType===RA.BIZ_PRIVACY_MODE_TO_FB)&&d.messageStubParameters?.[0]&&i.push({id:d.key.participant||d.key.remoteJid,verifiedName:d.messageStubParameters?.[0]})}e.push(A)}break;case oe.HistorySync.HistorySyncType.PUSH_NAME:for(let A of n.pushnames)i.push({id:A.id,notify:A.pushname});break}return{chats:e,contacts:i,messages:o,lidPnMappings:a,pastParticipants:n.pastParticipants,syncType:n.syncType,progress:n.progress}},Qie=async(n,t,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=oe.HistorySync.decode(await zje(n.initialHistBootstrapInlinePayload)):i=await Wje(n,t),Zje(i,o)},_O=n=>(n?Sa(n):void 0)?.protocolMessage?.historySyncNotification;var Jo=qe(Gr(),1);var Rs;(function(n){n.Chat="label_jid",n.Message="label_message"})(Rs||(Rs={}));var yie=new kd;var mie=(n,t,o)=>{let i=[];if(!t)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=bt(t),A=a?t:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:t,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&qA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:t}}),i},Sie=(n,t)=>{for(let o of t)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var zB=n=>{let t=N9(n);return{indexKey:t.indexKey,valueEncryptionKey:t.valueEncryptionKey,valueMacKey:t.valueMacKey,snapshotMacKey:t.snapshotMacKey,patchMacKey:t.patchMacKey}},Die=(n,t,o,i)=>{let e=n===oe.SyncdMutation.SyncdOperation.SET?1:2,a=typeof o=="string"?Buffer.from(o,"base64"):o,A=new Uint8Array(1+a.length);A[0]=e,A.set(a,1);let r=new Uint8Array(8);r[7]=A.length;let s=new Uint8Array(A.length+t.length+r.length);return s.set(A,0),s.set(t,A.length),s.set(r,A.length+t.length),mn(s,i,"sha512").subarray(0,32)},wie=n=>{let t=Buffer.alloc(8);return t.writeUint32BE(n,4),t},Oie=({indexValueMap:n,hash:t})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let r=Buffer.from(e).toString("base64"),s=n[r];if(A===oe.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[r]}else o.push(a),n[r]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=yie.subtractThenAdd(t,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},l2=(n,t,o,i)=>{let e=Buffer.concat([n,wie(t),Buffer.from(o,"utf-8")]);return mn(e,i,"sha256")},bie=(n,t,o,i,e)=>{let a=Buffer.concat([n,...t,wie(o),Buffer.from(i,"utf-8")]);return mn(a,e)},TO=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),p2=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),d2=2,VB=n=>n?.data?.isMissingKey===!0,Mie=(n,t)=>t>=d2||n?.name==="TypeError",_ie=async({type:n,index:t,syncAction:o,apiVersion:i,operation:e},a,A,r)=>{let s=a?await r(a):void 0;if(!s)throw new Jo.Boom(`myAppStateKey ("${a}") not present`,{data:{isMissingKey:!0}});let g=Buffer.from(a,"base64");A={...A,indexValueMap:{...A.indexValueMap}};let c=Buffer.from(JSON.stringify(t)),I=oe.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),d=oe.SyncActionData.encode(I).finish(),B=zB(s.keyData),f=U9(d,B.valueEncryptionKey),Q=Die(e,f,g,B.valueMacKey),y=mn(c,B.indexKey),m=Oie(A);m.mix({indexMac:y,valueMac:Q,operation:e}),Object.assign(A,m.finish()),A.version+=1;let _=l2(A.hash,A.version,n,B.snapshotMacKey),T={patchMac:bie(_,[Q],A.version,n,B.patchMacKey),snapshotMac:_,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([f,Q])},keyId:{id:g}}}]},R=y.toString("base64");return A.indexValueMap[R]={valueMac:Q},{patch:T,state:A}},Tie=async(n,t,o,i,e)=>{let a=Oie(t),A=new Map;for(let s of n){let g="operation"in s?s.operation:oe.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,I;try{I=await r(c.keyId.id)}catch(_){if(VB(_))throw _;continue}let d=c.value.blob,B=d.subarray(0,-32),f=d.subarray(-32);if(e){let _=Die(g,B,c.keyId.id,I.valueMacKey);if(Buffer.compare(_,f)!==0)continue}let Q;try{Q=L9(B,I.valueEncryptionKey)}catch{continue}let y=oe.SyncActionData.decode(Q);if(e){let _=mn(y.index,I.indexKey);if(Buffer.compare(_,c.index.blob)!==0)throw new Jo.Boom("HMAC index verification failed")}let m=Buffer.from(y.index).toString();i({syncAction:y,index:JSON.parse(m)}),a.mix({indexMac:c.index.blob,valueMac:f,operation:g})}return a.finish();async function r(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let I=await o(g);if(!I)throw new Jo.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let d=zB(I.keyData);return A.set(g,d),d}},Xje=async(n,t,o,i,e,a)=>{if(a){let r=Buffer.from(n.keyId.id).toString("base64"),s=await i(r);if(!s)throw new Jo.Boom(`failed to find key "${r}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=zB(s.keyData),c=n.mutations.map(d=>d.record.value.blob.slice(-32)),I=bie(n.snapshotMac,c,Lr(n.version.version),t,g.patchMacKey);if(Buffer.compare(I,n.patchMac)!==0)throw new Jo.Boom("Invalid patch mac")}return await Tie(n.mutations,o,i,e,a)},Nie=async(n,t)=>{let o=Ie(n,"sync"),i=PA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=Ie(a,"patches"),r=PA(A||a,"patch"),s=Ie(a,"snapshot"),g=[],c=a.attrs.name,I=a.attrs.has_more_patches==="true",d;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=oe.ExternalBlobReference.decode(s.content),f=await Rie(B,t);d=oe.SyncdSnapshot.decode(f)}for(let{content:B}of r)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let f=oe.SyncdPatch.decode(B);f.version||(f.version={version:+a.attrs.version+1}),g.push(f)}e[c]={patches:g,hasMorePatches:I,snapshot:d}})),e},Rie=async(n,t)=>{let o=await _h(n,"md-app-state",{options:t}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},$je=async(n,t)=>{let o=await Rie(n,t);return oe.SyncdMutations.decode(o)},kie=async(n,t,o,i,e=!0,a)=>{let A=TO();A.version=Lr(t.version.version);let r={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await Tie(t.records,A,o,s?I=>{let d=I.syncAction.index?.toString();r[d]=I}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let I=Buffer.from(t.keyId.id).toString("base64"),d=await o(I);if(!d)throw new Jo.Boom(`failed to find key "${I}" to decode mutation`,{data:{isMissingKey:!0}});let B=zB(d.keyData),f=l2(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(t.mac,f)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:r}},h2=async(n,t,o,i,e,a,A,r=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of t){let{version:I,keyId:d,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:I},"downloading external patch");let m=await $je(c.externalMutations,e);A?.debug({name:n,version:I,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let f=Lr(I.version);s.version=f;let Q=typeof a>"u"||f>a,y;try{y=await Xje(c,n,s,i,Q?m=>{let _=m.syncAction.index?.toString();g[_]=m}:()=>{},r)}catch(m){if(VB(m))throw m;A?.warn({name:n,version:f,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,r){let m=Buffer.from(d.id).toString("base64"),_=await i(m);if(!_)throw new Jo.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let T=zB(_.keyData),R=l2(s.hash,s.version,n,T.snapshotMacKey);if(Buffer.compare(B,R)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},vie=(n,t)=>{let o=oe.SyncdMutation.SyncdOperation,i=a=>{let A;return Array.isArray(a)?A={lastMessageTimestamp:a[a.length-1]?.messageTimestamp,messages:a?.length?a.map(s=>{if(!s.key?.id||!s.key?.remoteJid)throw new Jo.Boom("Incomplete key",{statusCode:400,data:s});if(Fr(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new Jo.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!Lr(s.messageTimestamp))throw new Jo.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=uA(s.key.participant)),s}):void 0}:A=a,A},e;if("mute"in n)e={syncAction:{muteAction:{muted:!!n.mute,muteEndTimestamp:n.mute||void 0}},index:["mute",t],type:"regular_high",apiVersion:2,operation:o.SET};else if("archive"in n)e={syncAction:{archiveChatAction:{archived:!!n.archive,messageRange:i(n.lastMessages)}},index:["archive",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("markRead"in n)e={syncAction:{markChatAsReadAction:{read:n.markRead,messageRange:i(n.lastMessages)}},index:["markChatAsRead",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:r}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:r,messageTimestamp:a}},index:["deleteMessageForMe",t,A.id,A.fromMe?"1":"0","0"],type:"regular_high",apiVersion:3,operation:o.SET}}else if("clear"in n)e={syncAction:{clearChatAction:{messageRange:i(n.lastMessages)}},index:["clearChat",t,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",t],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",t],type:"critical_unblock_low",apiVersion:2,operation:n.contact?o.SET:o.REMOVE};else if("disableLinkPreviews"in n)e={syncAction:{privacySettingDisableLinkPreviewsAction:n.disableLinkPreviews||{}},index:["setting_disableLinkPreviews"],type:"regular",apiVersion:8,operation:o.SET};else if("star"in n){let a=n.star.messages[0];e={syncAction:{starAction:{starred:!!n.star.star}},index:["star",t,a.id,a.fromMe?"1":"0","0"],type:"regular_low",apiVersion:2,operation:o.SET}}else if("delete"in n)e={syncAction:{deleteChatAction:{messageRange:i(n.lastMessages)}},index:["deleteChat",t,"1"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pushNameSetting"in n)e={syncAction:{pushNameSetting:{name:n.pushNameSetting}},index:["setting_pushName"],type:"critical_block",apiVersion:1,operation:o.SET};else if("quickReply"in n)e={syncAction:{quickReplyAction:{count:0,deleted:n.quickReply.deleted||!1,keywords:[],message:n.quickReply.message||"",shortcut:n.quickReply.shortcut||""}},index:["quick_reply",n.quickReply.timestamp||String(Math.floor(Date.now()/1e3))],type:"regular",apiVersion:2,operation:o.SET};else if("addLabel"in n)e={syncAction:{labelEditAction:{name:n.addLabel.name,color:n.addLabel.color,predefinedId:n.addLabel.predefinedId,deleted:n.addLabel.deleted}},index:["label_edit",n.addLabel.id],type:"regular",apiVersion:3,operation:o.SET};else if("addChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Rs.Chat,n.addChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Rs.Chat,n.removeChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Rs.Message,n.addMessageLabel.labelId,t,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Rs.Message,n.removeMessageLabel.labelId,t,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new Jo.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},Pie=(n,t,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:r},index:[s,g,c,I]}=n;if(r?.muteAction)t.emit("chats.update",[{id:g,muteEndTime:r.muteAction?.muted?Lr(r.muteAction.muteEndTimestamp):null,conditional:d(g,void 0)}]);else if(r?.archiveChatAction||s==="archive"||s==="unarchive"){let f=r?.archiveChatAction,Q=f?f.archived:s==="archive",y=A?.unarchiveChats?f?.messageRange:void 0;t.emit("chats.update",[{id:g,archived:Q,conditional:d(g,y)}])}else if(r?.markChatAsReadAction){let f=r.markChatAsReadAction,Q=a&&f.read;t.emit("chats.update",[{id:g,unreadCount:Q?null:f?.read?0:-1,conditional:d(g,f?.messageRange)}])}else if(r?.deleteMessageForMeAction||s==="deleteMessageForMe")t.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:I==="1"}]});else if(r?.contactAction){let f=mie(r.contactAction,g,e);Sie(t,f)}else if(r?.pushNameSetting){let f=r?.pushNameSetting?.name;f&&o?.name!==f&&t.emit("creds.update",{me:{...o,name:f}})}else if(r?.pinAction)t.emit("chats.update",[{id:g,pinned:r.pinAction?.pinned?Lr(r.timestamp):null,conditional:d(g,void 0)}]);else if(r?.unarchiveChatsSetting){let f=!!r.unarchiveChatsSetting.unarchiveChats;t.emit("creds.update",{accountSettings:{unarchiveChats:f}}),e?.info(`archive setting updated => '${r.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=f)}else if(r?.starAction||s==="star"){let f=r?.starAction?.starred;typeof f!="boolean"&&(f=n.index[n.index.length-1]==="1"),t.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:I==="1"},update:{starred:f}}])}else if(r?.deleteChatAction||s==="deleteChat")a||t.emit("chats.delete",[g]);else if(r?.labelEditAction){let{name:f,color:Q,deleted:y,predefinedId:m}=r.labelEditAction;t.emit("labels.edit",{id:g,name:f,color:Q,deleted:y,predefinedId:m?String(m):void 0})}else r?.labelAssociationAction?t.emit("labels.association",{type:r.labelAssociationAction.labeled?"add":"remove",association:s===Rs.Chat?{type:Rs.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:Rs.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):r?.localeSetting?.locale?t.emit("settings.update",{setting:"locale",value:r.localeSetting.locale}):r?.timeFormatAction?t.emit("settings.update",{setting:"timeFormat",value:r.timeFormatAction}):r?.pnForLidChatAction?r.pnForLidChatAction.pnJid&&t.emit("lid-mapping.update",{lid:g,pn:r.pnForLidChatAction.pnJid}):r?.privacySettingRelayAllCalls?t.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:r.privacySettingRelayAllCalls}):r?.statusPrivacy?t.emit("settings.update",{setting:"statusPrivacy",value:r.statusPrivacy}):r?.lockChatAction?t.emit("chats.lock",{id:g,locked:!!r.lockChatAction.locked}):r?.privacySettingDisableLinkPreviewsAction?t.emit("settings.update",{setting:"disableLinkPreviews",value:r.privacySettingDisableLinkPreviewsAction}):r?.notificationActivitySettingAction?.notificationActivitySetting?t.emit("settings.update",{setting:"notificationActivitySetting",value:r.notificationActivitySettingAction.notificationActivitySetting}):r?.lidContactAction?t.emit("contacts.upsert",[{id:g,name:r.lidContactAction.fullName||r.lidContactAction.firstName||r.lidContactAction.username||void 0,username:r.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):r?.privacySettingChannelsPersonalisedRecommendationAction?t.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:r.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function d(f,Q){return a?y=>{let m=y.historySets.chats[f]||y.chatUpserts[f];if(m)return Q?B(m,Q):!0}:void 0}function B(f,Q){let y=Number(Q?.lastMessageTimestamp||Q?.lastSystemMessageTimestamp||0),m=Number(f?.lastMessageRecvTimestamp||0);return y>=m}};var eJe=class{_eventListeners;_maxListeners;_logger;_throwOnEmitError=!1;_throwOnEmptyListeners=!1;_errorEvent="error";constructor(n){this._eventListeners=new Map,this._maxListeners=100,this._logger=n?.logger,n?.throwOnEmitError!==void 0&&(this._throwOnEmitError=n.throwOnEmitError),n?.throwOnEmptyListeners!==void 0&&(this._throwOnEmptyListeners=n.throwOnEmptyListeners)}get logger(){return this._logger}set logger(n){this._logger=n}get throwOnEmitError(){return this._throwOnEmitError}set throwOnEmitError(n){this._throwOnEmitError=n}get throwOnEmptyListeners(){return this._throwOnEmptyListeners}set throwOnEmptyListeners(n){this._throwOnEmptyListeners=n}once(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let t=this._eventListeners.get(n);return t?t.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,t){let o=this._eventListeners.get(n)??[];return o.unshift(t),this._eventListeners.set(n,o),this}prependOnceListener(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,t){return this.on(n,t),this}on(n,t){this._eventListeners.has(n)||this._eventListeners.set(n,[]);let o=this._eventListeners.get(n);return o&&(o.length>=this._maxListeners&&console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${o.length+1} ${n} listeners added. Use setMaxListeners() to increase limit.`),o.push(t)),this}removeListener(n,t){return this.off(n,t),this}off(n,t){let o=this._eventListeners.get(n)??[],i=o.indexOf(t);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...t){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...t),o=!0;if(n===this._errorEvent){let e=t[0]instanceof Error?t[0]:new Error(`${t[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,t),o}listeners(n){return this._eventListeners.get(n)??[]}removeAllListeners(n){return n!==void 0?this._eventListeners.delete(n):this._eventListeners.clear(),this}setMaxListeners(n){this._maxListeners=n;for(let t of this._eventListeners.values())t.length>n&&t.splice(n)}getAllListeners(){let n=[];for(let t of this._eventListeners.values())n=[...n,...t];return n}sendLog(n,t){if(!this._logger)return;let o;switch(typeof t=="string"?o=t:Array.isArray(t)&&t.length>0&&t[0]instanceof Error?o=t[0].message:t instanceof Error?o=t.message:Array.isArray(t)&&t.length>0&&typeof t[0]?.message=="string"?o=t[0].message:o=JSON.stringify(t),n){case"error":{this._logger.error?.(o,{event:n,data:t});break}case"warn":{this._logger.warn?.(o,{event:n,data:t});break}case"trace":{this._logger.trace?.(o,{event:n,data:t});break}case"debug":{this._logger.debug?.(o,{event:n,data:t});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:t});break}default:{this._logger.info?.(o,{event:n,data:t});break}}}},Zc=class extends eJe{_hooks;_throwOnHookError=!1;_enforceBeforeAfter=!1;_deprecatedHooks;_allowDeprecated=!0;constructor(n){super({logger:n?.logger,throwOnEmitError:n?.throwOnEmitError,throwOnEmptyListeners:n?.throwOnEmptyListeners}),this._hooks=new Map,this._deprecatedHooks=n?.deprecatedHooks?new Map(n.deprecatedHooks):new Map,n?.throwOnHookError!==void 0?this._throwOnHookError=n.throwOnHookError:n?.throwHookErrors!==void 0&&(this._throwOnHookError=n.throwHookErrors),n?.enforceBeforeAfter!==void 0&&(this._enforceBeforeAfter=n.enforceBeforeAfter),n?.allowDeprecated!==void 0&&(this._allowDeprecated=n.allowDeprecated)}get hooks(){return this._hooks}get throwHookErrors(){return this._throwOnHookError}set throwHookErrors(n){this._throwOnHookError=n}get throwOnHookError(){return this._throwOnHookError}set throwOnHookError(n){this._throwOnHookError=n}get enforceBeforeAfter(){return this._enforceBeforeAfter}set enforceBeforeAfter(n){this._enforceBeforeAfter=n}get deprecatedHooks(){return this._deprecatedHooks}set deprecatedHooks(n){this._deprecatedHooks=n}get allowDeprecated(){return this._allowDeprecated}set allowDeprecated(n){this._allowDeprecated=n}validateHookName(n){if(this._enforceBeforeAfter){let t=n.trim().toLocaleLowerCase();if(!t.startsWith("before")&&!t.startsWith("after"))throw new Error(`Hook event "${n}" must start with "before" or "after" when enforceBeforeAfter is enabled`)}}checkDeprecatedHook(n){if(this._deprecatedHooks.has(n)){let t=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${t?`: ${t}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,t){this.onHookEntry({event:n,handler:t})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let t=this._hooks.get(n.event);t?t.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,t){this.onHookEntry({event:n,handler:t})}onHooks(n){for(let t of n)this.onHook(t.event,t.handler)}prependHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(t):this._hooks.set(n,[t])}prependOnceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.prependHook(n,o)}onceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.onHook(n,o)}removeHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let t of n)this.removeHook(t.event,t.handler)}async hook(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){for(let i of o)if(i.constructor.name!=="AsyncFunction")try{i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...t){await this.hook(`before:${n}`,...t)}async afterHook(n,...t){await this.hook(`after:${n}`,...t)}async callHook(n,...t){await this.hook(n,...t)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var AJe=class{_enabled=!0;_maxSize=4e3;_store=new Map;_keys=[];constructor(n){n?.enabled!==void 0&&(this._enabled=n.enabled),n?.maxSize!==void 0&&(this._maxSize=n.maxSize)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get maxSize(){return this._maxSize}set maxSize(n){this._maxSize=n}get store(){return this._store}get size(){return this._store.size}get(n){return this._store.get(n)}set(n,t){if(this._enabled){if(this._store.has(n)){this._store.set(n,t);return}if(this._store.size>=this._maxSize){let o=this._keys.shift();o&&this._store.delete(o)}this._keys.push(n),this._store.set(n,t)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},tJe=class{get name(){return"crc32"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;t=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}let o=3988292384,i=4294967295;for(let a=0;a>>1^o&-(i&1)}return i=(i^4294967295)>>>0,i.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},NO=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let t=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}},rJe=class{get name(){return"djb2"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let o=5381;for(let e=0;e>>0;return o.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},aJe=class{get name(){return"fnv1"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;t=new Uint8Array(A.buffer,A.byteOffset,A.byteLength)}let o=2166136261,i=16777619,e=o;for(let A=0;A>>0;return e.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},iJe=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;t=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=t.length,a=Math.floor(e/4),A=this._seed;for(let c=0;c>>16,A=this._imul(A,2246822507),A^=A>>>13,A=this._imul(A,3266489909),A^=A>>>16,A=A>>>0,A.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}_imul(n,t){if(Math.imul)return Math.imul(n,t);let o=n>>>16&65535,i=n&65535,e=t>>>16&65535,a=t&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,t){return n<>>32-t}},oJe=class{_providers=new Map;_getFuzzy=!0;constructor(n){n?.providers&&this.loadProviders(n?.providers),n?.getFuzzy!==void 0&&(this._getFuzzy=!!n?.getFuzzy)}loadProviders(n){for(let t of n)this._providers.set(t.name,t)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,t){let o=t?.fuzzy??this._getFuzzy;n=n.trim();let i=this._providers.get(n);return i===void 0&&o===!0&&(n=n.toLowerCase(),i=this._providers.get(n)),i===void 0&&o===!0&&(n=n.replaceAll("-",""),i=this._providers.get(n)),i}add(n){this._providers.set(n.name,n)}remove(n){return this._providers.delete(n)}},E2=class extends Zc{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new oJe;_defaultAlgorithm="SHA-256";_defaultAlgorithmSync="djb2";_cache;constructor(n){super(n),n?.parse&&(this._parse=n.parse),n?.stringify&&(this._stringify=n.stringify),n?.defaultAlgorithm&&(this._defaultAlgorithm=n.defaultAlgorithm),n?.defaultAlgorithmSync&&(this._defaultAlgorithmSync=n.defaultAlgorithmSync),this._cache=new AJe(n?.cache),this.loadProviders(n?.providers,{includeBase:n?.includeBase??!0})}get parse(){return this._parse}set parse(n){this._parse=n}get stringify(){return this._stringify}set stringify(n){this._stringify=n}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return this._providers.names}get defaultAlgorithm(){return this._defaultAlgorithm}set defaultAlgorithm(n){this._defaultAlgorithm=n}get defaultAlgorithmSync(){return this._defaultAlgorithmSync}set defaultAlgorithmSync(n){this._defaultAlgorithmSync=n}get cache(){return this._cache}async toHash(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithm,maxLength:t?.maxLength};await this.beforeHook("toHash",o);let i=this._stringify(o.data),e=`${o.algorithm}:${i}`;if(this._cache.enabled){let c=this._cache.get(e);if(c!==void 0){let I=c;t?.maxLength&&I.length>t.maxLength&&(I=I.substring(0,t.maxLength));let d={hash:I,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",d),d.hash}}let A=new TextEncoder().encode(i),r=this._providers.get(o.algorithm);r||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),r=new NO({algorithm:this._defaultAlgorithm}));let s=await r.toHash(A);this._cache.enabled&&this._cache.set(e,s),t?.maxLength&&s.length>t?.maxLength&&(s=s.substring(0,t.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}toHashSync(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithmSync,maxLength:t?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let I=this._cache.get(a);if(I!==void 0){let d=I;t?.maxLength&&d.length>t.maxLength&&(d=d.substring(0,t.maxLength));let B={hash:d,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let r=new TextEncoder().encode(e),s=this._providers.get(i);if(!s&&(this.emit("warn",`Invalid algorithm '${i}' not found. Falling back to default algorithm '${this._defaultAlgorithmSync}'.`),s=this._providers.get(this._defaultAlgorithmSync),!s))throw new Error(`Hash provider '${this._defaultAlgorithmSync}' (default) not found`);if(!s.toHashSync)throw new Error(`Hash provider '${i}' does not support synchronous hashing. Use toHash() instead or choose a different algorithm (djb2, fnv1, murmur, crc32).`);let g=s.toHashSync(r);this._cache.enabled&&this._cache.set(a,g),t?.maxLength&&g.length>t?.maxLength&&(g=g.substring(0,t.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}loadProviders(n,t={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);t.includeBase&&(this.providers.add(new NO({algorithm:"SHA-256"})),this.providers.add(new NO({algorithm:"SHA-384"})),this.providers.add(new NO({algorithm:"SHA-512"})),this.providers.add(new tJe),this.providers.add(new rJe),this.providers.add(new aJe),this.providers.add(new iJe))}};var B2=n=>{let t;if(n!==void 0){if(typeof n=="number")t=n;else{if(typeof n!="string")return;if(n=n.trim(),Number.isNaN(Number(n))){let o=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(n);if(!o)throw new Error(`Unsupported time format: "${n}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,e]=o,a=Number.parseFloat(i);switch(e.toLowerCase()){case"ms":t=a;break;case"s":t=a*1e3;break;case"m":t=a*1e3*60;break;case"h":t=a*1e3*60*60;break;case"hr":t=a*1e3*60*60;break;case"d":t=a*1e3*60*60*24;break;default:t=Number(n)}}else t=Number(n)}return t}},Nl=(n,t)=>{t??=new Date;let o=B2(n);return o===void 0?t.getTime():t.getTime()+o};var WB=(function(n){return n.SHA256="SHA-256",n.SHA384="SHA-384",n.SHA512="SHA-512",n.DJB2="djb2",n.FNV1="fnv1",n.MURMER="murmer",n.CRC32="crc32",n})({});function C2(n,t={algorithm:"djb2",serialize:JSON.stringify}){let o=t?.algorithm??"djb2",i=(t?.serialize??JSON.stringify)(n);return new E2().toHashSync(i,{algorithm:o})}function Gie(n,t={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=t?.min??0,i=t?.max??10,e=t?.algorithm??"djb2",a=t?.serialize??JSON.stringify,A=t?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let r=a(n);return new E2().toNumberSync(r,{algorithm:e,min:o,max:i,hashLength:A})}function f2(n,t){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=t;return(...A)=>{let r=nJe(n,A,{keyPrefix:i,serialize:a});t.createKey&&(r=t.createKey(n,A,t));let s=e.get(r);if(s===void 0)try{s=n(...A),e.set(r,s,o)}catch(g){e.emit("error",g),t.cacheErrors&&e.set(r,g,o)}return s}}function Q2(n,t,o){let i=typeof n=="function"?n(o):n,e;try{e=o.cache.get(i)}catch(a){if(o.cache.emit("error",a),o.throwErrors===!0||o.throwErrors==="store")throw a}if(e===void 0)try{try{e=t()}catch(a){throw new RO(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new RO(a,"store")}}catch(a){let A=a instanceof RO?a.context:void 0,r=a instanceof RO?a.error:a;if(o.cache.emit("error",r),o.cacheErrors&&A==="function")try{o.cache.set(i,r,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw r}return e}function nJe(n,t,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${C2(t,{serialize:e})}`:`${n.name}::${C2(t,{serialize:e})}`}var RO=class{error;context;constructor(n,t){this.error=n,this.context=t}};var Xc=class{_counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0};_vsize=0;_ksize=0;_enabled=!1;_lastUpdated;_lastReset;_subscriptions=[];_trackedKeys=new Map;_trackKeys=!1;_maxTrackedKeys;constructor(n){n?.enabled&&(this._enabled=n.enabled),n?.trackKeys&&(this._trackKeys=n.trackKeys),n?.maxTrackedKeys!==void 0&&(this._maxTrackedKeys=n.maxTrackedKeys),n?.emitter&&n?.eventMap&&this.subscribe(n.emitter,n.eventMap)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get trackKeys(){return this._trackKeys}set trackKeys(n){this._trackKeys=n}get maxTrackedKeys(){return this._maxTrackedKeys}set maxTrackedKeys(n){this._maxTrackedKeys=n}get trackedKeys(){return this._trackedKeys}get hits(){return this._counters.hits}get misses(){return this._counters.misses}get gets(){return this._counters.gets}get sets(){return this._counters.sets}get deletes(){return this._counters.deletes}get clears(){return this._counters.clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._counters.count}get hitRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.hits/n}get missRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.misses/n}get lastUpdated(){return this._lastUpdated}get lastReset(){return this._lastReset}increment(n,t=1){this._enabled&&(this._counters[n]+=t,this.touch())}decrement(n,t=1){this._enabled&&(this._counters[n]-=t,this.touch())}incrementHits(n=1){this.increment("hits",n)}incrementMisses(n=1){this.increment("misses",n)}incrementGets(n=1){this.increment("gets",n)}incrementSets(n=1){this.increment("sets",n)}incrementDeletes(n=1){this.increment("deletes",n)}incrementClears(n=1){this.increment("clears",n)}incrementVSize(n){this._enabled&&(this._vsize+=this.roughSizeOfObject(n),this.touch())}decreaseVSize(n){this._enabled&&(this._vsize=Math.max(0,this._vsize-this.roughSizeOfObject(n)),this.touch())}incrementKSize(n){this._enabled&&(this._ksize+=this.roughSizeOfString(n),this.touch())}decreaseKSize(n){this._enabled&&(this._ksize=Math.max(0,this._ksize-this.roughSizeOfString(n)),this.touch())}incrementCount(n=1){this.increment("count",n)}decreaseCount(n=1){this._enabled&&(this._counters.count=Math.max(0,this._counters.count-n),this.touch())}setCount(n){this._enabled&&(this._counters.count=n,this.touch())}roughSizeOfString(n){return n.length*2}roughSizeOfObject(n){let t=[],o=[n],i=0;for(;o.length>0;){let e=o.pop();if(typeof e=="boolean")i+=4;else if(typeof e=="string")i+=e.length*2;else if(typeof e=="number")i+=8;else{if(e==null){i+=4;continue}if(t.includes(e))continue;t.push(e);for(let a in e)i+=a.length*2,o.push(e[a])}}return i}enable(){this._enabled=!0}disable(){this._enabled=!1}clear(){this.reset()}reset(){this._counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0},this._vsize=0,this._ksize=0,this._trackedKeys.clear(),this._lastReset=Date.now(),this._lastUpdated=void 0}resetStoreValues(){this._vsize=0,this._ksize=0,this._counters.count=0}toJSON(){return{enabled:this._enabled,hits:this._counters.hits,misses:this._counters.misses,gets:this._counters.gets,sets:this._counters.sets,deletes:this._counters.deletes,clears:this._counters.clears,vsize:this._vsize,ksize:this._ksize,count:this._counters.count,hitRate:this.hitRate,missRate:this.missRate,trackedKeys:this._trackedKeys.size,lastUpdated:this._lastUpdated,lastReset:this._lastReset}}snapshot(){return this.toJSON()}recordKey(n,t,o=1){if(!this._enabled||!this._trackKeys)return;let i=this._trackedKeys.get(n);i||(i={hits:0,misses:0,gets:0,sets:0,deletes:0},this._trackedKeys.set(n,i),this.pruneTrackedKeys(n)),i[t]+=o,this.touch()}mostUsedKeys(n=100,t){return this.sortedKeyEntries(t,"desc").slice(0,n)}leastUsedKeys(n=100,t){return this.sortedKeyEntries(t,"asc").slice(0,n)}keyStats(n){let t=this._trackedKeys.get(n);return t?this.toKeyEntry(n,t):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,t){let o=t.hits+t.misses;return{key:n,count:this.totalOf(t),hits:t.hits,misses:t.misses,gets:t.gets,sets:t.sets,deletes:t.deletes,hitRate:o===0?0:t.hits/o}}sortedKeyEntries(n,t){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=t==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,r=n?a[n]:a.count;return A!==r?(A-r)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=t)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,t){for(let[o,i]of Object.entries(t)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let t=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){t.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=t}applyEvent(n,t){if(this._enabled){if(typeof n=="function"){n(this,...t);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var sJe=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},y2=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let t=new sJe(n);this.head?(t.next=this.head,this.head.prev=t,this.head=t):this.head=this.tail=t,this.nodesMap.set(n,t)}moveToFront(n){let t=this.nodesMap.get(n);if(!t||this.head===t)return;t.prev&&(t.prev.next=t.next);t.next&&(t.next.prev=t.prev);t===this.tail&&(this.tail=t.prev),t.prev=void 0,t.next=this.head;this.head&&(this.head.prev=t),this.head=t,this.tail??=t}getOldest(){return this.tail?this.tail.value:void 0}removeOldest(){if(!this.tail)return;let n=this.tail.value;return this.tail.prev?(this.tail=this.tail.prev,this.tail.next=void 0):this.head=this.tail=void 0,this.nodesMap.delete(n),n}remove(n){let t=this.nodesMap.get(n);return t?(t.prev?t.prev.next=t.next:(this.head=t.next,this.head&&(this.head.prev=void 0)),t.next?t.next.prev=t.prev:(this.tail=t.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var Fie=16777216,m2=class extends Zc{_lru=new y2;_storeHashSize=16;_storeHashAlgorithm=WB.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new Xc({enabled:!1});constructor(n){super(),n?.ttl&&this.setTtl(n.ttl),n?.maxTtl!==void 0&&this.setMaxTtl(n.maxTtl),n?.useClone!==void 0&&(this._useClone=n.useClone),n?.stats&&(this._stats.enabled=n.stats),n?.storeHashSize&&n.storeHashSize>0&&(this._storeHashSize=n.storeHashSize),n?.lruSize&&(n.lruSize>16777216?this.emit("error",new Error(`LRU size cannot be larger than ${Fie} due to Map limitations.`)):this._lruSize=n.lruSize),n?.checkInterval&&(this._checkInterval=n.checkInterval),n?.storeHashAlgorithm&&(this._storeHashAlgorithm=n.storeHashAlgorithm),this._store=Array.from({length:this._storeHashSize},()=>new Map),this.startIntervalCheck()}get ttl(){return this._ttl}set ttl(n){this.setTtl(n)}get maxTtl(){return this._maxTtl}set maxTtl(n){this.setMaxTtl(n)}get useClone(){return this._useClone}set useClone(n){this._useClone=n}get lruSize(){return this._lruSize}set lruSize(n){if(n>16777216){this.emit("error",new Error(`LRU size cannot be larger than ${Fie} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new y2;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let t of this._store)n+=t.size;return n}get stats(){return this._stats}get storeHashSize(){return this._storeHashSize}set storeHashSize(n){n!==this._storeHashSize&&(this._storeHashSize=n,this._store=Array.from({length:this._storeHashSize},()=>new Map),this._stats.enabled&&this._stats.resetStoreValues())}get storeHashAlgorithm(){return this._storeHashAlgorithm}set storeHashAlgorithm(n){this._storeHashAlgorithm=n}get keys(){let n=[];for(let t of this._store)for(let o of t.keys()){let i=t.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),t.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let t of this._store)for(let o of t.values()){if(this.hasExpired(o)){this.recordExpiration(o),t.delete(o.key),this.lruRemove(o.key);continue}n.push(o)}return n.values()}get store(){return this._store}get(n){this.hookSync("BEFORE_GET",n);let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}this.lruMoveToFront(n);let i;return this._useClone?i=this.clone(o.value):i=o.value,this.recordRead(!0),this.hookSync("AFTER_GET",{key:n,result:i}),i}getMany(n){this.hookSync("BEFORE_GET_MANY",n);let t=[];for(let o of n)t.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:t}),t}getRaw(n){let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let t=[];for(let o of n)t.push(this.getRaw(o));return t}set(n,t,o){let i={key:n,value:t,ttl:o};this.hookSync("BEFORE_SET",i);let e=this.getStore(i.key),a,A=i.ttl;if(A!==void 0||this._ttl!==void 0)if(typeof A=="object"){if(A.expire&&(a=typeof A.expire=="number"?A.expire:A.expire.getTime()),A.ttl){let s=Nl(A.ttl);s!==void 0&&(a=s)}}else{let s=Nl(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=Nl(this._maxTtl);(a===void 0||a>s)&&(a=s)}if(this._lruSize>0){if(e.has(i.key))this.lruMoveToFront(i.key);else if(this.lruAddToFront(i.key),this._lru.size>this._lruSize){let s=this._lru.getOldest();s&&(this._lru.removeOldest(),this.delete(s))}}if(this._stats.enabled){let s=e.get(i.key);s?this._stats.decreaseVSize(s.value):(this._stats.incrementKSize(i.key),this._stats.incrementCount()),this._stats.incrementVSize(i.value),this._stats.incrementSets()}let r={key:i.key,value:i.value,expires:a};e.set(i.key,r),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let t of n)this.set(t.key,t.value,t.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let t=[];for(let o of n){let i=this.get(o);t.push(!!i)}return t}take(n){let t=this.get(n);if(t)return this.delete(n),t}takeMany(n){let t=[];for(let o of n)t.push(this.take(o));return t}delete(n){this.hookSync("BEFORE_DELETE",n);let t=this.getStore(n);if(this._stats.enabled){let o=t.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}t.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let t of n)this.delete(t);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new y2,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let t=this.getKeyStoreHash(n);return this._store[t]||=new Map,this._store[t]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):Gie(n,{min:0,max:this._storeHashSize-1,algorithm:this._storeHashAlgorithm})}clone(n){return this.isPrimitive(n)?n:structuredClone(n)}lruAddToFront(n){this._lruSize!==0&&this._lru.addToFront(n)}lruMoveToFront(n){this._lruSize!==0&&this._lru.moveToFront(n)}lruRemove(n){this._lruSize!==0&&this._lru.remove(n)}lruResize(){for(;this._lru.size>this._lruSize;){let n=this._lru.getOldest();n&&(this._lru.removeOldest(),this.delete(n))}}checkExpiration(){for(let n of this._store)for(let t of n.values())t.expires&&Date.now()>t.expires&&(this.recordExpiration(t),n.delete(t.key),this.lruRemove(t.key))}startIntervalCheck(){if(this._checkInterval>0){this._interval&&clearInterval(this._interval),this._interval=setInterval(()=>{this.checkExpiration()},this._checkInterval).unref()}}stopIntervalCheck(){this._interval&&clearInterval(this._interval),this._interval=0,this._checkInterval=0}wrap(n,t){return f2(n,{ttl:t?.ttl??this._ttl,keyPrefix:t?.keyPrefix,createKey:t?.createKey,cache:this})}getOrSet(n,t,o){return Q2(n,t,{cache:this,ttl:o?.ttl??this._ttl,cacheErrors:o?.cacheErrors,throwErrors:o?.throwErrors})}recordRead(n){this._stats.enabled&&(n?this._stats.incrementHits():this._stats.incrementMisses(),this._stats.incrementGets())}recordExpiration(n){this._stats.enabled&&(this._stats.decreaseKSize(n.key),this._stats.decreaseVSize(n.value),this._stats.decreaseCount())}isPrimitive(n){return n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}setTtl(n){typeof n=="string"||n===void 0?this._ttl=n:n>0?this._ttl=n:this._ttl=void 0}setMaxTtl(n){typeof n=="string"||n===void 0?this._maxTtl=n:n>0?this._maxTtl=n:this._maxTtl=void 0}hasExpired(n){return!!(n.expires&&Date.now()>n.expires)}};var hJe=class extends Zc{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new Xc({enabled:!0});_cacheable=new m2;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,t,o=0){if(typeof n!="string"&&typeof n!="number")throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`",n);if(o&&typeof o!="number"&&typeof o!="string")throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.",this.formatKey(n));let i=this.formatKey(n),e=0;this.options.stdTTL&&(e=this.getExpirationTimestamp(this.options.stdTTL)),o&&(e=this.getExpirationTimestamp(o));let a=0;if(e&&e>0&&(a=e),this.options.maxKeys){let{maxKeys:A}=this.options;if(A>-1&&this.store.size>=A)throw this.createError("Cache max keys amount exceeded",this.formatKey(n))}return this.store.set(i,{key:i,value:t,ttl:a}),this.emit("set",i,t,e),this._stats.incrementKSize(i),this._stats.incrementVSize(t),this._stats.setCount(this.store.size),!0}mset(n){if(!Array.isArray(n))throw this.createError("The keys argument has to be an array.");for(let t of n)this.set(t.key,t.value,t.ttl);return!0}get(n){let t=this.store.get(this.formatKey(n));if(t){if(t.ttl>0){if(t.ttl0){let n=this.options.checkperiod*1e3;this.intervalId=setInterval(()=>{this.checkData()},n).unref();return}this.intervalId=0}stopInterval(){this.intervalId!==0&&(clearInterval(this.intervalId),this.intervalId=0)}formatKey(n){return n.toString()}getExpirationTimestamp(n){if(typeof n=="string")return Nl(n);let t=Date.now(),o=n*1e3;return t+o}checkData(){for(let[n,t]of this.store.entries())t.ttl>0&&t.ttl{let a={resolve:i,reject:e,weight:t,priority:o},A=Uie(this._queue,r=>o<=r.priority);A===-1&&t<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(t){return CJe(this,arguments,void 0,function*(o,i=1,e=0){let[a,A]=yield this.acquire(i,e);try{return yield o(a)}finally{A()}})}waitForUnlock(t=1,o=0){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return this._couldLockImmediately(t,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),uJe(this._weightedWaiters[t-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatchQueue()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatchQueue()}cancel(){this._queue.forEach(t=>t.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(t){let o=this._value;this._value-=t.weight,t.resolve([o,this._newReleaser(t.weight)])}_newReleaser(t){let o=!1;return()=>{o||(o=!0,this.release(t))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let t=this._value;t>0;t--){let o=this._weightedWaiters[t-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[t-1]=[])}else{let t=this._queue[0].priority;for(let o=this._value;o>0;o--){let i=this._weightedWaiters[o-1];if(!i)continue;let e=i.findIndex(a=>a.priority<=t);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(t,o){return(this._queue.length===0||this._queue[0].priorityt.priority<=i.priority);n.splice(o+1,0,t)}function Uie(n,t){for(let o=n.length-1;o>=0;o--)if(t(n[o]))return o;return-1}var BJe=function(n,t,o,i){function e(a){return a instanceof o?a:new o(function(A){A(a)})}return new(o||(o=Promise))(function(a,A){function r(c){try{g(i.next(c))}catch(I){A(I)}}function s(c){try{g(i.throw(c))}catch(I){A(I)}}function g(c){c.done?a(c.value):e(c.value).then(r,s)}g((i=i.apply(n,t||[])).next())})},kg=class{constructor(t){this._semaphore=new S2(1,t)}acquire(){return BJe(this,arguments,void 0,function*(t=0){let[,o]=yield this._semaphore.acquire(1,t);return o})}runExclusive(t,o=0){return this._semaphore.runExclusive(()=>t(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(t=0){return this._semaphore.waitForUnlock(1,t)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as SJe}from"crypto";var w2=qe(Kie(),1);var O2=class n extends Error{name="TimeoutError";constructor(t,o){super(t,o),Error.captureStackTrace?.(this,n)}},xie=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function b2(n,t){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=t,r,s,c=new Promise((I,d)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){d(xie(A));return}if(A&&(s=()=>{d(xie(A))},A.addEventListener("abort",s,{once:!0})),n.then(I,d),o===Number.POSITIVE_INFINITY)return;let B=new O2;r=a.setTimeout.call(void 0,()=>{if(i){try{I(i())}catch(f){d(f)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?I():e instanceof Error?d(e):(B.message=e??`Promise timed out after ${o} milliseconds`,d(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,r),r=void 0},c}function M2(n,t,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],t)<=0?(i=++A,e-=a+1):e=a}return i}var yJe=100,Nh=class{#e=[];#A=0;enqueue(t,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:t};if(a===0){this.#e.length=0,this.#A=0,this.#e.push(A);return}if(this.#e.at(-1).priority>=i){this.#e.push(A);return}this.#t();let r=M2(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(r,0,A)}setPriority(t,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===t);if(i===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:t})}remove(t){let o=this.#e.findIndex((i,e)=>eyJe&&this.#A>this.#e.length/2&&this.#t(),t?.run}filter(t){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);if(t.strict&&t.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(t.strict&&t.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=t.carryoverIntervalCount??t.carryoverConcurrencyCount??!1,this.#A=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#r=t.intervalCap,this.#c=t.interval,this.#n=t.strict,this.#p=new t.queueClass,this.#d=t.queueClass,this.concurrency=t.concurrency,t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);this.timeout=t.timeout,this.#B=t.autoStart===!1,this.#Y()}#y(t){for(;this.#l=this.#c)this.#l++;else break}(this.#l>100&&this.#l>this.#g.length/2||this.#l===this.#g.length)&&(this.#g=this.#g.slice(this.#l),this.#l=0)}#Q(t){this.#n?this.#g.push(t):this.#t++}#C(){this.#n?this.#g.length>this.#l&&this.#g.pop():this.#t>0&&this.#t--}#M(){return this.#g.length-this.#l}get#b(){return this.#A?!0:this.#n?this.#M()=this.#r){let i=this.#g[this.#l],e=this.#c-(t-i);return this.#k(e),!0}return!1}if(this.#I===void 0){let o=this.#s-t;if(o<0)this.#t=this.#e?this.#h:0;else return this.#k(o),!0}return!1}#k(t){this.#o===void 0&&(this.#o=setTimeout(()=>{this.#_()},t))}#T(){this.#I&&(clearInterval(this.#I),this.#I=void 0)}#v(){this.#o&&(clearTimeout(this.#o),this.#o=void 0)}#N(){if(this.#p.size===0){if(this.#T(),this.emit("empty"),this.#h===0){if(this.#v(),this.#n&&this.#l>0){let o=Date.now();this.#y(o)}this.emit("idle")}return!1}let t=!1;if(!this.#B){let o=Date.now(),i=!this.#R(o);if(this.#b&&this.#w){let e=this.#p.dequeue();this.#A||(this.#Q(o),this.#K()),i&&this.#F(),this.emit("active"),e(),t=!0}}return t}#F(){this.#A||this.#I!==void 0||this.#n||(this.#I=setInterval(()=>{this.#O()},this.#c),this.#s=Date.now()+this.#c)}#O(){this.#n||(this.#I!==void 0&&(this.#t===0&&this.#h===0?this.#T():this.#s=Date.now()+this.#c),this.#t=this.#e?this.#h:0),this.#U(),this.#K()}#U(){for(;this.#N(););}get concurrency(){return this.#E}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#E=t,this.#U()}setPriority(t,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#p.setPriority(t,o)}async add(t,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#u++).toString()},o.timeout!==void 0&&!(Number.isFinite(o.timeout)&&o.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${o.timeout}\` (${typeof o.timeout})`);return new Promise((i,e)=>{let a=Symbol(`task-${o.id}`),A=()=>{},r=async()=>{A(),this.#h++,this.#f.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(d){throw this.#J(),this.#f.delete(a),d}let c=t({signal:o.signal});if(o.timeout!==void 0&&(c=b2(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#h} running, ${this.#p.size} waiting)`})),o.signal){let{signal:d}=o;c=Promise.race([c,new Promise((B,f)=>{g=()=>{f(d.reason)},d.addEventListener("abort",g,{once:!0})})])}let I=await c;i(I),this.emit("completed",I)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#f.delete(a),queueMicrotask(()=>{this.#S()})}};this.#p.enqueue(r,o);let s=()=>{if(this.#p instanceof Nh){this.#p.remove(r);return}this.#p.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#N(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#m.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#m.add(A)}this.emit("add"),this.#N()})}async addAll(t,o){return Promise.all(t.map(async i=>this.add(i,o)))}start(){return this.#B?(this.#B=!1,this.#U(),this):this}pause(){this.#B=!0}clear(){for(let t of this.#m)t();this.#p=new this.#d,this.#T(),this.#P(),this.emit("empty"),this.#h===0&&(this.#v(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#p.size!==0&&await this.#L("empty")}async onSizeLessThan(t){this.#p.sizethis.#p.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#L(t,o){let i=Array.isArray(t)?t:[t];return new Promise(e=>{let a=()=>{if(!(o&&!o())){for(let A of i)this.off(A,a);e()}};for(let A of i)this.on(A,a)})}get size(){return this.#p.size}sizeBy(t){return this.#p.filter(t).length}get pending(){return this.#h}get isPaused(){return this.#B}#Y(){this.#A||(this.on("add",()=>{this.#p.size>0&&this.#K()}),this.on("next",()=>{this.#K()}))}#K(){this.#A||this.#i||(this.#i=!0,queueMicrotask(()=>{this.#i=!1,this.#P()}))}#J(){this.#A||(this.#C(),this.#K())}#P(){let t=this.#a;if(this.#A||this.#p.size===0){t&&(this.#a=!1,this.emit("rateLimitCleared"));return}let o;if(this.#n){let e=Date.now();this.#y(e),o=this.#M()}else o=this.#t;let i=o>=this.#r;i!==t&&(this.#a=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#a}get isSaturated(){return this.#h===this.#E&&this.#p.size>0||this.isRateLimited&&this.#p.size>0}get runningTasks(){return[...this.#f.values()].map(t=>({...t,timeoutRemaining:t.timeout?Math.max(0,t.startTime+t.timeout-Date.now()):void 0}))}};var vO=class{constructor(t,o){this.store=t,this.logger=o,this.queues=new Map}getQueue(t){return this.queues.has(t)||this.queues.set(t,new Rl({concurrency:1})),this.queues.get(t)}async processOperations(t,o,i,e,a){let A=t[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let r=[],s={};for(let g in A)A[g]===null?r.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),r.length>0&&await this.processDeletions(o,r,i,e,a)})}async processDeletions(t,o,i,e,a){if(a)for(let A of o)i[t]?.[A]?(i[t][A]=null,e[t][A]=null):this.logger.warn(`Skipping deletion of non-existent ${t} in transaction: ${A}`);else{let A=await this.store.get(t,o);for(let r of o)A[r]?(i[t][r]=null,e[t][r]=null):this.logger.warn(`Skipping deletion of non-existent ${t}: ${r}`)}}async validateDeletions(t,o){let i=t[o];if(i)return this.getQueue(o).add(async()=>{let e=Object.keys(i).filter(A=>i[A]===null);if(e.length===0)return;let a=await this.store.get(o,e);for(let A of e)a[A]||(this.logger.warn(`Skipping deletion of non-existent ${o}: ${A}`),delete t[o][A])})}};var jie=(n,t,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new mJe,a=new Map,A=new Map,r=new Map,s=new vO(n,t);function g(Q){return a.has(Q)||a.set(Q,new Rl({concurrency:1})),a.get(Q)}function c(Q){return A.has(Q)||(A.set(Q,new kg),r.set(Q,0)),A.get(Q)}function I(Q){let y=r.get(Q)??0;r.set(Q,y+1)}function d(Q){let y=(r.get(Q)??1)-1;if(r.set(Q,y),y<=0){let m=A.get(Q);m&&!m.isLocked()&&(A.delete(Q),r.delete(Q))}}function B(){return!!e.getStore()}async function f(Q){if(Object.keys(Q).length===0){t.trace("no mutations in transaction");return}t.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(Q,y);let _=m.cache[Q]||{},T=y.filter(H=>!(H in _));if(T.length>0){m.dbQueries++,t.trace({type:Q,count:T.length},"fetching missing keys in transaction");let H=await c(Q).runExclusive(()=>n.get(Q,T));m.cache[Q]=m.cache[Q]||{},Object.assign(m.cache[Q],H)}let R={};for(let H of y){let j=m.cache[Q]?.[H];j!=null&&(R[H]=j)}return R},set:async Q=>{let y=e.getStore();if(!y){let m=Object.keys(Q);for(let _ of m){let T=_;T==="pre-key"&&await s.validateDeletions(Q,T)}await Promise.all(m.map(_=>g(_).add(async()=>{let T={[_]:Q[_]};await n.set(T)})));return}t.trace({types:Object.keys(Q)},"caching in transaction");for(let m in Q){let _=m;y.cache[_]=y.cache[_]||{},y.mutations[_]=y.mutations[_]||{},_==="pre-key"?await s.processOperations(Q,_,y.cache,y.mutations,!0):(Object.assign(y.cache[_],Q[_]),Object.assign(y.mutations[_],Q[_]))}},isInTransaction:B,transaction:async(Q,y)=>{if(e.getStore())return t.trace("reusing existing transaction context"),Q();let _=c(y);I(y);try{return await _.runExclusive(async()=>{let T={cache:{},mutations:{},dbQueries:0};t.trace("entering transaction");try{let R=await e.run(T,Q);return await f(T.mutations),t.trace({dbQueries:T.dbQueries},"transaction completed"),R}catch(R){throw t.error({error:R},"transaction failed, rolling back"),R}})}finally{d(y)}}}},Jie=n=>{let t=n.me?.id;if(!t)throw new Yie.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return t},qie=()=>{let n=ur.generateKeyPair();return{noiseKey:ur.generateKeyPair(),pairingEphemeralKeyPair:ur.generateKeyPair(),signedIdentityKey:n,signedPreKey:QD(n,1),registrationId:J9(),advSecretKey:SJe(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},registered:!1,pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0,additionalData:void 0}};import{mkdir as DJe,readFile as wJe,stat as OJe,unlink as bJe,writeFile as MJe}from"fs/promises";import{join as _2}from"path";var zie=new Map,T2=n=>{let t=zie.get(n);return t||(t=new kg,zie.set(n,t)),t},Vie=async n=>{let t=async(r,s)=>{let g=_2(n,a(s));return T2(g).acquire().then(async I=>{try{await MJe(g,JSON.stringify(r,qu.replacer))}finally{I()}})},o=async r=>{try{let s=_2(n,a(r));return await T2(s).acquire().then(async c=>{try{let I=await wJe(s,{encoding:"utf-8"});return JSON.parse(I,qu.reviver)}finally{c()}})}catch{return null}},i=async r=>{try{let s=_2(n,a(r));return T2(s).acquire().then(async c=>{try{await bJe(s)}catch{}finally{c()}})}catch{}},e=await OJe(n).catch(()=>{});if(e){if(!e.isDirectory())throw new Error(`found something that is not a directory at ${n}, either delete it or specify a different location`)}else await DJe(n,{recursive:!0});let a=r=>r?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||qie();return{state:{creds:A,keys:{get:async(r,s)=>{let g={};return await Promise.all(s.map(async c=>{let I=await o(`${r}-${c}.json`);r==="app-state-sync-key"&&I&&(I=oe.Message.AppStateSyncKeyData.fromObject(I)),g[c]=I})),g},set:async r=>{let s=[];for(let g in r)for(let c in r[g]){let I=r[g][c],d=`${g}-${c}.json`;s.push(I?t(I,d):i(d))}await Promise.all(s)}}},saveCreds:async()=>t(A,"creds.json")}};var _Je=192,TJe=async(n,{thumbnailWidth:t,fetchOpts:o})=>{let i=await wO(n,o);return await WL(i,t)},Wie=async(n,t={thumbnailWidth:_Je,fetchOpts:{timeout:3e3}})=>{try{let o=0,i=5,{getLinkPreview:e}=await import("link-preview-js"),a=n;!n.startsWith("https://")&&!n.startsWith("http://")&&(a="https://"+a);let A=await e(a,{...t.fetchOpts,followRedirects:"follow",handleRedirects:(r,s)=>{let g=new URL(r),c=new URL(s);return o>=i?!1:c.hostname===g.hostname||c.hostname==="www."+g.hostname||"www."+c.hostname===g.hostname?(o+=1,!0):!1},headers:t.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[r]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:r};if(t.uploadImage){let{imageMessage:g}=await xB({image:{url:r}},{upload:t.uploadImage,mediaTypeOverride:"thumbnail-link",options:t.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=r?(await TJe(r,t)).buffer:void 0}catch(g){t.logger?.debug({err:g.stack,url:a},"error in generating thumbnail")}return s}}catch(o){if(!o.message.includes("receive a valid"))throw o}};import HJe from"events";var R2=qe(Gr(),1);var NJe=/^1313555\d{4}$|^131655500\d{2}$/;function RJe(n){if(!n)return!1;let t=n.split("@")[0]??"";return t==="0"||NJe.test(t)||Nd(n)?!1:!!(bt(n)||qA(n)||Cr(n)||oa(n)||n.endsWith("@c.us"))}var PO=604800,kJe=4,eI="__index";async function GO(n){let o=(await n.get("tctoken",[eI]))[eI];if(!o?.token?.length)return[];try{let i=JSON.parse(Buffer.from(o.token).toString());return Array.isArray(i)?i.filter(e=>typeof e=="string"&&e.length>0&&e!==eI):[]}catch{return[]}}async function Rh(n,t){let o=await GO(n),i=new Set(o);for(let e of t)e&&e!==eI&&i.add(e);return{[eI]:{token:Buffer.from(JSON.stringify([...i]))}}}function kl(n){if(n==null)return!0;let t=typeof n=="string"?parseInt(n):n;if(isNaN(t))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/PO)-(kJe-1))*PO;return ti}async function ks(n,t){return qA(n)?n:await t(n)??n}async function XB(n,t,o,i){return t?qA(n)?n:await o(n)??n:qA(n)&&i?await i(n)??n:n}async function N2({authState:n,jid:t,baseContent:o=[],getLIDForPN:i}){try{let e=await ks(t,i),A=(await n.keys.get("tctoken",[e]))?.[e],r=A?.token,s=A?.timestamp;if(!r?.length||s===void 0||kl(s)){if(r){let g=A?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:A.senderTimestamp}:null;await n.keys.set({tctoken:{[e]:g}})}return o.length>0?o:void 0}return o.push({tag:"tctoken",attrs:{t:String(s)},content:r}),o}catch{return o.length>0?o:void 0}}async function kh({result:n,fallbackJid:t,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=Ie(n,"tokens");if(!a)return;let A=PA(a,"token");for(let r of A){if(r.attrs.type!=="trusted_contact"||!(r.content instanceof Uint8Array))continue;let s=uA(t||r.attrs.jid);if(!RJe(s))continue;let g=await ks(s,i),I=(await o.get("tctoken",[g]))[g],d=I?.timestamp?Number(I.timestamp):0,B=r.attrs.t?Number(r.attrs.t):0;B&&(d>0&&d>B||(await o.set({tctoken:{[g]:{...I,token:Buffer.from(r.content),timestamp:r.attrs.t}}}),e?.(g)))}}var vJe=new Set([RA.CALL_MISSED_GROUP_VIDEO,RA.CALL_MISSED_GROUP_VOICE,RA.CALL_MISSED_VIDEO,RA.CALL_MISSED_VOICE]),PJe=new Set([RA.GROUP_PARTICIPANT_ADD]);async function GJe(n,t,o,i){let e=t.lidMapping.getLIDForPN.bind(t.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?Lr(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let I=uA(g.id),d=await ks(I,e);a.push({storageJid:d,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?Lr(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),r=await o.get("tctoken",A),s={};for(let g of a){let c=r[g.storageJid],I=c?.timestamp?Number(c.timestamp):0;I>0&&I>=g.ts||(s[g.storageJid]={...c,token:g.token,timestamp:String(g.ts),...g.senderTs!==void 0?{senderTimestamp:g.senderTs}:{}})}if(Object.keys(s).length){i?.debug({count:Object.keys(s).length},"storing tctokens from history sync");try{let g=await Rh(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Xie=(n,t,o)=>{Cr(n.key.remoteJid)||oa(n.key.remoteJid)?n.key.remoteJid=Er(yA(n.key?.remoteJid)?.user,Cr(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=uA(n.key.remoteJid),Cr(n.key.participant)||oa(n.key.participant)?n.key.participant=Er(yA(n.key.participant)?.user,Cr(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=uA(n.key.participant);let i=Sa(n.message);i?.reactionMessage&&e(i.reactionMessage.key),i?.pollUpdateMessage&&e(i.pollUpdateMessage.pollCreationMessageKey);function e(a){n.key.fromMe||(a.fromMe=a.fromMe?!1:Mt(a.participant||a.remoteJid,t)||Mt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},k2=n=>{let t=Sa(n.message),o=!!YB(t);return(!!t||vJe.has(n.messageStubType)||PJe.has(n.messageStubType))&&o&&!t?.protocolMessage&&!t?.reactionMessage&&!t?.pollUpdateMessage},v2=n=>!n.key.fromMe&&!n.messageStubType,FJe=({remoteJid:n,participant:t,fromMe:o})=>{if(!n)throw new R2.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:t,fromMe:o}});if(Fu(n)&&!Bg(n)&&!o){if(!t)throw new R2.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return t}return n};function LJe({encPayload:n,encIv:t},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([I(i),I(o),I(a),I("Event Response"),new Uint8Array([1])]),r=mn(e,new Uint8Array(32),"sha256"),s=mn(A,r,"sha256"),g=I(`${i}\0${a}`),c=sl(n,s,t,g);return oe.Message.EventResponseMessage.decode(c);function I(d){return Buffer.from(d)}}var UJe=async(n,{shouldProcessHistoryMsg:t,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:r,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:I}=e,d={id:uA(FJe(n.key))},B=k2(n);B&&(d.messages=[{message:n}],d.conversationTimestamp=Lr(n.messageTimestamp),v2(n)&&(d.unreadCount=(d.unreadCount||0)+1));let f=Sa(n.message);(B||f?.reactionMessage?.key?.fromMe)&&I?.unarchiveChats&&(d.archived=!1,d.readOnly=!1);let Q=f?.protocolMessage;if(Q){let y=new Set([oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(Q.type!==null&&Q.type!==void 0&&y.has(Q.type)&&!n.key.fromMe){r?.warn({msgId:n.key.id,type:Q.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(Q.type){case oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=Q.historySyncNotification,_=t,T=!e.processedHistoryMessages?.length;if(r?.info({histNotification:m,process:_,id:n.key.id,isLatest:T},"got history notification"),_){m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let P=await Qie(m,s,r);P.lidPnMappings?.length&&(r?.debug({count:P.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(P.lidPnMappings).catch(z=>r?.warn({err:z},"failed to store LID-PN mappings from history sync"))),await GJe(P.chats,a,A,r),i.emit("messaging-history.set",{...P,isLatest:m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND?T:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let R=Q.appStateSyncKeyShare.keys;if(R?.length){let P="";await A.transaction(async()=>{let z=[];for(let{keyData:U,keyId:N}of R){let k=Buffer.from(N.keyId).toString("base64");z.push(k),await A.set({"app-state-sync-key":{[k]:U}}),P=k}r?.info({newAppStateSyncKeyId:P,newKeys:z},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:P})}else r?.info({protocolMsg:Q},"recv app state sync with 0 keys");break;case oe.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:Q.key.id},update:{message:null,messageStubType:RA.REVOKE,key:n.key}}]);break;case oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(d,{ephemeralSettingTimestamp:Lr(n.messageTimestamp),ephemeralExpiration:Q.ephemeralExpiration||null});break;case oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let H=Q.peerDataOperationRequestResponseMessage;if(H){let P=H.peerDataOperationResult||[];for(let z of P){let U=z?.placeholderMessageResendResponse;if(U?.webMessageInfoBytes)try{let N=oe.WebMessageInfo.decode(U.webMessageInfoBytes),k=N.key?.id,V=k?await o?.get(k):void 0;k&&await o?.del(k);let ee;V&&typeof V=="object"?(V.message=N.message,N.messageTimestamp&&(V.messageTimestamp=N.messageTimestamp),ee=V):ee=N,r?.debug({msgId:k,requestId:H.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[ee],type:"notify",requestId:H.stanzaId})}catch(N){r?.warn({err:N,stanzaId:H.stanzaId},"failed to decode placeholder resend response")}}}break;case oe.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:Q.key?.id},update:{message:{editedMessage:{message:Q.editedMessage}},messageTimestamp:Q.timestampMs?Math.floor(Lr(Q.timestampMs)/1e3):n.messageTimestamp}}]);break;case oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let j=Q.memberLabel;j?.label&&i.emit("group.member-tag.update",{groupId:d.id,label:j.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let F=Q.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:J}=oe.LIDMigrationMappingSyncPayload.decode(F);r?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:J},"got lid mappings and chat db migration timestamp");let x=[];for(let{pn:P,latestLid:z,assignedLid:U}of q){let N=z||U;x.push({lid:`${N}@lid`,pn:`${P}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(x),x.length)for(let{pn:P,lid:z}of x)await a.migrateSession(P,z)}}else if(f?.reactionMessage){let y={...f.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:f.reactionMessage?.key}])}else if(f?.encEventResponseMessage){let y=f.encEventResponseMessage,m=y.eventCreationMessageKey,_=await g(m);if(_)try{let T=uA(c),R=m.participant||m.remoteJid,H=qA(R)?await a.lidMapping.getPNForLID(R):R,j=Fd({remoteJid:uA(H),fromMe:T===H},T),F=Fd(n.key,T),q=_?.messageContextInfo?.messageSecret;if(!q)r?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let J=LJe(y,{eventEncKey:q,eventCreatorJid:j,eventMsgId:m.id,responderJid:F}),x={eventResponseMessageKey:n.key,senderTimestampMs:J.timestampMs,response:J};i.emit("messages.update",[{key:m,update:{eventResponses:[x]}}])}}catch(T){r?.warn({err:T,creationMsgKey:m},"failed to decrypt event response")}else r?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,_=j=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:j}),T=j=>{i.emit("groups.update",[{id:y,...j,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},R=(j,F,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:j.lid,participantPn:j.pn,action:F,method:q})},H=()=>m.find(j=>Mt(c,j.phoneNumber));switch(n.messageStubType){case RA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("modify");break;case RA.GROUP_PARTICIPANT_LEAVE:case RA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("remove"),H()&&(d.readOnly=!0);break;case RA.GROUP_PARTICIPANT_ADD:case RA.GROUP_PARTICIPANT_INVITE:case RA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],H()&&(d.readOnly=!1),_("add");break;case RA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("demote");break;case RA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("promote");break;case RA.GROUP_CHANGE_ANNOUNCE:let j=n.messageStubParameters?.[0];T({announce:j==="true"||j==="on"});break;case RA.GROUP_CHANGE_RESTRICT:let F=n.messageStubParameters?.[0];T({restrict:F==="true"||F==="on"});break;case RA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];d.name=q,T({subject:q});break;case RA.GROUP_CHANGE_DESCRIPTION:let J=n.messageStubParameters?.[0];d.description=J,T({desc:J});break;case RA.GROUP_CHANGE_INVITE_LINK:let x=n.messageStubParameters?.[0];T({inviteCode:x});break;case RA.GROUP_MEMBER_ADD_MODE:let P=n.messageStubParameters?.[0];T({memberAddMode:P==="all_member_add"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let z=n.messageStubParameters?.[0];T({joinApprovalMode:z==="on"});break;case RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let U=JSON.parse(n.messageStubParameters?.[0]),N=n.messageStubParameters?.[1],k=n.messageStubParameters?.[2];R(U,N,k);break}}Object.keys(d).length>1&&i.emit("chats.update",[d])},$ie=UJe;var KJe=["messaging-history.set","chats.upsert","chats.update","chats.delete","contacts.upsert","contacts.update","messages.upsert","messages.update","messages.delete","messages.reaction","message-receipt.update","groups.update"],xJe=new Set(KJe),eoe=n=>{let t=new HJe,o=new Set,i=P2(),e=!1,a=null,A=null,r=0,s=1e4,g=3e4;t.on("event",d=>{for(let B in d)t.emit(B,d[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,r=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),I())},g)),r++}function I(){if(!e)return!1;n.debug({bufferCount:r},"Flushing event buffer"),e=!1,r=0,a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.size>s&&(n.debug({cacheSize:o.size},"Clearing history cache"),o.clear());let d=P2(),B=Object.values(i.chatUpdates),f=0;for(let y of B)y.conditional&&(f+=1,d.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let Q=jJe(i);return Object.keys(Q).length&&t.emit("event",Q),i=d,n.trace({conditionalChatUpdatesLeft:f},"released buffered events"),!0}return{process(d){let B=async f=>{await d(f)};return t.on("event",B),()=>{t.off("event",B)}},emit(d,B){if(d==="messages.upsert"){let{type:f}=B,Q=Object.values(i.messageUpserts);if(Q.length>0){let y=Q[0].type;y!==f&&(n.debug({bufferedType:y,newType:f},"messages.upsert type mismatch, emitting buffered messages"),t.emit("event",{"messages.upsert":{messages:Q.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&xJe.has(d)?(YJe(i,o,d,B,n),!0):t.emit("event",{[d]:B})},isBuffering(){return e},buffer:c,flush:I,createBufferedFunction(d){return async(...B)=>{c();try{let f=await d(...B);return r===1&&setTimeout(()=>{e&&r===1&&I()},100),f}catch(f){throw f}finally{r=Math.max(0,r-1),r===0&&(A||(A=setTimeout(I,100)))}}},on:(...d)=>t.on(...d),off:(...d)=>t.off(...d),removeAllListeners:(...d)=>t.removeAllListeners(...d),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=P2(),e=!1,r=0,t.removeAllListeners(),n.debug("Event buffer destroyed")}}},P2=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function YJe(n,t,o,i,e){switch(o){case"messaging-history.set":for(let Q of i.chats){let y=Q.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=Q.endOfHistoryTransferType),!m&&!t.has(y)&&(n.historySets.chats[y]=Q,t.add(y),a(Q))}for(let Q of i.contacts){let y=n.historySets.contacts[Q.id];if(y)Object.assign(y,SD(Q));else{let m=`c:${Q.id}`,_=Q.notify||Q.name||Q.verifiedName;(!t.has(m)||_)&&(n.historySets.contacts[Q.id]=Q,t.add(m))}}for(let Q of i.messages){let y=vh(Q.key);!n.historySets.messages[y]&&!t.has(y)&&(n.historySets.messages[y]=Q,t.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let Q=new Map,y=_=>`${_.userJid||""}:${_.leaveTs||""}:${_.leaveReason||""}`,m=_=>{let T=_.groupJid??JSON.stringify(_),R=Q.get(T);if(!R){Q.set(T,{..._,pastParticipants:[..._.pastParticipants||[]]});return}let H=new Set((R.pastParticipants||[]).map(y));for(let j of _.pastParticipants||[]){let F=y(j);H.has(F)||(R.pastParticipants.push(j),H.add(F))}};for(let _ of n.historySets.pastParticipants||[])m(_);for(let _ of i.pastParticipants)m(_);n.historySets.pastParticipants=[...Q.values()]}n.historySets.progress=i.progress,n.historySets.chunkOrder=i.chunkOrder,n.historySets.peerDataRequestSessionId=i.peerDataRequestSessionId,n.historySets.isLatest=i.isLatest||n.historySets.isLatest;break;case"chats.upsert":for(let Q of i){let y=Q.id||"",m=n.chatUpserts[y];y&&!m&&(m=n.historySets.chats[y],m&&e.debug({chatId:y},"absorbed chat upsert in chat set")),m?m=FO(m,Q):(m=Q,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let Q of i){let y=Q.id,m=Q.conditional?Q.conditional(n):!0;if(m){delete Q.conditional;let _=n.historySets.chats[y]||n.chatUpserts[y];if(_)FO(_,Q);else{let T=n.chatUpdates[y]||{};n.chatUpdates[y]=FO(T,Q)}}else m===void 0&&(n.chatUpdates[y]=Q);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let Q of i)n.chatDeletes.has(Q)||n.chatDeletes.add(Q),n.chatUpdates[Q]&&delete n.chatUpdates[Q],n.chatUpserts[Q]&&delete n.chatUpserts[Q],n.historySets.chats[Q]&&delete n.historySets.chats[Q];break;case"contacts.upsert":for(let Q of i){let y=n.contactUpserts[Q.id];y||(y=n.historySets.contacts[Q.id],y&&e.debug({contactId:Q.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,SD(Q)):(y=Q,n.contactUpserts[Q.id]=y),n.contactUpdates[Q.id]&&(y=Object.assign(n.contactUpdates[Q.id],SD(Q)),delete n.contactUpdates[Q.id])}break;case"contacts.update":let r=i;for(let Q of r){let y=Q.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,Q);else{let _=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(_,Q)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let Q of s){let y=vh(Q.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(Q.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(Q,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=Q:n.messageUpserts[y]={message:Q,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:Q,update:y}of c){let m=vh(Q),_=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(_)Object.assign(_,y),y.status===Td.READ&&!Q.fromMe&&A(_);else{let T=n.messageUpdates[m]||{key:Q,update:{}};Object.assign(T.update,y),n.messageUpdates[m]=T}}break;case"messages.delete":let I=i;if("keys"in I){let{keys:Q}=I;for(let y of Q){let m=vh(y);n.messageDeletes[m]||(n.messageDeletes[m]=y),n.messageUpserts[m]&&delete n.messageUpserts[m],n.messageUpdates[m]&&delete n.messageUpdates[m]}}break;case"messages.reaction":let d=i;for(let{key:Q,reaction:y}of d){let m=vh(Q),_=n.messageUpserts[m];_?a2(_.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:Q,reactions:[]},a2(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:Q,receipt:y}of B){let m=vh(Q),_=n.messageUpserts[m];_?r2(_.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:Q,userReceipt:[]},r2(n.messageReceipts[m],y))}break;case"groups.update":let f=i;for(let Q of f){let y=Q.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,Q))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(r){let s=r.id||"",g=n.chatUpdates[s];if(g){let c=g.conditional?g.conditional(n):!0;c?(delete g.conditional,e.debug({chatId:s},"absorbed chat update in existing chat"),Object.assign(r,FO(g,r)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(r){let s=r.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];k2(r)&&v2(r)&&typeof g?.unreadCount=="number"&&g.unreadCount>0&&(e.debug({chatId:g.id},"decrementing chat counter"),g.unreadCount-=1,g.unreadCount===0&&delete g.unreadCount)}}function jJe(n){let t={};n.historySets.empty||(t["messaging-history.set"]={chats:Object.values(n.historySets.chats),messages:Object.values(n.historySets.messages),contacts:Object.values(n.historySets.contacts),pastParticipants:n.historySets.pastParticipants,syncType:n.historySets.syncType,progress:n.historySets.progress,isLatest:n.historySets.isLatest,chunkOrder:n.historySets.chunkOrder,peerDataRequestSessionId:n.historySets.peerDataRequestSessionId});let o=Object.values(n.chatUpserts);o.length&&(t["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(t["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(t["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;t["messages.upsert"]={messages:a.map(f=>f.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(t["messages.update"]=A);let r=Object.values(n.messageDeletes);r.length&&(t["messages.delete"]={keys:r});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:f})=>f.flatMap(Q=>({key:B,reaction:Q})));s.length&&(t["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:f})=>f.flatMap(Q=>({key:B,receipt:Q})));g.length&&(t["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(t["contacts.upsert"]=c);let I=Object.values(n.contactUpdates);I.length&&(t["contacts.update"]=I);let d=Object.values(n.groupUpdates);return d.length&&(t["groups.update"]=d),t}function FO(n,t){return t.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,t.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof t.unreadCount=="number"&&(t={...t},t.unreadCount>=0&&(t.unreadCount=Math.max(t.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,t)}var vh=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var JJe=512,G2="\0",Aoe=3600*1e3,qJe=3e3,vg;(function(n){n[n.UnknownError=0]="UnknownError",n[n.SignalErrorNoSession=1]="SignalErrorNoSession",n[n.SignalErrorInvalidKey=2]="SignalErrorInvalidKey",n[n.SignalErrorInvalidKeyId=3]="SignalErrorInvalidKeyId",n[n.SignalErrorInvalidMessage=4]="SignalErrorInvalidMessage",n[n.SignalErrorInvalidSignature=5]="SignalErrorInvalidSignature",n[n.SignalErrorFutureMessage=6]="SignalErrorFutureMessage",n[n.SignalErrorBadMac=7]="SignalErrorBadMac",n[n.SignalErrorInvalidSession=8]="SignalErrorInvalidSession",n[n.SignalErrorInvalidMsgKey=9]="SignalErrorInvalidMsgKey",n[n.BadBroadcastEphemeralSetting=10]="BadBroadcastEphemeralSetting",n[n.UnknownCompanionNoPrekey=11]="UnknownCompanionNoPrekey",n[n.AdvFailure=12]="AdvFailure",n[n.StatusRevokeDelay=13]="StatusRevokeDelay"})(vg||(vg={}));var toe=new Set([vg.SignalErrorInvalidMessage,vg.SignalErrorBadMac]),LO=class{constructor(t,o){this.logger=t,this.recentMessagesMap=new Cg({max:JJe,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(G2);if(a>-1){let A=e.slice(a+G2.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Cg({ttl:Aoe*2,ttlAutopurge:!0}),this.retryCounters=new Cg({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Cg({max:1024,ttl:900*1e3,ttlAutopurge:!0}),this.pendingPhoneRequests={},this.maxMsgRetryCount=5,this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0},this.maxMsgRetryCount=o}addRecentMessage(t,o,i){let e={to:t,id:o},a=this.keyToString(e);this.recentMessagesMap.set(a,{message:i,timestamp:Date.now()}),this.messageKeyIndex.set(o,a),this.logger.debug(`Added message to retry cache: ${t}/${o}`)}getRecentMessage(t,o){let i={to:t,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(t,o,i){if(!o)return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&toe.has(i))return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:t,errorCode:vg[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${vg[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(t);return!a||e-a>Aoe?(this.sessionRecreateHistory.set(t,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(t){if(t===void 0||t==="")return;let o=parseInt(t,10);if(!Number.isNaN(o))return o>=vg.UnknownError&&o<=vg.StatusRevokeDelay?o:vg.UnknownError}isMacError(t){return t!==void 0&&toe.has(t)}incrementRetryCount(t){return this.retryCounters.set(t,(this.retryCounters.get(t)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(t)}getRetryCount(t){return this.retryCounters.get(t)||0}hasExceededMaxRetries(t){return this.getRetryCount(t)>=this.maxMsgRetryCount}markRetrySuccess(t){this.statistics.successfulRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}markRetryFailed(t){this.statistics.failedRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}schedulePhoneRequest(t,o,i=qJe){this.cancelPendingPhoneRequest(t),this.pendingPhoneRequests[t]=setTimeout(()=>{delete this.pendingPhoneRequests[t],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${t} with ${i}ms delay`)}cancelPendingPhoneRequest(t){let o=this.pendingPhoneRequests[t];o&&(clearTimeout(o),delete this.pendingPhoneRequests[t],this.logger.debug(`Cancelled pending phone request for message ${t}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let t of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(t);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(t,o,i){this.baseKeys.set(`${t}:${o}`,i)}hasSameBaseKey(t,o,i){let e=this.baseKeys.get(`${t}:${o}`);if(!e||e.length!==i.length)return!1;for(let a=0;a["Ubuntu",n,"22.04.4"],macOS:n=>["Mac OS",n,"14.4.1"],baileys:n=>["Baileys",n,"6.5.0"],windows:n=>["Windows",n,"10.0.22631"],android:n=>[n,"Android",""],appropriate:n=>[WJe[zJe()]||"Ubuntu",n,VJe()]};var wn;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.CHROME=1]="CHROME",n[n.EDGE=2]="EDGE",n[n.FIREFOX=3]="FIREFOX",n[n.IE=4]="IE",n[n.OPERA=5]="OPERA",n[n.SAFARI=6]="SAFARI",n[n.ELECTRON=7]="ELECTRON",n[n.UWP=8]="UWP",n[n.OTHER_WEB_CLIENT=9]="OTHER_WEB_CLIENT"})(wn||(wn={}));var ZJe={Chrome:wn.CHROME,Edge:wn.EDGE,Firefox:wn.FIREFOX,IE:wn.IE,Opera:wn.OPERA,Safari:wn.SAFARI},XJe=([n,t])=>t==="Desktop"?n==="Windows"?wn.UWP:wn.ELECTRON:ZJe[t]||wn.OTHER_WEB_CLIENT,F2=n=>XJe(n).toString(),roe=(n,t,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,t,o,i,F2(e)].join(",");async function aoe(n,t){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!Ie(n,"identity"))return{action:"no_identity_node"};t.logger.info({jid:o},"identity changed");let e=yA(o);if(e?.device&&e.device!==0)return t.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(t.meId&&(Mt(o,t.meId)||t.meLid&&Mt(o,t.meLid)))return t.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(t.debounceCache.get(o))return t.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};t.debounceCache.set(o,!0);let A=!x9(n.attrs.offline);if(!(await t.validateSession(o)).exists)return t.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(t.logger.debug({jid:o},"old session exists, will refresh session"),A)return t.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};t.onBeforeSessionRefresh?.(o);try{return await t.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return t.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function ioe(n,t,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return t&&(a.attrs.error=t.toString()),e.participant&&(a.attrs.participant=e.participant),e.recipient&&(a.attrs.recipient=e.recipient),e.type&&(a.attrs.type=e.type),i==="message"&&o&&(a.attrs.from=o),a}function $Je(n){return n===null||n===""}function eqe(n){return n>2147483647||n<-2147483648?n&4294967295:n}function ooe(n){let t=0;if(!$Je(n))for(let o=0;oo.iteration===t)}addSenderMessageKey(t){this.senderKeyStateStructure.senderMessageKeys.push({iteration:t.getIteration(),seed:t.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(t){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===t);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new vl(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var Pg=class n{constructor(t){if(this.MAX_STATES=5,this.senderKeyStates=[],t)for(let o of t)this.senderKeyStates.push(new Pl(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(t){return t===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===t)}addSenderKeyState(t,o,i,e){this.senderKeyStates.push(new Pl(t,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(t,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new Pl(t,o,i,e))}serialize(){return this.senderKeyStates.map(t=>t.getStructure())}static deserialize(t){let o=Buffer.from(t).toString("utf-8"),i=JSON.parse(o,qu.reviver);return new n(i)}};var goe=qe(Bc(),1);import*as HO from"crypto";function coe(){return HO.randomBytes(32)}function Ioe(){return HO.randomInt(2147483647)}function loe(n){return n||(n=(0,goe.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var Gl=class{constructor(){this.UNSUPPORTED_VERSION=1,this.CURRENT_VERSION=3,this.WHISPER_TYPE=2,this.PREKEY_TYPE=3,this.SENDERKEY_TYPE=4,this.SENDERKEY_DISTRIBUTION_TYPE=5,this.ENCRYPTED_MESSAGE_OVERHEAD=53}};var Fl=class extends Gl{constructor(t,o,i,e,a){if(super(),a)try{let A=a.slice(1),r=oe.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=r.id,this.iteration=r.iteration,this.chainKey=typeof r.chainKey=="string"?Buffer.from(r.chainKey,"base64"):r.chainKey,this.signatureKey=typeof r.signingKey=="string"?Buffer.from(r.signingKey,"base64"):r.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=t,this.iteration=o,this.chainKey=i,this.signatureKey=e;let r=oe.SenderKeyDistributionMessage.encode(oe.SenderKeyDistributionMessage.create({id:t,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),r])}}intsToByteHighAndLow(t,o){return((t<<4|o)&255)%256}serialize(){return this.serialized}getType(){return this.SENDERKEY_DISTRIBUTION_TYPE}getIteration(){return this.iteration}getChainKey(){return this.chainKey}getSignatureKey(){return this.signatureKey}getId(){return this.id}};var Ph=class{constructor(t){this.senderKeyStore=t}async process(t,o){let i=await this.senderKeyStore.loadSenderKey(t);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(t,i)}async create(t){let o=await this.senderKeyStore.loadSenderKey(t);if(o.isEmpty()){let e=Ioe(),a=coe(),A=loe();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(t,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new Fl(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var xO=qe(rl(),1);var KO=qe(Bc(),1);var Gh=class extends Gl{constructor(t,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],r=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=oe.SenderKeyMessage.decode(r).toJSON();this.serialized=a,this.messageVersion=(A&255)>>4,this.keyId=g.id,this.iteration=g.iteration,this.ciphertext=typeof g.ciphertext=="string"?Buffer.from(g.ciphertext,"base64"):g.ciphertext,this.signature=s}else{let A=((this.CURRENT_VERSION<<4|this.CURRENT_VERSION)&255)%256,r=Buffer.from(i),s=oe.SenderKeyMessage.encode(oe.SenderKeyMessage.create({id:t,iteration:o,ciphertext:r})).finish(),g=this.getSignature(e,Buffer.concat([Buffer.from([A]),s]));this.serialized=Buffer.concat([Buffer.from([A]),s,Buffer.from(g)]),this.messageVersion=this.CURRENT_VERSION,this.keyId=t,this.iteration=o,this.ciphertext=r,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(t){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,KO.verifySignature)(t,o,i))throw new Error("Invalid signature!")}getSignature(t,o){return Buffer.from((0,KO.calculateSignature)(t,o))}serialize(){return this.serialized}getType(){return 4}};var Fh=class{constructor(t,o){this.senderKeyStore=t,this.senderKeyName=o}async encrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for encryption");let i=o.getSenderKeyState();if(!i)throw new Error("No session to encrypt message");let e=i.getSenderChainKey().getIteration(),a=this.getSenderKey(i,e===0?0:e+1),A=await this.getCipherText(a.getIv(),a.getCipherKey(),t),r=new Gh(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),r.serialize()}async decrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new Gh(null,null,null,null,t),e=o.getSenderKeyState(i.getKeyId());if(!e)throw new Error("No session found to decrypt message");i.verifySignature(e.getSigningKeyPublic());let a=this.getSenderKey(e,i.getIteration()),A=await this.getPlainText(a.getIv(),a.getCipherKey(),i.getCipherText());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),A}getSenderKey(t,o){let i=t.getSenderChainKey();if(i.getIteration()>o){if(t.hasSenderMessageKey(o)){let e=t.removeSenderMessageKey(o);if(!e)throw new Error("No sender message key found for iteration");return e}throw new Error(`Received message with old counter: ${i.getIteration()}, ${o}`)}if(o-i.getIteration()>2e3)throw new Error("Over 2000 messages into the future!");for(;i.getIteration()0){let r=[...i];this.logger.trace(`Batch fetching ${r.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",r);for(let g of r){let c=s[g];c&&(e.set(g,c),this.mappingCache.set(`pn:${g}`,c),this.mappingCache.set(`lid:${c}`,g))}}let a={};for(let{pnUser:r,lidUser:s}of o){if(e.get(r)===s){this.logger.debug({pnUser:r,lidUser:s},"LID mapping already exists, skipping");continue}a[r]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[r,s]of Object.entries(a))A[r]=s,A[`${s}_reverse`]=r;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[r,s]of Object.entries(a))this.mappingCache.set(`pn:${r}`,s),this.mappingCache.set(`lid:${s}`,r)}async getLIDForPN(t){return(await this.getLIDsForPNs([t]))?.[0]?.lid||null}async getLIDsForPNs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightLIDLookups.get(i);if(e)return this.logger.trace(`Coalescing getLIDsForPNs request for ${o.length} PNs`),e;let a=this._getLIDsForPNsImpl(t);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(t){let o={},i={},e=[],a=(A,r,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=r.device!==void 0?r.device:0,I=`${g}${c?`:${c}`:""}@${r.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${I} (user mapping with device ${c})`),i[A]={lid:I,pn:A},!0};for(let A of t){if(!bt(A)&&!Cr(A))continue;let r=yA(A);if(!r)continue;let s=r.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,r,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:r})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],r=await this.keys.get("lid-mapping",A);for(let s of A){let g=r[s];g&&typeof g=="string"&&(this.mappingCache.set(`pn:${s}`,g),this.mappingCache.set(`lid:${g}`,s))}for(let{pn:s,pnUser:g,decoded:c}of e){let I=this.mappingCache.get(`pn:${g}`);if(I&&typeof I=="string"){if(!a(s,c,I)){this.logger.warn(`Invalid entry for ${s} (pair not resolved)`);continue}}else{this.logger.trace(`No LID mapping found for PN user ${g}; batch getting from USync`);let d=c.device||0,B=uA(s);Cr(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(d):o[B]=[d]}}}if(Object.keys(o).length>0){let A=await this.pnToLIDFunc?.(Object.keys(o));if(A&&A.length>0){await this.storeLIDPNMappings(A);for(let r of A){let g=yA(r.pn)?.user;if(!g)continue;let c=yA(r.lid)?.user;if(c)for(let I of o[r.pn]){let d=`${c}${I?`:${I}`:""}@${I===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${r.pn} \u2192 ${d} (user mapping with device ${I})`);let B=`${g}${I?`:${I}`:""}@${I===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:d,pn:B}}}}else this.logger.warn("USync fetch yielded no results for pending PNs")}return Object.values(i).length>0?Object.values(i):null}async getPNForLID(t){return(await this.getPNsForLIDs([t]))?.[0]?.pn||null}async getPNsForLIDs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightPNLookups.get(i);if(e)return this.logger.trace(`Coalescing getPNsForLIDs request for ${o.length} LIDs`),e;let a=this._getPNsForLIDsImpl(t);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(t){let o={},i=[],e=(a,A,r)=>{if(!r||typeof r!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${r}:${s}@${A.domainType===xt.HOSTED_LID?"hosted":"s.whatsapp.net"}`;return this.logger.trace(`Found reverse mapping: ${a} \u2192 ${g}`),o[a]={lid:a,pn:g},!0};for(let a of t){if(!qA(a))continue;let A=yA(a);if(!A)continue;let r=A.user,s=this.mappingCache.get(`lid:${r}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:r,decoded:A})}if(i.length){let a=[...new Set(i.map(r=>`${r.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:r,lidUser:s,decoded:g}of i){let c=this.mappingCache.get(`lid:${s}`);(!c||typeof c!="string")&&(c=A[`${s}_reverse`],c&&typeof c=="string"&&(this.mappingCache.set(`lid:${s}`,c),this.mappingCache.set(`pn:${c}`,s))),c&&typeof c=="string"?e(r,g,c):this.logger.trace(`No reverse mapping found for LID user: ${s}`)}}return Object.values(o).length?Object.values(o):null}close(){this.mappingCache.clear()}};function Aqe(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=doe.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function hoe(n,t,o){let i=new YO(n.keys,t,o),e=tqe(n,i),a=n.keys,A=new Cg({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),r=async(g,c)=>{let I=jO(g,c),d=I.toString(),{[d]:B}=await n.keys.get("sender-key",[d]);B||await e.storeSenderKey(I,new Pg);let f=await new Ph(e).create(I);return{senderName:I,skdm:f}};return{decryptGroupMessage({group:g,authorJid:c,msg:I}){let d=jO(g,c),B=new Fh(e,d);return a.transaction(async()=>B.decrypt(I),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let I=new Ph(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let d=jO(g.groupId,c),B=new Fl(null,null,null,null,g.axolotlSenderKeyDistributionMessage),f=d.toString(),{[f]:Q}=await n.keys.get("sender-key",[f]);return Q||await e.storeSenderKey(d,new Pg),a.transaction(async()=>{let{[f]:y}=await n.keys.get("sender-key",[f]);y||await e.storeSenderKey(d,new Pg),await I.process(d,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:I}){let d=On(g),B=new vs.SessionCipher(e,d);if(c==="pkmsg"){let Q=Aqe(I);if(Q){let y=d.toString();await e.saveIdentity(y,Q)&&t.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function f(){let Q;switch(c){case"pkmsg":Q=await B.decryptPreKeyWhisperMessage(I);break;case"msg":Q=await B.decryptWhisperMessage(I);break}return Q}return a.transaction(async()=>await f(),g)},async encryptMessage({jid:g,data:c}){let I=On(g),d=new vs.SessionCipher(e,I);return a.transaction(async()=>{let{type:B,body:f}=await d.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(f,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:I}){return a.transaction(async()=>{let{senderName:d,skdm:B}=await r(g,c);return{ciphertext:await new Fh(e,d).encrypt(I),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:I}=await r(g,c);return I.serialize()},g)},async hasSenderKey({group:g,meId:c}){let I=jO(g,c).toString(),{[I]:d}=await n.keys.get("sender-key",[I]);return!!d},async getSessionInfo(g){let c=On(g).toString(),I=await e.loadSession(c);if(!I)return null;let d=I.getOpenSession?.(),B=d?.indexInfo?.baseKey,f=d?.registrationId;return!B||typeof f!="number"?null:{baseKey:new Uint8Array(B),registrationId:f}},async injectE2ESession({jid:g,session:c}){t.trace({jid:g},"injecting E2EE session");let I=new vs.SessionBuilder(e,On(g));return a.transaction(async()=>{await I.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return On(g).toString()},lidMapping:i,async validateSession(g){try{let c=On(g),I=await e.loadSession(c.toString());return I?I.haveOpenSession()?{exists:!0}:{exists:!1,reason:"no open session"}:{exists:!1,reason:"no session"}}catch{return{exists:!1,reason:"validation error"}}},async deleteSession(g){if(!g.length)return;let c={};return g.forEach(I=>{let d=On(I);c[d.toString()]=null}),a.transaction(async()=>{await n.keys.set({session:c})},`delete-${g.length}-sessions`)},close(){A.clear(),i.close()},async migrateSession(g,c){if(!g||!qA(c)&&!oa(c))return{migrated:0,skipped:0,total:0};if(!bt(g)&&!Cr(g))return{migrated:0,skipped:0,total:1};let{user:I}=yA(g);t.debug({fromJid:g},"bulk device migration - loading all user devices");let{[I]:d}=await a.get("device-list",[I]);if(!d)return{migrated:0,skipped:0,total:0};let{device:B}=yA(g),f=B?.toString()||"0";d.includes(f)||d.push(f);let y=d.filter(T=>{let R=`${I}.${T}`;return!A.has(R)}).map(T=>`${I}.${T}`),m=await a.get("session",y),_=[];for(let[T,R]of Object.entries(m))if(R){let H=T.split(".")[1];if(!H)continue;let j=parseInt(H),F=j===0?`${I}@s.whatsapp.net`:`${I}:${j}@s.whatsapp.net`;j===99&&(F=`${I}:99@hosted`),_.push(F)}return t.debug({fromJid:g,totalDevices:d.length,devicesWithSessions:_.length,devices:_},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let T=_.map(x=>{let P=l9(x,c),z=yA(x),U=yA(P);return{fromJid:x,toJid:P,pnUser:z.user,lidUser:U.user,deviceId:z.device||0,fromAddr:On(x),toAddr:On(P)}}),R=T.length,H=0,j=Array.from(new Set(T.map(x=>x.fromAddr.toString()))),F=await a.get("session",j),q={};for(let x of T){let P=x.fromAddr.toString(),z=x.toAddr.toString(),U=F[P];if(U){let N=vs.SessionRecord.deserialize(U);N.haveOpenSession()&&(q[z]=N.serialize(),q[P]=null,H++)}}if(Object.keys(q).length>0){await a.set({session:q}),t.debug({migratedSessions:H},"bulk session migration complete");for(let x of T)if(q[x.toAddr.toString()]){let P=`${x.pnUser}.${x.deviceId}`;A.set(P,!0)}}let J=R-H;return{migrated:H,skipped:J,total:R}},`migrate-${_.length}-sessions-${yA(c)?.user}`)}}}var On=n=>{let t=yA(n),{user:o,device:i,server:e,domainType:a}=t;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==xt.WHATSAPP?`${o}_${a}`:o,r=i||0;if(i===99&&t.server!=="hosted"&&t.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new vs.ProtocolAddress(A,r)},jO=(n,t)=>new $B(n,On(t));function tqe({creds:n,keys:t},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[r,s]=a.split("_"),g=parseInt(s||"0");if(g===xt.LID||g===xt.HOSTED_LID)return e;let c=`${r}${A!=="0"?`:${A}`:""}@${g===xt.HOSTED?"hosted":"s.whatsapp.net"}`,I=await o.getLIDForPN(c);if(I)return On(I).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await t.get("session",[a]);if(A)return vs.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await t.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await t.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:r}=await t.get("identity-key",[A]),s=r?.length===a.length&&r.every((g,c)=>g===a[c]);return r&&!s?(await t.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):r?!1:(await t.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>t.set({"pre-key":{[e]:null}}),loadSignedPreKey:()=>{let e=n.signedPreKey;return{privKey:Buffer.from(e.keyPair.private),pubKey:Buffer.from(e.keyPair.public)}},loadSenderKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("sender-key",[a]);return A?Pg.deserialize(A):new Pg},storeSenderKey:async(e,a)=>{let A=e.toString(),r=JSON.stringify(a.serialize());await t.set({"sender-key":{[A]:Buffer.from(r,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from(vo(e.public))}}}}var Cse=qe(Ese(),1),of=(0,Cse.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var TVe=[2,3e3,1043857760];var KB="https://web.whatsapp.com",eie="https://call.whatsapp.com/video/",Aie="https://call.whatsapp.com/voice/",xh="CB:",use="TAG:";var die=Buffer.from([6,0]),hie=Buffer.from([6,1]),g2=Buffer.from([6,5]),hTA=Buffer.from([6,6]),jB=10080*60,Bse=1440*60,fse=336*60*60,fie="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",NVe=3,Qg=Buffer.from([5]),Qse=Buffer.from([87,65,6,NVe]),tie=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,I2={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},nf=[oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,oe.HistorySync.HistorySyncType.PUSH_NAME,oe.HistorySync.HistorySyncType.RECENT,oe.HistorySync.HistorySyncType.FULL,oe.HistorySync.HistorySyncType.ON_DEMAND,oe.HistorySync.HistorySyncType.NON_BLOCKING_DATA,oe.HistorySync.HistorySyncType.INITIAL_STATUS_V3],$c={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},yse={version:TVe,browser:UO.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:of.child({class:"baileys"}),emitOwnEvents:!0,defaultQueryTimeoutMs:6e4,customUploadHosts:[],retryRequestDelayMs:250,maxMsgRetryCount:5,fireInitQueries:!0,auth:void 0,markOnlineOnConnect:!0,syncFullHistory:!0,patchMessageBeforeSending:n=>n,shouldSyncHistoryMessage:({syncType:n})=>n!==oe.HistorySync.HistorySyncType.FULL,shouldIgnoreJid:()=>!1,linkPreviewImageThumbnailWidth:192,transactionOpts:{maxCommitRetries:10,delayBetweenTriesMs:3e3},generateHighQualityLinkPreview:!1,enableAutoSessionRecreation:!0,enableRecentMessageCache:!0,options:{},appStateMacVerification:{patch:!1,snapshot:!1},countryCode:"US",getMessage:async()=>{},cachedGroupMetadata:async()=>{},makeSignalRepository:hoe},$L={image:"/mms/image",video:"/mms/video",document:"/mms/document",audio:"/mms/audio",sticker:"/mms/image","thumbnail-link":"/mms/image","product-catalog-image":"/product/image","md-app-state":"","md-msg-hist":"/mms/md-app-state","biz-cover-photo":"/pps/biz-cover-photo"},xae={audio:"Audio",document:"Document",gif:"Video",image:"Image",ppic:"",product:"Image",ptt:"Audio",sticker:"Image",video:"Video","thumbnail-document":"Document Thumbnail","thumbnail-image":"Image Thumbnail","thumbnail-video":"Video Thumbnail","thumbnail-link":"Link Thumbnail","md-msg-hist":"History","md-app-state":"App State","product-catalog-image":"","payment-bg-image":"Payment Background",ptv:"Video","biz-cover-photo":"Image"},rie=Object.keys($L),mse=12e4,sf=5,Sse=812,Dse=3e4,TU={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var wse=qe(Gr(),1);import{createHash as RVe}from"crypto";import{createWriteStream as kVe,promises as vVe}from"fs";import{tmpdir as PVe}from"os";import{join as GVe}from"path";var Ose=n=>{let t=Ie(n,"product_catalog"),o=PA(t,"product").map(gf),i=Ie(t,"paging");return{products:o,nextPageCursor:i?jA(i,"after"):void 0}},bse=n=>{let t=Ie(n,"collections");return{collections:PA(t,"collection").map(i=>{let e=jA(i,"id"),a=jA(i,"name"),A=PA(i,"product").map(gf);return{id:e,name:a,products:A,status:UVe(i)}})}},Mse=n=>{let t=Ie(n,"order"),o=PA(t,"product").map(a=>{let A=Ie(a,"image");return{id:jA(a,"id"),name:jA(a,"name"),imageUrl:jA(A,"url"),price:+jA(a,"price"),currency:jA(a,"currency"),quantity:+jA(a,"quantity")}}),i=Ie(t,"price");return{price:{total:+jA(i,"total"),currency:jA(i,"currency")},products:o}},NU=(n,t)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof t.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(t.name)}),typeof t.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(t.description)}),typeof t.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(t.retailerId)}),t.images.length&&i.push({tag:"media",attrs:{},content:t.images.map(a=>{if(!("url"in a))throw new wse.Boom("Expected img for product to already be uploaded",{statusCode:400});return{tag:"image",attrs:{},content:[{tag:"url",attrs:{},content:Buffer.from(a.url.toString())}]}})}),typeof t.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(t.price.toString())}),typeof t.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(t.currency)}),"originCountryCode"in t&&(typeof t.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(t.originCountryCode)}]})),typeof t.isHidden<"u"&&(o.is_hidden=t.isHidden.toString()),{tag:"product",attrs:o,content:i}},gf=n=>{let t=n.attrs.is_hidden==="true",o=jA(n,"id"),i=Ie(n,"media"),e=Ie(n,"status_info");return{id:o,imageUrls:LVe(i),reviewStatus:{whatsapp:jA(e,"status")},availability:"in stock",name:jA(n,"name"),retailerId:jA(n,"retailer_id"),url:jA(n,"url"),description:jA(n,"description"),price:+jA(n,"price"),currency:jA(n,"currency"),isHidden:t}};async function RU(n,t,o=3e4){return n={...n,images:n.images?await FVe(n.images,t,o):n.images},n}var FVe=async(n,t,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let I=e.url.toString();if(I.includes(".whatsapp.net"))return{url:I}}let{stream:a}=await UB(e),A=RVe("sha256"),r=GVe(PVe(),"img"+Ur()),s=kVe(r);for await(let I of a)A.update(I),s.write(I);let g=A.digest("base64"),{directPath:c}=await t(r,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await vVe.unlink(r).catch(I=>console.log("Error deleting temp file ",I)),{url:HB(c)}})),LVe=n=>{let t=Ie(n,"image");return{requested:jA(t,"request_image_url"),original:jA(t,"original_image_url")}},UVe=n=>{let t=Ie(n,"status_info");return{status:jA(t,"status"),canAppeal:jA(t,"can_appeal")==="true"}};var If=qe(Gr(),1);import{randomBytes as LU}from"crypto";var Vo=null;try{Vo=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Nt(n,t,o){this.low=n|0,this.high=t|0,this.unsigned=!!o}Nt.prototype.__isLong__;Object.defineProperty(Nt.prototype,"__isLong__",{value:!0});function za(n){return(n&&n.__isLong__)===!0}function _se(n){var t=Math.clz32(n&-n);return n?31-t:t}Nt.isLong=za;var Tse={},Nse={};function xl(n,t){var o,i,e;return t?(n>>>=0,(e=0<=n&&n<256)&&(i=Nse[n],i)?i:(o=yt(n,0,!0),e&&(Nse[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=Tse[n],i)?i:(o=yt(n,n<0?-1:0,!1),e&&(Tse[n]=o),o))}Nt.fromInt=xl;function Wo(n,t){if(isNaN(n))return t?Gg:_n;if(t){if(n<0)return Gg;if(n>=Pse)return Lse}else{if(n<=-kse)return Pi;if(n+1>=kse)return Fse}return n<0?Wo(-n,t).neg():yt(n%jh|0,n/jh|0,t)}Nt.fromNumber=Wo;function yt(n,t,o){return new Nt(n,t,o)}Nt.fromBits=yt;var pb=Math.pow;function vU(n,t,o){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(o=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Gg:_n;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return vU(n.substring(1),t,o).neg();for(var e=Wo(pb(o,8)),a=_n,A=0;A>>0:this.low};Ue.toNumber=function(){return this.unsigned?(this.high>>>0)*jh+(this.low>>>0):this.high*jh+(this.low>>>0)};Ue.toString=function(t){if(t=t||10,t<2||36>>0,c=g.toString(t);if(A=s,A.isZero())return c+r;for(;c.length<6;)c="0"+c;r=""+c+r}};Ue.getHighBits=function(){return this.high};Ue.getHighBitsUnsigned=function(){return this.high>>>0};Ue.getLowBits=function(){return this.low};Ue.getLowBitsUnsigned=function(){return this.low>>>0};Ue.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Pi)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,o=31;o>0&&(t&1<>21;return t?this.unsigned?!1:t===-1&&!(this.low===0&&this.high===-2097152):!0};Ue.isZero=function(){return this.high===0&&this.low===0};Ue.eqz=Ue.isZero;Ue.isNegative=function(){return!this.unsigned&&this.high<0};Ue.isPositive=function(){return this.unsigned||this.high>=0};Ue.isOdd=function(){return(this.low&1)===1};Ue.isEven=function(){return(this.low&1)===0};Ue.equals=function(t){return za(t)||(t=Zo(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};Ue.eq=Ue.equals;Ue.notEquals=function(t){return!this.eq(t)};Ue.neq=Ue.notEquals;Ue.ne=Ue.notEquals;Ue.lessThan=function(t){return this.comp(t)<0};Ue.lt=Ue.lessThan;Ue.lessThanOrEqual=function(t){return this.comp(t)<=0};Ue.lte=Ue.lessThanOrEqual;Ue.le=Ue.lessThanOrEqual;Ue.greaterThan=function(t){return this.comp(t)>0};Ue.gt=Ue.greaterThan;Ue.greaterThanOrEqual=function(t){return this.comp(t)>=0};Ue.gte=Ue.greaterThanOrEqual;Ue.ge=Ue.greaterThanOrEqual;Ue.compare=function(t){if(za(t)||(t=Zo(t)),this.eq(t))return 0;var o=this.isNegative(),i=t.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};Ue.comp=Ue.compare;Ue.negate=function(){return!this.unsigned&&this.eq(Pi)?Pi:this.not().add(Yh)};Ue.neg=Ue.negate;Ue.add=function(t){za(t)||(t=Zo(t));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=t.high>>>16,r=t.high&65535,s=t.low>>>16,g=t.low&65535,c=0,I=0,d=0,B=0;return B+=a+g,d+=B>>>16,B&=65535,d+=e+s,I+=d>>>16,d&=65535,I+=i+r,c+=I>>>16,I&=65535,c+=o+A,c&=65535,yt(d<<16|B,c<<16|I,this.unsigned)};Ue.subtract=function(t){return za(t)||(t=Zo(t)),this.add(t.neg())};Ue.sub=Ue.subtract;Ue.multiply=function(t){if(this.isZero())return this;if(za(t)||(t=Zo(t)),Vo){var o=Vo.mul(this.low,this.high,t.low,t.high);return yt(o,Vo.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Gg:_n;if(this.eq(Pi))return t.isOdd()?Pi:_n;if(t.eq(Pi))return this.isOdd()?Pi:_n;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(vse)&&t.lt(vse))return Wo(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,r=t.high>>>16,s=t.high&65535,g=t.low>>>16,c=t.low&65535,I=0,d=0,B=0,f=0;return f+=A*c,B+=f>>>16,f&=65535,B+=a*c,d+=B>>>16,B&=65535,B+=A*g,d+=B>>>16,B&=65535,d+=e*c,I+=d>>>16,d&=65535,d+=a*g,I+=d>>>16,d&=65535,d+=A*s,I+=d>>>16,d&=65535,I+=i*c+e*g+a*s+A*r,I&=65535,yt(B<<16|f,I<<16|d,this.unsigned)};Ue.mul=Ue.multiply;Ue.divide=function(t){if(za(t)||(t=Zo(t)),t.isZero())throw Error("division by zero");if(Vo){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var o=(this.unsigned?Vo.div_u:Vo.div_s)(this.low,this.high,t.low,t.high);return yt(o,Vo.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Gg:_n;var i,e,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Gg;if(t.gt(this.shru(1)))return Gse;a=Gg}else{if(this.eq(Pi)){if(t.eq(Yh)||t.eq(kU))return Pi;if(t.eq(Pi))return Yh;var A=this.shr(1);return i=A.div(t).shl(1),i.eq(_n)?t.isNegative()?Yh:kU:(e=this.sub(t.mul(i)),a=i.add(e.div(t)),a)}else if(t.eq(Pi))return this.unsigned?Gg:_n;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=_n}for(e=this;e.gte(t);){i=Math.max(1,Math.floor(e.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(i)/Math.LN2),s=r<=48?1:pb(2,r-48),g=Wo(i),c=g.mul(t);c.isNegative()||c.gt(e);)i-=s,g=Wo(i,this.unsigned),c=g.mul(t);g.isZero()&&(g=Yh),a=a.add(g),e=e.sub(c)}return a};Ue.div=Ue.divide;Ue.modulo=function(t){if(za(t)||(t=Zo(t)),Vo){var o=(this.unsigned?Vo.rem_u:Vo.rem_s)(this.low,this.high,t.low,t.high);return yt(o,Vo.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};Ue.mod=Ue.modulo;Ue.rem=Ue.modulo;Ue.not=function(){return yt(~this.low,~this.high,this.unsigned)};Ue.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};Ue.clz=Ue.countLeadingZeros;Ue.countTrailingZeros=function(){return this.low?_se(this.low):_se(this.high)+32};Ue.ctz=Ue.countTrailingZeros;Ue.and=function(t){return za(t)||(t=Zo(t)),yt(this.low&t.low,this.high&t.high,this.unsigned)};Ue.or=function(t){return za(t)||(t=Zo(t)),yt(this.low|t.low,this.high|t.high,this.unsigned)};Ue.xor=function(t){return za(t)||(t=Zo(t)),yt(this.low^t.low,this.high^t.high,this.unsigned)};Ue.shiftLeft=function(t){return za(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low<>>32-t,this.unsigned):yt(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):yt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};Ue.shr=Ue.shiftRight;Ue.shiftRightUnsigned=function(t){return za(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?yt(this.high,0,this.unsigned):yt(this.high>>>t-32,0,this.unsigned)};Ue.shru=Ue.shiftRightUnsigned;Ue.shr_u=Ue.shiftRightUnsigned;Ue.rotateLeft=function(t){var o;return za(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.low<>>o,this.high<>>o,this.unsigned)):(t-=32,o=32-t,yt(this.high<>>o,this.low<>>o,this.unsigned))};Ue.rotl=Ue.rotateLeft;Ue.rotateRight=function(t){var o;return za(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,o=32-t,yt(this.low<>>t,this.high<>>t,this.unsigned))};Ue.rotr=Ue.rotateRight;Ue.toSigned=function(){return this.unsigned?yt(this.low,this.high,!1):this};Ue.toUnsigned=function(){return this.unsigned?this:yt(this.low,this.high,!0)};Ue.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};Ue.toBytesLE=function(){var t=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};Ue.toBytesBE=function(){var t=this.high,o=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};Nt.fromBytes=function(t,o,i){return i?Nt.fromBytesLE(t,o):Nt.fromBytesBE(t,o)};Nt.fromBytesLE=function(t,o){return new Nt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,o)};Nt.fromBytesBE=function(t,o){return new Nt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],o)};typeof BigInt=="function"&&(Nt.fromBigInt=function(t,o){var i=Number(BigInt.asIntN(32,t)),e=Number(BigInt.asIntN(32,t>>BigInt(32)));return yt(i,e,o)},Nt.fromValue=function(t,o){return typeof t=="bigint"?Nt.fromBigInt(t,o):Zo(t,o)},Ue.toBigInt=function(){var t=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new kg;return{mutex(t){return n.runExclusive(t)}}},Use=()=>{let n=new Map;return{async mutex(t,o){let i=n.get(t);i||(i={mutex:new kg,refCount:0},n.set(t,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(t)===i&&n.delete(t)}}}};function Hse(n,t,o=10){let i=[],e=!1;return{enqueue:(A,r)=>{if(i.push({type:A,node:r}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&t.isWsOpen();){let{type:c,node:I}=i.shift(),d=n.get(c);if(!d){t.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await d(I).catch(B=>t.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await t.yieldToEventLoop())}e=!1})().catch(g=>t.onUnexpectedError(g,"processing offline nodes"))}}}var Sb=qe(Gr(),1);var tI=qe(Gr(),1);var db=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(t){let o=[],i;if(t.tag==="devices"){_i(t);let e=Ie(t,"device-list"),a=Ie(t,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:r}of e.content){let s=+r.id,g=+r["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(r.is_hosted&&r.is_hosted==="true")})}a?.tag==="key-index-list"&&(i={timestamp:+a.attrs.ts,signedKeyIndex:a?.content,expectedTimestamp:a.attrs.expected_ts?+a.attrs.expected_ts:void 0})}return{deviceList:o,keyIndex:i}}};var Fs=class{withId(t){return this.id=t,this}withLid(t){return this.lid=t,this}withPhone(t){return this.phone=t,this}withUsername(t){return this.username=t,this}withUsernameKey(t){return this.usernameKey=t,this}withType(t){return this.type=t,this}withPersonaId(t){return this.personaId=t,this}};var hb=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(t){return t.phone?{tag:"contact",attrs:{},content:t.phone}:t.username?{tag:"contact",attrs:{username:t.username,...t.usernameKey?{pin:t.usernameKey}:{},...t.lid?{lid:t.lid}:{}}}:t.type?{tag:"contact",attrs:{type:t.type}}:{tag:"contact",attrs:{}}}parser(t){return t.tag==="contact"?(_i(t),t?.attrs?.type==="in"):!1}};var Eb=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="status"){_i(t);let o=t?.content?.toString()??null,i=new Date(+(t?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):t.attrs?.code&&+t.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var Cb=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="disappearing_mode"){_i(t);let o=+t?.attrs.duration,i=new Date(+(t?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var ub=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(t){return null}parser(t){return t.tag==="username"?(_i(t),typeof t.content=="string"?t.content:null):null}};var Bb=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(t){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:t.personaId}}]}}parser(t){let o=Ie(t,"bot"),i=Ie(o,"profile"),e=Ie(i,"commands"),a=Ie(i,"prompts"),A=[],r=[];for(let s of PA(e,"command"))A.push({name:jA(s,"name"),description:jA(s,"description")});for(let s of PA(a,"prompt"))r.push(`${jA(s,"emoji")} ${jA(s,"text")}`);return{isDefault:!!Ie(i,"default"),jid:t.attrs.jid,name:jA(i,"name"),attributes:jA(i,"attributes"),description:jA(i,"description"),category:jA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:jA(e,"description"),commands:A,prompts:r}}};var fb=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(t){return t.lid?{tag:"lid",attrs:{jid:t.lid}}:null}parser(t){return t.tag==="lid"?t.attrs.val:null}};var Ls=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(t){return this.mode=t,this}withContext(t){return this.context=t,this}withUser(t){return this.users.push(t),this}parseUSyncQueryResult(t){if(t?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=Ie(t,"usync"),a=e?Ie(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,r)=>{let s=r?.attrs.jid;if(s){let g=Array.isArray(r?.content)?Object.fromEntries(r.content.map(c=>{let I=c.tag,d=o[I];return d?[I,d(c)]:[I,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new db),this}withContactProtocol(){return this.protocols.push(new hb),this}withStatusProtocol(){return this.protocols.push(new Eb),this}withDisappearingModeProtocol(){return this.protocols.push(new Cb),this}withBotProfileProtocol(){return this.protocols.push(new Bb),this}withLIDProtocol(){return this.protocols.push(new fb),this}withUsernameProtocol(){return this.protocols.push(new ub),this}};var jr=qe(Gr(),1);import{randomBytes as GU}from"crypto";import{URL as YVe}from"url";import{promisify as jVe}from"util";var Qb=class{constructor(t={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,t)}};import{EventEmitter as KVe}from"events";var yb=class extends KVe{constructor(t,o){super(),this.url=t,this.config=o,this.setMaxListeners(0)}};var mb=class extends yb{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===wo.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===wo.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===wo.CLOSING}get isConnecting(){return this.socket?.readyState===wo.CONNECTING}connect(){if(this.socket)return;this.socket=new wo(this.url,{origin:KB,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let t=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of t)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let t=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await t,this.socket=null}send(t,o){return this.socket?.send(t,o),!!this.socket}};var PU=qe(Gr(),1);var xVe=(n,t,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:OA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:t},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),cf=async(n,t,o,i,e)=>{let a=await xVe(n,t,i,e),A=Ie(a,"result");if(A?.content){let s=JSON.parse(A.content.toString());if(s.errors&&s.errors.length>0){let c=s.errors.map(B=>B.message||"Unknown error").join(", "),I=s.errors[0],d=I.extensions?.error_code||400;throw new PU.Boom(`GraphQL server error: ${c}`,{statusCode:d,data:I})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let r=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new PU.Boom(`Failed to ${r}, unexpected response structure.`,{statusCode:400,data:a})};var Kse=n=>{let{waWebSocketUrl:t,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:r,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:I}=n,d=new Qb,B=0,f=V9(),Q=()=>`${f}${se++}`;r&&i.warn({},"\u26A0\uFE0F The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version."),a[1].toLocaleLowerCase().includes("android")&&i.warn("\u26A0\uFE0F Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk."),nf.map(le=>n.shouldSyncHistoryMessage({syncType:le})).filter(le=>le===!1).length===nf.length&&i.warn("\u26A0\uFE0F DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS");let m=typeof t=="string"?new YVe(t):t;if(n.mobile||m.protocol==="tcp:")throw new jr.Boom("Mobile API is not supported anymore",{statusCode:Zt.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let _=ur.generateKeyPair(),T=Bie({keyPair:_,NOISE_HEADER:Qse,logger:i,routingInfo:A?.creds?.routingInfo}),R=new mb(m,n);R.connect();let H=jVe(R.send),j=async le=>{if(!R.isOpen)throw new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed});let Qe=T.encodeFrame(le);await Ud(o,async(be,oA)=>{try{await H.call(R,Qe),be()}catch(lA){oA(lA)}})},F=le=>{i.level==="trace"&&i.trace({xml:Bn(le),msg:"xml send"});let Qe=p9(le);return j(Qe)},q=async(le,Qe=s)=>{let be,oA;try{return await Ud(Qe,(FA,Ut)=>(be=st=>{FA(st)},oA=st=>{Ut(st||new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed}))},R.on(`TAG:${le}`,be),R.on("close",oA),R.on("error",oA),()=>Ut(new jr.Boom("Query Cancelled"))))}catch(lA){if(lA instanceof jr.Boom&&lA.output?.statusCode===Zt.timedOut){i?.warn?.({msgId:le},"timed out waiting for message");return}throw lA}finally{be&&R.off(`TAG:${le}`,be),oA&&(R.off("close",oA),R.off("error",oA))}},J=async(le,Qe)=>{le.attrs.id||(le.attrs.id=Q());let be=le.attrs.id,oA=await Ud(Qe,async(lA,FA)=>{let Ut=q(be,Qe).catch(FA);F(le).then(async()=>lA(await Ut)).catch(FA)});return oA&&"tag"in oA&&_i(oA),oA},x=async()=>{let le=await J({tag:"iq",attrs:{to:OA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!Ie(le,"digest"))throw await Ze(),new Error("encrypt/get digest returned no digest node")},P=async()=>{let le=(V.signedPreKey.keyId||0)+1,Qe=await QD(V.signedIdentityKey,le);await J({tag:"iq",attrs:{to:OA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[JB(Qe)]}]}),k.emit("creds.update",{signedPreKey:Qe})},z=async le=>{if(le.protocols.length===0)throw new jr.Boom("USyncQuery must have at least one protocol");let be=le.users.map(st=>({tag:"user",attrs:{jid:st.phone?void 0:st.id},content:le.protocols.map(fr=>fr.getUserElement(st)).filter(fr=>fr!==null)})),oA={tag:"list",attrs:{},content:be},lA={tag:"query",attrs:{},content:le.protocols.map(st=>st.getQueryElement())},FA={tag:"iq",attrs:{to:OA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:le.context,mode:le.mode,sid:Q(),last:"true",index:"0"},content:[lA,oA]}]},Ut=await J(FA);return le.parseUSyncQueryResult(Ut)},U=async(...le)=>{let Qe=new Ls,be=!1;for(let lA of le)if(qA(lA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{be||(be=!0,Qe=Qe.withContactProtocol());let FA=`+${lA.replace("+","").split("@")[0]?.split(":")[0]}`;Qe.withUser(new Fs().withPhone(FA))}if(Qe.users.length===0)return[];let oA=await z(Qe);if(oA)return oA.list.filter(lA=>!!lA.contact).map(({contact:lA,id:FA})=>({jid:FA,exists:lA}))},N=async le=>{let Qe=new Ls().withLIDProtocol().withContext("background");for(let oA of le)if(qA(oA)){i?.warn("LID user found in LID fetch call");continue}else Qe.withUser(new Fs().withId(oA));if(Qe.users.length===0)return[];let be=await z(Qe);return be?be.list.filter(oA=>!!oA.lid).map(({lid:oA,id:lA})=>({pn:lA,lid:oA})):[]},k=eoe(i),{creds:V}=A,ee=jie(A.keys,i,g),ie=I({creds:V,keys:ee},i,N),Te,se=1,Ne,fe,De=!1,Ke=[],rA=(le,Qe)=>{i.error({err:le},`unexpected error in '${Qe}'`)},ve=async le=>{if(!R.isOpen)throw new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed});let Qe,be,oA=Ud(o,(lA,FA)=>{Qe=lA,be=FU(FA),R.on("frame",Qe),R.on("close",be),R.on("error",be)}).finally(()=>{R.off("frame",Qe),R.off("close",be),R.off("error",be)});return le&&j(le).catch(be),oA},iA=async()=>{let le={clientHello:{ephemeral:_.public}};le=oe.HandshakeMessage.fromObject(le),i.info({browser:a,helloMsg:le},"connected to WA");let Qe=oe.HandshakeMessage.encode(le).finish(),be=await ve(Qe),oA=oe.HandshakeMessage.decode(be);i.trace({handshake:oA},"handshake recv from WA");let lA=T.processHandshake(oA,V.noiseKey),FA;V.me?(FA=Iie(V.me.id,n),i.info({node:FA},"logging in...")):(FA=lie(V,n),i.info({node:FA},"not logged in, attempting registration..."));let Ut=T.encrypt(oe.ClientPayload.encode(FA).finish());await j(oe.HandshakeMessage.encode({clientFinish:{static:lA,payload:Ut}}).finish()),await T.finishInit(),We()},Ce=async()=>{let le=await J({tag:"iq",attrs:{id:Q(),xmlns:"encrypt",type:"get",to:OA},content:[{tag:"count",attrs:{}}]});return+Ie(le,"count").attrs.value},he=null,Ze=async(le=sf)=>{if(he){i.debug("Pre-key upload already in progress, waiting for completion"),await he;return}let Qe=async be=>{i.info({count:le,retryCount:be},"uploading pre-keys");let oA=await ee.transaction(async()=>{i.debug({requestedCount:le},"generating pre-keys with requested count");let{update:lA,node:FA}=await sie({creds:V,keys:ee},le);return k.emit("creds.update",lA),FA},V?.me?.id||"upload-pre-keys");try{await J(oA),i.info({count:le},"uploaded pre-keys successfully")}catch(lA){if(i.error({uploadError:lA.toString(),count:le},"Failed to upload pre-keys to server"),be<3){let FA=Math.min(1e3*Math.pow(2,be),1e4);return i.info(`Retrying pre-key upload in ${FA}ms`),await new Promise(Ut=>setTimeout(Ut,FA)),Qe(be+1)}throw lA}};he=Promise.race([Qe(0),new Promise((be,oA)=>setTimeout(()=>oA(new jr.Boom("Pre-key upload timeout",{statusCode:408})),Dse))]);try{await he}finally{he=null}},je=async()=>{let le=V.nextPreKeyId-1;return le<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await ee.get("pre-key",[le.toString()]))[le.toString()],currentPreKeyId:le}},Oe=async()=>{try{let le=0,Qe=await Ce();Qe===0?le=Sse:le=sf;let{exists:be,currentPreKeyId:oA}=await je();i.info(`${Qe} pre-keys found on server`),i.info(`Current prekey ID: ${oA}, exists in storage: ${be}`);let lA=Qe<=le,FA=!be&&oA>0;if(lA||FA){let st=[];lA&&st.push(`server count low (${Qe})`),FA&&st.push(`current prekey ${oA} missing from storage`),i.info(`Uploading PreKeys due to: ${st.join(", ")}`),await Ze(le)}else i.info(`PreKey validation passed - Server: ${Qe}, Current prekey ${oA} exists`)}catch(le){i.error({error:le},"Failed to check/upload pre-keys during initialization")}},hA=async le=>{await T.decodeFrame(le,Qe=>{Te=new Date;let be=!1;if(be=R.emit("frame",Qe),!(Qe instanceof Uint8Array)){let oA=Qe.attrs.id;i.level==="trace"&&i.trace({xml:Bn(Qe),msg:"recv xml"}),be=R.emit(`${use}${oA}`,Qe)||be;let lA=Qe.tag,FA=Qe.attrs||{},Ut=Array.isArray(Qe.content)?Qe.content[0]?.tag:"";for(let st of Object.keys(FA))be=R.emit(`${xh}${lA},${st}:${FA[st]},${Ut}`,Qe)||be,be=R.emit(`${xh}${lA},${st}:${FA[st]}`,Qe)||be,be=R.emit(`${xh}${lA},${st}`,Qe)||be;be=R.emit(`${xh}${lA},,${Ut}`,Qe)||be,be=R.emit(`${xh}${lA}`,Qe)||be,!be&&i.level==="debug"&&i.debug({unhandled:!0,msgId:oA,fromMe:!1,frame:Qe},"communication recv")}})},dA=async le=>{if(De){i.trace({trace:le?.stack},"connection already closed");return}if(De=!0,i.info({trace:le?.stack},le?"connection errored":"connection closed"),clearInterval(Ne),clearTimeout(fe),R.removeAllListeners("close"),R.removeAllListeners("open"),R.removeAllListeners("message"),ie.close?.(),!R.isClosed&&!R.isClosing)try{await R.close()}catch{}for(let Qe of Ke)try{await Qe(le)}catch(be){i.error({err:be},"error in socket end handler")}k.emit("connection.update",{connection:"close",lastDisconnect:{error:le,date:new Date}}),k.removeAllListeners("connection.update"),k.destroy()},aA=async()=>{if(R.isOpen)return;if(R.isClosed||R.isClosing)throw new jr.Boom("Connection Closed",{statusCode:Zt.connectionClosed});let le,Qe;await new Promise((be,oA)=>{le=()=>be(void 0),Qe=FU(oA),R.on("open",le),R.on("close",Qe),R.on("error",Qe)}).finally(()=>{R.off("open",le),R.off("close",Qe),R.off("error",Qe)})},We=()=>Ne=setInterval(()=>{Te||(Te=new Date),Date.now()-Te.getTime()>e+5e3?dA(new jr.Boom("Connection was lost",{statusCode:Zt.connectionLost})):R.isOpen?J({tag:"iq",attrs:{id:Q(),to:OA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(Qe=>{i.error({trace:Qe.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),bA=le=>J({tag:"iq",attrs:{to:OA,xmlns:"passive",type:"set"},content:[{tag:le,attrs:{}}]}),Be=async le=>{let Qe=A.creds.me?.id;Qe&&await F({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:Qe,reason:"user_initiated"}}]}),dA(new jr.Boom(le||"Intentional Logout",{statusCode:Zt.loggedOut}))},Re=async(le,Qe)=>{let be=Qe??eX(GU(5));if(Qe&&Qe?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=be,A.creds.me={id:Er(le,"s.whatsapp.net"),name:"~"},k.emit("creds.update",A.creds),await F({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:A.creds.me.id,stage:"companion_hello",should_show_push_notification:"true"},content:[{tag:"link_code_pairing_wrapped_companion_ephemeral_pub",attrs:{},content:await Le()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:F2(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function Le(){let le=GU(32),Qe=GU(16),be=await yD(A.creds.pairingCode,le),oA=G9(A.creds.pairingEphemeralKeyPair.public,be,Qe);return Buffer.concat([le,Qe,oA])}let MA=le=>J({tag:"iq",attrs:{to:OA,id:Q(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:le}]});R.on("message",hA),R.on("open",async()=>{try{await iA()}catch(le){i.error({err:le},"error in validating connection"),dA(le)}}),R.on("error",FU(dA)),R.on("close",()=>void dA(new jr.Boom("Connection Terminated",{statusCode:Zt.connectionClosed}))),R.on("CB:xmlstreamend",()=>void dA(new jr.Boom("Connection Terminated by Server",{statusCode:Zt.connectionClosed}))),R.on("CB:iq,type:set,pair-device",async le=>{let Qe={tag:"iq",attrs:{to:OA,type:"result",id:le.attrs.id}};await F(Qe);let be=Ie(le,"pair-device"),oA=PA(be,"ref"),lA=Buffer.from(V.noiseKey.public).toString("base64"),FA=Buffer.from(V.signedIdentityKey.public).toString("base64"),Ut=V.advSecretKey,st=c||6e4,fr=()=>{if(!R.isOpen)return;let Ar=oA.shift();if(!Ar){dA(new jr.Boom("QR refs attempts ended",{statusCode:Zt.timedOut}));return}let oo=Ar.content.toString("utf-8"),Gi=roe(oo,lA,FA,Ut,a);k.emit("connection.update",{qr:Gi}),fe=setTimeout(fr,st),st=c||2e4};fr()}),R.on("CB:iq,,pair-success",async le=>{i.debug("pair success recv");try{_A(le);let{reply:Qe,creds:be}=pie(le,V);i.info({me:be.me,platform:be.platform},"pairing configured successfully, expect to restart the connection..."),k.emit("creds.update",be),k.emit("connection.update",{isNewLogin:!0,qr:void 0}),await F(Qe),DA()}catch(Qe){i.info({trace:Qe.stack},"error in pairing"),dA(Qe)}}),R.on("CB:success",async le=>{try{_A(le),await Oe(),await bA("active");try{await x()}catch(Qe){i.warn({e:Qe},"failed to run digest after login")}}catch(Qe){i.warn({err:Qe},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(fe),k.emit("creds.update",{me:{...A.creds.me,lid:le.attrs.lid}}),k.emit("connection.update",{connection:"open"}),DA(),le.attrs.lid&&A.creds.me?.id){let Qe=le.attrs.lid;process.nextTick(async()=>{try{let be=A.creds.me.id;await ie.lidMapping.storeLIDPNMappings([{lid:Qe,pn:be}]);let{user:oA,device:lA}=yA(be);await A.keys.set({"device-list":{[oA]:[lA?.toString()||"0"]}}),await ie.migrateSession(be,Qe),i.info({myPN:be,myLID:Qe},"Own LID session created successfully")}catch(be){i.error({error:be,lid:Qe},"Failed to create own LID session")}})}}),R.on("CB:stream:error",le=>{let[Qe]=ls(le);i.error({reasonNode:Qe,fullErrorNode:le},"stream errored out");let{reason:be,statusCode:oA}=Z9(le);dA(new jr.Boom(`Stream Errored (${be})`,{statusCode:oA,data:Qe||le}))}),R.on("CB:failure",le=>{let Qe=+(le.attrs.reason||500);dA(new jr.Boom("Connection Failure",{statusCode:Qe,data:le.attrs}))}),R.on("CB:ib,,downgrade_webclient",()=>{dA(new jr.Boom("Multi-device beta not joined",{statusCode:Zt.multideviceMismatch}))}),R.on("CB:ib,,offline_preview",async le=>{i.info("offline preview received",JSON.stringify(le)),await F({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),R.on("CB:ib,,edge_routing",le=>{let Qe=Ie(le,"edge_routing"),be=Ie(Qe,"routing_info");be?.content&&(A.creds.routingInfo=Buffer.from(be?.content),k.emit("creds.update",A.creds))});let He=!1;process.nextTick(()=>{V.me?.id&&(k.buffer(),He=!0),k.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),R.on("CB:ib,,offline",le=>{let be=+(Ie(le,"offline")?.attrs.count||0);i.info(`handled ${be} offline messages/notifications`),He&&(k.flush(),i.trace("flushed events for initial buffer")),k.emit("connection.update",{receivedPendingNotifications:!0})}),k.on("creds.update",le=>{let Qe=le.me?.name;V.me?.name!==Qe&&(i.debug({name:Qe},"updated pushName"),F({tag:"presence",attrs:{name:Qe}}).catch(be=>{i.warn({trace:be.stack},"error in sending presence update on name change")})),Object.assign(V,le)});let _A=({attrs:le})=>{let Qe=le?.t;if(!Qe)return;let be=Number(Qe);if(Number.isNaN(be)||be<=0)return;let oA=Date.now();B=be*1e3-oA,i.debug({offset:B},"calculated server time offset")},at=()=>{let le=3*TU.Day;return((Date.now()+B+le)%TU.Week).toString()},DA=async()=>{if(!R.isOpen)return;let le={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:at()}}]};try{await F(le)}catch(Qe){i.debug({error:Qe},"failed to send unified_session telemetry")}},lt=le=>{Ke.push(le)},Ir=async()=>{let le=await cf({},ia.REACHOUT_TIMELOCK,Ca.xwa2_fetch_account_reachout_timelock,J,Q),Qe={isActive:!!le?.is_active,timeEnforcementEnds:le?.time_enforcement_ends&&le?.time_enforcement_ends!=="0"?new Date(parseInt(le.time_enforcement_ends,10)*1e3):void 0,enforcementType:le?.enforcement_type??Dc.DEFAULT};return k.emit("connection.update",{reachoutTimeLock:Qe}),Qe},UA=async()=>cf({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},ia.MESSAGE_CAPPING_INFO,Ca.xwa2_message_capping_info,J,Q);return{type:"md",ws:R,ev:k,authState:{creds:V,keys:ee},signalRepository:ie,get user(){return A.creds.me},generateMessageTag:Q,query:J,waitForMessage:q,waitForSocketOpen:aA,sendRawMessage:j,sendNode:F,logout:Be,end:dA,registerSocketEndHandler:lt,onUnexpectedError:rA,uploadPreKeys:Ze,uploadPreKeysToServerIfRequired:Oe,digestKeyBundle:x,rotateSignedPreKey:P,requestPairingCode:Re,updateServerTimeOffset:_A,sendUnifiedSession:DA,wamBuffer:d,waitForConnectionUpdate:z9(k),sendWAMBuffer:MA,executeUSyncQuery:z,onWhatsApp:U,fetchAccountReachoutTimelock:Ir,fetchNewChatMessageCap:UA}};function FU(n){return t=>{n(new jr.Boom(`WebSocket Error (${t?.message})`,{statusCode:$9(t),data:t}))}}var JVe=(n,t)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return t?.length&&(o.content=t),[o]},xse=n=>{let{logger:t,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:r}=n,s=Kse(n),{ev:g,ws:c,authState:I,generateMessageTag:d,sendNode:B,query:f,signalRepository:Q,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:_}=s,T=Q.lidMapping.getLIDForPN.bind(Q.lidMapping),R,H={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},j=aa.Connecting,F=Fg(),q=Fg(),J=Fg(),x=Fg(),P,z={initialBootstrapComplete:!1,recentSyncComplete:!1},U,N=new Set,k=n.placeholderResendCache||new Rg({stdTTL:$c.MSG_RETRY,useClones:!1}),V=async W=>{let{[W]:X}=await I.keys.get("app-state-sync-key",[W]);return X},ee=async(W=!1)=>{if(!R||W){let{content:X}=await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"get"},content:[{tag:"privacy",attrs:{}}]});R=_G(X?.[0],"category")}return R},ie=async(W,X)=>{await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:W,value:X}}]}]})},Te=async W=>{await ie("messages",W)},se=async W=>{await ie("calladd",W)},Ne=async W=>{await ie("last",W)},fe=async W=>{await ie("online",W)},De=async W=>{await ie("profile",W)},Ke=async W=>{await ie("status",W)},rA=async W=>{await ie("readreceipts",W)},ve=async W=>{await ie("groupadd",W)},iA=async W=>{await f({tag:"iq",attrs:{xmlns:"disappearing_mode",to:OA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:W.toString()}}]})},Ce=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"bot",to:OA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),X=Ie(W,"bot"),re=[];for(let ne of PA(X,"section"))if(ne.attrs.type==="all")for(let Se of PA(ne,"bot"))re.push({jid:Se.attrs.jid,personaId:Se.attrs.persona_id});return re},he=async(...W)=>{let X=new Ls().withStatusProtocol();for(let ne of W)X.withUser(new Fs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},Ze=async(...W)=>{let X=new Ls().withDisappearingModeProtocol();for(let ne of W)X.withUser(new Fs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},je=async(W,X,re)=>{let ne;if(!W)throw new tI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?ne=uA(W):ne=void 0;let{img:Se}=await DO(X,re);await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...ne?{target:ne}:{}},content:[{tag:"picture",attrs:{type:"image"},content:Se}]})},Oe=async W=>{let X;if(!W)throw new tI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?X=uA(W):X=void 0,await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...X?{target:X}:{}}})},hA=async W=>{await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(W,"utf-8")}]})},dA=async W=>{await UA({pushNameSetting:W},"")},aA=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"get"}}),X=Ie(W,"list");return PA(X,"item").map(re=>re.attrs.jid)},We=async(W,X)=>{let re=uA(W),ne,Se;if(qA(re)||oa(re)){if(ne=re,X==="block"){let de=await Q.lidMapping.getPNForLID(re);if(!de)throw new tI.Boom(`Unable to resolve PN JID for LID: ${W}`,{statusCode:400});Se=uA(de)}}else if(bt(re)||Cr(re)){let de=await Q.lidMapping.getLIDForPN(re);if(!de)throw new tI.Boom(`Unable to resolve LID for PN JID: ${W}`,{statusCode:400});ne=de,X==="block"&&(Se=uA(re))}else throw new tI.Boom(`Invalid jid: ${W}`,{statusCode:400});let Ee={action:X,jid:ne};if(X==="block"){if(!Se)throw new tI.Boom(`pn_jid required for block: ${W}`,{statusCode:400});Ee.pn_jid=Se}await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"set"},content:[{tag:"item",attrs:Ee}]})},bA=async W=>{let X=await f({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:W}}]}]}),re=Ie(X,"business_profile"),ne=Ie(re,"profile");if(ne){let Se=Ie(ne,"address"),Ee=Ie(ne,"description"),de=Ie(ne,"website"),ye=Ie(ne,"email"),Je=Ie(Ie(ne,"categories"),"category"),IA=Ie(ne,"business_hours"),QA=IA?PA(IA,"business_hours_config"):void 0,XA=de?.content?.toString();return{wid:ne.attrs?.jid,address:Se?.content?.toString(),description:Ee?.content?.toString()||"",website:XA?[XA]:[],email:ye?.content?.toString(),category:Je?.content?.toString(),business_hours:{timezone:IA?.attrs?.timezone,business_config:QA?.map(({attrs:vA})=>vA)}}}},Be=async(W,X)=>{t.info({fromTimestamp:X},"clean dirty bits "+W),await B({tag:"iq",attrs:{to:OA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:d()},content:[{tag:"clean",attrs:{type:W,...X?{timestamp:X.toString()}:null}}]})},Re=W=>({onMutation(X){Pie(X,g,I.creds.me,W?{accountSettings:I.creds.accountSettings}:void 0,t)}}),Le=g.createBufferedFunction(async(W,X)=>{let re=new Map,ne=async ye=>{if(re.has(ye))return re.get(ye)??void 0;let Je=await V(ye);return re.set(ye,Je??null),Je},Se={},Ee={};await I.keys.transaction(async()=>{let ye=new Set(W),Je={},IA=new Set;for(;ye.size;){let QA={},XA=[];for(let $A of ye){let AA=(await I.keys.get("app-state-sync-version",[$A]))[$A];AA?(AA=p2(AA),typeof Se[$A]>"u"&&(Se[$A]=AA.version)):AA=TO(),QA[$A]=AA;let et=IA.has($A);et&&IA.delete($A),t.info(`resyncing ${$A} from v${AA.version}${et?" (forcing snapshot)":""}`),XA.push({tag:"collection",attrs:{name:$A,version:AA.version.toString(),return_snapshot:(et||!AA.version).toString()}})}let vA=await f({tag:"iq",attrs:{to:OA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:XA}]}),YA=await Nie(vA,n?.options);for(let $A in YA){let Pe=$A,{patches:AA,hasMorePatches:et,snapshot:qr}=YA[Pe];try{if(qr){let{state:tr,mutationMap:no}=await kie(Pe,qr,ne,Se[Pe],e.snapshot,t);QA[Pe]=tr,Object.assign(Ee,no),t.info(`restored state of ${Pe} from snapshot to v${tr.version} with mutations`),await I.keys.set({"app-state-sync-version":{[Pe]:tr}})}if(AA.length){let{state:tr,mutationMap:no}=await h2(Pe,AA,QA[Pe],ne,n.options,Se[Pe],t,e.patch);await I.keys.set({"app-state-sync-version":{[Pe]:tr}}),t.info(`synced ${Pe} to v${tr.version}`),Se[Pe]=tr.version,Object.assign(Ee,no)}et?t.info(`${Pe} has more patches...`):ye.delete(Pe)}catch(tr){Je[Pe]=(Je[Pe]||0)+1;let no={name:Pe,attempt:Je[Pe],version:QA[Pe].version,statusCode:tr.output?.statusCode,errorType:tr.name,error:tr.stack};VB(tr)&&Je[Pe]>=d2?(t.warn(no,`${Pe} blocked on missing key from v${QA[Pe].version}, parking after ${Je[Pe]} attempts`),N.add(Pe),ye.delete(Pe)):VB(tr)?(t.info(no,`${Pe} blocked on missing key from v${QA[Pe].version}, retrying with snapshot`),IA.add(Pe)):Mie(tr,Je[Pe])?(t.warn(no,`failed to sync ${Pe} from v${QA[Pe].version}, giving up`),ye.delete(Pe)):(t.info(no,`failed to sync ${Pe} from v${QA[Pe].version}, forcing snapshot retry`),IA.add(Pe))}}}},I?.creds?.me?.id||"resync-app-state");let{onMutation:de}=Re(X);for(let ye in Ee)de(Ee[ye])}),MA=async(W,X="preview",re)=>{let ne=uA(W),Se=bt(ne)||qA(ne),Ee=I.creds.me,de=Ee&&(ne===uA(Ee.id)||Ee.lid&&ne===uA(Ee.lid)),ye;H.profilePicPrivacyToken&&Se&&!de&&(ye=await N2({authState:I,jid:ne,getLIDForPN:T})),W=uA(W);let Je=await f({tag:"iq",attrs:{target:W,to:OA,type:"get",xmlns:"w:profile:picture"},content:JVe(X,ye)},re);return Ie(Je,"picture")?.attrs?.url},He=async(W,X,re)=>{let ne=await f({tag:"call",attrs:{id:d(),to:"@call"},content:[{tag:"link_create",attrs:{media:W},content:X?[{tag:"event",attrs:{start_time:String(X.startTime)}}]:void 0}]},re);return Ie(ne,"link_create")?.attrs?.token},_A=async(W,X)=>{let re=I.creds.me,ne=W==="available";if(ne||W==="unavailable"){if(!re.name){t.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:ne}),ne&&m(),await B({tag:"presence",attrs:{name:re.name.replace(/@/g,""),type:W}})}else{let{server:Se}=yA(X);await B({tag:"chatstate",attrs:{from:Se==="lid"?re.lid:re.id,to:X},content:[{tag:W==="recording"?"composing":W,attrs:W==="recording"?{media:"audio"}:{}}]})}},at=async W=>{let X=uA(W),ne=bt(X)||qA(X)?await N2({authState:I,jid:X,getLIDForPN:T}):void 0;return B({tag:"presence",attrs:{to:W,id:d(),type:"subscribe"},content:ne})},DA=({tag:W,attrs:X,content:re})=>{let ne,Se=X.from,Ee=X.participant||X.from;if(!(a(Se)&&Se!==OA)){if(W==="presence")ne={lastKnownPresence:X.type==="unavailable"?"unavailable":"available",lastSeen:X.last&&X.last!=="deny"?+X.last:void 0,groupOnlineCount:X.count?+X.count:void 0};else if(Array.isArray(re)){let[de]=re,ye=de.tag;ye==="paused"&&(ye="available"),de.attrs?.media==="audio"&&(ye="recording"),ne={lastKnownPresence:ye}}else t.error({tag:W,attrs:X,content:re},"recv invalid presence node");ne&&g.emit("presence.update",{id:Se,presences:{[Ee]:ne}})}},lt=async W=>{let X=W.type,re=I.creds.myAppStateKeyId;if(!re)throw new tI.Boom("App state key not present!",{statusCode:400});let ne,Se;if(await J.mutex(async()=>{await I.keys.transaction(async()=>{t.debug({patch:W},"applying app patch"),await Le([X],!1);let{[X]:Ee}=await I.keys.get("app-state-sync-version",[X]);ne=Ee?p2(Ee):TO(),Se=await _ie(W,re,ne,V);let{patch:de,state:ye}=Se,Je={tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:X,version:(ye.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:oe.SyncdPatch.encode(de).finish()}]}]}]};await f(Je),await I.keys.set({"app-state-sync-version":{[X]:ye}})},I?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:Ee}=Re(!1),{mutationMap:de}=await h2(X,[{...Se.patch,version:{version:Se.state.version}}],ne,V,n.options,void 0,t);for(let ye in de)Ee(de[ye])}},Ir=async()=>{let W=await f({tag:"iq",attrs:{to:OA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...I?.creds?.lastPropHash?{hash:I.creds.lastPropHash}:{}}}]}),X=Ie(W,"props"),re={};X&&(X.attrs?.hash&&(I.creds.lastPropHash=X?.attrs?.hash,g.emit("creds.update",I.creds)),re=_G(X,"prop"));let ne=re[10518]??re.privacy_token_sending_on_all_1_on_1_messages;ne!==void 0&&(H.privacyTokenOn1to1=ne==="true"||ne==="1");let Se=re[9666]??re.profile_scraping_privacy_token_in_photo_iq;Se!==void 0&&(H.profilePicPrivacyToken=Se==="true"||Se==="1");let Ee=re[14303]??re.lid_trusted_token_issue_to_lid;return Ee!==void 0&&(H.lidTrustedTokenIssueToLid=Ee==="true"||Ee==="1"),t.debug({serverProps:H},"fetched props"),re},UA=(W,X)=>{let re=vie(W,X);return lt(re)},le=W=>UA({disableLinkPreviews:{isPreviewsDisabled:W}},""),Qe=(W,X,re)=>UA({star:{messages:X,star:re}},W),be=(W,X)=>UA({contact:X},W),oA=W=>UA({contact:null},W),lA=(W,X)=>UA({addLabel:{...X}},W),FA=(W,X)=>UA({addChatLabel:{labelId:X}},W),Ut=(W,X)=>UA({removeChatLabel:{labelId:X}},W),st=(W,X,re)=>UA({addMessageLabel:{messageId:X,labelId:re}},W),fr=(W,X,re)=>UA({removeMessageLabel:{messageId:X,labelId:re}},W),Ar=W=>UA({quickReply:W},""),oo=W=>UA({quickReply:{timestamp:W,deleted:!0}},""),Gi=async()=>{await Promise.all([Ir(),aA(),ee()])},Ae=g.createBufferedFunction(async(W,X)=>{if(g.emit("messages.upsert",{messages:[W],type:X}),W.pushName){let Ee=W.key.fromMe?I.creds.me.id:W.key.participant||W.key.remoteJid;Ee=uA(Ee),W.key.fromMe||g.emit("contacts.update",[{id:Ee,notify:W.pushName,verifiedName:W.verifiedBizName}]),W.key.fromMe&&W.pushName&&I.creds.me?.name!==W.pushName&&g.emit("creds.update",{me:{...I.creds.me,name:W.pushName}})}let re=_O(W.message),ne=re?A(re)&&nf.includes(re.syncType):!1;if(re&&ne){let Ee=re.syncType;Ee===oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!z.initialBootstrapComplete&&(z.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===oe.HistorySync.HistorySyncType.RECENT&&re.progress===100&&!z.recentSyncComplete&&(z.recentSyncComplete=!0,clearTimeout(U),U=void 0,g.emit("messaging-history.status",{syncType:Ee,status:"complete",explicit:!0})),Ee===oe.HistorySync.HistorySyncType.RECENT&&!z.recentSyncComplete&&(clearTimeout(U),U=setTimeout(()=>{z.recentSyncComplete||(z.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:oe.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),U=void 0},mse))}re&&j===aa.AwaitingInitialSync&&(P&&(clearTimeout(P),P=void 0),ne?(j=aa.Syncing,t.info("Transitioned to Syncing state")):(j=aa.Online,t.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let Se=async()=>{if(j===aa.Syncing){N.clear(),t.info("Doing app state sync"),await Le(r9,!0),j=aa.Online,t.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let Ee=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:Ee})}};await Promise.all([(async()=>{ne&&await Se()})(),$ie(W,{signalRepository:Q,shouldProcessHistoryMsg:ne,placeholderResendCache:k,ev:g,creds:I.creds,keyStore:I.keys,logger:t,options:n.options,getMessage:r})]),W.message?.protocolMessage?.appStateSyncKeyShare&&j===aa.Syncing&&(t.info("App state sync key arrived, triggering app state sync"),await Se())});return c.on("CB:presence",DA),c.on("CB:chatstate",DA),c.on("CB:ib,,dirty",async W=>{let{attrs:X}=Ie(W,"dirty");switch(X.type){case"account_sync":if(X.timestamp){let{lastAccountSyncTimestamp:ne}=I.creds;ne&&await Be("account_sync",ne),ne=+X.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:ne})}break;case"groups":break;default:t.info({node:W},"received unknown sync");break}}),g.on("connection.update",({connection:W,receivedPendingNotifications:X})=>{if(W==="close"&&(N.clear(),clearTimeout(U),U=void 0),W==="open"&&(i&&Gi().catch(ne=>y(ne,"init queries")),_A(o?"available":"unavailable").catch(ne=>y(ne,"presence update requests"))),!X||j!==aa.Connecting)return;if(z.initialBootstrapComplete=!1,z.recentSyncComplete=!1,clearTimeout(U),U=void 0,j=aa.AwaitingInitialSync,t.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(oe.Message.HistorySyncNotification.create({syncType:oe.HistorySync.HistorySyncType.RECENT}))){t.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),j=aa.Online,setTimeout(()=>g.flush(),0);return}if(I.creds.accountSyncCounter>0){t.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),j=aa.Online,setTimeout(()=>g.flush(),0);return}t.info("First connection, awaiting history sync notification with a 20s timeout."),P&&clearTimeout(P),P=setTimeout(()=>{if(j===aa.AwaitingInitialSync){t.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),j=aa.Online,g.flush();let ne=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:ne})}},2e4)}),g.on("creds.update",({myAppStateKeyId:W})=>{if(!W||N.size===0)return;if(j===aa.Syncing){N.clear();return}let X=[...N];N.clear(),t.info({collections:X},"app state sync key arrived, re-syncing blocked collections"),Le(X,!1).catch(re=>y(re,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:W,pn:X})=>{try{await Q.lidMapping.storeLIDPNMappings([{lid:W,pn:X}])}catch(re){t.warn({lid:W,pn:X,error:re},"Failed to store LID-PN mapping")}}),_(()=>{P&&(clearTimeout(P),P=void 0),!n.placeholderResendCache&&k.close&&k.close(),j=aa.Connecting,R=void 0}),{...s,serverProps:H,createCallLink:He,getBotListV2:Ce,messageMutex:F,receiptMutex:q,appStatePatchMutex:J,notificationMutex:x,fetchPrivacySettings:ee,upsertMessage:Ae,appPatch:lt,sendPresenceUpdate:_A,presenceSubscribe:at,profilePictureUrl:MA,fetchBlocklist:aA,fetchStatus:he,fetchDisappearingDuration:Ze,updateProfilePicture:je,removeProfilePicture:Oe,updateProfileStatus:hA,updateProfileName:dA,updateBlockStatus:We,updateDisableLinkPreviewsPrivacy:le,updateCallPrivacy:se,updateMessagesPrivacy:Te,updateLastSeenPrivacy:Ne,updateOnlinePrivacy:fe,updateProfilePicturePrivacy:De,updateStatusPrivacy:Ke,updateReadReceiptsPrivacy:rA,updateGroupsAddPrivacy:ve,updateDefaultDisappearingMode:iA,getBusinessProfile:bA,resyncAppState:Le,chatModify:UA,cleanDirtyBits:Be,addOrEditContact:be,removeContact:oA,placeholderResendCache:k,addLabel:lA,addChatLabel:FA,removeChatLabel:Ut,addMessageLabel:st,removeMessageLabel:fr,star:Qe,addOrEditQuickReply:Ar,removeQuickReply:oo}};var Yse=n=>{let t=xse(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(g,c,I)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:I}),r=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return Jh(c)},s=async()=>{let g=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),c={},I=Ie(g,"groups");if(I){let d=PA(I,"group");for(let B of d){let f=Jh({tag:"result",attrs:{},content:[B]});c[f.id]=f}}return t.ev.emit("groups.update",Object.values(c)),c};return t.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=Ie(g,"dirty");c.type==="groups"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,groupMetadata:r,groupCreate:async(g,c)=>{let I=Ur(),d=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:I},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return Jh(d)},groupLeave:async g=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"group",attrs:{id:g}}]}])},groupUpdateSubject:async(g,c)=>{await A(g,"set",[{tag:"subject",attrs:{},content:Buffer.from(c,"utf-8")}])},groupRequestParticipantsList:async g=>{let c=await A(g,"get",[{tag:"membership_approval_requests",attrs:{}}]),I=Ie(c,"membership_approval_requests");return PA(I,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:I,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=Ie(d,"membership_requests_action"),f=Ie(B,I);return PA(f,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:I,attrs:{},content:c.map(Q=>({tag:"participant",attrs:{jid:Q}}))}]),B=Ie(d,I);return PA(B,"participant").map(Q=>({status:Q.attrs.error||"200",jid:Q.attrs.jid,content:Q}))},groupUpdateDescription:async(g,c)=>{let d=(await r(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:Ur()}:{delete:"true"},...d?{prev:d}:{}},content:c?[{tag:"body",attrs:{},content:Buffer.from(c,"utf-8")}]:void 0}])},groupInviteCode:async g=>{let c=await A(g,"get",[{tag:"invite",attrs:{}}]);return Ie(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return Ie(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return Ie(c,"group")?.attrs.jid},groupRevokeInviteV4:async(g,c)=>!!await A(g,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:c}}]}]),groupAcceptInviteV4:i.createBufferedFunction(async(g,c)=>{g=typeof g=="string"?{remoteJid:g}:g;let I=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=oe.Message.GroupInviteMessage.fromObject(c),c.inviteExpiration=0,c.inviteCode="",i.emit("messages.update",[{key:g,update:{message:{groupInviteMessage:c}}}])),await a({key:{remoteJid:c.groupJid,id:Ur(t.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:Ba()},"notify"),I.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return Jh(c)},groupToggleEphemeral:async(g,c)=>{let I=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[I])},groupSettingUpdate:async(g,c)=>{await A(g,"set",[{tag:c,attrs:{}}])},groupMemberAddMode:async(g,c)=>{await A(g,"set",[{tag:"member_add_mode",attrs:{},content:c}])},groupJoinApprovalMode:async(g,c)=>{await A(g,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"group_join",attrs:{state:c}}]}])},groupFetchAllParticipating:s}},Jh=n=>{let t=Ie(n,"group");if(!t){let B=Ie(n,"error");if(B){let f=B.attrs.code?+B.attrs.code:500,Q=B.attrs.text||"group metadata query failed";throw new Sb.Boom(Q,{statusCode:f,data:B})}throw new Sb.Boom("Invalid group metadata response: missing node",{data:n})}if(!t.attrs.id)throw new Sb.Boom("Invalid group metadata response: missing group id",{data:t});let o=Ie(t,"description"),i,e,a,A,r,s;o&&(i=jA(o,"body"),a=o.attrs.participant?uA(o.attrs.participant):void 0,A=o.attrs.participant_pn?uA(o.attrs.participant_pn):void 0,r=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=t.attrs.id.includes("@")?t.attrs.id:Er(t.attrs.id,"g.us"),c=Ie(t,"ephemeral")?.attrs.expiration,I=jA(t,"member_add_mode")==="all_member_add";return{id:g,notify:t.attrs.notify,addressingMode:t.attrs.addressing_mode==="lid"?Pu.LID:Pu.PN,subject:t.attrs.subject,subjectOwner:t.attrs.s_o,subjectOwnerPn:t.attrs.s_o_pn,subjectOwnerUsername:t.attrs.s_o_username,subjectTime:+t.attrs.s_t,size:t.attrs.size?+t.attrs.size:PA(t,"participant").length,creation:+t.attrs.creation,owner:t.attrs.creator?uA(t.attrs.creator):void 0,ownerPn:t.attrs.creator_pn?uA(t.attrs.creator_pn):void 0,ownerUsername:t.attrs.creator_username||void 0,owner_country_code:t.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:r,descTime:s,linkedParent:Ie(t,"linked_parent")?.attrs.jid||void 0,restrict:!!Ie(t,"locked"),announce:!!Ie(t,"announcement"),isCommunity:!!Ie(t,"parent"),isCommunityAnnounce:!!Ie(t,"default_sub_group"),joinApprovalMode:!!Ie(t,"membership_approval_mode"),memberAddMode:I,participants:PA(t,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:qA(B.jid)&&bt(B.phone_number)?B.phone_number:void 0,lid:bt(B.jid)&&qA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var qh=qe(Gr(),1);var qVe=n=>{let{id:t,thread_metadata:o,viewer_metadata:i}=n;return{id:t,owner:void 0,name:o.name.text,creation_time:parseInt(o.creation_time,10),description:o.description.text,invite:o.invite,subscribers:parseInt(o.subscribers_count,10),verification:o.verification,picture:{id:o.picture.id,directPath:o.picture.direct_path},mute_state:i.mute}},zVe=n=>typeof n!="object"||n===null?null:"id"in n&&typeof n.id=="string"?n:"result"in n&&typeof n.result=="object"&&n.result!==null&&"id"in n.result?n.result:null,jse=n=>{let t=Yse(n),{query:o,generateMessageTag:i}=t,e=(A,r,s)=>cf(A,r,s,o,i),a=async(A,r)=>{let s={newsletter_id:A,updates:{...r,settings:null}};return e(s,ia.UPDATE_METADATA,"xwa2_newsletter_update")};return{...t,newsletterCreate:async(A,r)=>{let g=await e({input:{name:A,description:r??null}},ia.CREATE,Ca.xwa2_newsletter_create);return qVe(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},ia.SUBSCRIBERS,Ca.xwa2_newsletter_subscribers),newsletterMetadata:async(A,r)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:r,type:A.toUpperCase()}},g=await e(s,ia.METADATA,Ca.xwa2_newsletter_metadata);return zVe(g)},newsletterFollow:A=>e({newsletter_id:A},ia.FOLLOW,Ca.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},ia.UNFOLLOW,Ca.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},ia.MUTE,Ca.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},ia.UNMUTE,Ca.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,r)=>await a(A,{name:r}),newsletterUpdateDescription:async(A,r)=>await a(A,{description:r}),newsletterUpdatePicture:async(A,r)=>{let{img:s}=await DO(r);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,r,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:r,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,r,s,g)=>{let c={count:r.toString()};return typeof s=="number"&&(c.since=s.toString()),g&&(c.after=g.toString()),await o({tag:"iq",attrs:{id:i(),type:"get",xmlns:"newsletter",to:A},content:[{tag:"message_updates",attrs:c}]})},subscribeNewsletterUpdates:async A=>{let r=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=Ie(r,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},ia.ADMIN_COUNT,Ca.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,r)=>{await e({newsletter_id:A,user_id:r},ia.CHANGE_OWNER,Ca.xwa2_newsletter_change_owner)},newsletterDemote:async(A,r)=>{await e({newsletter_id:A,user_id:r},ia.DEMOTE,Ca.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},ia.DELETE,Ca.xwa2_newsletter_delete_v2)}}};var Jse=n=>{let{logger:t,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:r,maxMsgRetryCount:s}=n,g=jse(n),{ev:c,authState:I,messageMutex:d,signalRepository:B,upsertMessage:f,query:Q,fetchPrivacySettings:y,sendNode:m,groupMetadata:_,groupToggleEphemeral:T,registerSocketEndHandler:R}=g,H=B.lidMapping.getLIDForPN.bind(B.lidMapping),j=new Set,F=n.userDevicesCache||new Rg({stdTTL:$c.USER_DEVICES,useClones:!1}),q=Fg(),J=r?new LO(t,s):null,x=Use(),P,z=ZL,U=async(Ce=!1)=>{let he=await P;return(!he||Ce||new Date().getTime()-he.fetchDate.getTime()>he.ttl*1e3)&&(P=(async()=>{let Ze=await Q({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:OA},content:[{tag:"media_conn",attrs:{}}]}),je=Ie(Ze,"media_conn"),Oe={hosts:PA(je,"host").map(({attrs:hA})=>({hostname:hA.hostname,maxContentLengthBytes:+hA.maxContentLengthBytes})),auth:je.attrs.auth,ttl:+je.attrs.ttl,fetchDate:new Date};return t.debug("fetched media conn"),Oe.hosts[0]&&(z=Oe.hosts[0].hostname),Oe})()),P},N=async(Ce,he,Ze,je)=>{if(!Ze||Ze.length===0)throw new qh.Boom("missing ids in receipt");let Oe={tag:"receipt",attrs:{id:Ze[0]}};(je==="read"||je==="read-self")&&(Oe.attrs.t=Ba().toString()),je==="sender"&&(bt(Ce)||qA(Ce))?(Oe.attrs.recipient=Ce,Oe.attrs.to=he):(Oe.attrs.to=Ce,he&&(Oe.attrs.participant=he)),je&&(Oe.attrs.type=je);let dA=Ze.slice(1);dA.length&&(Oe.content=[{tag:"list",attrs:{},content:dA.map(aA=>({tag:"item",attrs:{id:aA}}))}]),t.debug({attrs:Oe.attrs,messageIds:Ze},"sending receipt for messages"),await m(Oe)},k=async(Ce,he)=>{let Ze=Xae(Ce);for(let{jid:je,participant:Oe,messageIds:hA}of Ze)await N(je,Oe,hA,he)},V=async Ce=>{let Ze=(await y()).readreceipts==="all"?"read":"read-self";await k(Ce,Ze)},ee=async(Ce,he,Ze)=>{let je=[];he||t.debug("not using cache for devices");let Oe=[],hA=Ce.map(Be=>{let Re=yA(Be),Le=Re?.user,MA=Re?.device;return typeof MA=="number"&&MA>=0&&Le?(je.push({user:Le,device:MA,jid:Be}),null):(Be=uA(Be),{jid:Be,user:Le})}).filter(Be=>Be!==null),dA;if(he&&F.mget){let Be=hA.map(Re=>Re?.user).filter(Boolean);dA=await F.mget(Be)}for(let{jid:Be,user:Re}of hA)if(he){let Le=dA?.[Re]||(F.mget?void 0:await F.get(Re));if(Le){let MA=Le.map(He=>({...He,jid:Er(He.user,He.server,He.device)}));je.push(...MA),t.trace({user:Re},"using cache for devices")}else Oe.push(Be)}else Oe.push(Be);if(!Oe.length)return je;let aA=new Set;for(let Be of Oe)if(qA(Be)||oa(Be)){let Re=yA(Be)?.user;Re&&aA.add(Re)}let We=new Ls().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Be of Oe)We.withUser(new Fs().withId(Be));let bA=await g.executeUSyncQuery(We);if(bA){let Be=bA.list.filter(He=>!!He.lid);if(Be.length>0){t.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Be.map(He=>({lid:He.lid,pn:He.id})));try{let He=Be.map(_A=>_A.lid);He.length&&await Te(He,!0)}catch(He){t.warn({e:He,count:Be.length},"failed to assert sessions for newly mapped LIDs")}}let Re=nie(bA?.list,I.creds.me.id,I.creds.me.lid,Ze),Le={};for(let He of Re)Le[He.user]=Le[He.user]||[],Le[He.user]?.push(He);for(let[He,_A]of Object.entries(Le)){let at=aA.has(He);for(let DA of _A){let lt=at?Er(He,DA.server,DA.device):Er(DA.user,DA.server,DA.device);je.push({...DA,jid:lt}),t.debug({user:DA.user,device:DA.device,finalJid:lt,usedLid:at},"Processed device with LID priority")}}await q.mutex(async()=>{if(F.mset)await F.mset(Object.entries(Le).map(([He,_A])=>({key:He,value:_A})));else for(let He in Le)Le[He]&&await F.set(He,Le[He])});let MA={};for(let[He,_A]of Object.entries(Le))_A&&_A.length>0&&(MA[He]=_A.map(at=>at.device?.toString()||"0"));if(Object.keys(MA).length>0)try{await I.keys.set({"device-list":MA}),t.debug({userCount:Object.keys(MA).length},"stored user device lists for bulk migration")}catch(He){t.warn({error:He},"failed to store user device lists")}}return je},ie=(Ce,he)=>fe(Ce,{protocolMessage:{type:oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:he?.slice(0,30),labelTimestamp:Ba()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),Te=async(Ce,he)=>{let Ze=!1,je=[...new Set(Ce)],Oe=[];t.debug({jids:Ce},"assertSessions call with jids");for(let hA of je)!he&&(await B.validateSession(hA)).exists||Oe.push(hA);if(Oe.length){let hA=[...Oe.filter(aA=>!!qA(aA)||!!oa(aA)),...(await B.lidMapping.getLIDsForPNs(Oe.filter(aA=>!!bt(aA)||!!Cr(aA)))||[]).map(aA=>aA.lid)];t.debug({jidsRequiringFetch:Oe,wireJids:hA},"fetching sessions");let dA=await Q({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:OA},content:[{tag:"key",attrs:{},content:hA.map(aA=>{let We={jid:aA};return he&&(We.reason="identity"),{tag:"user",attrs:We}})}]});await oie(dA,B),Ze=!0}return Ze},se=async Ce=>{if(!I.creds.me?.id)throw new qh.Boom("Not authenticated");let he={protocolMessage:{peerDataOperationRequestMessage:Ce,type:oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},Ze=uA(I.creds.me.id);return await fe(Ze,he,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},Ne=async(Ce,he,Ze,je)=>{if(!Ce.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let Oe=await a(he,Ce),hA=Array.isArray(Oe)?Oe:Ce.map(Le=>({recipientJid:Le,message:Oe})),dA=!1,aA=I.creds.me.id,We=I.creds.me?.lid,bA=We?yA(We)?.user:null,Be=hA.map(async({recipientJid:Le,message:MA})=>{try{if(!Le)return null;let He=MA;if(je){let{user:lt}=yA(Le),{user:Ir}=yA(aA),UA=bA;(lt===Ir||UA&<===UA)&&!(Le===aA||We&&Le===We)&&(He=je,t.debug({jid:Le,targetUser:lt},"Using DSM for own device"))}let _A=Ld(He),at=Le;return await x.mutex(at,async()=>{let{type:lt,ciphertext:Ir}=await B.encryptMessage({jid:Le,data:_A});return lt==="pkmsg"&&(dA=!0),{tag:"to",attrs:{jid:Le},content:[{tag:"enc",attrs:{v:"2",type:lt,...Ze||{}},content:Ir}]}})}catch(He){return t.error({jid:Le,err:He},"Failed to encrypt for recipient"),null}}),Re=(await Promise.all(Be)).filter(Le=>Le!==null);if(Ce.length>0&&Re.length===0)throw new qh.Boom("All encryptions failed",{statusCode:500});return{nodes:Re,shouldIncludeDeviceIdentity:dA}},fe=async(Ce,he,{messageId:Ze,participant:je,additionalAttributes:Oe,additionalNodes:hA,useUserDevicesCache:dA,useCachedGroupMetadata:aA,statusJidList:We})=>{let bA=Jie(I.creds),Be=I.creds.me?.lid,Re=!!je?.jid,Le=Re,MA="status@broadcast",{user:He,server:_A}=yA(Ce),at=_A==="g.us",DA=Ce===MA,lt=_A==="lid",Ir=_A==="newsletter",UA=at||DA,le=Ce;Ze=Ze||Ur(bA),dA=dA!==!1,aA=aA!==!1&&!DA;let Qe=[],be=DA?MA:le,oA=[],lA=[],FA,Ut={deviceSentMessage:{destinationJid:be,message:he},messageContextInfo:he.messageContextInfo},st={};if(je){!at&&!DA&&(Oe={...Oe,device_fanout:"false"});let{user:fr,device:Ar}=yA(je.jid);lA.push({user:fr,device:Ar,jid:je.jid})}return await I.keys.transaction(async()=>{let fr=Ke(he);if(fr&&(st.mediatype=fr),Ir){let Ee=a?await a(he,[]):he,de=AX(Ee);oA.push({tag:"plaintext",attrs:{},content:de});let ye={tag:"message",attrs:{to:Ce,id:Ze,type:De(he),...Oe||{}},content:oA};t.debug({msgId:Ze},`sending newsletter message to ${Ce}`),await m(ye);return}if((Sa(he)?.pinInChatMessage||Sa(he)?.reactionMessage)&&(st["decrypt-fail"]="hide"),UA&&!Re){let[Ee,de]=await Promise.all([(async()=>{let AA=aA&&A?await A(Ce):void 0;return AA&&Array.isArray(AA?.participants)?t.trace({jid:Ce,participants:AA.participants.length},"using cached group metadata"):DA||(AA=await _(Ce)),AA})(),(async()=>!je&&!DA?(await I.keys.get("sender-key-memory",[Ce]))[Ce]||{}:{})()]),ye=Ee?Ee.participants.map(AA=>AA.id):[];Ee?.ephemeralDuration&&Ee.ephemeralDuration>0&&(Oe={...Oe,expiration:Ee.ephemeralDuration.toString()}),DA&&We&&ye.push(...We);let Je=await ee(ye,!!dA,!1);lA.push(...Je),at&&(Oe={...Oe,addressing_mode:Ee?.addressingMode||"lid"});let IA=await a(he);if(Array.isArray(IA))throw new qh.Boom("Per-jid patching is not supported in groups");let QA=Ld(IA);FA=IA;let vA=(Oe?.addressing_mode||Ee?.addressingMode||"lid")==="lid"&&Be?Be:bA,{ciphertext:YA,senderKeyDistributionMessage:$A}=await B.encryptGroupMessage({group:be,data:QA,meId:vA}),Pe=[];for(let AA of lA){let et=AA.jid;(!!!de[et]||je)&&!oa(et)&&!Cr(et)&&AA.device!==99&&(Pe.push(et),de[et]=!0)}if(Pe.length){t.debug({senderKeyJids:Pe},"sending new sender key");let AA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:$A,groupId:be}};await Te(Pe);let qr=await Ne(Pe,AA,st);Le=Le||qr.shouldIncludeDeviceIdentity,Qe.push(...qr.nodes)}oA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...st},content:YA}),await I.keys.set({"sender-key-memory":{[Ce]:de}})}else{let Ee=bA;lt&&Be?(Ee=Be,t.debug({to:Ce,ownId:Ee},"Using LID identity for @lid conversation")):t.debug({to:Ce,ownId:Ee},"Using PN identity for @s.whatsapp.net conversation");let{user:de}=yA(Ee);if(!je){let AA=await a(he,[Ce]);FA=Array.isArray(AA)?AA.find(et=>et.recipientJid===Ce)||AA[0]:AA}if(!Re){let AA=lt?"lid":"s.whatsapp.net";if(lA.push({user:He,device:0,jid:Er(He,AA,0)}),He!==de){let et=lt?"lid":"s.whatsapp.net",qr=lt&&Be?yA(Be).user:yA(bA).user;lA.push({user:qr,device:0,jid:Er(qr,et,0)})}if(Oe?.category!=="peer"){lA.length=0;let et=lt&&Be?Er(yA(Be)?.user,"lid",void 0):Er(yA(bA)?.user,"s.whatsapp.net",void 0),qr=await ee([et,Ce],!0,!1);lA.push(...qr),t.debug({deviceCount:lA.length,devices:lA.map(tr=>`${tr.user}:${tr.device}@${yA(tr.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let ye=[],Je=[],IA=[],{user:QA}=yA(bA),{user:XA}=Be?yA(Be):{user:null};for(let{user:AA,jid:et}of lA){if(et===bA||Be&&et===Be){t.debug({jid:et,meId:bA,meLid:Be},"Skipping exact sender device (whatsmeow pattern)");continue}AA===QA||AA===XA?Je.push(et):IA.push(et),ye.push(et)}await Te(ye);let[{nodes:vA,shouldIncludeDeviceIdentity:YA},{nodes:$A,shouldIncludeDeviceIdentity:Pe}]=await Promise.all([Ne(Je,Ut||he,st),Ne(IA,he,st,Ut)]);Qe.push(...vA),Qe.push(...$A),(Je.length>0||IA.length>0)&&(st.phash=j9([...Je,...IA])),Le=Le||YA||Pe}if(Re){let Ee=qA(je.jid),de=Mt(je.jid,Ee?Be:bA),ye=he;if(UA){let XA;if(Be&&await B.hasSenderKey({group:be,meId:Be})?XA=Be:await B.hasSenderKey({group:be,meId:bA})&&(XA=bA),XA)try{let vA=await B.getSenderKeyDistributionMessage({group:be,meId:XA});ye={...he,senderKeyDistributionMessage:{groupId:be,axolotlSenderKeyDistributionMessage:vA}}}catch(vA){t.warn({err:vA,jid:be},"failed to build SKDM for retry, sending without it")}}let Je=de?Ld({deviceSentMessage:{destinationJid:be,message:ye}}):Ld(ye),{type:IA,ciphertext:QA}=await B.encryptMessage({data:Je,jid:je.jid});oA.push({tag:"enc",attrs:{v:"2",type:IA,count:je.count.toString()},content:QA})}if(Qe.length)if(Oe?.category==="peer"){let Ee=Qe[0]?.content?.[0];Ee&&oA.push(Ee)}else oA.push({tag:"participants",attrs:{},content:Qe});let Ar={tag:"message",attrs:{id:Ze,to:be,type:De(he),...Oe||{}},content:oA};if(je?Fr(be)?(Ar.attrs.to=be,Ar.attrs.participant=je.jid):Mt(je.jid,bA)?(Ar.attrs.to=je.jid,Ar.attrs.recipient=be):Ar.attrs.to=je.jid:Ar.attrs.to=be,Le&&(Ar.content.push({tag:"device-identity",attrs:{},content:qB(I.creds.account,!0)}),t.debug({jid:Ce},"adding device identity")),!Ir&&!Re&&FA?.messageContextInfo?.messageSecret&&bO(FA))try{let Ee=Ld(FA),de={id:Ze,fromMe:!0,remoteJid:be,participant:je?.jid},ye=await qae(Ee,FA,de);ye&&(Ar.content.push(ye),t.trace({jid:Ce},"added reporting token to message"))}catch(Ee){t.warn({jid:Ce,trace:Ee?.stack},"failed to attach reporting token")}let oo=Oe?.category==="peer",Gi=!at&&!Re&&!DA&&!Ir&&!oo,Ae=Gi?await ks(be,H):be,X=(Gi?await I.keys.get("tctoken",[Ae]):{})[Ae],re=X?.token;if(re?.length&&kl(X?.timestamp)){t.debug({jid:be,timestamp:X?.timestamp},"tctoken expired, clearing"),re=void 0;let Ee=X?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:X.senderTimestamp}:null;try{await I.keys.set({tctoken:{[Ae]:Ee}})}catch(de){t.debug({jid:be,err:de?.message},"failed to persist tctoken expiry cleanup")}}re?.length&&g.serverProps.privacyTokenOn1to1&&Ar.content.push({tag:"tctoken",attrs:{},content:re}),hA&&hA.length>0&&Ar.content.push(...hA),t.debug({msgId:Ze},`sending message to ${Qe.length} devices`),await m(Ar);let ne=!!Sa(he)?.protocolMessage,Se=be===g9||I9(be)||Nd(be);if(Gi&&!ne&&!Se&&Zie(X?.senderTimestamp)&&!j.has(Ae)){j.add(Ae);let Ee=Ba(),de=B.lidMapping.getPNForLID.bind(B.lidMapping);XB(be,g.serverProps.lidTrustedTokenIssueToLid,H,de).then(ye=>rA([ye],Ee)).then(async ye=>{await kh({result:ye,fallbackJid:Ae,keys:I.keys,getLIDForPN:H});let IA=(await I.keys.get("tctoken",[Ae]))[Ae],QA=await Rh(I.keys,[Ae]);await I.keys.set({tctoken:{[Ae]:{token:Buffer.alloc(0),...IA,senderTimestamp:Ee},...QA}})}).catch(ye=>{t.debug({jid:be,err:ye?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{j.delete(Ae)})}J&&!je&&J.addRecentMessage(be,Ze,he)},bA),Ze},De=Ce=>{let he=Sa(Ce);return he?he.reactionMessage||he.encReactionMessage?"reaction":he.pollCreationMessage||he.pollCreationMessageV2||he.pollCreationMessageV3||he.pollUpdateMessage?"poll":he.eventMessage?"event":Ke(he)!==""?"media":"text":"text"},Ke=Ce=>Ce.imageMessage?"image":Ce.videoMessage?Ce.videoMessage.gifPlayback?"gif":"video":Ce.audioMessage?Ce.audioMessage.ptt?"ptt":"audio":Ce.contactMessage?"vcard":Ce.documentMessage?"document":Ce.contactsArrayMessage?"contact_array":Ce.liveLocationMessage?"livelocation":Ce.stickerMessage?"sticker":Ce.listMessage?"list":Ce.listResponseMessage?"list_response":Ce.buttonsResponseMessage?"buttons_response":Ce.orderMessage?"order":Ce.productMessage?"product":Ce.interactiveResponseMessage?"native_flow_response":Ce.groupInviteMessage?"url":"",rA=async(Ce,he)=>{let Ze=(he??Ba()).toString();return await Q({tag:"iq",attrs:{to:OA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:Ce.map(Oe=>({tag:"token",attrs:{jid:uA(Oe),t:Ze,type:"trusted_contact"}}))}]})},ve=Fae(n,U),iA=LG(c,"messages.media-update");return R(()=>{!n.userDevicesCache&&F.close&&F.close(),P=void 0,J&&J.clear()}),{...g,userDevicesCache:F,devicesMutex:q,issuePrivacyTokens:rA,assertSessions:Te,relayMessage:fe,sendReceipt:N,sendReceipts:k,readMessages:V,refreshMediaConn:U,getMediaHost:()=>z,waUploadToServer:ve,fetchPrivacySettings:y,sendPeerDataOperationMessage:se,createParticipantNodes:Ne,getUSyncDevices:ee,messageRetryManager:J,updateMemberLabel:ie,updateMediaMessage:async Ce=>{let he=$ae(Ce.message),Ze=he.mediaKey,je=I.creds.me.id,Oe=Uae(Ce.key,Ze,je),hA;if(await Promise.all([m(Oe),iA(async dA=>{let aA=dA.find(We=>We.key.id===Ce.key.id);if(aA){if(aA.error)hA=aA.error;else try{let We=Kae(aA.media,Ze,aA.key.id);if(We.result!==oe.MediaRetryNotification.ResultType.SUCCESS){let bA=oe.MediaRetryNotification.ResultType[We.result];throw new qh.Boom(`Media re-upload failed by device (${bA})`,{data:We,statusCode:XL(We.result)||404})}he.directPath=We.directPath,he.url=HB(he.directPath,z),t.debug({directPath:We.directPath,key:aA.key},"media update successful")}catch(We){hA=We}return!0}})]),hA)throw hA;return c.emit("messages.update",[{key:Ce.key,update:{message:Ce.message}}]),Ce},sendMessage:async(Ce,he,Ze={})=>{let je=I.creds.me.id;if(typeof he=="object"&&"disappearingMessagesInChat"in he&&typeof he.disappearingMessagesInChat<"u"&&Fr(Ce)){let{disappearingMessagesInChat:Oe}=he;await T(Ce,typeof Oe=="boolean"?Oe?jB:0:Oe)}else{let Oe=await Wae(Ce,he,{logger:t,userJid:je,getUrlInfo:Le=>Wie(Le,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:t,uploadImage:i?ve:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:ve,mediaCache:n.mediaCache,options:n.options,messageId:Ur(g.user?.id),...Ze}),hA="event"in he&&!!he.event,dA="delete"in he&&!!he.delete,aA="edit"in he&&!!he.edit,We="pin"in he&&!!he.pin,bA="poll"in he&&!!he.poll,Be={},Re=[];return dA?Fr(he.delete?.remoteJid)&&!he.delete?.fromMe?Be.edit="8":Be.edit="7":aA?Be.edit="1":We?Be.edit="2":bA?Re.push({tag:"meta",attrs:{polltype:"creation"}}):hA&&Re.push({tag:"meta",attrs:{event_type:"creation"}}),await fe(Ce,Oe.message,{messageId:Oe.key.id,useCachedGroupMetadata:Ze.useCachedGroupMetadata,additionalAttributes:Be,statusJidList:Ze.statusJidList,additionalNodes:Re}),n.emitOwnEvents&&process.nextTick(async()=>{await d.mutex(()=>f(Oe,"append"))}),Oe}}}};var VVe=new Set(Object.values(Dc));function WVe(n){return typeof n=="string"&&VVe.has(n)}var qse=n=>{let{logger:t,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,r=Jse(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:I,ws:d,messageMutex:B,notificationMutex:f,receiptMutex:Q,signalRepository:y,query:m,upsertMessage:_,resyncAppState:T,onUnexpectedError:R,assertSessions:H,sendNode:j,relayMessage:F,sendReceipt:q,uploadPreKeys:J,sendPeerDataOperationMessage:x,messageRetryManager:P,registerSocketEndHandler:z,issuePrivacyTokens:U,fetchAccountReachoutTimelock:N,placeholderResendCache:k}=r,V=y.lidMapping.getLIDForPN.bind(y.lidMapping),ee=Fg(),ie=n.msgRetryCounterCache||new Rg({stdTTL:$c.MSG_RETRY,useClones:!1}),Te=n.callOfferCache||new Rg({stdTTL:$c.CALL_OFFER,useClones:!1}),se=new Rg({stdTTL:5,useClones:!1}),Ne=!1,fe=async(Ae,W,X)=>{if(!I.creds.me?.id)throw new If.Boom("Not authenticated");let re={historySyncOnDemandRequest:{chatJid:W.remoteJid,oldestMsgFromMe:W.fromMe,oldestMsgId:W.id,oldestMsgTimestampMs:X,onDemandMsgCount:Ae},peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return x(re)},De=async(Ae,W)=>{if(!I.creds.me?.id)throw new If.Boom("Not authenticated");if(await k.get(Ae?.id)){t.debug({messageKey:Ae},"already requested resend");return}else await k.set(Ae?.id,W||!0);if(await zu(2e3),!await k.get(Ae?.id))return t.debug({messageKey:Ae},"message received while resend requested"),"RESOLVED";let X={placeholderMessageResendRequest:[{messageKey:Ae}],peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await k.get(Ae?.id)&&(t.debug({messageKey:Ae},"PDO message without response after 8 seconds. Phone possibly offline"),await k.del(Ae?.id))},8e3),x(X)},Ke=async Ae=>{let W=Ie(Ae,"update");if(W){let X=W.attrs?.op_name;if(!X){t.warn({node:Bn(Ae)},"mex notification missing op_name, fallback to legacy"),await iA(Ae);return}let re;try{re=JSON.parse(W.content.toString())}catch(Se){t.error({err:Se,opName:X},"failed to parse mex notification JSON");return}if(re.errors?.length){t.warn({errors:re.errors,opName:X},"mex notification has GQL errors");return}let ne=re.data;if(!ne){t.warn({opName:X},"mex notification has null data");return}switch(t.debug({opName:X},"processing mex notification"),X){case"NotificationUserReachoutTimelockUpdate":rA(ne);break;case"MessageCappingInfoNotification":ve(ne);break;case"NotificationNewsletterUpdate":case"NotificationLinkedProfilesUpdates":case"NotificationNewsletterAdminPromote":case"NotificationNewsletterAdminDemote":case"NotificationNewsletterUserSettingChange":case"NotificationNewsletterJoin":case"NotificationNewsletterLeave":case"NotificationNewsletterStateChange":case"NotificationNewsletterAdminMetadataUpdate":case"NotificationNewsletterOwnerUpdate":case"NotificationNewsletterAdminInviteRevoke":case"NotificationNewsletterWamoSubStatusChange":case"NotificationNewsletterBlockUser":case"NotificationNewsletterPaidPartnership":case"NotificationNewsletterMilestone":case"NewsletterResponseStateUpdate":await iA(Ae);break;default:t.debug({opName:X},"unhandled mex notification");break}return}await iA(Ae)},rA=Ae=>{let W=Ae.xwa2_notify_account_reachout_timelock;if(!W){t.warn("reachout timelock notification missing payload");return}if(!W.is_active){t.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:Dc.DEFAULT}});return}let X=W.time_enforcement_ends?new Date(parseInt(W.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),re=WVe(W.enforcement_type)?W.enforcement_type:Dc.DEFAULT;t.info({enforcementType:re,timeEnforcementEnds:X},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:X,enforcementType:re}})},ve=Ae=>{let W=Ae.xwa2_notify_new_chat_messages_capping_info_update;if(!W){t.warn("message capping notification missing payload");return}t.info({payload:W},"received message capping update"),c.emit("message-capping.update",W)},iA=async Ae=>{let W=Ie(Ae,"mex"),X=W?.content?null:Ie(Ae,"update")||ls(Ae)[0],re=W?.content?W:X;if(!re?.content){t.warn({node:Bn(Ae)},"invalid mex newsletter notification");return}let ne;try{let de=re.content;if(Array.isArray(de)){t.warn({payloadNode:re},"invalid mex newsletter notification payload format");return}let ye=typeof de=="string"?Buffer.from(de,"binary"):Buffer.from(de);ne=JSON.parse(ye.toString())}catch(de){t.error({err:de,node:Bn(Ae)},"failed to parse mex newsletter notification");return}let Se=ne?.operation??re?.attrs?.op_name,Ee=ne?.updates;if(!Ee){let de=ne?.data?.xwa2_notify_linked_profiles;de&&(Ee=[de])}if(!Ee||!Se){t.warn({data:ne},"invalid mex newsletter notification content");return}switch(t.info({operation:Se,updates:Ee},"got mex newsletter notification"),Se){case"NotificationNewsletterUpdate":for(let de of Ee)de.jid&&de.settings&&Object.keys(de.settings).length>0&&c.emit("newsletter-settings.update",{id:de.jid,update:de.settings});break;case"NotificationNewsletterAdminPromote":for(let de of Ee)de.jid&&de.user&&c.emit("newsletter-participants.update",{id:de.jid,author:Ae.attrs.from,user:de.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let de of Ee){let ye=de?.jid,Je=Array.isArray(de?.added_profiles)?de.added_profiles:[],IA=[];for(let QA of Je){let XA=typeof QA=="string"?QA:QA?.pn??QA?.jid??null;if(ye&&XA){let vA={lid:ye,pn:XA};c.emit("lid-mapping.update",vA),IA.push(vA)}}await y.lidMapping.storeLIDPNMappings(IA)}break;default:t.info({operation:Se,data:ne},"unhandled mex newsletter notification");break}},Ce=async Ae=>{let W=Ae.attrs.from,X=ls(Ae),re=Ae.attrs.participant;for(let ne of X)switch(t.debug({from:W,child:ne},"got newsletter notification"),ne.tag){case"reaction":{let Se={id:W,server_id:ne.attrs.message_id,reaction:{code:jA(ne,"reaction"),count:1}};c.emit("newsletter.reaction",Se);break}case"view":{let Se={id:W,server_id:ne.attrs.message_id,count:parseInt(ne.content?.toString()||"0",10)};c.emit("newsletter.view",Se);break}case"participant":{let Se={id:W,author:re,user:ne.attrs.jid,action:ne.attrs.action,new_role:ne.attrs.role};c.emit("newsletter-participants.update",Se);break}case"update":{let Se=Ie(ne,"settings");if(Se){let Ee={},de=Ie(Se,"name");de?.content&&(Ee.name=de.content.toString());let ye=Ie(Se,"description");ye?.content&&(Ee.description=ye.content.toString()),c.emit("newsletter-settings.update",{id:W,update:Ee})}break}case"message":{let Se=Ie(ne,"plaintext");if(Se?.content)try{let Ee=typeof Se.content=="string"?Buffer.from(Se.content,"binary"):Buffer.from(Se.content),de=oe.Message.decode(Ee).toJSON(),ye=oe.WebMessageInfo.fromObject({key:{remoteJid:W,id:ne.attrs.message_id||ne.attrs.server_id,fromMe:!1},message:de,messageTimestamp:+ne.attrs.t}).toJSON();await _(ye,"append"),t.debug("Processed plaintext newsletter message")}catch(Ee){t.error({error:Ee},"Failed to decode plaintext newsletter message")}break}default:t.warn({node:Ae,child:ne},"Unknown newsletter notification child");break}},he=async(Ae,W)=>{let X=ioe(Ae,W,I.creds.me.id);t.debug({recv:{tag:Ae.tag,attrs:Ae.attrs},sent:X.attrs},"sent ack"),await j(X)},Ze=async(Ae,W)=>{let X={tag:"call",attrs:{from:I.creds.me.id,to:W},content:[{tag:"reject",attrs:{"call-id":Ae,"call-creator":W,count:"0"},content:void 0}]};await m(X)},je=async(Ae,W=!1)=>{let{fullMessage:X}=HG(Ae,I.creds.me.id,I.creds.me.lid||""),{key:re}=X,ne=re.id;if(P){if(P.hasExceededMaxRetries(ne)){t.debug({msgId:ne},"reached retry limit with new retry manager, clearing"),P.markRetryFailed(ne);return}let YA=P.incrementRetryCount(ne),$A=`${ne}:${re?.participant}`;await ie.set($A,YA)}else{let YA=`${ne}:${re?.participant}`,$A=await ie.get(YA)||0;if($A>=i){t.debug({retryCount:$A,msgId:ne},"reached retry limit, clearing"),await ie.del(YA);return}$A+=1,await ie.set(YA,$A)}let Se=`${ne}:${re?.participant}`,Ee=await ie.get(Se)||1,{account:de,signedPreKey:ye,signedIdentityKey:Je}=I.creds,IA=Ae.attrs.from,QA=!1,XA="";if(A&&P&&Ee>1)try{let YA=y.jidToSignalProtocolAddress(IA),$A=await y.validateSession(IA),Pe=P.shouldRecreateSession(IA,$A.exists);QA=Pe.recreate,XA=Pe.reason,QA&&(t.debug({fromJid:IA,retryCount:Ee,reason:XA},"recreating session for retry"),await I.keys.set({session:{[YA]:null}}),W=!0)}catch(YA){t.warn({error:YA,fromJid:IA},"failed to check session recreation")}if(Ee<=2)if(P)P.schedulePhoneRequest(ne,async()=>{try{let YA=await De(re);t.debug(`sendRetryRequest: requested placeholder resend (${YA}) for message ${ne} (scheduled)`)}catch(YA){t.warn({error:YA,msgId:ne},"failed to send scheduled phone request")}});else{let YA=await De(re);t.debug(`sendRetryRequest: requested placeholder resend for message ${YA}`)}let vA=qB(de,!0);await I.keys.transaction(async()=>{let YA={tag:"receipt",attrs:{id:ne,type:"retry",to:Ae.attrs.from},content:[{tag:"retry",attrs:{count:Ee.toString(),id:Ae.attrs.id,t:Ae.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:yg(I.creds.registrationId)}]};if(Ae.attrs.recipient&&(YA.attrs.recipient=Ae.attrs.recipient),Ae.attrs.participant&&(YA.attrs.participant=Ae.attrs.participant),Ee>1||W||QA){let{update:$A,preKeys:Pe}=await s2(I,1),[AA]=Object.keys(Pe),et=Pe[+AA];YA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Qg)},{tag:"identity",attrs:{},content:Je.public},n2(et,+AA),JB(ye),{tag:"device-identity",attrs:{},content:vA}]}),c.emit("creds.update",$A)}await j(YA),t.info({msgAttrs:Ae.attrs,retryCount:Ee},"sent retry receipt")},I?.creds?.me?.id||"sendRetryRequest")},Oe=new Set,hA=Ae=>{(async()=>{let W=uA(Ae),X=await ks(W,V),ne=(await I.keys.get("tctoken",[X]))?.[X]?.senderTimestamp;if(ne==null||kl(ne))return;t.debug({jid:W,senderTimestamp:ne},"identity changed, re-issuing tctoken");let Se=y.lidMapping.getPNForLID.bind(y.lidMapping),Ee=await XB(W,r.serverProps.lidTrustedTokenIssueToLid,V,Se),de=await U([Ee],ne);await kh({result:de,fallbackJid:X,keys:I.keys,getLIDForPN:V,onNewJidStored:_A})})().catch(W=>{t.debug({jid:Ae,err:W?.message},"failed to re-issue tctoken after identity change")})},dA=async Ae=>{if(Ae.attrs.from===OA){let X=Ae.attrs.id;if(X&&Oe.has(X))return;let ne=+Ie(Ae,"count").attrs.value,Se=ne{let re=Ae.attrs.participant,ne=Ae.attrs.participant_pn,Se=Ae.attrs.participant_username,Ee=Ie(W,"participant")?.attrs?.jid||re,de=Ie(W,"participant")?.attrs?.phone_number||ne;switch(W?.tag){case"create":let ye=Jh(W);X.messageStubType=RA.GROUP_CREATE,X.messageStubParameters=[ye.subject],X.key={participant:ye.owner,participantAlt:ye.ownerPn},c.emit("chats.upsert",[{id:ye.id,name:ye.subject,conversationTimestamp:ye.creation}]),c.emit("groups.upsert",[{...ye,author:re,authorPn:ne,authorUsername:Se}]);break;case"ephemeral":case"not_ephemeral":X.message={protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(W.attrs.expiration||0)}};break;case"modify":let Je=PA(W,"participant").map(Pe=>Pe.attrs.jid);X.messageStubParameters=Je||[],X.messageStubType=RA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let IA=`GROUP_PARTICIPANT_${W.tag.toUpperCase()}`;X.messageStubType=RA[IA];let QA=PA(W,"participant").map(({attrs:Pe})=>({id:Pe.jid,phoneNumber:qA(Pe.jid)&&bt(Pe.phone_number)?Pe.phone_number:void 0,lid:bt(Pe.jid)&&qA(Pe.lid)?Pe.lid:void 0,username:Pe.participant_username||Pe.username||void 0,admin:Pe.type||null}));QA.length===1&&(Mt(QA[0].id,re)||Mt(QA[0].id,ne))&&W.tag==="remove"&&(X.messageStubType=RA.GROUP_PARTICIPANT_LEAVE),X.messageStubParameters=QA.map(Pe=>JSON.stringify(Pe));break;case"subject":X.messageStubType=RA.GROUP_CHANGE_SUBJECT,X.messageStubParameters=[W.attrs.subject];break;case"description":let XA=Ie(W,"body")?.content?.toString();X.messageStubType=RA.GROUP_CHANGE_DESCRIPTION,X.messageStubParameters=XA?[XA]:void 0;break;case"announcement":case"not_announcement":X.messageStubType=RA.GROUP_CHANGE_ANNOUNCE,X.messageStubParameters=[W.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":X.messageStubType=RA.GROUP_CHANGE_RESTRICT,X.messageStubParameters=[W.tag==="locked"?"on":"off"];break;case"invite":X.messageStubType=RA.GROUP_CHANGE_INVITE_LINK,X.messageStubParameters=[W.attrs.code];break;case"member_add_mode":let vA=W.content;vA&&(X.messageStubType=RA.GROUP_MEMBER_ADD_MODE,X.messageStubParameters=[vA.toString()]);break;case"membership_approval_mode":let YA=Ie(W,"group_join");YA&&(X.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,X.messageStubParameters=[YA.attrs.state]);break;case"created_membership_requests":X.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ee,pn:de}),"created",W.attrs.request_method];break;case"revoked_membership_requests":let $A=Mt(Ee,re);X.messageStubType=RA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ee,pn:de}),$A?"revoked":"rejected"];break}},We=async Ae=>{let[W]=ls(Ae),X=uA(Ae.attrs.from);if(!W){t.debug({from:X},"devices notification missing child, skipping");return}let re=W.tag,ne=W.attrs.device_hash,Se=PA(W,"device");if(Mt(X,I.creds.me.id)||Mt(X,I.creds.me.lid)){let de=Se.map(ye=>ye.attrs.jid);t.info({deviceJids:de},"got my own devices")}if(!Se.length){t.debug({from:X,tag:re},"no devices in notification, skipping");return}let Ee=[];for(let de of Se){let ye=de.attrs.jid;if(!ye)continue;let Je=yA(ye);if(!Je){t.debug({jid:ye},"failed to decode device jid, skipping");continue}Ee.push({jid:ye,user:Je.user,server:Je.server,device:Je.device})}Ee.length&&await g.mutex(async()=>{let de=new Map;for(let ye of Ee){let Je=de.get(ye.user)||[];Je.push(ye),de.set(ye.user,Je)}for(let[ye,Je]of de){if(re==="update"){t.debug({user:ye},`${ye}'s device list updated, dropping cached devices`),await s?.del(ye);continue}re==="remove"&&await y.deleteSession(Je.map(vA=>vA.jid));let IA=await s?.get(ye)||[];if(!IA.length){t.debug({user:ye,tag:re},"device list not cached, deferring to USync refresh");continue}let QA=new Set(Je.map(vA=>vA.device)),XA;switch(re){case"add":t.info({deviceHash:ne,count:Je.length},"devices added"),XA=[...IA.filter(vA=>!QA.has(vA.device)),...Je.map(vA=>({user:vA.user,server:vA.server,device:vA.device}))];break;case"remove":t.info({deviceHash:ne,count:Je.length},"devices removed"),XA=IA.filter(vA=>!QA.has(vA.device));break;default:t.debug({tag:re},"Unknown device list change tag");continue}XA.length===0?await s?.del(ye):await s?.set(ye,XA)}})},bA=async Ae=>{let W={},[X]=ls(Ae),re=Ae.attrs.type,ne=uA(Ae.attrs.from);switch(re){case"newsletter":await Ce(Ae);break;case"mex":await Ke(Ae);break;case"w:gp2":aA(Ae,X,W);break;case"mediaretry":let Se=Hae(Ae);c.emit("messages.media-update",[Se]);break;case"encrypt":await dA(Ae);break;case"devices":try{await We(Ae)}catch(so){t.error({error:so,node:Ae},"failed to handle devices notification")}break;case"server_sync":let Ee=Ie(Ae,"collection");if(Ee){let so=Ee.attrs.name;await T([so],!1)}break;case"picture":let de=Ie(Ae,"set"),ye=Ie(Ae,"delete");if(c.emit("contacts.update",[{id:uA(Ae?.attrs?.from)||(de||ye)?.attrs?.hash||"",imgUrl:de?"changed":"removed"}]),Fr(ne)){let so=de||ye;W.messageStubType=RA.GROUP_CHANGE_ICON,de&&(W.messageStubParameters=[de.attrs.id]),W.participant=so?.attrs.author,W.key={...W.key||{},participant:de?.attrs.author}}break;case"account_sync":if(X.tag==="disappearing_mode"){let so=+X.attrs.duration,Yl=+X.attrs.t;t.info({newDuration:so},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...I.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:so,ephemeralSettingTimestamp:Yl}}})}else if(X.tag==="blocklist"){let so=PA(X,"item");for(let{attrs:Yl}of so){let kb=[Yl.jid],vb=Yl.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:kb,type:vb})}}break;case"link_code_companion_reg":let Je=Ie(Ae,"link_code_companion_reg"),IA=lt(ua(Je,"link_code_pairing_ref")),QA=lt(ua(Je,"primary_identity_pub")),XA=lt(ua(Je,"link_code_pairing_wrapped_primary_ephemeral_pub")),vA=await DA(XA),YA=ur.sharedKey(I.creds.pairingEphemeralKeyPair.private,vA),$A=LU(32),Pe=LU(32),AA=yn(YA,32,{salt:Pe,info:"link_code_pairing_key_bundle_encryption_key"}),et=Buffer.concat([Buffer.from(I.creds.signedIdentityKey.public),QA,$A]),qr=LU(12),tr=nl(et,AA,qr,Buffer.alloc(0)),no=Buffer.concat([Pe,qr,tr]),Nb=ur.sharedKey(I.creds.signedIdentityKey.private,QA),Rb=Buffer.concat([YA,Nb,$A]);I.creds.advSecretKey=Buffer.from(yn(Rb,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:OA,type:"set",id:r.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:I.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:no},{tag:"companion_identity_public",attrs:{},content:I.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:IA}]}]}),I.creds.registered=!0,c.emit("creds.update",I.creds);break;case"privacy_token":await at(Ae);break}if(Object.keys(W).length)return W},Be=new Set,Re=(async()=>{try{let Ae=await GO(I.keys);for(let W of Ae)Be.add(W);t.debug({count:Be.size},"loaded tctoken index")}catch(Ae){t.warn({err:Ae?.message},"failed to load tctoken index")}})(),Le;async function MA(){Le&&(clearTimeout(Le),Le=void 0);let Ae=await Rh(I.keys,Be);return I.keys.set({tctoken:Ae})}function He(){Le&&clearTimeout(Le),Le=setTimeout(()=>{Le=void 0,MA().catch(Ae=>{t.warn({err:Ae?.message},"failed to save tctoken index")})},5e3)}function _A(Ae){Ae&&Ae!==eI&&!Be.has(Ae)&&(Be.add(Ae),He())}let at=async Ae=>{if(!Ie(Ae,"tokens"))return;let X=uA(Ae.attrs.from),ne=(Ae.attrs.sender_lid&&qA(uA(Ae.attrs.sender_lid))?uA(Ae.attrs.sender_lid):void 0)??await ks(X,V);t.debug({from:X,storageJid:ne},"processing privacy token notification"),await kh({result:Ae,fallbackJid:ne,keys:I.keys,getLIDForPN:V,onNewJidStored:_A})};async function DA(Ae){let W=lt(Ae),X=W.slice(0,32),re=await yD(I.creds.pairingCode,X),ne=W.slice(32,48),Se=W.slice(48,80);return F9(Se,re,ne)}function lt(Ae){if(Ae===void 0)throw new If.Boom("Invalid buffer",{statusCode:400});return Ae instanceof Buffer?Ae:Buffer.from(Ae)}let Ir=async(Ae,W)=>{let X=`${Ae}:${W}`;return(await ie.get(X)||0){let X=`${Ae}:${W}`,re=(await ie.get(X)||0)+1;await ie.set(X,re)},le=async(Ae,W,X,re)=>{let ne=Ae.remoteJid,Se=Ae.participant||ne,Ee=+X.attrs.count||1,de=W[0],ye=[];for(let Pe of W){let AA;if(P){let et=P.getRecentMessage(ne,Pe);et&&(AA=et.message,t.debug({jid:ne,id:Pe},"found message in retry cache"),P.markRetrySuccess(Pe))}AA||(AA=await e({...Ae,id:Pe}),AA&&(t.debug({jid:ne,id:Pe},"found message via getMessage"),P&&P.markRetrySuccess(Pe))),ye.push(AA)}let Je=!yA(Se)?.device,IA=y.jidToSignalProtocolAddress(Se),QA=!1,XA=iie(re);if(XA)try{await y.injectE2ESession({jid:Se,session:XA}),QA=!0,t.debug({participant:Se,retryCount:Ee},"injected session from retry receipt key bundle")}catch(Pe){t.warn({error:Pe,participant:Se},"failed to inject session from retry receipt")}if(!QA){let Pe=Oc(re,"registration",4);if(typeof Pe=="number"&&Number.isInteger(Pe)){let AA=await y.getSessionInfo(Se);AA&&AA.registrationId!==0&&AA.registrationId!==Pe&&(t.info({participant:Se,stored:AA.registrationId,received:Pe},"reg id mismatch on retry without bundle, deleting session"),await I.keys.set({session:{[IA]:null}}))}}let vA=2;if(de&&P){let Pe=await y.getSessionInfo(Se);Pe&&(Ee===vA?P.saveBaseKey(IA,de,Pe.baseKey):Ee>vA&&(P.hasSameBaseKey(IA,de,Pe.baseKey)&&(t.warn({participant:Se,retryCount:Ee},"base key collision on retry, forcing fresh session"),await I.keys.set({session:{[IA]:null}})),P.deleteBaseKey(IA,de)))}let YA=!1,$A="";if(A&&P&&Ee>1&&!QA)try{let Pe=await y.validateSession(Se),AA=P.shouldRecreateSession(Se,Pe.exists);YA=AA.recreate,$A=AA.reason,YA&&(t.debug({participant:Se,retryCount:Ee,reason:$A},"recreating session for outgoing retry"),await I.keys.set({session:{[IA]:null}}))}catch(Pe){t.warn({error:Pe,participant:Se},"failed to check session recreation for outgoing retry")}QA||await H([Se],!0),Fr(ne)&&await I.keys.set({"sender-key-memory":{[ne]:null}}),t.debug({participant:Se,sendToAll:Je,shouldRecreateSession:YA,recreateReason:$A,injectedFromBundle:QA},"prepared session for retry resend");for(let[Pe,AA]of ye.entries())if(W[Pe])if(AA&&await Ir(W[Pe],Se)){await UA(W[Pe],Se);let et={messageId:W[Pe]};Je?et.useUserDevicesCache=!1:et.participant={jid:Se,count:+X.attrs.count},await F(Ae.remoteJid,AA,et)}else t.debug({jid:Ae.remoteJid,id:W[Pe]},"recv retry request, but message not available")},Qe=async Ae=>{let{attrs:W,content:X}=Ae,re=W.from.includes("lid"),ne=Mt(W.participant||W.from,re?I.creds.me?.lid:I.creds.me?.id),Se=!ne||Fr(W.from)?W.from:W.recipient,Ee=!W.recipient||(W.type==="retry"||W.type==="sender")&&ne,de={remoteJid:Se,id:"",fromMe:Ee,participant:W.participant},ye=[W.id];if(Array.isArray(X)){let Je=PA(X[0],"item");ye.push(...Je.map(IA=>IA.attrs.id))}try{await Promise.all([Q.mutex(async()=>{let Je=W9(W.type);if(typeof Je<"u"&&(Je>=oe.WebMessageInfo.Status.SERVER_ACK||!ne))if(Fr(Se)||Bg(Se)){if(W.participant){let IA=Je===oe.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",ye.map(QA=>({key:{...de,id:QA},receipt:{userJid:uA(W.participant),[IA]:+W.t}})))}}else c.emit("messages.update",ye.map(IA=>({key:{...de,id:IA},update:{status:Je,messageTimestamp:Lr(+(W.t??0))}})));if(W.type==="retry"){de.participant=de.participant||W.from;let IA=Ie(Ae,"retry");if(ye[0]&&de.participant&&await Ir(ye[0],de.participant))if(de.fromMe)try{await UA(ye[0],de.participant),t.debug({attrs:W,key:de},"recv retry request"),await le(de,ye,IA,Ae)}catch(QA){t.error({key:de,ids:ye,trace:QA instanceof Error?QA.stack:"Unknown error"},"error in sending message again")}else t.info({attrs:W,key:de},"recv retry for not fromMe message");else t.info({attrs:W,key:de},"will not send message again, as sent too many times")}})])}finally{await he(Ae).catch(Je=>t.error({ackErr:Je},"failed to ack receipt"))}},be=async Ae=>{let W=Ae.attrs.from;try{await Promise.all([f.mutex(async()=>{let X=await bA(Ae);if(X){let re=Mt(Ae.attrs.participant||W,I.creds.me.id),{senderAlt:ne,addressingMode:Se}=wD(Ae);X.key={remoteJid:W,fromMe:re,participant:Ae.attrs.participant,participantAlt:ne,participantUsername:Ae.attrs.participant_username,addressingMode:Se,id:Ae.attrs.id,...X.key||{}},X.participant??(X.participant=Ae.attrs.participant),X.messageTimestamp=+Ae.attrs.t;let Ee=oe.WebMessageInfo.fromObject(X);await _(Ee,"append")}})])}finally{await he(Ae).catch(X=>t.error({ackErr:X},"failed to ack notification"))}},oA=async Ae=>{if(Ie(Ae,"enc")?.attrs.type==="msmsg"){t.debug({key:Ae.attrs.key},"ignored msmsg"),await he(Ae,cl.MissingMessageSecret);return}let X=!1;try{let{fullMessage:re,category:ne,author:Se,decrypt:Ee}=aX(Ae,I.creds.me.id,I.creds.me.lid||"",y,t),de=re.key.participantAlt||re.key.remoteJidAlt;if(de){let ye=yA(de)?.server,Je=re.key.participant||re.key.remoteJid;ye==="lid"?await y.lidMapping.getPNForLID(de)||(await y.lidMapping.storeLIDPNMappings([{lid:de,pn:Je}]),await y.migrateSession(Je,de)):(await y.lidMapping.storeLIDPNMappings([{lid:Je,pn:de}]),await y.migrateSession(de,Je))}await B.mutex(async()=>{if(await Ee(),re.key?.remoteJid&&re.key?.id&&re.message&&P&&P.addRecentMessage(re.key.remoteJid,re.key.id,re.message),re.messageStubType===oe.WebMessageInfo.StubType.CIPHERTEXT&&re.category!=="peer"){if(re?.messageStubParameters?.[0]===tX)return X=!0,he(Ae,cl.ParsingError);if(re.messageStubParameters?.[0]===DD){let Je=Ie(Ae,"unavailable")?.attrs?.type;if(Je==="bot_unavailable_fanout"||Je==="hosted_unavailable_fanout"||Je==="view_once_unavailable_fanout")return t.debug({msgId:re.key.id,unavailableType:Je},"skipping placeholder resend for excluded unavailable type"),X=!0,he(Ae);let IA=Ba()-Lr(re.messageTimestamp);if(IA>fse)return t.debug({msgId:re.key.id,messageAge:IA},"skipping placeholder resend for old message"),X=!0,he(Ae);let QA={remoteJid:re.key.remoteJid,fromMe:re.key.fromMe,id:re.key.id,participant:re.key.participant},XA={key:re.key,messageTimestamp:re.messageTimestamp,pushName:re.pushName,participant:re.participant,verifiedBizName:re.verifiedBizName};De(QA,XA).then(vA=>{vA&&vA!=="RESOLVED"&&(t.debug({msgId:re.key.id,requestId:vA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:re.key,update:{messageStubParameters:[DD,vA]}}]))}).catch(vA=>{t.warn({err:vA,msgId:re.key.id},"failed to request placeholder resend for unavailable message")}),X=!0,await he(Ae)}else{if(Bg(re.key.remoteJid)){let ye=Ba()-Lr(re.messageTimestamp);if(ye>Bse)return t.debug({msgId:re.key.id,messageAge:ye,remoteJid:re.key.remoteJid},"skipping retry for expired status message"),X=!0,he(Ae)}t.debug("[handleMessage] Attempting retry request for failed decryption"),await ee.mutex(async()=>{try{if(!d.isOpen){t.debug({node:Ae},"Connection closed, skipping retry");return}let ye=Ie(Ae,"enc");await je(Ae,!ye),o&&await zu(o)}catch(ye){t.error({err:ye},"Failed to send retry")}X=!0,await he(Ae,cl.UnhandledError)})}}else if(P&&re.key.id&&P.cancelPendingPhoneRequest(re.key.id),wc(re.key.remoteJid))X=!0,await he(Ae),t.debug({key:re.key},"processed newsletter message without receipts");else{let Je,IA=re.key.participant;if(ne==="peer"?Je="peer_msg":re.key.fromMe?(Je="sender",(qA(re.key.remoteJid)||qA(re.key.remoteJidAlt))&&(IA=Se)):Ne||(Je="inactive"),X=!0,await q(re.key.remoteJid,IA,[re.key.id],Je),_O(re.message)){let XA=uA(re.key.remoteJid);await q(XA,void 0,[re.key.id],"hist_sync")}}Xie(re,I.creds.me.id,I.creds.me.lid),await _(re,Ae.attrs.offline?"append":"notify")})}catch(re){t.error({error:re,node:Bn(Ae)},"error in handling message"),X||await he(Ae,cl.UnhandledError).catch(ne=>t.error({ackErr:ne},"failed to ack message after error"))}},lA=async Ae=>{try{let{attrs:W}=Ae,[X]=ls(Ae);if(!X)throw new If.Boom("Missing call info in call node");let re=X9(X),ne=X.attrs["call-id"],Se=X.attrs.from||X.attrs["call-creator"],Ee={chatId:W.from,from:Se,callerPn:X.attrs.caller_pn,id:ne,date:new Date(+W.t*1e3),offline:!!W.offline,status:re};if(re==="relaylatency"){let ye=X.attrs.latency||X.attrs.latency_ms||X.attrs["latency-ms"],Je=ye?Number(ye):void 0;Number.isFinite(Je)&&(Ee.latencyMs=Je)}re==="offer"&&(Ee.isVideo=!!Ie(X,"video"),Ee.isGroup=X.attrs.type==="group"||!!X.attrs["group-jid"],Ee.groupJid=X.attrs["group-jid"],await Te.set(Ee.id,Ee));let de=await Te.get(Ee.id);de&&(Ee.isVideo=de.isVideo,Ee.isGroup=de.isGroup,Ee.callerPn=Ee.callerPn||de.callerPn),(re==="reject"||re==="accept"||re==="timeout"||re==="terminate")&&await Te.del(Ee.id),c.emit("call",[Ee])}catch(W){t.error({error:W,node:Bn(Ae)},"error in handling call")}finally{await he(Ae).catch(W=>t.error({ackErr:W},"failed to ack call"))}},FA=async({attrs:Ae})=>{let W={remoteJid:Ae.from,fromMe:!0,id:Ae.id};if(Ae.error){let X=Ae.error===String(cl.SenderReachoutTimelocked);if(Ae.error===UG.MessageAccountRestriction){t.warn({msgId:Ae.id,from:Ae.from},"error 463: account restricted or missing tctoken for contact");let re=Ae.from;re&&!oo.has(re)&&(oo.add(re),(async()=>{try{let ne=y.lidMapping.getPNForLID.bind(y.lidMapping),Se=await ks(re,V),Ee=await XB(re,r.serverProps.lidTrustedTokenIssueToLid,V,ne),de=await U([Ee],Ba());await kh({result:de,fallbackJid:Se,keys:I.keys,getLIDForPN:V,onNewJidStored:_A}),t.debug({from:re},"completed 463 token recovery issuance")}catch(ne){t.debug({from:re,err:ne?.message},"failed 463 token recovery issuance")}finally{oo.delete(re)}})())}else Ae.error===UG.SmaxInvalid?t.warn({msgId:Ae.id,from:Ae.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):X?(await N().catch(re=>t.warn({err:re},"failed to fetch reachout timelock")),t.warn({attrs:Ae},"received error in ack")):t.warn({attrs:Ae},"received error in ack");c.emit("messages.update",[{key:W,update:{status:Td.ERROR,messageStubParameters:X?[Ae.error,rX]:[Ae.error]}}])}},Ut=async(Ae,W,X)=>{c.buffer(),await re(),c.flush();function re(){return X(Ae,!1).catch(ne=>R(ne,W))}},st=Hse(new Map([["message",oA],["call",lA],["receipt",Qe],["notification",be]]),{isWsOpen:()=>d.isOpen,onUnexpectedError:R,yieldToEventLoop:()=>new Promise(Ae=>setImmediate(Ae))}),fr=async(Ae,W,X,re)=>{let ne=W.attrs.from,Se=ne;if(Ae==="receipt"&&ne){let de=W.attrs,ye=de.from.includes("lid");Se=!Mt(de.participant||de.from,ye?I.creds.me?.lid:I.creds.me?.id)||Fr(de.from)?de.from:de.recipient}if(Se&&Se!==OA&&a(Se)){await he(W,Ae==="message"?cl.UnhandledError:void 0);return}!!W.attrs.offline?st.enqueue(Ae,W):await Ut(W,X,re)};d.on("CB:message",async Ae=>{await fr("message",Ae,"processing message",oA)}),d.on("CB:call",async Ae=>{await fr("call",Ae,"handling call",lA)}),d.on("CB:receipt",async Ae=>{await fr("receipt",Ae,"handling receipt",Qe)}),d.on("CB:notification",async Ae=>{await fr("notification",Ae,"handling notification",be)}),d.on("CB:ack,class:message",Ae=>{FA(Ae).catch(W=>R(W,"handling bad ack"))}),c.on("call",async([Ae])=>{if(Ae&&(Ae.status==="timeout"||Ae.status==="offer"&&Ae.isGroup)){let W={key:{remoteJid:Ae.chatId,id:Ae.id,fromMe:!1},messageTimestamp:Ba(Ae.date)};Ae.status==="timeout"?Ae.isGroup?W.messageStubType=Ae.isVideo?RA.CALL_MISSED_GROUP_VIDEO:RA.CALL_MISSED_GROUP_VOICE:W.messageStubType=Ae.isVideo?RA.CALL_MISSED_VIDEO:RA.CALL_MISSED_VOICE:W.message={call:{callKey:Buffer.from(Ae.id)}};let X=oe.WebMessageInfo.fromObject(W);await _(X,Ae.offline?"append":"notify")}});let Ar=0,oo=new Set;c.on("connection.update",({isOnline:Ae,connection:W})=>{if(typeof Ae<"u"&&(Ne=Ae,t.trace(`sendActiveReceipts set to "${Ne}"`)),W==="close"&&Le){clearTimeout(Le),Le=void 0;try{Promise.resolve(MA()).catch(()=>{})}catch{}}if(Ae){let X=Date.now(),re=1440*60*1e3;X-Ar>=re&&(Ar=X,Gi())}}),z(()=>{!n.msgRetryCounterCache&&ie.close&&ie.close(),!n.callOfferCache&&Te.close&&Te.close(),se.close(),Ne=!1});async function Gi(){try{await Re;let Ae=await GO(I.keys),W=new Set(Be);for(let de of Ae)W.add(de);if(!W.size)return;let X=[...W],re=await I.keys.get("tctoken",X),ne={},Se=new Set,Ee=0;for(let de of X){let ye=re[de];if(!ye){Ee++;continue}let Je=!!ye.token?.length,IA=Je&&kl(ye.timestamp),QA=ye.senderTimestamp!==void 0,XA=QA&&kl(ye.senderTimestamp),vA=Je&&!IA,YA=QA&&!XA;!vA&&!YA?(ne[de]=null,Ee++):IA&&YA?(ne[de]={token:Buffer.alloc(0),senderTimestamp:ye.senderTimestamp},Se.add(de),Ee++):Se.add(de)}if(Ee===0)return;await I.keys.set({tctoken:{...ne,[eI]:{token:Buffer.from(JSON.stringify([...Se]))}}}),Be.clear();for(let de of Se)Be.add(de);t.debug({mutated:Ee,remaining:Se.size},"pruned expired tctokens")}catch(Ae){t.warn({err:Ae?.message},"failed to prune expired tctokens")}}return{...r,sendMessageAck:he,sendRetryRequest:je,rejectCall:Ze,fetchMessageHistory:fe,requestPlaceholderResend:De,messageRetryManager:P}};var zse=n=>{let t=qse(n),{authState:o,query:i,waUploadToServer:e}=t,a=async f=>{let Q=[],y=["address","email","description"];return Q.push(...y.filter(_=>f[_]!==void 0&&f[_]!==null).map(_=>({tag:_,attrs:{},content:f[_]}))),f.websites!==void 0&&Q.push(...f.websites.map(_=>({tag:"website",attrs:{},content:_}))),f.hours!==void 0&&Q.push({tag:"business_hours",attrs:{timezone:f.hours.timezone},content:f.hours.days.map(_=>{let T={tag:"business_hours_config",attrs:{day_of_week:_.day,mode:_.mode}};return _.mode==="specific_hours"?{...T,attrs:{...T.attrs,open_time:_.openTimeInMinutes,close_time:_.closeTimeInMinutes}}:T})}),await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:Q}]})},A=async f=>{let{fileSha256:Q,filePath:y}=await SO(f,"biz-cover-photo"),m=Q.toString("base64"),{meta_hmac:_,fbid:T,ts:R}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(T),op:"update",token:_,ts:String(R)}}]}]}),T},r=async f=>await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:f}}]}]}),s=async({jid:f,limit:Q,cursor:y})=>{f=f||o.creds.me?.id,f=uA(f);let m=[{tag:"limit",attrs:{},content:Buffer.from((Q||10).toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}];y&&m.push({tag:"after",attrs:{},content:y});let _=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:f,allow_shop_source:"true"},content:m}]});return Ose(_)},g=async(f,Q=51)=>{f=f||o.creds.me?.id,f=uA(f);let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:f},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return bse(y)},c=async(f,Q)=>{let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:f},content:[{tag:"image_dimensions",attrs:{},content:[{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]},{tag:"token",attrs:{},content:Buffer.from(Q)}]}]});return Mse(y)},I=async(f,Q)=>{Q=await RU(Q,e);let y=NU(f,Q),m=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_edit",attrs:{v:"1"},content:[y,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),_=Ie(m,"product_catalog_edit"),T=Ie(_,"product");return gf(T)},d=async f=>{f.isHidden=!!f.isHidden,f=await RU(f,e);let Q=NU(void 0,f),y=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[Q,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=Ie(y,"product_catalog_add"),_=Ie(m,"product");return gf(_)},B=async f=>{let Q=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:f.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(Ie(Q,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...t,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:d,productDelete:B,productUpdate:I,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:r}};var Vse=n=>{let t=zse(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(I,d,B)=>e({tag:"iq",attrs:{type:d,xmlns:"w:g2",to:I},content:B}),r=async I=>{let d=await A(I,"get",[{tag:"query",attrs:{request:"interactive"}}]);return UU(d)},s=async()=>{let I=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),d={},B=Ie(I,"communities");if(B){let f=PA(B,"community");for(let Q of f){let y=UU({tag:"result",attrs:{},content:[Q]});d[y.id]=y}}return t.ev.emit("groups.update",Object.values(d)),d};async function g(I){of.info({node:I},"parseGroupResult");let d=Ie(I,"group");if(d)try{of.info({groupNode:d},"groupNode");let B=await t.groupMetadata(`${d.attrs.id}@g.us`);return B||c.empty()}catch(B){return console.error("Error parsing group metadata:",B),c.empty()}return c.empty()}let c={empty:()=>null,of:I=>I!==null?{value:I}:null};return t.ws.on("CB:ib,,dirty",async I=>{let{attrs:d}=Ie(I,"dirty");d.type==="communities"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,communityMetadata:r,communityCreate:async(I,d)=>{let B=FG().substring(0,12),f=await A("@g.us","set",[{tag:"create",attrs:{subject:I},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(d||"","utf-8")}]},{tag:"parent",attrs:{default_membership_approval_mode:"request_required"}},{tag:"allow_non_admin_sub_group_creation",attrs:{}},{tag:"create_general_chat",attrs:{}}]}]);return await g(f)},communityCreateGroup:async(I,d,B)=>{let f=Ur(),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:I,key:f},content:[...d.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(Q)},communityLeave:async I=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:I}}]}])},communityUpdateSubject:async(I,d)=>{await A(I,"set",[{tag:"subject",attrs:{},content:Buffer.from(d,"utf-8")}])},communityLinkGroup:async(I,d)=>{await A(d,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}]}])},communityUnlinkGroup:async(I,d)=>{await A(d,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}])},communityFetchLinkedGroups:async I=>{let d=I,B=!1,f=await t.groupMetadata(I);f.linkedParent?d=f.linkedParent:B=!0;let Q=await A(d,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=Ie(Q,"sub_groups");if(m){let _=PA(m,"group");for(let T of _)y.push({id:T.attrs.id?Er(T.attrs.id,"g.us"):void 0,subject:T.attrs.subject||"",creation:T.attrs.creation?Number(T.attrs.creation):void 0,owner:T.attrs.creator?uA(T.attrs.creator):void 0,size:T.attrs.size?Number(T.attrs.size):void 0})}return{communityJid:d,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async I=>{let d=await A(I,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=Ie(d,"membership_approval_requests");return PA(B,"membership_approval_request").map(Q=>Q.attrs)},communityRequestParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:d.map(_=>({tag:"participant",attrs:{jid:_}}))}]}]),Q=Ie(f,"membership_requests_action"),y=Ie(Q,B);return PA(y,"participant").map(_=>({status:_.attrs.error||"200",jid:_.attrs.jid}))},communityParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:d.map(m=>({tag:"participant",attrs:{jid:m}}))}]),Q=Ie(f,B);return PA(Q,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(I,d)=>{let f=(await r(I)).descId??null;await A(I,"set",[{tag:"description",attrs:{...d?{id:FG()}:{delete:"true"},...f?{prev:f}:{}},content:d?[{tag:"body",attrs:{},content:Buffer.from(d,"utf-8")}]:void 0}])},communityInviteCode:async I=>{let d=await A(I,"get",[{tag:"invite",attrs:{}}]);return Ie(d,"invite")?.attrs.code},communityRevokeInvite:async I=>{let d=await A(I,"set",[{tag:"invite",attrs:{}}]);return Ie(d,"invite")?.attrs.code},communityAcceptInvite:async I=>{let d=await A("@g.us","set",[{tag:"invite",attrs:{code:I}}]);return Ie(d,"community")?.attrs.jid},communityRevokeInviteV4:async(I,d)=>!!await A(I,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:d}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(I,d)=>{I=typeof I=="string"?{remoteJid:I}:I;let B=await A(d.groupJid,"set",[{tag:"accept",attrs:{code:d.inviteCode,expiration:d.inviteExpiration.toString(),admin:I.remoteJid}}]);return I.id&&(d=oe.Message.GroupInviteMessage.fromObject(d),d.inviteExpiration=0,d.inviteCode="",i.emit("messages.update",[{key:I,update:{message:{groupInviteMessage:d}}}])),await a({key:{remoteJid:d.groupJid,id:Ur(t.user?.id),fromMe:!1,participant:I.remoteJid},messageStubType:RA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:I.remoteJid,messageTimestamp:Ba()},"notify"),B.attrs.from}),communityGetInviteInfo:async I=>{let d=await A("@g.us","get",[{tag:"invite",attrs:{code:I}}]);return UU(d)},communityToggleEphemeral:async(I,d)=>{let B=d?{tag:"ephemeral",attrs:{expiration:d.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(I,"set",[B])},communitySettingUpdate:async(I,d)=>{await A(I,"set",[{tag:d,attrs:{}}])},communityMemberAddMode:async(I,d)=>{await A(I,"set",[{tag:"member_add_mode",attrs:{},content:d}])},communityJoinApprovalMode:async(I,d)=>{await A(I,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:d}}]}])},communityFetchAllParticipating:s}},UU=n=>{let t=Ie(n,"community"),o=Ie(t,"description"),i,e;o&&(i=jA(o,"body"),e=o.attrs.id);let a=t.attrs.id?.includes("@")?t.attrs.id:Er(t.attrs.id||"","g.us"),A=Ie(t,"ephemeral")?.attrs.expiration,r=jA(t,"member_add_mode")==="all_member_add";return{id:a,subject:t.attrs.subject||"",subjectOwner:t.attrs.s_o,subjectTime:Number(t.attrs.s_t||0),size:PA(t,"participant").length,creation:Number(t.attrs.creation||0),owner:t.attrs.creator?uA(t.attrs.creator):void 0,desc:i,descId:e,linkedParent:Ie(t,"linked_parent")?.attrs.jid||void 0,restrict:!!Ie(t,"locked"),announce:!!Ie(t,"announcement"),isCommunity:!!Ie(t,"parent"),isCommunityAnnounce:!!Ie(t,"default_sub_community"),joinApprovalMode:!!Ie(t,"membership_approval_mode"),memberAddMode:r,participants:PA(t,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:jA(t,"addressing_mode")}};var ZVe=n=>{let t={...yse,...n};return Vse(t)},Wse=ZVe;var Zse=Wse;var XVe=Object.freeze({key:"whatsapp",label:"WhatsApp",get connectionLabel(){return D(" Web \u5173\u8054\u8BBE\u5907")},reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),Db=class extends xn{constructor(t){super({...t,descriptor:XVe})}};import{chmod as Xse,mkdir as $Ve,readdir as eWe}from"node:fs/promises";var AWe=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),tWe=6e4;function $se(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function rWe(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function aWe(n){let t=n;if(typeof t=="string"){if(!/^\d+$/.test(t))return null;t=Number(t)}else typeof t=="bigint"?t=Number(t):t&&typeof t=="object"&&(t=Number(t.valueOf()));return Number.isFinite(t)&&t>=0?t*1e3:null}async function HU(n){await $Ve(n,{recursive:!0,mode:448}),await Xse(n,448);let t=await eWe(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(t.filter(o=>o.isFile()).map(o=>Xse(`${n}/${o.name}`,384).catch(()=>{})))}function iWe(n,t){let o=n.user??t.creds.me,i=uA(o?.id);if(!/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i??""))throw new Error("WhatsApp did not return a valid linked account");return{accountJid:i,name:typeof o?.name=="string"&&o.name.trim()?o.name.trim().slice(0,100):D("WhatsApp\u673A\u5668\u4EBA")}}async function wb({authDir:n,onQr:t,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=Zse,loadAuthState:r=Vie}={}){if(!n||typeof t!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await HU(n);let s=Date.now(),{state:g,saveCreds:c}=await r(n),I=g.keys.set.bind(g.keys);g.keys.set=async J=>{await I(J),await HU(n)};let d=!1,B=!1,f,Q,y=Promise.resolve(),m=null,_=0,T=null,R=new Promise((J,x)=>{f=J,Q=x}),H=J=>{B||(B=!0,Q(J))},j=async()=>{d||(d=!0,_+=1,H($se()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},F=async()=>{d||(d=!0,_+=1,H($se()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let J=++_,x=!1,P=A({auth:g,browser:UO.macOS("DeepSeek Harness"),logger:AWe,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=P;let z=()=>{!x||!g.creds.me||B||y.then(()=>{d||B||J!==_||!x||!g.creds.me||(B=!0,f(iWe(P,g)))}).catch(U=>H(U))};P.ev.on("creds.update",()=>{d||J!==_||(y=y.then(async()=>{await c(),await HU(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),z())}),P.ev.on("connection.update",U=>{if(!(d||J!==_)&&(typeof U.qr=="string"&&U.qr&&t(U.qr),U.connection==="open"&&(x=!0,z()),U.connection==="close")){let N=rWe(U.lastDisconnect?.error);if(N===Zt.restartRequired){T??=y.then(async()=>{d||J!==_||(await P.end(void 0).catch(()=>{}),!(d||J!==_)&&q())}).catch(ee=>H(ee)).finally(()=>{T=null});return}let k=N===Zt.loggedOut,V=Object.assign(new Error(k?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:k?"logged-out":"connection-closed"});B?i?.({error:V,loggedOut:k}):H(V)}}),P.ev.on("messages.upsert",({messages:U,type:N})=>{if(!(d||J!==_||N!=="notify"&&N!=="append"||typeof o!="function"))for(let k of Array.isArray(U)?U:[]){if(N==="append"){let V=aWe(k?.messageTimestamp);if(V===null||V{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await j():e.addEventListener("abort",()=>void j(),{once:!0})),Object.freeze({get socket(){return m},ready:R,close:j,logout:F})}var xU=new Set(["image/jpeg","image/png","image/webp","image/gif"]),nWe=5*1024*1024,KU=15e3,YU=12e4,sWe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],gWe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]);function cWe(n){let t=n;for(let o=0;o<5&&t&&typeof t=="object";o+=1){let i=sWe.find(e=>t[e]?.message);if(!i)return!1;if(gWe.has(i))return!0;t=t[i].message}return!1}function IWe(n){return n?.extendedTextMessage?.contextInfo??n?.imageMessage?.contextInfo??n?.videoMessage?.contextInfo??n?.documentMessage?.contextInfo??null}function lWe(n){return n?.conversation??n?.extendedTextMessage?.text??n?.imageMessage?.caption??n?.videoMessage?.caption??n?.documentMessage?.caption??""}function tge(n){if(Number.isSafeInteger(n)&&n>=0)return n;let t;try{t=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(t)&&t>=0?t:void 0}async function pWe(n,t,{signal:o,maxBytes:i=nWe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(KU),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>t(n,"stream",{options:{signal:a}})),r=await new Promise((I,d)=>{let B=!1,f=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",Q),y(m),!0),Q=()=>f(d,a.reason);a.addEventListener("abort",Q,{once:!0}),A.then(y=>{f(I,y)||y?.destroy?.()},y=>f(d,y)),a.aborted&&Q()}).catch(I=>{throw o?.aborted?o.reason??I:e.aborted?new ut("image-download-failed",`WhatsApp image download timed out after ${KU} ms`,D("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}),s=[],g=0,c=()=>r?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let I of r){a.throwIfAborted();let d=Buffer.from(I);if(g+=d.length,g>i)throw r.destroy?.(),new ut("image-too-large",`WhatsApp image exceeded ${i} bytes`,D("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));s.push(d)}}catch(I){throw o?.aborted?o.reason??I:e.aborted?new ut("image-download-failed",`WhatsApp image stream timed out after ${KU} ms`,D("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function dWe(n,t,o,{viewOnce:i=!1}={}){let e,a;if(!i&&t?.imageMessage&&t.imageMessage.viewOnce!==!0)e=t.imageMessage;else if(t?.documentMessage){let r=typeof t.documentMessage.mimetype=="string"?t.documentMessage.mimetype.toLowerCase():"";if(!xU.has(r))return null;e=t.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return xU.has(A)?{name:a,mediaType:A,size:tge(e.fileLength),load:r=>pWe(n,o,r)}:null}function hWe(n,t,o){let i=t?.documentMessage;if(!i)return null;let e=typeof i.mimetype=="string"&&i.mimetype?i.mimetype.toLowerCase():void 0;return xU.has(e)?null:{name:typeof i.fileName=="string"&&i.fileName?i.fileName:"whatsapp-file",...e?{mediaType:e}:{},size:tge(i.fileLength),async load({signal:a}={}){a?.throwIfAborted();let A=await o(n,"stream",{options:{signal:a}});return a?.throwIfAborted(),{stream:A}}}}function EWe({socket:n,logger:t=console,download:o=i2}={}){if(typeof o!="function")throw new TypeError("WhatsApp media downloader is required");return typeof n?.updateMediaMessage!="function"?o:(i,e,a)=>o(i,e,a,{logger:t,reuploadRequest:A=>n.updateMediaMessage(A)})}function CWe(n,t,{download:o=i2}={}){let i=typeof n?.key?.remoteJid=="string"?n.key.remoteJid:"",e=typeof n?.key?.remoteJidAlt=="string"?n.key.remoteJidAlt:"",a=typeof n?.key?.id=="string"?n.key.id:"";if(!i||!a||i==="status@broadcast"||i.endsWith("@newsletter"))return null;let A=i.endsWith("@g.us"),r=n.key.fromMe===!0,s=r&&!A&&[i,e].some(_=>_&&Mt(_,t));if(r&&!s&&!A)return null;let g=r?t:A?n.key.participant:i,c=A&&!r?n.key.participantAlt:e;if(typeof g!="string"||!g)return null;let I=cWe(n.message),d=Sa(n.message),B=IWe(d),f=Array.isArray(B?.mentionedJid)&&B.mentionedJid.some(_=>Mt(_,t)),Q=typeof B?.participant=="string"&&Mt(B.participant,t),y=dWe(n,d,o,{viewOnce:I}),m=hWe(n,d,o);return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,senderAlternateId:typeof c=="string"?c:"",senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:lWe(d),plainText:typeof d?.conversation=="string"||typeof d?.extendedTextMessage?.text=="string",images:y?[y]:[],files:m?[m]:[],addressed:!A||r||f||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s},reactionTarget:{jid:i,key:n.key}}}function uWe(n,{accessMode:t=md.selfOnly,allowedNumbers:o=new Set}={}){if(t===md.open)return!0;if(n?.kind!=="direct")return!1;if(n.selfChat===!0)return!0;if(t!==md.privateAllowlist||!(o instanceof Set))return!1;let i=[n.senderId,n.senderAlternateId].filter(e=>typeof e=="string"&&e.endsWith("@s.whatsapp.net"));return[...o].some(e=>i.some(a=>Mt(a,`${e}@s.whatsapp.net`)))}var jU=class{#e=new Map;has(t){return this.#t(),this.#e.has(t)}remember(t){this.#A(t)}reserve(t){this.#A(t)}#A(t){if(!(typeof t!="string"||!t))for(this.#t(),this.#e.set(t,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#t(){let t=Date.now();for(let[o,i]of this.#e)i>t||this.#e.delete(o)}};function rge(n){return n?.reason??new DOMException("The operation was aborted.","AbortError")}function Age(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,rge(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function BWe(n){if(n?.code==="artifact-delivery-uncertain")return n;let t=new Error("WhatsApp could not confirm artifact delivery.");return t.code="artifact-delivery-uncertain",t.cause=n,t}function fWe(n){if(n?.code?.startsWith?.("artifact-"))return n;let t=n?.output?.statusCode??n?.data?.statusCode??n?.statusCode,o;if(t===401||t===403?o="artifact-permission-required":t===413?o="artifact-too-large":t===429?o="artifact-rate-limited":[400,404,405,406,410,415,422].includes(t)&&(o="artifact-provider-rejected"),!o)return BWe(n);let i=new Error("WhatsApp rejected artifact delivery.");return i.code=o,i.cause=n,i}var JU=class{#e;#A;#t;#r;#a=new Map;constructor(t,o,{signal:i,mediaUploadTimeoutMs:e=YU}={}){this.#e=t,this.#A=o,this.#t=i,this.#r=e}async sendText(t,o){await this.#s(t.jid);let i=[];for(let[e,a]of Yn(o,4e3).entries()){let A=ege(10).toString("hex").toUpperCase(),r={...e===0&&t.quoted?{quoted:t.quoted}:{},messageId:A};typeof this.#A.reserve=="function"?this.#A.reserve(A):this.#A.remember(A);let s=await this.#e.sendMessage(t.jid,{text:a},r);this.#A.remember(s?.key?.id),typeof s?.key?.id=="string"&&s.key.id&&i.push(s.key.id)}return{providerMessageIds:i}}async sendFile(t,o){return this.#c(t,o,{document:o.bytes,mimetype:o.mediaType??"application/octet-stream",fileName:o.fileName},"file")}async sendImage(t,o){return this.#c(t,o,{image:o.bytes,mimetype:o.mediaType??"image/jpeg"},"image")}async addReaction(t,o,{signal:i}={}){if(typeof o!="string"||!o.trim())throw new TypeError("A WhatsApp reaction emoji is required");let e=o.trim();return await this.#i(t,e,i),e}removeReaction(t,o,{signal:i}={}){return this.#i(t,"",i)}async#i(t,o,i){if(typeof t?.jid!="string"||!t.jid||!t.key?.id)throw new TypeError("A WhatsApp reaction target is required");let e=i??this.#t;e?.throwIfAborted();let a=ege(10).toString("hex").toUpperCase();typeof this.#A.reserve=="function"?this.#A.reserve(a):this.#A.remember(a);let A=this.#e.sendMessage(t.jid,{react:{text:o,key:t.key}},{messageId:a}),r=await Age(A,e);return this.#A.remember(r?.key?.id),r}async#c(t,o,i,e){this.#t?.throwIfAborted(),await this.#s(t.jid),this.#t?.throwIfAborted();let a=typeof o.deliveryKey=="string"&&o.deliveryKey?o.deliveryKey:o.artifactId,A=e==="image"?`${a}:image`:a,r=typeof A=="string"&&A?oWe("sha256").update(A).digest("hex").slice(0,20).toUpperCase():void 0,s={...t.quoted?{quoted:t.quoted}:{},...r?{messageId:r}:{},mediaUploadTimeoutMs:this.#r};this.#A.remember(r);let g;try{let c=this.#e.sendMessage(t.jid,i,s);An(o,c);let I=AbortSignal.timeout(this.#r),d=this.#t?AbortSignal.any([this.#t,I]):I;g=await Age(c,d)}catch(c){throw this.#t?.aborted?rge(this.#t):fWe(c)}return this.#t?.throwIfAborted(),this.#A.remember(g?.key?.id),g}async sendTyping(t){!t.selfChat&&t.quoted?.key&&await this.#e.readMessages([t.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",t.jid),await this.#s(t.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",t.jid).catch(()=>{this.#s(t.jid)})},2e4);o.unref?.(),this.#a.set(t.jid,o)}async close(){let t=[...this.#a.keys()];await Promise.allSettled(t.map(o=>this.#s(o)))}async#s(t,o=!0){let i=this.#a.get(t);i&&clearInterval(i),this.#a.delete(t),o&&await this.#e.sendPresenceUpdate("paused",t).catch(()=>{})}};function QWe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Yi()}}var lf=class{#e;#A;#t;#r;#a;#i;#c;#s;#I;#o;#n;#g=QWe();#l=null;#p=null;#d=null;#h=null;#E=null;constructor({config:t,authDir:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:r=3e4,mediaUploadTimeoutMs:s=YU,createSession:g=wb}){if(!t||!o||!i||!e||typeof g!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");if(this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#a=a,this.#i=A,this.#c=r,!Number.isSafeInteger(s)||s<=0)throw new TypeError("mediaUploadTimeoutMs must be a positive safe integer");this.#s=Math.min(s,YU),this.#n=g,this.setAccessPolicy(t)}get status(){return structuredClone(this.#g)}setAccessPolicy(t){let o=pg(t);return this.#I=o.accessMode,this.#o=new Set(o.allowedNumbers),this.#e={...this.#e,...o},o}async start(){return this.#g.ready&&this.#p?this.status:this.#E?this.#E:(this.#E=this.#B().finally(()=>{this.#E=null}),this.#E)}async#B(){await this.stop(),this.#g.startedAt=new Date().toISOString(),this.#g.connectionState="connecting",this.#g.lastError=null,await this.#t.ensureRunning(),this.#g.harnessReachable=!0;let t=new AbortController;this.#l=t;let o=new jU,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#n({authDir:this.#A,signal:t.signal,logger:this.#a,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async(c,I)=>{let d=CWe(c,this.#e.accountJid,{download:EWe({socket:I?.socket,logger:this.#a})});if(!(!d||o.has(d.providerMessageId)||!this.#h)){if(this.#g.lastCheckedAt=Date.now(),!uWe(d,{accessMode:this.#I,allowedNumbers:this.#o})){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}await this.#h.accept(d)}},onDisconnect:({error:c})=>{t.signal.aborted||(this.#g.ready=!1,this.#g.connectionState="failed",this.#g.lastError=c?.message??"WhatsApp Web connection closed")}});this.#p=a;let A,r=await Promise.race([a.ready,e,new Promise((c,I)=>{A=setTimeout(()=>I(new Error("WhatsApp Web did not connect in time")),this.#c)})]).finally(()=>clearTimeout(A));if(!Mt(r.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new JU(a.socket,o,{signal:t.signal,mediaUploadTimeoutMs:this.#s});this.#d=s,this.#h=new Db({bot:s,harness:this.#t,state:this.#r,status:this.#g,logger:this.#a,replyTimeoutMs:this.#i,signal:t.signal});let g=Date.now();return this.#g.ready=!0,this.#g.connectionState="connected",this.#g.lastCheckedAt=g,this.#g.lastConnectedAt=g,this.status}catch(a){throw this.#g.ready=!1,this.#g.connectionState="failed",this.#g.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#p?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(t){if(!this.#g.ready||!this.#d){let o=new Error(D("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw o.code="test-target-unavailable",o}if(typeof t!="string"||!t.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#d.sendText({jid:this.#e.accountJid,selfChat:!0},t),{sent:!0}}async stop(){let t=this.#p,o=this.#d,i=this.#h;return this.#l?.abort(),this.#l=null,this.#p=null,this.#d=null,this.#h=null,await o?.close().catch(()=>{}),await t?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#g.ready=!1,this.#g.connectionState="idle",this.status}};var DWe=/^[a-f0-9-]{36}$/;function wWe(n){let t=Lg(n.dshHome??process.env.DSH_HOME??zh(SWe(),".dsh")),o=Lg(n.dataDir??zh(t,"integrations","dsh-whatsapp")),i=Lg(n.authDir??zh(o,"auth")),e=a=>{if(!DWe.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return Lg(i,a)};return{config:Lg(n.configPath??zh(o,"config.json")),bots:Lg(n.botsDir??zh(o,"bots")),workspaces:Lg(n.workspacesPath??zh(o,"workspaces.json")),authPath:e}}async function qU(n,t={},o={}){let i=$r(n,t),e=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,a=()=>_a(n),A=o.ConfigStore??HS,r=o.StateStore??xS,s=o.HarnessClient??KS,g=o.Controller??bu,c=o.Runtime??lf,I=o.createSession??wb,d=o.createConnectionSupervisor??sp,B=wWe(t),f=await new A(B.config).load(),Q=Lg(t.workspace??process.cwd()),y=o.WorkspaceStore??Xr,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(k=>k.botId)),await Promise.all(_.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Ra(f,{workspaces:m}):f,R=new Map,H=k=>Lg(B.bots,k,"state.json"),j=async k=>{let V=R.get(k);return V||(V=await new r(H(k)).load(),R.set(k,V)),V},F=Pa(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:J,fileIngressExecutor:x}=Ga(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),P=new s({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...F?{commandExecutor:F}:{},...q?{controlExecutor:q}:{},...J?{sessionMaintenanceExecutor:J}:{},...x?{fileIngressExecutor:x}:{}}),z=new g({configStore:T,authPath:B.authPath,createSession:I,logger:e,createRuntime:async({botId:k,config:V,authDir:ee})=>{let ie=await j(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset});let Te=ka(P,{botId:k,workspaces:m,state:ie,agentPresetCatalog:a});return new c({config:V,authDir:ee,harness:Te.harness,state:Te.state,replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??3e4,createSession:I,logger:{error:(...se)=>e.error?.(`[${k}]`,...se),warn:(...se)=>e.warn?.(`[${k}]`,...se),info:(...se)=>e.info?.(`[${k}]`,...se),debug:(...se)=>e.debug?.(`[${k}]`,...se)}})},deleteAuth:k=>yWe(B.authPath(k),{recursive:!0,force:!0}),deleteState:async({botId:k})=>{let V=R.get(k);if(R.delete(k),V&&typeof V.remove=="function")await V.remove();else try{await mWe(H(k))}catch(ee){if(ee?.code!=="ENOENT")throw ee}}}),U=va(z,{workspaces:m,stateFor:j,agentPresetCatalog:a}),N=d({channel:"whatsapp",controller:U,harness:P,logger:e,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:U,ready:N.ready,async close(){await N.close(),await U.close(),P.stopManagedProcess()}}}import OWe from"qrcode";var age="/whatsapp",Jr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setAccessPolicy:"bot.access-policy.set",setWorkspace:ui,setAgentPreset:Bi}),ige=Object.freeze(Object.values(Jr)),bWe=new Set(["qrValue","accountJid","authDirectory"]);function VU(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function pf(n,t){return VU(n)&&Object.keys(n).every(o=>t.includes(o))}function Ob(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function MWe(n,t){if(!VU(t))return"Payload must be an object.";if([Jr.status,Jr.beginProvisioning].includes(n))return pf(t,[])?null:`${n} does not accept fields.`;if([Jr.pollProvisioning,Jr.cancelProvisioning].includes(n))return pf(t,["attemptId"])&&Ob(t.attemptId)?null:`${n} requires an attemptId.`;if(n===Jr.reconnectBot)return pf(t,["botId","sendTest"])&&Ob(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.";if(n===Jr.deleteBot)return pf(t,["botId","confirm"])&&Ob(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.";if(n===Jr.setAccessPolicy){if(!pf(t,["botId","accessMode","allowedNumbers"])||Object.keys(t).length!==3||!Ob(t.botId))return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002";try{return pg(t),null}catch{return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002"}}return n===Jr.setWorkspace?Fa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Jr.setAgentPreset?Ua(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":"Unknown WhatsApp endpoint."}function Wh(n){if(Array.isArray(n))return n.map(Wh);if(!VU(n))return n;let t={};for(let[o,i]of Object.entries(n))bWe.has(o)||(t[o]=Wh(i));return t}async function _We(n){return OWe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function zU(n,t){return!n||typeof n.qrValue!="string"?Wh(n):Wh({...n,qrCodeDataUrl:await t(n.qrValue)})}async function Vh(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await zU(o.provisioning,t)),Wh(o)}function oge(n,{encodeQr:t=_We}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","reconnectBot","deleteBot","setAccessPolicy"])if(typeof n?.[e]!="function")throw new TypeError(`A complete WhatsApp controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!ige.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let r=MWe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===Jr.status)s=await Vh(await n.status(),i);else if(e===Jr.beginProvisioning)s=await zU(await n.startProvisioning(),i);else if(e===Jr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await zU(g,i)}else if(e===Jr.cancelProvisioning)s=Wh(await n.cancelProvisioning(a.attemptId));else if(e===Jr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(s=await Vh(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(d=>d?.botId===a.botId&&d.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let d=new Error("Connection test is unavailable");throw d.code="test-target-unavailable",d}await n.sendConnectionTest(a.botId)}catch(d){c=d}s={...s,testMessage:ar(c)}}}else if(e===Jr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Vh(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Jr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Vh(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Jr.setAccessPolicy?s=await Vh(await n.setAccessPolicy(a.botId,pg(a)),i):s=await Vh(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=La(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"whatsapp-operation-failed",message:"WhatsApp \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function bb(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(age,oge(t,o),{authority:mr(i)})}async function nge(n,t={}){if(t?.controller)return bb(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await qU(n,t,t.internals??{}),i=bb(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close WhatsApp Web connections"),i}var df=qe(xD(),1);import{createHash as TWe}from"node:crypto";import{readFile as cge,realpath as Tn,stat as NWe}from"node:fs/promises";import{homedir as RWe}from"node:os";import{basename as kWe,dirname as ZU,isAbsolute as eH,join as Ug,relative as vWe,resolve as _b,sep as PWe}from"node:path";import{fileURLToPath as GWe}from"node:url";var rI="@xmanrui/dsh-im",hf="https://registry.npmjs.org/",FWe=15*6e4,LWe=1e4,sge=16*1024;function Nn(n,t={}){return Object.assign(new Error(n),{code:n,...t})}function Mb(n,t){return typeof n?.get=="function"?n.get(t):n?.[t]}function XU(n,t){let o=vWe(n,t);return o!==".."&&!o.startsWith(`..${PWe}`)&&!eH(o)}async function UWe(n){try{return await cge(n,"utf8")}catch(t){if(t.code==="ENOENT")return"";throw t}}async function $U(n){let t=await cge(Ug(n,"package.json"),"utf8");return{directory:await Tn(n),manifest:JSON.parse(t),contents:t}}async function WU(n,t){let o=ZU(await Tn(n));for(;;){try{let e=await $U(o);return e.manifest?.name===t?e:null}catch(e){if(e.code!=="ENOENT")throw e}let i=ZU(o);if(i===o)return null;o=i}}function HWe(n){return typeof n=="string"&&n.length>0&&Buffer.byteLength(n)<=255&&!n.startsWith("-")&&![".","..","node_modules"].includes(n)&&!/[\\/\x00-\x1f\x7f<>:"|?*]/u.test(n)}function KWe(n){if(n[0]==="web")return"web";let t;for(let o=0;o0&&(df.default.validRange(n)!==null||/^[A-Za-z][A-Za-z0-9._-]*$/u.test(n))}async function jWe(n){if(n.manifest?.name!==rI||df.default.valid(n.manifest.version)===null)return!1;let t=[n.manifest.main,n.manifest.exports?.["./client"],n.manifest.dsh?.bundle?.patch];for(let o of t){if(typeof o!="string"||!o||eH(o)||o.includes("\0"))return!1;let i=_b(n.directory,o);if(!XU(n.directory,i)||!XU(n.directory,await Tn(i))||!(await NWe(i)).isFile())return!1}return!0}function JWe(n){if(n==null||n==="")return!0;if(typeof n!="string")return!1;try{return new URL(n).href===hf}catch{return!1}}async function gge(n,{signal:t,timeoutMs:o,errorCode:i,capture:e=!1}){if(t?.aborted)throw Nn("install-interrupted");let a=new AbortController,A,r,s=B=>{A??=B,a.abort(),r?.cancel?.()},g=()=>s("install-interrupted");t?.addEventListener("abort",g,{once:!0});let c=setTimeout(()=>s("install-timeout"),o),I="",d="";try{r=n(a.signal),r.stdout?.on("data",f=>{e&&(I=(I+f.toString()).slice(-sge))}),r.stderr?.on("data",f=>{d=(d+f.toString()).slice(-sge)}),r.stdout?.on("error",()=>s(i)),r.stderr?.on("error",()=>s(i));let B=await r.done;if(A)throw Nn(A);if(B.exitCode!==0||B.signal)throw Nn(i,{exitCode:B.exitCode,diagnosticCode:d.match(/\bERR_PNPM_[A-Z0-9_]+\b/u)?.[0]});return{exitCode:0,signal:null,...e?{stdout:I}:{}}}catch(B){throw A?Nn(A):B.code===i?B:Nn(i)}finally{clearTimeout(c),t?.removeEventListener("abort",g)}}function Ige(n={}){let t=n.ctx,o=n.env??process.env,i=n.argv??process.argv,e=n.execArgv??process.execArgv,a=n.execPath??process.execPath,A=n.cwd??process.cwd(),r=n.platform??process.platform,s=n.osHome??RWe(),g=n.electron??process.versions.electron,c=n.moduleUrl??import.meta.url,I=WU(GWe(c),rI).catch(()=>null),d;async function B(){let _=Mb(t,"desktopProfiles"),T=Mb(t,"desktopPnpm"),R=Mb(t,"desktopPnpmBootstrap"),H=!!(g||_||T||R),j=_?.current,F=H?j?.name:KWe(i.slice(2)),q=H&&R?.homeDir?_b(R.homeDir):xWe(o,s),J={environmentKind:H?"desktop":"cli",homeDir:q,profileName:F};if(!HWe(F))return{...J,blockedReason:"unknown-profile"};let x=await Tn(Ug(q,"profiles",F)),P=await Tn(q),z={...J,homeDir:P,profileDir:x};if(H)try{if(typeof T?.runPlugin!="function"||typeof T?.run!="function"||!R||!j?.dir||R.activeProfileName!==F||await Tn(j.dir)!==x||await Tn(R.activeProfileDir)!==x||await Tn(R.appExecutable)!==await Tn(a))return{...z,blockedReason:"executor-unavailable"};let N=await WU(R.dshBootstrapPath,"dsh-plugin-desktop");return!N||kWe(R.dshBootstrapPath)!=="desktop-cli.js"||ZU(await Tn(R.dshBootstrapPath))!==Ug(N.directory,"lib")?{...z,blockedReason:"executor-unavailable"}:{...z,desktop:T,executable:a,cliEntry:R.dshBootstrapPath}}catch{return{...z,blockedReason:"executor-unavailable"}}let U=Mb(t,"subprocess");if(typeof U?.spawn!="function"||typeof i[1]!="string"||!eH(i[1])||r==="win32")return{...z,blockedReason:"executor-unavailable"};try{let N=await WU(i[1],"@deepseek-ai/dsh");if(!N)return{...z,blockedReason:"executor-unavailable"};let k=await Tn(i[1]),V=typeof N.manifest.bin=="string"?N.manifest.bin:N.manifest.bin?.dsh,ee=typeof V=="string"?_b(N.directory,V):"";return k!==ee&&k!==Ug(N.directory,"src","bin.ts")?{...z,blockedReason:"executor-unavailable"}:{...z,subprocess:U,executable:a,cliEntry:k}}catch{return{...z,blockedReason:"executor-unavailable"}}}function f(_,T,R,H=!1){let j=_.subprocess.spawn({argv:H?["pnpm",...T]:[a,...e,_.cliEntry,...T],cwd:H?_.profileDir:A,env:{DSH_HOME:_.homeDir,CI:"true"},stdio:{stdin:"ignore",stdout:"pipe",stderr:"pipe"},graceMs:3e3,signal:R});return{stdout:j.stdout,stderr:j.stderr,cancel:()=>j.terminate(),done:(async()=>{try{return await j.done}finally{await j.waitForExit()}})()}}async function Q(_,T){let R=["config","get","@xmanrui:registry","--json"],j=(await gge(q=>_.desktop?_.desktop.run(R,q):f(_,R,q,!0),{signal:T,timeoutMs:n.configTimeoutMs??LWe,errorCode:"registry-check-failed",capture:!0})).stdout.trim(),F;try{F=j===""||j==="undefined"?void 0:JSON.parse(j)}catch{throw Nn("registry-check-failed")}if(!JWe(F))throw Nn("registry-conflict")}async function y({preflight:_=!1}={}){let T,R={installedVersion:null,packageValid:!1,eligible:!1,installationKey:null};try{T=await B();for(let P of["homeDir","profileDir","profileName","environmentKind","executable","cliEntry"])R[P]=T[P]??null;if(!T.profileDir)return{...R,blockedReason:T.blockedReason??"unknown-profile"};let H=await $U(T.profileDir),j=await $U(Ug(T.profileDir,"node_modules",rI));R.sourceInstall=!YWe(H.manifest.dependencies?.[rI])||!XU(Ug(T.profileDir,"node_modules"),j.directory),R.installedVersion=typeof j.manifest.version=="string"?j.manifest.version:null,R.packageValid=await jWe(j);let F=await I,q=`${T.homeDir}\0${T.profileDir}\0${T.profileName}`,J=F?.directory===j.directory&&F?.manifest.version===j.manifest.version;d===void 0&&J&&R.packageValid&&(d=q);let x=await Promise.all(["pnpm-lock.yaml","pnpm-workspace.yaml","package-lock.json"].map(P=>UWe(Ug(T.profileDir,P))));return R.installationKey=TWe("sha256").update(JSON.stringify([q,H.contents,j.directory,j.contents,T.cliEntry,T.executable,...x])).digest("hex"),d!==void 0&&d!==q||!J&&d===void 0?R.blockedReason="installation-changed":R.packageValid?R.sourceInstall?R.blockedReason="source-install":T.blockedReason?R.blockedReason=T.blockedReason:J?_&&await Q(T):R.blockedReason="pending-restart":R.blockedReason="invalid-installation",R.eligible=!R.blockedReason,{...R,blockedReason:R.blockedReason??null}}catch(H){return{...R,blockedReason:["registry-conflict","registry-check-failed","install-timeout","install-interrupted"].includes(H.code)?H.code:T?.profileDir?"invalid-installation":"unknown-profile"}}}async function m(_,{signal:T,expectedInstallationKey:R}={}){if(df.default.valid(_)!==_||df.default.prerelease(_))throw Nn("invalid-version");let H=await y();if(R!==void 0&&H.installationKey!==R)throw Nn("installation-changed");if(!H.eligible)throw Nn(H.blockedReason);let j=await B();await Q(j,T);let F=await y();if(!F.eligible||F.installationKey!==H.installationKey)throw Nn("installation-changed");let q=["add","-w","--save-exact",`${rI}@${_}`,`--registry=${hf}`];return gge(J=>j.desktop?j.desktop.runPlugin(q,j.profileDir,J):f(j,["plugin","--profile",j.profileName,...q],J),{signal:T,timeoutMs:n.installTimeoutMs??FWe,errorCode:"install-failed"})}return Object.freeze({inspect:y,install:m})}var aI=qe(xD(),1);import{createHash as qWe,randomUUID as tH}from"node:crypto";import{mkdir as zWe,open as VWe,readFile as Ege,rename as WWe,stat as Cge,unlink as uge,writeFile as ZWe}from"node:fs/promises";import{isAbsolute as lge,join as Cf}from"node:path";var uf=new Set(["installing","verifying"]),XWe=new Set([...uf,"restart-required","completed","failed","interrupted"]),pge=256*1024,$We=["package.json","pnpm-lock.yaml","pnpm-workspace.yaml"],Tb=Symbol("no update lock");function wt(n){return Object.assign(new Error(n),{code:n})}async function dge(n=globalThis.fetch,t=1e4){let o;try{if(o=await n(`${hf}${encodeURIComponent(rI)}/latest`,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(t)}),!o.ok)throw wt("check-failed");if(Number(o.headers.get("content-length"))>pge)throw wt("invalid-release");let i=[],e=0;for await(let c of o.body){if(e+=c.byteLength,e>pge)throw wt("invalid-release");i.push(Buffer.from(c))}let a=JSON.parse(Buffer.concat(i).toString("utf8")),A=a.version;if(a.name!==rI||typeof A!="string"||aI.default.valid(A)!==A||aI.default.prerelease(A))throw wt("invalid-release");let r=a.engines?.node;if(r!==void 0&&(typeof r!="string"||!aI.default.validRange(r)))throw wt("invalid-release");let s=new URL(a.dist?.tarball),g=a.dist?.integrity;if(s.origin!==new URL(hf).origin||s.username||s.password||s.search||s.hash||s.pathname!==`/@xmanrui/dsh-im/-/dsh-im-${A}.tgz`||typeof g!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(g))throw wt("invalid-release");return{version:A,nodeRange:r??"*",integrity:g,tarball:s.href}}catch(i){throw i?.code==="invalid-release"||i instanceof SyntaxError||i instanceof TypeError&&o?.ok?wt("invalid-release"):wt("check-failed")}}function hge(n){if(!lge(n.homeDir??"")||!lge(n.profileDir??""))return null;let t=qWe("sha256").update(n.profileDir).digest("hex").slice(0,24),o=Cf(n.homeDir,"updates","dsh-im",t);return{directory:o,state:Cf(o,"state.json"),lock:Cf(o,"install.lock"),backup:Cf(o,"before.json")}}async function AH(n,t=null){try{if((await Cge(n)).size>10*1024*1024)throw wt("state-unavailable");return JSON.parse(await Ege(n,"utf8"))}catch(o){if(o.code==="ENOENT")return t;throw wt("state-unavailable")}}async function Ef(n,t){let o=`${n}.${tH()}.tmp`;try{await ZWe(o,`${JSON.stringify(t,null,2)} +`,{mode:384,flag:"wx"}),await WWe(o,n)}catch{throw wt("state-unavailable")}finally{await uge(o).catch(i=>{if(i.code!=="ENOENT")throw wt("state-unavailable")})}}function e6e(n){if(!Number.isSafeInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return t.code!=="ESRCH"}}function A6e(n){if(!n)return null;let{id:t,state:o,targetVersion:i,message:e}=n;return{id:t,state:o,targetVersion:i,message:e}}function Bge({runtime:n,runningVersion:t=Rf.version,nodeVersion:o=process.versions.node,fetchImpl:i=globalThis.fetch,now:e=Date.now,checkTimeoutMs:a=1e4,confirmationTtlMs:A=10*6e4,installTimeoutMs:r=15*6e4}={}){let s={},g=null,c=null,I=-1/0,d=null,B=null,f=null,Q=null,y=!1;function m(){if(y)throw wt("disposed")}async function _(z){let U=hge(z);if(!U)return null;if(Q?.statePath===U.state)return Q.job;let N=await AH(U.state),k=await AH(U.lock,Tb);if(!N)return k!==Tb?{id:"locked",state:"interrupted",message:"recovery-required",targetVersion:null}:null;if(!XWe.has(N.state)||typeof N.id!="string"||!aI.default.valid(N.targetVersion))throw wt("state-unavailable");if(uf.has(N.state)&&N.id!==d?.id&&(k===Tb||k?.id!==N.id||!e6e(k?.pid))&&(N={...N,state:"interrupted",message:"recovery-required"}),N.id!==d?.id&&!uf.has(N.state)){if(k!==Tb)return{...N,state:"interrupted",message:"recovery-required"};if(["failed","interrupted"].includes(N.state)&&z.packageValid===!0&&z.installedVersion===t&&!z.blockedReason)return N.targetVersion===t?{...N,state:"completed",message:"recovered"}:{...N,recoverable:!0}}return N.state==="restart-required"||N.state==="completed"?z.installedVersion!==N.targetVersion||z.packageValid!==!0?{...N,state:"interrupted",message:"installation-changed"}:{...N,state:t===N.targetVersion?"completed":"restart-required"}:N}function T(z,U){let N=z.blockedReason??g?.blockedReason??null;U?.state==="interrupted"&&!U.recoverable||U?.state==="failed"&&z.installedVersion!==t?N="recovery-required":(U?.state==="restart-required"||z.installedVersion&&z.installedVersion!==t)&&(N="pending-restart");let k=uf.has(U?.state),V=!!(z.eligible&&!N&&!k&&g?.checkId&&e(){try{let z=await n.inspect({preflight:!0}),U=await dge(i,a);return m(),g={release:U,checkId:tH(),checkedAt:e(),expiresAt:e()+A,installationKey:z.installationKey,profileDir:z.profileDir,blockedReason:z.blockedReason??(aI.default.satisfies(o,U.nodeRange)?null:"incompatible-node")},T(z,await _(z))}catch(z){throw g&&(g={...g,checkId:null,expiresAt:0}),z}finally{c=null}})(),c))}async function j(z,U){(await AH(z.lock))?.id===U&&await uge(z.lock)}async function F(z,U,N){let k={};for(let V of $We)try{let ee=Cf(z.profileDir,V);if((await Cge(ee)).size>3*1024*1024)throw wt("state-unavailable");k[V]=await Ege(ee,"utf8")}catch(ee){if(ee.code!=="ENOENT")throw wt("state-unavailable")}await Ef(U.backup,{jobId:N.id,previousVersion:N.previousVersion,files:k})}function q(z){d={...d,state:"interrupted",message:"state-unavailable"},Q={statePath:z.state,job:d}}async function J(z,U,N){let k=AbortSignal.timeout(r);try{if(await n.install(U.targetVersion,{signal:AbortSignal.any([f.signal,k]),expectedInstallationKey:N.installationKey}),y)throw wt("interrupted");d={...d,state:"verifying",updatedAt:e()},await Ef(z.state,d);let V=await n.inspect();if(V.homeDir!==N.homeDir||V.profileDir!==N.profileDir||V.profileName!==N.profileName||V.blockedReason==="installation-changed")throw wt("installation-changed");if(V.installedVersion!==U.targetVersion||V.packageValid!==!0||V.blockedReason&&V.blockedReason!=="pending-restart")throw wt("verify-failed");d={...d,state:"restart-required",message:null,updatedAt:e()},await Ef(z.state,d)}catch(V){let ee=k.aborted||V.code==="install-timeout",ie=y||f.signal.aborted||!ee&&["interrupted","install-interrupted"].includes(V.code);d={...d,state:ie?"interrupted":"failed",message:ie?"interrupted":ee?"install-timeout":["verify-failed","state-unavailable","installation-changed","registry-conflict"].includes(V.code)?V.code:"install-failed",updatedAt:e()};try{await Ef(z.state,d)}catch{q(z);return}}await j(z,U.id)}function x({checkId:z,requestId:U}){return Us(s,"install",async()=>{m();let N=await n.inspect({preflight:!0}),k=await _(N);if(k?.requestId===U)return T(N,k);if(uf.has(k?.state)||k?.state==="restart-required")throw wt("update-busy");let V=g;if(!V||!z||V.checkId!==z||e()>=V.expiresAt)throw wt("check-expired");if(N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw wt("installation-changed");if(!T(N,k).canInstall)throw wt(N.blockedReason??"update-busy");let ee=hge(N);if(!ee)throw wt("state-unavailable");let ie={id:tH(),requestId:U,state:"installing",message:null,targetVersion:V.release.version,previousVersion:N.installedVersion,startedAt:e(),updatedAt:e()},Te=!1;try{await zWe(ee.directory,{recursive:!0,mode:448});let se=await VWe(ee.lock,"wx",384);Te=!0;try{await se.writeFile(JSON.stringify({id:ie.id,pid:process.pid,startedAt:e()}))}finally{await se.close()}let Ne=await dge(i,a);if(JSON.stringify(Ne)!==JSON.stringify(V.release))throw wt("check-expired");if(N=await n.inspect({preflight:!0}),N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw wt("installation-changed");if(!N.eligible||N.blockedReason)throw wt(N.blockedReason??"update-busy");m(),await F(N,ee,ie),await Ef(ee.state,ie),m()}catch(se){throw Te&&await j(ee,ie.id),se.code==="EEXIST"?wt("update-busy"):se.code?.startsWith("E")?wt("state-unavailable"):se}return d=ie,f=new AbortController,B=J(ee,ie,N).catch(()=>{q(ee)}),T(N,ie)})}async function P(){y=!0,f?.abort(),B&&await B}return Object.freeze({status:R,check:H,install:x,close:P})}var t6e="/dsh-im",r6e=Object.freeze(["update.status","update.check","update.install"]);function a6e(n,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let o=Object.keys(t);return n!=="update.install"?o.length===0:o.length===2&&o.every(i=>i==="checkId"||i==="requestId")&&["checkId","requestId"].every(i=>typeof t[i]=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t[i]))}var i6e=new Set(["check-failed","invalid-release","check-expired","installation-changed","update-busy","install-failed","verify-failed","state-unavailable","interrupted","disposed","source-install","unknown-profile","unsupported-runtime","registry-conflict","incompatible-node","pending-restart","recovery-required","executor-unavailable","invalid-installation","registry-check-failed","install-timeout","install-interrupted","invalid-version"]);function o6e(n){return async(t,o,i)=>{if(!r6e.includes(t)||!a6e(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid update request."}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"Request cancelled."}};try{return{ok:!0,value:t==="update.install"?await n.install(o):t==="update.check"?await n.check():await n.status()}}catch(e){let a=i6e.has(e?.code)?e.code:"update-failed";return{ok:!1,error:{code:a,message:a}}}}}function fge(n,t={}){let o=t.runtime??Ige({ctx:n,moduleUrl:import.meta.url}),i=t.service??Bge({runtime:o}),e=n.connection.rpc.handle(t6e,o6e(i),{authority:"loopback"});return n.effect(()=>()=>i.close(),"dsh-im: close update installer"),e}var Qge="dsh-im-host",n6e=["connection","credentials","apiProxy","typertGateway"];function s6e(n,t){let o=n[t]??{};return n.rpcAuthority===void 0?o:{...o,rpcAuthority:n.rpcAuthority}}function g6e(n={}){let t=n.installUpdateRpc??fge,o=n.applyFeishu??OW,i=n.applyWeixin??C5,e=n.applyDingtalk??jx,a=n.applyWecom??H6,A=n.applyQq??JW,r=n.applySlack??g6,s=n.applyTelegram??D6,g=n.applyDiscord??EY,c=n.applyOffice??yY,I=n.applyWhatsapp??nge,d=[["feishu",o],["weixin",i],["dingtalk",e],["wecom",a],["qq",A],["slack",r],["telegram",s],["discord",g],["whatsapp",I],["office",c]];return Object.freeze({name:Qge,inject:n6e,async apply(B,f={}){KH(f.language??process.env.DSH_IM_LANGUAGE),typeof B?.inject=="function"?B.inject(["tools","systemPrompt"],m=>{SM(m)}):SM(B);let Q=typeof B?.logger=="function"?B.logger(Qge):B?.logger??console;if(B?.connection?.rpc)try{t(B)}catch(m){Q.error?.("[dsh-im] failed to activate update management; continuing with channels",m)}let y=[];for(let[m,_]of d)try{await _(B,s6e(f,m))}catch(T){y.push(T),Q.error?.(`[dsh-im] failed to activate ${m}; continuing with the remaining channels`,T)}if(y.length===d.length)throw new AggregateError(y,"dsh-im failed to activate every channel")}})}async function JkA(n,t={}){return g6e().apply(n,t)}export{JkA as apply,g6e as createImHostPlugin,n6e as inject,Qge as name}; /*! Bundled license information: mime-db/index.js: diff --git a/plugin-src/client/i18n.js b/plugin-src/client/i18n.js index 5e33451..ef11cdf 100644 --- a/plugin-src/client/i18n.js +++ b/plugin-src/client/i18n.js @@ -13,17 +13,28 @@ const EN = Object.freeze({ '检查更新': 'Check for updates', '重新检查': 'Check again', '刷新状态': 'Refresh status', + '手工更新': 'Manual update', + '手工更新命令': 'Manual update command', + '复制命令': 'Copy command', + '复制中…': 'Copying…', + '已复制': 'Copied', + '命令已复制。': 'Command copied.', + '复制失败,请选中命令后按 Ctrl+C 或 ⌘C 复制。': 'Copy failed. Select the command and press Ctrl+C or ⌘C to copy it.', + '自动更新失败可以使用命令更新:': 'If the automatic update fails, update with this command:', + '尚未确认目标版本,此命令安装执行时 npm 的 latest 版本。': 'No target version has been confirmed. This command installs the npm latest version available when you run it.', + '请在当前 Desktop 的内置终端执行,完成后手动重启。': 'Run this in the current Desktop’s built-in terminal, then restart manually.', + '请在运行当前 Harness 的同一环境执行,保持 DSH_HOME 一致,完成后手动重启。': 'Run this in the same environment as the current Harness, with the same DSH_HOME, then restart manually.', + '请等待当前操作结束,确认没有安装进程运行后再执行命令。': 'Wait for the current operation to finish and confirm no installer is running before using this command.', + '源码或链接安装请按原安装方式更新,不提供覆盖源码的 npm 命令。': 'Update source or linked installations using their original method. No npm command is provided to overwrite the source.', + '无法安全生成当前 profile 的命令,请在终端中手动确认 profile 后更新。': 'A safe command cannot be generated for this profile. Confirm the profile in your terminal before updating manually.', '更新至': 'Update to', '安装更新': 'Install update', '正在更新…': 'Updating…', '待手动重启': 'Restart needed', '运行版本': 'Running version', '已安装版本': 'Installed version', - 'npm 最新版本': 'Latest on npm', '目标 profile': 'Target profile', '目标版本': 'Target version', - '更新来源': 'Update source', - '页面版本': 'Page version', '无法确认': 'Unknown', '发现新版本': 'Update available', '已是最新版本': 'Up to date', diff --git a/plugin-src/client/styles.js b/plugin-src/client/styles.js index 2af5fa6..de92cbc 100644 --- a/plugin-src/client/styles.js +++ b/plugin-src/client/styles.js @@ -40,6 +40,17 @@ const CSS = String.raw` .dim-updateHint, .dim-updateError { margin: 12px 0 0; font-size: 12px; line-height: 19px; overflow-wrap: anywhere; } .dim-updateHint { color: var(--dsw-alias-label-secondary, #646a73); } .dim-updateError { color: var(--dsw-alias-state-danger-primary, #d92d20); } +.dim-updateManual { margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--dsw-alias-border-l1, #eef0f3); } +.dim-updateManualHeading { margin: 0; font-size: 13px; line-height: 20px; font-weight: 600; } +.dim-updateManualHint { margin: 8px 0 0; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; line-height: 19px; } +.dim-updateCommandRow { display: flex; align-items: center; gap: 8px; margin-top: 10px; padding: 10px 12px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 8px; background: var(--dsw-alias-bg-layer-1, #f7f8fa); } +.dim-updateCommand { display: block; flex: 1; width: 100%; min-width: 0; padding: 0; resize: none; border: 0; color: var(--dsw-alias-label-primary, #1f2329); background: transparent; font: 12px/19px ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; } +.dim-updateCommand:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary, #3370ff); outline-offset: 2px; } +.dim-updateCopy { display: inline-flex; flex: 0 0 28px; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 6px; color: var(--dsw-alias-label-secondary, #646a73); background: transparent; cursor: pointer; } +.dim-updateCopy:hover:not(:disabled) { color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-interactive-bg-hover, #eef0f3); } +.dim-updateCopy:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary, #3370ff); outline-offset: 2px; } +.dim-updateCopy:disabled { opacity: .55; cursor: default; } +.dim-updateCopyCopied { color: var(--dsw-alias-state-success-primary, #20a162); } .dim-updateFooter { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px; padding: 14px 24px; border-top: 1px solid var(--dsw-alias-border-l1, #eef0f3); } .dim-updateFooter .dim-updateButton:first-child { margin-right: auto; } .dim-updatePrimary, .dim-updatePrimary:hover:not(:disabled) { border-color: var(--dsw-alias-state-business-primary, #3370ff); color: #fff; background: var(--dsw-alias-state-business-primary, #3370ff); } diff --git a/plugin-src/client/update-panel.js b/plugin-src/client/update-panel.js index aff95d0..5e95e8b 100644 --- a/plugin-src/client/update-panel.js +++ b/plugin-src/client/update-panel.js @@ -1,5 +1,7 @@ import * as React from 'react'; import { createPortal } from 'react-dom'; +import validSemver from 'semver/functions/valid.js'; +import compareVersionsDescending from 'semver/functions/rcompare.js'; import { h } from './i18n.js'; import { createPollScheduler } from './lifecycle.js'; @@ -85,6 +87,102 @@ function retainDialogFocus(event) { event?.currentTarget?.closest?.('.dim-updateDialog')?.focus?.({ preventScroll: true }); } +function manualUpdateCommand(snapshot) { + const profile = snapshot?.profileName; + if (snapshot?.sourceInstall || ['source-install', 'unknown-profile'].includes(snapshot?.blockedReason) + || typeof profile !== 'string' || !profile.trim() || profile.length > 255 + || profile.startsWith('-') || ['.', '..', 'node_modules'].includes(profile) + || !/^[\p{L}\p{N}_. -]+$/u.test(profile)) return null; + + // Only allow shell-neutral profile characters; spaces and Unicode stay one argument. + const profileArgument = /^[A-Za-z0-9_.-]+$/.test(profile) ? profile : `"${profile}"`; + const validVersion = (version) => typeof version === 'string' && validSemver(version) === version; + const pendingRestart = snapshot.blockedReason === 'pending-restart' + || snapshot.job?.state === 'restart-required'; + const targets = [ + snapshot.latestVersion, + pendingRestart ? snapshot.installedVersion : null, + snapshot.job?.state !== 'completed' ? snapshot.job?.targetVersion : null, + ].filter(validVersion); + // Keep a known target pinned, and never suggest downgrading an installed/running version. + const version = targets.length + ? [...targets, snapshot.runningVersion, snapshot.installedVersion] + .filter(validVersion).sort(compareVersionsDescending)[0] + : 'latest'; + return `dsh plugin --profile ${profileArgument} add -w @xmanrui/dsh-im@${version}`; +} + +function ManualUpdateCommand({ command, disabled, sourceInstall, desktop }) { + const [copyState, setCopyState] = React.useState('idle'); + const commandRef = React.useRef(null); + const mounted = React.useRef(false); + const copying = React.useRef(false); + React.useEffect(() => { + mounted.current = true; + return () => { mounted.current = false; }; + }, []); + + const copy = async (event) => { + if (!command || disabled || copying.current) return; + retainDialogFocus(event); + copying.current = true; + setCopyState('copying'); + try { + const clipboard = globalThis.navigator?.clipboard; + if (typeof clipboard?.writeText !== 'function') throw new Error('Clipboard unavailable'); + await clipboard.writeText(command); + if (mounted.current) setCopyState('copied'); + } catch { + if (mounted.current) { + setCopyState('failed'); + commandRef.current?.focus?.({ preventScroll: true }); + commandRef.current?.select?.(); + } + } finally { + copying.current = false; + } + }; + + const copyLabel = copyState === 'copying' ? '复制中…' : copyState === 'copied' ? '已复制' : '复制命令'; + + return h('section', { className: 'dim-updateManual', 'aria-label': '手工更新' }, + h('h4', { className: 'dim-updateManualHeading' }, '手工更新'), + command ? h(React.Fragment, null, + h('p', { className: 'dim-updateManualHint' }, '自动更新失败可以使用命令更新:'), + h('div', { className: 'dim-updateCommandRow' }, + h('textarea', { + ref: commandRef, className: 'dim-updateCommand', 'aria-label': '手工更新命令', + value: command, readOnly: true, spellCheck: false, rows: 2, dir: 'ltr', + }), + h('button', { + type: 'button', className: `dim-updateCopy${copyState === 'copied' ? ' dim-updateCopyCopied' : ''}`, + 'aria-label': copyLabel, title: copyLabel, 'aria-busy': copyState === 'copying', + disabled: disabled || copyState === 'copying', onClick: (event) => void copy(event), + }, h('svg', { + width: 16, height: 16, viewBox: '0 0 20 20', fill: 'none', + stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', + 'aria-hidden': 'true', focusable: 'false', + }, copyState === 'copied' + ? h('path', { d: 'm4 10 4 4 8-8' }) + : h(React.Fragment, null, + h('rect', { x: 7, y: 7, width: 10, height: 11, rx: 1.5 }), + h('path', { d: 'M5 13H3.5A1.5 1.5 0 0 1 2 11.5v-8A1.5 1.5 0 0 1 3.5 2h8A1.5 1.5 0 0 1 13 3.5V5' }))))), + command.endsWith('@xmanrui/dsh-im@latest') ? h('p', { className: 'dim-updateManualHint' }, + '尚未确认目标版本,此命令安装执行时 npm 的 latest 版本。') : null, + h('p', { className: 'dim-updateManualHint' }, desktop + ? '请在当前 Desktop 的内置终端执行,完成后手动重启。' + : '请在运行当前 Harness 的同一环境执行,保持 DSH_HOME 一致,完成后手动重启。'), + disabled ? h('p', { className: 'dim-updateManualHint' }, + '请等待当前操作结束,确认没有安装进程运行后再执行命令。') : null, + copyState === 'failed' || copyState === 'copied' ? h('p', { + className: copyState === 'failed' ? 'dim-updateError' : 'dim-updateManualHint', + role: copyState === 'failed' ? 'alert' : 'status', + }, copyState === 'failed' ? '复制失败,请选中命令后按 Ctrl+C 或 ⌘C 复制。' : '命令已复制。') : null) + : h('p', { className: 'dim-updateManualHint' }, sourceInstall + ? '源码或链接安装请按原安装方式更新,不提供覆盖源码的 npm 命令。' + : '无法安全生成当前 profile 的命令,请在终端中手动确认 profile 后更新。')); +} + function UpdateDialog({ children, onClose }) { const dialogRef = React.useRef(null); const titleId = React.useId(); @@ -115,7 +213,7 @@ function UpdateDialog({ children, onClose }) { onClose(); } if (event.key !== 'Tab') return; - const buttons = dialogRef.current?.querySelectorAll?.('button:not(:disabled)'); + const buttons = dialogRef.current?.querySelectorAll?.('button:not(:disabled), textarea:not(:disabled)'); if (!buttons?.length) return; const first = buttons[0]; const last = buttons[buttons.length - 1]; @@ -299,6 +397,7 @@ export function UpdatePanel({ rpcCall, clientVersion, onStatus }) { const failedJob = ['failed', 'interrupted'].includes(snapshot?.job?.state); const jobMessage = snapshot?.job?.message; const targetVersion = snapshot?.job?.targetVersion; + const manualCommand = manualUpdateCommand(snapshot); const buttonLabel = action === 'checking' ? '检查中…' : action === 'starting' || activeJob ? '正在更新…' : restartRequired ? '待手动重启' @@ -324,13 +423,9 @@ export function UpdatePanel({ rpcCall, clientVersion, onStatus }) { snapshot?.installedVersion && snapshot.installedVersion !== snapshot.runningVersion ? h(React.Fragment, null, h('dt', null, '已安装版本'), h('dd', null, `v${snapshot.installedVersion}`)) : null, - h('dt', null, 'npm 最新版本'), h('dd', null, snapshot?.latestVersion ? `v${snapshot.latestVersion}` : '尚未检查'), targetVersion ? h(React.Fragment, null, h('dt', null, '目标版本'), h('dd', null, `v${targetVersion}`)) : null, - h('dt', null, '目标 profile'), h('dd', null, snapshot?.profileName ?? '无法确认'), - h('dt', null, '更新来源'), h('dd', null, 'registry.npmjs.org'), - versionsDiffer ? h(React.Fragment, null, - h('dt', null, '页面版本'), h('dd', null, `v${clientVersion}`)) : null), + h('dt', null, '目标 profile'), h('dd', null, snapshot?.profileName ?? '无法确认')), h('div', { className: `dim-updateStatus${error || failedJob ? ' dim-updateStatusError' : ''}`, role: 'status', @@ -347,7 +442,13 @@ export function UpdatePanel({ rpcCall, clientVersion, onStatus }) { blocked && !restartRequired ? h('p', { className: 'dim-updateHint' }, blocked) : null, versionsDiffer && !restartRequired ? h('p', { className: 'dim-updateHint' }, '页面版本与运行版本不同,请手动刷新页面;若仍不一致,请手动重启 Harness 或 Desktop。') : null, canConfirm ? h('p', { className: 'dim-updateHint' }, - '请在机器人空闲时安装;安装会修改当前 profile 的依赖,完成后需手动重启。') : null), + '请在机器人空闲时安装;安装会修改当前 profile 的依赖,完成后需手动重启。') : null, + h(ManualUpdateCommand, { + key: manualCommand ?? 'unavailable', command: manualCommand, + disabled: busyAction || activeJob || uncertainInstall, + sourceInstall: snapshot?.sourceInstall || snapshot?.blockedReason === 'source-install', + desktop: snapshot?.environmentKind === 'desktop', + })), h('footer', { className: 'dim-updateFooter' }, h('button', { type: 'button', className: 'dim-updateButton', onClick: () => setOpen(false) }, '关闭'), restartRequired || !activeJob ? h('button', { diff --git a/plugin-src/host/update-runtime.mjs b/plugin-src/host/update-runtime.mjs index 5bdfcd0..243b38d 100644 --- a/plugin-src/host/update-runtime.mjs +++ b/plugin-src/host/update-runtime.mjs @@ -280,6 +280,8 @@ export function createUpdateRuntime(options = {}) { const profile = await packageAt(runtime.profileDir); const installed = await packageAt(join(runtime.profileDir, 'node_modules', PACKAGE_NAME)); + result.sourceInstall = !registrySpec(profile.manifest.dependencies?.[PACKAGE_NAME]) + || !inside(join(runtime.profileDir, 'node_modules'), installed.directory); result.installedVersion = typeof installed.manifest.version === 'string' ? installed.manifest.version : null; result.packageValid = await validPackage(installed); const loaded = await loadedPackage; @@ -298,8 +300,7 @@ export function createUpdateRuntime(options = {}) { if (boundProfile !== undefined && boundProfile !== identity) result.blockedReason = 'installation-changed'; else if (!sameLoadedPackage && boundProfile === undefined) result.blockedReason = 'installation-changed'; else if (!result.packageValid) result.blockedReason = 'invalid-installation'; - else if (!registrySpec(profile.manifest.dependencies?.[PACKAGE_NAME]) - || !inside(join(runtime.profileDir, 'node_modules'), installed.directory)) result.blockedReason = 'source-install'; + else if (result.sourceInstall) result.blockedReason = 'source-install'; else if (runtime.blockedReason) result.blockedReason = runtime.blockedReason; else if (!sameLoadedPackage) result.blockedReason = 'pending-restart'; else if (preflight) await checkRegistry(runtime); diff --git a/plugin-src/host/update-service.mjs b/plugin-src/host/update-service.mjs index 9f1a040..a7c9ed9 100644 --- a/plugin-src/host/update-service.mjs +++ b/plugin-src/host/update-service.mjs @@ -201,6 +201,8 @@ export function createUpdateService({ latestVersion: checked?.release.version ?? null, profileName: environment.profileName ?? null, environmentKind: environment.environmentKind ?? 'cli', + // Preserve source protection even when restart/recovery takes status priority. + sourceInstall: environment.sourceInstall === true || environment.blockedReason === 'source-install', canInstall, blockedReason, checkedAt: checked?.checkedAt ?? null, diff --git a/test/update-runtime.test.mjs b/test/update-runtime.test.mjs index fec8444..0eea2ae 100644 --- a/test/update-runtime.test.mjs +++ b/test/update-runtime.test.mjs @@ -168,7 +168,9 @@ test('local, Git, alias and external-directory installations cannot be replaced' const f = await fixture(t); for (const spec of ['link:/work/dsh-im', 'file:../dsh-im', 'github:xmanrui/dsh-im', 'git+ssh://git@example.com/repo.git', 'npm:another-plugin@1.0.0']) { await json(join(f.profileDir, 'package.json'), { ...f.manifest, dependencies: { [PACKAGE_NAME]: spec } }); - assert.equal((await f.runtime().inspect()).blockedReason, 'source-install', spec); + const inspected = await f.runtime().inspect(); + assert.equal(inspected.blockedReason, 'source-install', spec); + assert.equal(inspected.sourceInstall, true, spec); } const sourceDir = join(f.root, 'source-checkout'); await plugin(sourceDir); @@ -176,7 +178,9 @@ test('local, Git, alias and external-directory installations cannot be replaced' await symlink(sourceDir, f.installedLink, 'dir'); await json(join(f.profileDir, 'package.json'), f.manifest); f.options.moduleUrl = pathToFileURL(join(sourceDir, 'lib/index.js')).href; - assert.equal((await f.runtime().inspect()).blockedReason, 'source-install'); + const inspected = await f.runtime().inspect(); + assert.equal(inspected.blockedReason, 'source-install'); + assert.equal(inspected.sourceInstall, true); assert.deepEqual(f.calls, []); }); diff --git a/test/update-service.test.mjs b/test/update-service.test.mjs index 5020508..28fa5d0 100644 --- a/test/update-service.test.mjs +++ b/test/update-service.test.mjs @@ -127,6 +127,7 @@ test('source installs and incompatible Host Node can check but cannot install', const checked = await source.service.check(); assert.equal(checked.latestVersion, '3.0.8'); assert.equal(checked.blockedReason, 'source-install'); + assert.equal(checked.sourceInstall, true); assert.equal(checked.canInstall, false); assert.equal(checked.checkId, null); const oldNode = await fixture(t, { service: { nodeVersion: '22.18.0' } }); @@ -134,6 +135,17 @@ test('source installs and incompatible Host Node can check but cannot install', assert.deepEqual(source.state.installs, []); }); +test('source-install protection remains independent of the primary status reason', async (t) => { + const f = await fixture(t, { environment: { + eligible: false, blockedReason: 'source-install', sourceInstall: true, installedVersion: '3.0.8', + } }); + const status = await f.service.status(); + assert.equal(status.blockedReason, 'pending-restart'); + assert.equal(status.sourceInstall, true); + f.environment.blockedReason = 'installation-changed'; + assert.equal((await f.service.status()).sourceInstall, true); +}); + test('a failed check invalidates previous install confirmation without claiming latest', async (t) => { const f = await fixture(t); const checked = await f.service.check(); diff --git a/test/update-ui.test.mjs b/test/update-ui.test.mjs index 9fcd3da..6ea8365 100644 --- a/test/update-ui.test.mjs +++ b/test/update-ui.test.mjs @@ -47,7 +47,7 @@ function textOf(node) { } function buttonNamed(renderer, label) { - return renderer.root.findAllByType('button').find((node) => textOf(node) === label); + return renderer.root.findAllByType('button').find((node) => (node.props['aria-label'] ?? textOf(node)) === label); } async function flushMicrotasks() { @@ -82,6 +82,19 @@ function deferred() { return { promise, resolve }; } +function stubClipboard(t, clipboard) { + const original = Object.getOwnPropertyDescriptor(globalThis, 'navigator'); + Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { clipboard } }); + t.after(() => { + if (original) Object.defineProperty(globalThis, 'navigator', original); + else delete globalThis.navigator; + }); +} + +function manualCommandOf(renderer) { + return renderer.root.findAllByType('textarea')[0]?.props.value; +} + async function tick(t, milliseconds = 1_000) { await act(async () => { t.mock.timers.tick(milliseconds); @@ -110,7 +123,6 @@ test('update panel reads local status first and requires an explicit npm check a assert.equal(renderer.root.findByProps({ role: 'dialog' }).props['aria-modal'], 'true'); assert.match(textOf(renderer.toJSON()), /发现新版本/); assert.match(textOf(renderer.toJSON()), /desktop-test/); - assert.match(textOf(renderer.toJSON()), /registry\.npmjs\.org/); assert.match(textOf(renderer.toJSON()), /需手动重启后台.*本功能不会自动重启或主动刷新页面/); assert.ok(buttonNamed(renderer, '安装更新')); assert.ok(buttonNamed(renderer, '更新至 v3.0.9')); @@ -119,6 +131,19 @@ test('update panel reads local status first and requires an explicit npm check a assert.equal(renderer.root.findAllByProps({ role: 'dialog' }).length, 0); }); +test('version details hide npm, registry and client metadata while preserving running and installed versions', async (t) => { + for (const latestVersion of [null, '3.1.2']) { + const renderer = await mount(t, async () => ok(snapshot({ + runningVersion: '3.1.0', installedVersion: '3.1.1', latestVersion, + profileName: 'web', blockedReason: 'pending-restart', + })), { clientVersion: '3.1.1' }); + await click(renderer, '待手动重启'); + const details = renderer.root.findByProps({ className: 'dim-updateVersions' }); + assert.deepEqual(details.findAllByType('dt').map(textOf), ['运行版本', '已安装版本', '目标 profile']); + assert.deepEqual(details.findAllByType('dd').map(textOf), ['v3.1.0', 'v3.1.1', 'web']); + } +}); + test('confirmed installation ignores double clicks, polls the Host and stops at manual restart', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const pendingInstall = deferred(); @@ -201,23 +226,24 @@ test('a failed npm check cannot reuse an earlier up-to-date result', async (t) = }); await click(renderer, '检查更新'); assert.match(textOf(renderer.toJSON()), /无法访问 npm 或请求超时/); - assert.match(textOf(renderer.toJSON()), /尚未检查/); + assert.match(manualCommandOf(renderer), /@latest$/); assert.doesNotMatch(textOf(renderer.toJSON()), /已是最新版本|当前版本无需更新/); assert.equal(buttonNamed(renderer, '安装更新'), undefined); }); test('source installations can check npm but never offer automatic replacement', async (t) => { const calls = []; + const reported = []; const renderer = await mount(t, async (endpoint) => { calls.push(endpoint); return ok(endpoint === 'update.status' ? snapshot({ blockedReason: 'source-install' }) : available({ blockedReason: 'source-install', canInstall: false, checkId: null })); - }); + }, { onStatus: (value) => reported.push(value) }); await click(renderer, '检查更新'); assert.deepEqual(calls, ['update.status', 'update.check']); assert.match(textOf(renderer.toJSON()), /当前是源码或链接安装/); - assert.match(textOf(renderer.toJSON()), /v3.0.9/); + assert.equal(reported.at(-1).latestVersion, '3.0.9'); assert.equal(buttonNamed(renderer, '安装更新'), undefined); }); @@ -299,7 +325,6 @@ test('pending restart shows manual restart guidance instead of a redundant page await click(renderer, '待手动重启'); assert.deepEqual(calls, ['update.status', 'update.status']); assert.match(textOf(renderer.toJSON()), /运行版本v3.0.8/); - assert.match(textOf(renderer.toJSON()), /页面版本v3.0.7/); assert.match(textOf(renderer.toJSON()), /手动重启当前 Harness 或 Desktop/); assert.doesNotMatch(textOf(renderer.toJSON()), /页面版本与运行版本不同|手动刷新页面/); assert.equal(buttonNamed(renderer, '安装更新'), undefined); @@ -330,7 +355,6 @@ test('remounting the new client retains the old Host version and restores the re await click(remounted, '待手动重启'); assert.match(textOf(remounted.toJSON()), /运行版本v3.0.8/); assert.match(textOf(remounted.toJSON()), /已安装版本v3.0.9/); - assert.match(textOf(remounted.toJSON()), /页面版本v3.0.9/); assert.match(textOf(remounted.toJSON()), /已安装,待手动重启/); assert.doesNotMatch(textOf(remounted.toJSON()), /手动刷新页面/); assert.equal(buttonNamed(remounted, '安装更新'), undefined); @@ -634,7 +658,10 @@ test('the confirmation supports keyboard focus, tab wrapping, Escape and focus r const last = { focus() { document.activeElement = last; } }; const dialogNode = { focus() { document.activeElement = dialogNode; }, - querySelectorAll() { return [first, last]; }, + querySelectorAll(selector) { + assert.match(selector, /textarea:not\(:disabled\)/); + return [first, last]; + }, }; Object.defineProperty(globalThis, 'document', { configurable: true, value: { activeElement: previous }, @@ -667,3 +694,177 @@ test('the confirmation supports keyboard focus, tab wrapping, Escape and focus r assert.equal(document.activeElement, previous); assert.equal(prevented, 2); }); + +test('manual commands use the current profile and a known target without downgrading', async (t) => { + const cases = [ + { profileName: 'web', runningVersion: '3.1.0', installedVersion: '3.1.1', + blockedReason: 'pending-restart', expected: 'web', version: '3.1.1' }, + { profileName: 'desktop-test', job: { state: 'failed', targetVersion: '3.1.2', message: 'install-failed' }, + expected: 'desktop-test', version: '3.1.2' }, + { profileName: 'web', latestVersion: '3.1.3', job: { state: 'failed', targetVersion: '3.1.2' }, + expected: 'web', version: '3.1.3' }, + { profileName: 'web', runningVersion: '3.1.10', installedVersion: '3.1.10', latestVersion: '3.1.9', + expected: 'web', version: '3.1.10' }, + { profileName: 'Team One', expected: '"Team One"', version: 'latest' }, + { profileName: '测试环境', expected: '"测试环境"', version: 'latest' }, + { profileName: 'web', latestVersion: '3.1.1; echo unsafe', expected: 'web', version: 'latest' }, + { profileName: 'web', job: { state: 'completed', targetVersion: '3.0.8' }, expected: 'web', version: 'latest' }, + ]; + for (const { expected, version, ...fields } of cases) { + const renderer = await mount(t, async () => ok(snapshot(fields))); + await click(renderer, fields.blockedReason === 'pending-restart' ? '待手动重启' : '检查更新'); + assert.equal(manualCommandOf(renderer), + `dsh plugin --profile ${expected} add -w @xmanrui/dsh-im@${version}`); + assert.equal(renderer.root.findByType('textarea').props.readOnly, true); + assert.match(textOf(renderer.toJSON()), /自动更新失败可以使用命令更新:/); + assert.doesNotMatch(textOf(renderer.toJSON()), /通常只需手动重启/); + } +}); + +test('manual copying uses an accessible icon at the right of the command row', async (t) => { + stubClipboard(t, { async writeText() {} }); + const renderer = await mount(t, async () => ok(available())); + await click(renderer, '更新至 v3.0.9'); + const row = renderer.root.findByProps({ className: 'dim-updateCommandRow' }); + const copy = buttonNamed(renderer, '复制命令'); + assert.equal(row.children[0].type, 'textarea'); + assert.equal(row.children.at(-1), copy); + assert.equal(copy.props.className, 'dim-updateCopy'); + assert.equal(copy.props.title, '复制命令'); + assert.equal(textOf(copy), ''); + assert.equal(copy.findByType('svg').props['aria-hidden'], 'true'); + assert.equal(copy.findByType('svg').props.focusable, 'false'); + await click(renderer, '复制命令'); + const copied = buttonNamed(renderer, '已复制'); + assert.match(copied.props.className, /dim-updateCopyCopied/); + assert.equal(copied.props.title, '已复制'); + assert.equal(textOf(copied), ''); + assert.equal(copied.findAllByType('rect').length, 0); +}); + +test('manual commands remain available after a failed npm check and explain the latest fallback', async (t) => { + const renderer = await mount(t, async (endpoint) => { + if (endpoint === 'update.status') return ok(snapshot({ profileName: 'web', environmentKind: 'cli' })); + throw new Error('npm unavailable'); + }); + await click(renderer, '检查更新'); + assert.match(manualCommandOf(renderer), /@xmanrui\/dsh-im@latest$/); + assert.match(textOf(renderer.toJSON()), /尚未确认目标版本.*执行时 npm 的 latest/); + assert.match(textOf(renderer.toJSON()), /DSH_HOME 一致/); + assert.equal(buttonNamed(renderer, '复制命令').props.disabled, false); + assert.equal(buttonNamed(renderer, '安装更新'), undefined); +}); + +test('manual commands cannot overwrite source installs or interpolate unsafe profiles', async (t) => { + for (const profileName of [null, '', '..', 'node_modules', '-other', '../other', 'work; echo x', + 'work$(echo x)', 'work`echo x`', 'work%PATH%', 'work"name', 'work\nname']) { + const renderer = await mount(t, async () => ok(snapshot({ profileName }))); + await click(renderer, '检查更新'); + assert.equal(manualCommandOf(renderer), undefined, String(profileName)); + assert.equal(buttonNamed(renderer, '复制命令'), undefined); + } + for (const blockedReason of ['source-install', 'pending-restart', 'recovery-required']) { + const renderer = await mount(t, async () => ok(snapshot({ + blockedReason, ...(blockedReason === 'source-install' ? {} : { sourceInstall: true }), + }))); + await click(renderer, blockedReason === 'pending-restart' ? '待手动重启' : '检查更新'); + assert.equal(manualCommandOf(renderer), undefined); + assert.equal(buttonNamed(renderer, '复制命令'), undefined); + assert.match(textOf(renderer.toJSON()), /不提供覆盖源码的 npm 命令/); + } +}); + +test('copying writes exactly the displayed command and never submits an installation', async (t) => { + const writes = []; + const calls = []; + const clipboard = { async writeText(value) { assert.equal(this, clipboard); writes.push(value); } }; + stubClipboard(t, clipboard); + const renderer = await mount(t, async (endpoint) => { + calls.push(endpoint); + return ok(available()); + }); + await click(renderer, '更新至 v3.0.9'); + assert.match(textOf(renderer.toJSON()), /Desktop 的内置终端/); + const before = [...calls]; + await click(renderer, '复制命令'); + assert.deepEqual(writes, [manualCommandOf(renderer)]); + assert.deepEqual(calls, before); + assert.ok(buttonNamed(renderer, '已复制')); + assert.match(textOf(renderer.toJSON()), /命令已复制/); +}); + +test('copy failure selects the command for keyboard copying and allows a retry', async (t) => { + const selection = []; + let denied = true; + stubClipboard(t, { async writeText() { if (denied) throw new Error('NotAllowedError'); } }); + const renderer = await mount(t, async () => ok(available()), {}, { + createNodeMock(element) { + return element.type === 'textarea' ? { + focus() { selection.push('focus'); }, select() { selection.push('select'); }, + } : null; + }, + }); + await click(renderer, '更新至 v3.0.9'); + await click(renderer, '复制命令'); + assert.deepEqual(selection, ['focus', 'select']); + assert.match(textOf(renderer.root.findByProps({ role: 'alert' })), /Ctrl\+C 或 ⌘C/); + assert.equal(buttonNamed(renderer, '复制命令').props.disabled, false); + denied = false; + await click(renderer, '复制命令'); + assert.ok(buttonNamed(renderer, '已复制')); + assert.equal(renderer.root.findAllByProps({ role: 'alert' }).length, 0); +}); + +test('missing clipboard support exposes a selectable command without claiming success', async (t) => { + stubClipboard(t, undefined); + const renderer = await mount(t, async () => ok(available())); + await click(renderer, '更新至 v3.0.9'); + await click(renderer, '复制命令'); + assert.match(textOf(renderer.toJSON()), /复制失败/); + assert.ok(manualCommandOf(renderer)); + assert.equal(buttonNamed(renderer, '已复制'), undefined); +}); + +test('an old clipboard result cannot mark a changed command or reopened dialog as copied', async (t) => { + const pending = deferred(); + let writes = 0; + stubClipboard(t, { writeText() { writes += 1; return pending.promise; } }); + const renderer = await mount(t, async (endpoint) => ok(endpoint === 'update.check' + ? available({ latestVersion: '3.0.10' }) : available())); + await click(renderer, '更新至 v3.0.9'); + const copy = buttonNamed(renderer, '复制命令'); + await act(async () => { copy.props.onClick(); copy.props.onClick(); await flushMicrotasks(); }); + assert.equal(writes, 1); + assert.equal(buttonNamed(renderer, '复制中…').props.disabled, true); + await click(renderer, '重新检查'); + assert.match(manualCommandOf(renderer), /@3\.0\.10$/); + await act(async () => { pending.resolve(); await flushMicrotasks(); }); + assert.equal(buttonNamed(renderer, '已复制'), undefined); + await click(renderer, '复制命令'); + assert.ok(buttonNamed(renderer, '已复制')); + await click(renderer, '关闭'); + await click(renderer, '更新至 v3.0.10'); + assert.ok(buttonNamed(renderer, '复制命令')); +}); + +test('manual copying is disabled while the Host may still be installing', async (t) => { + const renderer = await mount(t, async () => ok(installing())); + await click(renderer, '正在更新…'); + assert.equal(buttonNamed(renderer, '复制命令').props.disabled, true); + assert.match(textOf(renderer.toJSON()), /确认没有安装进程运行/); +}); + +test('manual update instructions and copy feedback render in English', async (t) => { + setImTranslator((key) => en[key] ?? key); + t.after(() => setImTranslator(null)); + stubClipboard(t, { async writeText() {} }); + const renderer = await mount(t, async () => ok(available())); + await click(renderer, 'Update to v3.0.9'); + assert.match(textOf(renderer.toJSON()), /Manual update/); + assert.match(textOf(renderer.toJSON()), /If the automatic update fails, update with this command:/); + assert.equal(renderer.root.findByType('textarea').props['aria-label'], 'Manual update command'); + assert.equal(buttonNamed(renderer, 'Copy command').props.title, 'Copy command'); + await click(renderer, 'Copy command'); + assert.match(textOf(renderer.toJSON()), /Command copied/); + assert.doesNotMatch(textOf(renderer.toJSON()), /[\p{Script=Han}]/u); +});